diff --git a/.claude/skills/measuring-hardware-cells/SKILL.md b/.claude/skills/measuring-hardware-cells/SKILL.md new file mode 100644 index 000000000..fa0fddcf6 --- /dev/null +++ b/.claude/skills/measuring-hardware-cells/SKILL.md @@ -0,0 +1,12 @@ +--- +name: measuring-hardware-cells +description: >- + Use when measuring local hardware capability cells on a GPU or Apple Silicon + Mac, benchmarking peak VRAM or unified memory and step times across + resolutions or durations, finding the true OOM or paging cliff in Cautious or + Brave mode, diagnosing silent WDDM shared-memory paging or macOS swap + thrashing, or contributing empirical hardware measurements and budget law + improvements. +--- + +@../../../docs/skills/measuring-hardware-cells.md diff --git a/.cursor/rules/ltx2-patch-reverify.mdc b/.cursor/rules/ltx2-patch-reverify.mdc index 4ecf9b6bb..f1ab70d7b 100644 --- a/.cursor/rules/ltx2-patch-reverify.mdc +++ b/.cursor/rules/ltx2-patch-reverify.mdc @@ -6,7 +6,7 @@ alwaysApply: false # LTX-2 bump → re-check `services.patches` -Delete-first. If this change updates `ltx-core` or `ltx-pipelines` (version pin, git tag, or `tool.uv.dependency-metadata`), treat every module imported from `backend/services/patches/` in `backend/ltx2_server.py` as suspect — plus any out-of-directory swaps such as `distilled_keyframe_guiding`. +Delete-first. If this change updates `ltx-core` or `ltx-pipelines` (version pin, git tag, or `tool.uv.dependency-metadata`), treat every module imported from `backend/services/patches/` in `backend/ltx2_server.py` as suspect, plus any out-of-directory swap of an upstream symbol. Those patches rebind private upstream symbols. A bump can rename the target (import-time assert should fail) or change the contract (assert still passes, behavior is wrong). Default is **delete** the patch; keep only what still fails on the new revision. @@ -22,6 +22,7 @@ Forked pipeline classes copy upstream bodies, and a signature test does not catc - `TiledICLoraPipeline._video_conditionings` (`ic_lora_pipeline/tiled_ic_lora_pipeline.py`) copies upstream `ICLoraPipeline._video_conditionings`; keep the `apply_ic_lora` gate and only change `encode_tiling`. - `DistilledPipelineWithSkipStage2._call_stage_1_only` mirrors stage 1 of `DistilledPipeline`. - `DistilledA2VPipeline` and `LTXRetakePipeline` call `DiffusionStage` directly. +- `NagDistilledMixin` (`fast_video_pipeline/nag_distilled.py`) wraps `DistilledPipeline._prepare_run` and `stream_chunks`. `nag_cross_attention` replaces `BasicAVTransformerBlock._apply_text_cross_attention`; diff it against upstream, including `apply_cross_attention_adaln` and `Attention.forward`. Size latents with `stage.video_scale_factors` (transformer geometry). `tiling_scale_factors_for_vae` is the decoder's tiling scale (2x8x8 on the 2.5 DiffVAE) and is only for `ensure_tiling_config`. diff --git a/.cursor/skills/measuring-hardware-cells/SKILL.md b/.cursor/skills/measuring-hardware-cells/SKILL.md new file mode 100644 index 000000000..fa0fddcf6 --- /dev/null +++ b/.cursor/skills/measuring-hardware-cells/SKILL.md @@ -0,0 +1,12 @@ +--- +name: measuring-hardware-cells +description: >- + Use when measuring local hardware capability cells on a GPU or Apple Silicon + Mac, benchmarking peak VRAM or unified memory and step times across + resolutions or durations, finding the true OOM or paging cliff in Cautious or + Brave mode, diagnosing silent WDDM shared-memory paging or macOS swap + thrashing, or contributing empirical hardware measurements and budget law + improvements. +--- + +@../../../docs/skills/measuring-hardware-cells.md diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 000000000..5508e434c --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +frontend/generated/** linguist-generated=true diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 699a074de..f3ef1f9fe 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -55,7 +55,7 @@ jobs: - name: Pyright type check working-directory: backend - run: uv run pyright + run: uv run --frozen pyright - name: OpenAPI contract check run: pnpm run openapi:check @@ -101,7 +101,7 @@ jobs: # The full suite runs on Linux. Windows only runs tests that call the # real Win32 DLL APIs. `--` keeps `-m` from being read as a uv flag. - name: Run tests - run: uv run -- pytest -v --tb=short -m ci_os + run: uv run --frozen -- pytest -v --tb=short -m ci_os # One Linux pytest job was the wait. Four shards run together. # The matrix length and `--splits` below are the same number. @@ -124,7 +124,7 @@ jobs: # least_duration deals tests round-robin when there is no durations file, # so a slow module is not collected entirely onto the first shard. - name: Run tests - run: uv run -- pytest -v --tb=short --splits 4 --group ${{ matrix.shard }} --splitting-algorithm least_duration + run: uv run --frozen -- pytest -v --tb=short --splits 4 --group ${{ matrix.shard }} --splitting-algorithm least_duration # Branch protection still looks for this name. It passes when every Linux shard passes. test-python-linux-gate: diff --git a/AGENTS.md b/AGENTS.md index f0e38d5c5..30fb658bf 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -98,6 +98,9 @@ Budget constants in `backend/runtime_config/` cite internal measurement run keys Budget comments explain why, not what was measured: mechanism, failure mode, and what breaks if the constant changes. No run keys, brackets, or fit math in code prose — those live behind the Evidence links and in the budgets ledger. +What each machine runs, for users, is `docs/hardware-compatibility.md`; when a +budget change moves what a card or Mac offers, update its tables in the same change +and regenerate `docs/local-compat-matrix.md` (never hand-edit it). ## Tests diff --git a/README.md b/README.md index 8958b2a13..7db1fb204 100644 --- a/README.md +++ b/README.md @@ -73,21 +73,21 @@ Release notes are on the [GitHub releases page](https://github.com/Lightricks/LT ### System requirements -These are the requirements for local generation. They match the [LTX Desktop page](https://ltx.io/ltx-desktop). +These are the recommended specs for local generation. What each GPU and Mac size can run, and why, is in [`docs/hardware-compatibility.md`](docs/hardware-compatibility.md). -| Platform | Requirements | +| Platform | Recommended | | --- | --- | -| **Windows 10/11** (64-bit) | NVIDIA GPU with CUDA and **24 GB or more VRAM** (32 GB recommended). 32 GB RAM. | +| **Windows 10/11** (64-bit) | NVIDIA GPU with CUDA and **24 GB or more VRAM** (32 GB recommended). 64 GB RAM; with the models on an NVMe drive, 32 GB runs every tool and 24 GB runs generation and editing. | | **Linux** (Ubuntu 22.04+ or similar, x64 or arm64) | NVIDIA GPU with CUDA and **24 GB or more VRAM** (32 GB recommended), NVIDIA driver installed. 32 GB RAM. | -| **macOS 26+** (Tahoe) | Apple Silicon (M1 or later) with **48 GB or more** for full local generation. Apple Silicon with 32 GB is limited to 540p and 5 s. Apple Silicon with less than 24 GB, and Intel Macs, use the Gen Space API only. | +| **macOS 26+** (Tahoe) | Apple Silicon (M1 or later) with **48 GB or more** for every local job. 32 GB is the advertised minimum: 32 and 36 GB Macs run most jobs up to 1080p and shorter 1440p and 4K clips. Apple Silicon with less than 24 GB, and Intel Macs, use the Gen Space API only. | The app itself needs **macOS 14 or later**. On macOS 14 and 15, local generation is not available and the app shows the **Coming soon to your device** notice. macOS 13 and earlier cannot run the app. All platforms need **100 GB or more** of free disk space. Plan for up to **160 GB or more** if you add LoRAs and IC-LoRAs. -The app offers local generation on lower-spec machines, but we do not recommend them. The app checks 9 GiB VRAM on Windows with an fp8-capable GPU (15 GiB on other CUDA setups), 32 GiB total RAM on macOS, and macOS 26 or later. Below these floors, the app shows a **Coming soon to your device** notice instead of the generation tools. Assets, Settings, Gen Space, and the Video Editor stay available. Cloud APIs are optional. An LTX API key is never required to start. +The app offers local generation on lower-spec machines, but we do not recommend them. The app checks 9 GiB VRAM on Windows with an fp8-capable GPU (15 GiB on other CUDA setups), 24 GiB total memory on macOS, and macOS 26 or later. Below these floors, the app shows a **Coming soon to your device** notice instead of the generation tools. Assets, Settings, Gen Space, and the Video Editor stay available. Cloud APIs are optional. An LTX API key is never required to start. -See [`docs/local-compat-matrix.md`](docs/local-compat-matrix.md) for the tool-by-hardware table. +Smaller cards run longer clips in parts rather than in one pass: a 16 GB card runs Fast 720p/20s in 2 parts and 1080p/10s in 3. See [`docs/hardware-compatibility.md`](docs/hardware-compatibility.md) for what each GPU and memory size can run, and [`docs/local-compat-matrix.md`](docs/local-compat-matrix.md) for the tool-by-hardware table. ## Models @@ -128,6 +128,7 @@ For the architecture and API boundary, see [`docs/remote-lan.md`](docs/remote-la - [`docs/tools-and-options.md`](docs/tools-and-options.md): every tool and setting, and how prompt enhancement works - [`docs/models-and-loras.md`](docs/models-and-loras.md): models, gated models, LoRA library, custom LoRAs - [`docs/setup-and-settings.md`](docs/setup-and-settings.md): per-platform requirements, first run, data folders, text encoding, Settings tabs +- [`docs/hardware-compatibility.md`](docs/hardware-compatibility.md): will it run on your machine — per-hardware capabilities for generation, editing, and IC-LoRA - [`docs/api-keys-and-privacy.md`](docs/api-keys-and-privacy.md): LTX, fal, and Gemini keys, cost, and privacy - [`docs/desktop-assistant.md`](docs/desktop-assistant.md): the Assistant's tools, runs, providers, and local runtime - [`docs/remote-lan.md`](docs/remote-lan.md): Remote architecture and API boundary diff --git a/backend/_routes/custom_lora.py b/backend/_routes/custom_lora.py new file mode 100644 index 000000000..942f4031e --- /dev/null +++ b/backend/_routes/custom_lora.py @@ -0,0 +1,102 @@ +from __future__ import annotations + +from fastapi import APIRouter, Depends, Path, Query + +from api_types import ( + ActiveCustomLoraImportResponse, + CustomLoraImportProgressResponse, + CustomLoraImportRequest, + CustomLoraImportStartResponse, + CustomLoraLinkInfoRequest, + CustomLoraLinkInfoResponse, + CustomLoraListResponse, + CustomLoraRestoreRequest, + StatusResponse, +) +from app_handler import AppHandler +from state import get_state_service + +# Desktop only: adding and deleting touch the user's disk. The phone gets the read-only list +# from remote/loras.py. +router = APIRouter(prefix="/api") + + +@router.get("/custom-loras", response_model=CustomLoraListResponse, tags=["custom-loras"]) +def route_list_custom_loras( + handler: AppHandler = Depends(get_state_service), +) -> CustomLoraListResponse: + return handler.custom_loras.list_loras() + + +@router.post("/custom-loras", response_model=CustomLoraImportStartResponse, tags=["custom-loras"]) +def route_import_custom_lora( + req: CustomLoraImportRequest, + handler: AppHandler = Depends(get_state_service), +) -> CustomLoraImportStartResponse: + return handler.custom_loras.start_import(req) + + +@router.post( + "/custom-loras/link-info", response_model=CustomLoraLinkInfoResponse, tags=["custom-loras"] +) +def route_custom_lora_link_info( + req: CustomLoraLinkInfoRequest, + handler: AppHandler = Depends(get_state_service), +) -> CustomLoraLinkInfoResponse: + return handler.custom_loras.link_info(req.url) + + +@router.get( + "/custom-loras/import/progress", + response_model=CustomLoraImportProgressResponse, + tags=["custom-loras"], +) +def route_custom_lora_import_progress( + sessionId: str = Query(...), + handler: AppHandler = Depends(get_state_service), +) -> CustomLoraImportProgressResponse: + return handler.custom_loras.get_import_progress(sessionId) + + +@router.get( + "/custom-loras/import/active", + response_model=ActiveCustomLoraImportResponse, + tags=["custom-loras"], +) +def route_custom_lora_import_active( + handler: AppHandler = Depends(get_state_service), +) -> ActiveCustomLoraImportResponse: + return handler.custom_loras.get_active_import() + + +@router.post( + "/custom-loras/{custom_lora_id}/weights", + response_model=CustomLoraImportStartResponse, + tags=["custom-loras"], +) +def route_restore_custom_lora_weights( + req: CustomLoraRestoreRequest, + custom_lora_id: str = Path(pattern=r"^[a-z0-9-]+$", max_length=64), + handler: AppHandler = Depends(get_state_service), +) -> CustomLoraImportStartResponse: + return handler.custom_loras.restore_weights(custom_lora_id, req) + + +@router.delete( + "/custom-loras/{custom_lora_id}/weights", response_model=StatusResponse, tags=["custom-loras"] +) +def route_delete_custom_lora_weights( + custom_lora_id: str = Path(pattern=r"^[a-z0-9-]+$", max_length=64), + handler: AppHandler = Depends(get_state_service), +) -> StatusResponse: + handler.custom_loras.delete_weights(custom_lora_id) + return StatusResponse(status="ok") + + +@router.delete("/custom-loras/{custom_lora_id}", response_model=StatusResponse, tags=["custom-loras"]) +def route_delete_custom_lora( + custom_lora_id: str = Path(pattern=r"^[a-z0-9-]+$", max_length=64), + handler: AppHandler = Depends(get_state_service), +) -> StatusResponse: + handler.custom_loras.delete(custom_lora_id) + return StatusResponse(status="ok") diff --git a/backend/_routes/generations.py b/backend/_routes/generations.py index 8599ba020..610ac9a87 100644 --- a/backend/_routes/generations.py +++ b/backend/_routes/generations.py @@ -4,14 +4,21 @@ from api_types import ( CreateAudioToVideoRequest, + CreateCustomLoraRequest, IcLoraRecipeCreate, + IcLoraTilePreflightRequest, + IcLoraTilePreflightResponse, CreateExtendRequest, CreateImageToVideoRequest, + CreateKeyframesRequest, CreateLoraRecipeRequest, CreateRetakeRequest, + CreateTextToImageRequest, CreateTextToVideoRequest, EditPreflightRequest, EditPreflightResponse, + IcLoraRecipeMemoryRequest, + IcLoraRecipeMemoryResponse, Generation, QueueSnapshot, ReorderGenerationQueueRequest, @@ -113,6 +120,19 @@ def route_create_text_to_video( ) +@router.post( + "/generations/text-to-image", + response_model=Generation, + tags=["generations"], +) +def route_create_text_to_image( + req: CreateTextToImageRequest, handler: AppHandler = Depends(get_state_service) +) -> Generation: + return handler.queued_generations.create_text_to_image( + req, analytics_client="desktop" + ) + + @router.post( "/generations/image-to-video", response_model=Generation, @@ -126,6 +146,19 @@ def route_create_image_to_video( ) +@router.post( + "/generations/keyframes", + response_model=Generation, + tags=["generations"], +) +def route_create_keyframes( + req: CreateKeyframesRequest, handler: AppHandler = Depends(get_state_service) +) -> Generation: + return handler.queued_generations.create_keyframes( + req, analytics_client="desktop" + ) + + @router.post( # Bounded under /recipes/ so the `{recipe_id}` wildcard does not swallow the # whole `POST /generations/*` namespace (a future static create route would @@ -144,6 +177,19 @@ def route_create_lora_recipe( ) +@router.post( + "/generations/custom-lora", + response_model=Generation, + tags=["generations"], +) +def route_create_custom_lora( + req: CreateCustomLoraRequest, handler: AppHandler = Depends(get_state_service) +) -> Generation: + return handler.queued_generations.create_custom_lora( + req, analytics_client="desktop" + ) + + @router.post( "/generations/audio-to-video", response_model=Generation, @@ -170,6 +216,20 @@ def route_create_retake( ) +@router.post( + "/generations/ic-lora-recipes/{recipe_id}/memory", + response_model=IcLoraRecipeMemoryResponse, + tags=["generations"], +) +def route_ic_lora_recipe_memory( + req: IcLoraRecipeMemoryRequest, + recipe_id: str = Path(pattern=_RECIPE_ID_PATTERN, max_length=64), + handler: AppHandler = Depends(get_state_service), +) -> IcLoraRecipeMemoryResponse: + # Path-free DTO (sizes and verdicts only): no remote projection needed. + return handler.ic_lora.recipe_memory(recipe_id, req) + + @router.post( "/generations/ic-lora-recipes/{recipe_id}", response_model=Generation, @@ -185,6 +245,19 @@ def route_create_ic_lora_recipe( ) +@router.post( + "/generations/ic-lora-recipes/{recipe_id}/preflight", + response_model=IcLoraTilePreflightResponse, + tags=["generations"], +) +def route_preflight_ic_lora_tile_sizes( + req: IcLoraTilePreflightRequest, + recipe_id: str = Path(pattern=_RECIPE_ID_PATTERN), + handler: AppHandler = Depends(get_state_service), +) -> IcLoraTilePreflightResponse: + return handler.queued_generations.preflight_ic_lora_tile_sizes(recipe_id, req) + + @router.post( "/generations/extend", response_model=Generation, diff --git a/backend/_routes/image_gen.py b/backend/_routes/image_gen.py index d5c2deadf..14614c495 100644 --- a/backend/_routes/image_gen.py +++ b/backend/_routes/image_gen.py @@ -10,7 +10,7 @@ pixel_resolution, run_tracked_generation, ) -from api_types import GenerateImageRequest, GenerateImageResponse +from api_types import GenerateImageRequest, GenerateImageResponse, ImageGenerationStatusResponse from state import get_state_service from app_handler import AppHandler @@ -40,3 +40,13 @@ def route_generate_image( lambda: handler.image_generation.generate(req), ) + +status_router = APIRouter(prefix="/api", tags=["image"]) + + +@status_router.get("/image-generation/status", response_model=ImageGenerationStatusResponse) +def route_image_generation_status( + handler: AppHandler = Depends(get_state_service), +) -> ImageGenerationStatusResponse: + """Mounted on both Desktop and Remote: the phone cannot read Settings.""" + return handler.image_generation.get_status() diff --git a/backend/_routes/ui_preferences.py b/backend/_routes/ui_preferences.py new file mode 100644 index 000000000..477afe1fc --- /dev/null +++ b/backend/_routes/ui_preferences.py @@ -0,0 +1,17 @@ +"""Route handler for GET /api/ui-preferences. Mounted on both Desktop and Remote.""" + +from __future__ import annotations + +from fastapi import APIRouter, Depends + +from api_types import UiPreferences +from app_handler import AppHandler +from state import get_state_service + +router = APIRouter(prefix="/api", tags=["ui-preferences"]) + + +@router.get("/ui-preferences", response_model=UiPreferences) +def route_get_ui_preferences(handler: AppHandler = Depends(get_state_service)) -> UiPreferences: + settings = handler.settings.get_settings_snapshot() + return UiPreferences(advancedControls=settings.advanced_controls) diff --git a/backend/api_model_specs.py b/backend/api_model_specs.py index 753cd6b2f..65f7652bd 100644 --- a/backend/api_model_specs.py +++ b/backend/api_model_specs.py @@ -7,15 +7,16 @@ from typing import Literal, cast from api_types import ( - BudgetReadout, ChunkedFastCell, DownloadedLocalVideoGenerationModelSpecItem, DroppedFastAspectCell, DroppedFastCell, + FastCellAsk, GenerateVideoModelsSpecsResponse, GenerateVideoRequest, LTXLocalModelId, LTXOfferingCapabilitiesSpec, + LTXVideoGenerationAspectSpec, LTXVideoGenerationModelSpecItem, LTXVideoGenerationResolutionSpec, LTXVideoGenerationSpec, @@ -46,35 +47,36 @@ offering_id_for_local_model_id, resolve_offering_local_model_id, ) +from runtime_config.measured_cells import BudgetRoute +from runtime_config.memory_meter import ( + job_filter_machine_factor, + job_memory_ask, + memory_capacity, +) from runtime_config.model_download_specs import ( get_latest_ltx_model_id, get_ltx_model_spec, is_duration_head_ready, ) -from runtime_config.reject_reasons import ( - LoadRiskTier, - ShortfallKind, - VideoJobRejectReason, +from runtime_config.budget_admission import ( + Admitted, + DroppedCellFieldsPayload, + PricedJob, + Refused, + RiskAllowance, + admit, + dropped_cell_fields, + warned_cell_parts, ) +from runtime_config.budget_decision import VideoJobReject from runtime_config.video_job_budget import ( - BudgetFeature, LocalJobFilter, - VideoJobLoad, - VideoJobReject, + budget_route, decide_fast_durations, decide_video_job, - load_headroom_gib, - load_risk_tier, + price_alternative_pass, reject_message_and_code, - reject_over_gib, - reject_over_ram_gb, - reject_shortfall_kind, - budget_readout_for_reject, - risk_for_reject, - tight_fit_message, - tight_readout, - unmeasured_message, - untested_readout, + video_job_reject, ) from server_utils.media_validation import normalize_optional_path @@ -305,51 +307,49 @@ def _unsupported_dropped_cells( ] -def _warned_cell_parts( - load: VideoJobLoad, - job_filter: LocalJobFilter, - *, - feature: BudgetFeature, -) -> tuple[LoadRiskTier, float | None, str, BudgetReadout] | None: - """Warning tier, headroom, and tooltip for a kept cell, if it warns. - - Single home for warned-cell emission (base cells and aspect cells): tight - cells carry available-minus-ask headroom, unmeasured cells compare nothing. - None when the cell fits cleanly. - """ - tier = load_risk_tier(load, job_filter, feature=feature) - if tier is None: - return None - if tier == "unmeasured": - return (tier, None, unmeasured_message(), untested_readout()) - headroom = load_headroom_gib(load, job_filter) - assert headroom is not None # a tight tier implies compared figures exist - available = headroom + load.stream_gib - darwin = job_filter.profile.system == "Darwin" - return ( - tier, - headroom, - tight_fit_message(load.stream_gib, available, darwin=darwin), - tight_readout(load.stream_gib, available), +def _dropped_cell_fields(refused: Refused, job_filter: LocalJobFilter) -> DroppedCellFieldsPayload: + reject = video_job_reject(refused) + return dropped_cell_fields( + reject, + refused.priced.evidence, + job_filter, + message=_dropped_cell_message(reject, job_filter), ) -def _dropped_cell_figures( - reject: VideoJobReject, job_filter: LocalJobFilter -) -> tuple[float | None, int | None, ShortfallKind | None]: - """Figure triple for one withheld cell: one ``risk_for_reject`` call, unpacked. - - When it declines (hard wall, or no compared exact bytes) the per-figure - helpers still name an integer-fallback total binding, so the fallback keeps - those rows byte-identical. - """ - risk = risk_for_reject(reject, job_filter) - if risk is not None: - return (risk.over_gib, risk.over_ram_gb, risk.shortfall_kind) - return ( - reject_over_gib(reject, job_filter), - reject_over_ram_gb(reject, job_filter), - reject_shortfall_kind(reject, job_filter), +def _cell_ask( + priced: PricedJob, + *, + route: BudgetRoute, + system: Literal["Windows", "Linux", "Darwin"] = "Windows", + resolution: LTXVideoGenResolution, + fps: LTXVideoGenFps, + duration: int, + audio: bool, + alternative: PricedJob | None, + machine_factor: float | None = None, + conv_vae: bool = False, +) -> FastCellAsk: + alternative_ask = None + if alternative is not None: + admitted = admit(alternative, RiskAllowance.for_mode("brave")) + alternative_ask = job_memory_ask( + alternative, + route=route, + system=system, + risk=admitted.risk if isinstance(admitted, Admitted) else None, + machine_factor=machine_factor, + conv_vae=conv_vae, + ) + return FastCellAsk( + **job_memory_ask( + priced, route=route, system=system, machine_factor=machine_factor, conv_vae=conv_vae + ).model_dump(), + resolution=resolution, + fps=fps, + duration=cast(LTXVideoGenDuration, duration), + audio=audio, + alternative=alternative_ask, ) @@ -360,6 +360,8 @@ def _filter_local_fast_resolution_map( job_filter: LocalJobFilter, mode: CanvasMode = "video", audio: bool = False, + aspect: LTXVideoGenAspectRatio = "16:9", + asks: list[FastCellAsk] | None = None, ) -> tuple[ dict[LTXVideoGenResolution, LTXVideoGenerationResolutionSpec] | None, list[DroppedFastCell], @@ -373,6 +375,7 @@ def _filter_local_fast_resolution_map( if job_filter.profile.process_mode == "unsupported": return {}, _unsupported_dropped_cells(specs, audio=audio, job_filter=job_filter), [], [], [], [] filtered: dict[LTXVideoGenResolution, LTXVideoGenerationResolutionSpec] = {} + route = budget_route("fast", job_filter.profile) dropped: list[DroppedFastCell] = [] aspect_dropped: list[DroppedFastAspectCell] = [] warned: list[WarnedFastCell] = [] @@ -381,7 +384,11 @@ def _filter_local_fast_resolution_map( for resolution, spec in specs.items(): if resolution not in caps.resolution_pixels_16_9: raise KeyError(resolution) - width, height = budget_size(local_canvas(resolution, mode=mode)) + width, height = ( + budget_size(local_canvas(resolution, mode=mode)) + if aspect == "16:9" + else budget_pixels(caps, resolution, aspect, mode=mode) + ) fps_to_durations: dict[LTXVideoGenFps, list[LTXVideoGenDuration]] = {} for fps, durations in spec.fps_to_durations.items(): outcome = decide_fast_durations( @@ -395,24 +402,39 @@ def _filter_local_fast_resolution_map( fps_to_durations[fps] = cast( list[LTXVideoGenDuration], outcome.kept ) - for duration, reason in outcome.rejected.items(): - reject = outcome.rejects[duration] - over_gib, over_ram_gb, shortfall_kind = _dropped_cell_figures( - reject, job_filter - ) - reject_window = reject.chunk_pixel_frames + if asks is not None: + # Every cell, kept or withheld, so a hover preview can show any option's ask. + machine_factor = job_filter_machine_factor(job_filter) + for duration in durations: + admission = outcome.admitted.get(duration) or outcome.refused[duration] + asks.append( + _cell_ask( + admission.priced, + route=route, + system=job_filter.profile.system, + resolution=resolution, + fps=fps, + duration=duration, + audio=audio, + alternative=price_alternative_pass( + width, + height, + compute_num_frames(duration, int(fps)), + job_filter=job_filter, + auto=admission.priced, + ), + machine_factor=machine_factor, + conv_vae=job_filter.conv_vae, + ) + ) + for duration, refused in outcome.refused.items(): + reject_window = video_job_reject(refused).chunk_pixel_frames dropped.append( DroppedFastCell( resolution=resolution, fps=fps, duration=cast(LTXVideoGenDuration, duration), - reason=reason, - message=_dropped_cell_message(reject, job_filter), audio=audio, - over_gib=over_gib, - over_ram_gb=over_ram_gb, - shortfall_kind=shortfall_kind, - readout=budget_readout_for_reject(reject, job_filter), windows=( None if reject_window is None @@ -421,13 +443,12 @@ def _filter_local_fast_resolution_map( ) ), window_frames=reject_window, + **_dropped_cell_fields(refused, job_filter), ) ) # Emit warned cells for kept durations - for duration in outcome.kept: - parts = _warned_cell_parts( - outcome.loads[duration], job_filter, feature="fast" - ) + for duration, admitted in outcome.admitted.items(): + parts = warned_cell_parts(admitted, job_filter) if parts is None: continue tier, headroom_gib, message, readout = parts @@ -444,8 +465,8 @@ def _filter_local_fast_resolution_map( ) ) # Kept durations that run in more than one window, for the "takes longer" notice. - for duration in outcome.kept: - window = outcome.loads[duration].chunk_pixel_frames + for duration, admitted in outcome.admitted.items(): + window = admitted.load.chunk_pixel_frames if window is None: continue chunked.append( @@ -458,6 +479,8 @@ def _filter_local_fast_resolution_map( audio=audio, ) ) + if aspect != "16:9": + continue # Aspect refinement: a kept anchor cell a wider shape cannot run. # Narrower-or-equal shapes cost no more than the anchor, so only # wider ratios (21:9 today) can emit here; the anchor itself and @@ -470,30 +493,22 @@ def _filter_local_fast_resolution_map( ) if selected_width * selected_height <= width * height: continue - decision = decide_video_job( + admission = decide_video_job( selected_width, selected_height, frames, job_filter=job_filter ) - if isinstance(decision, VideoJobReject): - over_gib, over_ram_gb, shortfall_kind = _dropped_cell_figures( - decision, job_filter - ) + if isinstance(admission, Refused): aspect_dropped.append( DroppedFastAspectCell( resolution=resolution, fps=fps, duration=cast(LTXVideoGenDuration, duration), aspectRatio=ratio, - reason=decision.reason, - message=_dropped_cell_message(decision, job_filter), audio=audio, - over_gib=over_gib, - over_ram_gb=over_ram_gb, - shortfall_kind=shortfall_kind, - readout=budget_readout_for_reject(decision, job_filter), + **_dropped_cell_fields(admission, job_filter), ) ) else: - parts = _warned_cell_parts(decision, job_filter, feature="fast") + parts = warned_cell_parts(admission, job_filter) if parts is not None: tier, headroom_gib, message, readout = parts aspect_warned.append( @@ -517,6 +532,65 @@ def _filter_local_fast_resolution_map( return filtered, dropped, aspect_dropped, warned, aspect_warned, chunked +def _aspect_ratios_in_spec(spec: LTXVideoGenerationSpec) -> list[LTXVideoGenAspectRatio]: + seen: list[LTXVideoGenAspectRatio] = [] + for table in ( + spec.supported_resolutions_durations, + spec.a2v_supported_resolutions_durations or {}, + ): + for rspec in table.values(): + for ratio in rspec.aspect_ratios: + if ratio not in seen: + seen.append(ratio) + return seen + + +def _build_aspect_spec( + spec: LTXVideoGenerationSpec, + caps: LtxOfferingCapabilities, + *, + job_filter: LocalJobFilter, + aspect: LTXVideoGenAspectRatio, +) -> tuple[ + LTXVideoGenerationAspectSpec, + list[DroppedFastAspectCell], + list[WarnedFastAspectCell], +]: + asks: list[FastCellAsk] = [] + kept, dropped, aspect_dropped, warned, aspect_warned, chunked = ( + _filter_local_fast_resolution_map( + spec.supported_resolutions_durations, + caps, + job_filter=job_filter, + aspect=aspect, + asks=asks, + ) + ) + a2v_kept, a2v_dropped, a2v_aspect_dropped, a2v_warned, a2v_aspect_warned, a2v_chunked = ( + _filter_local_fast_resolution_map( + spec.a2v_supported_resolutions_durations, + caps, + job_filter=job_filter, + mode="a2v", + audio=True, + aspect=aspect, + asks=asks, + ) + ) + return ( + LTXVideoGenerationAspectSpec( + supported_resolutions_durations=kept or {}, + a2v_supported_resolutions_durations=a2v_kept, + dropped_cells=dropped + a2v_dropped, + warned_cells=warned + a2v_warned, + chunked_cells=chunked + a2v_chunked, + cell_asks=asks, + ), + aspect_dropped + a2v_aspect_dropped, + aspect_warned + a2v_aspect_warned, + ) + + def _filter_local_fast_item( item: LTXVideoGenerationModelSpecItem, caps: LtxOfferingCapabilities, @@ -524,29 +598,30 @@ def _filter_local_fast_item( job_filter: LocalJobFilter, ) -> LTXVideoGenerationModelSpecItem: spec = item.spec - kept, dropped, aspect_dropped, warned, aspect_warned, chunked = _filter_local_fast_resolution_map( - spec.supported_resolutions_durations, - caps, - job_filter=job_filter, - ) - a2v_kept, a2v_dropped, a2v_aspect_dropped, a2v_warned, a2v_aspect_warned, a2v_chunked = _filter_local_fast_resolution_map( - spec.a2v_supported_resolutions_durations, - caps, - job_filter=job_filter, - mode="a2v", - audio=True, + anchor_spec, aspect_dropped, aspect_warned = _build_aspect_spec( + spec, caps, job_filter=job_filter, aspect="16:9" ) + aspect_specs: dict[LTXVideoGenAspectRatio, LTXVideoGenerationAspectSpec] = { + ratio: ( + anchor_spec + if ratio in ("16:9", "9:16") + else _build_aspect_spec(spec, caps, job_filter=job_filter, aspect=ratio)[0] + ) + for ratio in _aspect_ratios_in_spec(spec) + } return item.model_copy( update={ "spec": spec.model_copy( update={ - "supported_resolutions_durations": kept, - "a2v_supported_resolutions_durations": a2v_kept, - "dropped_cells": dropped + a2v_dropped, - "dropped_aspect_cells": aspect_dropped + a2v_aspect_dropped, - "warned_cells": warned + a2v_warned, - "warned_aspect_cells": aspect_warned + a2v_aspect_warned, - "chunked_cells": chunked + a2v_chunked, + "supported_resolutions_durations": anchor_spec.supported_resolutions_durations, + "a2v_supported_resolutions_durations": anchor_spec.a2v_supported_resolutions_durations, + "dropped_cells": anchor_spec.dropped_cells, + "dropped_aspect_cells": aspect_dropped, + "warned_cells": anchor_spec.warned_cells, + "warned_aspect_cells": aspect_warned, + "chunked_cells": anchor_spec.chunked_cells, + "cell_asks": anchor_spec.cell_asks, + "aspect_specs": aspect_specs, } ) } @@ -616,63 +691,16 @@ def get_downloaded_local_video_generation_model_specs( return items -def _fast_grid_reject_reasons( - specs: dict[LTXVideoGenResolution, LTXVideoGenerationResolutionSpec] | None, - caps: LtxOfferingCapabilities, - *, - job_filter: LocalJobFilter, -) -> set[VideoJobRejectReason]: - """Every reject reason the grid produces under the served filter. - - Mirrors ``_filter_local_fast_resolution_map``'s grid walk (same cells, - same filter) but aggregates verdicts instead of maps — no counterfactual - inputs. A second reason later is a set-membership check, not a new probe. - Single-pass collection would thread outcomes through four pydantic-returning - layers to save milliseconds of pure math on an infrequent endpoint — the - mirror stays. - """ - reasons: set[VideoJobRejectReason] = set() - if specs is None: - return reasons - for resolution, spec in specs.items(): - if resolution not in caps.resolution_pixels_16_9: - raise KeyError(resolution) - width, height = budget_size(local_canvas(resolution, mode="video")) - for fps, durations in spec.fps_to_durations.items(): - outcome = decide_fast_durations( - width, - height, - int(fps), - durations, - job_filter=job_filter, - ) - reasons.update(outcome.rejected.values()) - return reasons - - @dataclass(frozen=True, slots=True) class _LocalUnavailableDetails: - """Why the local grid is empty, plus RAM numbers when RAM binds. - - Numbers ride with the reason from the same verdicts: required is the floor - that actually gated this decision (read from the profile that produced it, - not a module constant), detected is the measured total RAM. Both None - unless the reason is ram_shortfall. - """ - - reason: LocalUnavailableReason | None - required_ram_gb: int | None - detected_ram_gb: int | None - - -_EMPTY_DETAILS = _LocalUnavailableDetails(reason=None, required_ram_gb=None, detected_ram_gb=None) + reason: LocalUnavailableReason | None = None + required_ram_gb: int | None = None + detected_ram_gb: int | None = None def _local_unavailable_details( local_models: list[LTXVideoGenerationModelSpecItem], *, - local_model_id: LTXLocalModelId | None, - duration_head_ready: bool, job_filter: LocalJobFilter, ) -> _LocalUnavailableDetails: """Name RAM when it is the binding constraint on an empty local grid. @@ -684,40 +712,19 @@ def _local_unavailable_details( """ fast = next((item for item in local_models if item.pipeline == "fast"), None) if fast is None or fast.spec.supported_resolutions_durations: - return _EMPTY_DETAILS - # Same row resolution as get_local_video_generation_model_specs: the probe - # must evaluate the model the served maps came from. - resolved_id = local_model_id or job_filter.profile.model_id or get_latest_ltx_model_id() - row_filter = replace(job_filter, profile=replace(job_filter.profile, model_id=resolved_id)) - fast_spec = next( - ( - spec - for pipeline, spec in get_ltx_model_spec(resolved_id).supported_pipelines - if pipeline == "fast" - ), - None, - ) - if fast_spec is None: - return _EMPTY_DETAILS - caps = effective_local_caps(resolved_id, duration_head_ready=duration_head_ready) - reasons = _fast_grid_reject_reasons( - fast_spec.supported_resolutions_durations, caps, job_filter=row_filter - ) - if job_filter.budget_mode == "reckless" and not reasons.isdisjoint( - {"stream_over", "ram_shortfall"} - ): - # Downgradable verdicts exist: reckless renders the warned form, not - # the empty-state card, so no reason may survive the mode flip. - return _EMPTY_DETAILS - if "ram_shortfall" not in reasons: - return _EMPTY_DETAILS + return _LocalUnavailableDetails() + video_dropped = [ + cell for cell in (fast.spec.dropped_cells or []) if not cell.audio + ] + if not any(cell.reason == "ram_shortfall" for cell in video_dropped): + return _LocalUnavailableDetails() # Shortfall verdicts prove total RAM is known (unknown yields unsupported), # so detected is present — the assert narrows what the verdicts guarantee. - total_ram_bytes = row_filter.budget.total_ram_bytes + total_ram_bytes = job_filter.budget.total_ram_bytes assert total_ram_bytes is not None return _LocalUnavailableDetails( reason="ram_shortfall", - required_ram_gb=row_filter.profile.windows_fast_required_ram_bytes // (1024**3), + required_ram_gb=job_filter.profile.windows_fast_required_ram_bytes // (1024**3), detected_ram_gb=total_ram_bytes // (1024**3), ) @@ -747,8 +754,6 @@ def build_generate_video_model_specs_response( ) unavailable = _local_unavailable_details( local_models, - local_model_id=local_model_id, - duration_head_ready=duration_head_ready, job_filter=job_filter, ) return GenerateVideoModelsSpecsResponse( @@ -765,6 +770,8 @@ def build_generate_video_model_specs_response( local_unavailable_detected_ram_gb=unavailable.detected_ram_gb, low_performance_machine=low_performance_machine, budgetMode=job_filter.budget_mode, + neverSplitIntoParts=job_filter.pass_shape == "one_pass", + memory=memory_capacity(job_filter), ) @@ -773,16 +780,30 @@ def _get_resolution_spec( *, resolution: LTXVideoGenResolution, is_a2v: bool, + aspect_ratio: LTXVideoGenAspectRatio | None = None, ) -> LTXVideoGenerationResolutionSpec | None: + aspect_spec = ( + item.spec.aspect_specs.get(aspect_ratio) + if aspect_ratio is not None and item.spec.aspect_specs is not None + else None + ) if is_a2v: # A pipeline with no a2v spec doesn't support audio-conditioned generation at # all — must not fall back to the plain (non-a2v) matrix, or an unsupported # pipeline looks valid here and only fails downstream at the LTX API. - if item.spec.a2v_supported_resolutions_durations is None: + resolution_map = ( + aspect_spec.a2v_supported_resolutions_durations + if aspect_spec is not None + else item.spec.a2v_supported_resolutions_durations + ) + if resolution_map is None: return None - resolution_map = item.spec.a2v_supported_resolutions_durations else: - resolution_map = item.spec.supported_resolutions_durations + resolution_map = ( + aspect_spec.supported_resolutions_durations + if aspect_spec is not None + else item.spec.supported_resolutions_durations + ) return resolution_map.get(resolution) @@ -799,9 +820,12 @@ def supported_duration_range( *, resolution: LTXVideoGenResolution, fps: LTXVideoGenFps, + aspect_ratio: LTXVideoGenAspectRatio | None = None, is_a2v: bool = False, ) -> tuple[LTXVideoGenDuration, LTXVideoGenDuration]: - resolution_spec = _get_resolution_spec(item, resolution=resolution, is_a2v=is_a2v) + resolution_spec = _get_resolution_spec( + item, resolution=resolution, is_a2v=is_a2v, aspect_ratio=aspect_ratio + ) if resolution_spec is None: raise KeyError(resolution) durations = get_supported_durations(resolution_spec, fps=fps) diff --git a/backend/api_types.py b/backend/api_types.py index 0a60597fa..efa3ab015 100644 --- a/backend/api_types.py +++ b/backend/api_types.py @@ -13,14 +13,43 @@ JsonValue, StringConstraints, field_validator, - model_serializer, model_validator, - SerializerFunctionWrapHandler, Tag, ) from pydantic.json_schema import SkipJsonSchema from api_motion_path import MOTION_PATH_MAX_PATHS, MotionPath +from api_types_lora import ( + CUSTOM_LORA_DESCRIPTION_MAX as CUSTOM_LORA_DESCRIPTION_MAX, + CUSTOM_LORA_EXAMPLE_MAX as CUSTOM_LORA_EXAMPLE_MAX, + CUSTOM_LORA_EXAMPLES_MAX as CUSTOM_LORA_EXAMPLES_MAX, + CUSTOM_LORA_TRIGGER_MAX as CUSTOM_LORA_TRIGGER_MAX, + ActiveCustomLoraImportResponse as ActiveCustomLoraImportResponse, + ActiveIcLoraDownloadResponse as ActiveIcLoraDownloadResponse, + ActiveLoraDownloadResponse as ActiveLoraDownloadResponse, + CatalogDownloadStartResponse as CatalogDownloadStartResponse, + CatalogDownloadStatus as CatalogDownloadStatus, + CustomLoraDescription as CustomLoraDescription, + CustomLoraExample as CustomLoraExample, + CustomLoraId as CustomLoraId, + CustomLoraImportProgressResponse as CustomLoraImportProgressResponse, + CustomLoraImportRequest as CustomLoraImportRequest, + CustomLoraImportStartResponse as CustomLoraImportStartResponse, + CustomLoraItem as CustomLoraItem, + CustomLoraLinkInfoRequest as CustomLoraLinkInfoRequest, + CustomLoraLinkInfoResponse as CustomLoraLinkInfoResponse, + CustomLoraListResponse as CustomLoraListResponse, + CustomLoraRestoreRequest as CustomLoraRestoreRequest, + CustomLoraSource as CustomLoraSource, + CustomLoraTrigger as CustomLoraTrigger, + IcLoraDeleteRequest as IcLoraDeleteRequest, + IcLoraDownloadProgressResponse as IcLoraDownloadProgressResponse, + IcLoraDownloadRequest as IcLoraDownloadRequest, + LoraDeleteRequest as LoraDeleteRequest, + LoraDownloadProgressResponse as LoraDownloadProgressResponse, + LoraDownloadRequest as LoraDownloadRequest, + LoraEntry as LoraEntry, +) from assistant_limits import ASSISTANT_LIMITS from frame_math import compute_num_frames from runtime_config.eta import EtaBasis, EtaFeature @@ -28,17 +57,42 @@ BudgetMode, IcLoraDroppedReason, JobRiskTier, - LoadRiskTier, + PassShape, ShortfallKind, + UnmeasuredBasis, VideoJobRejectReason, + WarnedCellTier, ) from runtime_config.ic_lora_stage_mode import IcLoraStageMode, ic_lora_stage_mode -from runtime_config.ic_lora_tiling import IcLoraTiling +from runtime_config.ic_lora_tiling import ( + MAX_TILE_OVERLAP, + MIN_CARRY_FRAMES, + MIN_TILE_OVERLAP, + MIN_WINDOW_FRAMES, + IcLoraTileSize, + IcLoraTiling, +) +from runtime_config.nag_limits import ( + MAX_ALPHA as NAG_MAX_ALPHA, + MAX_SCALE as NAG_MAX_SCALE, + MAX_TAU as NAG_MAX_TAU, + NEGATIVE_PROMPT_MAX_LENGTH, +) NonEmptyPrompt = Annotated[str, StringConstraints(strip_whitespace=True, min_length=1)] LocalAssistantModel = Literal["qwen3.5:9b"] +class NagParams(BaseModel): + model_config = ConfigDict(strict=True, extra="forbid") + + negativePrompt: str = Field(default="", max_length=NEGATIVE_PROMPT_MAX_LENGTH) + nagScale: float | None = Field(default=None, ge=0.0, le=NAG_MAX_SCALE, allow_inf_nan=False) + nagAlpha: float | None = Field(default=None, ge=0.0, le=NAG_MAX_ALPHA, allow_inf_nan=False) + nagTau: float | None = Field(default=None, ge=0.0, le=NAG_MAX_TAU, allow_inf_nan=False) + + + class AssistantModelDownloadRequest(BaseModel): model: LocalAssistantModel @@ -193,6 +247,21 @@ class FeatureFlags(BaseModel): # still gates every job, and a cell with no measured run (measured_cells.py) is # refused in Standard mode. The flag only adds the cell. Off by default. highResVideoToVideo: bool = False + # Show "Create with AI" next to the start frame, end frame and reference image fields. + # It opens the image generator and puts the image in the field. Off by default. + createWithAi: bool = False + # Show a "Negative prompt:" line under each result's meta bar, for every feature + # that stores a negative prompt. For comparing runs with and without one. Off by default. + showGenerationNegativePrompt: bool = False + # Offer the Keyframes feature on Home. The backend refuses the create route while it is + # off, and Home hides the feature. GenSpace multi-keyframe has no flag. Off by default. + keyframes: bool = False + + +class UiPreferences(BaseModel): + """The user settings that change what a form shows. Read-only, so Remote may read them.""" + + advancedControls: bool = False class FeatureFlagsPatch(BaseModel): @@ -203,6 +272,9 @@ class FeatureFlagsPatch(BaseModel): customIcLora: bool | None = None advancedIcLoraControls: bool | None = None highResVideoToVideo: bool | None = None + createWithAi: bool | None = None + showGenerationNegativePrompt: bool | None = None + keyframes: bool | None = None class GenerationProgressResponse(BaseModel): @@ -225,6 +297,7 @@ class GenerationProgressResponse(BaseModel): # measured hardware only). None means unknown, not zero. Shared with the # pre-generate estimate endpoint so both surfaces speak one contract. estimate: WallTimeEstimateResponse | None = None + remainingSeconds: int | None = None class WallTimeEstimateResponse(BaseModel): @@ -600,11 +673,12 @@ class BudgetReadout(BaseModel): class WarnedFastCell(BaseModel): - """One kept grid cell carrying a warning tier (tight fit or unmeasured). + """One kept grid cell carrying a warning tier: a tight fit, or a Brave bet + (over budget or untested) the echoed mode admits. Kept + warned render the full grid for warned-with-tooltip pickers: ``fps_to_durations`` stays the kept set, this list marks the risky subset. - ``headroom_gib`` is set on tight cells only (unmeasured compares nothing). + ``headroom_gib`` is set on tight cells only. ``message`` is backend-composed, same builder as the create annotation, so the picker tooltip and the queue badge read identically. """ @@ -612,7 +686,7 @@ class WarnedFastCell(BaseModel): resolution: LTXVideoGenResolution fps: LTXVideoGenFps duration: LTXVideoGenDuration - tier: LoadRiskTier + tier: WarnedCellTier headroom_gib: float | None = None message: str readout: BudgetReadout | None = None @@ -628,7 +702,7 @@ class WarnedFastAspectCell(BaseModel): fps: LTXVideoGenFps duration: LTXVideoGenDuration aspectRatio: LTXVideoGenAspectRatio - tier: LoadRiskTier + tier: WarnedCellTier headroom_gib: float | None = None message: str readout: BudgetReadout | None = None @@ -670,7 +744,8 @@ class DroppedFastCell(BaseModel): over_ram_gb: int | None = None shortfall_kind: ShortfallKind | None = None readout: BudgetReadout | None = None - # Set when the run this cell would get (a Reckless run, or an unmeasured bet) is in + unmeasured_basis: UnmeasuredBasis | None = None + # Set when the run this cell would get (a Brave run, or an unmeasured bet) is in # overlapping windows: the window count and the pixel frames of one window. A picker that # offers the cell anyway tells the user, as it does for a kept ``ChunkedFastCell``. windows: int | None = None @@ -698,6 +773,94 @@ class DroppedFastAspectCell(BaseModel): over_ram_gb: int | None = None shortfall_kind: ShortfallKind | None = None readout: BudgetReadout | None = None + unmeasured_basis: UnmeasuredBasis | None = None + + +MemoryConfidence = Literal["solid", "estimate", "rough"] + + +class GenerationRisk(BaseModel): + """Create-time snapshot of the bet a Brave job took. + + Stored privately as spec["_risk"] (no store migration), promoted to this + typed field on every read. Drives the queue badge and the failure backstop + copy. An `over` tier also waives a later memory miss at execute. An + `unmeasured` tier does not. `over_gib`/`over_ram_gb` mirror the dropped- + cell figure semantics; `message` is the snapshotted tier line. + """ + + model_config = ConfigDict(strict=True, extra="forbid") + + tier: JobRiskTier + shortfall_kind: ShortfallKind | None = None + over_gib: float | None = None + over_ram_gb: int | None = None + readout: BudgetReadout | None = None + message: str + unmeasured_basis: UnmeasuredBasis | None = None + + +class JobMemoryAsk(BaseModel): + """What one job asks of the memory the gate compares. + + ``ask_gib`` is the figure admission compares against ``MemoryCapacity.capacity_gib``, rounded + up to 0.001 GiB, so a meter drawn from it never shows an over job as fitting. ``windows`` is + 1 for a single pass. ``tight`` is the gate's own tight-fit flag. The band is sent on + ``estimate`` asks only: one ask per Fast grid point and aspect makes this the bulk of the + specs payload. ``risk`` is sent on ``FastCellAsk.alternative`` when the alternative pass + shape is an ``over`` or ``unmeasured`` bet. + """ + + ask_gib: float + confidence: MemoryConfidence + windows: int = 1 + tight: bool = False + band_low_gib: float | None = Field(default=None, exclude_if=lambda value: value is None) + band_high_gib: float | None = Field(default=None, exclude_if=lambda value: value is None) + risk: GenerationRisk | None = Field(default=None, exclude_if=lambda value: value is None) + estimated_seconds: int | None = Field(default=None, exclude_if=lambda value: value is None) + + +class FastCellAsk(JobMemoryAsk): + """One Fast grid cell's ask, kept or withheld. + + The ask is the shape the budget picks (``windows`` 1 is one pass). ``alternative`` is the + other shape's ask, sent only where a Brave form offers the choice, so a shape the form + shows is always one create runs. + """ + + resolution: LTXVideoGenResolution + fps: LTXVideoGenFps + duration: LTXVideoGenDuration + audio: bool + alternative: JobMemoryAsk | None = Field(default=None, exclude_if=lambda value: value is None) + + +class MemoryCapacity(BaseModel): + """The figure every ``FastCellAsk`` is compared against. + + ``gpu`` is total VRAM (list time gates on total). ``mac`` is the MPS pool macOS recommends + for this Mac, which is the whole allowance video may use. None when the backend compared + nothing (unknown VRAM, unsupported process). + """ + + device: Literal["gpu", "mac"] + capacity_gib: float | None + + +class LTXVideoGenerationAspectSpec(BaseModel): + """Per-aspect kept grids and cell annotations priced at that ratio's real canvas.""" + + supported_resolutions_durations: dict[ + LTXVideoGenResolution, LTXVideoGenerationResolutionSpec + ] + a2v_supported_resolutions_durations: ( + dict[LTXVideoGenResolution, LTXVideoGenerationResolutionSpec] | None + ) = None + dropped_cells: list[DroppedFastCell] = Field(default_factory=list[DroppedFastCell]) + warned_cells: list[WarnedFastCell] = Field(default_factory=list[WarnedFastCell]) + chunked_cells: list[ChunkedFastCell] = Field(default_factory=list[ChunkedFastCell]) + cell_asks: list[FastCellAsk] = Field(default_factory=list[FastCellAsk]) class LTXVideoGenerationSpec(BaseModel): @@ -721,6 +884,11 @@ class LTXVideoGenerationSpec(BaseModel): # Kept cells that run in more than one window (the anchor shape; a wider shape can need # more windows). Same None/empty contract as warned_cells. chunked_cells: list[ChunkedFastCell] | None = None + # Every priced cell's ask, kept and withheld, at the anchor shape. Same None/empty contract. + cell_asks: list[FastCellAsk] | None = None + # Per-aspect kept grids and cell annotations priced at each ratio's real canvas. + # None where no gating ran (API specs, unfiltered validation ceiling). + aspect_specs: dict[LTXVideoGenAspectRatio, LTXVideoGenerationAspectSpec] | None = None class LTXVideoGenerationModelSpecItem(BaseModel): @@ -758,7 +926,10 @@ class GenerateVideoModelsSpecsResponse(BaseModel): # The backend machine is slow for heavy local runs. The backend decides, so the # desktop app and the Remote app show the same warnings. low_performance_machine: bool = False - budgetMode: BudgetMode = "standard" + budgetMode: BudgetMode = "brave" + # "Never split into parts" the grid was priced with, echoed like the mode. + neverSplitIntoParts: bool = False + memory: MemoryCapacity | None = None class InstalledModelResponse(BaseModel): @@ -774,31 +945,6 @@ class InstalledModelsResponse(BaseModel): models: list[InstalledModelResponse] -class LoraEntry(BaseModel): - model_config = ConfigDict(strict=True) - - ref: str - scale: float = Field(default=1.0, ge=0.0, le=4.0) - # Catalog id when this LoRA was picked from the library, so automatic enhancement can look - # up its trigger/instructions. Absent for a custom LoRA the user supplied themselves, which - # stays weights-only — the weights' filename is never matched against the catalog. - catalogId: str | None = None - # Catalog name at enqueue time. Kept after the LoRA leaves the catalog so - # the dashboard can still label the run. - displayName: str | None = None - # Checkpoint chosen at enqueue, next to scale, so a later variant can be told apart. - variantId: str | None = None - - @model_serializer(mode="wrap") - def _omit_unset_variant( - self, handler: SerializerFunctionWrapHandler - ) -> dict[str, JsonValue]: - data = cast("dict[str, JsonValue]", handler(self)) - if data.get("variantId") is None: - data.pop("variantId", None) - return data - - # Local Distilled offering cap. API pipelines stay at 0 via multi_keyframe=False. LOCAL_MULTI_KEYFRAME_MAX_COUNT = 10 @@ -813,6 +959,16 @@ class KeyframeInput(BaseModel): strength: float = Field(default=1.0, ge=0.0, le=1.0) +class KeyframeRef(BaseModel): + """One still on the timeline. An asset id, never a path.""" + + model_config = ConfigDict(strict=True, extra="forbid") + + assetId: str = Field(min_length=1) + frameIndex: int = Field(ge=0) + strength: float = Field(default=1.0, ge=0.0, le=1.0) + + # Where the submitted prompt came from. "typed" (the default for any client that omits it) is # eligible for automatic enhancement; "enhanced" is the exact text a successful manual Enhance # produced and the user chose to keep, so generation must submit it untouched rather than @@ -820,7 +976,7 @@ class KeyframeInput(BaseModel): PromptProvenance: TypeAlias = Literal["typed", "enhanced"] -class GenerateVideoRequest(BaseModel): +class GenerateVideoRequest(NagParams): model_config = ConfigDict(strict=True) prompt: Annotated[str, StringConstraints(strip_whitespace=True)] @@ -828,7 +984,6 @@ class GenerateVideoRequest(BaseModel): resolution: LTXVideoGenResolution = "1080p" model: LTXVideoGenPipeline = "fast" cameraMotion: VideoCameraMotion = "none" - negativePrompt: str = "" # None = automatic duration (API 2.5 t2v/i2v only): the worker picks length from the prompt. duration: LTXVideoGenDuration | None = 5 fps: LTXVideoGenFps = 24 @@ -848,13 +1003,17 @@ def _require_prompt_or_start_image(self) -> "GenerateVideoRequest": return self +# Z-Image Turbo is distilled for four steps. Every image path uses it. +ZIT_DEFAULT_STEPS = 4 + + class GenerateImageRequest(BaseModel): model_config = ConfigDict(strict=True) prompt: NonEmptyPrompt width: int = Field(default=1024, ge=16) height: int = Field(default=1024, ge=16) - numSteps: int = Field(default=4, ge=1) + numSteps: int = Field(default=ZIT_DEFAULT_STEPS, ge=1) numImages: int = Field(default=1, ge=1) imagePath: str | None = None strength: float = Field(default=0.6, ge=0.0, le=1.0) @@ -1053,6 +1212,13 @@ class IcLoraGenerateRequest(BaseModel): # LoRA adapter merge weight (baked at load time). Bounded to [0, 2] to match the # desktop IC-LoRA strength control (same practical ceiling as the plain-LoRA UI slider). lora_strength: float | None = Field(default=None, ge=0.0, le=2.0) + # Advanced controls of a tiled catalog entry (Refine Details). None keeps the catalog + # value, or the high cell default for the carry. A request for an entry without a tile + # plan, or a pair the pipeline cannot run, is refused (422). + tile_overlap: float | None = Field(default=None, ge=MIN_TILE_OVERLAP, le=MAX_TILE_OVERLAP) + carry_frames: int | None = Field(default=None, ge=MIN_CARRY_FRAMES) + tile_size: IcLoraTileSize | None = None + max_window_frames: int | None = Field(default=None, ge=MIN_WINDOW_FRAMES) # Override the control-video fps by temporally resampling it. Lower fps = fewer frames = # less compute/VRAM (fits longer clips), at the cost of choppier motion. None = source fps. # Only decimates (ignored if >= source fps). @@ -1068,7 +1234,10 @@ class IcLoraGenerateRequest(BaseModel): loop_seconds: LTXVideoGenDuration | None = None num_inference_steps: int = 30 cfg_guidance_scale: float = 1.0 - negative_prompt: str = "" + negative_prompt: str = Field(default="", max_length=NEGATIVE_PROMPT_MAX_LENGTH) + nag_scale: float | None = Field(default=None, ge=0.0, le=NAG_MAX_SCALE, allow_inf_nan=False) + nag_alpha: float | None = Field(default=None, ge=0.0, le=NAG_MAX_ALPHA, allow_inf_nan=False) + nag_tau: float | None = Field(default=None, ge=0.0, le=NAG_MAX_TAU, allow_inf_nan=False) images: list[IcLoraImageInput] = Field(default_factory=_default_ic_lora_images) # "custom" conditioning: the user's own IC-LoRA + a pre-rendered control video. # Ignored for canny/depth; required (both) when conditioning_type == "custom". @@ -1350,6 +1519,8 @@ class LoraCatalogItem(BaseModel): enhancement_examples: list[str] = Field(default_factory=list) # Suggested LoRA scale when a plain LoRA is selected (IC-LoRAs use default_settings instead). recommended_strength: float | None = None + # Generic negative prompt from the Hugging Face model card, when the card names one. + default_negative_prompt: str | None = None # When true, generation may run with an empty prompt (e.g. outpainting fills from the scene). # Enforced for the catalog IC-LoRA path; plain-LoRA t2v enforcement is not wired yet. allows_empty_prompt: bool = False @@ -1426,6 +1597,7 @@ class DroppedIcLoraDuration(BaseModel): over_ram_gb: int | None = None shortfall_kind: ShortfallKind | None = None readout: BudgetReadout | None = None + unmeasured_basis: UnmeasuredBasis | None = None class IcLoraControl(BaseModel): @@ -1504,6 +1676,7 @@ def _empty_controls() -> list[IcLoraControl]: "base_model", "controls", "created_at", + "default_negative_prompt", "default_settings", "description", "download", @@ -1678,14 +1851,17 @@ def _check_end_after_start(self) -> "ReplacedWindow": class EnhancePromptRequest(BaseModel): """Regular-LoRA, IC-LoRA, and built-in conditioning-type selection are mutually exclusive UI - surfaces — a request never carries more than one of loraCatalogIds/icLoraId/conditioningType. + surfaces — a request never carries more than one of loraCatalogIds/customLoraIds/icLoraId/conditioningType. """ model_config = ConfigDict(strict=True) # Empty is allowed when imagePath or keyframes are set — the rewrite is then captioned # from the attached frame(s), plus any extra text the user did type. prompt: str + negativePrompt: str | None = Field(default=None, max_length=NEGATIVE_PROMPT_MAX_LENGTH) loraCatalogIds: list[str] = Field(default_factory=list) + # The user's saved custom LoRA. The enhancer reads what the user told it about the LoRA. + customLoraIds: list[str] = Field(default_factory=list, max_length=1) icLoraId: str | None = None # Set only for the built-in (non-catalog) "bring your own IC-LoRA" canny/depth conditioning # modes — those have no catalog entry to draw a system prompt from, but still need the same @@ -1701,6 +1877,9 @@ class EnhancePromptRequest(BaseModel): # Same shape as GenerateVideoRequest.keyframes. Mutually exclusive with imagePath/ # lastImagePath — middle markers have nowhere to go on the two-slot i2v path. keyframes: list[KeyframeInput] = Field(default_factory=list[KeyframeInput]) + # The same stills as asset ids. Explore sends these and the route resolves them to + # `keyframes`. Mutually exclusive with `keyframes`, and bound by the same rules. + keyframeAssets: list[KeyframeRef] = Field(default_factory=list[KeyframeRef]) # The panel images of an image-list IC-LoRA (Ingredients), in order. Explore sends asset # ids and the route resolves them to paths. Needs an icLoraId whose entry takes an image # list. Mutually exclusive with every other image input and with a video. @@ -1740,16 +1919,17 @@ class EnhancePromptRequest(BaseModel): def _check_selection_is_mutually_exclusive(self) -> "EnhancePromptRequest": selected = [ bool(self.loraCatalogIds), + bool(self.customLoraIds), self.icLoraId is not None, self.conditioningType is not None, ] if sum(selected) > 1: raise ValueError( - "loraCatalogIds, icLoraId, and conditioningType are mutually exclusive" + "loraCatalogIds, customLoraIds, icLoraId, and conditioningType are mutually exclusive" ) if self.mediaType == "image" and sum(selected) > 0: raise ValueError( - "loraCatalogIds, icLoraId, and conditioningType only apply to mediaType='video'" + "loraCatalogIds, customLoraIds, icLoraId, and conditioningType only apply to mediaType='video'" ) has_first_path = bool((self.imagePath or "").strip()) has_last_path = bool((self.lastImagePath or "").strip()) @@ -1761,19 +1941,27 @@ def _check_selection_is_mutually_exclusive(self) -> "EnhancePromptRequest": raise ValueError("Use lastImagePath or lastImageAssetId, not both") has_first = has_first_path or has_first_asset has_last = has_last_path or has_last_asset - has_keyframes = bool(self.keyframes) + if self.keyframes and self.keyframeAssets: + raise ValueError("Use keyframes or keyframeAssets, not both") + keyframe_indices = [ + keyframe.frameIndex for keyframe in (self.keyframes or self.keyframeAssets) + ] + has_keyframes = bool(keyframe_indices) if self.mediaType == "image" and has_keyframes: raise ValueError("keyframes only apply to mediaType='video'") + # Explore text-to-image has no input image. A path is the GenSpace edit rewrite. + if self.mediaType == "image" and (has_first_asset or has_last_asset or self.imageAssetIds): + raise ValueError("mediaType='image' takes no image asset ids") if has_keyframes and (has_first or has_last): raise ValueError("Keyframes cannot be combined with a first or last frame") if has_last and not has_first: raise ValueError("Last frame requires a first-frame image") if has_keyframes: - if len(self.keyframes) > LOCAL_MULTI_KEYFRAME_MAX_COUNT: + if len(keyframe_indices) > LOCAL_MULTI_KEYFRAME_MAX_COUNT: raise ValueError( f"You can place up to {LOCAL_MULTI_KEYFRAME_MAX_COUNT} keyframes" ) - indices = [keyframe.frameIndex for keyframe in self.keyframes] + indices = keyframe_indices if len(set(indices)) != len(indices): raise ValueError("Keyframe frame indices must be unique") if self.duration is not None and self.fps is not None and self.fps > 0: @@ -1795,7 +1983,9 @@ def _check_selection_is_mutually_exclusive(self) -> "EnhancePromptRequest": raise ValueError("A video cannot be combined with last-frame or keyframe input") if has_video and has_first and self.icLoraId is None: raise ValueError("A video combines with an image only for an IC-LoRA look image") - if has_video and (self.loraCatalogIds or self.conditioningType is not None): + if has_video and ( + self.loraCatalogIds or self.customLoraIds or self.conditioningType is not None + ): raise ValueError("A video only combines with icLoraId or no selection") if self.replacedWindow is not None and (not has_video or self.icLoraId is not None): raise ValueError("replacedWindow needs a video and does not combine with icLoraId") @@ -1832,6 +2022,10 @@ class PromptEnhancerStatusResponse(BaseModel): defaultProvider: Literal["local", "api"] canToggleProvider: bool showManualEnhance: bool + nagUnavailableReason: str | None = None + nagUnavailableReasonByFeature: dict[str, str] = Field(default_factory=dict) + # The Desktop setting that shows the per-run NAG strength row; Remote follows it. + showNagStrengthControls: bool = False class IcLoraListItem(BaseModel): @@ -1845,44 +2039,7 @@ class IcLoraListItem(BaseModel): class IcLoraListResponse(BaseModel): model_config = ConfigDict(strict=True) ic_loras: list[IcLoraListItem] - budgetMode: BudgetMode = "standard" - - -class IcLoraDownloadRequest(BaseModel): - model_config = ConfigDict(strict=True) - ic_lora_id: str - # Optional catalog download.variants[].id; omit to download the default filename. - variant_id: str | None = None - # Dev escape hatch: attach the in-app HuggingFace token even when HF gating is off - # (gated IC-LoRA repos need auth; gating is normally env-driven in packaged builds). - use_hf_auth: bool = False - - -class IcLoraDeleteRequest(BaseModel): - model_config = ConfigDict(strict=True) - ic_lora_id: str - variant_id: str | None = None - - -# Shared start-response for both catalog download kinds (IC-LoRA + plain LoRA). -class CatalogDownloadStartResponse(BaseModel): - model_config = ConfigDict(strict=True) - status: str - sessionId: str - - -CatalogDownloadStatus: TypeAlias = Literal["downloading", "complete", "error"] - - -class IcLoraDownloadProgressResponse(BaseModel): - model_config = ConfigDict(strict=True) - status: CatalogDownloadStatus - ic_lora_id: str | None = None - downloaded_bytes: int = 0 - expected_bytes: int = 0 - progress: float = 0.0 - speed_bytes_per_sec: float = 0.0 - error: str | None = None + budgetMode: BudgetMode = "brave" # --- Plain LoRA catalog (list + download). Mirrors the IC-LoRA flow with a separate @@ -1900,48 +2057,6 @@ class LoraListResponse(BaseModel): loras: list[LoraListItem] -class LoraDownloadRequest(BaseModel): - model_config = ConfigDict(strict=True) - lora_id: str - # Optional catalog download.variants[].id; omit to download the default filename. - variant_id: str | None = None - use_hf_auth: bool = False - - -class LoraDeleteRequest(BaseModel): - model_config = ConfigDict(strict=True) - lora_id: str - variant_id: str | None = None - - -class LoraDownloadProgressResponse(BaseModel): - model_config = ConfigDict(strict=True) - status: CatalogDownloadStatus - lora_id: str | None = None - downloaded_bytes: int = 0 - expected_bytes: int = 0 - progress: float = 0.0 - speed_bytes_per_sec: float = 0.0 - error: str | None = None - - -class ActiveLoraDownloadResponse(BaseModel): - model_config = ConfigDict(strict=True) - # The currently-running plain-LoRA download session. Nulls when idle. - session_id: str | None - lora_id: str | None - # 0–99 while downloading so a remount can seed the progress label instead of flashing 0%. - progress: float | None = None - - -class ActiveIcLoraDownloadResponse(BaseModel): - model_config = ConfigDict(strict=True) - # The currently-running IC-LoRA download session. Nulls when idle. - session_id: str | None - ic_lora_id: str | None - progress: float | None = None - - class GeminiModelOptionPayload(BaseModel): model_config = ConfigDict(strict=True) id: str @@ -1981,6 +2096,8 @@ class GeminiModelsResponsePayload(BaseModel): # Other capability failures stay CAPABILITY_FAILED. "LTX_INVALID_API_KEY", "LTX_API_PROMPT_EMBEDDING_FAILED", + # The image provider's safety checker returned no image for the prompt. + "IMAGE_BLOCKED_BY_SAFETY_CHECKER", ] @@ -2095,26 +2212,6 @@ class AssetListResponse(BaseModel): next_cursor: str | None = None -class GenerationRisk(BaseModel): - """Create-time snapshot of the bet a reckless job took. - - Stored privately as spec["_risk"] (no store migration), promoted to this - typed field on every read. Drives the queue badge and the failure backstop - copy. An `over` tier also waives a later memory miss at execute. An - `unmeasured` tier does not. `over_gib`/`over_ram_gb` mirror the dropped- - cell figure semantics; `message` is the snapshotted tier line. - """ - - model_config = ConfigDict(strict=True, extra="forbid") - - tier: JobRiskTier - shortfall_kind: ShortfallKind | None = None - over_gib: float | None = None - over_ram_gb: int | None = None - readout: BudgetReadout | None = None - message: str - - class GenerationCore(BaseModel): """Lifecycle fields shared by Desktop and Remote generations. @@ -2135,6 +2232,10 @@ class GenerationCore(BaseModel): started_at: int | None = None finished_at: int | None = None risk: GenerationRisk | None = None + # The execution lane the job runs on ("local" or a provider). Set when the job is queued. + lane: str = Field(default="local", min_length=1) + # The id of the job at its provider. Null for a local job and until the provider accepts it. + provider_job_id: str | None = None @model_validator(mode="after") def _failed_has_error_code(self) -> Self: @@ -2148,6 +2249,13 @@ class Generation(GenerationCore): outputs: list[Asset] +# What a provider reports for a running external job. Memory only, never stored. +ApiActivityStatus = Literal["pending", "processing"] + +# Who rewrote the prompt of a run: local Gemma, Gemini, or the provider's own expansion. +PromptRewriteSource = Literal["local", "gemini", "fal_expansion"] + + class QueueProgress(BaseModel): """Live progress for the persisted active queue entry.""" @@ -2156,6 +2264,7 @@ class QueueProgress(BaseModel): progress: int currentStep: int | None totalSteps: int | None + remainingSeconds: int | None = Field(default=None, exclude_if=lambda value: value is None) class QueueEntry(BaseModel): @@ -2163,11 +2272,15 @@ class QueueEntry(BaseModel): generation: Generation input_assets: list[Asset] progress: QueueProgress | None = None + # Live queue facts, never stored. A queued or finished row is always cancellable. + cancellable: bool = True + api_status: ApiActivityStatus | None = None class QueueSnapshot(BaseModel): model_config = ConfigDict(strict=True) - active: QueueEntry | None + # One entry per running job. Jobs on different lanes run at the same time. + active: list[QueueEntry] = Field(default_factory=list[QueueEntry]) queued: list[QueueEntry] done: list[QueueEntry] = Field(default_factory=list[QueueEntry]) failed: list[QueueEntry] = Field(default_factory=list[QueueEntry]) @@ -2191,17 +2304,17 @@ class TrimMediaRequest(BaseModel): endSec: float = Field(gt=0, allow_inf_nan=False) -class _QueuedVideoParams(BaseModel): +class _QueuedVideoParams(NagParams): model_config = ConfigDict(strict=True, extra="forbid") resolution: LTXVideoGenResolution = "1080p" model: OfferingId cameraMotion: VideoCameraMotion = "none" - negativePrompt: str = "" duration: LTXVideoGenDuration | None = 5 fps: LTXVideoGenFps = 24 seed: int | None = None promptProvenance: PromptProvenance = "typed" + passShape: PassShape = "auto" class TextToVideoParams(_QueuedVideoParams): @@ -2262,6 +2375,30 @@ class ImageToVideoInputs(BaseModel): endFrame: InputAssetRef | None = None +class KeyframesParams(_QueuedVideoParams): + """Non-media params of a Home Keyframes job. Several stills guide one clip. + + The keyframes need a known length, so ``duration`` cannot be ``None``. A blank prompt + is refused: the generate request takes a blank one only with a start image. + """ + + prompt: NonEmptyPrompt + aspectRatio: LTXQueuedAspectRatio = "auto" + + @field_validator("duration") + @classmethod + def _duration_is_set(cls, value: LTXVideoGenDuration | None) -> LTXVideoGenDuration: + if value is None: + raise ValueError("Keyframes cannot be combined with automatic duration") + return value + + +class KeyframesInputs(BaseModel): + model_config = ConfigDict(strict=True, extra="forbid") + + keyframes: list[KeyframeRef] = Field(min_length=1, max_length=LOCAL_MULTI_KEYFRAME_MAX_COUNT) + + class LoraRecipeInputs(BaseModel): """Start frame for an i2v LoRA recipe. t2v recipes omit this object. @@ -2282,12 +2419,90 @@ class CreateLoraRecipeRequest(BaseModel): contract_version: int = Field(default=1, ge=1) +class CustomLoraParams(_QueuedVideoParams): + """Create-body params for a custom LoRA run. + + The client sends the custom LoRA id + scale, never a filesystem path. Create stores + ``loras: [{ ref: "", scale, displayName, customLoraId }]`` and execute hydrates the + weights path (see ``make_custom_lora_resolver``). ``aspectRatio`` includes ``auto`` only + when the run has a start frame (resolved from the start frame at execute); a run without + one rejects ``auto``. + """ + + prompt: NonEmptyPrompt + aspectRatio: LTXQueuedAspectRatio = "16:9" + customLoraId: CustomLoraId + scale: float = Field(default=1.0, ge=0.0, le=4.0) + + +class CreateCustomLoraRequest(BaseModel): + """``inputs`` carries the optional Start Frame. With it the run is image to video. Without it, text to video.""" + + model_config = ConfigDict(strict=True, extra="forbid") + + params: CustomLoraParams + inputs: LoraRecipeInputs | None = None + contract_version: int = Field(default=1, ge=1) + + class CreateTextToVideoRequest(BaseModel): model_config = ConfigDict(strict=True, extra="forbid") params: TextToVideoParams contract_version: int = Field(default=1, ge=1) +ImageProvider: TypeAlias = Literal["local", "fal"] + +ImageProviderBlocker: TypeAlias = Literal[ + "FAL_API_KEY_NOT_CONFIGURED", + "LOCAL_GENERATION_UNSUPPORTED", + "IMAGE_MODEL_NOT_DOWNLOADED", +] + +IMAGE_MIN_SIDE = 256 +IMAGE_MAX_SIDE = 2048 +IMAGE_SIDE_GRID = 16 + + +class _TextToImageFields(BaseModel): + """Shared text-to-image params. No image input exists: Z-Image edit is not used.""" + + model_config = ConfigDict(strict=True, extra="forbid") + + prompt: NonEmptyPrompt = Field(max_length=4000) + promptProvenance: PromptProvenance = "typed" + width: int = Field(default=1024, ge=IMAGE_MIN_SIDE, le=IMAGE_MAX_SIDE) + height: int = Field(default=1024, ge=IMAGE_MIN_SIDE, le=IMAGE_MAX_SIDE) + seed: int | None = None + + +class TextToImageParams(_TextToImageFields): + """Create-body params. An omitted provider resolves from the settings at create time.""" + + provider: ImageProvider | None = None + + +class TextToImageStoredParams(_TextToImageFields): + """Params stored on the row: the provider is always resolved, so a retry keeps it.""" + + provider: ImageProvider + + +class ImageGenerationStatusResponse(BaseModel): + """Which image providers can run now. A blocker is the code create would refuse with.""" + + model_config = ConfigDict(strict=True, extra="forbid") + defaultProvider: ImageProvider + localBlocker: ImageProviderBlocker | None + falBlocker: ImageProviderBlocker | None + + +class CreateTextToImageRequest(BaseModel): + model_config = ConfigDict(strict=True, extra="forbid") + params: TextToImageParams + contract_version: int = Field(default=1, ge=1) + + _UUID_PATTERN = r"^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$" @@ -2388,7 +2603,14 @@ class CreateImageToVideoRequest(BaseModel): contract_version: int = Field(default=1, ge=1) -class CreateAudioToVideoParams(BaseModel): +class CreateKeyframesRequest(BaseModel): + model_config = ConfigDict(strict=True, extra="forbid") + params: KeyframesParams + inputs: KeyframesInputs + contract_version: int = Field(default=1, ge=1) + + +class CreateAudioToVideoParams(NagParams): """Public non-media A2V inputs; the server derives inference frames from audio.""" model_config = ConfigDict(strict=True, extra="forbid") @@ -2399,9 +2621,9 @@ class CreateAudioToVideoParams(BaseModel): model: OfferingId fps: LTXVideoGenFps = 24 cameraMotion: VideoCameraMotion = "none" - negativePrompt: str = "" seed: int | None = None promptProvenance: PromptProvenance = "typed" + passShape: PassShape = "auto" class AudioToVideoParams(CreateAudioToVideoParams): @@ -2436,7 +2658,7 @@ class CreateAudioToVideoRequest(BaseModel): RETAKE_MAX_DURATION_SECONDS = 10.0 -class RetakeParams(BaseModel): +class RetakeParams(NagParams): """Queued Home/Remote retake. ``resolution`` omitted keeps the source size. Either way the picture is @@ -2481,7 +2703,7 @@ class CreateRetakeRequest(BaseModel): contract_version: int = Field(default=1, ge=1) -class ExtendParams(BaseModel): +class ExtendParams(NagParams): """Queued Home/Remote extend. ``resolution`` omitted keeps the source size. Either way the picture is @@ -2601,8 +2823,10 @@ class EditPreflightResolution(BaseModel): class EditPreflightCell(BaseModel): - """Verdict for one (candidate, duration) cell. ``message``/``code`` are None - when ``ok``; otherwise the exact refusal Generate would return.""" + """Verdict for one (candidate, duration) cell. ``ok`` means Generate would + enqueue it in the echoed mode. An ok cell admitted on a bet carries the bet + line as ``message``; a failing cell carries the exact refusal Generate + would return.""" model_config = ConfigDict(strict=True, extra="forbid") @@ -2611,14 +2835,14 @@ class EditPreflightCell(BaseModel): ok: bool message: str | None = None code: str | None = None - # Set on a failing cell the memory check could downgrade. Hard refusals - # (window math, unsupported) leave these empty, so a picker can tell them - # apart while ``ok`` stays false in both modes. + # The bet: admitted on an ok cell, refused on a failing one. Hard refusals + # (window math, unsupported) leave these empty. tier: JobRiskTier | None = None over_gib: float | None = None over_ram_gb: int | None = None shortfall_kind: ShortfallKind | None = None readout: BudgetReadout | None = None + estimated_seconds: int | None = None class EditPreflightResponse(BaseModel): @@ -2629,7 +2853,7 @@ class EditPreflightResponse(BaseModel): source: EditPreflightSource resolutions: list[EditPreflightResolution] cells: list[EditPreflightCell] - budgetMode: BudgetMode = "standard" + budgetMode: BudgetMode = "brave" class IcLoraPreflightRequest(BaseModel): @@ -2677,18 +2901,20 @@ class IcLoraPreflightSource(BaseModel): fps: float = Field(gt=0) -class IcLoraPreflightCell(BaseModel): - """Verdict for one duration. ``message``/``code`` are None when ``ok``; - otherwise the exact refusal Generate would return for this input.""" +class IcLoraPreflightVerdict(BaseModel): + """Verdict for one candidate. ``ok`` means Generate would enqueue it in the echoed mode. + + A failing cell carries the exact refusal Generate would return. An ok cell admitted on a + bet carries the bet (``tier`` and ``message``). + """ model_config = ConfigDict(strict=True, extra="forbid") - duration: float ok: bool message: str | None = None code: str | None = None - # Set on a failing cell the memory check could downgrade. Hard refusals - # leave these empty. ``ok`` stays false in both modes. + # The bet: admitted on an ok cell, refused on a failing one. Hard refusals + # leave these empty. tier: JobRiskTier | None = None over_gib: float | None = None over_ram_gb: int | None = None @@ -2696,6 +2922,13 @@ class IcLoraPreflightCell(BaseModel): readout: BudgetReadout | None = None +class IcLoraPreflightCell(IcLoraPreflightVerdict): + """Verdict for one duration. ``message``/``code`` are None when ``ok``; + otherwise the exact refusal Generate would return for this input.""" + + duration: float + + class IcLoraPreflightResponse(BaseModel): """Source dims + verdicts only; the input path is never echoed.""" @@ -2703,7 +2936,7 @@ class IcLoraPreflightResponse(BaseModel): source: IcLoraPreflightSource cells: list[IcLoraPreflightCell] - budgetMode: BudgetMode = "standard" + budgetMode: BudgetMode = "brave" # 1440p and 2160p run on AlphaGen only, behind the highResVideoToVideo feature flag. @@ -2712,7 +2945,61 @@ class IcLoraPreflightResponse(BaseModel): ] -class _IcLoraRecipeCore(BaseModel): +class IcLoraRecipeMemorySource(BaseModel): + """The picked clip: its file size and its frames at the output rate.""" + + model_config = ConfigDict(strict=True, extra="forbid") + + width: int = Field(gt=0, le=16384) + height: int = Field(gt=0, le=16384) + frames: int = Field(gt=0, le=10000) + + +class IcLoraRecipeMemoryRequest(BaseModel): + """Memory advice for a Home video recipe, before and after a clip is picked. + + ``cells`` are the output cells the form offers. Without ``source`` each is priced for a 16:9 + clip of that size. ``resolution`` is the selected cell, priced for ``source`` when given. + """ + + model_config = ConfigDict(strict=True, extra="forbid") + + model: OfferingId + resolution: IcLoraRecipeResolution + cells: list[IcLoraRecipeResolution] = Field(max_length=7) + audioMode: IcLoraAudioMode | None = None + scale: float | None = Field(default=None, ge=0.0, le=2.0) + source: IcLoraRecipeMemorySource | None = None + # The Advanced choices of the form, as in the create body. None is Auto. The advice then + # prices the same tiling the run uses. + tilingOverlap: float | None = Field(default=None, ge=MIN_TILE_OVERLAP, le=MAX_TILE_OVERLAP) + carryFrames: int | None = Field(default=None, ge=MIN_CARRY_FRAMES) + tilingSize: IcLoraTileSize | None = None + maxWindowFrames: int | None = Field(default=None, ge=MIN_WINDOW_FRAMES) + + +class IcLoraCellFit(BaseModel): + """How long a clip one output cell fits on this machine. + + ``max_frames`` is the longest clip, in frames at the output rate, whose job loads. 0 when none + does. ``full`` is a clip at the input cap. + """ + + resolution: IcLoraRecipeResolution + max_frames: int + full: bool + + +class IcLoraRecipeMemoryResponse(BaseModel): + memory: MemoryCapacity + # The longest clip a recipe takes, in frames. Every ``IcLoraCellFit`` is measured against it. + max_input_frames: int + cells: list[IcLoraCellFit] + # The selected cell for the picked clip. None without a source, or when the cell cannot run. + selected: JobMemoryAsk | None = None + + +class _IcLoraRecipeCore(NagParams): model_config = ConfigDict(strict=True, extra="forbid") prompt: str = "" @@ -2744,6 +3031,97 @@ class IcLoraVideoRecipeParams(IcLoraRecipeParams): # Only a recipe whose catalog entry has a control_type control takes it. Create fills the # catalog default when it is omitted, and refuses it for any other recipe. controlType: IcLoraControlType | None = None + # Advanced controls of a recipe whose catalog entry has a tile plan (Refine Details). A + # recipe without one refuses them. Omitted keeps the catalog tile overlap and the carry + # of the cell. + tilingOverlap: float | None = Field(default=None, ge=MIN_TILE_OVERLAP, le=MAX_TILE_OVERLAP) + carryFrames: int | None = Field(default=None, ge=MIN_CARRY_FRAMES) + tilingSize: IcLoraTileSize | None = None + maxWindowFrames: int | None = Field(default=None, ge=MIN_WINDOW_FRAMES) + + +IcLoraTilePreset: TypeAlias = Literal["standard", "large", "extra-large"] + + +class IcLoraTilePreflightRequest(BaseModel): + """Advisory verdict per tile size and per window for a recipe create. + + The body is the create body. Each requested tile size replaces its ``tilingSize``, each + requested maximum chunk length replaces its ``maxWindowFrames``, and each requested carry replaces its + ``carryFrames``. The other choice of the body stays. ``standard`` is the tile of the + catalog entry. An empty prompt is accepted here. Create still refuses one. The response + also gives the carry, window and tile the run uses when the body omits them. + """ + + model_config = ConfigDict(strict=True, extra="forbid") + + params: IcLoraVideoRecipeParams + inputs: IcLoraRecipeInputs + tileSizes: list[IcLoraTilePreset] = Field(default_factory=list[IcLoraTilePreset], max_length=3) + maxWindows: list[Annotated[int, Field(ge=MIN_WINDOW_FRAMES)]] = Field(default_factory=list[int], max_length=4) + # Carries to judge against the window the body holds. The form sends the shared preset list. + carries: list[Annotated[int, Field(ge=MIN_CARRY_FRAMES)]] = Field(default_factory=list[int], max_length=8) + + +class IcLoraTilePreflightCell(IcLoraPreflightVerdict): + tileSize: IcLoraTilePreset + + +class IcLoraMaxWindowPreflightCell(IcLoraPreflightVerdict): + maxWindowFrames: int + + +class IcLoraCarryPreflightCell(IcLoraPreflightVerdict): + carryFrames: int + + +class IcLoraAutoSinglePass(BaseModel): + """Auto runs the whole clip in one pass.""" + + model_config = ConfigDict(strict=True, extra="forbid") + + kind: Literal["single-pass"] = "single-pass" + + +class IcLoraAutoWindowed(BaseModel): + """Auto runs the clip in chunks of ``frames`` frames.""" + + model_config = ConfigDict(strict=True, extra="forbid") + + kind: Literal["windowed"] = "windowed" + frames: int = Field(gt=0) + + +IcLoraAutoChunking: TypeAlias = Annotated[ + IcLoraAutoSinglePass | IcLoraAutoWindowed, Field(discriminator="kind") +] + + +class IcLoraTilingDefaults(BaseModel): + """What Auto runs when the request omits a tiling control. + + ``carryFrames`` is the Auto carry. ``overlapFraction`` is the Auto tile overlap of the LoRA. + ``auto`` is the Auto chunk length, picked from the clip and the resolution. It is None when + Auto is refused: the cells carry the refusal. + """ + + model_config = ConfigDict(strict=True, extra="forbid") + + carryFrames: int + overlapFraction: float | None = None + auto: IcLoraAutoChunking | None = None + + +class IcLoraTilePreflightResponse(BaseModel): + """Verdicts only. The input is never echoed.""" + + model_config = ConfigDict(strict=True, extra="forbid") + + cells: list[IcLoraTilePreflightCell] + maxWindowCells: list[IcLoraMaxWindowPreflightCell] = Field(default_factory=list[IcLoraMaxWindowPreflightCell]) + carryCells: list[IcLoraCarryPreflightCell] = Field(default_factory=list[IcLoraCarryPreflightCell]) + defaults: IcLoraTilingDefaults + budgetMode: BudgetMode = "brave" class IcLoraRecipeStoredParams(_IcLoraRecipeCore): @@ -2759,6 +3137,11 @@ class IcLoraRecipeStoredParams(_IcLoraRecipeCore): audioMode: IcLoraAudioMode fps: float = Field(gt=0) loras: list[LoraEntry] = Field(default_factory=list[LoraEntry]) + # Advanced tiling controls of a recipe with a catalog tile plan. None keeps the plan. + tilingOverlap: float | None = Field(default=None, ge=MIN_TILE_OVERLAP, le=MAX_TILE_OVERLAP) + carryFrames: int | None = Field(default=None, ge=MIN_CARRY_FRAMES) + tilingSize: IcLoraTileSize | None = None + maxWindowFrames: int | None = Field(default=None, ge=MIN_WINDOW_FRAMES) @model_validator(mode="after") def _require_one_catalog_lora(self) -> "IcLoraRecipeStoredParams": diff --git a/backend/api_types_lora.py b/backend/api_types_lora.py new file mode 100644 index 000000000..98f66a799 --- /dev/null +++ b/backend/api_types_lora.py @@ -0,0 +1,269 @@ +"""Wire models for catalog LoRA downloads and user-supplied Custom LoRAs.""" + +from __future__ import annotations + +from typing import Annotated, Literal, TypeAlias, cast + +from pydantic import ( + BaseModel, + ConfigDict, + Field, + JsonValue, + SerializerFunctionWrapHandler, + StringConstraints, + model_serializer, + model_validator, +) + + +CustomLoraId: TypeAlias = Annotated[ + str, + StringConstraints(pattern=r"^[a-z0-9-]+$", max_length=64), +] + + +class LoraEntry(BaseModel): + model_config = ConfigDict(strict=True) + + ref: str + scale: float = Field(default=1.0, ge=0.0, le=4.0) + # Catalog id when this LoRA was picked from the library, so automatic enhancement can look + # up its trigger/instructions. Absent for a custom LoRA the user supplied themselves, which + # stays weights-only — the weights' filename is never matched against the catalog. + catalogId: str | None = None + # Catalog name at enqueue time. Kept after the LoRA leaves the catalog so + # the dashboard can still label the run. + displayName: str | None = None + # Checkpoint chosen at enqueue, next to scale, so a later variant can be told apart. + variantId: str | None = None + # Id of the user's saved custom LoRA. Lets a client select it again when it reopens the run. + # The weights stay in ``ref``; a custom LoRA is never matched against the catalog. + customLoraId: CustomLoraId | None = None + + @model_serializer(mode="wrap") + def _omit_unset_optional_ids( + self, handler: SerializerFunctionWrapHandler + ) -> dict[str, JsonValue]: + data = cast("dict[str, JsonValue]", handler(self)) + for key in ("variantId", "customLoraId"): + if data.get(key) is None: + data.pop(key, None) + return data + + +class IcLoraDownloadRequest(BaseModel): + model_config = ConfigDict(strict=True) + ic_lora_id: str + # Optional catalog download.variants[].id; omit to download the default filename. + variant_id: str | None = None + # Dev escape hatch: attach the in-app HuggingFace token even when HF gating is off + # (gated IC-LoRA repos need auth; gating is normally env-driven in packaged builds). + use_hf_auth: bool = False + + +class IcLoraDeleteRequest(BaseModel): + model_config = ConfigDict(strict=True) + ic_lora_id: str + variant_id: str | None = None + + +# Shared start-response for both catalog download kinds (IC-LoRA + plain LoRA). +class CatalogDownloadStartResponse(BaseModel): + model_config = ConfigDict(strict=True) + status: str + sessionId: str + + +CatalogDownloadStatus: TypeAlias = Literal["downloading", "complete", "error"] + + +class IcLoraDownloadProgressResponse(BaseModel): + model_config = ConfigDict(strict=True) + status: CatalogDownloadStatus + ic_lora_id: str | None = None + downloaded_bytes: int = 0 + expected_bytes: int = 0 + progress: float = 0.0 + speed_bytes_per_sec: float = 0.0 + error: str | None = None + + +class LoraDownloadRequest(BaseModel): + model_config = ConfigDict(strict=True) + lora_id: str + # Optional catalog download.variants[].id; omit to download the default filename. + variant_id: str | None = None + use_hf_auth: bool = False + + +class LoraDeleteRequest(BaseModel): + model_config = ConfigDict(strict=True) + lora_id: str + variant_id: str | None = None + + +class LoraDownloadProgressResponse(BaseModel): + model_config = ConfigDict(strict=True) + status: CatalogDownloadStatus + lora_id: str | None = None + downloaded_bytes: int = 0 + expected_bytes: int = 0 + progress: float = 0.0 + speed_bytes_per_sec: float = 0.0 + error: str | None = None + + +class ActiveLoraDownloadResponse(BaseModel): + model_config = ConfigDict(strict=True) + # The currently-running plain-LoRA download session. Nulls when idle. + session_id: str | None + lora_id: str | None + # 0–99 while downloading so a remount can seed the progress label instead of flashing 0%. + progress: float | None = None + + +class ActiveIcLoraDownloadResponse(BaseModel): + model_config = ConfigDict(strict=True) + # The currently-running IC-LoRA download session. Nulls when idle. + session_id: str | None + ic_lora_id: str | None + progress: float | None = None + + +# --- Custom LoRA (user-supplied weights: a local file or a URL) --- +CustomLoraSource: TypeAlias = Literal["file", "url"] + +# What the user tells the prompt enhancer about their LoRA. The text goes into the enhancer's +# system prompt, so each part has a cap. +CUSTOM_LORA_TRIGGER_MAX = 80 +CUSTOM_LORA_DESCRIPTION_MAX = 600 +CUSTOM_LORA_EXAMPLE_MAX = 1000 +CUSTOM_LORA_EXAMPLES_MAX = 3 + +# A trigger is one line: it is quoted inside the enhancer's system prompt. +CustomLoraTrigger: TypeAlias = Annotated[ + str, + StringConstraints( + strip_whitespace=True, + min_length=1, + max_length=CUSTOM_LORA_TRIGGER_MAX, + pattern=r"^[^\r\n]+$", + ), +] +CustomLoraDescription: TypeAlias = Annotated[ + str, + StringConstraints(strip_whitespace=True, min_length=1, max_length=CUSTOM_LORA_DESCRIPTION_MAX), +] +CustomLoraExample: TypeAlias = Annotated[ + str, + StringConstraints(strip_whitespace=True, min_length=1, max_length=CUSTOM_LORA_EXAMPLE_MAX), +] + + +class CustomLoraItem(BaseModel): + """One saved custom LoRA. + + The desktop list puts the cover file path in ``cover_url``. The phone list replaces that + path with a signed URL, so a paired phone never receives a filesystem path. + """ + + model_config = ConfigDict(strict=True) + id: str + name: str + size_bytes: int + source: CustomLoraSource + # False after the user deleted the weights. The LoRA stays listed and needs the weights again. + downloaded: bool + # True when the weights can be fetched again from the saved link. + can_download: bool + # The Hugging Face model page, for a LoRA added from a Hugging Face link. Else `None`. + page_url: str | None = None + # What the user told the prompt enhancer. A LoRA saved before this existed has no description. + trigger: str | None = None + description: str = "" + examples: list[str] = Field(default_factory=list[str]) + # The cover picture. On this computer it is the file path. On a paired phone the list + # route replaces that path with a signed URL. `None` when the LoRA has no cover. + cover_url: str | None = None + + +class CustomLoraListResponse(BaseModel): + model_config = ConfigDict(strict=True) + loras: list[CustomLoraItem] + + +class CustomLoraImportRequest(BaseModel): + """Add a custom LoRA from exactly one source: a local file path or a URL.""" + + model_config = ConfigDict(strict=True, extra="forbid") + name: Annotated[str, StringConstraints(strip_whitespace=True, min_length=1, max_length=60)] + source_path: str | None = Field(default=None, min_length=1) + url: str | None = Field(default=None, min_length=1, max_length=2048) + # What the LoRA does. Without it the prompt enhancer gives the LoRA a generic rewrite. + description: CustomLoraDescription | None = None + # A word the prompt must contain for the LoRA to work. Many LoRAs have none. + trigger: CustomLoraTrigger | None = None + # Prompts that work well with this LoRA. The enhancer copies their style, not their wording. + examples: list[CustomLoraExample] = Field( + default_factory=list[CustomLoraExample], max_length=CUSTOM_LORA_EXAMPLES_MAX + ) + # A picture for the LoRA's card. Left out when the user skips the cover. + cover_path: str | None = Field(default=None, min_length=1) + + @model_validator(mode="after") + def _require_one_source(self) -> "CustomLoraImportRequest": + if (self.source_path is None) == (self.url is None): + raise ValueError("Give either source_path or url, not both") + return self + + +class CustomLoraLinkInfoRequest(BaseModel): + """Check whether a URL is an accepted Custom LoRA link and read its Hugging Face model card.""" + + model_config = ConfigDict(strict=True, extra="forbid") + url: str = Field(min_length=1, max_length=2048) + + +class CustomLoraLinkInfoResponse(BaseModel): + """Link validity and suggestions from a model card. The user checks and edits them. Nothing is saved.""" + + model_config = ConfigDict(strict=True) + accepted: bool = False + trigger: str | None = None + description: str = "" + examples: list[str] = Field(default_factory=list[str]) + + +class CustomLoraRestoreRequest(BaseModel): + """Put the weights of a saved LoRA back. A `source_path` copies that file. Without it, the + weights are fetched again from the saved link.""" + + model_config = ConfigDict(strict=True, extra="forbid") + source_path: str | None = Field(default=None, min_length=1) + + +class CustomLoraImportStartResponse(BaseModel): + model_config = ConfigDict(strict=True) + status: str + sessionId: str + # The id the LoRA has once the import completes, so the client can select it. + custom_lora_id: str + + +class CustomLoraImportProgressResponse(BaseModel): + model_config = ConfigDict(strict=True) + status: CatalogDownloadStatus + custom_lora_id: str | None = None + downloaded_bytes: int = 0 + expected_bytes: int = 0 + progress: float = 0.0 + speed_bytes_per_sec: float = 0.0 + error: str | None = None + + +class ActiveCustomLoraImportResponse(BaseModel): + model_config = ConfigDict(strict=True) + # The running import session. Nulls when idle. + session_id: str | None + custom_lora_id: str | None + progress: float | None = None diff --git a/backend/app_factory.py b/backend/app_factory.py index a71862d83..a70c3e8ea 100644 --- a/backend/app_factory.py +++ b/backend/app_factory.py @@ -20,7 +20,9 @@ from _routes.health import router as health_router from _routes.ic_lora import router as ic_lora_router from _routes.lora_catalog import router as lora_catalog_router +from _routes.custom_lora import router as custom_lora_router from _routes.image_gen import router as image_gen_router +from _routes.image_gen import status_router as image_status_router from _routes.prompt_enhancement import router as prompt_enhancement_router from _routes.models import router as models_router from _routes.suggest_gap_prompt import router as suggest_gap_prompt_router @@ -34,6 +36,7 @@ from _routes.runtime_policy import router as runtime_policy_router from _routes.feature_flags import router as feature_flags_router from _routes.settings import router as settings_router +from _routes.ui_preferences import router as ui_preferences_router from _routes.remote import router as remote_status_router from api_types import HTTPErrorResponse from http_exception_handlers import install_http_exception_handlers @@ -147,6 +150,7 @@ def _token_matches(candidate: str) -> bool: app.include_router(models_router) app.include_router(settings_router) app.include_router(image_gen_router) + app.include_router(image_status_router) app.include_router(suggest_gap_prompt_router) app.include_router(assistant_router) app.include_router(retake_router) @@ -157,9 +161,11 @@ def _token_matches(candidate: str) -> bool: app.include_router(generation_seed_router) app.include_router(ic_lora_router) app.include_router(lora_catalog_router) + app.include_router(custom_lora_router) app.include_router(prompt_enhancement_router) app.include_router(runtime_policy_router) app.include_router(feature_flags_router) + app.include_router(ui_preferences_router) app.include_router(hf_auth_router) app.include_router(remote_status_router) diff --git a/backend/app_handler.py b/backend/app_handler.py index f2b1ff1a9..8c5b723ff 100644 --- a/backend/app_handler.py +++ b/backend/app_handler.py @@ -7,8 +7,8 @@ import os import threading from collections.abc import AsyncIterator, Mapping -from contextlib import asynccontextmanager -from dataclasses import dataclass +from contextlib import AbstractContextManager, asynccontextmanager +from dataclasses import dataclass, replace from pathlib import Path from api_types import LTXLocalModelId @@ -24,6 +24,7 @@ ModelsHandler, PipelinesHandler, LoraCatalogHandler, + CustomLoraHandler, PromptEnhancementHandler, SuggestGapPromptHandler, RetakeHandler, @@ -34,8 +35,10 @@ TextHandler, VideoGenerationHandler, ) +from handlers.calibration_handler import CalibrationHandler from handlers.dashboard_handler import DashboardHandler from handlers.queued_generation_handler import QueuedGenerationHandler +from handlers.queued_image_handler import QueuedImageHandler from runtime_config.offerings import OFFERING_IDS, resolve_offering_local_model_id from handlers.assistant_handler import AssistantHandler from services.assistant_provider import AssistantProvider, DesktopAssistantProvider @@ -63,29 +66,45 @@ TextEncoder, VideoProcessor, ) +from services.url_downloader import UrlDownloader from services.analytics import AnalyticsService, QueuedEnhancement from services.lora_catalog import LoraCatalogProvider from services.store import Store -from services.records import GenerationRecord, UnavailableError +from services.records import LOCAL_LANE, GenerationRecord, UnavailableError from services.unavailable_store import UnavailableStore from services.generation_queue.registry import ExecutorRegistry +from services.generation_queue.dispatcher import QueueDispatcher +from services.generation_queue.lane_sessions import LaneJobSession +from services.generation_queue.lane_slots import CountingLaneSlot +from services.generation_queue.lanes import FAL_LANE_SPEC, LOCAL_LANE_SPEC, LaneRegistry, LaneSpec from services.generation_queue.runner import QueueRunner +from services.generation_queue.sessions import LocalJobSession from services.features.video import ( AUDIO_TO_VIDEO_FEATURE, + CUSTOM_LORA_FEATURE, EXTEND_FEATURE, FEATURE as TEXT_TO_VIDEO_FEATURE, IMAGE_TO_VIDEO_FEATURE, + KEYFRAMES_FEATURE, RETAKE_FEATURE, SYNTHESIZED_IC_LORA_EXECUTORS, AudioToVideoExecutor, + CustomLoraExecutor, IcLoraRecipeExecutor, ExtendExecutor, ImageToVideoExecutor, + KeyframesExecutor, RebindableAssetResolver, RetakeExecutor, TextToVideoExecutor, ) +from services.features.custom_loras import ( + custom_lora_in_use, + make_custom_lora_resolver, +) from services.features.ic_lora_recipes import queued_ic_lora_recipes +from services.features.image.feature_id import FEATURE as TEXT_TO_IMAGE_FEATURE +from services.features.image.text_to_image import TextToImageExecutor from services.features.lora_recipes import ( i2v_lora_recipes, make_recipe_lora_resolver, @@ -128,6 +147,7 @@ def __init__( generation_executors: Mapping[str, GenerationExecutor] | None = None, assistant_provider: AssistantProvider | None = None, assistant_models: LocalAssistantModels | None = None, + url_downloader: UrlDownloader | None = None, ) -> None: self.config = config @@ -211,7 +231,6 @@ def __init__( task_runner=task_runner, config=config, gpu_info=gpu_info, - high_res_enabled=self._high_res_video_to_video_enabled, ) self.text = TextHandler( @@ -237,7 +256,12 @@ def __init__( gpu_info=gpu_info, ) - self.generation = GenerationHandler(state=self.state, lock=self._lock, config=config) + self.calibration = CalibrationHandler( + state=self.state, lock=self._lock, config=config, gpu_info=gpu_info + ) + self.generation = GenerationHandler( + state=self.state, lock=self._lock, config=config, calibration=self.calibration + ) self.assistant_models = AssistantModelsHandler( state=self.state, lock=self._lock, models=local_assistant_models, task_runner=task_runner, generation=self.generation, @@ -293,6 +317,16 @@ async def assistant_gpu_session() -> AsyncIterator[None]: gpu_info=gpu_info, ) + self._store: Store = store + self.custom_loras = CustomLoraHandler( + state=self.state, + lock=self._lock, + task_runner=task_runner, + config=config, + url_downloader=url_downloader, + # Resolved at call time: `_store` is rebound when the store is replaced. + lora_in_use=lambda custom_lora_id: custom_lora_in_use(self._store, custom_lora_id), + ) self._lora_catalog_provider = lora_catalog_provider self.ic_lora = IcLoraHandler( state=self.state, @@ -307,15 +341,43 @@ async def assistant_gpu_session() -> AsyncIterator[None]: gpu_info=gpu_info, high_res_enabled=self._high_res_video_to_video_enabled, ) + self.image_generation = ImageGenerationHandler( + state=self.state, + lock=self._lock, + generation_handler=self.generation, + pipelines_handler=self.pipelines, + config=config, + zit_api_client=zit_api_client, + ) + self.queued_image = QueuedImageHandler( + state=self.state, + lock=self._lock, + generation_handler=self.generation, + pipelines_handler=self.pipelines, + config=config, + zit_api_client=zit_api_client, + prompt_enhancement_handler=self.prompt_enhancement, + lease_idle_gpu=self._lease_idle_gpu, + ) + self._queued_asset_resolver: RebindableAssetResolver | None = None + # The provider cancel of the fal lane needs the fal client, so its spec is built here. + fal_lane = replace(FAL_LANE_SPEC, cancel_orphan=self.queued_image.cancel_fal_request) + self._lanes = LaneRegistry( + [LOCAL_LANE_SPEC, fal_lane] if config.parallel_queue_lanes else [LOCAL_LANE_SPEC] + ) if generation_executors is None: self._queued_asset_resolver = RebindableAssetResolver(store) executors: dict[str, GenerationExecutor] = { + TEXT_TO_IMAGE_FEATURE: TextToImageExecutor(self.queued_image), TEXT_TO_VIDEO_FEATURE: TextToVideoExecutor(self.video_generation), IMAGE_TO_VIDEO_FEATURE: ImageToVideoExecutor( self.video_generation, self._queued_asset_resolver ), } + executors[KEYFRAMES_FEATURE] = KeyframesExecutor( + self.video_generation, self._queued_asset_resolver + ) # Each t2v LoRA recipe reuses the text-to-video executor, keyed on its # Explore id, with its scaffold applied post-enhance. i2v recipes reuse # the image-to-video executor the same way (start frame + LoRA). @@ -340,6 +402,21 @@ async def assistant_gpu_session() -> AsyncIterator[None]: models_dir=lambda: self.video_generation.models_dir, ), ) + # A custom LoRA is one feature for both forms. The row's inputs pick the executor. + custom_lora_resolver = make_custom_lora_resolver( + lambda: self.video_generation.models_dir + ) + executors[CUSTOM_LORA_FEATURE] = CustomLoraExecutor( + TextToVideoExecutor( + self.video_generation, + lora_resolver=custom_lora_resolver, + ), + ImageToVideoExecutor( + self.video_generation, + self._queued_asset_resolver, + lora_resolver=custom_lora_resolver, + ), + ) executors[AUDIO_TO_VIDEO_FEATURE] = AudioToVideoExecutor( self.video_generation, self._queued_asset_resolver ) @@ -351,6 +428,7 @@ async def assistant_gpu_session() -> AsyncIterator[None]: config.default_negative_prompt, self.generation, self.prompt_enhancement, + default_nag_scale=lambda: self.settings.get_settings_snapshot().nag_scale, ) executors[EXTEND_FEATURE] = ExtendExecutor( self.pipelines, @@ -360,6 +438,7 @@ async def assistant_gpu_session() -> AsyncIterator[None]: config.default_negative_prompt, self.generation, self.prompt_enhancement, + default_nag_scale=lambda: self.settings.get_settings_snapshot().nag_scale, ) for recipe in queued_ic_lora_recipes(): if recipe.kind != "video": @@ -379,20 +458,11 @@ async def assistant_gpu_session() -> AsyncIterator[None]: upscales_to_cell=recipe.upscales_to_cell, high_res_enabled=self._high_res_video_to_video_enabled, ) - self.executor_registry = ExecutorRegistry(executors) + self.executor_registry = ExecutorRegistry(executors, self._lanes) else: - self.executor_registry = ExecutorRegistry(generation_executors) + self.executor_registry = ExecutorRegistry(generation_executors, self._lanes) self._bind_store(store) - self.image_generation = ImageGenerationHandler( - state=self.state, - lock=self._lock, - generation_handler=self.generation, - pipelines_handler=self.pipelines, - config=config, - zit_api_client=zit_api_client, - ) - self.health = HealthHandler( state=self.state, lock=self._lock, @@ -451,6 +521,7 @@ def load_persistent_state(self, default_settings: AppSettings) -> None: exc_info=True, ) self._bind_store(UnavailableStore()) + self.calibration.load() def _queued_local_model_id(self, generation: GenerationRecord) -> LTXLocalModelId | None: """The checkpoint this queued job will encode with, not the active model.""" @@ -465,31 +536,68 @@ def _queued_local_model_id(self, generation: GenerationRecord) -> LTXLocalModelI def _queued_enhancement_policy(self, generation: GenerationRecord) -> QueuedEnhancement: settings = self.state.app_settings model_id = self._queued_local_model_id(generation) + # An image rewrite has its own rule (no local Gemma when API-only), kept in one place. + local_enhancer_root = ( + self.prompt_enhancement.local_image_enhancer_root() + if generation.feature == TEXT_TO_IMAGE_FEATURE + else self.text.resolve_prompt_enhancer_root_if_downloaded(model_id) + ) return QueuedEnhancement( explore_auto_enhance_prompts=settings.explore_auto_enhance_prompts, prompt_enhancer_enabled=settings.prompt_enhancer_enabled, use_local_encoding=self.text.should_use_local_encoding(model_id), - local_enhancer_available=( - self.text.resolve_prompt_enhancer_root_if_downloaded(model_id) is not None - ), + local_enhancer_available=local_enhancer_root is not None, gemini_video_enhance=self.prompt_enhancement.gemini_video_enhance_enabled(), ) def _high_res_video_to_video_enabled(self) -> bool: return self.feature_flags.get_flags().highResVideoToVideo - def _bind_store(self, store: Store) -> None: - if self._queued_asset_resolver is not None: - self._queued_asset_resolver.bind(store) - self.generation_queue = QueueRunner( + def _keyframes_enabled(self) -> bool: + return self.feature_flags.get_flags().keyframes + + def _lane_runner(self, store: Store, lane: LaneSpec) -> QueueRunner: + if lane.id == LOCAL_LANE: + return QueueRunner( + db=store, + generation=self.generation, + executors=self.executor_registry, + lane=lane, + session_factory=lambda job: LocalJobSession(self.generation, job.id), + analytics=self.analytics, + enhancement_policy=self._queued_enhancement_policy, + gpu_info=self.gpu_info, + checkpoint_drive_type=self.config.checkpoint_drive_type, + ) + return QueueRunner( db=store, - generation=self.generation, + generation=CountingLaneSlot(lane.concurrency), executors=self.executor_registry, + lane=lane, + session_factory=lambda job: LaneJobSession( + job.id, job.attempt_count, store.set_provider_job_id + ), analytics=self.analytics, enhancement_policy=self._queued_enhancement_policy, gpu_info=self.gpu_info, checkpoint_drive_type=self.config.checkpoint_drive_type, ) + + def _lease_idle_gpu(self) -> AbstractContextManager[bool]: + """The GPU for a short job of another lane, only when the local lane is idle.""" + return self.generation.try_lease_idle_gpu( + local_lane_idle=lambda: self.generation_queue.lane_is_idle(LOCAL_LANE) + ) + + def _bind_store(self, store: Store) -> None: + self._store = store + self.calibration.bind(store) + if self._queued_asset_resolver is not None: + self._queued_asset_resolver.bind(store) + self.generation_queue = QueueDispatcher( + [self._lane_runner(store, lane) for lane in self._lanes.lanes], + checkpoint_drive_type=self.config.checkpoint_drive_type, + ) self.assets = AssetHandler( store=store, ) @@ -498,7 +606,6 @@ def _bind_store(self, store: Store) -> None: executor_registry=self.executor_registry, derive_local_a2v=self.video_generation.derive_local_a2v_params, queue_control=self.generation_queue, - progress_reader=self.generation.get_generation_progress, config=self.config, lora_catalog_provider=self._lora_catalog_provider, state=self.state, @@ -508,8 +615,12 @@ def _bind_store(self, store: Store) -> None: preflight_queued_edit=self.pipelines.preflight_queued_edit_job, preflight_edit_matrix=self.pipelines.preflight_edit_matrix, preflight_queued_ic_lora_recipe=self.ic_lora.preflight_queued_recipe_job, + preflight_ic_lora_tile_sizes=self.ic_lora.preflight_recipe_tile_sizes, preflight_queued_synthesized_ic_lora=self.ic_lora.preflight_queued_synthesized_job, high_res_enabled=self._high_res_video_to_video_enabled, + keyframes_enabled=self._keyframes_enabled, + should_use_local_encoding=self.text.should_use_local_encoding, + image_generation_status=self.image_generation.get_status, ) self.assistant = AssistantHandler( state=self.state, lock=self._lock, provider=self._assistant_provider, store=store, @@ -552,6 +663,8 @@ class ServiceBundle: generation_executors: Mapping[str, GenerationExecutor] | None = None assistant_provider: AssistantProvider | None = None assistant_models: LocalAssistantModels | None = None + # None leaves URL import off. The real bundle supplies the downloader. + url_downloader: UrlDownloader | None = None def build_default_service_bundle(config: RuntimeConfig) -> ServiceBundle: @@ -571,6 +684,7 @@ def build_default_service_bundle(config: RuntimeConfig) -> ServiceBundle: from services.prompt_enhancer_pipeline.ltx_prompt_enhancer_pipeline import LtxPromptEnhancerPipeline from services.pose_processor_pipeline.dw_pose_pipeline import DWPosePipeline from services.task_runner.threading_runner import ThreadingRunner + from services.url_downloader.url_downloader_impl import UrlDownloaderImpl from services.text_encoder.ltx_text_encoder import LTXTextEncoder from services.video_processor.video_processor_impl import VideoProcessorImpl from services.lora_catalog import FileLoraCatalogProvider @@ -602,15 +716,16 @@ def build_default_service_bundle(config: RuntimeConfig) -> ServiceBundle: a2v_pipeline_class=LTXa2vPipeline, retake_pipeline_class=LTXRetakePipeline, prompt_enhancer_pipeline_class=LtxPromptEnhancerPipeline, - store=open_store(config.app_data_dir), + store=open_store(config.app_data_dir, config.assets_dir), + url_downloader=UrlDownloaderImpl(), ) -def open_store(app_data_dir: Path) -> Store: +def open_store(app_data_dir: Path, assets_dir: Path | None = None) -> Store: from services.sqlite_store import SqliteStore try: - return SqliteStore(app_data_dir) + return SqliteStore(app_data_dir, assets_dir=assets_dir) except UnavailableError: logger.warning( "Store unavailable at %s", app_data_dir / "store.sqlite3", exc_info=True @@ -650,4 +765,5 @@ def build_initial_state( generation_executors=bundle.generation_executors, assistant_provider=bundle.assistant_provider, assistant_models=bundle.assistant_models, + url_downloader=bundle.url_downloader, ) diff --git a/backend/handlers/__init__.py b/backend/handlers/__init__.py index 053aebafe..6743175a3 100644 --- a/backend/handlers/__init__.py +++ b/backend/handlers/__init__.py @@ -10,6 +10,7 @@ from handlers.models_handler import ModelsHandler from handlers.pipelines_handler import PipelinesHandler from handlers.lora_catalog_handler import LoraCatalogHandler +from handlers.custom_lora_handler import CustomLoraHandler from handlers.prompt_enhancement_handler import PromptEnhancementHandler from handlers.suggest_gap_prompt_handler import SuggestGapPromptHandler from handlers.retake_handler import RetakeHandler @@ -39,6 +40,7 @@ "IcLoraHandler", "HuggingFaceAuthHandler", "LoraCatalogHandler", + "CustomLoraHandler", "PromptEnhancementHandler", "AssetHandler", "QueuedGenerationHandler", diff --git a/backend/handlers/assistant_params.py b/backend/handlers/assistant_params.py index baadbfdc1..6642493ec 100644 --- a/backend/handlers/assistant_params.py +++ b/backend/handlers/assistant_params.py @@ -68,6 +68,7 @@ class AudioParams(AssistantParams): class ExtensionParams(AssistantParams): prompt: str = "" + negativePrompt: str = "" model: OfferingId # Two names because "duration" means clip length in every other tool. added_seconds: float | None = Field(default=None, ge=2, le=20, allow_inf_nan=False, description='"Add 3 seconds"') @@ -79,6 +80,7 @@ class ExtensionParams(AssistantParams): class VideoRecipeParams(AssistantParams): model: OfferingId prompt: str = "" + negativePrompt: str = "" resolution: IcLoraRecipeResolution = Field(default="720p", description="720p unless the user asks; lower is much faster") # Omitted keeps the source rate; a faster rate than the source is refused. fps: float | None = Field(default=None, gt=0, allow_inf_nan=False) @@ -96,6 +98,7 @@ class VideoRecipeParams(AssistantParams): class IngredientsParams(AssistantParams): model: OfferingId prompt: NonEmptyPrompt + negativePrompt: str = "" resolution: IngredientsResolution = Field(default="720p", description="720p unless the user asks; lower is much faster") duration: IngredientsDuration = 5 aspectRatio: LTXVideoGenAspectRatio = "16:9" @@ -103,6 +106,7 @@ class IngredientsParams(AssistantParams): class ReplacementParams(AssistantParams): prompt: str = "" + negativePrompt: str = "" model: OfferingId startTime: float = Field(ge=0, allow_inf_nan=False) duration: float = Field(ge=2, le=RETAKE_MAX_DURATION_SECONDS, allow_inf_nan=False) diff --git a/backend/handlers/base.py b/backend/handlers/base.py index 56c892fe3..fdb418e4e 100644 --- a/backend/handlers/base.py +++ b/backend/handlers/base.py @@ -12,14 +12,18 @@ from _routes._errors import HTTPError from runtime_config.model_download_specs import resolve_active_ltx_model_id -from runtime_config.runtime_policy import streaming_prefetch_count_for_mode +from runtime_config.runtime_policy import ( + CUDA_CPU_OFFLOAD_RAM_FLOOR_GB, + streaming_prefetch_count_for_mode, +) from runtime_config.video_job_budget import ( LOCAL_GENERATION_UNSUPPORTED, LOCAL_GENERATION_UNSUPPORTED_MESSAGE, build_local_job_filter, + resolve_pass_shape, ) from services.ltx_pipeline_common import offload_mode_for_prefetch_count -from state.app_settings import MAX_GENERATION_SEED +from state.app_settings import MAX_GENERATION_SEED, resolved_use_conv_vae from state.app_state_types import AppState if TYPE_CHECKING: @@ -27,6 +31,7 @@ from api_types import LTXLocalModelId from runtime_config.runtime_config import RuntimeConfig + from runtime_config.reject_reasons import PassShape from runtime_config.runtime_policy import LocalGenerationMode from runtime_config.video_job_budget import LocalJobFilter from services.gpu_info.gpu_info import GpuInfo @@ -95,28 +100,45 @@ def _local_job_filter( *, model_id: LTXLocalModelId | None = None, total_only: bool = False, + pass_shape: PassShape | None = None, ) -> LocalJobFilter: """Profile + budget for this request. Built once per public method so free VRAM and the MPS pool are sampled a single time per request, - never per check. Single source for every budget gate.""" + never per check. Single source for every budget gate. + + ``pass_shape=None`` follows the live "Never split" setting; a queued job + passes the shape it resolved at create.""" + with self._lock: + settings = self.state.app_settings + calibration = self.state.device_calibration + if pass_shape is None: + pass_shape = resolve_pass_shape( + "auto", never_split=settings.never_split_into_parts + ) return build_local_job_filter( self.config, model_id=( model_id if model_id is not None else resolve_active_ltx_model_id( - self.models_dir, self.state.app_settings.active_ltx_model_id + self.models_dir, settings.active_ltx_model_id ) ), free_vram_bytes=self._gpu.get_free_cuda_vram_bytes(), mps_pool_bytes=self._gpu.get_mps_pool_bytes(), total_only=total_only, - # Lock-free like active_ltx_model_id above: a str attribute read - # is atomic, and settings are replaced wholesale, never mutated. - budget_mode=self.state.app_settings.budget_mode, + budget_mode=settings.budget_mode, + calibration=calibration, + pass_shape=pass_shape, + conv_vae=resolved_use_conv_vae(settings, system=self.config.system), ) - def _offload_mode(self, load_mode: LocalGenerationMode) -> OffloadMode: + def _offload_mode( + self, + load_mode: LocalGenerationMode, + *, + cpu_ram_floor_gb: int | None = CUDA_CPU_OFFLOAD_RAM_FLOOR_GB, + ) -> OffloadMode: """Weight-streaming kind for a pipeline load. Computed once per load from frozen config facts; pipelines take the verdict, never the raw triple.""" return offload_mode_for_prefetch_count( @@ -125,6 +147,7 @@ def _offload_mode(self, load_mode: LocalGenerationMode) -> OffloadMode: drive_type=self.config.checkpoint_drive_type, system=self.config.system, ram_bytes=self.config.total_ram_bytes, + cpu_ram_floor_gb=cpu_ram_floor_gb, ) def _require_local_generation_possible(self, *, api_key: str | None = None) -> None: diff --git a/backend/handlers/calibration_handler.py b/backend/handlers/calibration_handler.py new file mode 100644 index 000000000..83e74e4ee --- /dev/null +++ b/backend/handlers/calibration_handler.py @@ -0,0 +1,144 @@ +"""Device calibration: watch a local GPU run's memory and record it when it ran clean.""" + +from __future__ import annotations + +import logging +from threading import RLock +from typing import TYPE_CHECKING + +from handlers.base import StateHandlerBase +from runtime_config.device_calibration import ( + CALIBRATION_EPOCH, + CleanVerdict, + DeviceCalibration, + DeviceIdentity, + FrontierPoint, + JobEnvelope, + RunMemoryBaseline, + RunMemoryEnd, + clean_run_verdict, + peak_growth_bytes, +) +from services.records import UnavailableError +from services.store import CalibrationStore +from services.unavailable_store import UnavailableStore +from state.app_state_types import AppState + +if TYPE_CHECKING: + from runtime_config.runtime_config import RuntimeConfig + from services.gpu_info.gpu_info import GpuInfo + +logger = logging.getLogger(__name__) + + +def device_identity(config: RuntimeConfig) -> DeviceIdentity | None: + """None when the GPU name or total memory is unknown: nothing is loaded or recorded.""" + match config.system: + case "Darwin": + total = config.total_ram_bytes + case "Windows" | "Linux": + total = config.vram_bytes + case _: + return None + if not config.gpu_device_name or total is None or total <= 0: + return None + return DeviceIdentity( + system=config.system, gpu_model=config.gpu_device_name, total_memory_bytes=total + ) + + +class CalibrationHandler(StateHandlerBase): + def __init__( + self, *, state: AppState, lock: RLock, config: RuntimeConfig, gpu_info: GpuInfo + ) -> None: + super().__init__(state, lock, config, gpu_info=gpu_info) + self._store: CalibrationStore = UnavailableStore() + + def bind(self, store: CalibrationStore) -> None: + self._store = store + + def load(self) -> None: + identity = device_identity(self.config) + if identity is None: + return + try: + frontier = self._store.load_device_frontier(identity, CALIBRATION_EPOCH) + machine_factor = self._store.load_device_machine_factor(identity, CALIBRATION_EPOCH) + except UnavailableError: + logger.warning("[calibration] frontier load failed; lab tables only", exc_info=True) + return + with self._lock: + self.state.device_calibration = DeviceCalibration( + identity=identity, frontier=frontier, machine_factor=machine_factor + ) + + def open_run(self) -> RunMemoryBaseline | None: + if device_identity(self.config) is None: + return None + return self._gpu.begin_run_memory_watch() + + def close_run(self) -> RunMemoryEnd: + return self._gpu.end_run_memory_watch() + + def record_if_clean( + self, + ran: JobEnvelope, + baseline: RunMemoryBaseline, + end: RunMemoryEnd, + *, + generation_id: str, + wall_s: float | None = None, + conv_vae: bool = False, + ) -> CleanVerdict: + """Widen the frontier with a clean run. Never raises: a lost record keeps the old warning.""" + identity = device_identity(self.config) + if identity is None: + return "no_evidence" + verdict = clean_run_verdict(identity, baseline, end) + if verdict != "clean": + logger.info("[calibration] %s not recorded: %s", generation_id, verdict) + return verdict + try: + points = self._store.widen_device_frontier( + identity, + CALIBRATION_EPOCH, + ran.bucket, + FrontierPoint( + point=ran.point, + peak_growth_bytes=peak_growth_bytes(baseline, end), + wall_s=wall_s, + ), + priced_gib=ran.priced_gib, + generation_id=generation_id, + conv_vae=conv_vae, + ) + except UnavailableError: + logger.warning("[calibration] %s record failed", generation_id, exc_info=True) + return verdict + # A failed refresh must not hide a frontier point that is already stored. + try: + machine_factor = self._store.load_device_machine_factor(identity, CALIBRATION_EPOCH) + except UnavailableError: + logger.warning( + "[calibration] %s machine factor refresh failed", generation_id, exc_info=True + ) + machine_factor = None + with self._lock: + if points is not None: + self.state.device_calibration = self.state.device_calibration.with_frontier( + ran.bucket, points, machine_factor=machine_factor + ) + elif machine_factor is not None: + self.state.device_calibration = self.state.device_calibration.with_machine_factor( + machine_factor + ) + logger.info( + "[calibration] %s clean: %s seq=%.0f canvas=%d windows=%d (%s)", + generation_id, + ran.bucket.feature, + ran.point.seq, + ran.point.canvas_px, + ran.point.windows, + "widened" if points is not None else "already covered", + ) + return verdict diff --git a/backend/handlers/custom_lora_handler.py b/backend/handlers/custom_lora_handler.py new file mode 100644 index 000000000..7af3a61d3 --- /dev/null +++ b/backend/handlers/custom_lora_handler.py @@ -0,0 +1,514 @@ +"""Custom LoRA handler: list, import (file copy or URL download), put weights back, delete. + +An import runs in the background and reports progress through one session slot, the same way a +catalog download does. Weights are staged in ``loras/custom/.tmp``, checked, then moved into +``loras/custom//``. The folder gets its ``meta.json`` last, so a failed or interrupted import +never shows up as a LoRA. + +A saved LoRA behaves like a catalog LoRA in Settings > Models. Deleting its weights keeps the +entry, and the weights come back from the saved link or from a chosen file (``restore_weights``). +Removing the LoRA deletes the whole folder. +""" + +from __future__ import annotations + +import logging +import shutil +from collections.abc import Callable +from dataclasses import dataclass, replace +from pathlib import Path +from threading import RLock +from typing import TYPE_CHECKING + +from PIL import Image + +from _routes._errors import HTTPError +from api_types import ( + ActiveCustomLoraImportResponse, + CatalogDownloadStatus, + CustomLoraImportProgressResponse, + CustomLoraImportRequest, + CustomLoraImportStartResponse, + CustomLoraItem, + CustomLoraLinkInfoResponse, + CustomLoraListResponse, + CustomLoraRestoreRequest, +) +from handlers.base import StateHandlerBase +from handlers.download_sessions import DownloadSessionTracker +from handlers.hf_auth_utils import optional_hf_token +from runtime_config.custom_lora_urls import ( + CustomLoraUrlError, + hugging_face_repo_of, + page_url_for, + pick_hugging_face_weights, + resolve_custom_lora_url, + saved_source_url, +) +from runtime_config.custom_loras import ( + COVER_MEDIA_TYPES, + MAX_CUSTOM_LORA_BYTES, + STAGING_DIRNAME, + WEIGHTS_SUFFIX, + CustomLoraFileError, + CustomLoraRecord, + custom_lora_cover_path, + custom_lora_dir, + custom_loras_root, + list_custom_loras, + read_custom_lora, + slugify_name, + validate_safetensors_weights, + write_meta, +) +from server_utils.media_validation import validate_image_file +from services.interfaces import TaskRunner +from services.url_downloader import UrlDownloadError, UrlDownloader, parse_model_card +from state.app_state_types import AppState, DownloadSessionId + +if TYPE_CHECKING: + from runtime_config.runtime_config import RuntimeConfig + +logger = logging.getLogger(__name__) + +_COPY_CHUNK_BYTES = 8 * 1024 * 1024 +_GENERIC_FAILURE = "The LoRA could not be saved. Check the free disk space and try again." +_COVER_FORMAT_SUFFIX = { + "PNG": ".png", + "JPEG": ".jpg", + "WEBP": ".webp", +} + + +def _in_use_error() -> HTTPError: + return HTTPError( + 409, + "A queued or running generation uses this LoRA. Wait for it to finish or cancel it, " + "then try again.", + code="CUSTOM_LORA_IN_USE", + ) + + +def _import_progress( + status: CatalogDownloadStatus, + *, + item_id: str | None = None, + downloaded_bytes: int = 0, + expected_bytes: int = 0, + progress: float = 0.0, + speed_bytes_per_sec: float = 0.0, + error: str | None = None, +) -> CustomLoraImportProgressResponse: + return CustomLoraImportProgressResponse( + status=status, + custom_lora_id=item_id, + downloaded_bytes=downloaded_bytes, + expected_bytes=expected_bytes, + progress=progress, + speed_bytes_per_sec=speed_bytes_per_sec, + error=error, + ) + + +@dataclass(frozen=True, slots=True) +class _UrlSource: + """Weights fetched from a checked HTTPS link.""" + + fetch_url: str + page_url: str | None + hf_token: str | None + downloader: UrlDownloader + + +@dataclass(frozen=True, slots=True) +class _FileSource: + """Weights copied from a file the user chose.""" + + path: Path + size: int + + +_Source = _UrlSource | _FileSource + + +class CustomLoraHandler(StateHandlerBase): + def __init__( + self, + state: AppState, + lock: RLock, + task_runner: TaskRunner, + config: "RuntimeConfig", + url_downloader: UrlDownloader | None = None, + lora_in_use: Callable[[str], bool] = lambda _custom_lora_id: False, + ) -> None: + super().__init__(state, lock, config) + # Whether a queued or running generation holds a saved LoRA. The queue owns that answer. + self._lora_in_use = lora_in_use + self._task_runner = task_runner + # None when the build has no URL downloader: file import still works. + self._url_downloader = url_downloader + self._sessions = DownloadSessionTracker( + state, + lock, + session_attr="custom_lora_import_session", + completed_attr="completed_custom_lora_import_sessions", + build_progress=_import_progress, + build_active=lambda session_id, item_id, progress: ActiveCustomLoraImportResponse( + session_id=session_id, custom_lora_id=item_id, progress=progress + ), + busy_message="Another LoRA is being added. Wait for it to finish.", + busy_code="CUSTOM_LORA_IMPORT_RUNNING", + ) + # A crash leaves the staging folder of a session. No import runs yet, so all of it is stale. + shutil.rmtree(custom_loras_root(self.models_dir) / STAGING_DIRNAME, ignore_errors=True) + + # --- listing --- + def list_loras(self) -> CustomLoraListResponse: + return CustomLoraListResponse( + loras=[ + CustomLoraItem( + id=r.id, + name=r.name, + size_bytes=r.size_bytes, + source=r.source, + downloaded=r.downloaded, + can_download=r.source_url is not None, + page_url=r.page_url, + trigger=r.trigger, + description=r.description, + examples=list(r.examples), + cover_url=( + None + if (cover := custom_lora_cover_path(self.models_dir, r)) is None + else str(cover) + ), + ) + for r in list_custom_loras(self.models_dir) + ] + ) + + # --- import --- + def start_import(self, req: CustomLoraImportRequest) -> CustomLoraImportStartResponse: + if self.config.force_api_generations: + raise HTTPError(409, "LOCAL_MODEL_DOWNLOADS_DISABLED_IN_FORCE_API_MODE") + slug = slugify_name(req.name) + if not slug: + raise HTTPError( + 422, "Use at least one letter or digit in the name.", code="CUSTOM_LORA_NAME_INVALID" + ) + + source: _Source + if req.url is not None: + source = self._link_source(req.url) + else: + assert req.source_path is not None # the request model guarantees one source + source = self._file_source(req.source_path) + cover_source = None if req.cover_path is None else self._cover_source(req.cover_path) + + record = CustomLoraRecord( + id=slug, + name=req.name, + filename=f"{slug}{WEIGHTS_SUFFIX}", + size_bytes=0, + source="url" if isinstance(source, _UrlSource) else "file", + source_url=saved_source_url(source.fetch_url) if isinstance(source, _UrlSource) else None, + page_url=source.page_url if isinstance(source, _UrlSource) else None, + trigger=req.trigger, + description=req.description or "", + examples=tuple(req.examples), + cover_filename=None if cover_source is None else cover_source[1], + ) + session_id = self._open_session(record, source, must_be_new=True) + return self._run_import( + session_id, + record, + source, + cover_source=None if cover_source is None else cover_source[0], + publish=self._publish_new, + ) + + def restore_weights( + self, custom_lora_id: str, req: CustomLoraRestoreRequest + ) -> CustomLoraImportStartResponse: + """Put the weights of a saved LoRA back, from its saved link or from a chosen file.""" + if self.config.force_api_generations: + raise HTTPError(409, "LOCAL_MODEL_DOWNLOADS_DISABLED_IN_FORCE_API_MODE") + record = self._require_record(custom_lora_id) + if record.downloaded: + raise HTTPError( + 409, "This LoRA already has its weights.", code="CUSTOM_LORA_ALREADY_DOWNLOADED" + ) + source: _Source + if req.source_path is not None: + source = self._file_source(req.source_path) + elif record.source_url is not None: + source = self._link_source(record.source_url) + else: + raise HTTPError( + 422, "This LoRA has no saved link. Choose the file again.", code="CUSTOM_LORA_SOURCE_MISSING" + ) + session_id = self._open_session(record, source, must_be_new=False) + return self._run_import(session_id, record, source, publish=self._publish_weights) + + def link_info(self, url: str) -> CustomLoraLinkInfoResponse: + """Validate a link and read form suggestions from the Hugging Face model card behind it. + + A link that fails ``resolve_custom_lora_url`` answers ``accepted=False``. Any accepted + link answers ``accepted=True``; a non-Hugging Face link, a missing card, or a failed card + request leaves the suggestions empty so the form is not blocked. + """ + try: + resolve_custom_lora_url(url) + except CustomLoraUrlError: + return CustomLoraLinkInfoResponse(accepted=False) + repo = hugging_face_repo_of(url) + if repo is None or self._url_downloader is None: + return CustomLoraLinkInfoResponse(accepted=True) + hf_token = optional_hf_token(self.state, self.lock) + try: + card = self._url_downloader.fetch_hugging_face_card(repo, hf_token=hf_token) + except UrlDownloadError as exc: + logger.info("No model card for %s: %s", repo.repo_id, exc) + return CustomLoraLinkInfoResponse(accepted=True) + suggestions = parse_model_card(card) + return CustomLoraLinkInfoResponse( + accepted=True, + trigger=suggestions.trigger, + description=suggestions.description, + examples=list(suggestions.examples), + ) + + def _link_source(self, url: str) -> _UrlSource: + if self._url_downloader is None: + raise HTTPError( + 409, "Adding a LoRA from a URL is not available.", code="CUSTOM_LORA_URL_UNAVAILABLE" + ) + # The token is read before the session opens. Only a Hugging Face host receives it. + hf_token = optional_hf_token(self.state, self.lock) + try: + resolved = resolve_custom_lora_url(url) + fetch_url = resolved.url + if resolved.repo is not None: + # A model page names no file. Take the one weights file the repo holds. + filename = pick_hugging_face_weights( + self._url_downloader.list_hugging_face_files(resolved.repo, hf_token=hf_token) + ) + fetch_url = resolved.repo.file_url(filename) + except (CustomLoraUrlError, UrlDownloadError) as exc: + raise HTTPError(422, str(exc), code="CUSTOM_LORA_URL_INVALID") from exc + return _UrlSource( + fetch_url=fetch_url, + page_url=page_url_for(fetch_url), + hf_token=hf_token, + downloader=self._url_downloader, + ) + + @staticmethod + def _cover_source(cover_path: str) -> tuple[Path, str]: + """The cover image and its stored filename, or a 422 the form can show.""" + if Path(cover_path).suffix.lower() not in COVER_MEDIA_TYPES: + raise HTTPError( + 422, "Choose a PNG, JPG, or WebP image.", code="CUSTOM_LORA_COVER_INVALID" + ) + try: + file_path = validate_image_file(cover_path) + with Image.open(file_path) as img: + suffix = _COVER_FORMAT_SUFFIX.get(str(img.format or "").upper()) + if suffix is None: + raise ValueError(img.format) + except (HTTPError, ValueError, OSError) as exc: + raise HTTPError( + 422, "Choose a PNG, JPG, or WebP image.", code="CUSTOM_LORA_COVER_INVALID" + ) from exc + return file_path, f"cover{suffix}" + + @staticmethod + def _file_source(source_path: str) -> _FileSource: + path = Path(source_path) + if path.suffix.lower() != WEIGHTS_SUFFIX or not path.is_file(): + raise HTTPError(422, "Choose a .safetensors file.", code="CUSTOM_LORA_FILE_INVALID") + size = path.stat().st_size + if size > MAX_CUSTOM_LORA_BYTES: + raise HTTPError(422, "The file is too large for a LoRA.", code="CUSTOM_LORA_FILE_INVALID") + return _FileSource(path=path, size=size) + + def _open_session( + self, record: CustomLoraRecord, source: _Source, *, must_be_new: bool + ) -> DownloadSessionId: + """Take the one session slot. A new LoRA also needs a free name.""" + + def _require_free_name() -> None: + if must_be_new and custom_lora_dir(self.models_dir, record.id).exists(): + raise HTTPError( + 409, + "A custom LoRA with this name already exists.", + code="CUSTOM_LORA_NAME_TAKEN", + ) + + return self._sessions.open( + record.id, + source.size if isinstance(source, _FileSource) else 0, + before_open=_require_free_name, + ) + + def _run_import( + self, + session_id: DownloadSessionId, + record: CustomLoraRecord, + source: _Source, + *, + cover_source: Path | None = None, + publish: Callable[[Path, Path, CustomLoraRecord], None], + ) -> CustomLoraImportStartResponse: + """Fetch or copy the weights in the background, check them, then publish them.""" + models_dir = self.models_dir + + def _work() -> None: + staging = custom_loras_root(models_dir) / STAGING_DIRNAME / session_id + staging.mkdir(parents=True, exist_ok=True) + try: + if cover_source is not None and record.cover_filename is not None: + shutil.copyfile(cover_source, staging / record.cover_filename) + staged = staging / record.filename + match source: + case _UrlSource(): + source.downloader.download( + source.fetch_url, + staged, + hf_token=source.hf_token, + max_bytes=MAX_CUSTOM_LORA_BYTES, + on_progress=lambda done, total: self._sessions.update_progress( + session_id, done, total + ), + ) + case _FileSource(): + self._copy(source.path, staged, session_id) + validate_safetensors_weights(staged) + publish(models_dir, staged, replace(record, size_bytes=staged.stat().st_size)) + finally: + shutil.rmtree(staging, ignore_errors=True) + self._remove_empty_staging_root(models_dir) + self._sessions.finish(session_id) + + self._task_runner.run_background( + _work, + task_name="custom-lora-import", + on_error=lambda exc: self._fail(session_id, exc), + daemon=True, + ) + return CustomLoraImportStartResponse( + status="started", sessionId=session_id, custom_lora_id=record.id + ) + + def _copy(self, source: Path, dest: Path, session_id: DownloadSessionId) -> None: + copied = 0 + with open(source, "rb") as src, open(dest, "wb") as out: + while chunk := src.read(_COPY_CHUNK_BYTES): + out.write(chunk) + copied += len(chunk) + self._sessions.update_progress(session_id, copied, 0) + + @staticmethod + def _publish_new(models_dir: Path, staged: Path, record: CustomLoraRecord) -> None: + final_dir = custom_lora_dir(models_dir, record.id) + final_dir.mkdir(parents=True, exist_ok=False) + try: + staged.replace(final_dir / record.filename) + if record.cover_filename is not None: + (staged.parent / record.cover_filename).replace(final_dir / record.cover_filename) + write_meta(final_dir, record) + except BaseException: + shutil.rmtree(final_dir, ignore_errors=True) + raise + + @staticmethod + def _publish_weights(models_dir: Path, staged: Path, record: CustomLoraRecord) -> None: + """Move the weights into the folder of an existing LoRA and save the new size.""" + final_dir = custom_lora_dir(models_dir, record.id) + staged.replace(final_dir / record.filename) + write_meta(final_dir, record) + + @staticmethod + def _remove_empty_staging_root(models_dir: Path) -> None: + root = custom_loras_root(models_dir) / STAGING_DIRNAME + try: + root.rmdir() + except OSError: + pass # not empty or already gone + + def _fail(self, session_id: DownloadSessionId, exc: Exception) -> None: + # These two carry a message written for the user. Anything else (disk, permissions) + # is logged by the task runner and shown as a generic message. + known = isinstance(exc, (UrlDownloadError, CustomLoraFileError)) + self._sessions.fail(session_id, str(exc) if known else _GENERIC_FAILURE) + + def get_import_progress(self, session_id: str) -> CustomLoraImportProgressResponse: + return self._sessions.get_progress(session_id) + + def get_active_import(self) -> ActiveCustomLoraImportResponse: + return self._sessions.get_active() + + # --- delete --- + def _require_dir(self, custom_lora_id: str) -> Path: + root = custom_loras_root(self.models_dir).resolve() + try: + target = custom_lora_dir(self.models_dir, custom_lora_id).resolve() + except ValueError as exc: + raise HTTPError(404, "CUSTOM_LORA_NOT_FOUND") from exc + # The route pattern already limits the id. This keeps a bad id from ever leaving the root. + if target.parent != root or custom_lora_id == STAGING_DIRNAME or not target.is_dir(): + raise HTTPError(404, "CUSTOM_LORA_NOT_FOUND") + return target + + def _require_record(self, custom_lora_id: str) -> CustomLoraRecord: + self._require_dir(custom_lora_id) + record = read_custom_lora(self.models_dir, custom_lora_id) + if record is None: + raise HTTPError(404, "CUSTOM_LORA_NOT_FOUND") + return record + + def _refuse_while_importing(self, custom_lora_id: str) -> None: + self._sessions.refuse_if_item_active( + custom_lora_id, message="CUSTOM_LORA_IMPORT_RUNNING" + ) + + def _refuse_while_in_use(self, custom_lora_id: str) -> None: + if self._lora_in_use(custom_lora_id): + raise _in_use_error() + + def delete_weights(self, custom_lora_id: str) -> None: + """Delete the weights and keep the entry, like Delete on a catalog LoRA.""" + record = self._require_record(custom_lora_id) + self._refuse_while_importing(custom_lora_id) + self._refuse_while_in_use(custom_lora_id) + weights = custom_lora_dir(self.models_dir, custom_lora_id) / record.filename + if not weights.is_file(): + raise HTTPError(404, "CUSTOM_LORA_NOT_DOWNLOADED") + try: + weights.unlink() + except PermissionError as exc: + # Windows refuses to remove a file the pipeline has open. + raise _in_use_error() from exc + + def cover_file(self, custom_lora_id: str) -> tuple[Path, str] | None: + """The cover file and its media type, or ``None`` when this LoRA has no cover.""" + record = read_custom_lora(self.models_dir, custom_lora_id) + if record is None: + return None + path = custom_lora_cover_path(self.models_dir, record) + if path is None: + return None + media_type = COVER_MEDIA_TYPES.get(path.suffix.lower()) + if media_type is None: + return None + return path, media_type + + def delete(self, custom_lora_id: str) -> None: + """Remove the LoRA: weights, entry, and folder.""" + target = self._require_dir(custom_lora_id) + self._refuse_while_importing(custom_lora_id) + self._refuse_while_in_use(custom_lora_id) + try: + shutil.rmtree(target) + except PermissionError as exc: + raise _in_use_error() from exc diff --git a/backend/handlers/download_sessions.py b/backend/handlers/download_sessions.py new file mode 100644 index 000000000..1817d394b --- /dev/null +++ b/backend/handlers/download_sessions.py @@ -0,0 +1,179 @@ +"""Single-slot background download session tracker shared by catalog and custom LoRA handlers. + +A handler keeps one active session slot in ``AppState`` and a bounded dict of finished +sessions. :class:`DownloadSessionTracker` owns the lock-protected lifecycle for one slot: +opening a session, updating progress, recording completion or failure, and answering the +progress and active-session endpoints. +""" + +from __future__ import annotations + +from collections.abc import Callable +from threading import RLock +import time +from typing import Generic, TypeVar +from uuid import uuid4 + +from _routes._errors import HTTPError +from api_types import CatalogDownloadStatus +from state.app_state_types import ( + AppState, + CatalogDownloadSession, + DownloadSessionComplete, + DownloadSessionError, + DownloadSessionId, + DownloadSessionResult, +) + +# Cap retained completed sessions so a long-running app doesn't accrue them forever. +# The client only needs a terminal status once; oldest-out is fine (dicts keep insertion order). +MAX_COMPLETED_SESSIONS = 32 + +ProgressResponseT = TypeVar("ProgressResponseT") +ActiveResponseT = TypeVar("ActiveResponseT") + + +def record_completed( + completed: dict[DownloadSessionId, DownloadSessionResult], + session_id: DownloadSessionId, + result: DownloadSessionResult, +) -> None: + completed[session_id] = result + while len(completed) > MAX_COMPLETED_SESSIONS: + completed.pop(next(iter(completed))) + + +def session_progress_pct(session: CatalogDownloadSession) -> float: + """Percent done, held below 100 until the session is recorded as complete.""" + if not session.expected_bytes: + return 0.0 + return min(99.0, session.downloaded_bytes / session.expected_bytes * 100) + + +class DownloadSessionTracker(Generic[ProgressResponseT, ActiveResponseT]): + """Lock-safe single-slot download session state machine.""" + + def __init__( + self, + state: AppState, + lock: RLock, + *, + session_attr: str, + completed_attr: str, + build_progress: Callable[..., ProgressResponseT], + build_active: Callable[[str | None, str | None, float | None], ActiveResponseT], + busy_message: str = "DOWNLOAD_ALREADY_RUNNING", + busy_code: str | None = None, + ) -> None: + self._state = state + self._lock = lock + self._session_attr = session_attr + self._completed_attr = completed_attr + self._build_progress = build_progress + self._build_active = build_active + self._busy_message = busy_message + self._busy_code = busy_code + + def _active(self) -> CatalogDownloadSession | None: + return getattr(self._state, self._session_attr) + + def _set_active(self, session: CatalogDownloadSession | None) -> None: + setattr(self._state, self._session_attr, session) + + def _completed(self) -> dict[DownloadSessionId, DownloadSessionResult]: + return getattr(self._state, self._completed_attr) + + def _busy_error(self) -> HTTPError: + return HTTPError(409, self._busy_message, code=self._busy_code) + + def open( + self, + item_id: str, + expected_bytes: int, + *, + before_open: Callable[[], None] | None = None, + ) -> DownloadSessionId: + with self._lock: + if self._active() is not None: + raise self._busy_error() + if before_open is not None: + before_open() + session_id = DownloadSessionId(uuid4().hex) + self._set_active( + CatalogDownloadSession( + id=session_id, + item_id=item_id, + downloaded_bytes=0, + expected_bytes=expected_bytes, + ) + ) + return session_id + + def refuse_if_item_active(self, item_id: str, *, message: str | None = None) -> None: + with self._lock: + session = self._active() + if session is not None and session.item_id == item_id: + raise HTTPError(409, message or self._busy_message, code=self._busy_code) + + def update_progress( + self, session_id: DownloadSessionId, downloaded: int, expected: int = 0 + ) -> None: + with self._lock: + session = self._active() + if session is not None and session.id == session_id: + now = time.monotonic() + elapsed = now - session.last_sample_time + if elapsed >= 0.5 and downloaded >= session.last_sample_bytes: + instant = (downloaded - session.last_sample_bytes) / elapsed + session.speed_bytes_per_sec = ( + instant + if session.speed_bytes_per_sec == 0.0 + else 0.3 * instant + 0.7 * session.speed_bytes_per_sec + ) + session.last_sample_time = now + session.last_sample_bytes = downloaded + session.downloaded_bytes = downloaded + if expected: + session.expected_bytes = expected + + def finish(self, session_id: DownloadSessionId) -> None: + with self._lock: + record_completed(self._completed(), session_id, DownloadSessionComplete()) + self._set_active(None) + + def fail(self, session_id: DownloadSessionId, error_message: str) -> None: + with self._lock: + record_completed( + self._completed(), session_id, DownloadSessionError(error_message=error_message) + ) + self._set_active(None) + + def get_progress(self, session_id: str) -> ProgressResponseT: + with self._lock: + sid = DownloadSessionId(session_id) + session = self._active() + if session is not None and session.id == sid: + status: CatalogDownloadStatus = "downloading" + return self._build_progress( + status, + item_id=session.item_id, + downloaded_bytes=session.downloaded_bytes, + expected_bytes=session.expected_bytes, + progress=session_progress_pct(session), + speed_bytes_per_sec=session.speed_bytes_per_sec, + ) + result = self._completed().get(sid) + if result is None: + raise HTTPError(404, "UNKNOWN_DOWNLOAD_SESSION") + if isinstance(result, DownloadSessionError): + return self._build_progress("error", error=result.error_message) + return self._build_progress("complete", progress=100.0) + + def get_active(self) -> ActiveResponseT: + with self._lock: + session = self._active() + if session is None: + return self._build_active(None, None, None) + return self._build_active( + str(session.id), session.item_id, session_progress_pct(session) + ) diff --git a/backend/handlers/extend_handler.py b/backend/handlers/extend_handler.py index 2b51105d2..93b0b4689 100644 --- a/backend/handlers/extend_handler.py +++ b/backend/handlers/extend_handler.py @@ -212,13 +212,13 @@ def _run_local_extend( ) try: - pipeline_state = self._pipelines.load_retake_pipeline( + pipeline_state, ran = self._pipelines.load_retake_pipeline( distilled=True, width=target_width, height=target_height, frames=target_frames + extend_frames, ) - self._generation.start_generation(generation_id) + self._generation.start_generation(generation_id, ran=ran) self._generation.update_progress("loading_model", 5, 0, 1) self._generation.update_progress("inference", 15, 0, 1) @@ -246,7 +246,7 @@ def _run_local_extend( raise GenerationCancelledError() self._generation.update_progress("complete", 100, 1, 1) - self._generation.complete_generation(str(output_path)) + self._generation.complete_generation(str(output_path), ran=ran) return RetakeVideoResponse(status="complete", video_path=str(output_path)) except HTTPError: self._generation.fail_generation("Extend generation failed") diff --git a/backend/handlers/generation_handler.py b/backend/handlers/generation_handler.py index c9e0df91f..8b6318dd9 100644 --- a/backend/handlers/generation_handler.py +++ b/backend/handlers/generation_handler.py @@ -4,7 +4,7 @@ import logging import time -from collections.abc import Iterator +from collections.abc import Callable, Iterator from contextlib import contextmanager from threading import Condition, Event, RLock from typing import TYPE_CHECKING, Literal @@ -18,11 +18,19 @@ WallTimeEstimateResponse, ) from handlers.base import StateHandlerBase, with_state_lock -from runtime_config.eta import WallTimeEstimate +from handlers.calibration_handler import CalibrationHandler +from runtime_config.device_calibration import JobEnvelope, RunMemoryBaseline, RunMemoryEnd +from runtime_config.eta import ( + WallTimeEstimate, + default_machine_factor, + estimate_envelope_wall_time, + remaining_wall_time_s, +) from services import generation_interrupt from services.generation_interrupt import GenerationCancelledError from services.generation_queue.control import GenerationSlotWaitAborted -from services.patches import diffusion_stage_cache +from services.patches import diffusion_stage_cache, mps_conv3d_as_conv2d +from state.app_settings import resolved_use_conv_vae from state.app_state_types import ( ApiGeneration, AppState, @@ -48,8 +56,16 @@ class GenerationHandler(StateHandlerBase): - def __init__(self, state: AppState, lock: RLock, config: RuntimeConfig) -> None: + def __init__( + self, + state: AppState, + lock: RLock, + config: RuntimeConfig, + *, + calibration: CalibrationHandler | None = None, + ) -> None: super().__init__(state, lock, config) + self._calibration = calibration self._generation_slot = Condition(self._lock) self._queue_yields = 0 from services.denoising_progress import configure_sink @@ -153,6 +169,35 @@ def queue_yields(self) -> Iterator[None]: self._queue_yields -= 1 self._generation_slot.notify_all() + @contextmanager + def try_lease_idle_gpu(self, *, local_lane_idle: Callable[[], bool]) -> Iterator[bool]: + """Hold the GPU for a short job of another lane, without waiting. Yields True when held. + + The lease succeeds only when the GPU is free: no running job, no reservation, nobody + waiting for it (assistant), and the local lane has no running or queued job. The last + check keeps an outside job from taking the GPU between two local jobs and evicting the + warm pipeline of the next one. The reservation does not expire while held. A granted + lease starts with the diffusion stage cache evicted. + """ + # The idle check reads SQLite, so it runs before the state lock is taken. The lock is + # shared by every handler, and a slow read must not stall them (busy_timeout is 5 s). + # Enqueue and claim do not take this lock, so holding it would not make the check exact. + leased = False + if local_lane_idle(): + with self._generation_slot: + leased = self._queue_yields == 0 and self.try_reserve_generation_start( + persistent=True + ) + try: + if leased: + # A local job cancelled before decode can leave its transformer cached. The + # borrower loads its own model next, so free the cache first. The slot is held. + diffusion_stage_cache.evict() + yield leased + finally: + if leased: + self.release_generation_start_reservation() + @contextmanager def reserved_generation_start(self, *, persistent: bool = False) -> Iterator[None]: """Guarantees the reservation is released on ANY exit — a normal return, a validation @@ -174,7 +219,11 @@ def reserved_generation_start(self, *, persistent: bool = False) -> Iterator[Non @with_state_lock def start_generation( - self, generation_id: str, *, estimated: WallTimeEstimate | None = None + self, + generation_id: str, + *, + estimated: WallTimeEstimate | None = None, + ran: JobEnvelope | None = None, ) -> None: if self.is_generation_running(): raise RuntimeError("Generation already in progress") @@ -189,6 +238,7 @@ def start_generation( state=GenerationCancelled(id=generation_id) ) raise GenerationCancelledError() + starting_since = self.state.generation_starting_since self.state.generation_starting_since = None # EXPERIMENTAL: push the live Settings toggle, then drop any transformer @@ -197,17 +247,47 @@ def start_generation( # build, double-booking VRAM. See that module's GENERATION-SCOPED # docstring section for the RTX 5090 repro (~42GB reported on a 32GB card). diffusion_stage_cache.set_enabled(self.state.app_settings.diffusion_stage_cache_enabled) + # EXPERIMENTAL (Apple Silicon): same live-push pattern. No-op off Darwin. The Settings + # toggle only shows under Fast decode, so the patch only runs while Fast decode is on. + app_settings = self.state.app_settings + conv_vae = resolved_use_conv_vae(app_settings, system=self.config.system) + mps_conv3d_as_conv2d.set_enabled(app_settings.mps_conv3d_as_conv2d_enabled and conv_vae) diffusion_stage_cache.evict() generation_interrupt.clear() from services.denoising_progress import configure_sink configure_sink(self._on_denoise_step) + resolved_estimated = estimated + if resolved_estimated is None and ran is not None: + calibrated = self.state.device_calibration.machine_factor + factor = ( + calibrated + if calibrated is not None + else default_machine_factor(self.config.gpu_device_name) + ) + system = ( + self.config.system + if self.config.system in ("Windows", "Linux", "Darwin") + else "Windows" + ) + resolved_estimated = estimate_envelope_wall_time( + ran, system=system, machine_factor=factor, conv_vae=conv_vae + ) + self.state.active_generation = GpuGeneration( state=GenerationRunning( id=generation_id, progress=GenerationProgress(phase="", progress=0, current_step=0, total_steps=0), - estimated=estimated, + estimated=resolved_estimated, + # After the evict above, so the baseline is the room this run starts with. + memory_baseline=( + self._calibration.open_run() if self._calibration is not None else None + ), + started_monotonic=( + starting_since if starting_since is not None else time.monotonic() + ), + conv_vae=conv_vae, ) ) logger.info("Generation %s started (gpu)", generation_id) @@ -350,6 +430,24 @@ def update_progress( running.progress.progress = progress running.progress.current_step = current_step running.progress.total_steps = total_steps + if ( + current_step is not None + and total_steps is not None + and total_steps > 1 + and current_step >= total_steps + ): + if running.decode_started_monotonic is None: + running.decode_started_monotonic = time.monotonic() + else: + running.decode_started_monotonic = None + + @with_state_lock + def _close_run_watch( + self, running: GenerationRunning + ) -> tuple[RunMemoryBaseline, RunMemoryEnd] | None: + if running.memory_baseline is None or self._calibration is None: + return None + return running.memory_baseline, self._calibration.close_run() @with_state_lock def cancel_generation(self) -> CancelResponse: @@ -357,6 +455,7 @@ def cancel_generation(self) -> CancelResponse: if running_generation is not None: generation_interrupt.request() slot, running = running_generation + self._close_run_watch(running) self._set_generation_state(slot, GenerationCancelled(id=running.id)) return CancelCancellingResponse(status="cancelling", id=running.id) @@ -375,15 +474,47 @@ def cancel_generation(self) -> CancelResponse: # arming the Event. return CancelNoActiveGenerationResponse(status="no_active_generation") + def complete_generation( + self, result: str | list[str] | None = None, *, ran: JobEnvelope | None = None + ) -> None: + """``ran`` is the admitted shape at the frames that actually ran; a clean run records it. + + A cancelled run is no longer running here, so it records nothing. + """ + finished = self._finish_running(result) + if finished is None or ran is None or self._calibration is None: + return + generation_id, measured, wall_s, conv_vae = finished + if measured is not None: + baseline, end = measured + self._calibration.record_if_clean( + ran, + baseline, + end, + generation_id=generation_id, + wall_s=wall_s, + conv_vae=conv_vae, + ) + @with_state_lock - def complete_generation(self, result: str | list[str] | None = None) -> None: + def _finish_running( + self, result: str | list[str] | None + ) -> tuple[str, tuple[RunMemoryBaseline, RunMemoryEnd] | None, float | None, bool] | None: running_generation = self._running_generation() if running_generation is None: - return + return None slot, running = running_generation + # Sampled before the slot frees, since the next run's watch resets this run's peak. + measured = self._close_run_watch(running) + wall_s = ( + max(0.001, time.monotonic() - running.started_monotonic) + if running.started_monotonic is not None + else None + ) self._set_generation_state(slot, GenerationComplete(id=running.id, result=result)) logger.info("Generation %s complete (%s)", running.id, slot) + return running.id, measured, wall_s, running.conv_vae @with_state_lock def fail_generation(self, error: str) -> None: @@ -394,6 +525,7 @@ def fail_generation(self, error: str) -> None: running_generation = self._running_generation() if running_generation is not None: slot, running = running_generation + self._close_run_watch(running) logger.error("Generation %s failed: %s", running.id, error) self._set_generation_state(slot, GenerationError(id=running.id, error=error)) return @@ -444,7 +576,18 @@ def get_generation_progress(self) -> GenerationProgressResponse: match gen: case GenerationRunning( id=generation_id, progress=progress, estimated=estimated - ): + ) as running: + now = time.monotonic() + elapsed_s = ( + max(0.0, now - running.started_monotonic) + if running.started_monotonic is not None + else 0.0 + ) + decode_elapsed_s = ( + max(0.0, now - running.decode_started_monotonic) + if running.decode_started_monotonic is not None + else None + ) return GenerationProgressResponse( status="running", phase=progress.phase, @@ -460,6 +603,13 @@ def get_generation_progress(self) -> GenerationProgressResponse: ) if estimated else None, + remainingSeconds=remaining_wall_time_s( + estimated, + elapsed_s=elapsed_s, + current_step=progress.current_step, + total_steps=progress.total_steps, + decode_elapsed_s=decode_elapsed_s, + ), ) case GenerationComplete(id=generation_id, result=result): return GenerationProgressResponse( diff --git a/backend/handlers/ic_lora_handler.py b/backend/handlers/ic_lora_handler.py index c42e674cb..16d0a5aaf 100644 --- a/backend/handlers/ic_lora_handler.py +++ b/backend/handlers/ic_lora_handler.py @@ -5,6 +5,7 @@ import base64 import logging import math +import os import time import uuid from collections.abc import Callable, Iterator, Sequence @@ -29,10 +30,25 @@ IcLoraGenerateCompleteResponse, IcLoraGenerateRequest, IcLoraGenerateResponse, + IcLoraAutoSinglePass, + IcLoraAutoWindowed, + IcLoraCarryPreflightCell, + IcLoraMaxWindowPreflightCell, IcLoraPreflightCell, IcLoraPreflightRequest, IcLoraPreflightResponse, IcLoraPreflightSource, + IcLoraPreflightVerdict, + IcLoraTilePreflightCell, + IcLoraTilePreflightResponse, + IcLoraTilingDefaults, + IcLoraTilePreset, + IcLoraTileSize, + IcLoraAudioMode, + IcLoraCellFit, + IcLoraRecipeMemoryRequest, + IcLoraRecipeMemoryResponse, + IcLoraRecipeResolution, IcLoraRecipeStoredParams, IcLoraSynthesizedStoredParams, IcLoraImageInput, @@ -48,41 +64,54 @@ from handlers.generation_handler import GenerationHandler from handlers.pipelines_handler import PipelinesHandler from handlers.prompt_enhancement_handler import PromptEnhancementHandler +from services.fast_video_pipeline.nag_config import ( + NagConfig, + NagDecision, + decide_nag, + log_nag_decision, +) from services.prompt_enhancement.source_video import SourceVideo from handlers.text_handler import TextHandler from ic_lora_preprocessing import MediaArtifact, OutpaintParams, PreprocessingContext, run_preprocessing +from runtime_config.budget_admission import ( + Admission, + Admitted, + PricedJob, + Refused, + RiskAllowance, + admit, + admits_within_device_memory, +) +from runtime_config.device_calibration import JobEnvelope +from runtime_config.ic_lora_auto_carry import picked_carry_tiling +from runtime_config.ic_lora_chunking import ic_lora_carry_frames from runtime_config.ic_lora_high_res import ( - HIGH_RES_NOT_ENABLED, - HIGH_RES_ONLY_IC_LORAS, high_res_cell, + high_res_flag_satisfied, high_res_settings, high_res_stage1, ) from runtime_config.ic_lora_job_budget import ( - IcLoraJobLoad, catalog_output_fps, catalog_preview_stills, - decide_ic_lora_job, dropped_duration_message_and_code, + price_ic_lora_job, ) from runtime_config.ic_lora_local_envelope import ( effective_denoise_stage1, ic_lora_output_canvas, ) from runtime_config.ic_lora_stage_mode import IcLoraStageMode, ic_lora_stage_mode -from runtime_config.ic_lora_tiling import IcLoraTiling +from runtime_config.ic_lora_tiling import DEFAULT_CARRY_FRAMES, IcLoraTiling, with_tiling_overrides from runtime_config.evict_retry import evict_retry_filter -from runtime_config.reject_reasons import IcLoraDroppedReason +from runtime_config.memory_meter import ( + job_filter_machine_factor, + job_memory_ask, + memory_capacity, +) from runtime_config.video_job_budget import ( - LoadMode, LocalJobFilter, - VideoJobLoad, - VideoJobReject, - risk_for_reject, - risk_if_allowed, - unmeasured_load_risk, - unmeasured_message, - untested_readout, + budget_route, vram_snapshot_suffix, ) from runtime_config.ltx_capabilities import budget_pixels, local_caps, supports @@ -102,7 +131,12 @@ from state.conditioning_cache import ConditioningCacheEntry, ConditioningCacheKey from services.interfaces import GpuInfo, VideoProcessor from services.aspect_ratio import center_cropped_size, find_closest_aspect_ratio_option -from services.features.ic_lora_recipes import IC_LORA_SUPPORTED_FPS, IcLoraRecipe +from services.features.ic_lora_recipes import ( + IC_LORA_SUPPORTED_FPS, + MAX_IC_LORA_INPUT_FRAMES, + IcLoraRecipe, + get_ic_lora_recipe, +) from services.features.video import SYNTHESIZED_IC_LORA_EXECUTORS from services.features.video.job_common import denoise_canvas, resolve_job_local_model_id from services.lora_catalog import LoraCatalogProvider @@ -115,32 +149,31 @@ logger = logging.getLogger(__name__) +# A 16:9 clip of each cell's size: what the memory advice prices before a clip is picked. The +# source mostly sets the aspect, and a recipe runs its cell, so the cell's own size stands in. +_STAND_IN_SOURCE: dict[IcLoraRecipeResolution, tuple[int, int]] = { + "270p": (480, 270), + "360p": (640, 360), + "540p": (960, 540), + "720p": (1280, 720), + "1080p": (1920, 1080), + "1440p": (2560, 1440), + "2160p": (3840, 2160), +} + @dataclass(frozen=True) -class _IcLoraVerdict: - """One IC-LoRA job verdict: the decided load mode, or the refusal pair. - - ``seq``/``full_gib``/``stream_gib`` feed the job-budget log line. The - two-stage fence is not a verdict — it raises before any curve runs, in - both generate and preflight, through the shared predicate. ``message``/ - ``code`` ride None on loads — refusals always set both. ``reason`` rides - None on loads; refusals carry the dropped reason so callers can tell a - VRAM-occupancy miss (``stream_over`` — an evict could help) from the - spatial/fence verdicts that share its code. ``chunk_pixel_frames`` is the - window the pipeline runs when a load chunks, else None. - ``reject`` carries the measured-budget reject for a downgradable - refusal, else None — fences and spatial verdicts never set it. +class RecipeRunPlan: + """What a queued Home recipe runs: the frame count, its risk, and its chunk window. + + ``window`` is the pixel frames of one chunk, or None when the clip runs in one pass. + ``carry`` is the carry of the chunks, the one Auto picked when the run did not choose it. """ - mode: LoadMode | None - message: str | None = None - code: str | None = None - seq: float = 0 - full_gib: float = 0 - stream_gib: float = 0 - reason: IcLoraDroppedReason | None = None - chunk_pixel_frames: int | None = None - reject: VideoJobReject | None = None + frames: int + risk: GenerationRisk | None + window: int | None + carry: int _IMAGE_SUFFIXES = frozenset({".png", ".jpg", ".jpeg", ".webp", ".bmp"}) @@ -171,8 +204,22 @@ def _reference_frame_idx(ic_lora: IcLoraCatalogItem, img: IcLoraImageInput) -> i return pinned if pinned is not None else int(img.frame) -def _resolve_settings(req: IcLoraGenerateRequest, base: IcLoraSettings) -> IcLoraSettings: - """Overlay the request's explicit settings onto a base; None means 'keep the base'.""" +def _with_high_res_plan(settings: IcLoraSettings, *, high_res: bool) -> IcLoraSettings: + """The settings with the plan of a high cell (1440p, 2160p), before the request's overrides. + + The one place that applies the plan, for the run and for the preflight defaults. + """ + return high_res_settings(settings) if high_res else settings + + +def _resolve_settings( + req: IcLoraGenerateRequest, base: IcLoraSettings, *, high_res: bool = False +) -> IcLoraSettings: + """Overlay the request's explicit settings onto a base; None means 'keep the base'. + + ``high_res`` runs the LoRA as tiles in windows, for the 1440p and 2160p cells. The + request's tile overlap and carry come last, so they win over the cell's own plan. + """ requested_stage2_lora = ( base.use_lora_in_stage_2 if req.use_lora_in_stage_2 is None else req.use_lora_in_stage_2 ) @@ -185,12 +232,12 @@ def _resolve_settings(req: IcLoraGenerateRequest, base: IcLoraSettings) -> IcLor if base.tiling is not None else base.skip_stage_2 if req.skip_stage_2 is None else req.skip_stage_2 ) - return IcLoraSettings( + settings = IcLoraSettings( skip_stage_2=skip_stage_2, use_lora_in_stage_2=False, # Stage 2 does not run when skipped, so the flag would only change the cache key. stage_2_ic_lora=base.stage_2_ic_lora and not skip_stage_2, - # Catalog only. A request cannot change the tile size. + # The tiling is the catalog's. ``_with_requested_tiling`` applies the request's overrides. tiling=base.tiling, resolution_factor=base.resolution_factor if req.resolution_factor is None else req.resolution_factor, audio_mode=base.audio_mode if req.audio_mode is None else req.audio_mode, @@ -199,6 +246,51 @@ def _resolve_settings(req: IcLoraGenerateRequest, base: IcLoraSettings) -> IcLor base.conditioning_strength if req.conditioning_strength is None else req.conditioning_strength ), ) + return _with_requested_tiling(req, _with_high_res_plan(settings, high_res=high_res)) + + +def _tiling_defaults(item: IcLoraCatalogItem, stored: IcLoraRecipeStoredParams) -> IcLoraTilingDefaults: + """The carry and tile the run keeps when the request omits them. + + The high-cell plan is applied to the catalog settings, as ``_resolve_settings`` does before + the request's overrides. The window is not here: Auto picks it from the clip, so the job + plan gives it. + """ + tiling = _with_high_res_plan( + item.default_settings, high_res=high_res_cell(stored.resolution) is not None + ).tiling + carry = DEFAULT_CARRY_FRAMES if tiling is None or tiling.carry_frames is None else tiling.carry_frames + return IcLoraTilingDefaults( + carryFrames=carry, overlapFraction=None if tiling is None else tiling.overlap_fraction + ) + + +def _with_requested_tiling(req: IcLoraGenerateRequest, settings: IcLoraSettings) -> IcLoraSettings: + """The settings with the request's tile overlap, carry, tile size and window. 422 when they cannot run.""" + if ( + req.tile_overlap is None + and req.carry_frames is None + and req.tile_size is None + and req.max_window_frames is None + ): + return settings + if settings.tiling is None: + raise HTTPError( + 422, + f"{req.ic_lora_id} takes no tile overlap, carry, tile size or window.", + code="INVALID_GENERATION_SPEC", + ) + try: + tiling = with_tiling_overrides( + settings.tiling, + overlap_fraction=req.tile_overlap, + carry_frames=req.carry_frames, + tile_size=req.tile_size, + max_window_frames=req.max_window_frames, + ) + except ValueError as exc: + raise HTTPError(422, f"Invalid tiling: {exc}.", code="INVALID_GENERATION_SPEC") from exc + return settings.model_copy(update={"tiling": tiling}) class IcLoraHandler(StateHandlerBase): @@ -225,7 +317,7 @@ def __init__( self._video_processor = video_processor self._catalog = lora_catalog - def _decide_ic_lora_verdict( + def _price_ic_lora( self, canvas_width: int, canvas_height: int, @@ -237,18 +329,14 @@ def _decide_ic_lora_verdict( ic_lora_id: str | None = None, stills: int = 0, tiling: IcLoraTiling | None = None, - ) -> _IcLoraVerdict: - """Spatial + budget verdict without raising. Generate raises from this; - preflight returns it per duration. The token-ceiling fence rides inside - decide (first pre-check), so no call site sequences it separately. - ic_lora_id threads to the Mac ingredients term (None prices on the line).""" + ) -> PricedJob: stage1_w, stage1_h = effective_denoise_stage1( canvas_width, canvas_height, skip_stage_2=stage_mode is IcLoraStageMode.SINGLE_STAGE, resolution_factor=resolution_factor, ) - decision = decide_ic_lora_job( + return price_ic_lora_job( stage1_w, stage1_h, frame_count, @@ -258,29 +346,37 @@ def _decide_ic_lora_verdict( stills=stills, tiling=tiling, ) - # Gate precedence, decided upstream: unsupported process mode, spatial - # canvas cap, token-ceiling fence, Mac two-stage fence, then the - # measured budget curves — the shared builder below routes the - # verdict to its message. Load first so it only sees rejects. - if isinstance(decision, IcLoraJobLoad): - return _IcLoraVerdict( - mode=decision.mode, - seq=decision.seq, - full_gib=decision.full_gib, - stream_gib=decision.stream_gib, - chunk_pixel_frames=decision.chunk_pixel_frames, - ) - message, code = dropped_duration_message_and_code(decision, job_filter) - return _IcLoraVerdict( - mode=None, - message=message, - code=code, - seq=decision.seq, - full_gib=decision.full_gib, - stream_gib=decision.stream_gib, - reason=decision.reason, - chunk_pixel_frames=decision.chunk_pixel_frames, - reject=decision if isinstance(decision, VideoJobReject) else None, + + def _decide_ic_lora_admission( + self, + canvas_width: int, + canvas_height: int, + *, + frame_count: int, + stage_mode: IcLoraStageMode, + resolution_factor: float, + job_filter: LocalJobFilter, + ic_lora_id: str | None = None, + stills: int = 0, + tiling: IcLoraTiling | None = None, + allowance: RiskAllowance | None = None, + ) -> Admission: + """Spatial + budget admission without raising. Generate raises on a + refusal; preflight returns it per duration. ic_lora_id threads to the + Mac ingredients term (None prices on the line).""" + return admit( + self._price_ic_lora( + canvas_width, + canvas_height, + frame_count=frame_count, + stage_mode=stage_mode, + resolution_factor=resolution_factor, + job_filter=job_filter, + ic_lora_id=ic_lora_id, + stills=stills, + tiling=tiling, + ), + allowance if allowance is not None else RiskAllowance.for_mode(job_filter.budget_mode), ) def _ic_lora_job( @@ -296,44 +392,41 @@ def _ic_lora_job( tiling: IcLoraTiling | None = None, total_only: bool = False, allow_evict_retry: bool = False, - allow_risk: bool | None = None, - unmeasured_bet: bool = False, - ) -> tuple[IcLoraJobLoad, GenerationRisk | None]: - """422, or pick full vs stream and the chunk window for this job. + allowance: RiskAllowance | None = None, + ) -> Admitted: + """422, or admit this job: full vs stream, the chunk window, and any bet. Does not change process mode. The pipeline runs the window this returns. - In reckless mode a downgradable reject downgrades to streaming instead, - with the bet annotation alongside the load. ``allow_risk=None`` follows - the filter's live mode (every request-scoped caller); executors pass an - explicit bool parsed from the stored annotation so a mode flip never - re-gates a queued job. + ``allowance=None`` follows the filter's live mode (every request-scoped + caller); executors pass an explicit allowance parsed from the stored + annotation so a mode flip never re-gates a queued job. Queued and direct execute (pre-start probe only) pass ``allow_evict_retry``: a total-possible CUDA reject whose shortfall - live weights cover gets one evict-and-resample before the 422. The + live weights cover gets one evict-and-resample before admission. The post-preprocess re-check must leave it off — a generation is Running by then and local refs pin the loaded pipeline, so an evict could not free it. """ job_filter = self._local_job_filter(total_only=total_only) - verdict = self._decide_ic_lora_verdict( - canvas_width, - canvas_height, - frame_count=frame_count, - stage_mode=stage_mode, - resolution_factor=resolution_factor, - job_filter=job_filter, - ic_lora_id=ic_lora_id, - stills=stills, - tiling=tiling, - ) - if verdict.mode is None and verdict.reason is not None and allow_evict_retry: + + def price(job_filter: LocalJobFilter) -> PricedJob: + return self._price_ic_lora( + canvas_width, + canvas_height, + frame_count=frame_count, + stage_mode=stage_mode, + resolution_factor=resolution_factor, + job_filter=job_filter, + ic_lora_id=ic_lora_id, + stills=stills, + tiling=tiling, + ) + + priced = price(job_filter) + if allow_evict_retry: rebuilt = evict_retry_filter( - feature="iclora", - is_vram_occupancy_miss=(verdict.reason == "stream_over"), - stream_gib=verdict.stream_gib, - seq=verdict.seq, - full_gib=verdict.full_gib, + priced=priced, job_filter=job_filter, live_allocated_bytes=self._gpu.get_cuda_live_allocated_bytes(), reserved_bytes=self._gpu.get_cuda_reserved_bytes(), @@ -343,135 +436,42 @@ def _ic_lora_job( ) if rebuilt is not None: job_filter = rebuilt - verdict = self._decide_ic_lora_verdict( - canvas_width, - canvas_height, - frame_count=frame_count, - stage_mode=stage_mode, - resolution_factor=resolution_factor, - job_filter=job_filter, - ic_lora_id=ic_lora_id, - stills=stills, - tiling=tiling, - ) - if verdict.mode is None: - assert verdict.message is not None and verdict.code is not None # refusals set both - risk = self._risk_for_iclora_verdict( - verdict, job_filter, allow_risk, unmeasured_bet=unmeasured_bet - ) - if risk is not None: - logger.info( - "[ic-lora] job budget seq=%.0f full=%.1fGiB stream=%.1fGiB -> risk:%s over_gib=%s over_ram_gb=%s%s", - verdict.seq, - verdict.full_gib, - verdict.stream_gib, - risk.tier, - risk.over_gib, - risk.over_ram_gb, - vram_snapshot_suffix( - allocated_bytes=self._gpu.get_cuda_live_allocated_bytes(), - reserved_bytes=self._gpu.get_cuda_reserved_bytes(), - free_bytes=job_filter.budget.free_vram_bytes, - ), - ) - return ( - IcLoraJobLoad( - mode="streaming_models_loading", - seq=verdict.seq, - full_gib=verdict.full_gib, - stream_gib=verdict.stream_gib, - chunk_pixel_frames=verdict.chunk_pixel_frames, - ), - risk, - ) + priced = price(job_filter) + admission = admit( + priced, + allowance if allowance is not None else RiskAllowance.for_mode(job_filter.budget_mode), + ) + snapshot = vram_snapshot_suffix( + allocated_bytes=self._gpu.get_cuda_live_allocated_bytes(), + reserved_bytes=self._gpu.get_cuda_reserved_bytes(), + free_bytes=job_filter.budget.free_vram_bytes, + ) + if isinstance(admission, Refused): logger.info( - "[ic-lora] job budget seq=%.0f full=%.1fGiB stream=%.1fGiB -> reject%s", - verdict.seq, - verdict.full_gib, - verdict.stream_gib, - vram_snapshot_suffix( - allocated_bytes=self._gpu.get_cuda_live_allocated_bytes(), - reserved_bytes=self._gpu.get_cuda_reserved_bytes(), - free_bytes=job_filter.budget.free_vram_bytes, - ), + "[ic-lora] job budget seq=%.0f full=%.1fGiB stream=%.1fGiB -> reject:%s%s", + priced.seq, + priced.full_gib, + priced.stream_gib, + admission.reject.reason, + snapshot, ) - raise HTTPError(422, verdict.message, code=verdict.code) + message, code = dropped_duration_message_and_code(admission.reject, job_filter) + raise HTTPError(422, message, code=code) + risk = admission.risk logger.info( - "[ic-lora] job budget seq=%.0f full=%.1fGiB stream=%.1fGiB -> %s%s", - verdict.seq, - verdict.full_gib, - verdict.stream_gib, - verdict.mode, - vram_snapshot_suffix( - allocated_bytes=self._gpu.get_cuda_live_allocated_bytes(), - reserved_bytes=self._gpu.get_cuda_reserved_bytes(), - free_bytes=job_filter.budget.free_vram_bytes, + "[ic-lora] job budget seq=%.0f full=%.1fGiB stream=%.1fGiB -> %s%s%s", + priced.seq, + priced.full_gib, + priced.stream_gib, + admission.load.mode, + ( + f" risk:{risk.tier} over_gib={risk.over_gib} over_ram_gb={risk.over_ram_gb}" + if risk is not None + else "" ), + snapshot, ) - load = IcLoraJobLoad( - mode=verdict.mode, - seq=verdict.seq, - full_gib=verdict.full_gib, - stream_gib=verdict.stream_gib, - chunk_pixel_frames=verdict.chunk_pixel_frames, - ) - return ( - load, - unmeasured_load_risk( - VideoJobLoad( - mode=load.mode, - seq=load.seq, - full_gib=load.full_gib, - stream_gib=load.stream_gib, - ), - job_filter, - feature="iclora", - allow_risk=allow_risk, - ), - ) - - @staticmethod - def _iclora_verdict_risk( - verdict: _IcLoraVerdict, - job_filter: LocalJobFilter, - ) -> GenerationRisk | None: - """Downgrade annotation for a refusal, ignoring the live mode. - - Preflight cells always carry this so a picker can tell a hard refusal - from one Reckless would run. Create and execute still gate on the mode. - """ - if verdict.reason is None: - return None - if verdict.reject is not None: - return risk_for_reject(verdict.reject, job_filter) - if verdict.reason == "two_stage_over_measured": - return GenerationRisk( - tier="unmeasured", - message=unmeasured_message(), - readout=untested_readout(), - ) - if verdict.reason == "mac_two_stage_unmeasured": - return GenerationRisk( - tier="unmeasured", - message=unmeasured_message("mac_two_stage"), - readout=untested_readout(), - ) - return None # spatial / decode floor / unsupported: hard walls - - @staticmethod - def _risk_for_iclora_verdict( - verdict: _IcLoraVerdict, - job_filter: LocalJobFilter, - allow_risk: bool | None, - *, - unmeasured_bet: bool = False, - ) -> GenerationRisk | None: - return risk_if_allowed( - IcLoraHandler._iclora_verdict_risk(verdict, job_filter), - job_filter, - allow_risk, - unmeasured_bet=unmeasured_bet, - ) + return admission def _probe_ic_lora_source( self, path: str, kind: str, requested_frames: int, *, raw_frames: bool = False @@ -700,14 +700,14 @@ def _outpaint_from_request(req: IcLoraGenerateRequest) -> OutpaintParams | None: return None return OutpaintParams(left=p.left, right=p.right, top=p.top, bottom=p.bottom) - def _complete_or_drop_cancelled(self, output_path: Path) -> None: + def _complete_or_drop_cancelled(self, output_path: Path, *, ran: JobEnvelope | None) -> None: # Denoiser interrupt cannot abort VAE decode / ffmpeg; a Stop after the last # denoise step still finishes encode, then this check drops the file. if self._generation.is_generation_cancelled(): output_path.unlink(missing_ok=True) raise GenerationCancelledError() self._generation.update_progress("complete", 100, 1, 1) - self._generation.complete_generation(str(output_path)) + self._generation.complete_generation(str(output_path), ran=ran) def generate_local_reserved( self, @@ -720,8 +720,7 @@ def generate_local_reserved( explore_generation: bool = True, explicit_generation_seed: bool = False, high_res: bool = False, - risk_allowance: bool | None = None, - unmeasured_bet: bool = False, + allowance: RiskAllowance | None = None, panel_paths: Sequence[str] = (), ) -> IcLoraGenerateResponse: """Local-only Home/Remote entry. The checkpoint id is required. @@ -744,8 +743,7 @@ def generate_local_reserved( explore_generation=explore_generation, explicit_generation_seed=explicit_generation_seed, high_res=high_res, - risk_allowance=risk_allowance, - unmeasured_bet=unmeasured_bet, + allowance=allowance, panel_paths=panel_paths, ) @@ -760,16 +758,13 @@ def _generate_ic_lora( explore_generation: bool, explicit_generation_seed: bool = False, high_res: bool = False, - risk_allowance: bool | None = None, - unmeasured_bet: bool = False, + allowance: RiskAllowance | None = None, panel_paths: Sequence[str] = (), ) -> IcLoraGenerateResponse: assert req.ic_lora_id is not None ic_lora = self._catalog.get_ic_lora(req.ic_lora_id) if ic_lora is None: raise HTTPError(404, "UNKNOWN_IC_LORA") - if ic_lora.id in HIGH_RES_ONLY_IC_LORAS and not self._high_res_enabled(): - raise HTTPError(422, HIGH_RES_NOT_ENABLED, code=HIGH_RES_NOT_ENABLED) if not catalog_item_visible_for_installed_ltx(ic_lora.supported_models, self.models_dir): raise HTTPError(422, "IC_LORA_UNSUPPORTED_MODEL") if ( @@ -818,9 +813,7 @@ def _generate_ic_lora( requested_frames = compute_num_frames(duration, catalog_output_fps(ic_lora, req.loop_fps)) # IC-LoRA defaults, with any explicit UI override (e.g. skip_stage_2) applied on top. - s = _resolve_settings(req, ic_lora.default_settings) - if high_res: - s = high_res_settings(s) + s = _resolve_settings(req, ic_lora.default_settings, high_res=high_res) stage_mode = s.stage_mode # Optional reference image (e.g. a photoreal seed for 3D-render): conditions the # first frame. Only honoured when the catalog entry opts in; ignored otherwise. @@ -852,7 +845,7 @@ def _generate_ic_lora( stage_2_ic_lora=s.stage_2_ic_lora, tiling=s.tiling, ) - job, _ = self._ic_lora_job( + admitted = self._ic_lora_job( width, height, frame_count=probe_frames, @@ -860,11 +853,13 @@ def _generate_ic_lora( resolution_factor=resolution_factor, ic_lora_id=req.ic_lora_id, allow_evict_retry=True, - allow_risk=risk_allowance, - unmeasured_bet=unmeasured_bet, + allowance=allowance, stills=stills, tiling=s.tiling, ) + job = admitted.load + run_tiling = picked_carry_tiling(s.tiling, admitted.priced) + nag_decision = self._decide_nag(req, model_id=local_model_id) resolved_prompt = self._prompt_enhancement.resolve_for_generation( req.prompt, provenance=req.prompt_provenance, @@ -889,6 +884,7 @@ def _generate_ic_lora( else None ), panel_paths=panel_paths if explore_generation and ic_lora.is_sheet_recipe() else (), + negative_prompt=nag_decision.enhancer_negative, ) prompt = resolved_prompt.prompt enhance_via_api = resolved_prompt.enhance_via_api @@ -902,9 +898,9 @@ def _generate_ic_lora( mode=job.mode, ltx_model_id=local_model_id, stage_2_ic_lora=s.stage_2_ic_lora, - tiling=s.tiling, + tiling=run_tiling, ) - self._generation.start_generation(generation_id) + self._generation.start_generation(generation_id, ran=admitted.envelope) self._generation.update_progress("loading_model", 5, 0, 1) input_artifact = MediaArtifact(path=req.input_path, kind=ic_lora.input.kind) @@ -954,20 +950,21 @@ def _generate_ic_lora( stage_2_ic_lora=s.stage_2_ic_lora, tiling=s.tiling, ) - new_job, _ = self._ic_lora_job( + admitted = self._ic_lora_job( width, height, frame_count=frame_count, stage_mode=stage_mode, resolution_factor=resolution_factor, ic_lora_id=req.ic_lora_id, - allow_risk=risk_allowance, - unmeasured_bet=unmeasured_bet, + allowance=allowance, stills=stills, tiling=s.tiling, ) - reload = new_job.mode != job.mode - job = new_job + rerun_tiling = picked_carry_tiling(s.tiling, admitted.priced) + reload = admitted.load.mode != job.mode or rerun_tiling != run_tiling + job = admitted.load + run_tiling = rerun_tiling if reload: ic_state = self._pipelines.load_ic_lora( str(lora_path), @@ -976,7 +973,7 @@ def _generate_ic_lora( mode=job.mode, ltx_model_id=local_model_id, stage_2_ic_lora=s.stage_2_ic_lora, - tiling=s.tiling, + tiling=run_tiling, ) self._text.prepare_text_encoding( @@ -984,6 +981,7 @@ def _generate_ic_lora( enhance_prompt=enhance_via_api, model_id=local_model_id, ) + nag = self._resolve_nag(req, model_id=local_model_id) self._generation.raise_if_cancelled() self._generation.update_progress("inference", 15, 0, 1) @@ -1009,8 +1007,9 @@ def _generate_ic_lora( ), mute_audio=s.audio_mode == "off", conditioning_mask_path=control.mask_path, + nag=nag, ) - self._complete_or_drop_cancelled(output_path) + self._complete_or_drop_cancelled(output_path, ran=admitted.envelope) return IcLoraGenerateCompleteResponse(status="complete", video_path=str(output_path)) except HTTPError: self._generation.fail_generation("IC-LoRA generation failed") @@ -1034,6 +1033,29 @@ def _generate_ic_lora( self._drop_preprocess_artifact(control.mask_path, req.input_path) self._text.clear_api_embeddings() + def _decide_nag( + self, req: IcLoraGenerateRequest, *, model_id: LTXLocalModelId | None + ) -> NagDecision: + with self._lock: + default_nag_scale = self.state.app_settings.nag_scale + return decide_nag( + req.negative_prompt, + os.environ, + scale=req.nag_scale, + alpha=req.nag_alpha, + tau=req.nag_tau, + default_scale=default_nag_scale, + local_encoding=self._text.should_use_local_encoding(model_id), + compiled=False, + ) + + def _resolve_nag( + self, req: IcLoraGenerateRequest, *, model_id: LTXLocalModelId | None + ) -> NagConfig | None: + return log_nag_decision( + logger, "ic-lora", self._decide_nag(req, model_id=model_id) + ) + def preflight(self, req: IcLoraPreflightRequest) -> IcLoraPreflightResponse: """Advisory sizing verdicts for a catalog input, before Generate. @@ -1047,8 +1069,6 @@ def preflight(self, req: IcLoraPreflightRequest) -> IcLoraPreflightResponse: ic_lora = self._catalog.get_ic_lora(req.ic_lora_id) if ic_lora is None: raise HTTPError(404, "UNKNOWN_IC_LORA") - if ic_lora.id in HIGH_RES_ONLY_IC_LORAS and not self._high_res_enabled(): - raise HTTPError(422, HIGH_RES_NOT_ENABLED, code=HIGH_RES_NOT_ENABLED) if not catalog_item_visible_for_installed_ltx(ic_lora.supported_models, self.models_dir): raise HTTPError(422, "IC_LORA_UNSUPPORTED_MODEL") assert ic_lora.input is not None, "IC-LoRA ic_lora is missing its input spec" @@ -1109,7 +1129,7 @@ def preflight(self, req: IcLoraPreflightRequest) -> IcLoraPreflightResponse: ) cells: list[IcLoraPreflightCell] = [] for duration, frames in targets: - verdict = self._decide_ic_lora_verdict( + admission = self._decide_ic_lora_admission( width, height, frame_count=frames, @@ -1120,13 +1140,19 @@ def preflight(self, req: IcLoraPreflightRequest) -> IcLoraPreflightResponse: stills=catalog_preview_stills(ic_lora), tiling=base.tiling, ) - risk = self._iclora_verdict_risk(verdict, job_filter) + if isinstance(admission, Admitted): + risk = admission.risk + message = None if risk is None else risk.message + code = None + else: + risk = admission.bet + message, code = dropped_duration_message_and_code(admission.reject, job_filter) cells.append( IcLoraPreflightCell( duration=duration, - ok=verdict.mode is not None, - message=verdict.message, - code=verdict.code, + ok=isinstance(admission, Admitted), + message=message, + code=code, tier=None if risk is None else risk.tier, over_gib=None if risk is None else risk.over_gib, over_ram_gb=None if risk is None else risk.over_ram_gb, @@ -1166,15 +1192,30 @@ def preflight_queued_recipe_job( upscale: bool = False, cutout: bool = False, ) -> GenerationRisk | None: + """The risk of ``preflight_queued_recipe_plan``. Raises HTTPError like it.""" + return self.preflight_queued_recipe_plan( + item=item, video=video, stored=stored, source_fps=source_fps, upscale=upscale, cutout=cutout + ).risk + + def preflight_queued_recipe_plan( + self, + *, + item: IcLoraCatalogItem, + video: AssetRecord, + stored: IcLoraRecipeStoredParams, + source_fps: float | None = None, + upscale: bool = False, + cutout: bool = False, + ) -> RecipeRunPlan: """Create-time mirror of IcLoraRecipeExecutor's budget gate. Assembles the same generate request execute would (same closest-match aspect, same explicit-resolution canvas, estimated resampled source frames) and runs it through the same load gate (``recipe_run_frames``), so an - over-budget create 422s here with the refusal execute would normally raise - instead of enqueueing a job that fails in the runner. A downgraded - reckless reject returns its annotation instead. Raises HTTPError; - returns None when the job loads clean. + over-budget create 422s here with the refusal execute would raise + instead of enqueueing a job that fails in the runner. A job admitted on + a bet returns the bet's annotation instead. Raises HTTPError; + the plan carries no risk when the job loads clean. Only the probe check is mirrored, not the post-preprocess re-check. Both price the resampled frames and the center-cropped canvas. The @@ -1208,7 +1249,7 @@ def preflight_queued_recipe_job( and stored.fps + 1e-3 < source_fps ): probe_frames = self._resampled_frame_count(probe_frames, source_fps, stored.fps) - _, risk = self.recipe_run_frames( + return self.recipe_run_plan( ic_lora_id=item.id, source_width=probe_w, source_height=probe_h, @@ -1217,54 +1258,36 @@ def preflight_queued_recipe_job( cutout=cutout, upscale=upscale, ) - return risk - def recipe_run_frames( + def _recipe_canvas( self, + item: IcLoraCatalogItem, *, - ic_lora_id: str, + local_model_id: LTXLocalModelId, + resolution: IcLoraRecipeResolution, source_width: int, source_height: int, - stored: IcLoraRecipeStoredParams, - clip_frames: int, - cutout: bool = False, - upscale: bool = False, - risk_allowance: bool | None = None, - unmeasured_bet: bool = False, - ) -> tuple[int, GenerationRisk | None]: - """Frame count a queued Home recipe runs for a clip of ``clip_frames`` frames, and its risk. - - The count snaps UP, so no frame is dropped: the recipe repeats the last frame to - reach it and cuts the output back. When that count is refused or carries a risk, and - the count snapped DOWN is strictly better, the job runs the smaller count, and the - pipeline drops the last frames as it did before. From best to worst: clean, an - ``unmeasured`` risk (a fence that moves with the frame count), an ``over`` risk, a - 422. Reckless mode returns a risk in place of the 422. When the snapped-down count - is no better, or is refused itself, the snapped-up count runs with its risk, or its 422 - propagates. The check asks "will it ever fit" (``total_only``). The create-time - preflight and the run use this one method, but they count the clip frames in two ways - (stored count with resample math, and the cropped file itself), so the counts can - differ by a frame. The run gates the count it reads from the file. - - An executor passes ``risk_allowance`` and ``unmeasured_bet`` from the stored - annotation, so a mode change never gates a queued job again. - - ``source_width`` and ``source_height`` are the size of the file the user picked. The - run reads the clip after ``center_crop_video``, so the canvas comes from the cropped - size. The cutout recipe keeps the whole frame and always pads up, so it uses the - uncropped size and has no snapped-down fallback. + audio_mode: IcLoraAudioMode, + lora_strength: float, + cutout: bool, + upscale: bool, + tile_overlap: float | None = None, + tile_size: IcLoraTileSize | None = None, + carry_frames: int | None = None, + max_window_frames: int | None = None, + ) -> tuple[int, int, float, IcLoraSettings]: + """Canvas, resolution factor and settings a Home recipe runs for a source of this size. + + One home for create, execute and the memory advice, so the three price one canvas. The + tiling arguments are the Advanced choices of the run. None keeps the plan of the cell. """ - item = self._catalog.get_ic_lora(ic_lora_id) - if item is None: - raise HTTPError(404, "UNKNOWN_IC_LORA") - local_model_id = resolve_job_local_model_id(self.models_dir, stored.model) aspect = cast( LTXVideoGenAspectRatio, find_closest_aspect_ratio_option( source_width, source_height, get_args(LTXVideoGenAspectRatio) ), ) - high_res = high_res_cell(stored.resolution) + high_res = high_res_cell(resolution) if high_res is not None: explicit_width, explicit_height = high_res_stage1( source_width, source_height, high_res, upscale=upscale @@ -1273,7 +1296,7 @@ def recipe_run_frames( try: explicit_width, explicit_height = budget_pixels( local_caps(local_model_id), - stored.resolution, + resolution, aspect, mode="video", ) @@ -1282,15 +1305,17 @@ def recipe_run_frames( request = IcLoraGenerateRequest( ic_lora_id=item.id, input_path="", - prompt=stored.prompt, + prompt="", conditioning_type="custom", resolution=TargetResolution(width=explicit_width, height=explicit_height), - audio_mode=stored.audioMode, - lora_strength=stored.loras[0].scale, + audio_mode=audio_mode, + lora_strength=lora_strength, + tile_overlap=tile_overlap, + tile_size=tile_size, + carry_frames=carry_frames, + max_window_frames=max_window_frames, ) - s = _resolve_settings(request, item.default_settings) - if high_res is not None: - s = high_res_settings(s) + s = _resolve_settings(request, item.default_settings, high_res=high_res is not None) input_width, input_height = ( center_cropped_size(source_width, source_height, aspect) if not cutout @@ -1305,64 +1330,362 @@ def recipe_run_frames( stage_2_ic_lora=s.stage_2_ic_lora, tiling=s.tiling, ) + return width, height, resolution_factor, s + + def preflight_recipe_tile_sizes( + self, + *, + item: IcLoraCatalogItem, + video: AssetRecord, + stored: IcLoraRecipeStoredParams, + source_fps: float | None, + upscale: bool, + cutout: bool, + tile_sizes: Sequence[IcLoraTilePreset], + max_windows: Sequence[int], + carries: Sequence[int] = (), + ) -> IcLoraTilePreflightResponse: + """Advisory verdict per tile size and per window, from the create-time gate of each one. + + A refusal is returned in its cell, never raised, so the form can disable the option + and show why. A job the budget mode admits on a bet returns the bet in its cell. + """ + budget_mode = self._local_job_filter(total_only=True).budget_mode + + def verdict(candidate: IcLoraRecipeStoredParams) -> IcLoraPreflightVerdict: + try: + risk = self.preflight_queued_recipe_job( + item=item, + video=video, + stored=candidate, + source_fps=source_fps, + upscale=upscale, + cutout=cutout, + ) + except HTTPError as exc: + return IcLoraPreflightVerdict(ok=False, message=exc.detail, code=exc.code) + if risk is None: + return IcLoraPreflightVerdict(ok=True) + return IcLoraPreflightVerdict( + ok=True, + message=risk.message, + tier=risk.tier, + over_gib=risk.over_gib, + over_ram_gb=risk.over_ram_gb, + shortfall_kind=risk.shortfall_kind, + readout=risk.readout, + ) + + def auto_plan(**unset: None) -> RecipeRunPlan | None: + try: + return self.preflight_queued_recipe_plan( + item=item, + video=video, + stored=stored.model_copy(update=unset), + source_fps=source_fps, + upscale=upscale, + cutout=cutout, + ) + except HTTPError: + return None # Auto is refused: the cells carry the refusal, and the label names none. + + defaults = _tiling_defaults(item, stored) + # Each Auto reads the form as it is: Auto chunk length keeps the carry the form holds, and + # Auto carry keeps the chunk length. A control that is on Auto leaves the other pins alone. + auto_window = auto_plan(maxWindowFrames=None) + auto_carry = auto_plan(carryFrames=None) + if auto_window is not None: + defaults = defaults.model_copy( + update={ + "auto": IcLoraAutoSinglePass() + if auto_window.window is None + else IcLoraAutoWindowed(frames=auto_window.window) + } + ) + if auto_carry is not None: + defaults = defaults.model_copy(update={"carryFrames": auto_carry.carry}) + + return IcLoraTilePreflightResponse( + cells=[ + IcLoraTilePreflightCell( + tileSize=tile_size, + **verdict( + stored.model_copy(update={"tilingSize": None if tile_size == "standard" else tile_size}) + ).model_dump(), + ) + for tile_size in tile_sizes + ], + maxWindowCells=[ + IcLoraMaxWindowPreflightCell( + maxWindowFrames=window, + **verdict(stored.model_copy(update={"maxWindowFrames": window})).model_dump(), + ) + for window in max_windows + ], + carryCells=[ + IcLoraCarryPreflightCell( + carryFrames=carry, **verdict(stored.model_copy(update={"carryFrames": carry})).model_dump() + ) + for carry in carries + ], + defaults=defaults, + budgetMode=budget_mode, + ) + + def recipe_run_frames( + self, + *, + ic_lora_id: str, + source_width: int, + source_height: int, + stored: IcLoraRecipeStoredParams, + clip_frames: int, + cutout: bool = False, + upscale: bool = False, + allowance: RiskAllowance | None = None, + ) -> tuple[int, GenerationRisk | None]: + """The frame count and the risk of ``recipe_run_plan``.""" + plan = self.recipe_run_plan( + ic_lora_id=ic_lora_id, + source_width=source_width, + source_height=source_height, + stored=stored, + clip_frames=clip_frames, + cutout=cutout, + upscale=upscale, + allowance=allowance, + ) + return plan.frames, plan.risk + + def recipe_run_plan( + self, + *, + ic_lora_id: str, + source_width: int, + source_height: int, + stored: IcLoraRecipeStoredParams, + clip_frames: int, + cutout: bool = False, + upscale: bool = False, + allowance: RiskAllowance | None = None, + ) -> RecipeRunPlan: + """Frame count a queued Home recipe runs for a clip of ``clip_frames`` frames, its risk, and its window. + + The count snaps UP, so no frame is dropped: the recipe repeats the last frame to + reach it and cuts the output back. When that count is refused or carries a risk, and + the count snapped DOWN is strictly better, the job runs the smaller count, and the + pipeline drops the last frames as it did before. From best to worst: clean, an + ``unmeasured`` risk (a fence that moves with the frame count), an ``over`` risk, a + 422. Brave mode returns a risk in place of the 422. When the snapped-down count + is no better, or is refused itself, the snapped-up count runs with its risk, or its 422 + propagates. The check asks "will it ever fit" (``total_only``). The create-time + preflight and the run use this one method, but they count the clip frames in two ways + (stored count with resample math, and the cropped file itself), so the counts can + differ by a frame. The run gates the count it reads from the file. + + An executor passes ``allowance`` from the stored annotation, so a mode change never + gates a queued job again. + + ``source_width`` and ``source_height`` are the size of the file the user picked. The + run reads the clip after ``center_crop_video``, so the canvas comes from the cropped + size. The cutout recipe keeps the whole frame and always pads up, so it uses the + uncropped size and has no snapped-down fallback. + """ + item = self._catalog.get_ic_lora(ic_lora_id) + if item is None: + raise HTTPError(404, "UNKNOWN_IC_LORA") + job_filter = self._local_job_filter(total_only=True) + local_model_id = resolve_job_local_model_id(self.models_dir, stored.model) + width, height, resolution_factor, s = self._recipe_canvas( + item, + local_model_id=local_model_id, + resolution=stored.resolution, + source_width=source_width, + source_height=source_height, + audio_mode=stored.audioMode, + lora_strength=stored.loras[0].scale, + cutout=cutout, + upscale=upscale, + tile_overlap=stored.tilingOverlap, + tile_size=stored.tilingSize, + carry_frames=stored.carryFrames, + max_window_frames=stored.maxWindowFrames, + ) snapped_up = snap_up_to_frame_grid(clip_frames, floor=9) snapped_down = snap_to_frame_grid(clip_frames, floor=9) + stills = catalog_preview_stills(item) - def check(frame_count: int) -> GenerationRisk | None: + def decide(frame_count: int) -> Admission: # Queued admission gates on total ("will it ever fit"): a running job # depresses free, and the queue exists to wait for a free slot. The # optional look still is priced as present, so execute never costs more. - _, risk = self._ic_lora_job( + return self._decide_ic_lora_admission( width, height, frame_count=frame_count, stage_mode=s.stage_mode, resolution_factor=resolution_factor, + job_filter=job_filter, ic_lora_id=item.id, - stills=catalog_preview_stills(item), + stills=stills, tiling=s.tiling, - total_only=True, - allow_risk=risk_allowance, - unmeasured_bet=unmeasured_bet, + allowance=allowance, ) - return risk - def badness(risk: GenerationRisk | None) -> int: - if risk is None: + def badness(admission: Admission) -> int: + if isinstance(admission, Refused): + return 3 + if admission.risk is None: return 0 - return 1 if risk.tier == "unmeasured" else 2 - - def probe(frame_count: int) -> tuple[GenerationRisk | None, HTTPError | None]: - try: - return check(frame_count), None - except HTTPError as exc: - return None, exc + return 1 if admission.risk.tier == "unmeasured" else 2 + + def finish(frame_count: int, admission: Admission) -> RecipeRunPlan: + if isinstance(admission, Refused): + message, code = dropped_duration_message_and_code(admission.reject, job_filter) + raise HTTPError(422, message, code=code) + return RecipeRunPlan( + frames=frame_count, + risk=admission.risk, + window=admission.load.chunk_pixel_frames, + carry=ic_lora_carry_frames(picked_carry_tiling(s.tiling, admission.priced)), + ) can_snap_down = not cutout and snapped_down < snapped_up - refused = 3 # worse than any risk - up_risk, up_error = probe(snapped_up) - if up_error is not None and not can_snap_down: - raise up_error - up_badness = refused if up_error is not None else badness(up_risk) + up_admission = decide(snapped_up) + up_badness = badness(up_admission) if up_badness == 0 or not can_snap_down: - return snapped_up, up_risk - down_risk, down_error = probe(snapped_down) - if down_error is not None or badness(down_risk) >= up_badness: + return finish(snapped_up, up_admission) + down_admission = decide(snapped_down) + if badness(down_admission) >= up_badness: # No better count. Keep the snapped-up count, so no frame drops: it runs with its # risk, or its refusal is the answer. A refused snapped-down count never # replaces a runnable snapped-up count. - if up_error is not None: - raise up_error - return snapped_up, up_risk - if up_error is not None: - reason = str(up_error.detail) + return finish(snapped_up, up_admission) + if isinstance(up_admission, Refused): + reason, _ = dropped_duration_message_and_code(up_admission.reject, job_filter) else: - reason = f"{up_risk.tier} risk" if up_risk is not None else "" + reason = f"{up_admission.risk.tier} risk" if up_admission.risk is not None else "" logger.warning( "[ic-lora] %d frames over budget (%s): running %d, dropping the last %d", snapped_up, reason, snapped_down, clip_frames - snapped_down, ) - return snapped_down, down_risk + return finish(snapped_down, down_admission) + + def recipe_memory( + self, recipe_id: str, req: IcLoraRecipeMemoryRequest + ) -> IcLoraRecipeMemoryResponse: + """Memory advice for a Home video recipe form. Never gates; create stays authoritative. + + Before a clip is picked, each offered cell reports the longest clip whose job loads, for + a 16:9 clip of that cell's size. With a clip, the selected cell reports its ask for that + clip, at the frame count ``recipe_run_frames`` would run. + """ + recipe = get_ic_lora_recipe(recipe_id) + item = None if recipe is None else self._catalog.get_ic_lora(recipe.catalog_id) + if recipe is None or recipe.kind != "video" or item is None: + raise HTTPError(404, "UNKNOWN_IC_LORA") + job_filter = self._local_job_filter(total_only=True) + local_model_id = resolve_job_local_model_id(self.models_dir, req.model) + base = item.default_settings + high_res_runs = ( + high_res_flag_satisfied(item.id, flag_enabled=self._high_res_enabled()) + and base.stage_mode is not IcLoraStageMode.STAGE_2_LORA + ) + + def price( + resolution: IcLoraRecipeResolution, width: int, height: int, frames: int + ) -> PricedJob | None: + if high_res_cell(resolution) is not None and not high_res_runs: + return None + try: + canvas_w, canvas_h, factor, s = self._recipe_canvas( + item, + local_model_id=local_model_id, + resolution=resolution, + source_width=width, + source_height=height, + audio_mode=req.audioMode or base.audio_mode, + lora_strength=base.lora_strength if req.scale is None else req.scale, + cutout=recipe.cutout, + upscale=recipe.upscales_to_cell, + tile_overlap=req.tilingOverlap, + tile_size=req.tilingSize, + carry_frames=req.carryFrames, + max_window_frames=req.maxWindowFrames, + ) + except HTTPError: + return None + return self._price_ic_lora( + canvas_w, + canvas_h, + frame_count=frames, + stage_mode=s.stage_mode, + resolution_factor=factor, + job_filter=job_filter, + ic_lora_id=item.id, + stills=catalog_preview_stills(item), + tiling=s.tiling, + ) + + def loads(priced: PricedJob | None) -> bool: + if priced is None: + return False + return admits_within_device_memory(priced, job_filter.budget_mode) + + # A clip at the cap snaps down to run when its snapped-up count does not load. + full_frames = snap_to_frame_grid(MAX_IC_LORA_INPUT_FRAMES, floor=9) + grid = range(snap_up_to_frame_grid(MAX_IC_LORA_INPUT_FRAMES, floor=9), 8, -8) + cells: list[IcLoraCellFit] = [] + for resolution in dict.fromkeys(req.cells): + width, height = _STAND_IN_SOURCE[resolution] + longest = next( + (frames for frames in grid if loads(price(resolution, width, height, frames))), + 0, + ) + cells.append( + IcLoraCellFit( + resolution=resolution, + max_frames=min(longest, MAX_IC_LORA_INPUT_FRAMES), + full=longest >= full_frames, + ) + ) + + selected = None + if req.source is not None: + source = req.source + up = price( + req.resolution, + source.width, + source.height, + snap_up_to_frame_grid(source.frames, floor=9), + ) + down = ( + None + if recipe.cutout + else price( + req.resolution, + source.width, + source.height, + snap_to_frame_grid(source.frames, floor=9), + ) + ) + chosen = up if loads(up) or not loads(down) else down + if chosen is not None: + selected = job_memory_ask( + chosen, + route=budget_route("iclora", job_filter.profile), + system=job_filter.profile.system, + machine_factor=( + job_filter_machine_factor(job_filter) if loads(chosen) else None + ), + conv_vae=job_filter.conv_vae, + ) + return IcLoraRecipeMemoryResponse( + memory=memory_capacity(job_filter), + max_input_frames=MAX_IC_LORA_INPUT_FRAMES, + cells=cells, + selected=selected, + ) def preflight_queued_synthesized_job( self, @@ -1395,8 +1718,9 @@ def preflight_queued_synthesized_job( stage_2_ic_lora=s.stage_2_ic_lora, ) # Queued admission gates on total ("will it ever fit"): a running job - # depresses free, and the queue exists to wait for a free slot. - _, risk = self._ic_lora_job( + # depresses free, and the queue exists to wait for a free slot. The + # optional look still is priced as present, so execute never costs more. + return self._ic_lora_job( width, height, frame_count=compute_num_frames(stored.duration, int(stored.fps)), @@ -1406,8 +1730,7 @@ def preflight_queued_synthesized_job( stills=catalog_preview_stills(item), tiling=s.tiling, total_only=True, - ) - return risk + ).risk def generate(self, req: IcLoraGenerateRequest) -> IcLoraGenerateResponse: # Hardware viability first: local downloads are disabled on an unsupported @@ -1512,7 +1835,7 @@ def generate(self, req: IcLoraGenerateRequest) -> IcLoraGenerateResponse: budget_frames = self._frame_count_after_fps_override( frame_count, fps, req.fps_override ) - job, _ = self._ic_lora_job( + admitted = self._ic_lora_job( width, height, frame_count=snap_to_frame_grid(budget_frames, floor=9), @@ -1520,13 +1843,16 @@ def generate(self, req: IcLoraGenerateRequest) -> IcLoraGenerateResponse: resolution_factor=resolution_factor, allow_evict_retry=True, ) + job = admitted.load # Before the pipeline claims the GPU. canny/depth get a conditioning system # prompt; a fully custom IC-LoRA falls back to the generic rewrite. + nag_decision = self._decide_nag(req, model_id=None) resolved_prompt = self._prompt_enhancement.resolve_for_generation( req.prompt, provenance=req.prompt_provenance, generation_seed=seed, conditioning_type=None if req.conditioning_type == "custom" else req.conditioning_type, + negative_prompt=nag_decision.enhancer_negative, ) prompt = resolved_prompt.prompt t_load_start = time.perf_counter() @@ -1540,7 +1866,7 @@ def generate(self, req: IcLoraGenerateRequest) -> IcLoraGenerateResponse: t_load_end = time.perf_counter() logger.info("[ic-lora] Pipeline load: %.2fs", t_load_end - t_load_start) - self._generation.start_generation(generation_id) + self._generation.start_generation(generation_id, ran=admitted.envelope) self._generation.update_progress("loading_model", 5, 0, 1) encoding_method = "local" if self._text.should_use_local_encoding() else "api" @@ -1548,6 +1874,7 @@ def generate(self, req: IcLoraGenerateRequest) -> IcLoraGenerateResponse: self._text.prepare_text_encoding(prompt, enhance_prompt=resolved_prompt.enhance_via_api) t_text_end = time.perf_counter() logger.info("[ic-lora] Text encoding (%s): %.2fs", encoding_method, t_text_end - t_text_start) + nag = self._resolve_nag(req, model_id=None) self._generation.raise_if_cancelled() if req.conditioning_type != "custom": @@ -1653,6 +1980,7 @@ def generate(self, req: IcLoraGenerateRequest) -> IcLoraGenerateResponse: else None ), mute_audio=settings.audio_mode == "off", + nag=nag, ) t_inference_end = time.perf_counter() logger.info("[ic-lora] Inference: %.2fs", t_inference_end - t_inference_start) @@ -1667,7 +1995,8 @@ def generate(self, req: IcLoraGenerateRequest) -> IcLoraGenerateResponse: t_inference_end - t_inference_start, ) - self._complete_or_drop_cancelled(output_path) + # Priced before preprocessing, so the frames that ran may not match the envelope. + self._complete_or_drop_cancelled(output_path, ran=None) return IcLoraGenerateCompleteResponse(status="complete", video_path=str(output_path)) except HTTPError: diff --git a/backend/handlers/image_generation_handler.py b/backend/handlers/image_generation_handler.py index c0294ad37..26f2c9bce 100644 --- a/backend/handlers/image_generation_handler.py +++ b/backend/handlers/image_generation_handler.py @@ -19,12 +19,16 @@ GenerateImageCompleteResponse, GenerateImageRequest, GenerateImageResponse, + ImageGenerationStatusResponse, ) from handlers.base import StateHandlerBase from handlers.generation_handler import GenerationHandler from handlers.pipelines_handler import PipelinesHandler +from runtime_config.model_download_specs import IMG_GEN_MODEL_CP_ID, is_cp_downloaded +from services.features.image.grid import floor_to_image_grid +from services.features.image.text_to_image import image_generation_status from services.generation_interrupt import is_cancel_exception -from services.interfaces import ZitAPIClient +from services.interfaces import ImageGenerationPipeline, ZitAPIClient from server_utils.heartbeat import log_heartbeat from server_utils.media_validation import validate_image_file from server_utils.oriented_image import open_oriented_rgb @@ -38,6 +42,26 @@ logger = logging.getLogger(__name__) +def text_to_image_on_pipeline( + pipeline: ImageGenerationPipeline, + *, + prompt: str, + width: int, + height: int, + num_inference_steps: int, + seed: int, +) -> PILImage.Image: + result = pipeline.generate( + prompt=prompt, + height=height, + width=width, + guidance_scale=0.0, + num_inference_steps=num_inference_steps, + seed=seed, + ) + return result.images[0] + + class ImageGenerationHandler(StateHandlerBase): def __init__( self, @@ -53,11 +77,23 @@ def __init__( self._pipelines = pipelines_handler self._zit_api_client = zit_api_client + def get_status(self) -> ImageGenerationStatusResponse: + """What image generation can do now: the provider choice and what blocks each one.""" + settings = self.state.app_settings + return image_generation_status( + force_api=self.config.force_api_generations, + default_to_fal=should_image_generate_with_fal_api( + force_api_generations=self.config.force_api_generations, settings=settings + ), + has_fal_key=bool(settings.fal_api_key.strip()), + local_model_downloaded=lambda: is_cp_downloaded(self.models_dir, IMG_GEN_MODEL_CP_ID), + ) + def generate(self, req: GenerateImageRequest) -> GenerateImageResponse: with self._generation.reserved_generation_start(): - width = (req.width // 16) * 16 - height = (req.height // 16) * 16 + width = floor_to_image_grid(req.width) + height = floor_to_image_grid(req.height) num_images = max(1, min(12, req.numImages)) seed = self._resolve_seed() @@ -203,15 +239,14 @@ def generate_image( self._generation.update_progress("inference", 15, 0, num_inference_steps) def generate_one(seed_i: int) -> PILImage.Image: - result = image_generation_pipeline.generate( + return text_to_image_on_pipeline( + image_generation_pipeline, prompt=prompt, - height=height, width=width, - guidance_scale=0.0, + height=height, num_inference_steps=num_inference_steps, seed=seed_i, ) - return result.images[0] with log_heartbeat(f"zit image {width}x{height}"): return self._run_local_batch(num_images, seed, "zit_image", generate_one) diff --git a/backend/handlers/image_prompt_plan.py b/backend/handlers/image_prompt_plan.py new file mode 100644 index 000000000..8c7cb176d --- /dev/null +++ b/backend/handlers/image_prompt_plan.py @@ -0,0 +1,54 @@ +"""The prompt a queued fal image job submits, and whether fal expands it. + +The rewrite runs where capacity is free (see ``PromptEnhancementHandler.rewrite_image_prompt``): + +- Auto-enhance off, or the prompt already enhanced: no rewrite, no expansion. +- Local Gemma is downloaded and the GPU is idle: Gemma rewrites, fal does not expand. +- Local Gemma is downloaded and the GPU is busy: fal expands. +- No Gemma, Gemini set up: Gemini rewrites, fal does not expand. +- Nothing available, or the rewrite fails: fal expands. + +fal bills its expansion per request, so it is the fallback, never the first choice. +""" + +from __future__ import annotations + +from collections.abc import Callable +from contextlib import AbstractContextManager +from dataclasses import dataclass + +from api_types import PromptProvenance, PromptRewriteSource +from handlers.prompt_enhancement_handler import PromptEnhancementHandler + + +@dataclass(frozen=True) +class FalImagePrompt: + prompt: str + expand_on_provider: bool + rewrite_source: PromptRewriteSource | None + + +def plan_fal_image_prompt( + enhancement: PromptEnhancementHandler, + prompt: str, + *, + provenance: PromptProvenance, + generation_seed: int, + explicit_generation_seed: bool, + lease_idle_gpu: Callable[[], AbstractContextManager[bool]], + raise_if_cancelled: Callable[[], None], +) -> FalImagePrompt: + """Plan the prompt. ``raise_if_cancelled`` runs before each step that takes long.""" + rewrite = enhancement.rewrite_image_prompt( + prompt, + provenance=provenance, + generation_seed=generation_seed, + explicit_generation_seed=explicit_generation_seed, + lease_gpu=lease_idle_gpu, + raise_if_cancelled=raise_if_cancelled, + ) + if rewrite.source is not None: + return FalImagePrompt(rewrite.prompt, expand_on_provider=False, rewrite_source=rewrite.source) + if not rewrite.wanted: + return FalImagePrompt(prompt, expand_on_provider=False, rewrite_source=None) + return FalImagePrompt(prompt, expand_on_provider=True, rewrite_source="fal_expansion") diff --git a/backend/handlers/lora_catalog_handler.py b/backend/handlers/lora_catalog_handler.py index e153d1900..dd8ac06a9 100644 --- a/backend/handlers/lora_catalog_handler.py +++ b/backend/handlers/lora_catalog_handler.py @@ -9,7 +9,6 @@ from pathlib import Path from threading import RLock from typing import TYPE_CHECKING, Generic, TypeVar -from uuid import uuid4 from _routes._errors import HTTPError from api_types import ( @@ -25,10 +24,10 @@ LoraListItem, LoraListResponse, ) -from handlers.base import StateHandlerBase, with_state_lock +from handlers.base import StateHandlerBase from handlers.checkpoint_files import commit_staged_checkpoint, stage_checkpoint +from handlers.download_sessions import DownloadSessionTracker from handlers.hf_auth_utils import optional_hf_token, require_hf_token -from runtime_config.ic_lora_high_res import HIGH_RES_ONLY_IC_LORAS from runtime_config.ic_lora_job_budget import with_budgeted_duration_controls from runtime_config.model_download_specs import ( catalog_item_visible_for_installed_ltx, @@ -38,41 +37,25 @@ missing_checkpoints, resolve_catalog_staging_dir, resolve_catalog_staging_root, - resolve_lora_path, resolve_ic_lora_path, + resolve_lora_path, ) from services.interfaces import GpuInfo, ModelDownloader, TaskRunner from services.lora_catalog import LoraCatalogProvider from services.lora_catalog.media_urls import with_resolved_media -from state.app_state_types import ( - AppState, - CatalogDownloadSession, - DownloadSessionComplete, - DownloadSessionError, - DownloadSessionId, - DownloadSessionResult, -) +from state.app_state_types import AppState if TYPE_CHECKING: from runtime_config.runtime_config import RuntimeConfig logger = logging.getLogger(__name__) -# Cap retained completed sessions so a long-running app doesn't accrue them forever. -# The client only needs a terminal status once; oldest-out is fine (dicts keep insertion order). -_MAX_COMPLETED_SESSIONS = 32 - -ProgressResponseT = TypeVar("ProgressResponseT", IcLoraDownloadProgressResponse, LoraDownloadProgressResponse) - - -def _record_completed( - completed: dict[DownloadSessionId, DownloadSessionResult], - session_id: DownloadSessionId, - result: DownloadSessionResult, -) -> None: - completed[session_id] = result - while len(completed) > _MAX_COMPLETED_SESSIONS: - completed.pop(next(iter(completed))) +ProgressResponseT = TypeVar( + "ProgressResponseT", IcLoraDownloadProgressResponse, LoraDownloadProgressResponse +) +ActiveResponseT = TypeVar( + "ActiveResponseT", ActiveIcLoraDownloadResponse, ActiveLoraDownloadResponse +) def _lookup_ic_lora(catalog: LoraCatalogProvider, item_id: str) -> LoraCatalogItem | None: @@ -83,12 +66,6 @@ def _lookup_lora(catalog: LoraCatalogProvider, item_id: str) -> LoraCatalogItem return catalog.get_lora(item_id) -def _session_progress_pct(session: CatalogDownloadSession) -> float: - if not session.expected_bytes: - return 0.0 - return min(99.0, session.downloaded_bytes / session.expected_bytes * 100) - - def _ic_lora_progress( status: CatalogDownloadStatus, *, @@ -132,41 +109,14 @@ def _lora_progress( @dataclass(frozen=True) -class _CatalogKind(Generic[ProgressResponseT]): - """Per-kind plumbing so IC-LoRA and plain-LoRA downloads share one implementation. - - Each kind keeps its own state slot (so an IC-LoRA and a plain-LoRA download can run at - once) and its own wire response type; everything else is identical. - """ +class _CatalogKind(Generic[ProgressResponseT, ActiveResponseT]): + """Per-kind plumbing so IC-LoRA and plain-LoRA downloads share one implementation.""" - session_attr: str # AppState attribute holding the active CatalogDownloadSession | None - completed_attr: str # AppState attribute holding the completed-sessions dict task_name: str not_found: str - resolve_path: Callable[[Path, str, str], Path] # (models_dir, item_id, filename) -> final file path + resolve_path: Callable[[Path, str, str], Path] lookup: Callable[[LoraCatalogProvider, str], LoraCatalogItem | None] - build_progress: Callable[..., ProgressResponseT] - - -_IC_LORA: _CatalogKind[IcLoraDownloadProgressResponse] = _CatalogKind( - session_attr="ic_lora_download_session", - completed_attr="completed_ic_lora_download_sessions", - task_name="ic-lora-download", - not_found="UNKNOWN_IC_LORA", - resolve_path=resolve_ic_lora_path, - lookup=_lookup_ic_lora, - build_progress=_ic_lora_progress, -) - -_PLAIN_LORA: _CatalogKind[LoraDownloadProgressResponse] = _CatalogKind( - session_attr="lora_download_session", - completed_attr="completed_lora_download_sessions", - task_name="lora-download", - not_found="UNKNOWN_LORA", - resolve_path=resolve_lora_path, - lookup=_lookup_lora, - build_progress=_lora_progress, -) + tracker: DownloadSessionTracker[ProgressResponseT, ActiveResponseT] class LoraCatalogHandler(StateHandlerBase): @@ -179,30 +129,52 @@ def __init__( task_runner: TaskRunner, config: "RuntimeConfig", gpu_info: GpuInfo, - high_res_enabled: Callable[[], bool] = lambda: False, ) -> None: super().__init__(state, lock, config, gpu_info=gpu_info) - self._high_res_enabled = high_res_enabled self._catalog = catalog self._model_downloader = model_downloader self._task_runner = task_runner + self._ic_lora = _CatalogKind( + task_name="ic-lora-download", + not_found="UNKNOWN_IC_LORA", + resolve_path=resolve_ic_lora_path, + lookup=_lookup_ic_lora, + tracker=DownloadSessionTracker( + state, + lock, + session_attr="ic_lora_download_session", + completed_attr="completed_ic_lora_download_sessions", + build_progress=_ic_lora_progress, + build_active=lambda session_id, item_id, progress: ActiveIcLoraDownloadResponse( + session_id=session_id, ic_lora_id=item_id, progress=progress + ), + ), + ) + self._plain_lora = _CatalogKind( + task_name="lora-download", + not_found="UNKNOWN_LORA", + resolve_path=resolve_lora_path, + lookup=_lookup_lora, + tracker=DownloadSessionTracker( + state, + lock, + session_attr="lora_download_session", + completed_attr="completed_lora_download_sessions", + build_progress=_lora_progress, + build_active=lambda session_id, item_id, progress: ActiveLoraDownloadResponse( + session_id=session_id, lora_id=item_id, progress=progress + ), + ), + ) # A crash leaves the staging folder of a session. No download runs yet, so all of it is stale. shutil.rmtree(resolve_catalog_staging_root(self.models_dir), ignore_errors=True) # --- listing --- - # Catalog download.variants is always non-empty; the first variant is the default - # checkpoint (preferred when listing "downloaded", when generation omits variant_id, - # and when a download request omits variant_id). def list_ic_loras(self, fresh: bool = False) -> IcLoraListResponse: catalog = self._catalog.get_catalog() - # Display on total: duration options must not drop total-fitting cells - # just because free is momentarily depressed; generate stays authoritative. job_filter = self._local_job_filter(total_only=True) items: list[IcLoraListItem] = [] - high_res = self._high_res_enabled() for r in catalog.ic_loras: - if r.id in HIGH_RES_ONLY_IC_LORAS and not high_res: - continue if not fresh and not catalog_item_visible_for_installed_ltx(r.supported_models, self.models_dir): continue variant_ids = downloaded_ic_lora_variant_ids( @@ -228,7 +200,9 @@ def list_loras(self, fresh: bool = False) -> LoraListResponse: catalog = self._catalog.get_catalog() items: list[LoraListItem] = [] for item in catalog.loras: - if not fresh and not catalog_item_visible_for_installed_ltx(item.supported_models, self.models_dir): + if not fresh and not catalog_item_visible_for_installed_ltx( + item.supported_models, self.models_dir + ): continue variant_ids = downloaded_lora_variant_ids( self.models_dir, item.id, [(v.id, v.filename) for v in item.download.variants] @@ -244,13 +218,6 @@ def list_loras(self, fresh: bool = False) -> LoraListResponse: # --- download (shared between both kinds) --- def _resolve_download_token(self, *, requires_hf_login: bool, use_hf_auth: bool) -> str | None: - """Token to attach to a catalog download. - - Gated items (a per-entry ``requires_hf_login``) must authenticate — ``require_hf_token`` - raises 403 if not signed in. Otherwise ``use_hf_auth`` is opt-in: attach the in-app token - when signed in, but still allow anonymous public downloads when signed out (we never force - sign-in for a public repo). - """ if requires_hf_login: return require_hf_token(self.state, self._lock) if use_hf_auth: @@ -259,7 +226,7 @@ def _resolve_download_token(self, *, requires_hf_login: bool, use_hf_auth: bool) def _start_download( self, - kind: _CatalogKind[ProgressResponseT], + kind: _CatalogKind[ProgressResponseT, ActiveResponseT], item_id: str, use_hf_auth: bool, variant_id: str | None = None, @@ -269,46 +236,24 @@ def _start_download( item = kind.lookup(self._catalog, item_id) if item is None: raise HTTPError(404, kind.not_found) - if kind is _IC_LORA and item.id in HIGH_RES_ONLY_IC_LORAS and not self._high_res_enabled(): - # Hidden from the list without the flag, so a download is unknown too. A create - # for a known recipe answers 422 HIGH_RES_NOT_ENABLED instead: the id exists there. - raise HTTPError(404, kind.not_found) variant = item.download.resolve_variant(variant_id) if variant is None: raise HTTPError(404, "UNKNOWN_DOWNLOAD_VARIANT") - # Resolve the token first (before opening a session): a gated item can raise 403 here. hf_token = self._resolve_download_token( requires_hf_login=item.requires_hf_login, use_hf_auth=use_hf_auth ) dest = kind.resolve_path(self.models_dir, item.id, variant.filename) - # An entry that reads processor models (Video Guide) fetches the missing ones after its - # file. A retry keeps a file that is already installed. fetch_file = not dest.exists() missing_cps = missing_checkpoints(self.models_dir, item.requires_checkpoints) - with self._lock: - if getattr(self.state, kind.session_attr) is not None: - raise HTTPError(409, "DOWNLOAD_ALREADY_RUNNING") - session_id = DownloadSessionId(uuid4().hex) - setattr( - self.state, - kind.session_attr, - CatalogDownloadSession( - id=session_id, - item_id=item_id, - downloaded_bytes=0, - expected_bytes=(variant.size_bytes if fetch_file else 0) - + sum(get_model_cp_spec(cp).expected_size_bytes for cp in missing_cps), - ), - ) + expected_bytes = (variant.size_bytes if fetch_file else 0) + sum( + get_model_cp_spec(cp).expected_size_bytes for cp in missing_cps + ) + session_id = kind.tracker.open(item_id, expected_bytes) def _progress_from(base: int) -> Callable[[int], None]: - return lambda n: self._update_progress(kind, session_id, base + n) + return lambda n: kind.tracker.update_progress(session_id, base + n) def _work() -> None: - # Stage into this session's own folder and atomically move on success, so an interrupted - # download never leaves a partial file at the final path (where it would report - # "downloaded" and get used by generation). The model download clears its own staging - # folder, so the two never share one. staging_dir = resolve_catalog_staging_dir(self.models_dir, session_id) staging_dir.mkdir(parents=True, exist_ok=True) try: @@ -326,82 +271,54 @@ def _work() -> None: finished_bytes = variant.size_bytes for cp in missing_cps: stage_checkpoint( - self._model_downloader, staging_dir, cp, hf_token, _progress_from(finished_bytes) + self._model_downloader, + staging_dir, + cp, + hf_token, + _progress_from(finished_bytes), ) commit_staged_checkpoint(self.models_dir, staging_dir, cp) finished_bytes += get_model_cp_spec(cp).expected_size_bytes finally: shutil.rmtree(staging_dir, ignore_errors=True) - self._finish(kind, session_id) + kind.tracker.finish(session_id) + + def _fail(exc: Exception) -> None: + logger.error("%s failed: %s", kind.task_name, exc) + kind.tracker.fail(session_id, str(exc)) self._task_runner.run_background( _work, task_name=kind.task_name, - on_error=lambda exc: self._fail(kind, session_id, str(exc)), + on_error=_fail, daemon=True, ) return CatalogDownloadStartResponse(status="started", sessionId=session_id) - @with_state_lock - def _update_progress(self, kind: _CatalogKind[ProgressResponseT], session_id: DownloadSessionId, downloaded: int) -> None: - s: CatalogDownloadSession | None = getattr(self.state, kind.session_attr) - if s is not None and s.id == session_id: - s.downloaded_bytes = downloaded - - def _completed(self, kind: _CatalogKind[ProgressResponseT]) -> dict[DownloadSessionId, DownloadSessionResult]: - return getattr(self.state, kind.completed_attr) - - @with_state_lock - def _finish(self, kind: _CatalogKind[ProgressResponseT], session_id: DownloadSessionId) -> None: - _record_completed(self._completed(kind), session_id, DownloadSessionComplete()) - setattr(self.state, kind.session_attr, None) - - @with_state_lock - def _fail(self, kind: _CatalogKind[ProgressResponseT], session_id: DownloadSessionId, error: str) -> None: - logger.error("%s failed: %s", kind.task_name, error) - _record_completed(self._completed(kind), session_id, DownloadSessionError(error_message=error)) - setattr(self.state, kind.session_attr, None) - - @with_state_lock - def _get_progress(self, kind: _CatalogKind[ProgressResponseT], session_id: str) -> ProgressResponseT: - sid = DownloadSessionId(session_id) - s: CatalogDownloadSession | None = getattr(self.state, kind.session_attr) - if s is not None and s.id == sid: - return kind.build_progress( - "downloading", - item_id=s.item_id, - downloaded_bytes=s.downloaded_bytes, - expected_bytes=s.expected_bytes, - progress=_session_progress_pct(s), - speed_bytes_per_sec=s.speed_bytes_per_sec, - ) - result = self._completed(kind).get(sid) - if result is None: - raise HTTPError(404, "UNKNOWN_DOWNLOAD_SESSION") - if isinstance(result, DownloadSessionError): - return kind.build_progress("error", error=result.error_message) - return kind.build_progress("complete", progress=100.0) - # --- thin per-kind entry points (the routes call these) --- def start_ic_lora_download( self, ic_lora_id: str, use_hf_auth: bool = False, variant_id: str | None = None ) -> CatalogDownloadStartResponse: - return self._start_download(_IC_LORA, ic_lora_id, use_hf_auth, variant_id=variant_id) + return self._start_download( + self._ic_lora, ic_lora_id, use_hf_auth, variant_id=variant_id + ) def get_ic_lora_download_progress(self, session_id: str) -> IcLoraDownloadProgressResponse: - return self._get_progress(_IC_LORA, session_id) + return self._ic_lora.tracker.get_progress(session_id) def start_lora_download( self, lora_id: str, use_hf_auth: bool = False, variant_id: str | None = None ) -> CatalogDownloadStartResponse: - return self._start_download(_PLAIN_LORA, lora_id, use_hf_auth, variant_id=variant_id) + return self._start_download( + self._plain_lora, lora_id, use_hf_auth, variant_id=variant_id + ) def get_lora_download_progress(self, session_id: str) -> LoraDownloadProgressResponse: - return self._get_progress(_PLAIN_LORA, session_id) + return self._plain_lora.tracker.get_progress(session_id) def _delete_installation( self, - kind: _CatalogKind[ProgressResponseT], + kind: _CatalogKind[ProgressResponseT, ActiveResponseT], item_id: str, variant_id: str | None = None, ) -> None: @@ -413,10 +330,7 @@ def _delete_installation( variant = item.download.resolve_variant(variant_id) if variant is None: raise HTTPError(404, "UNKNOWN_DOWNLOAD_VARIANT") - with self._lock: - session: CatalogDownloadSession | None = getattr(self.state, kind.session_attr) - if session is not None and session.item_id == item_id: - raise HTTPError(409, "DOWNLOAD_ALREADY_RUNNING") + kind.tracker.refuse_if_item_active(item_id) path = kind.resolve_path(self.models_dir, item.id, variant.filename) if not path.is_file(): raise HTTPError(404, "LORA_NOT_INSTALLED") @@ -426,41 +340,13 @@ def _delete_installation( parent.rmdir() def delete_lora(self, lora_id: str, variant_id: str | None = None) -> None: - self._delete_installation(_PLAIN_LORA, lora_id, variant_id) + self._delete_installation(self._plain_lora, lora_id, variant_id) def delete_ic_lora(self, ic_lora_id: str, variant_id: str | None = None) -> None: - self._delete_installation(_IC_LORA, ic_lora_id, variant_id) + self._delete_installation(self._ic_lora, ic_lora_id, variant_id) - @with_state_lock def get_active_lora_download(self) -> ActiveLoraDownloadResponse: - """The in-flight plain-LoRA download, if any, so a remounting screen can reattach. - - Returns nulls when idle; otherwise the session id (to resume polling - ``get_lora_download_progress``) and the lora id being fetched. - """ - session = self.state.lora_download_session - if session is None: - return ActiveLoraDownloadResponse(session_id=None, lora_id=None, progress=None) - return ActiveLoraDownloadResponse( - session_id=str(session.id), - lora_id=session.item_id, - progress=_session_progress_pct(session), - ) + return self._plain_lora.tracker.get_active() - @with_state_lock def get_active_ic_lora_download(self) -> ActiveIcLoraDownloadResponse: - """The in-flight IC-LoRA download, if any. Mirrors ``get_active_lora_download``. - - IC-LoRA downloads keep their own state slot, so both kinds can run at once and each - needs its own reattach point after a remount or a renderer reload. - """ - session = self.state.ic_lora_download_session - if session is None: - return ActiveIcLoraDownloadResponse( - session_id=None, ic_lora_id=None, progress=None - ) - return ActiveIcLoraDownloadResponse( - session_id=str(session.id), - ic_lora_id=session.item_id, - progress=_session_progress_pct(session), - ) + return self._ic_lora.tracker.get_active() diff --git a/backend/handlers/pipelines_handler.py b/backend/handlers/pipelines_handler.py index 08cf4a120..3e8b2d7ae 100644 --- a/backend/handlers/pipelines_handler.py +++ b/backend/handlers/pipelines_handler.py @@ -40,18 +40,17 @@ ) from runtime_config.evict_retry import evict_retry_filter from runtime_config.runtime_policy import LocalGenerationMode, streaming_prefetch_count_for_mode +from runtime_config.budget_admission import Admission, PricedJob, Refused, RiskAllowance, admit +from runtime_config.device_calibration import JobEnvelope +from runtime_config.eta import estimate_envelope_wall_time +from runtime_config.memory_meter import job_filter_machine_factor from runtime_config.video_job_budget import ( + WINDOWS_ICLORA_CPU_STREAMING_RAM_GB, LocalJobFilter, - VideoJobDecision, - VideoJobLoad, - VideoJobReject, - decide_edit_job, max_edit_frames_that_load, + price_edit_job, reject_message_and_code, - risk_allowed, - risk_for_reject, - risk_if_allowed, - unmeasured_load_risk, + video_job_reject, vram_snapshot_suffix, ) from services.retake_pipeline.window import ( @@ -101,38 +100,52 @@ @dataclass(frozen=True) class _EditVerdict: - """One edit cell verdict. ``cause`` chains the window ValueError so - create-time raises keep ``from exc`` chaining; the matrix drops it. - ``message``/``code`` ride None on ok — failing verdicts always set both.""" + """One edit cell verdict under the live mode. ``cause`` chains the window + ValueError so create-time raises keep ``from exc`` chaining; the matrix + drops it. ``ok`` means create would enqueue it. ``risk`` is the bet: the + admitted one on ok, the one the mode refused otherwise (None for a hard + refusal). Failing verdicts always set ``message``/``code``; an ok verdict + with a bet carries the bet line as ``message``.""" ok: bool message: str | None = None code: str | None = None cause: BaseException | None = None risk: GenerationRisk | None = None - - -def _risk_for_edit_reject( - decision: VideoJobReject, - job_filter: LocalJobFilter, -) -> GenerationRisk | None: - """Bet a failing edit cell could downgrade to, ignoring the live mode. - - Callers that enqueue or run still check the mode. The preflight cell - always carries this, so a hard refusal and an over-budget cell differ. - """ - return risk_for_reject(decision, job_filter) - - -def _edit_duration_offered(verdict: _EditVerdict, job_filter: LocalJobFilter) -> bool: - """Whether the trim slider may sit on this duration. - - A clean load always counts. In Reckless, a downgradable refusal counts - too, so the slider does not clamp to zero for a job create would enqueue. - """ - if verdict.ok: - return True - return risk_allowed(None, job_filter) and verdict.risk is not None + estimated_seconds: int | None = None + + +def _budget_verdict( + admission: Admission, + refusal: tuple[str, str] | None, + *, + job_filter: LocalJobFilter | None = None, +) -> _EditVerdict: + if isinstance(admission, Refused): + assert refusal is not None # _decide_edit_budget pairs every refusal + message, code = refusal + return _EditVerdict(ok=False, message=message, code=code, risk=admission.bet) + risk = admission.risk + estimated_seconds: int | None = None + if job_filter is not None: + system = ( + job_filter.profile.system + if job_filter.profile.system in ("Windows", "Linux", "Darwin") + else "Windows" + ) + est = estimate_envelope_wall_time( + admission.envelope, + system=system, + machine_factor=job_filter_machine_factor(job_filter), + conv_vae=job_filter.conv_vae, + ) + estimated_seconds = None if est is None else est.seconds + return _EditVerdict( + ok=True, + message=None if risk is None else risk.message, + risk=risk, + estimated_seconds=estimated_seconds, + ) class PipelinesHandler(StateHandlerBase): @@ -316,18 +329,19 @@ def park_image_generation_pipeline_on_cpu(self) -> None: self._assert_invariants() def load_image_generation_pipeline_to_gpu(self) -> ImageGenerationPipeline: - with self._lock: - if self.state.gpu_slot is not None: - active = self.state.gpu_slot.active_pipeline - if isinstance(active, ImageGenerationPipeline): - return active - self._ensure_no_running_generation() + resident = self._resident_matching(ImageGenerationPipeline, lambda _: True) + if resident is not None: + return resident image_generation_pipeline: ImageGenerationPipeline | None = None # Cold zit loads read weights off disk: same proof-of-life hold as # the GPU swaps so a slow load reads as busy, not hung. with liveness_hold(): + # A resident video pipeline is released before zit allocates, as in + # _swap_gpu_pipeline: both models must not be resident at once on a + # tight card. A queued image job often runs right after a video job. + self._evict_gpu_pipeline_for_swap() with self._lock: match self.state.cpu_slot: case CpuSlot(active_pipeline=stored): @@ -520,7 +534,10 @@ def _create() -> ICLoraState: self.config.device, prefetch, lora_strength, - offload_mode=self._offload_mode(load_mode), + offload_mode=self._offload_mode( + load_mode, + cpu_ram_floor_gb=WINDOWS_ICLORA_CPU_STREAMING_RAM_GB, + ), video_vae_path=paths.video_vae_path, audio_vae_path=paths.audio_vae_path, duration_head_path=paths.duration_head_path, @@ -600,6 +617,30 @@ def _create() -> A2VPipelineState: state = self._swap_gpu_pipeline(_create) return state + def _admit_edit_budget( + self, + priced: PricedJob, + *, + job_filter: LocalJobFilter, + queued_home: bool = False, + allowance: RiskAllowance | None = None, + ) -> tuple[Admission, tuple[str, str] | None]: + admission = admit( + priced, + allowance if allowance is not None else RiskAllowance.for_mode(job_filter.budget_mode), + ) + if not isinstance(admission, Refused): + return admission, None + reject = video_job_reject(admission) + if queued_home: + return admission, reject_message_and_code( + reject, + job_filter, + action=_EDIT_HOME_ACTION, + free_short_action=_EDIT_HOME_ACTION, + ) + return admission, reject_message_and_code(reject, job_filter) + def _decide_edit_budget( self, width: int, @@ -608,31 +649,20 @@ def _decide_edit_budget( *, job_filter: LocalJobFilter, queued_home: bool = False, - ) -> tuple[VideoJobDecision, tuple[str, str] | None]: - """Decided edit load plus the reject pair, if it rejects. + allowance: RiskAllowance | None = None, + ) -> tuple[Admission, tuple[str, str] | None]: + """Edit admission plus the refusal pair, if it refuses. Single decide + message mapping shared by the raise path (``_edit_load_mode``) and the verdict path (create-time preflight, preflight matrix): one decide call, one message builder, no drift. """ - decision = decide_edit_job( - width, - height, - frames, + return self._admit_edit_budget( + price_edit_job(width, height, frames, job_filter=job_filter), job_filter=job_filter, + queued_home=queued_home, + allowance=allowance, ) - if isinstance(decision, VideoJobReject): - if queued_home: - message, code = reject_message_and_code( - decision, - job_filter, - action=_EDIT_HOME_ACTION, - free_short_action=_EDIT_HOME_ACTION, - ) - else: - message, code = reject_message_and_code(decision, job_filter) - return decision, (message, code) - return decision, None def _edit_load_mode( self, @@ -642,38 +672,27 @@ def _edit_load_mode( *, queued_home: bool = False, allow_evict_retry: bool = False, - allow_risk: bool | None = None, - unmeasured_bet: bool = False, - ) -> LocalGenerationMode: - """Per-job full vs stream. Missing shape keeps the process mode. + allowance: RiskAllowance | None = None, + ) -> tuple[LocalGenerationMode, JobEnvelope | None]: + """Per-job full vs stream, and the priced envelope. Missing shape keeps the process mode. Does not change ``local_generations_mode``. Uses the edit headroom, so a 31 GB card streams a long 720p retake/extend as well as 1080p. Real loads pass ``allow_evict_retry``: a total-possible CUDA reject whose - shortfall live weights cover gets one evict-and-resample before the 422. - ``allow_risk=None`` follows the filter's live mode (every request-scoped - caller); executors pass the stored annotation so a mode flip never + shortfall live weights cover gets one evict-and-resample before admission. + ``allowance=None`` follows the filter's live mode (every request-scoped + caller); executors pass the stored allowance so a mode flip never re-gates a queued job. An over bet streams, including when the shortfall later grows. An unmeasured bet does not cover a later memory miss. Hard rejects raise in every mode. """ if width is None or height is None or frames is None: - return self.config.local_generations_mode + return self.config.local_generations_mode, None job_filter = self._local_job_filter() - decision, reject = self._decide_edit_budget( - width, - height, - frames, - job_filter=job_filter, - queued_home=queued_home, - ) - if isinstance(decision, VideoJobReject) and allow_evict_retry: + priced = price_edit_job(width, height, frames, job_filter=job_filter) + if allow_evict_retry: rebuilt = evict_retry_filter( - feature="edit", - is_vram_occupancy_miss=(decision.reason == "stream_over"), - stream_gib=decision.stream_gib, - seq=decision.seq, - full_gib=decision.full_gib, + priced=priced, job_filter=job_filter, live_allocated_bytes=self._gpu.get_cuda_live_allocated_bytes(), reserved_bytes=self._gpu.get_cuda_reserved_bytes(), @@ -683,64 +702,45 @@ def _edit_load_mode( ) if rebuilt is not None: job_filter = rebuilt - decision, reject = self._decide_edit_budget( - width, - height, - frames, - job_filter=job_filter, - queued_home=queued_home, - ) - if isinstance(decision, VideoJobReject): - assert reject is not None # _decide_edit_budget pairs every reject - message, code = reject - risk = risk_if_allowed( - risk_for_reject(decision, job_filter), - job_filter, - allow_risk, - unmeasured_bet=unmeasured_bet, - ) - if risk is not None: - logger.info( - "[video-edit] job budget seq=%.0f full=%.1fGiB stream=%.1fGiB -> risk:%s over_gib=%s over_ram_gb=%s%s", - decision.seq, - decision.full_gib, - decision.stream_gib, - risk.tier, - risk.over_gib, - risk.over_ram_gb, - vram_snapshot_suffix( - allocated_bytes=self._gpu.get_cuda_live_allocated_bytes(), - reserved_bytes=self._gpu.get_cuda_reserved_bytes(), - free_bytes=job_filter.budget.free_vram_bytes, - ), - ) - return "streaming_models_loading" + priced = price_edit_job(width, height, frames, job_filter=job_filter) + admission, refusal = self._admit_edit_budget( + priced, + job_filter=job_filter, + queued_home=queued_home, + allowance=allowance, + ) + snapshot = vram_snapshot_suffix( + allocated_bytes=self._gpu.get_cuda_live_allocated_bytes(), + reserved_bytes=self._gpu.get_cuda_reserved_bytes(), + free_bytes=job_filter.budget.free_vram_bytes, + ) + if isinstance(admission, Refused): + assert refusal is not None # _decide_edit_budget pairs every refusal logger.info( - "[video-edit] job budget seq=%.0f full=%.1fGiB stream=%.1fGiB -> reject%s", - decision.seq, - decision.full_gib, - decision.stream_gib, - vram_snapshot_suffix( - allocated_bytes=self._gpu.get_cuda_live_allocated_bytes(), - reserved_bytes=self._gpu.get_cuda_reserved_bytes(), - free_bytes=job_filter.budget.free_vram_bytes, - ), + "[video-edit] job budget seq=%.0f full=%.1fGiB stream=%.1fGiB -> reject:%s%s", + priced.seq, + priced.full_gib, + priced.stream_gib, + admission.reject.reason, + snapshot, ) + message, code = refusal raise HTTPError(422, message, code=code) + risk = admission.risk logger.info( - "[video-edit] job budget seq=%.0f full=%.1fGiB stream=%.1fGiB -> %s%s", - decision.seq, - decision.full_gib, - decision.stream_gib, - decision.mode, - vram_snapshot_suffix( - allocated_bytes=self._gpu.get_cuda_live_allocated_bytes(), - reserved_bytes=self._gpu.get_cuda_reserved_bytes(), - free_bytes=job_filter.budget.free_vram_bytes, + "[video-edit] job budget seq=%.0f full=%.1fGiB stream=%.1fGiB -> %s%s%s", + priced.seq, + priced.full_gib, + priced.stream_gib, + admission.load.mode, + ( + f" risk:{risk.tier} over_gib={risk.over_gib} over_ram_gb={risk.over_ram_gb}" + if risk is not None + else "" ), + snapshot, ) - assert isinstance(decision, VideoJobLoad) - return decision.mode + return admission.load.mode, admission.envelope def high_res_video_enabled(self) -> bool: return self._high_res_enabled() @@ -791,7 +791,7 @@ def preflight_queued_edit_job( same file metadata, the same frame cap, the same load gate — so an over-budget create 422s here instead of enqueueing a job that fails in the runner with a bare code. Raises HTTPError; returns the bet - annotation for a downgraded reject in reckless mode, else None. + annotation for an admitted risky job, else None. ``feature`` must agree with the params type (wiring check only — the params type is authoritative for dispatch). """ @@ -818,7 +818,6 @@ def _retake_verdict( job_filter: LocalJobFilter, start_time: float, duration: float, - allow_risk: bool | None = None, ) -> _EditVerdict: """Retake window + budget verdict. Window math is shared with the executor.""" prepared = prepare_retake_window( @@ -840,28 +839,15 @@ def _retake_verdict( # Window math and refusal copy read the picture size; the budget reads # the letterboxed canvas the model actually encodes (never smaller). canvas = generation_letterbox(target_width, target_height) - decision, reject = self._decide_edit_budget( - canvas.canvas_width, - canvas.canvas_height, - prepared.window.encode_frames, - job_filter=job_filter, - queued_home=True, - ) - if reject is not None: - assert isinstance(decision, VideoJobReject) # reject pair implies reject - message, code = reject - return _EditVerdict( - ok=False, - message=message, - code=code, - risk=_risk_for_edit_reject(decision, job_filter), - ) - assert isinstance(decision, VideoJobLoad) - return _EditVerdict( - ok=True, - risk=unmeasured_load_risk( - decision, job_filter, feature="edit", allow_risk=allow_risk + return _budget_verdict( + *self._decide_edit_budget( + canvas.canvas_width, + canvas.canvas_height, + prepared.window.encode_frames, + job_filter=job_filter, + queued_home=True, ), + job_filter=job_filter, ) def _extend_verdict( @@ -875,7 +861,6 @@ def _extend_verdict( job_filter: LocalJobFilter, duration: float, mode: ExtendMode, - allow_risk: bool | None = None, ) -> _EditVerdict: """Extend window + budget verdict. Window math is shared with the executor.""" prepared = prepare_extend_window( @@ -897,46 +882,23 @@ def _extend_verdict( # Same picture/canvas split as the retake verdict: messages name the # picture, the budget prices the canvas. canvas = generation_letterbox(target_width, target_height) - decision, reject = self._decide_edit_budget( - canvas.canvas_width, - canvas.canvas_height, - prepared.window.context_frames + prepared.extend_frames, - job_filter=job_filter, - queued_home=True, - ) - if reject is not None: - assert isinstance(decision, VideoJobReject) # reject pair implies reject - message, code = reject - return _EditVerdict( - ok=False, - message=message, - code=code, - risk=_risk_for_edit_reject(decision, job_filter), - ) - assert isinstance(decision, VideoJobLoad) - return _EditVerdict( - ok=True, - risk=unmeasured_load_risk( - decision, job_filter, feature="edit", allow_risk=allow_risk + return _budget_verdict( + *self._decide_edit_budget( + canvas.canvas_width, + canvas.canvas_height, + prepared.window.context_frames + prepared.extend_frames, + job_filter=job_filter, + queued_home=True, ), + job_filter=job_filter, ) @staticmethod - def _raise_verdict_or_risk( - verdict: _EditVerdict, - job_filter: LocalJobFilter, - allow_risk: bool | None, - ) -> GenerationRisk | None: - """Raise a failing verdict as the create-time 422, unless reckless - downgraded it — then hand the bet back for the annotation. - - A clean legacy load can also carry an unmeasured bet. That one is - already mode-gated on the verdict. - """ + def _raise_verdict_or_risk(verdict: _EditVerdict) -> GenerationRisk | None: + """Raise a failing verdict as the create-time 422, else hand back the + admitted bet for the annotation.""" if verdict.ok: return verdict.risk - if verdict.risk is not None and risk_allowed(allow_risk, job_filter): - return verdict.risk assert verdict.message is not None and verdict.code is not None if verdict.cause is not None: raise HTTPError(422, verdict.message, code=verdict.code) from verdict.cause @@ -947,7 +909,7 @@ def _preflight_retake(self, asset_path: str, params: RetakeParams) -> Generation Same verdicts execute would reach (shared window math, same frame cap, same load gate), raised as the create 422 instead of failing - in the runner. A downgraded reckless reject returns its annotation. + in the runner. An admitted risky job returns its annotation. """ fps, source_width, source_height, source_frames = read_source_metadata( asset_path @@ -977,8 +939,6 @@ def _preflight_retake(self, asset_path: str, params: RetakeParams) -> Generation start_time=params.startTime, duration=params.duration, ), - job_filter, - None, ) def _preflight_extend(self, asset_path: str, params: ExtendParams) -> GenerationRisk | None: @@ -986,7 +946,7 @@ def _preflight_extend(self, asset_path: str, params: ExtendParams) -> Generation Same verdicts execute would reach (shared window math, same frame cap, same load gate), raised as the create 422 instead of failing - in the runner. A downgraded reckless reject returns its annotation. + in the runner. An admitted risky job returns its annotation. """ fps, source_width, source_height, source_frames = read_source_metadata( asset_path @@ -1017,8 +977,6 @@ def _preflight_extend(self, asset_path: str, params: ExtendParams) -> Generation duration=params.duration, mode=params.mode, ), - job_filter, - None, ) @staticmethod @@ -1121,13 +1079,13 @@ def verdict_at(d: float) -> _EditVerdict: mode=mode, ) - if not _edit_duration_offered(verdict_at(min_duration), job_filter) or hi_cap <= 0: + if not verdict_at(min_duration).ok or hi_cap <= 0: max_duration = 0.0 elif hi_cap <= min_duration: max_duration = hi_cap else: max_duration = self._max_passing_duration( - lambda d: _edit_duration_offered(verdict_at(d), job_filter), + lambda d: verdict_at(d).ok, min_duration, hi_cap, ) @@ -1157,6 +1115,7 @@ def verdict_at(d: float) -> _EditVerdict: None if verdict.risk is None else verdict.risk.shortfall_kind ), readout=None if verdict.risk is None else verdict.risk.readout, + estimated_seconds=verdict.estimated_seconds, ) ) return EditPreflightResponse( @@ -1181,9 +1140,9 @@ def load_retake_pipeline( height: int | None = None, frames: int | None = None, queued_home: bool = False, - allow_risk: bool | None = None, - unmeasured_bet: bool = False, - ) -> RetakePipelineState: + allowance: RiskAllowance | None = None, + ) -> tuple[RetakePipelineState, JobEnvelope | None]: + """The pipeline for this edit job, and the envelope a clean run of it records.""" self._install_text_patches_if_needed() quantized = device_supports_fp8(self.config.device) @@ -1192,14 +1151,13 @@ def load_retake_pipeline( # job can load 2.3 while Settings stays on 2.5, and the two do not share an encoder. gemma_root = self._text_handler.resolve_gemma_root(model_id=model_id) paths = self._resolve_ltx_paths(model_id, gemma_root) - load_mode = self._edit_load_mode( + load_mode, envelope = self._edit_load_mode( width, height, frames, queued_home=queued_home, allow_evict_retry=True, - allow_risk=allow_risk, - unmeasured_bet=unmeasured_bet, + allowance=allowance, ) state = self._resident_matching( @@ -1226,7 +1184,10 @@ def _create() -> RetakePipelineState: streaming_prefetch_count=streaming_prefetch_count_for_mode(load_mode), loras=[], quantization=quantization, - offload_mode=self._offload_mode(load_mode), + offload_mode=self._offload_mode( + load_mode, + cpu_ram_floor_gb=None, + ), video_vae_path=paths.video_vae_path, audio_vae_path=paths.audio_vae_path, duration_head_path=paths.duration_head_path, @@ -1242,4 +1203,4 @@ def _create() -> RetakePipelineState: ) state = self._swap_gpu_pipeline(_create) - return state + return state, envelope diff --git a/backend/handlers/prompt_enhancement_handler.py b/backend/handlers/prompt_enhancement_handler.py index 829f0837e..ba348e681 100644 --- a/backend/handlers/prompt_enhancement_handler.py +++ b/backend/handlers/prompt_enhancement_handler.py @@ -6,10 +6,10 @@ import random import uuid from collections.abc import Callable, Iterator, Sequence -from contextlib import contextmanager, nullcontext +from contextlib import AbstractContextManager, contextmanager, nullcontext from pathlib import Path from threading import Lock, RLock -from typing import TYPE_CHECKING, Literal, NamedTuple +from typing import TYPE_CHECKING, Literal from _routes._errors import HTTPError from api_types import ( @@ -17,7 +17,7 @@ EnhancePromptRequest, EnhancePromptResponse, IcLoraCatalogItem, - LoraCatalogItem, + LoraEntry, LTXLocalModelId, LTXVideoGenAspectRatio, LTXVideoGenResolution, @@ -27,11 +27,24 @@ from handlers.base import StateHandlerBase from handlers.generation_handler import GenerationHandler from handlers.pipelines_handler import PipelinesHandler +from handlers.prompt_enhancer_nag import nag_unavailable_reasons +from handlers.prompt_rewrite_helpers import ( + ic_lora_rewrite, + reference_frame, + video_role, + writes_blank_prompt, +) +from handlers.resolved_generation_prompt import ( + PromptProvenanceLabel, + ResolvedGenerationPrompt, +) from handlers.text_handler import TextHandler +from runtime_config.custom_loras import custom_lora_prompt_guidance, read_custom_lora from server_utils.media_validation import normalize_optional_path, validate_image_file from services.analytics import resolution_for_provenance as shared_resolution_for_provenance from services.analytics import prompt_provenance_label as shared_prompt_provenance_label from services.features.ic_lora_recipes import ic_lora_skips_prompt_enhancement +from services.features.image.prompt_rewrite import ImagePromptRewrite from services.features.video.job_common import UNNAMED_RECIPE, denoise_canvas_for from services.features.video.reference_sheet import ensure_reference_sheet from services.gemini_text_client import resolve_gemini_model @@ -39,24 +52,20 @@ from services.interfaces import PromptEnhancerPipeline from services.lora_catalog import LoraCatalogProvider from services.prompt_enhancement import ( + LoraPromptGuidance, build_audio_visual_caption_system_prompt, build_conditioning_system_prompt, - build_ic_lora_enhancement_system_prompt, build_image_edit_system_prompt, build_image_generation_system_prompt, build_keyframe_enhancement_system_prompt, build_lora_enhancement_system_prompt, - build_template_fill_system_prompt, enforce_trigger_placements, - fill_prompt_template, - parse_template_fill_response, ) from services.prompt_enhancement.i2v_frames import ( KeyframeStill, SceneFrame, VideoRole, reference_sheet_still, - reference_still, strip_panel_labels, ) from services.prompt_enhancement.source_video import SourceVideo @@ -78,74 +87,12 @@ _MAX_ENHANCE_SEED = 2147483647 -class ResolvedGenerationPrompt(NamedTuple): - """The prompt a local generation should submit, and how it got (or will get) enhanced.""" - - prompt: str - enhance_via_api: bool - enhanced_locally: bool - skip_recipe_wrap: bool = False - - @property - def enhancement(self) -> str: - """Where the rewrite happens, for run logs: local, server-side, or nowhere.""" - if self.enhanced_locally: - return "local" - return "api" if self.enhance_via_api else "none" - - -PromptProvenanceLabel = Literal["raw", "manually-enhanced", "auto-enhanced"] - - -def prompt_provenance_label( - provenance: PromptProvenance, - resolved: ResolvedGenerationPrompt, -) -> PromptProvenanceLabel: - """How this run asked for the prompt to be passed. Not the prompt text.""" - return shared_prompt_provenance_label( - provenance, - enhanced_locally=resolved.enhanced_locally, - enhance_via_api=resolved.enhance_via_api, - ) - - -def _video_role(req: EnhancePromptRequest) -> VideoRole: - """A list of panel images is its own role. An IC-LoRA transforms its video, so the stills - are ground truth. Anything else (Extend, Retake) only gets scene context from them and the - typed prompt leads.""" - if req.imagePaths: - return "panels" - return "driving" if req.icLoraId is not None else "scene" - - -def _ic_lora_rewrite(ic_lora: IcLoraCatalogItem, run: Callable[[str], str]) -> str: - """The catalog policy of an IC-LoRA rewrite, for every path that makes one. - - ``run`` sends one rewrite call with the given system prompt and returns the raw reply. - A template entry gets the template fill. Any other entry gets a free rewrite with its - trigger phrases enforced. ``ValueError`` means the reply did not fill the template. - """ - template = ic_lora.prompt_template - if template is not None: - raw = run(build_template_fill_system_prompt(ic_lora)) - values = parse_template_fill_response(raw, set(template.placeholders)) - return fill_prompt_template(template, values) - enhanced = run(build_ic_lora_enhancement_system_prompt(ic_lora)) - # Trigger enforcement on an empty rewrite would make a bare trigger word the prompt. - if not enhanced.strip(): - return enhanced - return enforce_trigger_placements(enhanced, [ic_lora]) - +def _always_leased() -> AbstractContextManager[bool]: + return nullcontext(True) -def _writes_blank_prompt(source_video: SourceVideo | None) -> bool: - return source_video is not None and source_video.writes_blank_prompt - -def _reference_frame(ic_lora: IcLoraCatalogItem, path: str) -> SceneFrame: - """A catalog entry pins the frame its look image conditions: the first frame of the clip - (Restore), or a still before the clip (Layout to Render). An unpinned one uses frame 0.""" - pinned = ic_lora.reference_image_frame - return reference_still(path, is_clip_frame=pinned is None or pinned >= 0) +def _never_cancelled() -> None: + return None class PromptEnhancementHandler(StateHandlerBase): @@ -203,6 +150,13 @@ def status(self, *, prefer_gemini: bool) -> PromptEnhancerStatusResponse: if preferred == "api" and not has_gemini and has_local else preferred ) + local_encoding = self._text_handler.should_use_local_encoding() + compile_on = ( + settings.use_torch_compile and not self.config.use_sage_attention + ) + base_reason, reason_by_feature = nag_unavailable_reasons( + nag_scale=settings.nag_scale, local_encoding=local_encoding, compile_on=compile_on + ) return PromptEnhancerStatusResponse( exploreAutoEnhancePrompts=settings.explore_auto_enhance_prompts, hasGeminiApiKey=has_gemini, @@ -210,6 +164,9 @@ def status(self, *, prefer_gemini: bool) -> PromptEnhancerStatusResponse: defaultProvider=default_provider, canToggleProvider=has_local and has_gemini, showManualEnhance=not settings.explore_auto_enhance_prompts, + nagUnavailableReason=base_reason, + nagUnavailableReasonByFeature=reason_by_feature, + showNagStrengthControls=settings.show_nag_strength_controls, ) def _automatic_enhancement_seed( @@ -325,7 +282,7 @@ def _sheet_frames( ) try: sheet = ensure_reference_sheet( - paths, *canvas, app_data_dir=self.config.app_data_dir + paths, *canvas, in_flight_dir=self.config.in_flight_dir ) except (OSError, ValueError) as exc: raise HTTPError(400, "Invalid image file") from exc @@ -347,7 +304,7 @@ def _video_frames( raise HTTPError(400, "This IC-LoRA does not take a reference image") # Before it reaches either provider: Gemini would otherwise get unchecked file bytes. validate_image_file(source_video.reference_image_path) - reference = _reference_frame(ic_lora, source_video.reference_image_path) + reference = reference_frame(ic_lora, source_video.reference_image_path) try: with sampled_video_frames( source_video.path, replaced_window=source_video.replaced_window @@ -379,7 +336,7 @@ def _resolve_and_enhance_media( return self._enhance_ic_lora(ic_lora, req, gemma_root, frames) if req.loraCatalogIds: - loras: list[LoraCatalogItem] = [] + loras: list[LoraPromptGuidance] = [] for catalog_id in req.loraCatalogIds: lora = self._lora_catalog_provider.get_lora(catalog_id) if lora is None: @@ -387,6 +344,12 @@ def _resolve_and_enhance_media( loras.append(lora) return self._enhance_loras(loras, req, gemma_root) + if req.customLoraIds: + record = read_custom_lora(self.models_dir, req.customLoraIds[0]) + if record is None: + raise HTTPError(404, "CUSTOM_LORA_NOT_FOUND") + return self._enhance_loras([custom_lora_prompt_guidance(record)], req, gemma_root) + if req.conditioningType is not None: system_prompt = build_conditioning_system_prompt(req.conditioningType) return self._run_free_rewrite(req, system_prompt, gemma_root) @@ -434,13 +397,14 @@ def resolve_for_generation( duration: int | None = None, fps: int | None = None, ic_lora: IcLoraCatalogItem | None = None, - lora_catalog_ids: list[str] | None = None, + loras: Sequence[LoraEntry] | None = None, conditioning_type: ConditioningType | None = None, local_model_id: LTXLocalModelId | None = None, explore_generation: bool = False, audio_path: str | None = None, source_video: SourceVideo | None = None, panel_paths: Sequence[str] = (), + negative_prompt: str = "", ) -> ResolvedGenerationPrompt: """The single enhancement policy for prompt-bearing local generation. @@ -460,9 +424,9 @@ def resolve_for_generation( the prompt as typed, which for a version captioned in 150-220 word audio-visual paragraphs (2.5) lands far outside its training distribution and it invents the rest. - ``lora_catalog_ids`` are the catalog ids of the plain LoRAs the request selected. They - get the same catalog-aware treatment manual Enhance gives them, because the generic - rewrite would paraphrase a required trigger phrase away and leave the adapter inert. + ``loras`` are the plain LoRA entries the request selected. Catalog entries get the + same catalog-aware treatment manual Enhance gives them, and saved custom LoRAs get what + the user told the enhancer when adding the LoRA (description, trigger, and examples). ``generation_seed`` is the seed the caller already resolved for this run (an explicit request seed, the lock, or a fresh draw). It reaches the rewrite when @@ -509,11 +473,12 @@ def resolve_for_generation( duration=duration, fps=fps, ic_lora=ic_lora, - loras=self._resolve_generation_loras(lora_catalog_ids), + loras=self._resolve_generation_loras(loras), conditioning_type=conditioning_type, local_model_id=local_model_id, source_video=source_video, panel_paths=panel_paths, + negative_prompt=negative_prompt, ) return ResolvedGenerationPrompt(enhanced, False, rewritten, False) @@ -578,7 +543,7 @@ def _preview_resolution( ), force_api=force_api, gemini_video_enhance=self._wants_gemini_media_enhance(source_video, panel_paths), - enhance_blank_prompt=_writes_blank_prompt(source_video), + enhance_blank_prompt=writes_blank_prompt(source_video), ) if decided is None: return None @@ -586,11 +551,12 @@ def _preview_resolution( return ResolvedGenerationPrompt(prompt, enhance_via_api, enhanced_locally, skip_recipe_wrap) def gemini_video_enhance_enabled(self) -> bool: - """Whether an automatic rewrite of a source video or panel images may go to Gemini. + """Whether an automatic rewrite may go to Gemini. - Manual Enhance with Gemini is an explicit click. Automatic enhancement is not, and it - would upload stills of the user's video or the user's panel images. So it needs an explicit provider choice (not - the default that merely follows a stored key) as well as the key. + Manual Enhance with Gemini is an explicit click. Automatic enhancement is not, and a + video or panel rewrite would upload stills of the user's media. So every automatic + Gemini rewrite needs an explicit provider choice (not the default that merely follows a + stored key) as well as the key. """ settings = self.state.app_settings return ( @@ -625,24 +591,31 @@ def api_enhance_prompt( return False return self.state.app_settings.prompt_enhancer_enabled - def _resolve_generation_loras(self, catalog_ids: list[str] | None) -> list[LoraCatalogItem]: - """The catalog entries behind a generation's selected plain LoRAs, by id alone. + def _resolve_generation_loras( + self, loras: Sequence[LoraEntry] | None + ) -> list[LoraPromptGuidance]: + """The prompt-enhancer guidance behind a generation's selected plain LoRAs. Unlike manual Enhance, an unresolvable id doesn't 404: automatic enhancement is a quality step layered onto a generation the user already started, so a stale id costs the catalog treatment rather than the run. """ - items: list[LoraCatalogItem] = [] - for catalog_id in catalog_ids or []: - lora = self._lora_catalog_provider.get_lora(catalog_id) - if lora is None: - logger.info("Skipping unknown LoRA catalog id for enhancement: %s", catalog_id) - continue - # A templated entry needs the template-fill path, which the multi-select free - # rewrite has no shape for. No plain catalog LoRA has one today. - if lora.prompt_template is not None: - continue - items.append(lora) + items: list[LoraPromptGuidance] = [] + for entry in loras or (): + if entry.catalogId is not None: + lora = self._lora_catalog_provider.get_lora(entry.catalogId) + if lora is None: + logger.info("Skipping unknown LoRA catalog id for enhancement: %s", entry.catalogId) + continue + if lora.prompt_template is not None: + continue + items.append(lora) + elif entry.customLoraId is not None: + record = read_custom_lora(self.models_dir, entry.customLoraId) + if record is None: + logger.info("Skipping unknown custom LoRA for enhancement: %s", entry.customLoraId) + continue + items.append(custom_lora_prompt_guidance(record)) return items def enhance_for_generation( @@ -657,11 +630,12 @@ def enhance_for_generation( duration: int | None = None, fps: int | None = None, ic_lora: IcLoraCatalogItem | None = None, - loras: list[LoraCatalogItem] | None = None, + loras: Sequence[LoraPromptGuidance] | None = None, conditioning_type: ConditioningType | None = None, local_model_id: LTXLocalModelId | None = None, source_video: SourceVideo | None = None, panel_paths: Sequence[str] = (), + negative_prompt: str = "", ) -> tuple[str, bool]: """Rewrite ``prompt`` on the local enhancer: ``(prompt, rewritten)``. @@ -685,7 +659,7 @@ def enhance_for_generation( the generation. """ loras = loras or [] - if not prompt.strip() and not _writes_blank_prompt(source_video): + if not prompt.strip() and not writes_blank_prompt(source_video): return prompt, False gemma_root = self._text_handler.resolve_prompt_enhancer_root_if_downloaded( model_id=local_model_id @@ -710,6 +684,7 @@ def enhance_for_generation( provider="api" if use_gemini else "local", gemma_root=gemma_root, sheet_path=image_path, + negative_prompt=negative_prompt, ) elif source_video is not None: with self._gemini_enhance_slot if use_gemini else nullcontext(): @@ -721,15 +696,19 @@ def enhance_for_generation( provider="api" if use_gemini else "local", gemma_root=gemma_root, local_model_id=local_model_id, + negative_prompt=negative_prompt, ) else: assert gemma_root is not None pipeline = self._load_prompt_enhancer_pipeline(gemma_root) if ic_lora is not None: - enhanced = _ic_lora_rewrite( + enhanced = ic_lora_rewrite( ic_lora, lambda system_prompt: pipeline.enhance_t2v( - prompt, system_prompt=system_prompt, seed=seed + prompt, + system_prompt=system_prompt, + seed=seed, + negative_prompt=negative_prompt, ), ) else: @@ -752,9 +731,15 @@ def enhance_for_generation( keyframes=keyframes, duration=duration, fps=fps, + negative_prompt=negative_prompt, ) else: - enhanced = pipeline.enhance_t2v(prompt, system_prompt=system_prompt, seed=seed) + enhanced = pipeline.enhance_t2v( + prompt, + system_prompt=system_prompt, + seed=seed, + negative_prompt=negative_prompt, + ) if enhanced.strip(): # Deterministic, same as manual Enhance: the rewrite is asked for the # trigger phrases, never trusted to have kept them. @@ -774,14 +759,96 @@ def enhance_for_generation( ) return enhanced, True + def local_image_enhancer_root(self) -> str | None: + """The local Gemma an image rewrite may use, or None. + + None on an API-only machine (`force_api_generations`): local enhancement is not + supported there, as `status()` reports. The image job then rewrites on Gemini if the + user chose it, else keeps the typed prompt. + """ + if self.config.force_api_generations: + return None + return self._text_handler.resolve_prompt_enhancer_root_if_downloaded() + + def _image_rewrite_wanted(self, prompt: str, provenance: PromptProvenance) -> bool: + """Explore auto-enhance is on and the prompt is still as typed.""" + settings = self.state.app_settings + return not ( + provenance == "enhanced" + or not prompt.strip() + or not settings.explore_auto_enhance_prompts + ) + + def rewrite_image_prompt( + self, + prompt: str, + *, + provenance: PromptProvenance, + generation_seed: int, + explicit_generation_seed: bool, + lease_gpu: Callable[[], AbstractContextManager[bool]] = _always_leased, + raise_if_cancelled: Callable[[], None] = _never_cancelled, + ) -> ImagePromptRewrite: + """The automatic rewrite of a text-to-image prompt, for a local job and a fal job. + + Rewrites only when Explore auto-enhance is on and the prompt is still as typed. The + rewrite runs on local Gemma when it is downloaded and ``lease_gpu`` grants the GPU, else + on Gemini when the user chose Gemini and stored a key. Any failure keeps the typed + prompt: the image job must not fail for a quality step. Only cancellation is re-raised. + ``raise_if_cancelled`` runs before each step that takes long. + """ + if not self._image_rewrite_wanted(prompt, provenance): + return ImagePromptRewrite(prompt, source=None, wanted=False) + typed = ImagePromptRewrite(prompt, source=None, wanted=True) + gemma_root = self.local_image_enhancer_root() + use_gemini = gemma_root is None and self.gemini_video_enhance_enabled() + if gemma_root is None and not use_gemini: + logger.info("No prompt enhancer available for the image prompt") + return typed + seed = self._automatic_enhancement_seed( + generation_seed, explicit_generation_seed=explicit_generation_seed + ) + system_prompt = build_image_generation_system_prompt() + try: + if gemma_root is not None: + with lease_gpu() as leased: + if not leased: + logger.info("GPU busy: the image prompt is not rewritten on local Gemma") + return typed + # A cancel that came while the lease was taken must not load Gemma. + raise_if_cancelled() + pipeline = self._load_prompt_enhancer_pipeline(gemma_root) + rewritten = pipeline.enhance_t2v(prompt, system_prompt=system_prompt, seed=seed) + source: Literal["local", "gemini"] = "local" + else: + raise_if_cancelled() + settings = self.state.app_settings + with self._gemini_enhance_slot: + rewritten = self._gemini_pipeline.enhance_t2v( + prompt, + system_prompt=system_prompt, + seed=seed, + api_key=settings.gemini_api_key.strip(), + model=resolve_gemini_model(settings.gemini_model), + ) + source = "gemini" + except Exception as exc: + if is_cancel_exception(exc): + raise + logger.warning("Automatic image enhancement failed; using the typed prompt", exc_info=True) + return typed + if not rewritten.strip(): + return typed + return ImagePromptRewrite(rewritten, source=source, wanted=True) + def _generation_fallback_prompt( self, prompt: str, ic_lora: IcLoraCatalogItem | None, - loras: list[LoraCatalogItem], + loras: Sequence[LoraPromptGuidance], ) -> str: """Preserve every non-template catalog adapter's trigger when no rewrite is available.""" - items: list[LoraCatalogItem] = list(loras) + items: list[LoraPromptGuidance] = list(loras) if ic_lora is not None and ic_lora.prompt_template is None: items.append(ic_lora) return prompt if not items else enforce_trigger_placements(prompt, items) @@ -789,7 +856,7 @@ def _generation_fallback_prompt( def _generation_system_prompt( self, *, - loras: list[LoraCatalogItem], + loras: Sequence[LoraPromptGuidance], image_path: str | None, keyframes: list[KeyframeStill] | None, conditioning_type: ConditioningType | None, @@ -819,6 +886,7 @@ def _enhance_video_for_generation( provider: Literal["local", "api"], gemma_root: str | None, local_model_id: LTXLocalModelId | None, + negative_prompt: str = "", ) -> str: """The rewrite of an IC-LoRA, Extend, or Retake job that sees its source video. @@ -837,8 +905,9 @@ def _enhance_video_for_generation( provider=provider, gemma_root=gemma_root, seed=seed, + negative_prompt=negative_prompt, ) - return _ic_lora_rewrite( + return ic_lora_rewrite( ic_lora, lambda system_prompt: self._run_video_rewrite( prompt, @@ -848,6 +917,7 @@ def _enhance_video_for_generation( provider=provider, gemma_root=gemma_root, seed=seed, + negative_prompt=negative_prompt, ), ) @@ -861,6 +931,7 @@ def _enhance_panels_for_generation( provider: Literal["local", "api"], gemma_root: str | None, sheet_path: str | None = None, + negative_prompt: str = "", ) -> str: """The rewrite of an image-list IC-LoRA job. It sees the constructed reference sheet. @@ -868,7 +939,7 @@ def _enhance_panels_for_generation( or a template that can't be filled raises out to the caller's typed-prompt fallback. """ frames = self._sheet_frames(panel_paths, sheet_path=sheet_path) - return _ic_lora_rewrite( + return ic_lora_rewrite( ic_lora, lambda system_prompt: self._run_video_rewrite( prompt, @@ -878,11 +949,12 @@ def _enhance_panels_for_generation( provider=provider, gemma_root=gemma_root, seed=seed, + negative_prompt=negative_prompt, ), ) def _enhance_loras( - self, loras: list[LoraCatalogItem], req: EnhancePromptRequest, gemma_root: str | None + self, loras: Sequence[LoraPromptGuidance], req: EnhancePromptRequest, gemma_root: str | None ) -> str: # None of the plain LoRAs in the catalog have a prompt_template today (only IC-LoRAs # do) — the multi-select path is always a free rewrite. @@ -908,7 +980,7 @@ def _enhance_ic_lora( else req ) try: - return _ic_lora_rewrite( + return ic_lora_rewrite( ic_lora, lambda system_prompt: self._run_free_rewrite( target, system_prompt, gemma_root, frames @@ -924,15 +996,17 @@ def _run_free_rewrite( gemma_root: str | None, frames: Sequence[SceneFrame] | None = None, ) -> str: + negative_prompt = (req.negativePrompt or "") if self.state.app_settings.nag_scale > 0 else "" if frames is not None: return self._run_video_rewrite( req.prompt, frames, system_prompt, - role=_video_role(req), + role=video_role(req), provider=req.provider, gemma_root=gemma_root, seed=self._random_seed(), + negative_prompt=negative_prompt, ) # Reject an invalid/unreadable/oversized path before it reaches either provider — the # API path in particular would otherwise base64-encode and ship arbitrary file bytes to @@ -969,6 +1043,7 @@ def _run_free_rewrite( keyframes=keyframes, duration=req.duration, fps=req.fps, + negative_prompt=negative_prompt, ) return self._gemini_pipeline.enhance_t2v( req.prompt, @@ -976,6 +1051,7 @@ def _run_free_rewrite( seed=seed, api_key=api_key, model=resolved_model, + negative_prompt=negative_prompt, ) logger.info("Enhancing prompt via local Gemma") @@ -991,8 +1067,14 @@ def _run_free_rewrite( keyframes=keyframes, duration=req.duration, fps=req.fps, + negative_prompt=negative_prompt, ) - return pipeline.enhance_t2v(req.prompt, system_prompt=system_prompt, seed=seed) + return pipeline.enhance_t2v( + req.prompt, + system_prompt=system_prompt, + seed=seed, + negative_prompt=negative_prompt, + ) def _validated_keyframes(self, req: EnhancePromptRequest) -> list[KeyframeStill] | None: if req.mediaType == "image" or not req.keyframes: @@ -1017,10 +1099,18 @@ def _run_video_rewrite( provider: Literal["local", "api"], gemma_root: str | None, seed: int, + negative_prompt: str = "", ) -> str: """One rewrite call that sees the source video's stills, on either provider.""" reply = self._call_video_rewrite( - prompt, frames, system_prompt, role=role, provider=provider, gemma_root=gemma_root, seed=seed + prompt, + frames, + system_prompt, + role=role, + provider=provider, + gemma_root=gemma_root, + seed=seed, + negative_prompt=negative_prompt, ) # The panel labels are input only. A small model sometimes copies them into the reply. return strip_panel_labels(reply) if role == "panels" else reply @@ -1035,6 +1125,7 @@ def _call_video_rewrite( provider: Literal["local", "api"], gemma_root: str | None, seed: int, + negative_prompt: str = "", ) -> str: look_images = sum(1 for frame in frames if frame.is_reference) logger.info( @@ -1055,11 +1146,14 @@ def _call_video_rewrite( role, api_key=self.state.app_settings.gemini_api_key.strip(), model=resolved_model, + negative_prompt=negative_prompt, ) logger.info("Enhancing prompt with video frames via local Gemma") assert gemma_root is not None pipeline = self._load_prompt_enhancer_pipeline(gemma_root) - return pipeline.enhance_with_video_frames(prompt, frames, system_prompt, seed, role) + return pipeline.enhance_with_video_frames( + prompt, frames, system_prompt, seed, role, negative_prompt=negative_prompt + ) def _load_prompt_enhancer_pipeline(self, gemma_root: str) -> PromptEnhancerPipeline: self._pipelines.evict_resident_pipeline() diff --git a/backend/handlers/prompt_enhancer_nag.py b/backend/handlers/prompt_enhancer_nag.py new file mode 100644 index 000000000..1fcc5fc34 --- /dev/null +++ b/backend/handlers/prompt_enhancer_nag.py @@ -0,0 +1,59 @@ +"""Why NAG (negative guidance) is unavailable, per feature, for the prompt enhancer status.""" + +from __future__ import annotations + +import os + +from services.fast_video_pipeline.nag_config import decide_nag +from services.features.ic_lora_recipes import IC_LORA_RECIPES +from services.features.lora_recipes import queued_lora_recipes +from services.features.video import ( + AUDIO_TO_VIDEO_FEATURE, + CUSTOM_LORA_FEATURE, + EXTEND_FEATURE, + FEATURE as TEXT_TO_VIDEO_FEATURE, + IMAGE_TO_VIDEO_FEATURE, + KEYFRAMES_FEATURE, + RETAKE_FEATURE, +) + + +def nag_unavailable_reasons( + *, nag_scale: float, local_encoding: bool, compile_on: bool +) -> tuple[str | None, dict[str, str]]: + """The reason NAG is off for the base pipeline, and the reason for each feature.""" + base_reason = decide_nag( + "x", + os.environ, + default_scale=nag_scale, + local_encoding=local_encoding, + compiled=False, + ).user_message + fast_reason = decide_nag( + "x", + os.environ, + default_scale=nag_scale, + local_encoding=local_encoding, + compiled=compile_on, + ).user_message + fast_features = ( + TEXT_TO_VIDEO_FEATURE, + IMAGE_TO_VIDEO_FEATURE, + KEYFRAMES_FEATURE, + CUSTOM_LORA_FEATURE, + *(recipe.recipe_id for recipe in queued_lora_recipes()), + ) + non_compiled_features = ( + AUDIO_TO_VIDEO_FEATURE, + RETAKE_FEATURE, + EXTEND_FEATURE, + *(recipe.recipe_id for recipe in IC_LORA_RECIPES.values()), + ) + reason_by_feature: dict[str, str] = {} + if fast_reason is not None: + for fid in fast_features: + reason_by_feature[fid] = fast_reason + if base_reason is not None: + for fid in non_compiled_features: + reason_by_feature[fid] = base_reason + return base_reason, reason_by_feature diff --git a/backend/handlers/prompt_rewrite_helpers.py b/backend/handlers/prompt_rewrite_helpers.py new file mode 100644 index 000000000..ed0400ee4 --- /dev/null +++ b/backend/handlers/prompt_rewrite_helpers.py @@ -0,0 +1,55 @@ +"""Pure helpers of the prompt enhancement handler: video roles and IC-LoRA rewrites.""" + +from __future__ import annotations + +from collections.abc import Callable + +from api_types import EnhancePromptRequest, IcLoraCatalogItem +from services.prompt_enhancement import ( + build_ic_lora_enhancement_system_prompt, + build_template_fill_system_prompt, + enforce_trigger_placements, + fill_prompt_template, + parse_template_fill_response, +) +from services.prompt_enhancement.i2v_frames import SceneFrame, VideoRole, reference_still +from services.prompt_enhancement.source_video import SourceVideo + + +def video_role(req: EnhancePromptRequest) -> VideoRole: + """A list of panel images is its own role. An IC-LoRA transforms its video, so the stills + are ground truth. Anything else (Extend, Retake) only gets scene context from them and the + typed prompt leads.""" + if req.imagePaths: + return "panels" + return "driving" if req.icLoraId is not None else "scene" + + +def ic_lora_rewrite(ic_lora: IcLoraCatalogItem, run: Callable[[str], str]) -> str: + """The catalog policy of an IC-LoRA rewrite, for every path that makes one. + + ``run`` sends one rewrite call with the given system prompt and returns the raw reply. + A template entry gets the template fill. Any other entry gets a free rewrite with its + trigger phrases enforced. ``ValueError`` means the reply did not fill the template. + """ + template = ic_lora.prompt_template + if template is not None: + raw = run(build_template_fill_system_prompt(ic_lora)) + values = parse_template_fill_response(raw, set(template.placeholders)) + return fill_prompt_template(template, values) + enhanced = run(build_ic_lora_enhancement_system_prompt(ic_lora)) + # Trigger enforcement on an empty rewrite would make a bare trigger word the prompt. + if not enhanced.strip(): + return enhanced + return enforce_trigger_placements(enhanced, [ic_lora]) + + +def writes_blank_prompt(source_video: SourceVideo | None) -> bool: + return source_video is not None and source_video.writes_blank_prompt + + +def reference_frame(ic_lora: IcLoraCatalogItem, path: str) -> SceneFrame: + """A catalog entry pins the frame its look image conditions: the first frame of the clip + (Restore), or a still before the clip (Layout to Render). An unpinned one uses frame 0.""" + pinned = ic_lora.reference_image_frame + return reference_still(path, is_clip_frame=pinned is None or pinned >= 0) diff --git a/backend/handlers/queued_generation_handler.py b/backend/handlers/queued_generation_handler.py index 1f3d3339a..e613d4935 100644 --- a/backend/handlers/queued_generation_handler.py +++ b/backend/handlers/queued_generation_handler.py @@ -1,15 +1,18 @@ from __future__ import annotations import logging +import os import sqlite3 from collections.abc import Callable, Collection +from dataclasses import dataclass from pathlib import Path from threading import RLock -from typing import TYPE_CHECKING, Literal, cast +from typing import TYPE_CHECKING, Literal, Protocol, cast -from pydantic import JsonValue, ValidationError +from pydantic import BaseModel, JsonValue, ValidationError from api_types import ( + CreateCustomLoraRequest, CreateIcLoraRecipeRequest, CreateIcLoraSheetRequest, CreateIcLoraTrackRequest, @@ -18,17 +21,26 @@ CreateAudioToVideoParams, CreateAudioToVideoRequest, CreateImageToVideoRequest, + CreateKeyframesRequest, CreateLoraRecipeRequest, CreateExtendRequest, CreateRetakeRequest, + CreateTextToImageRequest, + ImageGenerationStatusResponse, CreateTextToVideoRequest, EditPreflightRequest, EditPreflightResponse, + IcLoraCatalogItem, + IcLoraTilePreflightRequest, + IcLoraTilePreflightResponse, + IcLoraVideoRecipeStoredParams, ExtendParams, Generation, - GenerationProgressResponse, + ApiActivityStatus, GenerationRisk, IcLoraRecipeStoredParams, + ImageToVideoInputs, + ImageToVideoRecipeParams, LTXQueuedAspectRatio, LTXVideoGenFps, LTXVideoGenResolution, @@ -37,6 +49,7 @@ QueueProgress, QueueSnapshot, RetakeParams, + TextToVideoParams, ) from _routes._errors import HTTPError from handlers.base import resolve_models_dir @@ -44,23 +57,32 @@ from runtime_config.accelerator import accelerator_backend from runtime_config.ic_lora_high_res import ( HIGH_RES_NOT_ENABLED, - HIGH_RES_ONLY_IC_LORAS, high_res_cell, + high_res_flag_satisfied, high_res_source_large_enough, ) from runtime_config.ic_lora_stage_mode import IcLoraStageMode +from runtime_config.reject_reasons import PassShape from runtime_config.video_job_budget import ( LOCAL_GENERATION_UNSUPPORTED, LOCAL_GENERATION_UNSUPPORTED_MESSAGE, + resolve_pass_shape, ) from runtime_config.ltx_capabilities import LtxCapabilityFeature from runtime_config.model_download_specs import local_aspect_ratios +from services.features.image.feature_id import FEATURE as TEXT_TO_IMAGE_FEATURE +from services.features.image.text_to_image import resolve_text_to_image_params from services.features.video.job_common import ( + PASS_SHAPE_SPEC_KEY, high_res_unsupported_error, require_capable_local_model, stored_generation_risk, ) from services.aspect_ratio import find_closest_aspect_ratio_option +from services.fast_video_pipeline.nag_config import ( + DEFAULT_SCALE as DEFAULT_NAG_SCALE, + decide_nag, +) from services.media_probe import MAX_VIDEO_BYTES, video_fps from services.features.ic_lora_recipes import ( IC_LORA_RECIPES, @@ -69,6 +91,10 @@ resolve_ic_lora_recipe_create, resolve_synthesized_ic_lora_create, ) +from services.features.custom_loras import ( + CustomLoraCreateError, + resolve_custom_lora_create, +) from services.features.lora_recipes import RecipeCreateError, resolve_recipe_create from services.lora_catalog import LoraCatalogProvider from services.store import Store @@ -89,12 +115,17 @@ cancel_queued_generation, ) from services.generation_queue.finished_tray import FinishedTray +from services.generation_queue.orphans import ( + cancel_provider_orphans_in_background, + forget_in, +) from services.generation_queue.registry import ExecutorRegistry from services.features.video import ( AUDIO_TO_VIDEO_FEATURE, EXTEND_FEATURE, FEATURE as TEXT_TO_VIDEO_FEATURE, IMAGE_TO_VIDEO_FEATURE, + KEYFRAMES_FEATURE, RETAKE_FEATURE, ) from state.app_state_types import AppState @@ -110,12 +141,8 @@ logger = logging.getLogger(__name__) -# Recipe ids (the generation `feature`) of the catalog IC-LoRAs that need highResVideoToVideo. -_HIGH_RES_ONLY_RECIPE_IDS = frozenset( - recipe.recipe_id - for recipe in IC_LORA_RECIPES.values() - if recipe.catalog_id in HIGH_RES_ONLY_IC_LORAS -) +# Error code of a Keyframes create while the `keyframes` feature flag is off. +KEYFRAMES_NOT_ENABLED = "KEYFRAMES_NOT_ENABLED" def _generation_to_api(record: GenerationRecord) -> Generation: @@ -123,6 +150,7 @@ def _generation_to_api(record: GenerationRecord) -> Generation: spec = dict(record.spec) spec.pop("_analytics", None) spec.pop("_risk", None) + spec.pop(PASS_SHAPE_SPEC_KEY, None) payload["spec"] = spec # Junk fails closed on read the same way execute does. A strict validate # of the raw dict raises on list, get, queue, retry, and cancel. @@ -139,6 +167,18 @@ def _generation_to_api(record: GenerationRecord) -> Generation: QueuedA2VPreflight = Callable[..., GenerationRisk | None] +class LocalA2VDeriver(Protocol): + """Frames from the audio, sized for the resolved shape. Raises HTTPError.""" + + def __call__( + self, + params: CreateAudioToVideoParams, + audio_duration_ms: int, + *, + pass_shape: PassShape, + ) -> AudioToVideoParams: ... + + # Create-time edit window + budget gate. Raises HTTPError; returns the bet annotation. QueuedEditPreflight = Callable[..., GenerationRisk | None] @@ -147,6 +187,21 @@ def _generation_to_api(record: GenerationRecord) -> Generation: QueuedIcLoraRecipePreflight = Callable[..., GenerationRisk | None] +# Advisory verdict per tile size of a recipe create. Per-size failures are returned, never raised. +IcLoraTileSizePreflight = Callable[..., IcLoraTilePreflightResponse] + + +@dataclass(frozen=True) +class _PreparedIcLoraRecipe: + """A recipe create that passed every check before the budget.""" + + recipe: IcLoraRecipe + item: IcLoraCatalogItem + stored: IcLoraVideoRecipeStoredParams + video: AssetRecord + source_fps: float + + # Advisory per-cell verdicts for edit pickers. Per-cell failures are returned, never raised. EditMatrixPreflight = Callable[..., EditPreflightResponse] @@ -166,10 +221,9 @@ def __init__( self, store: Store, executor_registry: ExecutorRegistry, - derive_local_a2v: Callable[[CreateAudioToVideoParams, int], AudioToVideoParams], + derive_local_a2v: LocalA2VDeriver, queue_control: QueueControl | None = None, *, - progress_reader: Callable[[], GenerationProgressResponse] | None = None, config: "RuntimeConfig | None" = None, lora_catalog_provider: LoraCatalogProvider | None = None, state: AppState | None = None, @@ -180,7 +234,11 @@ def __init__( preflight_edit_matrix: EditMatrixPreflight, preflight_queued_ic_lora_recipe: QueuedIcLoraRecipePreflight, preflight_queued_synthesized_ic_lora: QueuedIcLoraRecipePreflight, + preflight_ic_lora_tile_sizes: IcLoraTileSizePreflight, high_res_enabled: Callable[[], bool] | None = None, + keyframes_enabled: Callable[[], bool] | None = None, + should_use_local_encoding: Callable[[], bool] | None = None, + image_generation_status: Callable[[], ImageGenerationStatusResponse] | None = None, ) -> None: self._db = store self._executor_registry = executor_registry @@ -191,10 +249,10 @@ def __init__( self._preflight_edit_matrix = preflight_edit_matrix self._preflight_queued_ic_lora_recipe = preflight_queued_ic_lora_recipe self._preflight_queued_synthesized_ic_lora = preflight_queued_synthesized_ic_lora + self._preflight_ic_lora_tile_sizes = preflight_ic_lora_tile_sizes self._queue_control = ( NoOpQueueControl() if queue_control is None else queue_control ) - self._progress_reader = progress_reader # LoRA-recipe create needs the models dir, the catalog, and HF-auth state to # resolve a catalog id to an installed path and to gate typed misses before # enqueue. Optional so tests that only exercise the plain t2v/i2v create paths @@ -204,10 +262,71 @@ def __init__( self._state = state self._lock = lock self._high_res_enabled = high_res_enabled or (lambda: False) + self._keyframes_enabled = keyframes_enabled or (lambda: False) + self._should_use_local_encoding = should_use_local_encoding + self._image_generation_status = image_generation_status self._finished = FinishedTray() def recover_on_boot(self) -> None: + lanes = self._executor_registry.lanes self._db.fail_running_on_boot() + self._db.reassign_unknown_lanes(lanes.ids) + # A row keeps its provider job id until a cancel succeeds. A failure here, or a stop + # before the cancel ends, leaves the id for the next boot. + orphans = self._db.list_provider_orphans() + cancel_provider_orphans_in_background(orphans, lanes.spec, forget_in(self._db)) + + def _dump_fast_params( + self, + params: BaseModel, + *, + exclude: set[str] | None = None, + uses_torch_compile: bool = True, + ) -> dict[str, JsonValue]: + payload: dict[str, JsonValue] = params.model_dump(mode="json", exclude=exclude) + default_scale = DEFAULT_NAG_SCALE + compile_on = False + local_encoding_on = True + if self._state is not None and self._lock is not None: + with self._lock: + settings = self._state.app_settings + default_scale = settings.nag_scale + compile_on = ( + uses_torch_compile + and settings.use_torch_compile + and not ( + self._config is not None and self._config.use_sage_attention + ) + ) + if self._should_use_local_encoding is not None: + local_encoding_on = self._should_use_local_encoding() + else: + local_encoding_on = not ( + bool(settings.ltx_api_key.strip()) + and not settings.use_local_text_encoder + ) + negative_prompt = getattr(params, "negativePrompt", "") + explicit_scale = getattr(params, "nagScale", None) + decision = decide_nag( + negative_prompt if isinstance(negative_prompt, str) else "", + os.environ, + scale=explicit_scale, + alpha=getattr(params, "nagAlpha", None), + tau=getattr(params, "nagTau", None), + default_scale=default_scale, + local_encoding=local_encoding_on, + compiled=compile_on, + ) + if decision.config is not None: + payload["nagScale"] = decision.config.scale + payload["nagAlpha"] = decision.config.alpha + payload["nagTau"] = decision.config.tau + else: + for key in ("nagScale", "nagAlpha", "nagTau"): + payload.pop(key, None) + if isinstance(explicit_scale, (int, float)) and explicit_scale <= 0.0: + payload["nagScale"] = 0.0 + return payload def create_text_to_video( self, @@ -218,15 +337,17 @@ def create_text_to_video( generation_id: str | None = None, ) -> Generation: spec: dict[str, JsonValue] = { - "params": req.params.model_dump(mode="json"), + "params": self._dump_fast_params(req.params), "inputs": {}, } + pass_shape = self._resolve_pass_shape(req.params.passShape) risk = self._preflight_fast_params( offering=req.params.model, resolution=req.params.resolution, aspect_ratio=req.params.aspectRatio, duration=req.params.duration, fps=req.params.fps, + pass_shape=pass_shape, ) return self._enqueue_generation( TEXT_TO_VIDEO_FEATURE, @@ -236,6 +357,7 @@ def create_text_to_video( analytics_requested_by=analytics_requested_by, generation_id=generation_id, risk=risk, + pass_shape=pass_shape, ) def create_image_to_video( @@ -250,9 +372,10 @@ def create_image_to_video( if req.inputs.endFrame is not None: self._require_image_asset(req.inputs.endFrame.assetId, slot="endFrame") spec: dict[str, JsonValue] = { - "params": req.params.model_dump(mode="json"), + "params": self._dump_fast_params(req.params), "inputs": req.inputs.model_dump(mode="json", exclude_none=True), } + pass_shape = self._resolve_pass_shape(req.params.passShape) risk = self._preflight_fast_params( offering=req.params.model, resolution=req.params.resolution, @@ -261,6 +384,7 @@ def create_image_to_video( ), duration=req.params.duration, fps=req.params.fps, + pass_shape=pass_shape, ) return self._enqueue_generation( IMAGE_TO_VIDEO_FEATURE, @@ -270,6 +394,78 @@ def create_image_to_video( analytics_requested_by=analytics_requested_by, generation_id=generation_id, risk=risk, + pass_shape=pass_shape, + ) + + def create_keyframes( + self, + req: CreateKeyframesRequest, + *, + analytics_client: AnalyticsClient | None = None, + analytics_requested_by: AnalyticsRequestedBy | None = None, + generation_id: str | None = None, + ) -> Generation: + # The flag is the backend gate. Hiding the feature on Home does not stop a direct request. + if not self._keyframes_enabled(): + raise HTTPError(422, KEYFRAMES_NOT_ENABLED, code=KEYFRAMES_NOT_ENABLED) + stills = [ + (keyframe, self._require_image_asset(keyframe.assetId, slot="keyframe")) + for keyframe in req.inputs.keyframes + ] + self._require_offering_capability( + req.params.model, + "multi_keyframe", + code="UNSUPPORTED_MULTI_KEYFRAME", + message="Keyframes are not supported for the selected LTX model.", + ) + # Auto follows the first still on the timeline. Execute picks the same one. + _, first_still = min(stills, key=lambda pair: pair[0].frameIndex) + spec: dict[str, JsonValue] = { + "params": self._dump_fast_params(req.params), + "inputs": req.inputs.model_dump(mode="json"), + } + pass_shape = self._resolve_pass_shape(req.params.passShape) + risk = self._preflight_fast_params( + offering=req.params.model, + resolution=req.params.resolution, + aspect_ratio=self._resolve_queued_preflight_aspect( + req.params.aspectRatio, req.params.resolution, first_still + ), + duration=req.params.duration, + fps=req.params.fps, + pass_shape=pass_shape, + ) + return self._enqueue_generation( + KEYFRAMES_FEATURE, + spec, + contract_version=req.contract_version, + analytics_client=analytics_client, + analytics_requested_by=analytics_requested_by, + generation_id=generation_id, + risk=risk, + pass_shape=pass_shape, + ) + + def create_text_to_image( + self, + req: CreateTextToImageRequest, + *, + analytics_client: AnalyticsClient | None = None, + generation_id: str | None = None, + ) -> Generation: + if self._image_generation_status is None: + raise HTTPError(500, "Image generation status is not configured") + params = resolve_text_to_image_params(req.params, self._image_generation_status()) + spec: dict[str, JsonValue] = { + "params": params.model_dump(mode="json"), + "inputs": {}, + } + return self._enqueue_generation( + TEXT_TO_IMAGE_FEATURE, + spec, + contract_version=req.contract_version, + analytics_client=analytics_client, + generation_id=generation_id, ) def create_lora_recipe( @@ -305,6 +501,60 @@ def create_lora_recipe( except RecipeCreateError as exc: raise HTTPError(422, str(exc), code=exc.code) from exc + return self._enqueue_resolved_lora_run( + feature, + params, + inputs, + contract_version=req.contract_version, + analytics_client=analytics_client, + analytics_requested_by=analytics_requested_by, + generation_id=generation_id, + ) + + def create_custom_lora( + self, + req: CreateCustomLoraRequest, + *, + analytics_client: AnalyticsClient | None = None, + analytics_requested_by: AnalyticsRequestedBy | None = None, + generation_id: str | None = None, + ) -> Generation: + """Create a queued generation for a saved custom LoRA. + + The client sends the custom LoRA id + scale, never a filesystem path. + :func:`resolve_custom_lora_create` reads the LoRA's saved mode and weights path, and + validates the Start Frame rules, before anything is queued. The row is stored under the + ``custom-lora`` feature. + """ + self._require_local_generation_possible() + try: + feature, params, inputs = resolve_custom_lora_create( + req, models_dir=self._models_dir() + ) + except CustomLoraCreateError as exc: + raise HTTPError(exc.status, str(exc), code=exc.code) from exc + return self._enqueue_resolved_lora_run( + feature, + params, + inputs, + contract_version=req.contract_version, + analytics_client=analytics_client, + analytics_requested_by=analytics_requested_by, + generation_id=generation_id, + ) + + def _enqueue_resolved_lora_run( + self, + feature: str, + params: TextToVideoParams | ImageToVideoRecipeParams, + inputs: ImageToVideoInputs | None, + *, + contract_version: int, + analytics_client: AnalyticsClient | None, + analytics_requested_by: AnalyticsRequestedBy | None, + generation_id: str | None, + ) -> Generation: + """Check the input frames, run the Fast budget gate, and enqueue a resolved LoRA run.""" if inputs is not None: start_frame = self._require_image_asset( inputs.startFrame.assetId, slot="startFrame" @@ -313,10 +563,11 @@ def create_lora_recipe( self._require_image_asset(inputs.endFrame.assetId, slot="endFrame") else: start_frame = None - # Same Fast budget gate as the plain t2v/i2v creates: the recipe's params + # Same Fast budget gate as the plain t2v/i2v creates: the run's params # carry the client's offering, and execute budgets via that same field, # so preflighting here admits exactly what the run budgets. i2v auto # resolves from the start frame; t2v never sends auto. + pass_shape = self._resolve_pass_shape(params.passShape) risk = self._preflight_fast_params( offering=params.model, resolution=params.resolution, @@ -325,10 +576,11 @@ def create_lora_recipe( ), duration=params.duration, fps=params.fps, + pass_shape=pass_shape, ) spec: dict[str, JsonValue] = { - "params": params.model_dump(mode="json"), + "params": self._dump_fast_params(params), "inputs": ( inputs.model_dump(mode="json", exclude_none=True) if inputs is not None else {} ), @@ -336,11 +588,12 @@ def create_lora_recipe( return self._enqueue_generation( feature, spec, - contract_version=req.contract_version, + contract_version=contract_version, analytics_client=analytics_client, analytics_requested_by=analytics_requested_by, generation_id=generation_id, risk=risk, + pass_shape=pass_shape, ) def _require_local_generation_possible(self) -> None: @@ -406,9 +659,11 @@ def create_audio_to_video( req.inputs.startFrame.assetId, slot="startFrame" ) ) + pass_shape = self._resolve_pass_shape(req.params.passShape) params = self._derive_local_a2v( req.params, audio.metadata.metadata.durationMs, + pass_shape=pass_shape, ) # budget_shape, the same canvas as a fully dropped row. Auto resolves # from the start frame first; a missing frame falls back to 16:9. @@ -419,9 +674,10 @@ def create_audio_to_video( params.aspectRatio, params.resolution, start_frame, is_a2v=True ), num_frames=params.numFrames, + pass_shape=pass_shape, ) spec: dict[str, JsonValue] = { - "params": params.model_dump(mode="json"), + "params": self._dump_fast_params(params, uses_torch_compile=False), "inputs": req.inputs.model_dump(mode="json", exclude_none=True), } return self._enqueue_generation( @@ -432,6 +688,7 @@ def create_audio_to_video( analytics_requested_by=analytics_requested_by, generation_id=generation_id, risk=risk, + pass_shape=pass_shape, ) def create_retake( @@ -472,10 +729,58 @@ def create_ic_lora_recipe( recipe_id, req, analytics_client=analytics_client, analytics_requested_by=analytics_requested_by, generation_id=generation_id, ) + prepared = self._prepare_ic_lora_recipe(recipe_id, req) + risk = self._preflight_queued_ic_lora_recipe( + item=prepared.item, + video=prepared.video, + stored=prepared.stored, + source_fps=prepared.source_fps, + upscale=prepared.recipe.upscales_to_cell, + cutout=prepared.recipe.cutout, + ) + return self._enqueue_ic_lora_recipe( + prepared.recipe, + prepared.stored, + req, + risk=risk, + analytics_client=analytics_client, + analytics_requested_by=analytics_requested_by, + generation_id=generation_id, + ) + + def preflight_ic_lora_tile_sizes( + self, recipe_id: str, req: IcLoraTilePreflightRequest + ) -> IcLoraTilePreflightResponse: + """Advisory verdict per tile size and window. Every check before the budget is the create's own.""" + prepared = self._prepare_ic_lora_recipe( + recipe_id, + CreateIcLoraRecipeRequest(params=req.params, inputs=req.inputs), + require_prompt=False, + ) + return self._preflight_ic_lora_tile_sizes( + item=prepared.item, + video=prepared.video, + stored=prepared.stored, + source_fps=prepared.source_fps, + upscale=prepared.recipe.upscales_to_cell, + cutout=prepared.recipe.cutout, + tile_sizes=req.tileSizes, + max_windows=req.maxWindows, + carries=req.carries, + ) + + def _prepare_ic_lora_recipe( + self, recipe_id: str, req: CreateIcLoraRecipeRequest, *, require_prompt: bool = True + ) -> _PreparedIcLoraRecipe: + """Every create check that runs before the budget. Raises the create's own 422. + + The tile preflight sets ``require_prompt`` false. An empty prompt must not turn every + verdict into "Prompt is required." Create still refuses an empty prompt. + """ self._require_local_generation_possible() high_res = high_res_cell(req.params.resolution) - if high_res is not None and not self._high_res_enabled(): - raise HTTPError(422, HIGH_RES_NOT_ENABLED, code=HIGH_RES_NOT_ENABLED) + if high_res is not None: + self._require_high_res_cell(recipe_id) video = self._require_asset( req.inputs.video.assetId, slot="video", @@ -502,11 +807,10 @@ def create_ic_lora_recipe( models_dir=self._models_dir(), hf_authenticated=self._hf_authenticated(), source_fps=source_fps, + require_prompt=require_prompt, ) except RecipeCreateError as exc: raise _ic_lora_create_error(exc) from exc - if item.id in HIGH_RES_ONLY_IC_LORAS and not self._high_res_enabled(): - raise HTTPError(422, HIGH_RES_NOT_ENABLED, code=HIGH_RES_NOT_ENABLED) # A high cell runs one tiled stage. An IC-LoRA that keeps its LoRA on stage 2 has no # such run, and its look still cannot go through the tiled path. if high_res is not None and item.default_settings.stage_mode is IcLoraStageMode.STAGE_2_LORA: @@ -536,23 +840,18 @@ def create_ic_lora_recipe( "or a larger clip.", code="IC_LORA_SOURCE_TOO_SMALL", ) - risk = self._preflight_queued_ic_lora_recipe( - item=item, - video=video, - stored=stored, - source_fps=source_fps, - upscale=recipe.upscales_to_cell, - cutout=recipe.cutout, - ) - return self._enqueue_ic_lora_recipe( - recipe, - stored, - req, - risk=risk, - analytics_client=analytics_client, - analytics_requested_by=analytics_requested_by, - generation_id=generation_id, - ) + return _PreparedIcLoraRecipe(recipe, item, stored, video, source_fps) + + def _require_high_res_cell(self, recipe_id: str) -> None: + """422 for a 1440p or 2160p cell of a recipe the highResVideoToVideo flag still gates. + + An unknown id is not treated as a catalog id. The create path reports that id itself. + """ + recipe = IC_LORA_RECIPES.get(recipe_id) + if recipe is None: + return + if not high_res_flag_satisfied(recipe.catalog_id, flag_enabled=self._high_res_enabled()): + raise HTTPError(422, HIGH_RES_NOT_ENABLED, code=HIGH_RES_NOT_ENABLED) def _create_synthesized_ic_lora( self, @@ -604,7 +903,9 @@ def _enqueue_ic_lora_recipe( generation_id: str | None = None, ) -> Generation: spec: dict[str, JsonValue] = { - "params": stored.model_dump(mode="json", exclude={"scale", "variantId"}), + "params": self._dump_fast_params( + stored, exclude={"scale", "variantId"}, uses_torch_compile=False + ), "inputs": req.inputs.model_dump(mode="json", exclude_none=True), } return self._enqueue_generation( @@ -686,7 +987,7 @@ def _enqueue_video_edit( risk = self._preflight_edit_params( feature, asset_path=video.path, params=req.params ) - params_payload = req.params.model_dump(mode="json") + params_payload = self._dump_fast_params(req.params, uses_torch_compile=False) spec: dict[str, JsonValue] = { "params": params_payload, "inputs": req.inputs.model_dump(mode="json", exclude_none=True), @@ -709,6 +1010,7 @@ def _preflight_fast_params( aspect_ratio: LTXQueuedAspectRatio, duration: int | None, fps: LTXVideoGenFps, + pass_shape: PassShape, ) -> GenerationRisk | None: return self._preflight_queued_fast( offering=offering, @@ -716,8 +1018,13 @@ def _preflight_fast_params( aspect_ratio=aspect_ratio, duration=duration, fps=fps, + pass_shape=pass_shape, ) + def _resolve_pass_shape(self, requested: PassShape) -> PassShape: + never_split = self._state is not None and self._state.app_settings.never_split_into_parts + return resolve_pass_shape(requested, never_split=never_split) + @staticmethod def _resolve_queued_preflight_aspect( aspect_ratio: LTXQueuedAspectRatio, @@ -863,6 +1170,7 @@ def _enqueue_generation( analytics_requested_by: AnalyticsRequestedBy | None = None, generation_id: str | None = None, risk: GenerationRisk | None = None, + pass_shape: PassShape | None = None, ) -> Generation: try: self._executor_registry.validate_params( @@ -882,6 +1190,8 @@ def _enqueue_generation( ) from exc if risk is not None: spec = {**spec, "_risk": risk.model_dump(mode="json")} + if pass_shape is not None: + spec = {**spec, PASS_SHAPE_SPEC_KEY: pass_shape} if analytics_client is not None: analytics: dict[str, JsonValue] = {"client": analytics_client} if analytics_requested_by is not None: @@ -893,6 +1203,7 @@ def _enqueue_generation( spec, contract_version=contract_version, generation_id=generation_id, + lane=self._executor_registry.lane_for(feature, spec), ) except UnavailableError as exc: raise HTTPError(503, "STORE_UNAVAILABLE") from exc @@ -905,7 +1216,9 @@ def _enqueue_generation( def retry_generation(self, generation_id: str) -> Generation: try: - record = self._db.retry_generation(generation_id) + record = self._db.retry_generation( + generation_id, lane=self._lane_for_stored(generation_id) + ) except UnavailableError as exc: raise HTTPError(503, "STORE_UNAVAILABLE") from exc except KeyError as exc: @@ -916,12 +1229,31 @@ def retry_generation(self, generation_id: str) -> Generation: self._queue_control.wake() return _generation_to_api(record) + def _lane_for_stored(self, generation_id: str) -> str | None: + """The lane a stored job runs on now. None keeps the stored lane. + + The registry can differ from the one at insert (the kill switch, a removed provider). + """ + try: + stored = self._db.get_generation(generation_id) + except UnavailableError: + return None + if stored is None: + return None + try: + return self._executor_registry.lane_for(stored.feature, stored.spec) + except ValueError: + # The spec or the feature is no longer valid. The job fails when it runs. + # It still needs a lane that has a runner. + return self._executor_registry.lanes.resolve(stored.lane) + def cancel_generation(self, generation_id: str) -> Generation: try: record = cancel_queued_generation( self._db, generation_id, self._queue_control.interrupt, + uncancellable_lanes=self._executor_registry.lanes.uncancellable_ids, ) except UnavailableError as exc: raise HTTPError(503, "STORE_UNAVAILABLE") from exc @@ -939,19 +1271,11 @@ def get_queue_snapshot(self) -> QueueSnapshot: except UnavailableError as exc: raise HTTPError(503, "STORE_UNAVAILABLE") from exc - active_record = next( - ( - entry - for entry in entries - if entry.generation.status in {"running", "cancelling"} - ), - None, - ) - active = ( - self._queue_entry(active_record, self._active_progress(active_record)) - if active_record is not None - else None - ) + active = [ + self._active_entry(entry) + for entry in entries + if entry.generation.status in {"running", "cancelling"} + ] queued = [ self._queue_entry(entry, None) for entry in entries @@ -1018,24 +1342,24 @@ def reorder_queue( self._queue_control.wake() return self.get_queue_snapshot() - def _active_progress( - self, active: QueueGenerationRecord - ) -> QueueProgress | None: - if self._progress_reader is None: - return None - progress = self._progress_reader() - if progress.id != active.generation.id: - return None - return QueueProgress( - phase=progress.phase, - progress=progress.progress, - currentStep=progress.currentStep, - totalSteps=progress.totalSteps, + def _active_entry(self, entry: QueueGenerationRecord) -> QueueEntry: + live = self._queue_control.live_state(entry.generation.id) + if live is None: + return self._queue_entry(entry, None) + return self._queue_entry( + entry, + live.progress, + cancellable=live.cancellable, + api_status=live.api_status, ) @staticmethod def _queue_entry( - entry: QueueGenerationRecord, progress: QueueProgress | None + entry: QueueGenerationRecord, + progress: QueueProgress | None, + *, + cancellable: bool = True, + api_status: ApiActivityStatus | None = None, ) -> QueueEntry: return QueueEntry( generation=_generation_to_api(entry.generation), @@ -1044,6 +1368,8 @@ def _queue_entry( for asset in entry.input_assets ], progress=progress, + cancellable=cancellable, + api_status=api_status, ) def list_generations(self, feature: str | None = None, *, limit: int | None = None) -> list[Generation]: @@ -1056,10 +1382,10 @@ def list_generations(self, feature: str | None = None, *, limit: int | None = No def list_recent_features( self, *, limit: int, allowed: Collection[str] | None = None ) -> list[str]: - if allowed is not None and not self._high_res_enabled(): - # Drop the hidden recipes before the store applies the limit, so they do + if allowed is not None and not self._keyframes_enabled(): + # Drop the hidden feature before the store applies the limit, so it does # not take a slot from an older feature that is offered. - allowed = [name for name in allowed if name not in _HIGH_RES_ONLY_RECIPE_IDS] + allowed = [name for name in allowed if name != KEYFRAMES_FEATURE] try: return self._db.list_recent_features(limit=limit, allowed=allowed) except UnavailableError as exc: diff --git a/backend/handlers/queued_image_handler.py b/backend/handlers/queued_image_handler.py new file mode 100644 index 000000000..90be9feb9 --- /dev/null +++ b/backend/handlers/queued_image_handler.py @@ -0,0 +1,188 @@ +"""Queued text-to-image jobs: the local pipeline lane and the fal API lane.""" + +from __future__ import annotations + +import io +import logging +from collections.abc import Callable +from contextlib import AbstractContextManager, nullcontext +from pathlib import Path +from threading import RLock +from typing import TYPE_CHECKING + +from _routes._errors import HTTPError +from api_types import TextToImageStoredParams, ZIT_DEFAULT_STEPS +from handlers.base import StateHandlerBase +from handlers.generation_handler import GenerationHandler +from handlers.image_generation_handler import text_to_image_on_pipeline +from handlers.image_prompt_plan import plan_fal_image_prompt +from handlers.pipelines_handler import PipelinesHandler +from handlers.prompt_enhancement_handler import PromptEnhancementHandler +from server_utils.heartbeat import log_heartbeat +from services.features.image.text_to_image import QueuedImageResult +from services.generation_queue.sessions import JobSession +from services.interfaces import ZitAPIClient +from services.zit_api_client.zit_api_client import ZitImageBlockedError +from state.app_state_types import AppState + +if TYPE_CHECKING: + from runtime_config.runtime_config import RuntimeConfig + +logger = logging.getLogger(__name__) + + +class QueuedImageHandler(StateHandlerBase): + def __init__( + self, + state: AppState, + lock: RLock, + generation_handler: GenerationHandler, + pipelines_handler: PipelinesHandler, + config: RuntimeConfig, + zit_api_client: ZitAPIClient, + prompt_enhancement_handler: PromptEnhancementHandler, + lease_idle_gpu: Callable[[], AbstractContextManager[bool]], + ) -> None: + super().__init__(state, lock, config) + self._generation = generation_handler + self._pipelines = pipelines_handler + self._zit_api_client = zit_api_client + self._prompt_enhancement = prompt_enhancement_handler + self._lease_idle_gpu = lease_idle_gpu + + def _gpu_lease_for(self, session: JobSession) -> Callable[[], AbstractContextManager[bool]]: + """A job that holds the GPU slot (the kill switch runs fal on the local lane) needs no lease.""" + if session.holds_gpu_slot: + return lambda: nullcontext(True) + return self._lease_idle_gpu + + def cancel_fal_request(self, request_id: str) -> None: + """The cancel of the fal lane for a job that a stopped app left at fal.""" + api_key = self.state.app_settings.fal_api_key.strip() + if not api_key: + raise RuntimeError("FAL API key is not configured") + self._zit_api_client.cancel_queued(api_key=api_key, request_id=request_id) + + def generate_queued( + self, + params: TextToImageStoredParams, + *, + generation_id: str, + output_path: Path, + session: JobSession, + ) -> QueuedImageResult: + """Run one queued text-to-image job. + + Text-to-image only: the Z-Image edit path is never used. Raises on failure and on + cancellation, and removes a partial output. The job reports through its session, so + a job on the fal lane never touches the local generation state. + """ + explicit_seed = params.seed is not None + seed = params.seed if params.seed is not None else self._resolve_seed() + try: + if params.provider == "fal": + image_bytes, result = self._via_api( + session, params, seed=seed, explicit_seed=explicit_seed + ) + else: + image_bytes = self._via_local( + session, generation_id, params, seed=seed, explicit_seed=explicit_seed + ) + result = QueuedImageResult() + session.raise_if_cancelled() + output_path.write_bytes(image_bytes) + session.set_progress("complete", 100, None, None) + session.complete(str(output_path)) + return result + except Exception as e: + output_path.unlink(missing_ok=True) + session.fail(e.detail if isinstance(e, HTTPError) else str(e)) + raise + + def _via_local( + self, + session: JobSession, + generation_id: str, + params: TextToImageStoredParams, + *, + seed: int, + explicit_seed: bool, + ) -> bytes: + prompt = self._prompt_enhancement.rewrite_image_prompt( + params.prompt, + provenance=params.promptProvenance, + generation_seed=seed, + explicit_generation_seed=explicit_seed, + raise_if_cancelled=session.raise_if_cancelled, + ).prompt + session.raise_if_cancelled() + steps = ZIT_DEFAULT_STEPS + session.set_progress("loading_model", 5, 0, steps) + pipeline = self._pipelines.load_image_generation_pipeline_to_gpu() + # The local pipeline owns the global GPU state. Only the local lane runs this path. + self._generation.start_generation(generation_id) + session.set_progress("inference", 15, 0, steps) + with log_heartbeat(f"zit image {params.width}x{params.height}"): + image = text_to_image_on_pipeline( + pipeline, + prompt=prompt, + width=params.width, + height=params.height, + num_inference_steps=steps, + seed=seed, + ) + buffer = io.BytesIO() + image.save(buffer, format="PNG") + return buffer.getvalue() + + def _via_api( + self, + session: JobSession, + params: TextToImageStoredParams, + *, + seed: int, + explicit_seed: bool, + ) -> tuple[bytes, QueuedImageResult]: + api_key = self.state.app_settings.fal_api_key.strip() + session.start_api() + session.set_progress("validating_request", 5, None, None) + if not api_key: + raise HTTPError(422, "FAL_API_KEY_NOT_CONFIGURED") + session.raise_if_cancelled() + planned = plan_fal_image_prompt( + self._prompt_enhancement, + params.prompt, + provenance=params.promptProvenance, + generation_seed=seed, + explicit_generation_seed=explicit_seed, + lease_idle_gpu=self._gpu_lease_for(session), + raise_if_cancelled=session.raise_if_cancelled, + ) + prompt = planned.prompt + session.raise_if_cancelled() + session.set_progress("inference", 15, None, None) + try: + queued = self._zit_api_client.generate_text_to_image_queued( + api_key=api_key, + prompt=prompt, + width=params.width, + height=params.height, + seed=seed, + num_inference_steps=ZIT_DEFAULT_STEPS, + enable_prompt_expansion=planned.expand_on_provider, + on_status=session.set_api_status, + on_submitted=session.set_provider_job_id, + wait_cancelled=session.wait_cancelled, + ) + except ZitImageBlockedError as exc: + raise HTTPError(422, "IMAGE_BLOCKED_BY_SAFETY_CHECKER") from exc + # The provider's expansion replaces the typed prompt on the finished row. A rewrite + # done here does not: the local provider keeps the typed prompt in the same case. + written = ( + queued.prompt + if planned.expand_on_provider and queued.prompt not in (None, prompt) + else None + ) + return queued.image_bytes, QueuedImageResult( + written_prompt=written, prompt_rewrite=planned.rewrite_source + ) diff --git a/backend/handlers/resolved_generation_prompt.py b/backend/handlers/resolved_generation_prompt.py new file mode 100644 index 000000000..d46e1c41f --- /dev/null +++ b/backend/handlers/resolved_generation_prompt.py @@ -0,0 +1,39 @@ +"""The prompt a local generation submits, and how it got enhanced.""" + +from __future__ import annotations + +from typing import Literal, NamedTuple + +from api_types import PromptProvenance +from services.analytics import prompt_provenance_label as shared_prompt_provenance_label + + +class ResolvedGenerationPrompt(NamedTuple): + """The prompt a local generation should submit, and how it got (or will get) enhanced.""" + + prompt: str + enhance_via_api: bool + enhanced_locally: bool + skip_recipe_wrap: bool = False + + @property + def enhancement(self) -> str: + """Where the rewrite happens, for run logs: local, server-side, or nowhere.""" + if self.enhanced_locally: + return "local" + return "api" if self.enhance_via_api else "none" + + +PromptProvenanceLabel = Literal["raw", "manually-enhanced", "auto-enhanced"] + + +def prompt_provenance_label( + provenance: PromptProvenance, + resolved: ResolvedGenerationPrompt, +) -> PromptProvenanceLabel: + """How this run asked for the prompt to be passed. Not the prompt text.""" + return shared_prompt_provenance_label( + provenance, + enhanced_locally=resolved.enhanced_locally, + enhance_via_api=resolved.enhance_via_api, + ) diff --git a/backend/handlers/retake_handler.py b/backend/handlers/retake_handler.py index 835f65295..9e60ef9f4 100644 --- a/backend/handlers/retake_handler.py +++ b/backend/handlers/retake_handler.py @@ -227,13 +227,13 @@ def _run_local_retake( ) try: - pipeline_state = self._pipelines.load_retake_pipeline( + pipeline_state, ran = self._pipelines.load_retake_pipeline( distilled=True, width=target_width, height=target_height, frames=target_frames, ) - self._generation.start_generation(generation_id) + self._generation.start_generation(generation_id, ran=ran) self._generation.update_progress("loading_model", 5, 0, 1) self._generation.update_progress("inference", 15, 0, 1) @@ -265,7 +265,7 @@ def _run_local_retake( raise GenerationCancelledError() self._generation.update_progress("complete", 100, 1, 1) - self._generation.complete_generation(str(output_path)) + self._generation.complete_generation(str(output_path), ran=ran) return RetakeVideoResponse(status="complete", video_path=str(output_path)) except HTTPError: self._generation.fail_generation("Retake generation failed") diff --git a/backend/handlers/video_generation_handler.py b/backend/handlers/video_generation_handler.py index 702d68969..8caf335f1 100644 --- a/backend/handlers/video_generation_handler.py +++ b/backend/handlers/video_generation_handler.py @@ -52,8 +52,8 @@ EtaFeature, EtaLoadMode, WallTimeEstimate, + default_machine_factor, estimate_fast_wall_time_s, - is_measured_hardware_class, ) from runtime_config.evict_retry import evict_retry_filter from runtime_config.ltx_capabilities import ( @@ -68,17 +68,18 @@ ) from runtime_config.low_performance_machine import detect_low_performance_machine from runtime_config.models_scanner import resolve_lora_ref +from runtime_config.budget_admission import Admitted, Refused, RiskAllowance, admit +from runtime_config.reject_reasons import PassShape +from runtime_config.device_calibration import JobEnvelope from runtime_config.runtime_policy import LocalGenerationMode from runtime_config.video_job_budget import ( LOCAL_GENERATION_UNSUPPORTED, LOCAL_GENERATION_UNSUPPORTED_MESSAGE, LocalJobFilter, - VideoJobLoad, - VideoJobReject, + decide_video_job, + price_video_job, reject_message_and_code, - risk_for_reject, - risk_if_allowed, - unmeasured_load_risk, + video_job_reject, vram_snapshot_suffix, ) from _routes._errors import HTTPError @@ -105,13 +106,18 @@ ) from server_utils.oriented_image import open_oriented_rgb, oriented_image_file from services.denoising_progress import distilled_total_steps +from services.fast_video_pipeline.nag_config import ( + NagDecision, + decide_nag, + log_nag_decision, +) from services.generation_interrupt import GenerationCancelledError, is_cancel_exception from services.interfaces import GpuInfo, LTXAPIClient from services.ltx_api_client.ltx_api_client import LTXAPIClientError from services.ltx_api_client.ltx_api_errors import map_ltx_api_client_error, missing_ltx_api_key_error from services.patches import diffusion_stage_cache from state.app_state_types import AppState -from state.app_settings import should_video_generate_with_ltx_api +from state.app_settings import resolved_use_conv_vae, should_video_generate_with_ltx_api if TYPE_CHECKING: from runtime_config.runtime_config import RuntimeConfig @@ -124,15 +130,6 @@ def _upload_oriented_image(client: LTXAPIClient, *, api_key: str, path: Path) -> return client.upload_file(api_key=api_key, file_path=str(upload_path)) -def _lora_catalog_ids(loras: list[LoraEntry]) -> list[str]: - """The catalog ids among the selected LoRAs, for catalog-aware prompt enhancement. - - A custom LoRA carries none and stays weights-only: its filename is deliberately not - matched against the catalog, which would attach a stranger's trigger phrase to it. - """ - return [entry.catalogId for entry in loras if entry.catalogId is not None] - - FORCED_API_RESOLUTION_MAP: dict[str, dict[str, dict[str, str]]] = forced_api_resolution_map() @@ -140,8 +137,22 @@ def _a2v_fps_durations( item: LTXVideoGenerationModelSpecItem | None, resolution: LTXLocalA2VResolution, fps: LTXVideoGenFps, + *, + aspect_ratio: LTXQueuedAspectRatio = "16:9", ) -> list[int]: - duration_map = None if item is None else item.spec.a2v_supported_resolutions_durations + if item is None: + return [] + aspect: LtxAspectRatio = "16:9" if aspect_ratio == "auto" else aspect_ratio + aspect_spec = ( + item.spec.aspect_specs.get(aspect) + if item.spec.aspect_specs is not None + else None + ) + duration_map = ( + aspect_spec.a2v_supported_resolutions_durations + if aspect_spec is not None + else item.spec.a2v_supported_resolutions_durations + ) if duration_map is None: return [] resolution_spec = duration_map.get(resolution) @@ -231,11 +242,18 @@ def estimate_local_fast(self, req: EstimateVideoRequest) -> EstimateVideoRespons mode=canvas_mode, ) frames = compute_num_frames(req.duration, req.fps) - load_mode, risk = self._video_job_load_mode( + admitted = self._video_job_load( budget_width, budget_height, frames, job_filter=job_filter ) + load_mode, risk = admitted.load.mode, admitted.risk est = self._estimate_wall_time( - budget_width, budget_height, frames, load_mode, req.feature + budget_width, + budget_height, + frames, + load_mode, + req.feature, + chunk_pixel_frames=admitted.load.chunk_pixel_frames, + stage_2=not local_canvas(req.resolution, mode=canvas_mode).skip_stage_2, ) if est is None: return EstimateVideoResponse(estimate=None, risk=risk) @@ -247,7 +265,11 @@ def estimate_local_fast(self, req: EstimateVideoRequest) -> EstimateVideoRespons ) def derive_local_a2v_params( - self, params: CreateAudioToVideoParams, audio_duration_ms: int + self, + params: CreateAudioToVideoParams, + audio_duration_ms: int, + *, + pass_shape: PassShape, ) -> AudioToVideoParams: num_frames = self._local_a2v_num_frames( resolution=params.resolution, @@ -255,6 +277,7 @@ def derive_local_a2v_params( fps=params.fps, aspect_ratio=params.aspectRatio, audio_duration_ms=audio_duration_ms, + pass_shape=pass_shape, ) return AudioToVideoParams( **params.model_dump(mode="python"), @@ -262,7 +285,11 @@ def derive_local_a2v_params( ) def validate_local_a2v_request( - self, params: AudioToVideoParams, audio_duration_ms: int + self, + params: AudioToVideoParams, + audio_duration_ms: int, + *, + pass_shape: PassShape, ) -> None: num_frames = self._local_a2v_num_frames( resolution=params.resolution, @@ -270,6 +297,7 @@ def validate_local_a2v_request( fps=params.fps, aspect_ratio=params.aspectRatio, audio_duration_ms=audio_duration_ms, + pass_shape=pass_shape, ) if params.numFrames != num_frames: raise HTTPError( @@ -342,6 +370,7 @@ def _local_a2v_num_frames( fps: LTXVideoGenFps, aspect_ratio: LTXQueuedAspectRatio, audio_duration_ms: int, + pass_shape: PassShape, ) -> int: # Envelope of the checkpoint that will actually run, not the catalog # preferred row (2.3 1.1 while only 1.0 is on disk). @@ -406,9 +435,13 @@ def _local_a2v_num_frames( ) # Total, like queued create: create and execute agree on the shape. # Free fit is the execute gate's problem. - job_filter = self._local_job_filter(model_id=a2v_model_id, total_only=True) + job_filter = self._local_job_filter( + model_id=a2v_model_id, total_only=True, pass_shape=pass_shape + ) filtered_item = self._fast_local_spec_item(a2v_model_id, job_filter=job_filter) - kept = _a2v_fps_durations(filtered_item, resolution, fps) + kept = _a2v_fps_durations( + filtered_item, resolution, fps, aspect_ratio=aspect_ratio + ) if not kept: # The picker dropped the whole row. That stays a hard refusal in # every mode: there is no warned cell to accept. A derived shape @@ -459,8 +492,8 @@ def generate_local_reserved( a2v_audio_duration_seconds: float | None = None, local_model_id: LTXLocalModelId, explore_generation: bool = True, - risk_allowance: bool | None = None, - unmeasured_bet: bool = False, + allowance: RiskAllowance | None = None, + pass_shape: PassShape | None = None, ) -> GenerateVideoResponse: # Local-only Home/Remote entry: checkpoint is required. GenSpace # ``generate()`` still uses Settings via ``_generate_local_reserved_validated``. @@ -477,8 +510,8 @@ def generate_local_reserved( a2v_audio_duration_seconds=a2v_audio_duration_seconds, local_model_id=local_model_id, explore_generation=explore_generation, - risk_allowance=risk_allowance, - unmeasured_bet=unmeasured_bet, + allowance=allowance, + pass_shape=pass_shape, ) def _validate_generate_video_request( @@ -509,8 +542,8 @@ def _generate_local_reserved_validated( a2v_audio_duration_seconds: float | None = None, local_model_id: LTXLocalModelId | None = None, explore_generation: bool = False, - risk_allowance: bool | None = None, - unmeasured_bet: bool = False, + allowance: RiskAllowance | None = None, + pass_shape: PassShape | None = None, ) -> GenerateVideoResponse: resolution = req.resolution duration = req.duration @@ -536,8 +569,8 @@ def _generate_local_reserved_validated( audio_duration_seconds=a2v_audio_duration_seconds, local_model_id=job_model_id, explore_generation=explore_generation, - risk_allowance=risk_allowance, - unmeasured_bet=unmeasured_bet, + allowance=allowance, + pass_shape=pass_shape, ) logger.info("Resolution %s - using fast pipeline", resolution) @@ -551,7 +584,7 @@ def _generate_local_reserved_validated( width = snap_up_to_multiple(width, 64) height = snap_up_to_multiple(height, 64) - job_filter = self._local_job_filter(model_id=job_model_id) + job_filter = self._local_job_filter(model_id=job_model_id, pass_shape=pass_shape) if duration is None: item = next( candidate @@ -564,7 +597,10 @@ def _generate_local_reserved_validated( ) try: min_seconds, max_seconds = supported_duration_range( - item, resolution=resolution, fps=fps + item, + resolution=resolution, + fps=fps, + aspect_ratio=req.aspectRatio, ) except KeyError: # Validated against the static ceiling but fully @@ -580,13 +616,12 @@ def _generate_local_reserved_validated( aspect_ratio=req.aspectRatio, fps=fps, allow_evict_retry=True, - allow_risk=risk_allowance, - unmeasured_bet=unmeasured_bet, + allowance=allowance, ) # The static probe may have evicted the resident pipeline to # admit the range; re-sample so the gate below prices the # freed card instead of the stale pre-evict filter. - job_filter = self._local_job_filter(model_id=job_model_id) + job_filter = self._local_job_filter(model_id=job_model_id, pass_shape=pass_shape) num_frames: int | AutoDurationSpec = AutoDurationSpec( min_seconds=float(min_seconds), max_seconds=float(max_seconds), @@ -637,14 +672,13 @@ def _generate_local_reserved_validated( budget_width, budget_height = budget_shape( local_caps(job_model_id), resolution, req.aspectRatio, mode="video" ) - load_mode, chunk_pixel_frames = self._plan_video_job( + load_mode, chunk_pixel_frames, envelope = self._plan_video_job( budget_width, budget_height, self._budget_frame_count(num_frames, fps), job_filter=job_filter, allow_evict_retry=True, - allow_risk=risk_allowance, - unmeasured_bet=unmeasured_bet, + allowance=allowance, ) try: @@ -652,6 +686,14 @@ def _generate_local_reserved_validated( # enhancement needs the VRAM a resident pipeline holds, and evicting a pipeline is # refused once a generation is running. Budget 422 already happened so Gemma is # not loaded for a job this machine cannot run. + nag_decision = self._decide_nag( + req.negativePrompt, + scale=req.nagScale, + alpha=req.nagAlpha, + tau=req.nagTau, + local_encoding=self._text.should_use_local_encoding(job_model_id), + compiled=True, + ) resolved_prompt = self._prompt_enhancement.resolve_for_generation( req.prompt, provenance=req.promptProvenance, @@ -662,9 +704,10 @@ def _generate_local_reserved_validated( keyframes=enhance_keyframes, duration=req.duration, fps=req.fps, - lora_catalog_ids=_lora_catalog_ids(req.loras), + loras=req.loras, local_model_id=job_model_id, explore_generation=explore_generation, + negative_prompt=nag_decision.enhancer_negative, ) # Recipe-scoped: applied after enhancement so the LLM rewrites the user # scene, then the fixed scaffold wraps the result. None (and thus @@ -705,11 +748,13 @@ def _generate_local_reserved_validated( self._generation.start_generation( generation_id, estimated=self._estimate_wall_time( - width, - height, + budget_width, + budget_height, self._budget_frame_count(num_frames, fps), load_mode, "i2v" if has_image_input else "t2v", + chunk_pixel_frames=chunk_pixel_frames, + stage_2=not canvas.skip_stage_2, ), ) @@ -732,9 +777,16 @@ def _generate_local_reserved_validated( ltx_model_id=job_model_id, skip_stage_2=canvas.skip_stage_2, chunk_pixel_frames=chunk_pixel_frames, + nag_scale=req.nagScale, + nag_alpha=req.nagAlpha, + nag_tau=req.nagTau, ) - self._generation.complete_generation(written_path) + self._generation.complete_generation( + written_path, + # Auto duration priced its ceiling and ran shorter: not a proof of the ceiling. + ran=None if isinstance(num_frames, AutoDurationSpec) else envelope, + ) return self._complete_response(written_path, load_mode) except HTTPError as e: @@ -748,6 +800,34 @@ def _generate_local_reserved_validated( raise HTTPError(500, str(e)) from e + def _decide_nag( + self, + negative_prompt: str, + *, + scale: float | None, + alpha: float | None, + tau: float | None, + local_encoding: bool, + compiled: bool = False, + ) -> NagDecision: + with self._lock: + default_nag_scale = self.state.app_settings.nag_scale + compile_enabled = ( + compiled + and self.state.app_settings.use_torch_compile + and not self.config.use_sage_attention + ) + return decide_nag( + negative_prompt, + os.environ, + scale=scale, + alpha=alpha, + tau=tau, + default_scale=default_nag_scale, + local_encoding=local_encoding, + compiled=compile_enabled, + ) + def _resolve_loras( self, loras: list[LoraEntry], @@ -790,6 +870,9 @@ def generate_video( ltx_model_id: LTXLocalModelId | None = None, skip_stage_2: bool = False, chunk_pixel_frames: int | None = None, + nag_scale: float | None = None, + nag_alpha: float | None = None, + nag_tau: float | None = None, ) -> str: t_total_start = time.perf_counter() gen_mode = "keyframes" if keyframe_images else "i2v" if image is not None else "t2v" @@ -836,6 +919,29 @@ def generate_video( t_text_end = time.perf_counter() logger.info("[%s] Text encoding (%s): %.2fs", gen_mode, encoding_method, t_text_end - t_text_start) + # Negative prompt through NAG. API text encoding returns zeros for any prompt + # after the first, so NAG needs local encoding. + with self._lock: + default_nag_scale = self.state.app_settings.nag_scale + compile_enabled = ( + self.state.app_settings.use_torch_compile + and not self.config.use_sage_attention + ) + nag = log_nag_decision( + logger, + gen_mode, + decide_nag( + negative_prompt, + os.environ, + scale=nag_scale, + alpha=nag_alpha, + tau=nag_tau, + default_scale=default_nag_scale, + local_encoding=encoding_method == "local", + compiled=pipeline_state.is_compiled or compile_enabled, + ), + ) + self._generation.raise_if_cancelled() self._generation.update_progress("inference", 15) @@ -859,6 +965,7 @@ def generate_video( guide_all_images=bool(keyframe_images), skip_stage_2=skip_stage_2, chunk_pixel_frames=chunk_pixel_frames, + nag=nag, ) t_inference_end = time.perf_counter() logger.info("[%s] Inference: %.2fs", gen_mode, t_inference_end - t_inference_start) @@ -894,8 +1001,8 @@ def _generate_a2v( audio_duration_seconds: float | None = None, local_model_id: LTXLocalModelId | None = None, explore_generation: bool = False, - risk_allowance: bool | None = None, - unmeasured_bet: bool = False, + allowance: RiskAllowance | None = None, + pass_shape: PassShape | None = None, ) -> GenerateVideoResponse: model_id = local_model_id if model_id is None: @@ -954,14 +1061,13 @@ def _generate_a2v( # Decided pre-try like the Fast path: a 422 here propagates without # failing a generation that never started, and the cancelled branch # below always sees a bound mode. - load_mode, chunk_pixel_frames = self._plan_video_job( + load_mode, chunk_pixel_frames, envelope = self._plan_video_job( width, height, num_frames, - job_filter=self._local_job_filter(model_id=model_id), + job_filter=self._local_job_filter(model_id=model_id, pass_shape=pass_shape), allow_evict_retry=True, - allow_risk=risk_allowance, - unmeasured_bet=unmeasured_bet, + allowance=allowance, ) try: @@ -973,6 +1079,14 @@ def _generate_a2v( # Same ordering as Fast: budget 422 before Gemma so an over-size cell # does not evict a warmed pipeline for a rewrite that will not run. + nag_decision = self._decide_nag( + req.negativePrompt, + scale=req.nagScale, + alpha=req.nagAlpha, + tau=req.nagTau, + local_encoding=self._text.should_use_local_encoding(model_id), + compiled=False, + ) resolved_prompt = self._prompt_enhancement.resolve_for_generation( req.prompt, provenance=req.promptProvenance, @@ -980,10 +1094,11 @@ def _generate_a2v( explicit_generation_seed=req.seed is not None, image_path=image_path, last_image_path=last_image_path, - lora_catalog_ids=_lora_catalog_ids(req.loras), + loras=req.loras, local_model_id=model_id, explore_generation=explore_generation, audio_path=audio_path_str, + negative_prompt=nag_decision.enhancer_negative, ) enhanced_prompt = resolved_prompt.prompt + self.config.camera_motion_prompts.get(req.cameraMotion, "") @@ -994,7 +1109,12 @@ def _generate_a2v( self._generation.start_generation( generation_id, estimated=self._estimate_wall_time( - width, height, num_frames, load_mode, "a2v" + width, + height, + num_frames, + load_mode, + "a2v", + chunk_pixel_frames=chunk_pixel_frames, ), ) @@ -1003,11 +1123,26 @@ def _generate_a2v( self._generation.update_progress("loading_model", 5) self._generation.update_progress("encoding_text", 10) + encoding_method = ( + "api" if not self._text.should_use_local_encoding(model_id) else "local" + ) self._text.prepare_text_encoding( enhanced_prompt, enhance_prompt=resolved_prompt.enhance_via_api, model_id=model_id, ) + nag = log_nag_decision( + logger, + "a2v", + self._decide_nag( + req.negativePrompt, + scale=req.nagScale, + alpha=req.nagAlpha, + tau=req.nagTau, + local_encoding=encoding_method == "local", + compiled=False, + ), + ) self._generation.raise_if_cancelled() self._generation.update_progress("inference", 15) @@ -1031,6 +1166,7 @@ def _generate_a2v( ), output_path=str(output_path), chunk_pixel_frames=chunk_pixel_frames, + nag=nag, ) # Denoiser interrupt cannot abort VAE decode / ffmpeg; a Stop after the last @@ -1041,7 +1177,7 @@ def _generate_a2v( raise GenerationCancelledError() self._generation.update_progress("complete", 100) - self._generation.complete_generation(str(output_path)) + self._generation.complete_generation(str(output_path), ran=envelope) return self._complete_response(str(output_path), load_mode) except HTTPError as e: @@ -1146,20 +1282,18 @@ def _plan_video_job( *, job_filter: LocalJobFilter, allow_evict_retry: bool = False, - allow_risk: bool | None = None, - unmeasured_bet: bool = False, - ) -> tuple[LocalGenerationMode, int | None]: - """Load mode and temporal window (pixel frames, None = one pass) for this job.""" - load, _ = self._video_job_load( + allowance: RiskAllowance | None = None, + ) -> tuple[LocalGenerationMode, int | None, JobEnvelope]: + """Load mode, temporal window (pixel frames, None = one pass), and the priced envelope.""" + admitted = self._video_job_load( width, height, frames, job_filter=job_filter, allow_evict_retry=allow_evict_retry, - allow_risk=allow_risk, - unmeasured_bet=unmeasured_bet, + allowance=allowance, ) - return load.mode, load.chunk_pixel_frames + return admitted.load.mode, admitted.load.chunk_pixel_frames, admitted.envelope def _video_job_load_mode( self, @@ -1169,19 +1303,17 @@ def _video_job_load_mode( *, job_filter: LocalJobFilter, allow_evict_retry: bool = False, - allow_risk: bool | None = None, - unmeasured_bet: bool = False, + allowance: RiskAllowance | None = None, ) -> tuple[LocalGenerationMode, GenerationRisk | None]: - load, risk = self._video_job_load( + admitted = self._video_job_load( width, height, frames, job_filter=job_filter, allow_evict_retry=allow_evict_retry, - allow_risk=allow_risk, - unmeasured_bet=unmeasured_bet, + allowance=allowance, ) - return load.mode, risk + return admitted.load.mode, admitted.risk def _video_job_load( self, @@ -1191,30 +1323,28 @@ def _video_job_load( *, job_filter: LocalJobFilter, allow_evict_retry: bool = False, - allow_risk: bool | None = None, - unmeasured_bet: bool = False, - ) -> tuple[VideoJobLoad, GenerationRisk | None]: - """422 or pick full vs stream (and the window) for this job. Does not change process mode. + allowance: RiskAllowance | None = None, + ) -> Admitted: + """422 or admit this job: full vs stream, the window, and any bet. Does not change process mode. Real-generation paths pass ``allow_evict_retry``: a total-possible CUDA reject whose shortfall live weights cover gets one evict-and-resample - before the 422. Read-only callers (estimate) and total-only preflights + before admission. Read-only callers (estimate) and total-only preflights must leave it off — the former must never mutate GPU state, the latter - reject total-short by construction. ``allow_risk=None`` follows the - filter's live mode (every request-scoped caller); executors pass an - explicit bool parsed from the stored annotation so a mode flip never - re-gates a queued job. An over bet streams, including when the + reject total-short by construction. ``allowance=None`` follows the + filter's live mode (every request-scoped caller); executors pass the + allowance stored at create, and a filter built with the stored shape, + so a settings flip never re-gates or re-cuts a queued job. An over bet streams, including when the shortfall later grows. An unmeasured bet does not cover a later memory miss. Hard rejects raise in every mode. """ - decision = job_filter.decide(width, height, frames) - if isinstance(decision, VideoJobReject) and allow_evict_retry: + allowance = allowance if allowance is not None else RiskAllowance.for_mode(job_filter.budget_mode) + priced = price_video_job( + width, height, frames, job_filter=job_filter, allowance=allowance + ) + if allow_evict_retry: rebuilt = evict_retry_filter( - feature="fast", - is_vram_occupancy_miss=(decision.reason == "stream_over"), - stream_gib=decision.stream_gib, - seq=decision.seq, - full_gib=decision.full_gib, + priced=priced, job_filter=job_filter, live_allocated_bytes=self._gpu.get_cuda_live_allocated_bytes(), reserved_bytes=self._gpu.get_cuda_reserved_bytes(), @@ -1223,79 +1353,53 @@ def _video_job_load( rebuild=lambda: self._local_job_filter( model_id=job_filter.profile.model_id, total_only=job_filter.budget.total_only, + pass_shape=job_filter.pass_shape, ), ) if rebuilt is not None: job_filter = rebuilt - decision = job_filter.decide(width, height, frames) + priced = price_video_job( + width, height, frames, job_filter=job_filter, allowance=allowance + ) + admission = admit(priced, allowance) window = ( - f" window={decision.chunk_pixel_frames}f" - if decision.chunk_pixel_frames is not None + f" window={priced.chunk_pixel_frames}f" + if priced.chunk_pixel_frames is not None else "" ) - if isinstance(decision, VideoJobReject): - risk = risk_if_allowed( - risk_for_reject(decision, job_filter), - job_filter, - allow_risk, - unmeasured_bet=unmeasured_bet, - ) - if risk is not None: - logger.info( - "[video] job budget seq=%.0f full=%.1fGiB stream=%.1fGiB -> risk:%s over_gib=%s over_ram_gb=%s%s%s", - decision.seq, - decision.full_gib, - decision.stream_gib, - risk.tier, - risk.over_gib, - risk.over_ram_gb, - window, - vram_snapshot_suffix( - allocated_bytes=self._gpu.get_cuda_live_allocated_bytes(), - reserved_bytes=self._gpu.get_cuda_reserved_bytes(), - free_bytes=job_filter.budget.free_vram_bytes, - ), - ) - return ( - VideoJobLoad( - mode="streaming_models_loading", - seq=decision.seq, - full_gib=decision.full_gib, - stream_gib=decision.stream_gib, - chunk_pixel_frames=decision.chunk_pixel_frames, - ), - risk, - ) + snapshot = vram_snapshot_suffix( + allocated_bytes=self._gpu.get_cuda_live_allocated_bytes(), + reserved_bytes=self._gpu.get_cuda_reserved_bytes(), + free_bytes=job_filter.budget.free_vram_bytes, + ) + if isinstance(admission, Refused): logger.info( - "[video] job budget seq=%.0f full=%.1fGiB stream=%.1fGiB -> reject%s%s", - decision.seq, - decision.full_gib, - decision.stream_gib, + "[video] job budget seq=%.0f full=%.1fGiB stream=%.1fGiB -> reject:%s%s%s", + priced.seq, + priced.full_gib, + priced.stream_gib, + admission.reject.reason, window, - vram_snapshot_suffix( - allocated_bytes=self._gpu.get_cuda_live_allocated_bytes(), - reserved_bytes=self._gpu.get_cuda_reserved_bytes(), - free_bytes=job_filter.budget.free_vram_bytes, - ), + snapshot, ) - message, code = reject_message_and_code(decision, job_filter) + message, code = reject_message_and_code(video_job_reject(admission), job_filter) raise HTTPError(422, message, code=code) + risk = admission.risk logger.info( - "[video] job budget seq=%.0f full=%.1fGiB stream=%.1fGiB -> %s%s%s", - decision.seq, - decision.full_gib, - decision.stream_gib, - decision.mode, - window, - vram_snapshot_suffix( - allocated_bytes=self._gpu.get_cuda_live_allocated_bytes(), - reserved_bytes=self._gpu.get_cuda_reserved_bytes(), - free_bytes=job_filter.budget.free_vram_bytes, + "[video] job budget seq=%.0f full=%.1fGiB stream=%.1fGiB -> %s%s%s%s", + priced.seq, + priced.full_gib, + priced.stream_gib, + admission.load.mode, + ( + f" risk:{risk.tier} over_gib={risk.over_gib} over_ram_gb={risk.over_ram_gb}" + if risk is not None + else "" ), + window, + snapshot, ) - return decision, unmeasured_load_risk( - decision, job_filter, feature="fast", allow_risk=allow_risk - ) + return admission def _load_offload_for_response( self, load_mode: LocalGenerationMode | None @@ -1317,8 +1421,11 @@ def _estimate_wall_time( frames: int, load_mode: LocalGenerationMode, feature: EtaFeature, + *, + chunk_pixel_frames: int | None = None, + stage_2: bool = True, ) -> WallTimeEstimate | None: - """ETA v1 for the decided cell. None whenever the table has no answer.""" + """Wall-time estimate and 3-part breakdown for the decided cell.""" if load_mode == "full_models_loading": eta_load: EtaLoadMode = "full_models_loading" elif load_mode == "streaming_models_loading": @@ -1328,6 +1435,13 @@ def _estimate_wall_time( _load, offload = self._load_offload_for_response(load_mode) if offload is None: return None + system = self.config.system if self.config.system in ("Windows", "Linux", "Darwin") else "Windows" + calibrated = self.state.device_calibration.machine_factor + machine_factor = ( + calibrated + if calibrated is not None + else default_machine_factor(self.config.gpu_device_name) + ) return estimate_fast_wall_time_s( width=width, height=height, @@ -1335,11 +1449,11 @@ def _estimate_wall_time( load_mode=eta_load, offload_mode=offload, feature=feature, - machine_factor=( - 1.0 - if is_measured_hardware_class(self.config.gpu_device_name) - else None - ), + machine_factor=machine_factor, + system=system, + chunk_pixel_frames=chunk_pixel_frames, + stage_2=stage_2, + conv_vae=resolved_use_conv_vae(self.state.app_settings, system=self.config.system), ) def _complete_response( @@ -1371,22 +1485,20 @@ def preflight_queued_fast_job( aspect_ratio: LTXQueuedAspectRatio, duration: int | None, fps: LTXVideoGenFps, + pass_shape: PassShape, ) -> GenerationRisk | None: """Apply the measured LTX 2.5 Fast policy before a Home/Remote queue insert. - Raises hard rejects; returns the bet annotation for downgradable - rejects in reckless mode. + Raises refusals; returns the bet annotation for an admitted risky job. """ model_id = resolve_offering_local_model_id(self.models_dir, offering) if model_id is None: model_id = OFFERING_LOCAL_MODEL_IDS[offering][0] # Queued admission gates on total ("will it ever fit"): a running job # depresses free, and the queue exists to wait for a free slot. - job_filter = self._local_job_filter(model_id=model_id, total_only=True) - if job_filter.budget_mode != "reckless" and not ( - job_filter.profile.is_windows_fast or job_filter.profile.is_mac_fast - ): - return + job_filter = self._local_job_filter( + model_id=model_id, total_only=True, pass_shape=pass_shape + ) # Callers resolve auto (i2v start-frame closest-match) before calling; # auto reaching here would budget the wrong shape silently. assert aspect_ratio != "auto" @@ -1406,7 +1518,9 @@ def preflight_queued_fast_job( ) else: frames = self._compute_num_frames(duration, fps) - return self._video_job_load_mode(width, height, frames, job_filter=job_filter)[1] + return self._video_job_load_mode( + width, height, frames, job_filter=job_filter + )[1] def preflight_queued_a2v_job( self, @@ -1415,11 +1529,12 @@ def preflight_queued_a2v_job( resolution: LTXLocalA2VResolution, aspect_ratio: LTXQueuedAspectRatio, num_frames: int, + pass_shape: PassShape, ) -> GenerationRisk | None: """Apply the A2V budget before a Home/Remote queue insert. Raises hard rejects; returns the bet annotation for downgradable - rejects in reckless mode. Runs on every route: the frame count was + rejects in Brave mode. Runs on every route: the frame count was derived from the static ceiling, so a duration the filter dropped is a budget result here rather than an invalid spec. @@ -1434,7 +1549,9 @@ def preflight_queued_a2v_job( model_id = OFFERING_LOCAL_MODEL_IDS[offering][0] # Queued admission gates on total ("will it ever fit"): a running job # depresses free, and the queue exists to wait for a free slot. - job_filter = self._local_job_filter(model_id=model_id, total_only=True) + job_filter = self._local_job_filter( + model_id=model_id, total_only=True, pass_shape=pass_shape + ) aspect: LtxAspectRatio = "16:9" if aspect_ratio == "auto" else aspect_ratio try: width, height = budget_shape( @@ -1442,7 +1559,9 @@ def preflight_queued_a2v_job( ) except KeyError as exc: raise HTTPError(400, "INVALID_LOCAL_A2V_RESOLUTION") from exc - return self._video_job_load_mode(width, height, num_frames, job_filter=job_filter)[1] + return self._video_job_load_mode( + width, height, num_frames, job_filter=job_filter + )[1] def _queued_auto_budget_frames( self, @@ -1473,7 +1592,10 @@ def _queued_auto_budget_frames( ) try: _min_seconds, max_seconds = supported_duration_range( - item, resolution=resolution, fps=fps + item, + resolution=resolution, + fps=fps, + aspect_ratio=aspect_ratio, ) except KeyError: # Fully budget-dropped resolution/fps: refuse with the compared @@ -1498,8 +1620,7 @@ def _static_auto_range_or_reject( aspect_ratio: LtxAspectRatio, fps: LTXVideoGenFps, allow_evict_retry: bool = False, - allow_risk: bool | None = None, - unmeasured_bet: bool = False, + allowance: RiskAllowance | None = None, ) -> tuple[int, int]: """Static (min, max) auto seconds, refusing with the enriched budget 422. @@ -1509,8 +1630,8 @@ def _static_auto_range_or_reject( max cell on live figures — ``_video_job_load_mode`` raises the enriched 422 naming what the job needs vs what the machine has; if it loads now (figures moved since list time), the static range stands. - ``allow_risk=None`` follows the filter's live mode; executors pass the - stored annotation so a mode flip never re-gates a queued job. + ``allowance=None`` follows the filter's live mode; executors pass the + stored allowance so a mode flip never re-gates a queued job. """ static_item = next( ( @@ -1549,8 +1670,7 @@ def _static_auto_range_or_reject( compute_num_frames(max_seconds, fps), job_filter=job_filter, allow_evict_retry=allow_evict_retry, - allow_risk=allow_risk, - unmeasured_bet=unmeasured_bet, + allowance=allowance, ) return min_seconds, max_seconds @@ -1568,7 +1688,7 @@ def _reject_budget_dropped_a2v_cell( The audio-derived frame count is quoted when that shape misses. When it loads, ``static_cell_frames`` (the shortest static cell) is quoted instead, so the figures match the drop that emptied the row. - ``allow_risk=False`` so reckless does not annotate a row the picker + ``RiskAllowance.none()`` so Brave does not annotate a row the picker no longer offers. A partial drop does not come here. """ model_id = job_filter.profile.model_id @@ -1582,14 +1702,19 @@ def _reject_budget_dropped_a2v_cell( except KeyError as exc: raise HTTPError(400, "INVALID_VIDEO_GENERATION_SPEC") from exc quoted_frames = num_frames - if not isinstance(job_filter.decide(width, height, num_frames), VideoJobReject): + if isinstance( + decide_video_job( + width, height, num_frames, job_filter=job_filter, allowance=RiskAllowance.none() + ), + Admitted, + ): quoted_frames = static_cell_frames self._video_job_load_mode( width, height, quoted_frames, job_filter=job_filter, - allow_risk=False, + allowance=RiskAllowance.none(), ) raise HTTPError( 422, diff --git a/backend/handlers/video_resolution.py b/backend/handlers/video_resolution.py index 531cdbbd8..701c388ec 100644 --- a/backend/handlers/video_resolution.py +++ b/backend/handlers/video_resolution.py @@ -13,11 +13,13 @@ from typing import TYPE_CHECKING from _routes._errors import HTTPError +from frame_math import snap_up_to_multiple if TYPE_CHECKING: from api_types import TargetResolution _SPATIAL_FACTOR = 32 +_CHROMA_FACTOR = 2 # yuv420p subsamples chroma 2x2, so encoded edges must be even. # VAE temporal downscale: valid frame counts are 8k+1. Single source of truth for the # 8-frame rule (extend's snap-up and video generation's frame math reuse this). TIME_FACTOR = 8 @@ -154,7 +156,15 @@ def resolve_home_edit_size( width = source_width if requested_width is None or requested_height is None else requested_width height = source_height if requested_width is None or requested_height is None else requested_height width, height = cap_edit_size(width, height, high_res=high_res) - return min(width, source_width), min(height, source_height) + # libx264 with yuv420p cannot encode an odd edge, and the cap's round() can produce one + # (960x544 at 360p gives 635x360). Snap the picture size to even, source bound included. + even = _CHROMA_FACTOR + even_source_width = snap_up_to_multiple(source_width, even) + even_source_height = snap_up_to_multiple(source_height, even) + return ( + min(snap_up_to_multiple(width, even), even_source_width), + min(snap_up_to_multiple(height, even), even_source_height), + ) def resolve_requested_home_edit_size( diff --git a/backend/http_exception_handlers.py b/backend/http_exception_handlers.py index 6064107ee..e84b0227a 100644 --- a/backend/http_exception_handlers.py +++ b/backend/http_exception_handlers.py @@ -34,9 +34,17 @@ async def _starlette_http_error_handler(_request: Request, exc: Exception) -> JS async def _validation_error_handler(_request: Request, exc: Exception) -> JSONResponse: + if isinstance(exc, RequestValidationError): + errors = exc.errors() + message = f"{len(errors)} validation error{'s' if len(errors) != 1 else ''}:\n" + for err in errors: + message += f" {err}\n" + message = message.rstrip() + else: + message = str(exc) return JSONResponse( status_code=422, - content=build_http_error_response(422, str(exc)).model_dump(), + content=build_http_error_response(422, message).model_dump(), ) diff --git a/backend/keyframe_request.py b/backend/keyframe_request.py index e42faefa8..422f757b9 100644 --- a/backend/keyframe_request.py +++ b/backend/keyframe_request.py @@ -2,11 +2,26 @@ from __future__ import annotations +from collections.abc import Sequence + from api_types import GenerateVideoRequest from frame_math import compute_num_frames from server_utils.media_validation import normalize_optional_path +def validate_keyframe_frames(frame_indices: Sequence[int], *, duration: int, fps: int) -> str | None: + """The frame checks for any multi-keyframe request: unique, and inside the clip.""" + if len(set(frame_indices)) != len(frame_indices): + return "Keyframe frame indices must be unique" + + last_frame = compute_num_frames(duration, fps) - 1 + for frame_idx in frame_indices: + if frame_idx < 0 or frame_idx > last_frame: + return f"Keyframe frame index {frame_idx} is outside 0..{last_frame}" + + return None + + def validate_keyframe_inputs( req: GenerateVideoRequest, *, @@ -34,13 +49,6 @@ def validate_keyframe_inputs( if any(normalize_optional_path(keyframe.imagePath) is None for keyframe in entries): return "Each keyframe requires an image path" - indices = [keyframe.frameIndex for keyframe in entries] - if len(set(indices)) != len(indices): - return "Keyframe frame indices must be unique" - - last_frame = compute_num_frames(req.duration, req.fps) - 1 - for frame_idx in indices: - if frame_idx < 0 or frame_idx > last_frame: - return f"Keyframe frame index {frame_idx} is outside 0..{last_frame}" - - return None + return validate_keyframe_frames( + [keyframe.frameIndex for keyframe in entries], duration=req.duration, fps=req.fps + ) diff --git a/backend/ltx2_server.py b/backend/ltx2_server.py index ebc838ca5..c31f5c79f 100644 --- a/backend/ltx2_server.py +++ b/backend/ltx2_server.py @@ -60,24 +60,22 @@ # ltx-core / ltx-pipelines / safetensors symbols. Delete-first: drop a patch if # upstream now includes the fix (see that file's "Remove once ..." docstring). # Do not reorder this block relative to mps_prebuilt_ext / MPS_SDPA_SKIP_CALIBRATION. -import services.patches.safetensors_loader_fix as _safetensors_loader_fix # pyright: ignore[reportUnusedImport] # Remove once safetensors/PyTorch fix the mmap issue -del _safetensors_loader_fix -import services.patches.disk_streaming_pread as _disk_streaming_pread # Remove once ltx-core DiskTensorReader passes backend=pread on Darwin. No-op off Darwin. -_disk_streaming_pread.install() -import services.patches.linux_disk_streaming_backend as _linux_disk_streaming_backend # Remove once safetensors maps read-only (LTX-Desktop#163). No-op off Linux. -_linux_disk_streaming_backend.install() -import services.patches.safetensors_metadata_fix as _safetensors_metadata_fix # pyright: ignore[reportUnusedImport] # Remove once safetensors supports read-only mmap +import services.patches.safetensors_metadata_fix as _safetensors_metadata_fix # pyright: ignore[reportUnusedImport] # Remove once safetensors supports read-only mmap or ltx-pipelines stops calling safe_open for metadata del _safetensors_metadata_fix -import services.patches.pinned_pool_fix as _pinned_pool_fix # pyright: ignore[reportUnusedImport] # Remove once ltx-core alloc_buffer does not report pinned-host failure as CUDA VRAM OOM (LTX-Desktop#141) +import services.patches.pinned_pool_fix as _pinned_pool_fix # pyright: ignore[reportUnusedImport] # Remove once ltx-core host_bytes works on Windows and a failed pin cannot poison CUDA (LTX-Desktop#141) del _pinned_pool_fix import services.patches.diffusion_stage_cache as _diffusion_stage_cache # pyright: ignore[reportUnusedImport] # EXPERIMENTAL: remove once DiffusionStage caches/reuses identical builds upstream del _diffusion_stage_cache +import services.patches.mps_transfer_sync as _mps_transfer_sync # pyright: ignore[reportUnusedImport] # Remove once ltx-core waits for queued MPS compute before a transfer and a 1080p stage 2 passes on a 48 GB Mac without it +del _mps_transfer_sync import services.patches.diffvae_decode_vram as _diffvae_decode_vram # pyright: ignore[reportUnusedImport] # Remove once upstream decode tiling is confirmed sufficient (E1) del _diffvae_decode_vram import services.patches.natten_libnatten_gate as _natten_libnatten_gate # pyright: ignore[reportUnusedImport] # Remove once ltx-core natten_available checks HAS_LIBNATTEN del _natten_libnatten_gate import services.patches.diffusion_interrupt as _diffusion_interrupt # pyright: ignore[reportUnusedImport] # Remove once ltx-pipelines denoiser/loop accepts an interrupt callback del _diffusion_interrupt +import services.patches.nag_cross_attention as _nag_cross_attention # pyright: ignore[reportUnusedImport] # EXPERIMENTAL: remove once ltx-core supports a negative text context in the distilled path +del _nag_cross_attention from state.app_settings import AppSettings @@ -109,11 +107,6 @@ # Now that logging is configured, report which mps-sdpa attention backend is live # (the setup call at import time logs too early to be captured). No-op off Darwin. _mps_prebuilt_ext.log_mps_backend_status() -# install() ran before basicConfig, so its status log would have been dropped. -_disk_streaming_pread.log_status() -del _disk_streaming_pread -_linux_disk_streaming_backend.log_status() -del _linux_disk_streaming_backend # ============================================================ # SageAttention Integration @@ -184,6 +177,14 @@ def patched_sdpa( import services.patches.mps_sdpa_torch as _mps_sdpa_torch _mps_sdpa_torch.install() +# Darwin: MPS conv3d runs at ~1/5 of conv2d throughput, which makes the conv VAE +# decode ~4x slower than it needs to be. The hook is installed off; the experimental +# Settings toggle turns it on per generation (GenerationHandler.start_generation). +# Remove once torch MPS conv3d reaches conv2d throughput. +import services.patches.mps_conv3d_as_conv2d as _mps_conv3d_as_conv2d +_mps_conv3d_as_conv2d.install(enabled=False) +del _mps_conv3d_as_conv2d + # ============================================================ # Constants & Paths # ============================================================ @@ -216,6 +217,11 @@ def _resolve_app_data_dir() -> Path: APP_DATA_DIR = _resolve_app_data_dir() +# Optional. Electron sets it when the user picked an assets folder. The store does not +# create it: the folder must exist and hold the .ltx-assets marker. +_assets_dir_env = os.environ.get("LTX_ASSETS_DIR") +ASSETS_DIR = Path(_assets_dir_env) if _assets_dir_env else None + DEFAULT_MODELS_DIR = APP_DATA_DIR / "models" DEFAULT_MODELS_DIR.mkdir(parents=True, exist_ok=True) @@ -322,6 +328,7 @@ def _effective_local_generations_mode(mode: LocalGenerationMode) -> LocalGenerat runtime_config = RuntimeConfig( device=DEVICE, app_data_dir=APP_DATA_DIR, + assets_dir=ASSETS_DIR, default_models_dir=DEFAULT_MODELS_DIR, outputs_dir=OUTPUTS_DIR, settings_file=SETTINGS_FILE, @@ -330,6 +337,7 @@ def _effective_local_generations_mode(mode: LocalGenerationMode) -> LocalGenerat camera_motion_prompts=CAMERA_MOTION_PROMPTS, default_negative_prompt=DEFAULT_NEGATIVE_PROMPT, dev_mode=os.environ.get("LTX_DEV_MODE") == "1", + parallel_queue_lanes=os.environ.get("LTX_PARALLEL_QUEUE_LANES", "1") != "0", hf_oauth_client_id=HF_OAUTH_CLIENT_ID, backend_port=int(os.environ.get("LTX_PORT", "") or PORT), lora_catalog_source=str(Path(__file__).parent / "runtime_config" / "lora_catalog.json"), diff --git a/backend/performance_runner/README.md b/backend/performance_runner/README.md index 48359469e..32b4ba268 100644 --- a/backend/performance_runner/README.md +++ b/backend/performance_runner/README.md @@ -60,7 +60,7 @@ dashboard in a browser. Ctrl+C stops both. > The runner measures **local** generation. The backend decides local-vs-API at > startup from the hardware available _at that moment_ — on Apple Silicon, **total** -> unified RAM (32 GiB minimum), not free RAM. If it comes up in API-only mode, +> unified RAM (24 GiB minimum; see the README's System requirements), not free RAM. If it comes up in API-only mode, > `perf:dev` stops because this machine is below the local-gen floor. > **`perf:dev` measures the dev backend** — the same interpreter `pnpm dev` uses, with @@ -273,7 +273,7 @@ uv run python soak_test.py --n 3 --label bump_e4 --set-cache on # E4 stage-cac | those plus `last_frames_not_black` | E2 MPS tail-frame zeroing | each of last ~8 frames has non-zero luma (fails closed without ffmpeg) | | `iclora_stage2_on` | E3 two-stage IC-LoRA | completes with `skip_stage_2=false` (stage 2 is not forced onto streaming) | | `soak_test.py --n 3 --set-cache on` | E4 stage-cache soak | flat reserved-VRAM floor | -| `mkf_interpolation` | guiding-latent swap | output exists | +| `mkf_interpolation` | guide-all image binding | output exists | | `cancel_mid_denoise` | interrupt hook | generate returns `cancelled` after `phase=inference` | | `iclora_day_to_night` | shipped skip_stage_2 tiling | no OOM / crawl | diff --git a/backend/performance_runner/bench_mps_conv3d.py b/backend/performance_runner/bench_mps_conv3d.py new file mode 100644 index 000000000..339416942 --- /dev/null +++ b/backend/performance_runner/bench_mps_conv3d.py @@ -0,0 +1,216 @@ +#!/usr/bin/env python3 +"""Stock MPS Conv3d vs the per-tap conv2d patch (services/patches/mps_conv3d_as_conv2d). + +Two checks, both on Apple Silicon only: + +- Default: one 3x3x3 Conv3d per conv VAE decoder stage, bf16, in the decoder's + ``channels_last_3d`` layout and in contiguous layout. Reports time, TFLOPS, + speedup, and the largest difference from stock. No model weights needed. +- ``--vae``: decodes one 1024x576, 121-frame latent with the real conv VAE + (``ltx-2.5-video-vae-conv``), stock then patched, the way the pipeline builds + it. Reports both decode times and the PSNR of patched vs stock frames. + +Measurement and reporting are separate: the ``bench_*`` functions return results +and ``report`` prints them once at the end. + +Use it to check the patch on your Mac and after every torch bump. Remove the +patch when stock is as fast in the ``channels_last_3d`` rows. + +Credit: written by Sabbagh Fares (@Sabmit) in https://github.com/Lightricks/LTX-Desktop/pull/189 + +Usage (from backend/, no backend running): + uv run python performance_runner/bench_mps_conv3d.py + uv run python performance_runner/bench_mps_conv3d.py --vae + uv run python performance_runner/bench_mps_conv3d.py --vae --checkpoint /path/to/ltx-2.5-video-vae-conv-bf16.safetensors +""" + +from __future__ import annotations + +import argparse +import platform +import sys +import time +from collections.abc import Callable +from dataclasses import dataclass +from pathlib import Path + +import torch +from torch import nn + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +import services.patches.mps_conv3d_as_conv2d as patch # noqa: E402 + +SEED = 42 # any fixed value; makes runs repeatable across machines and torch versions + +# What the ``--vae`` check decodes: the app's default 540p, 5 s clip. +HEIGHT, WIDTH, NUM_FRAMES = 576, 1024, 121 +# LTX-2 video VAE: 32x spatial and 8x temporal compression, 128 latent channels. +SPATIAL_SCALE, TEMPORAL_SCALE, LATENT_CHANNELS = 32, 8, 128 +LATENT_SHAPE = ( + 1, + LATENT_CHANNELS, + (NUM_FRAMES - 1) // TEMPORAL_SCALE + 1, + HEIGHT // SPATIAL_SCALE, + WIDTH // SPATIAL_SCALE, +) + +# One Conv3d per decoder stage: (channels, frames, height, width) for the clip above. +SHAPES = [(1024, 16, 18, 32), (512, 32, 36, 64), (256, 64, 72, 128), (128, 32, 144, 256)] +KERNEL_TAPS = 3 * 3 * 3 # a 3x3x3 kernel: 27 multiply-adds per output value per input channel +FLOPS_PER_MAC = 2 # one multiply and one add + +DEFAULT_CHECKPOINT = ( + Path.home() / "Library/Application Support/LTXDesktop/models/ltx-2.5/ltx-2.5-video-vae-conv-bf16.safetensors" +) +WARMUP, ITERS = 2, 5 + + +@dataclass(frozen=True) +class OpResult: + layout: str + channels: int + frames: int + height: int + width: int + stock_s: float + patched_s: float + flops: int + max_abs_diff: float + + +@dataclass(frozen=True) +class VaeResult: + stock_s: float + patched_s: float + psnr_db: float + max_abs_diff: float + finite: bool + + +def _time(fn: Callable[[], torch.Tensor]) -> float: + for _ in range(WARMUP): + fn() + torch.mps.synchronize() + start = time.perf_counter() + for _ in range(ITERS): + fn() + torch.mps.synchronize() + return (time.perf_counter() - start) / ITERS + + +@torch.inference_mode() +def bench_ops() -> list[OpResult]: + torch.manual_seed(SEED) + results: list[OpResult] = [] + for layout in (torch.channels_last_3d, torch.contiguous_format): + for channels, frames, height, width in SHAPES: + conv = nn.Conv3d(channels, channels, 3, padding=(0, 1, 1)).to("mps", torch.bfloat16) + conv = conv.to(memory_format=layout) + # No temporal padding: the 3-tap kernel turns frames + 2 input frames into frames output frames. + x = torch.randn(1, channels, frames + 2, height, width, device="mps", dtype=torch.bfloat16) + x = x.contiguous(memory_format=layout) + stock_s = _time(lambda: patch._original_forward(conv, x)) + patched_s = _time(lambda: patch._conv3d_as_conv2d(conv, x)) + diff = (patch._conv3d_as_conv2d(conv, x).float() - patch._original_forward(conv, x).float()).abs().max() + results.append( + OpResult( + layout="channels_last_3d" if layout is torch.channels_last_3d else "contiguous", + channels=channels, + frames=frames, + height=height, + width=width, + stock_s=stock_s, + patched_s=patched_s, + # in_channels == out_channels in every decoder stage, hence channels squared. + flops=FLOPS_PER_MAC * channels * channels * KERNEL_TAPS * frames * height * width, + max_abs_diff=diff.item(), + ) + ) + del conv, x + torch.mps.empty_cache() + return results + + +@torch.inference_mode() +def _decode(checkpoint: Path, latent: torch.Tensor) -> tuple[torch.Tensor, float]: + from ltx_pipelines.utils.blocks import VideoDecoder + from ltx_pipelines.utils.helpers import tiling_config_for_vae + + device = torch.device("mps") + tiling = tiling_config_for_vae(str(checkpoint), height=HEIGHT, width=WIDTH, num_frames=NUM_FRAMES, device=device) + decoder = VideoDecoder(str(checkpoint), torch.bfloat16, device) + generator = torch.Generator(device="mps").manual_seed(SEED) + torch.mps.synchronize() + start = time.perf_counter() + frames = torch.cat([chunk.float().cpu() for chunk in decoder(latent, tiling, generator)], dim=0) + torch.mps.synchronize() + elapsed = time.perf_counter() - start + torch.mps.empty_cache() + return frames, elapsed + + +def bench_vae(checkpoint: Path) -> VaeResult: + torch.manual_seed(SEED) + latent = torch.randn(LATENT_SHAPE).to("mps", torch.bfloat16) + original = nn.Conv3d.forward + was_enabled = patch._enabled + try: + nn.Conv3d.forward = original # type: ignore[method-assign] + stock, stock_s = _decode(checkpoint, latent) + nn.Conv3d.forward = patch._forward # type: ignore[method-assign] + patch._enabled = True + patched, patched_s = _decode(checkpoint, latent) + finally: + nn.Conv3d.forward = original # type: ignore[method-assign] + patch._enabled = was_enabled + mse = (patched - stock).pow(2).mean().item() + span = (stock.max() - stock.min()).item() + psnr_db = float("inf") if mse == 0 else 10 * torch.log10(torch.tensor(span**2 / mse)).item() + return VaeResult( + stock_s=stock_s, + patched_s=patched_s, + psnr_db=psnr_db, + max_abs_diff=(patched - stock).abs().max().item(), + finite=bool(torch.isfinite(patched).all()), + ) + + +def report(op_results: list[OpResult], vae: VaeResult | None) -> None: + print(f"torch {torch.__version__}, macOS {platform.mac_ver()[0]}, {platform.machine()}, bf16\n") + print( + f"{'layout':17} {'C':>5} {'T':>3} {'H':>4} {'W':>4} | {'stock ms':>9} {'TFLOPS':>6} | " + f"{'patch ms':>9} {'TFLOPS':>6} | speedup max|d|" + ) + for row in op_results: + print( + f"{row.layout:17} {row.channels:>5} {row.frames:>3} {row.height:>4} {row.width:>4} | " + f"{row.stock_s * 1e3:>9.1f} {row.flops / row.stock_s / 1e12:>6.2f} | " + f"{row.patched_s * 1e3:>9.1f} {row.flops / row.patched_s / 1e12:>6.2f} | " + f"{row.stock_s / row.patched_s:>6.2f}x {row.max_abs_diff:.4f}" + ) + if vae is None: + return + print() + print(f"stock decode {vae.stock_s:6.1f}s") + print(f"patched decode {vae.patched_s:6.1f}s ({vae.stock_s / vae.patched_s:.2f}x)") + print(f"patched vs stock: PSNR {vae.psnr_db:.1f} dB, max|d| {vae.max_abs_diff:.4f}") + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--vae", action="store_true", help="also decode with the real conv VAE (needs the checkpoint)") + parser.add_argument("--checkpoint", type=Path, default=DEFAULT_CHECKPOINT) + args = parser.parse_args() + if not torch.backends.mps.is_available(): + sys.exit("MPS is not available. This benchmark needs an Apple Silicon Mac.") + if args.vae and not args.checkpoint.exists(): + sys.exit(f"Conv VAE checkpoint not found: {args.checkpoint}\nDownload it in the app or pass --checkpoint.") + op_results = bench_ops() + vae = bench_vae(args.checkpoint) if args.vae else None + report(op_results, vae) + if vae is not None and not vae.finite: + sys.exit("FAIL: patched output has NaN or Inf values") + + +if __name__ == "__main__": + main() diff --git a/backend/performance_runner/perf_config.py b/backend/performance_runner/perf_config.py index 20aa14de4..a0a67d13b 100644 --- a/backend/performance_runner/perf_config.py +++ b/backend/performance_runner/perf_config.py @@ -282,9 +282,10 @@ def ltx_versions() -> list[dict[str, Any]]: def activate_ltx_model(want: str) -> str: - """Activate by model_id or Settings label ('2.5', '2.3'). Must already be installed.""" + """Activate by model_id, Settings label ('LTX 2.5') or bare version ('2.5'). Must already be installed.""" versions = ltx_versions() - match = next((v for v in versions if v.get("model_id") == want or v.get("label") == want), None) + accepted = {want, f"LTX {want}"} + match = next((v for v in versions if v.get("model_id") in accepted or v.get("label") in accepted), None) if match is None: known = ", ".join(str(v.get("label") or v.get("model_id")) for v in versions) or "none" raise RuntimeError(f"unknown LTX version {want!r} (known: {known})") diff --git a/backend/performance_runner/queued.py b/backend/performance_runner/queued.py index 8847b4aef..b5bb5ceeb 100644 --- a/backend/performance_runner/queued.py +++ b/backend/performance_runner/queued.py @@ -85,6 +85,14 @@ def _output(generation: dict[str, Any]) -> str | None: return outputs[0]["path"] if outputs else None +def _active_entry(snapshot: Any, generation_id: str) -> dict[str, Any] | None: + """The running entry of this job. ``active`` lists one entry per running job (several lanes).""" + for entry in (snapshot or {}).get("active") or []: + if (entry.get("generation") or {}).get("id") == generation_id: + return entry + return None + + def trigger(jobs: list[QueuedJob]) -> list[str | None]: """Submit every job first (so several really queue up), then wait for each in order.""" ids = [_create(job) for job in jobs] @@ -102,8 +110,8 @@ def trigger_cancellable(job: QueuedJob, *, after_s: float, wait_timeout_s: float try: deadline = time.time() + wait_timeout_s while time.time() < deadline: - active = (perf_config._get(QUEUE_PATH) or {}).get("active") or {} - if (active.get("generation") or {}).get("id") == generation_id: + active = _active_entry(perf_config._get(QUEUE_PATH), generation_id) + if active is not None: saw_inference = (active.get("progress") or {}).get("phase") == "inference" if saw_inference: break diff --git a/backend/performance_runner/regression_scenarios.py b/backend/performance_runner/regression_scenarios.py index c4b775314..9698f0d99 100644 --- a/backend/performance_runner/regression_scenarios.py +++ b/backend/performance_runner/regression_scenarios.py @@ -32,6 +32,7 @@ SCENARIOS, VIDEO_ASSET, Scenario, + last_frames_not_black, output_exists, output_nonempty, ) @@ -139,6 +140,36 @@ def retake_checks(mode: str, source: str = VIDEO_ASSET) -> list: "imagePath": IMAGE_ASSET, "audioPath": AUDIO_ASSET, "resolution": "270p", "duration": 5}, a2v_checks(with_image=True), tags=("ia2v", "speech")) +# Full-size A2V checks for the single-window run (`DistilledA2VPipeline.__call__` runs as one +# `stream_chunks` window). They sit in the `full` and `bump` tiers because the smoke canvas hides what +# they look for: the decode now lands on the GPU as one tensor, a clip past 128 frames must keep a +# live tail, and a still on the last frame must survive the frame snap. 6 s is 145 frames. +A2V_BUMP = {"prompt": "a cartoon character telling a joke, talking to camera", "seed": 42, + "audio": True, "audioPath": AUDIO_ASSET, "duration": 6} +A2V_BUMP_REF = "a2v_540p_6s" + + +def a2v_bump_checks(*, first: str | None = None, last: str | None = None) -> list: + checks = [chk.media_ok(audio=True, duration=(5.5, 6.6)), chk.not_dead(), last_frames_not_black, + chk.audio_matches(AUDIO_ASSET)] + checks += [chk.frame_matches(first, at="first")] if first else [] + return checks + ([chk.frame_matches(last, at="last")] if last else []) + + +add_regression("bump_a2v_540p_6s", "A2V 540p / 6s (single window, reference for the same-seed repeat)", + {**A2V_BUMP, "resolution": "540p"}, + [*a2v_bump_checks(), chk.remember(A2V_BUMP_REF)], tiers=("full",), tags=("a2v", "bump", "speech"), order=FIRST) +add_regression("bump_a2v_1080p_6s", "A2V 1080p / 6s (145 frames: decode peak and live tail)", + {**A2V_BUMP, "resolution": "1080p"}, + a2v_bump_checks(), tiers=("full",), tags=("a2v", "bump", "speech")) +add_regression("bump_ia2v_first_last_540p", "Image+A2V 540p / 6s (first and last still honoured on the snapped grid)", + {**A2V_BUMP, "resolution": "540p", "imagePath": IMAGE_ASSET, "lastImagePath": KEYFRAME_B}, + a2v_bump_checks(first=IMAGE_ASSET, last=KEYFRAME_B), tiers=("full",), tags=("ia2v", "bump", "speech")) +add_regression("bump_a2v_540p_6s_repeat", "A2V 540p / 6s again (same seed reproduces with the ancestral sampler)", + {**A2V_BUMP, "resolution": "540p"}, + [chk.media_ok(audio=True, duration=(5.5, 6.6)), chk.reproduces(A2V_BUMP_REF)], + tiers=("full",), tags=("a2v", "bump", "speech"), order=LAST) + # -- image ------------------------------------------------------------------------------ add_regression("smoke_t2i", "Text-to-Image", {"prompt": "a cozy felt duck in a sunlit room", "width": 1024, "height": 576, "numSteps": 4, "numImages": 1}, diff --git a/backend/performance_runner/scenarios.py b/backend/performance_runner/scenarios.py index c68af32be..1f2fcc02d 100644 --- a/backend/performance_runner/scenarios.py +++ b/backend/performance_runner/scenarios.py @@ -345,9 +345,10 @@ def _add(s: Scenario) -> None: SCENARIOS["t2v_1080p_5s"].tags.append("e1") SCENARIOS["t2v_1080p_5s"].checks = list(BUMP_VIDEO_CHECKS) -# 5s @ 24fps = 120 frames. Same still at 0 / mid / last — exercises the Distilled -# guiding-latent swap (distilled_keyframe_guiding), not visual variety. -_add(Scenario("mkf_interpolation", "Multi-keyframe interpolation (guiding swap)", +# 5s @ 24fps snaps to 121 frames (indices 0..120); the last still sits one frame before the end +# on purpose, so runs stay comparable with earlier baselines. Same still at 0 / mid / last — exercises the Distilled +# guide-all image binding (to_ltx_images guide_all=True), not visual variety. +_add(Scenario("mkf_interpolation", "Multi-keyframe interpolation (guide-all binding)", {"prompt": "a fox and a panda walking through a sunlit forest", "seed": 42, "resolution": "540p", "duration": 5, "fps": 24, "keyframes": [ diff --git a/backend/pyproject.toml b/backend/pyproject.toml index 6fc630f54..975659949 100644 --- a/backend/pyproject.toml +++ b/backend/pyproject.toml @@ -5,6 +5,7 @@ description = "LTX-2 Video Generation Backend" requires-python = ">=3.12" dependencies = [ "pillow>=12.3.0", + "pyyaml>=6.0", "av>=16.1.0", # macOS caps at <2.12: ltx-core imports torchaudio (audio VAE), torchaudio tops out at # 2.11.0 with empty torch metadata, so an uncapped torch resolves to 2.12.1 and the @@ -25,13 +26,13 @@ dependencies = [ "pydantic-ai-slim[google,openai]>=1.0,<3", "httpx2>=2.13,<3", "httpx>=0.27", - # LTX-2 inference dependencies (v1.4.1). + # LTX-2 inference dependencies (v1.6.0). # LLM: changing ltx-core / ltx-pipelines version or git tag requires re-checking # every monkey-patch in backend/services/patches/ (imported from ltx2_server.py). # Those rebind private upstream symbols; drop a patch only if upstream now includes # the fix (see each module's "Remove once ..." docstring) and its tests still pass. - "ltx-core==1.4.1", - "ltx-pipelines==1.4.1", + "ltx-core==1.6.0", + "ltx-pipelines==1.6.0", "diffusers>=0.39.0", # ltx-core 1.4 imports colour-science. Without matplotlib, colour.plotting puts MagicMock # objects in sys.modules["matplotlib"], and diffusers' importlib.util.find_spec("matplotlib") @@ -91,18 +92,18 @@ torchvision = [ # Linux keeps resolving sageattention from PyPI (no reported Blackwell crashes there yet). sageattention = { url = "https://github.com/woct0rdho/SageAttention/releases/download/v2.2.0-windows.post5/sageattention-2.2.0+cu128torch2.10.0andhigher.post5-cp310-abi3-win_amd64.whl", marker = "sys_platform == 'win32'" } natten = { url = "https://storage.googleapis.com/ltx-desktop-artifacts/wheels/natten-0.21.6+torch2100cu128-cp313-cp313-win_amd64.whl", marker = "sys_platform == 'win32'" } -# Official LTX-2 v1.4.1 packages (not on PyPI). We do not take ltx-core's own +# Official LTX-2 v1.6.0 packages (not on PyPI). We do not take ltx-core's own # tool.uv.sources (cu132) — this app's pytorch-cu128 pin above owns torch. # Do not take ltx-core's natten extra (0.21.7+torch2130cu132 plus torch==2.13.0). # LLM: bumping this tag/version → re-verify backend/services/patches/ (see ltx2_server.py). -ltx-core = { git = "https://github.com/Lightricks/LTX-2.git", subdirectory = "packages/ltx-core", tag = "v1.4.1" } -ltx-pipelines = { git = "https://github.com/Lightricks/LTX-2.git", subdirectory = "packages/ltx-pipelines", tag = "v1.4.1" } +ltx-core = { git = "https://github.com/Lightricks/LTX-2.git", subdirectory = "packages/ltx-core", tag = "v1.6.0" } +ltx-pipelines = { git = "https://github.com/Lightricks/LTX-2.git", subdirectory = "packages/ltx-pipelines", tag = "v1.6.0" } -# v1.4.1's library pyproject pins torch to a cu132 index. Static metadata lets uv +# v1.6.0's library pyproject pins torch to a cu132 index. Static metadata lets uv # resolve without reading that table, so this app's cu128 pin above stays in charge. [[tool.uv.dependency-metadata]] name = "ltx-core" -version = "1.4.1" +version = "1.6.0" requires-dist = [ "torch~=2.7", "torchaudio", @@ -110,7 +111,6 @@ requires-dist = [ "einops", "numpy", "colour-science", - "av", "transformers>=5.8.0,<5.15", "safetensors", "accelerate", @@ -120,7 +120,7 @@ requires-dist = [ [[tool.uv.dependency-metadata]] name = "ltx-pipelines" -version = "1.4.1" +version = "1.6.0" requires-dist = ["ltx-core", "av", "tqdm", "pillow", "openimageio", "cloudpickle>=3.1"] [project.optional-dependencies] diff --git a/backend/remote/app.py b/backend/remote/app.py index 6e5de97ee..c6b10e74f 100644 --- a/backend/remote/app.py +++ b/backend/remote/app.py @@ -21,7 +21,9 @@ from _routes.assets import phone_assets_router from _routes.assistant import phone_assistant_router from _routes.feature_flags import router as feature_flags_router +from _routes.ui_preferences import router as ui_preferences_router from _routes.generation_seed import phone_generation_seed_router +from _routes.image_gen import status_router as image_status_router from _routes.stats import phone_stats_router from _routes.generation import specs_router as generate_specs_router from api_types import HTTPErrorResponse @@ -38,6 +40,7 @@ from state import get_state_service _BYTES_PATH = re.compile(r"^/api/assets/([^/]+)/(?:thumbnail/)?bytes$") +_COVER_PATH = re.compile(r"^/api/custom-loras/([^/]+)/cover$") _EXCHANGE_PATH = "/api/pairing/exchange" FALLBACK_HTML = """ @@ -175,14 +178,16 @@ async def _remote_auth_middleware( # pyright: ignore[reportUnusedFunction] if _is_public_path(request.url.path): return await call_next(request) bytes_match = _BYTES_PATH.match(request.url.path) - if bytes_match is not None: + cover_match = _COVER_PATH.match(request.url.path) + media_match = bytes_match or cover_match + if media_match is not None: if request.query_params.get("t") is not None: return _unauthorized() try: device = pairing.authenticate_media( request.url.path, urlsplit(str(request.url)).query, - asset_id=bytes_match.group(1), + asset_id=media_match.group(1), ) except PairingError as exc: if exc.status_code == 503: @@ -246,6 +251,8 @@ def route_pairing_exchange( # pyright: ignore[reportUnusedFunction] app.include_router(loras_router) app.include_router(hf_auth_router) app.include_router(feature_flags_router) + app.include_router(ui_preferences_router) + app.include_router(image_status_router) app.include_router(prompt_enhancement_router) app.include_router(phone_assistant_router) diff --git a/backend/remote/dto.py b/backend/remote/dto.py index 6521e90e9..0fa139f8f 100644 --- a/backend/remote/dto.py +++ b/backend/remote/dto.py @@ -14,13 +14,16 @@ from pydantic import BaseModel, ConfigDict, Field, JsonValue, ValidationError, field_serializer from api_types import ( + ApiActivityStatus, Asset, AssetCore, ExtendMode, IcLoraAudioMode, IcLoraControlType, + ImageProvider, Generation, GenerationCore, + NagParams, QueueEntry, QueueProgress, QueueSnapshot, @@ -28,23 +31,40 @@ ) from api_motion_path import MotionPath from remote.media_urls import MediaUrlSigner +from runtime_config.ic_lora_tiling import ( + MAX_TILE_OVERLAP, + MIN_CARRY_FRAMES, + MIN_TILE_OVERLAP, + MIN_WINDOW_FRAMES, + IcLoraTileSize, +) +from runtime_config.reject_reasons import PassShape logger = logging.getLogger(__name__) +_NAG_NUMBER_FIELDS = frozenset(NagParams.model_fields) - {"negativePrompt"} + _SAFE_PARAM_STRINGS = frozenset( { "prompt", + "negativePrompt", "model", "aspectRatio", "promptProvenance", + "provider", "mode", "audioMode", + "passShape", "controlType", + "tilingSize", } ) +_REMOTE_IMAGE_PROVIDERS = frozenset(get_args(ImageProvider)) _REMOTE_AUDIO_MODES = frozenset(get_args(IcLoraAudioMode)) +_REMOTE_PASS_SHAPES = frozenset(get_args(PassShape)) _REMOTE_CONTROL_TYPES = frozenset(get_args(IcLoraControlType)) -_SAFE_PARAM_NUMBERS = frozenset({"duration", "fps", "startTime"}) +_REMOTE_TILE_SIZES = frozenset(get_args(IcLoraTileSize)) +_SAFE_PARAM_NUMBERS = frozenset({"duration", "fps", "startTime", "tilingOverlap", *_NAG_NUMBER_FIELDS}) _REMOTE_MODES = frozenset((*get_args(RetakeMode), *get_args(ExtendMode))) @@ -73,6 +93,16 @@ class RemoteInputAssetRef(BaseModel): assetId: str = Field(min_length=1) +class RemoteKeyframe(BaseModel): + """One still of a Keyframes run. Reuse puts it back on the timeline.""" + + model_config = ConfigDict(strict=True, extra="forbid") + + assetId: str = Field(min_length=1) + frameIndex: int = Field(ge=0) + strength: float = Field(ge=0.0, le=1.0) + + class RemoteTargetResolution(BaseModel): """Home Retake/Extend target size. Tier ids stay strings.""" @@ -82,12 +112,16 @@ class RemoteTargetResolution(BaseModel): height: int = Field(gt=0) -class RemoteVideoParams(BaseModel): - """T2V/I2V/A2V form and result-meta fields only.""" +class RemoteGenerationParams(BaseModel): + """Form and result-meta fields only, for video and text-to-image generations.""" model_config = ConfigDict(strict=True, extra="forbid") prompt: str | None = None + negativePrompt: str | None = None + nagScale: int | float | None = None + nagAlpha: int | float | None = None + nagTau: int | float | None = None model: str | None = None resolution: str | RemoteTargetResolution | None = None duration: int | float | None = None @@ -95,12 +129,25 @@ class RemoteVideoParams(BaseModel): aspectRatio: str | None = None promptProvenance: str | None = None scale: int | float | None = None + # Which saved custom LoRA the run used, so Reuse can select it again. An id, never a path. + customLoraId: str | None = None + # The LoRA name at run time, so the queue and results show it on a phone. + customLoraName: str | None = None numFrames: int | None = None mode: RetakeMode | ExtendMode | None = None startTime: int | float | None = None seed: int | None = None audioMode: IcLoraAudioMode | None = None + passShape: PassShape | None = None controlType: IcLoraControlType | None = None + # Advanced tiling controls of a recipe, so Reuse restores the same run on the phone. + tilingOverlap: float | None = None + carryFrames: int | None = None + tilingSize: IcLoraTileSize | None = None + maxWindowFrames: int | None = None + width: int | None = None + height: int | None = None + provider: ImageProvider | None = None class RemoteVideoInputs(BaseModel): @@ -112,6 +159,7 @@ class RemoteVideoInputs(BaseModel): video: RemoteInputAssetRef | None = None image: RemoteInputAssetRef | None = None images: list[RemoteInputAssetRef] | None = None + keyframes: list[RemoteKeyframe] | None = None # Motion Track: coordinates and pacing only, so Reuse can draw the paths again. paths: list[MotionPath] | None = None @@ -119,7 +167,7 @@ class RemoteVideoInputs(BaseModel): class RemoteGenerationSpec(BaseModel): model_config = ConfigDict(strict=True, extra="forbid") - params: RemoteVideoParams = Field(default_factory=RemoteVideoParams) + params: RemoteGenerationParams = Field(default_factory=RemoteGenerationParams) inputs: RemoteVideoInputs | None = None @@ -140,12 +188,14 @@ class RemoteQueueEntry(BaseModel): generation: RemoteGeneration input_assets: list[RemoteAsset] progress: QueueProgress | None = None + cancellable: bool = True + api_status: ApiActivityStatus | None = None class RemoteQueueSnapshot(BaseModel): model_config = ConfigDict(strict=True, extra="forbid") - active: RemoteQueueEntry | None + active: list[RemoteQueueEntry] = Field(default_factory=list[RemoteQueueEntry]) queued: list[RemoteQueueEntry] done: list[RemoteQueueEntry] = Field(default_factory=list[RemoteQueueEntry]) failed: list[RemoteQueueEntry] = Field(default_factory=list[RemoteQueueEntry]) @@ -200,6 +250,8 @@ def to_remote_generation( started_at=generation.started_at, finished_at=generation.finished_at, risk=generation.risk, + lane=generation.lane, + provider_job_id=generation.provider_job_id, outputs=[ to_remote_asset(asset, signer=signer, device_id=device_id) for asset in generation.outputs @@ -219,6 +271,8 @@ def to_remote_queue_entry( for asset in entry.input_assets ], progress=entry.progress, + cancellable=entry.cancellable, + api_status=entry.api_status, ) @@ -229,7 +283,6 @@ def to_remote_queue_snapshot( device_id: str, feature_is_allowed: Callable[[str], bool], ) -> RemoteQueueSnapshot: - active = snapshot.active done = [ to_remote_queue_entry(entry, signer=signer, device_id=device_id) for entry in snapshot.done @@ -237,11 +290,11 @@ def to_remote_queue_snapshot( ] visible_done_ids = {entry.generation.id for entry in done} return RemoteQueueSnapshot( - active=( - to_remote_queue_entry(active, signer=signer, device_id=device_id) - if active is not None and feature_is_allowed(active.generation.feature) - else None - ), + active=[ + to_remote_queue_entry(entry, signer=signer, device_id=device_id) + for entry in snapshot.active + if feature_is_allowed(entry.generation.feature) + ], queued=[ to_remote_queue_entry(entry, signer=signer, device_id=device_id) for entry in snapshot.queued @@ -268,10 +321,10 @@ def project_remote_spec(spec: dict[str, JsonValue]) -> RemoteGenerationSpec: ) -def _project_params(value: object) -> RemoteVideoParams: +def _project_params(value: object) -> RemoteGenerationParams: mapping = _string_mapping(value) if mapping is None: - return RemoteVideoParams() + return RemoteGenerationParams() strings = { key: extracted for key in _SAFE_PARAM_STRINGS @@ -282,8 +335,12 @@ def _project_params(value: object) -> RemoteVideoParams: for key in _SAFE_PARAM_NUMBERS if (extracted := _optional_number(mapping.get(key))) is not None } - return RemoteVideoParams( + return RemoteGenerationParams( prompt=strings.get("prompt"), + negativePrompt=strings.get("negativePrompt") or None, + nagScale=_non_negative_number(numbers.get("nagScale")), + nagAlpha=_non_negative_number(numbers.get("nagAlpha")), + nagTau=_non_negative_number(numbers.get("nagTau")), model=strings.get("model"), resolution=_project_resolution(mapping.get("resolution")), duration=numbers.get("duration"), @@ -291,12 +348,22 @@ def _project_params(value: object) -> RemoteVideoParams: aspectRatio=strings.get("aspectRatio"), promptProvenance=strings.get("promptProvenance"), scale=_project_lora_scale(mapping.get("loras")), + customLoraId=_project_custom_lora_id(mapping.get("loras")), + customLoraName=_project_custom_lora_name(mapping.get("loras")), numFrames=_optional_int(mapping.get("numFrames")), mode=_project_mode(strings.get("mode")), startTime=_non_negative_number(numbers.get("startTime")), seed=_optional_int(mapping.get("seed")), audioMode=_project_audio_mode(strings.get("audioMode")), + passShape=_project_pass_shape(strings.get("passShape")), controlType=_project_control_type(strings.get("controlType")), + tilingOverlap=_project_tiling_overlap(numbers.get("tilingOverlap")), + carryFrames=_at_least(_optional_int(mapping.get("carryFrames")), MIN_CARRY_FRAMES), + tilingSize=_project_tile_size(strings.get("tilingSize")), + maxWindowFrames=_at_least(_optional_int(mapping.get("maxWindowFrames")), MIN_WINDOW_FRAMES), + width=_positive_int(mapping.get("width")), + height=_positive_int(mapping.get("height")), + provider=_project_provider(strings.get("provider")), ) @@ -310,6 +377,24 @@ def _project_lora_scale(value: object) -> int | float | None: return _optional_number(first.get("scale")) +def _project_custom_lora_id(value: object) -> str | None: + """``loras[0].customLoraId`` when the run used a saved custom LoRA.""" + if not isinstance(value, list) or not value: + return None + first = _string_mapping(cast(list[object], value)[0]) + return None if first is None else _optional_str(first.get("customLoraId")) + + +def _project_custom_lora_name(value: object) -> str | None: + """``loras[0].displayName`` when the run used a saved custom LoRA.""" + if not isinstance(value, list) or not value: + return None + first = _string_mapping(cast(list[object], value)[0]) + if first is None or _optional_str(first.get("customLoraId")) is None: + return None + return _optional_str(first.get("displayName")) + + def _project_inputs(value: object) -> RemoteVideoInputs | None: mapping = _string_mapping(value) if mapping is None: @@ -320,8 +405,9 @@ def _project_inputs(value: object) -> RemoteVideoInputs | None: video = _input_asset_ref(mapping.get("video")) image = _input_asset_ref(mapping.get("image")) images = _input_asset_refs(mapping.get("images")) + keyframes = _keyframes(mapping.get("keyframes")) paths = _motion_paths(mapping.get("paths")) - if images is None and paths is None and all( + if images is None and keyframes is None and paths is None and all( ref is None for ref in (start, end, audio, video, image) ): return None @@ -332,10 +418,32 @@ def _project_inputs(value: object) -> RemoteVideoInputs | None: video=video, image=image, images=images, + keyframes=keyframes, paths=paths, ) +def _keyframes(value: object) -> list[RemoteKeyframe] | None: + """The stills with frame and strength. One unusable entry drops the list, never a part of it.""" + if not isinstance(value, list): + return None + keyframes: list[RemoteKeyframe] = [] + for item in cast(list[object], value): + mapping = _string_mapping(item) + ref = None if mapping is None else _input_asset_ref(mapping) + frame_index = None if mapping is None else _optional_int(mapping.get("frameIndex")) + strength = None if mapping is None else _optional_number(mapping.get("strength")) + if ref is None or frame_index is None or strength is None: + return None + try: + keyframes.append( + RemoteKeyframe(assetId=ref.assetId, frameIndex=frame_index, strength=float(strength)) + ) + except ValidationError: + return None + return keyframes or None + + def _motion_paths(value: object) -> list[MotionPath] | None: if not isinstance(value, list): return None @@ -411,18 +519,48 @@ def _project_mode(value: str | None) -> RetakeMode | ExtendMode | None: return None +def _project_provider(value: str | None) -> ImageProvider | None: + if value in _REMOTE_IMAGE_PROVIDERS: + return cast(ImageProvider, value) + return None + + def _project_audio_mode(value: str | None) -> IcLoraAudioMode | None: if value in _REMOTE_AUDIO_MODES: return cast(IcLoraAudioMode, value) return None +def _project_pass_shape(value: str | None) -> PassShape | None: + if value in _REMOTE_PASS_SHAPES: + return cast(PassShape, value) + return None + + def _project_control_type(value: str | None) -> IcLoraControlType | None: if value in _REMOTE_CONTROL_TYPES: return cast(IcLoraControlType, value) return None +def _project_tile_size(value: str | None) -> IcLoraTileSize | None: + if value in _REMOTE_TILE_SIZES: + return cast(IcLoraTileSize, value) + return None + + +def _project_tiling_overlap(value: int | float | None) -> float | None: + if value is None or not MIN_TILE_OVERLAP <= value <= MAX_TILE_OVERLAP: + return None + return float(value) + + +def _at_least(value: int | None, minimum: int) -> int | None: + if value is None or value < minimum: + return None + return value + + def _optional_int(value: object) -> int | None: if isinstance(value, bool) or not isinstance(value, int): return None diff --git a/backend/remote/generations.py b/backend/remote/generations.py index 0796b5349..9015c78dc 100644 --- a/backend/remote/generations.py +++ b/backend/remote/generations.py @@ -1,9 +1,9 @@ """Remote-only generation HTTP surface. Desktop generation CRUD stays unfiltered. This module is the remote contract: -only Home/Remote text-to-video, image-to-video, audio-to-video, retake, -extend, and IC-LoRA recipes, plus get/retry/cancel/delete when the generation's feature is in that -allowlist. Recently used uses the same feature set on both apps. +only Home/Remote text-to-image, text-to-video, image-to-video, audio-to-video, retake, +extend, custom LoRA, and IC-LoRA recipes, plus get/retry/cancel/delete when the generation's feature is in that +allowlist. Recently used uses the same feature set on both apps, without the image jobs. """ from __future__ import annotations @@ -13,14 +13,21 @@ from _routes._errors import HTTPError from api_types import ( CreateAudioToVideoRequest, + CreateCustomLoraRequest, IcLoraRecipeCreate, CreateExtendRequest, CreateImageToVideoRequest, + CreateKeyframesRequest, CreateLoraRecipeRequest, CreateRetakeRequest, + CreateTextToImageRequest, CreateTextToVideoRequest, EditPreflightRequest, EditPreflightResponse, + IcLoraRecipeMemoryRequest, + IcLoraRecipeMemoryResponse, + IcLoraTilePreflightRequest, + IcLoraTilePreflightResponse, Generation, QueueSnapshot, ReorderGenerationQueueRequest, @@ -29,11 +36,13 @@ from app_handler import AppHandler from remote.deps import RemoteContext, get_remote_context from remote.dto import RemoteGeneration, RemoteQueueSnapshot, to_remote_queue_snapshot +from services.features.image.feature_id import FEATURE as TEXT_TO_IMAGE_FEATURE from services.features.queued_features import QUEUED_GENERATION_FEATURES from state import get_state_service -# Same set the desktop recents endpoint uses, so Electron and remote agree. -REMOTE_GENERATION_FEATURES = QUEUED_GENERATION_FEATURES +# The jobs Remote can read and control. Recently used asks for QUEUED_GENERATION_FEATURES alone, +# as on Desktop: an image job is Remote-visible but has no Home screen to reopen. +REMOTE_GENERATION_FEATURES = QUEUED_GENERATION_FEATURES | {TEXT_TO_IMAGE_FEATURE} router = APIRouter(prefix="/api") @@ -175,6 +184,23 @@ def route_create_text_to_video( ) +@router.post( + "/generations/text-to-image", + response_model=RemoteGeneration, + tags=["generations"], +) +def route_create_text_to_image( + req: CreateTextToImageRequest, + handler: AppHandler = Depends(get_state_service), + remote: RemoteContext = Depends(get_remote_context), +) -> RemoteGeneration: + return remote.generation( + handler.queued_generations.create_text_to_image( + req, analytics_client="remote" + ) + ) + + @router.post( "/generations/image-to-video", response_model=RemoteGeneration, @@ -192,6 +218,23 @@ def route_create_image_to_video( ) +@router.post( + "/generations/keyframes", + response_model=RemoteGeneration, + tags=["generations"], +) +def route_create_keyframes( + req: CreateKeyframesRequest, + handler: AppHandler = Depends(get_state_service), + remote: RemoteContext = Depends(get_remote_context), +) -> RemoteGeneration: + return remote.generation( + handler.queued_generations.create_keyframes( + req, analytics_client="remote" + ) + ) + + @router.post( "/generations/recipes/{recipe_id}", response_model=RemoteGeneration, @@ -212,6 +255,22 @@ def route_create_lora_recipe( ) +@router.post( + "/generations/custom-lora", + response_model=RemoteGeneration, + tags=["generations"], +) +def route_create_custom_lora( + req: CreateCustomLoraRequest, + handler: AppHandler = Depends(get_state_service), + remote: RemoteContext = Depends(get_remote_context), +) -> RemoteGeneration: + # The saved LoRA is named by id. The weights path is stripped by the DTO. + return remote.generation( + handler.queued_generations.create_custom_lora(req, analytics_client="remote") + ) + + @router.post( "/generations/audio-to-video", response_model=RemoteGeneration, @@ -271,6 +330,21 @@ def route_preflight_edit( return handler.queued_generations.preflight_edit(req) +@router.post( + "/generations/ic-lora-recipes/{recipe_id}/memory", + response_model=IcLoraRecipeMemoryResponse, + tags=["generations"], +) +def route_ic_lora_recipe_memory( + req: IcLoraRecipeMemoryRequest, + recipe_id: str = Path(pattern=r"^[a-z0-9-]+$", max_length=64), + handler: AppHandler = Depends(get_state_service), + _remote: RemoteContext = Depends(get_remote_context), +) -> IcLoraRecipeMemoryResponse: + # Path-free DTO (sizes and verdicts only): no remote projection needed. + return handler.ic_lora.recipe_memory(recipe_id, req) + + @router.post( "/generations/ic-lora-recipes/{recipe_id}", response_model=RemoteGeneration, @@ -289,6 +363,20 @@ def route_create_ic_lora_recipe( ) +@router.post( + "/generations/ic-lora-recipes/{recipe_id}/preflight", + response_model=IcLoraTilePreflightResponse, + tags=["generations"], +) +def route_preflight_ic_lora_tile_sizes( + req: IcLoraTilePreflightRequest, + recipe_id: str = Path(pattern=r"^[a-z0-9-]+$", max_length=64), + handler: AppHandler = Depends(get_state_service), +) -> IcLoraTilePreflightResponse: + # Path-free DTO (verdicts only): no remote projection needed. + return handler.queued_generations.preflight_ic_lora_tile_sizes(recipe_id, req) + + @router.get( "/generations/recent-features", response_model=list[str], @@ -301,7 +389,7 @@ def route_list_recent_features( ) -> list[str]: return handler.queued_generations.list_recent_features( limit=limit, - allowed=REMOTE_GENERATION_FEATURES, + allowed=QUEUED_GENERATION_FEATURES, ) diff --git a/backend/remote/loras.py b/backend/remote/loras.py index 6c30df0f5..2904e0774 100644 --- a/backend/remote/loras.py +++ b/backend/remote/loras.py @@ -1,4 +1,4 @@ -"""Remote LoRA-catalog surface: list + download for the recipe preflight. +"""Remote LoRA-catalog surface: list + download for the recipe preflight, plus the custom LoRA list. Mirrors the plain-LoRA endpoints of ``_routes.lora_catalog``. IC-LoRA downloads stay on the desktop. The phone only lists IC-LoRAs so a Home feature can tell @@ -9,17 +9,22 @@ from __future__ import annotations -from fastapi import APIRouter, Depends, Query +from fastapi import APIRouter, Depends, Path, Query +from fastapi.responses import FileResponse +from _routes._errors import HTTPError from api_types import ( ActiveLoraDownloadResponse, CatalogDownloadStartResponse, + CustomLoraItem, + CustomLoraListResponse, IcLoraListResponse, LoraDownloadProgressResponse, LoraDownloadRequest, LoraListResponse, ) from app_handler import AppHandler +from remote.deps import RemoteContext, get_remote_context from state import get_state_service router = APIRouter(prefix="/api") @@ -74,3 +79,42 @@ def route_lora_download_active( handler: AppHandler = Depends(get_state_service), ) -> ActiveLoraDownloadResponse: return handler.catalog.get_active_lora_download() + + +def _cover_for_phone(item: CustomLoraItem, remote: RemoteContext) -> CustomLoraItem: + """Swap the desktop file path for a signed URL. A phone cannot read ``file://``.""" + if item.cover_url is None: + return item + return item.model_copy( + update={ + "cover_url": remote.signer.sign( + f"/api/custom-loras/{item.id}/cover", + asset_id=item.id, + device_id=remote.device.id, + ) + } + ) + + +@router.get("/custom-loras", response_model=CustomLoraListResponse, tags=["custom-loras"]) +def route_list_custom_loras( + handler: AppHandler = Depends(get_state_service), + remote: RemoteContext = Depends(get_remote_context), +) -> CustomLoraListResponse: + # Read-only. Adding or deleting a custom LoRA stays on the desktop. + # The desktop list puts a file path in cover_url. Replace it before the phone sees the list. + listed = handler.custom_loras.list_loras() + return CustomLoraListResponse(loras=[_cover_for_phone(item, remote) for item in listed.loras]) + + +@router.get("/custom-loras/{custom_lora_id}/cover", tags=["custom-loras"]) +def route_custom_lora_cover( + custom_lora_id: str = Path(pattern=r"^[a-z0-9-]+$", max_length=64), + handler: AppHandler = Depends(get_state_service), +) -> FileResponse: + # The auth middleware already checked the signed URL. This only serves the cover file. + found = handler.custom_loras.cover_file(custom_lora_id) + if found is None: + raise HTTPError(404, "CUSTOM_LORA_COVER_NOT_FOUND") + path, media_type = found + return FileResponse(path, media_type=media_type, content_disposition_type="inline") diff --git a/backend/remote/prompt_enhancement.py b/backend/remote/prompt_enhancement.py index 0547df904..3e3987734 100644 --- a/backend/remote/prompt_enhancement.py +++ b/backend/remote/prompt_enhancement.py @@ -11,7 +11,9 @@ from _routes._errors import HTTPError from api_types import ( IC_LORA_SHEET_MAX_IMAGES, + LOCAL_MULTI_KEYFRAME_MAX_COUNT, EnhancePromptRequest, + KeyframeRef, EnhancePromptResponse, LTXVideoGenAspectRatio, LTXVideoGenResolution, @@ -19,6 +21,7 @@ ReplacedWindow, ) from app_handler import AppHandler +from runtime_config.nag_limits import NEGATIVE_PROMPT_MAX_LENGTH from services.prompt_enhancement.resolve_enhance_assets import resolve_enhance_media_assets from state import get_state_service @@ -30,18 +33,27 @@ class RemoteEnhancePromptRequest(BaseModel): model_config = ConfigDict(strict=True, extra="forbid") prompt: str + negativePrompt: str | None = Field(default=None, max_length=NEGATIVE_PROMPT_MAX_LENGTH) loraCatalogIds: list[str] = Field(default_factory=list) + # The saved custom LoRA. The id is checked against a strict pattern where it is read. + customLoraIds: list[str] = Field(default_factory=list, max_length=1) icLoraId: str | None = None imageAssetId: str | None = None lastImageAssetId: str | None = None # The panel images of an image-list IC-LoRA (Ingredients), in order. imageAssetIds: list[str] = Field(default_factory=list[str], max_length=IC_LORA_SHEET_MAX_IMAGES) + # The stills of a Keyframes clip. `duration` and `fps` give the rewrite their clock times. + keyframeAssets: list[KeyframeRef] = Field( + default_factory=list[KeyframeRef], max_length=LOCAL_MULTI_KEYFRAME_MAX_COUNT + ) + duration: int | None = Field(default=None, gt=0) + fps: int | None = Field(default=None, gt=0) aspectRatio: LTXVideoGenAspectRatio | None = None resolution: LTXVideoGenResolution | None = None videoAssetId: str | None = None replacedWindow: ReplacedWindow | None = None provider: Literal["local", "api"] | None = None - mediaType: Literal["video"] = "video" + mediaType: Literal["video", "image"] = "video" @field_validator("imageAssetId", "lastImageAssetId", "videoAssetId", mode="before") @classmethod @@ -74,6 +86,7 @@ def _last_frame_needs_first(self) -> RemoteEnhancePromptRequest: not self.prompt.strip() and not self.imageAssetId and not self.imageAssetIds + and not self.keyframeAssets and not self.videoAssetId ): raise ValueError("Prompt is required unless an image or video is provided") @@ -116,11 +129,16 @@ def route_remote_enhance_prompt( try: desktop_req = EnhancePromptRequest( prompt=req.prompt, + negativePrompt=req.negativePrompt, loraCatalogIds=req.loraCatalogIds, + customLoraIds=req.customLoraIds, icLoraId=req.icLoraId, imageAssetId=req.imageAssetId, lastImageAssetId=req.lastImageAssetId, imageAssetIds=req.imageAssetIds, + keyframeAssets=req.keyframeAssets, + duration=req.duration, + fps=req.fps, aspectRatio=req.aspectRatio, resolution=req.resolution, videoAssetId=req.videoAssetId, diff --git a/backend/runtime_config/assets_layout.py b/backend/runtime_config/assets_layout.py new file mode 100644 index 000000000..a13f9a3c5 --- /dev/null +++ b/backend/runtime_config/assets_layout.py @@ -0,0 +1,16 @@ +"""Where the asset store keeps its files. One definition, used by the store and its callers.""" + +from __future__ import annotations + +from pathlib import Path + +IN_FLIGHT_DIRNAME = ".in-flight" + + +def assets_folder(app_data_dir: Path, assets_dir: Path | None = None) -> Path: + """The user-chosen assets folder (LTX_ASSETS_DIR), or ``/assets``.""" + return assets_dir if assets_dir is not None else app_data_dir / "assets" + + +def in_flight_folder(app_data_dir: Path, assets_dir: Path | None = None) -> Path: + return assets_folder(app_data_dir, assets_dir) / IN_FLIGHT_DIRNAME diff --git a/backend/runtime_config/budget_admission.py b/backend/runtime_config/budget_admission.py new file mode 100644 index 000000000..da0c59fa2 --- /dev/null +++ b/backend/runtime_config/budget_admission.py @@ -0,0 +1,786 @@ +"""The one admission policy: may this priced job run, and as what bet. + +Pricing (``video_job_budget``, ``ic_lora_job_budget``) is mode-blind and +returns a ``PricedJob``. ``admit`` turns it into ``Admitted`` or ``Refused`` +from the verdict, its evidence, and a ``RiskAllowance``. The budget mode +enters only through the allowance, so no caller re-reads the mode, the +reject reasons, or the evidence to decide whether a job may run. +""" + +from __future__ import annotations + +from collections.abc import Mapping +from dataclasses import dataclass +from typing import TYPE_CHECKING, Literal, TypedDict, TypeGuard, assert_never + +from pydantic import ValidationError + +from api_types import BudgetReadout, GenerationRisk, LocalUnavailableReason +from runtime_config.budget_decision import ( + IcLoraJobDecision, + IcLoraJobLoad, + IcLoraJobReject, + VideoJobDecision, + VideoJobLoad, + VideoJobReject, +) +from runtime_config.budget_evidence import ( + Extrapolated, + Fitted, + GenericCurve, + JobShape, + PriceEvidence, +) +from runtime_config.device_calibration import JobEnvelope, envelope_for +from runtime_config.measured_cells import BudgetFeature +from runtime_config.reject_reasons import ( + BudgetMode, + JobRiskTier, + ShortfallKind, + UnmeasuredBasis, + VideoJobRejectReason, + WarnedCellTier, +) + +if TYPE_CHECKING: + # Runtime import would cycle (video_job_budget imports this module). + from runtime_config.video_job_budget import LocalJobFilter + +_GIB = 1024**3 +TIGHT_FIT_HEADROOM_GIB = 0.5 +TIGHT_FIT_HEADROOM_RATIO = 0.05 + + +def _is_str_object_dict(value: object) -> TypeGuard[dict[str, object]]: + return isinstance(value, dict) + + +def stored_generation_risk(spec: Mapping[str, object]) -> GenerationRisk | None: + """The stored bet, or None when it is missing or junk. + + Junk fails closed: execute must not waive a limit off a corrupt row. + """ + risk = spec.get("_risk") + if not _is_str_object_dict(risk): + return None + try: + return GenerationRisk.model_validate(risk) + except ValidationError: + return None + + +@dataclass(frozen=True, slots=True) +class PricedJob: + """A mode-blind verdict plus everything admission needs to apply the mode. + + ``covered``, ``tight``, and ``over_risk`` are attached by ``priced_job``: + ``covered`` marks an extrapolated load this device already ran cleanly at + an equal or larger shape; ``tight`` marks a load inside max(0.5 GiB, 5% of + the ask); ``over_risk`` is the bet a downgradable reject would run as, + None for loads, hard walls, and uncompared figures. + """ + + feature: BudgetFeature + decision: VideoJobDecision | IcLoraJobDecision + evidence: PriceEvidence + shape: JobShape + covered: bool = False + tight: bool = False + over_risk: GenerationRisk | None = None + # The carry an IC-LoRA job on Auto carry runs, picked with its window. None otherwise. + carry_frames: int | None = None + + @property + def seq(self) -> float: + return self.decision.seq + + @property + def full_gib(self) -> float: + return self.decision.full_gib + + @property + def stream_gib(self) -> float: + return self.decision.stream_gib + + @property + def chunk_pixel_frames(self) -> int | None: + return self.decision.chunk_pixel_frames + + +@dataclass(frozen=True, slots=True) +class RiskAllowance: + """Which bets may run: an over-budget downgrade, an untested load, or both.""" + + over: bool + unmeasured: bool + + @staticmethod + def none() -> RiskAllowance: + return RiskAllowance(over=False, unmeasured=False) + + @staticmethod + def for_mode(mode: BudgetMode) -> RiskAllowance: + match mode: + case "brave": + return RiskAllowance(over=True, unmeasured=True) + case "cautious": + return RiskAllowance(over=False, unmeasured=False) + case _ as unreachable: + assert_never(unreachable) + + @staticmethod + def from_risk(risk: GenerationRisk | None) -> RiskAllowance: + """Allowance for the bet a queued job already confirmed. + + A stored ``over`` bet covers the over-budget downgrade (plus the + extrapolated load when ``unmeasured_basis`` was part of the bet). A + stored ``unmeasured`` bet covers the untested load it was taken for, + never a later VRAM or RAM miss. + """ + if risk is None: + return RiskAllowance.none() + match risk.tier: + case "over": + return RiskAllowance( + over=True, + unmeasured=risk.unmeasured_basis is not None, + ) + case "unmeasured": + return RiskAllowance(over=False, unmeasured=True) + case _ as unreachable: + assert_never(unreachable) + + @staticmethod + def from_stored(spec: Mapping[str, object]) -> RiskAllowance: + """Parse the stored ``_risk`` annotation on a queued generation spec.""" + return RiskAllowance.from_risk(stored_generation_risk(spec)) + + def without_over(self) -> RiskAllowance: + """Keep ``unmeasured`` while probing for a free-VRAM dip that can shrink.""" + return RiskAllowance(over=False, unmeasured=self.unmeasured) + + +@dataclass(frozen=True, slots=True) +class Admitted: + priced: PricedJob + load: VideoJobLoad | IcLoraJobLoad + # Confirmable bet, stored as spec["_risk"]. None for a clean admit. + risk: GenerationRisk | None + # Passive tight-fit note; never confirms. + tight: bool + + @property + def envelope(self) -> JobEnvelope: + """The shape this admission runs, as device calibration records it.""" + return envelope_for(self.priced.shape, self.load.mode, self.load.stream_gib) + + +@dataclass(frozen=True, slots=True) +class Refused: + priced: PricedJob + reject: VideoJobReject | IcLoraJobReject + # The bet the job would run as if the allowance covered it. None for a hard wall. + bet: GenerationRisk | None + + +Admission = Admitted | Refused + + +def priced_job( + feature: BudgetFeature, + decision: VideoJobDecision | IcLoraJobDecision, + evidence: PriceEvidence, + shape: JobShape, + *, + job_filter: LocalJobFilter, +) -> PricedJob: + """Attach the compared figures admission needs: local coverage, tight fit, or the over bet. + + An extrapolated load this device already ran cleanly at an equal or larger + shape is ``covered``. An over bet on an extrapolated verdict names the + missing measurement, but keeps tier ``over``: a real memory miss is never + relabelled untested, and a device proof never waives it. + """ + if isinstance(decision, (VideoJobLoad, IcLoraJobLoad)): + covered = isinstance(evidence, Extrapolated) and ( + job_filter.calibration.covering( + envelope_for(shape, decision.mode, decision.stream_gib) + ) + is not None + ) + return PricedJob( + feature=feature, + decision=decision, + evidence=evidence, + shape=shape, + covered=covered, + tight=is_tight_fit(decision, job_filter), + ) + over_risk = ( + risk_for_reject(decision, job_filter) + if isinstance(decision, VideoJobReject) + else None + ) + if over_risk is not None and isinstance(evidence, Extrapolated): + over_risk = over_risk.model_copy(update={"unmeasured_basis": evidence.basis}) + return PricedJob( + feature=feature, + decision=decision, + evidence=evidence, + shape=shape, + over_risk=over_risk, + ) + + +def admit(priced: PricedJob, allowance: RiskAllowance) -> Admission: + """Apply the admission table to one priced job. + + Hard walls refuse in every mode. A fitted load admits (tight when the + headroom is small); a generic-curve load or a locally covered extrapolation + admits silently. An uncovered extrapolated load admits with an unmeasured + bet when the allowance covers it, else refuses as ``unmeasured_cell`` with + the priced figures. A downgradable reject runs streaming at its own window + with an over bet when the allowance covers it: a real memory miss is never + relabelled untested. + """ + decision = priced.decision + if isinstance(decision, (VideoJobLoad, IcLoraJobLoad)): + match priced.evidence: + case Fitted(): + return Admitted(priced=priced, load=decision, risk=None, tight=priced.tight) + case GenericCurve(): + return Admitted(priced=priced, load=decision, risk=None, tight=False) + case Extrapolated(basis=basis): + if priced.covered: + return Admitted(priced=priced, load=decision, risk=None, tight=False) + risk = unmeasured_risk(basis, need_gib=decision.stream_gib) + if allowance.unmeasured: + return Admitted(priced=priced, load=decision, risk=risk, tight=False) + return Refused( + priced=priced, + reject=VideoJobReject( + seq=decision.seq, + full_gib=decision.full_gib, + stream_gib=decision.stream_gib, + reason="unmeasured_cell", + chunk_pixel_frames=decision.chunk_pixel_frames, + unmeasured_basis=basis, + ), + bet=risk, + ) + case _ as unreachable: + assert_never(unreachable) + if isinstance(decision, IcLoraJobReject) or not is_downgradable(decision): + return Refused(priced=priced, reject=decision, bet=None) + risk = priced.over_risk + if risk is not None and allowance.over: + return Admitted( + priced=priced, + load=_streaming_load(priced.feature, decision), + risk=risk, + tight=False, + ) + return Refused(priced=priced, reject=decision, bet=risk) + + +def admits_within_device_memory(priced: PricedJob, mode: BudgetMode) -> bool: + """Whether ``admit`` accepts ``priced`` in ``mode`` without a device-memory miss. + + Used by the IC-LoRA recipe fit preview: Cautious requires a clean admit; + Brave admits untested loads and host-RAM shortfalls whose GPU ask fits, but + still bounds the preview by the device's VRAM / MPS pool (``stream_over``). + """ + if isinstance(priced.decision, VideoJobReject) and priced.decision.reason == "stream_over": + return False + return isinstance(admit(priced, RiskAllowance.for_mode(mode)), Admitted) + + +def is_downgradable(decision: VideoJobReject | IcLoraJobReject) -> bool: + """A memory miss (VRAM or RAM) that may run as an over bet. + + ``unsupported`` (no pipeline), ``mps_sequence_over`` (the Metal kernel + aborts past the fence), and the IC-LoRA canvas and decode walls never run. + """ + if isinstance(decision, IcLoraJobReject): + return False + match decision.reason: + case "stream_over" | "ram_shortfall": + return True + case "unsupported" | "mps_sequence_over" | "unmeasured_cell" | "one_pass_unavailable": + return False + case _ as unreachable: + assert_never(unreachable) + + +def is_clean(priced: PricedJob) -> bool: + """A load whose evidence needs no bet.""" + return isinstance(priced.decision, (VideoJobLoad, IcLoraJobLoad)) and ( + not isinstance(priced.evidence, Extrapolated) or priced.covered + ) + + +_SafetyRank = Literal[0, 1, 2, 3] + + +def safety_rank(priced: PricedJob) -> _SafetyRank: + decision = priced.decision + if isinstance(decision, (VideoJobLoad, IcLoraJobLoad)): + if isinstance(priced.evidence, Extrapolated) and not priced.covered: + return 2 + return 3 + return 1 if is_downgradable(decision) else 0 + + +def safer(first: PricedJob, chunked: PricedJob) -> PricedJob: + """The safer of an unchunked and a chunked price for one job. + + Clean load > extrapolated load > downgradable reject > hard wall. A tie + keeps the unchunked job, so chunking only escapes risk and never adds + seams to a job that already fits; between two downgradable rejects the + smaller ask wins, so a downgrade runs the cheaper window. + """ + first_rank = safety_rank(first) + chunked_rank = safety_rank(chunked) + if chunked_rank > first_rank: + return chunked + if ( + chunked_rank == first_rank == 1 + and chunked.decision.stream_gib < first.decision.stream_gib + ): + return chunked + return first + + +def budget_readout_for_reject( + decision: VideoJobReject, job_filter: LocalJobFilter +) -> BudgetReadout | None: + """Need and have for the same comparison ``reject_message_and_code`` prints. + + None for a hard wall or when the gate compared no figure. + """ + reason = decision.reason + if reason == "unmeasured_cell": + return untested_readout(decision.stream_gib) + if reason in ("unsupported", "mps_sequence_over", "one_pass_unavailable"): + return None + if reason == "ram_shortfall": + required = decision.required_ram_bytes + detected = job_filter.budget.total_ram_bytes + if required is None or detected is None: + return None + return BudgetReadout( + kind="ram", + need_gb=float(required // _GIB), + have_gb=float(detected // _GIB), + ) + required_gib = decision.stream_gib + if job_filter.profile.system == "Darwin": + pool = job_filter.budget.mps_pool_gib + if pool is None: + return None + return BudgetReadout(kind="mac", need_gb=required_gib, have_gb=pool) + total = job_filter.budget.usable_vram_gib + available = job_filter.budget.available_vram_gib + if total is None or available is None: + return None + if required_gib > total: + return BudgetReadout(kind="gpu", need_gb=required_gib, have_gb=total) + if required_gib > available: + return BudgetReadout(kind="gpu_busy", need_gb=required_gib, have_gb=available) + return None + + +def tight_readout(ask_gib: float, available_gib: float) -> BudgetReadout: + return BudgetReadout(kind="tight", need_gb=ask_gib, have_gb=available_gib) + + +def compared_available_gib(job_filter: LocalJobFilter) -> float | None: + """The figure the gate compared the ask against. + + Single home for the figure-selection rule: the MPS pool on Darwin, + min(total, free) — or usable_vram_gib under total_only — on CUDA. None + means the gate compared nothing (callers stay silent). + """ + if job_filter.profile.system == "Darwin": + return job_filter.budget.mps_pool_gib + if job_filter.budget.total_vram_bytes is None: + return None + return job_filter.budget.available_vram_gib + + +def load_headroom_gib( + decision: VideoJobLoad | IcLoraJobLoad, job_filter: LocalJobFilter +) -> float | None: + """Available minus ask on the compared figure. None when uncompared.""" + available = compared_available_gib(job_filter) + if available is None: + return None + return available - decision.stream_gib + + +def is_tight_fit( + decision: VideoJobLoad | IcLoraJobLoad, job_filter: LocalJobFilter +) -> bool: + """A load inside max(0.5 GiB, 5% of the ask) on the compared figure. + + Unknown figures stay silent. + """ + headroom = load_headroom_gib(decision, job_filter) + if headroom is None: + return False + threshold = max( + TIGHT_FIT_HEADROOM_GIB, TIGHT_FIT_HEADROOM_RATIO * decision.stream_gib + ) + return headroom < threshold + + +def reject_risk_tier(reason: VideoJobRejectReason) -> JobRiskTier | None: + """Measurement rejects are over-budget bets, an unmeasured cell is an + unmeasured bet; hard walls return None. + + Allow-list: a new ``VideoJobRejectReason`` fails typecheck here until it + picks a tier. ``unsupported`` (no pipeline) and ``mps_sequence_over`` (the + Metal kernel SIGABRTs past the fence — uncatchable, not a bet) never + downgrade. + """ + match reason: + case "stream_over" | "ram_shortfall": + return "over" + case "unmeasured_cell": + return "unmeasured" + case "unsupported" | "mps_sequence_over" | "one_pass_unavailable": + return None + case _ as unreachable: + assert_never(unreachable) + + +def reject_over_gib( + decision: VideoJobReject, job_filter: LocalJobFilter +) -> float | None: + """VRAM shortfall on a stream_over reject. None for any other reason — + RAM verdicts passed VRAM, so subtracting would print a negative lie.""" + if decision.reason != "stream_over": + return None + available = compared_available_gib(job_filter) + if available is None: + return None + return decision.stream_gib - available + + +def reject_over_ram_gb( + decision: VideoJobReject, job_filter: LocalJobFilter +) -> int | None: + """RAM shortfall in whole GB, message-consistent (required//GiB minus + detected//GiB, the same ints the 422 prints).""" + if decision.reason != "ram_shortfall": + return None + required = decision.required_ram_bytes + detected = job_filter.budget.total_ram_bytes + if required is None or detected is None: + return None + return required // _GIB - detected // _GIB + + +def reject_shortfall_kind( + decision: VideoJobReject, job_filter: LocalJobFilter +) -> ShortfallKind | None: + """Which figure bound a CUDA stream_over reject. + + "free" only when free strictly binds (free < total on exact floats — + min() returns its input, so equality with total is exact). Total-gated + lists, missing samples, and Darwin (pool gate, never free advice) all + report "total"/None respectively: Darwin returns None and the frontend + keys Darwin copy off platform, not kind. + """ + if decision.reason != "stream_over": + return None + if job_filter.profile.system == "Darwin": + return None + total = job_filter.budget.usable_vram_gib + available = job_filter.budget.available_vram_gib + if total is None or available is None: + return None + return "total" if available == total or decision.stream_gib > total else "free" + + +def tight_fit_message(ask_gib: float, available_gib: float, *, darwin: bool) -> str: + if darwin: + return ( + f"Tight fit: this needs ~{ask_gib:.1f} GB of the " + f"{available_gib:.1f} GB available for video on this Mac. It should run." + ) + return ( + f"Tight fit: this needs ~{ask_gib:.1f} GB and about " + f"{available_gib:.1f} GB is available. It should run, but close " + "other heavy apps (like games, browsers, or video editors) first." + ) + + +def over_budget_message( + ask_gib: float, + available_gib: float, + *, + darwin: bool, + shortfall_kind: ShortfallKind | None, +) -> str: + if darwin: + return ( + f"Needs too much memory: this needs {ask_gib:.1f} GB but this Mac allows " + f"{available_gib:.1f} GB. It may run out of memory or stall — " + "lower the resolution or duration to fit." + ) + if shortfall_kind == "free": + return ( + f"Needs too much memory right now: this needs {ask_gib:.1f} GB but only " + f"{available_gib:.1f} GB is free. Close other heavy apps (like games, " + "browsers, or video editors) and retry, or lower the resolution or duration." + ) + return ( + f"Needs too much memory: this needs {ask_gib:.1f} GB but this machine's graphics " + f"card has {available_gib:.1f} GB. It may run out of memory or stall — " + "lower the resolution or duration to fit." + ) + + +def over_ram_message(required_gb: int, detected_gb: int) -> str: + return ( + f"Needs too much memory: this needs {required_gb} GB of system RAM but this machine " + f"has {detected_gb} GB. Close heavy programs; on desktops, more RAM " + "is the real fix." + ) + + +def risk_for_reject( + decision: VideoJobReject, job_filter: LocalJobFilter +) -> GenerationRisk | None: + """Over-budget annotation for a measurement reject, if downgradable. + + Returns None for unsupported (hard wall) and for uncompared figures. + Legacy-route rejects tier as over: the curve is rough, but a reject is + conservative by construction — the unmeasured bet is the legacy *load*. + """ + tier = reject_risk_tier(decision.reason) + if tier is None: + return None + if tier == "unmeasured": + basis = decision.unmeasured_basis + if basis is None: + return None + return unmeasured_risk(basis, need_gib=decision.stream_gib) + darwin = job_filter.profile.system == "Darwin" + if decision.reason == "ram_shortfall": + required = decision.required_ram_bytes + detected = job_filter.budget.total_ram_bytes + if required is None or detected is None: + return None + required_gb = required // _GIB + detected_gb = detected // _GIB + return GenerationRisk( + tier="over", + shortfall_kind=None, + over_gib=None, + over_ram_gb=required_gb - detected_gb, + message=over_ram_message(required_gb, detected_gb), + readout=budget_readout_for_reject(decision, job_filter), + ) + available = compared_available_gib(job_filter) + if available is None: + return None + kind = reject_shortfall_kind(decision, job_filter) + over = decision.stream_gib - available + return GenerationRisk( + tier="over", + shortfall_kind=kind, + over_gib=over, + over_ram_gb=None, + message=over_budget_message( + decision.stream_gib, available, darwin=darwin, shortfall_kind=kind + ), + readout=budget_readout_for_reject(decision, job_filter), + ) + + +def unmeasured_message(basis: UnmeasuredBasis) -> str: + """The bet line for an admitted untested job.""" + match basis: + case "high_res_cell": + return ( + "Untested: this resolution hasn't been run on hardware like yours, " + "so the memory estimate is extrapolated. It may fail or stall." + ) + case "two_stage_range": + return ( + "Untested: this two-step upscale is longer than we have measured at " + "this photo size, so the memory estimate is extrapolated. It may " + "fail or stall." + ) + case "mac_two_stage_cell": + return ( + "Untested: two-step upscaling at this size isn't measured on Mac yet. " + "It may fail or stall." + ) + case "windowed_range": + return ( + "Untested: this clip runs in more sections than we have tested on " + "hardware like yours, so the memory estimate is extrapolated. It may " + "take a long time, and it may fail or stall." + ) + case "pass_tokens": + return ( + "Untested: this clip is longer than the longest clip we have " + "tested all at once, so the memory estimate is extrapolated. It may fail or stall." + ) + case "unmeasured_model": + return ( + "Untested: this model hasn't been measured on hardware like yours yet, " + "so the memory estimate is extrapolated. It may fail or stall." + ) + case _ as unreachable: + assert_never(unreachable) + + +def unmeasured_refusal_message(basis: UnmeasuredBasis) -> str: + """The refusal line for an untested job the mode does not allow.""" + match basis: + case "high_res_cell": + return ( + "This resolution hasn't been tested on this machine, so Cautious " + "mode blocks it. Turn off Cautious mode to try it anyway, or lower " + "the resolution." + ) + case "two_stage_range": + return ( + "This two-step upscale is longer than we have measured at this photo " + "size, so Cautious mode blocks it. Try a shorter clip, a smaller " + "photo, or single-stage, or turn off Cautious mode to try it anyway." + ) + case "mac_two_stage_cell": + return ( + "Two-step upscaling at this size isn't measured on Macs yet, so " + "Cautious mode blocks it. Use single-stage, or turn off Cautious " + "mode to try it anyway." + ) + case "windowed_range": + return ( + "This clip runs in more sections than we have tested on this machine, " + "so Cautious mode blocks it. Try a shorter clip, a lower frame rate or " + "a smaller resolution, or turn off Cautious mode to try it anyway." + ) + case "pass_tokens": + return ( + "This clip is longer than the longest clip we have tested all at once, so " + "Cautious mode blocks it. Try a shorter clip or a lower frame rate, or " + "turn off Cautious mode to try it anyway." + ) + case "unmeasured_model": + return ( + "This model hasn't been tested on this machine yet, so Cautious " + "mode blocks it. Turn off Cautious mode to try it anyway." + ) + case _ as unreachable: + assert_never(unreachable) + + +def untested_readout(need_gib: float | None = None) -> BudgetReadout: + return BudgetReadout(kind="untested", need_gb=need_gib) + + +def unmeasured_risk(basis: UnmeasuredBasis, *, need_gib: float) -> GenerationRisk: + return GenerationRisk( + tier="unmeasured", + message=unmeasured_message(basis), + readout=untested_readout(need_gib), + unmeasured_basis=basis, + ) + + +def _streaming_load( + feature: BudgetFeature, reject: VideoJobReject +) -> VideoJobLoad | IcLoraJobLoad: + """The streamed load an over bet runs: the reject's own window and figures.""" + if feature == "iclora": + return IcLoraJobLoad( + mode="streaming_models_loading", + seq=reject.seq, + full_gib=reject.full_gib, + stream_gib=reject.stream_gib, + chunk_pixel_frames=reject.chunk_pixel_frames, + ) + return VideoJobLoad( + mode="streaming_models_loading", + seq=reject.seq, + full_gib=reject.full_gib, + stream_gib=reject.stream_gib, + chunk_pixel_frames=reject.chunk_pixel_frames, + ) + + +class DroppedCellFieldsPayload(TypedDict): + reason: LocalUnavailableReason + message: str + over_gib: float | None + over_ram_gb: int | None + shortfall_kind: ShortfallKind | None + readout: BudgetReadout | None + unmeasured_basis: UnmeasuredBasis | None + + +def dropped_cell_fields( + reject: VideoJobReject, + evidence: PriceEvidence, + job_filter: LocalJobFilter, + *, + message: str, +) -> DroppedCellFieldsPayload: + """Refusal copy and figures for one withheld cell. + + Figures come from one ``risk_for_reject`` call. When it declines (hard + wall, or no compared exact bytes) the per-figure helpers still name an + integer-fallback total binding, so the fallback keeps those rows + byte-identical. + """ + risk = risk_for_reject(reject, job_filter) + return { + "reason": reject.reason, + "message": message, + "over_gib": (risk.over_gib if risk is not None else reject_over_gib(reject, job_filter)), + "over_ram_gb": ( + risk.over_ram_gb if risk is not None else reject_over_ram_gb(reject, job_filter) + ), + "shortfall_kind": ( + risk.shortfall_kind + if risk is not None + else reject_shortfall_kind(reject, job_filter) + ), + "readout": budget_readout_for_reject(reject, job_filter), + "unmeasured_basis": (evidence.basis if isinstance(evidence, Extrapolated) else None), + } + + +def warned_cell_parts( + admitted: Admitted, job_filter: LocalJobFilter +) -> tuple[WarnedCellTier, float | None, str, BudgetReadout | None] | None: + """Warning tier, headroom, and tooltip for a kept cell, if it warns. + + Single home for warned-cell emission (base cells and aspect cells): a bet + the mode admitted (over or unmeasured) carries its own line and readout; + tight cells carry available-minus-ask headroom. None when the cell fits + cleanly. + """ + risk = admitted.risk + if risk is not None: + return (risk.tier, None, risk.message, risk.readout) + if not admitted.tight: + return None + load = admitted.load + headroom = load_headroom_gib(load, job_filter) + assert headroom is not None # a tight fit implies compared figures exist + available = headroom + load.stream_gib + darwin = job_filter.profile.system == "Darwin" + return ( + "tight", + headroom, + tight_fit_message(load.stream_gib, available, darwin=darwin), + tight_readout(load.stream_gib, available), + ) + diff --git a/backend/runtime_config/budget_decision.py b/backend/runtime_config/budget_decision.py new file mode 100644 index 000000000..30a08defc --- /dev/null +++ b/backend/runtime_config/budget_decision.py @@ -0,0 +1,77 @@ +"""Priced verdicts for one local job: load it (and how) or refuse it. + +Leaf module shared by the pricing layer (``video_job_budget``, +``ic_lora_job_budget``) and the admission layer (``budget_admission``), so the +admission policy can build and downgrade verdicts without importing pricing. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Literal + +from runtime_config.reject_reasons import UnmeasuredBasis, VideoJobRejectReason + +LoadMode = Literal["full_models_loading", "streaming_models_loading"] + + +@dataclass(frozen=True, slots=True) +class VideoJobLoad: + mode: LoadMode + seq: float + full_gib: float + stream_gib: float + # Window length in pixel frames when the job runs in windows, else None (one pass). + # ``seq`` and the GiB figures then describe one window. The pipeline runs this value. + chunk_pixel_frames: int | None = None + + +@dataclass(frozen=True, slots=True) +class VideoJobReject: + seq: float + full_gib: float + stream_gib: float + reason: VideoJobRejectReason = "stream_over" + # RAM floor the gate compared, set only on ram_shortfall (its sole + # producer is _streaming_ram_reject, which holds the figure). Message + # builders read this — never re-derive the floor from the profile, or a + # wrong property prints a number the gate did not compare. + required_ram_bytes: int | None = None + # Set by IC-LoRA and by a Fast canvas that runs in windows, to the window the + # pricing tried. A downgraded over-budget job must run that window: ``None`` is one + # unchunked pass, which costs more than the over-budget figure the user + # confirmed. Edit leaves it None. + chunk_pixel_frames: int | None = None + # Which lab measurement is missing, set only on ``unmeasured_cell`` (produced + # by admission, never by pricing). + unmeasured_basis: UnmeasuredBasis | None = None + + +VideoJobDecision = VideoJobLoad | VideoJobReject + + +@dataclass(frozen=True, slots=True) +class IcLoraJobLoad: + mode: LoadMode + seq: float + full_gib: float + stream_gib: float + # Window length when the job runs chunked, else None. The pipeline runs this value. + chunk_pixel_frames: int | None = None + + +@dataclass(frozen=True, slots=True) +class IcLoraJobReject: + reason: Literal["spatial", "unsupported", "refine_decode_floor", "window_over_cap"] + seq: float + full_gib: float + stream_gib: float + # Uniform with VideoJobReject; always None (these verdicts never compare + # RAM — spatial is a canvas fence, unsupported short-circuits first, and + # the decode floor refuses before any curve runs). + required_ram_bytes: int | None = None + # Window the pricing tried; None is one unchunked pass. + chunk_pixel_frames: int | None = None + + +IcLoraJobDecision = IcLoraJobLoad | IcLoraJobReject | VideoJobReject diff --git a/backend/runtime_config/budget_evidence.py b/backend/runtime_config/budget_evidence.py new file mode 100644 index 000000000..b0d7c7db7 --- /dev/null +++ b/backend/runtime_config/budget_evidence.py @@ -0,0 +1,52 @@ +"""How much to trust a priced verdict, and the job shape it priced. + +Pricing tags every verdict with its evidence; admission reads the tag. A +``Fitted`` verdict sits inside the lab-measured range, ``GenericCurve`` comes +from the legacy curve (no measured route), and ``Extrapolated`` prices a shape +no lab run covers. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field + +from runtime_config.measured_cells import BudgetFeature +from runtime_config.reject_reasons import UnmeasuredBasis + + +@dataclass(frozen=True, slots=True) +class Fitted: + pass + + +@dataclass(frozen=True, slots=True) +class GenericCurve: + pass + + +@dataclass(frozen=True, slots=True) +class Extrapolated: + basis: UnmeasuredBasis + + +PriceEvidence = Fitted | GenericCurve | Extrapolated + + +@dataclass(frozen=True, slots=True) +class JobShape: + """What the priced job runs, minus the load mode. Device calibration keys on it.""" + + feature: BudgetFeature + model_id: str + # IC-LoRA adapter id; "" for Fast and edit (their laws ignore LoRAs). + adapter_id: str + # IcLoraStageMode value; "" for Fast and edit. + stage_mode: str + tiled: bool + chunked: bool + # Heaviest pass tokens, per window when chunked. + seq: float + # Output canvas (Fast, edit) or heavy-pass canvas (IC-LoRA), in pixels. + canvas_px: int + windows: int + tiles: int = field(default=1, compare=False) diff --git a/backend/runtime_config/custom_lora_urls.py b/backend/runtime_config/custom_lora_urls.py new file mode 100644 index 000000000..0f4f26466 --- /dev/null +++ b/backend/runtime_config/custom_lora_urls.py @@ -0,0 +1,253 @@ +"""Rules for the URL a user pastes to add a custom LoRA. + +Two kinds of link are supported: a Hugging Face model page and a Hugging Face file link. +Civitai and other direct HTTPS links to a ``.safetensors`` file are also parsed below, but +they are not supported and not tested. Everything else fails before a request leaves the +machine. The same rules run again on every redirect target, because a download link often +redirects to a CDN host. + +A Hugging Face model page names no file. ``resolve_custom_lora_url`` returns the repo, the +handler lists its files, and ``pick_hugging_face_weights`` chooses the one ``.safetensors`` file. +""" + +from __future__ import annotations + +import ipaddress +import re +from collections.abc import Sequence +from dataclasses import dataclass +from urllib.parse import parse_qs, quote, unquote, urlsplit + +# The in-app Hugging Face token goes to these hosts only. A redirect target (a signed CDN URL) +# never gets it. +HF_HOSTS = frozenset({"huggingface.co", "hf.co"}) +CIVITAI_HOSTS = frozenset({"civitai.com", "www.civitai.com"}) + +_CIVITAI_DOWNLOAD_PATH = re.compile(r"^/api/download/models/(\d+)/?$") +_CIVITAI_PAGE_PATH = re.compile(r"^/models/\d+") +# A model page is //, optionally with /tree/. A file page is +# ///blob//. The file page differs from the download link by one word. +# Owner and name use the characters Hugging Face allows, so they are safe in an API path. +_HF_NAME = r"[A-Za-z0-9][A-Za-z0-9._-]*" +_HF_MODEL_PAGE_PATH = re.compile( + rf"^/(?P{_HF_NAME})/(?P{_HF_NAME})(?:/tree/(?P[^/]+))?/?$" +) +# Any link to a repo: model page, /tree/, /blob/ or /resolve/ file link. The revision is optional. +_HF_REPO_LINK_PATH = re.compile( + rf"^/(?P{_HF_NAME})/(?P{_HF_NAME})(?:/(?:tree|blob|resolve)/(?P[^/]+))?(?:/|$)" +) +_HF_FILE_PATH = re.compile( + rf"^/(?P{_HF_NAME})/(?P{_HF_NAME})/(?:blob|resolve)/(?P[^/]+)/(?P.+\.safetensors)$", + re.IGNORECASE, +) +_HF_OWNER_PATH = re.compile(rf"^/(?P{_HF_NAME})/(?P{_HF_NAME})(?:/|$)") +# Top-level Hugging Face sections that look like // but are not model repos. +_HF_RESERVED_OWNERS = frozenset( + {"api", "blog", "collections", "datasets", "docs", "models", "papers", "settings", "spaces"} +) +_HF_DEFAULT_REVISION = "main" +_MAX_LISTED_NAMES = 4 + + +class CustomLoraUrlError(ValueError): + """The URL is not accepted. The message is safe to show to the user.""" + + +@dataclass(frozen=True, slots=True) +class HuggingFaceRepo: + """A Hugging Face model repository named by a model-page link.""" + + repo_id: str + revision: str = _HF_DEFAULT_REVISION + + @property + def page_url(self) -> str: + return f"https://huggingface.co/{self.repo_id}" + + def file_url(self, filename: str) -> str: + path = "/".join(quote(part, safe="") for part in filename.split("/")) + return f"{self.page_url}/resolve/{quote(self.revision, safe='')}/{path}" + + +@dataclass(frozen=True, slots=True) +class CustomLoraUrl: + """A checked URL. ``repo`` is set when the link is a model page: it still names no file.""" + + url: str + host: str + repo: HuggingFaceRepo | None = None + + @property + def is_hugging_face(self) -> bool: + return self.host in HF_HOSTS + + +_TOP_LEVEL_LABEL = re.compile(r"[a-z][a-z0-9-]*") + + +def _host_is_local(host: str) -> bool: + """Whether the host is, or can be written as, this computer or a private network. + + The check is on the text of the host, before any DNS lookup. The downloader checks the + resolved addresses again at connect time (``public_address_adapter``), which catches a public + name that points to a private address. + """ + # "localhost." is the same host as "localhost": the trailing dot is the DNS root. + host = host.rstrip(".") + if host == "localhost" or host.endswith((".localhost", ".local", ".internal")): + return True + try: + address = ipaddress.ip_address(host) + except ValueError: + pass + else: + return not address.is_global + # Other numeric spellings (127.1, 2130706433, 0x7f.1) are not IP literals for ipaddress, but + # the system resolver reads them as one. A real host name has a letter in its last label and + # a dot, so a single label such as "intranet" (a private name) is refused too. + labels = host.split(".") + return len(labels) < 2 or _TOP_LEVEL_LABEL.fullmatch(labels[-1]) is None + + +def check_fetch_url(url: str) -> CustomLoraUrl: + """Check one URL for a request: HTTPS, a real host, no private network address. + + Used for the pasted URL (after ``resolve_custom_lora_url``) and for each redirect target. + """ + parts = urlsplit(url.strip()) + if parts.scheme != "https": + raise CustomLoraUrlError("Use an https:// link.") + host = (parts.hostname or "").lower().rstrip(".") + if not host or parts.username is not None or parts.password is not None: + raise CustomLoraUrlError("The link is not valid.") + if _host_is_local(host): + raise CustomLoraUrlError("The link points to this computer or a private network.") + return CustomLoraUrl(url=parts.geturl(), host=host) + + +def _decoded_path(path: str) -> str: + try: + return unquote(path, errors="strict") + except UnicodeDecodeError as exc: + raise CustomLoraUrlError("The link is not valid.") from exc + + +def resolve_custom_lora_url(url: str) -> CustomLoraUrl: + """Turn a pasted link into the file URL to fetch, or raise ``CustomLoraUrlError``. + + Only Hugging Face model pages and file links are supported sources. The Civitai and direct + ``.safetensors`` branches below are not a supported source (most Civitai files require a + sign-in). + """ + checked = check_fetch_url(url) + parts = urlsplit(checked.url) + decoded_path = _decoded_path(parts.path) + if checked.host in HF_HOSTS: + return _resolve_hugging_face(checked, decoded_path) + if checked.host not in CIVITAI_HOSTS: + if not decoded_path.lower().endswith(".safetensors"): + raise CustomLoraUrlError("Use a direct link to a .safetensors file.") + return checked + if _CIVITAI_DOWNLOAD_PATH.match(parts.path): + return checked + if _CIVITAI_PAGE_PATH.match(parts.path): + versions = parse_qs(parts.query).get("modelVersionId", []) + if len(versions) == 1 and versions[0].isdigit(): + return check_fetch_url(f"https://civitai.com/api/download/models/{versions[0]}") + raise CustomLoraUrlError( + "This is a Civitai page. Open the version you want, then copy the Download link " + "(civitai.com/api/download/models/...)." + ) + raise CustomLoraUrlError( + "Use a Civitai download link (civitai.com/api/download/models/...)." + ) + + +def _resolve_hugging_face(checked: CustomLoraUrl, decoded_path: str) -> CustomLoraUrl: + """A file page (``/blob/``) becomes its download link. A model page returns its repo.""" + parts = urlsplit(checked.url) + file_link = _HF_FILE_PATH.match(parts.path) + if ( + file_link + and file_link.group("owner") not in _HF_RESERVED_OWNERS + and decoded_path.lower().endswith(".safetensors") + ): + owner = file_link.group("owner") + name = file_link.group("name") + revision = file_link.group("revision") + file_part = file_link.group("file") + resolved_url = parts._replace(path=f"/{owner}/{name}/resolve/{revision}/{file_part}").geturl() + return check_fetch_url(resolved_url) + model_page = _HF_MODEL_PAGE_PATH.match(parts.path) + if model_page and model_page.group("owner") not in _HF_RESERVED_OWNERS: + repo = HuggingFaceRepo( + repo_id=f"{model_page.group('owner')}/{model_page.group('name')}", + revision=model_page.group("revision") or _HF_DEFAULT_REVISION, + ) + return CustomLoraUrl(url=checked.url, host=checked.host, repo=repo) + raise CustomLoraUrlError("Use a Hugging Face model page or a .safetensors file link.") + + +def hugging_face_repo_of(url: str) -> HuggingFaceRepo | None: + """The repo a Hugging Face link points to, or ``None`` for any other link. + + The model page lists the README (the model card). This accepts any link kind that + names a repo. It does not raise: a link without a card has nothing to suggest. + """ + parts = urlsplit(url.strip()) + if parts.scheme != "https" or (parts.hostname or "").lower() not in HF_HOSTS: + return None + match = _HF_REPO_LINK_PATH.match(parts.path) + if match is None or match.group("owner") in _HF_RESERVED_OWNERS: + return None + return HuggingFaceRepo( + repo_id=f"{match.group('owner')}/{match.group('name')}", + revision=match.group("revision") or _HF_DEFAULT_REVISION, + ) + + +def pick_hugging_face_weights(filenames: Sequence[str]) -> str: + """The one ``.safetensors`` file of a repo, or ``CustomLoraUrlError`` with what to do next. + + A repo has other files (the README, ``.gitattributes``) that are not weights. Two or more + weights files are ambiguous: a guess could load the wrong LoRA, so the user picks the file. + """ + weights = sorted(name for name in filenames if name.lower().endswith(".safetensors")) + if not weights: + raise CustomLoraUrlError( + "This Hugging Face repository has no .safetensors file. Use a repository " + "that contains a LoRA file." + ) + if len(weights) > 1: + shown = ", ".join(weights[:_MAX_LISTED_NAMES]) + more = "" if len(weights) <= _MAX_LISTED_NAMES else f" and {len(weights) - _MAX_LISTED_NAMES} more" + raise CustomLoraUrlError( + f"This Hugging Face repository has more than one .safetensors file ({shown}{more}). " + "Open the file you want and copy its link." + ) + return weights[0] + + +def page_url_for(fetch_url: str) -> str | None: + """The Hugging Face model page of a fetch URL, or ``None`` for any other host. + + The details screen links to this page only. A file the user chose from disk has no page. + """ + parts = urlsplit(fetch_url) + if (parts.hostname or "").lower() not in HF_HOSTS: + return None + match = _HF_OWNER_PATH.match(parts.path) + if match is None or match.group("owner") in _HF_RESERVED_OWNERS: + return None + return HuggingFaceRepo(repo_id=f"{match.group('owner')}/{match.group('name')}").page_url + + +def saved_source_url(fetch_url: str) -> str: + """The link to keep in ``meta.json`` so the weights can be fetched again. + + CWE-312: a pasted link can carry a secret in its query string (for example a ``?token=`` + query or a signed CDN URL). The query and fragment are dropped for every host before the + link is saved on disk. The file is found by its path. A link that needs its query to work + fails when the weights are fetched again, and the user then adds the file. + """ + return urlsplit(fetch_url)._replace(query="", fragment="").geturl() diff --git a/backend/runtime_config/custom_loras.py b/backend/runtime_config/custom_loras.py new file mode 100644 index 000000000..5ede08ee4 --- /dev/null +++ b/backend/runtime_config/custom_loras.py @@ -0,0 +1,320 @@ +"""On-disk storage for custom LoRAs (weights the user supplies as a file or a URL). + +Layout under the models dir:: + + loras/custom//.safetensors + loras/custom//meta.json + loras/custom//cover. + +```` is a slug of the name the user typed. A folder is one custom LoRA. A folder without +``meta.json`` is an unfinished import and is ignored. A folder with ``meta.json`` and no weights +is a LoRA whose weights the user deleted: it stays listed and asks for the weights again. +The ``loras`` directory also makes the file visible to the plain-LoRA scanner, so a saved +custom LoRA shows up in the GenSpace picker without extra work. +""" + +from __future__ import annotations + +import json +import os +import re +import struct +from dataclasses import dataclass +from pathlib import Path +from typing import Annotated, cast + +from pydantic import ( + BaseModel, + ConfigDict, + Field, + NonNegativeInt, + StrictInt, + TypeAdapter, + ValidationError, + field_validator, + model_validator, +) + +from api_types import ( + CustomLoraSource, + InstructionSection, + TriggerPlacement, +) +from runtime_config.models_scanner import is_ic_lora_file + +CUSTOM_LORAS_SUBDIR = Path("loras") / "custom" +META_FILENAME = "meta.json" +STAGING_DIRNAME = ".tmp" +WEIGHTS_SUFFIX = ".safetensors" +# The cover is stored under a fixed name so meta.json never points outside the LoRA folder. +COVER_MEDIA_TYPES = { + ".png": "image/png", + ".jpg": "image/jpeg", + ".jpeg": "image/jpeg", + ".webp": "image/webp", +} +COVER_FILENAMES = frozenset(f"cover{suffix}" for suffix in COVER_MEDIA_TYPES) +_NOT_SAFETENSORS = "The file is not a .safetensors file." + +# LTX LoRAs are hundreds of megabytes to a few gigabytes. The cap stops a wrong link +# (a model checkpoint, a video) from filling the disk before the header check can run. +MAX_CUSTOM_LORA_BYTES = 8 * 1024**3 + +_MAX_SLUG_LENGTH = 48 +_MAX_ID_LENGTH = 64 +_MAX_HEADER_BYTES = 16 * 1024 * 1024 +_SLUG_RE = re.compile(r"[^a-z0-9]+") +_CUSTOM_LORA_ID_RE = re.compile(r"^[a-z0-9-]+$") + +class CustomLoraFileError(ValueError): + """The file is not usable as a custom LoRA. The message is safe to show to the user.""" + + +@dataclass(frozen=True, slots=True) +class CustomLoraRecord: + id: str + name: str + filename: str + # The size of the weights. Kept in ``meta.json`` so the row shows it after the weights are deleted. + size_bytes: int + source: CustomLoraSource + # The file URL that was fetched. ``None`` for a file import: only a link can be fetched again. + source_url: str | None = None + # The Hugging Face model page, when the link pointed at Hugging Face. ``None`` otherwise. + page_url: str | None = None + downloaded: bool = True + # What the user told the prompt enhancer. A LoRA saved before this existed has no description. + trigger: str | None = None + description: str = "" + examples: tuple[str, ...] = () + # ``cover.png`` (or jpg, jpeg, webp) inside the LoRA folder. ``None`` when the user skipped it. + cover_filename: str | None = None + + @property + def ref(self) -> str: + """The weights path relative to the models dir, in the form ``resolve_lora_ref`` takes.""" + return (CUSTOM_LORAS_SUBDIR / self.id / self.filename).as_posix() + + +def custom_loras_root(models_dir: Path) -> Path: + return models_dir / CUSTOM_LORAS_SUBDIR + + +def custom_lora_dir(models_dir: Path, custom_lora_id: str) -> Path: + if not _CUSTOM_LORA_ID_RE.fullmatch(custom_lora_id) or len(custom_lora_id) > _MAX_ID_LENGTH: + raise ValueError(f"Invalid custom LoRA id: {custom_lora_id!r}") + return custom_loras_root(models_dir) / custom_lora_id + + +def slugify_name(name: str) -> str: + """The folder id for a name, or ``""`` when the name has no letters or digits.""" + slug = _SLUG_RE.sub("-", name.strip().lower()).strip("-") + return slug[:_MAX_SLUG_LENGTH].strip("-") + + +class _TensorEntry(BaseModel): + """One tensor of a safetensors header. Only the byte range matters here.""" + + model_config = ConfigDict(strict=True, extra="ignore") + + # [start, end]. A strict int refuses True and False, which are ints in Python. + data_offsets: Annotated[list[NonNegativeInt], Field(min_length=2, max_length=2)] + + @model_validator(mode="after") + def _ordered(self) -> "_TensorEntry": + if self.data_offsets[0] > self.data_offsets[1]: + raise ValueError("data_offsets are out of order") + return self + + +# A header maps tensor names to entries. ``__metadata__`` is not a tensor and is taken out first. +_HEADER = TypeAdapter(dict[str, _TensorEntry]) + + +def validate_safetensors_weights(path: Path) -> None: + """Raise ``CustomLoraFileError`` unless ``path`` is a complete plain-LoRA safetensors file. + + Reads the header only. The tensor offsets must fit inside the file, which catches a + truncated download. A file with the IC-LoRA marker is rejected: this feature runs plain + LoRAs, and an IC-LoRA needs a control video. + + The ``safetensors`` library is not used for this check: it memory-maps the whole file, and the + app patches it on purpose because of the Windows commit-charge cost of that + (``services/patches/safetensors_metadata_fix.py``). + """ + try: + file_size = path.stat().st_size + with open(path, "rb") as f: + raw_size = f.read(8) + if len(raw_size) != 8: + raise CustomLoraFileError(_NOT_SAFETENSORS) + (header_size,) = struct.unpack(" _MAX_HEADER_BYTES or 8 + header_size > file_size: + raise CustomLoraFileError(_NOT_SAFETENSORS) + header: object = json.loads(f.read(header_size).decode("utf-8")) + if not isinstance(header, dict): + raise CustomLoraFileError(_NOT_SAFETENSORS) + tensors = _HEADER.validate_python( + {name: entry for name, entry in cast("dict[str, object]", header).items() if name != "__metadata__"} + ) + except (OSError, UnicodeDecodeError, ValueError) as exc: + # json.JSONDecodeError and pydantic's ValidationError are both ValueErrors. + raise CustomLoraFileError(_NOT_SAFETENSORS) from exc + if not tensors: + raise CustomLoraFileError("The file has no weights.") + if 8 + header_size + max(t.data_offsets[1] for t in tensors.values()) > file_size: + raise CustomLoraFileError("The file is incomplete. Download it again.") + if is_ic_lora_file(path): + raise CustomLoraFileError( + "This is an IC-LoRA. Custom LoRA runs plain LoRAs only." + ) + lora_a = {k[: -len(".lora_A.weight")] for k in tensors if k.endswith(".lora_A.weight")} + lora_b = {k[: -len(".lora_B.weight")] for k in tensors if k.endswith(".lora_B.weight")} + if not (lora_a & lora_b): + raise CustomLoraFileError("The file does not contain LoRA weights.") + + +def write_meta(directory: Path, record: CustomLoraRecord) -> None: + """Write ``meta.json`` last, so a folder with a meta file is always a finished import.""" + payload: dict[str, object] = { + "name": record.name, + "filename": record.filename, + "source": record.source, + "size_bytes": record.size_bytes, + "source_url": record.source_url, + "page_url": record.page_url, + "trigger": record.trigger, + "description": record.description, + "examples": list(record.examples), + "cover_filename": record.cover_filename, + } + tmp = directory / f"{META_FILENAME}.part" + tmp.write_text(json.dumps(payload), encoding="utf-8") + os.replace(tmp, directory / META_FILENAME) + + +class _Meta(BaseModel): + """The shape of ``meta.json``. A file that does not fit is treated as no LoRA.""" + + model_config = ConfigDict(strict=True, extra="ignore") + + name: str + filename: str + source: CustomLoraSource + size_bytes: StrictInt = 0 + source_url: str | None = None + page_url: str | None = None + trigger: str | None = None + description: str = "" + examples: list[str] = Field(default_factory=list[str]) + cover_filename: str | None = None + + @field_validator("source_url", "page_url", "trigger") + @classmethod + def _empty_is_none(cls, value: str | None) -> str | None: + return value or None + + @field_validator("filename") + @classmethod + def _bare_name(cls, value: str) -> str: + # The filename comes from a file on disk: keep it a bare name so the ref stays inside the folder. + if Path(value).name != value: + raise ValueError("filename must be a bare name") + return value + + @field_validator("cover_filename") + @classmethod + def _cover_name(cls, value: str | None) -> str | None: + # A bad name is no cover. It must not hide the rest of the LoRA. + if not value or value not in COVER_FILENAMES: + return None + return value + + +def read_custom_lora(models_dir: Path, custom_lora_id: str) -> CustomLoraRecord | None: + """The saved LoRA, or ``None`` when its folder or its meta file is missing or unreadable. + + A LoRA whose weights are gone is still returned, with ``downloaded=False``. + """ + try: + directory = custom_lora_dir(models_dir, custom_lora_id) + meta = _Meta.model_validate_json((directory / META_FILENAME).read_bytes()) + except (OSError, ValidationError, ValueError): + return None + size = meta.size_bytes + downloaded = False + try: + size = (directory / meta.filename).stat().st_size + downloaded = True + except OSError: + pass + return CustomLoraRecord( + id=custom_lora_id, + name=meta.name, + filename=meta.filename, + size_bytes=size, + source=meta.source, + source_url=meta.source_url, + page_url=meta.page_url, + downloaded=downloaded, + trigger=meta.trigger, + description=meta.description, + examples=tuple(meta.examples), + cover_filename=meta.cover_filename, + ) + + +def custom_lora_cover_path(models_dir: Path, record: CustomLoraRecord) -> Path | None: + """The cover file inside the LoRA folder, or ``None`` when there is no cover. + + The filename is a fixed bare name. A path that resolves outside the folder is ignored. + """ + if record.cover_filename is None: + return None + directory = custom_lora_dir(models_dir, record.id).resolve() + path = (directory / record.cover_filename).resolve() + if path.parent != directory or not path.is_file(): + return None + return path + + +@dataclass(frozen=True, slots=True) +class CustomLoraPromptGuidance: + name: str + instructions: tuple[InstructionSection, ...] + trigger: str | None + trigger_placement: TriggerPlacement | None + enhancement_examples: tuple[str, ...] + + +def custom_lora_prompt_guidance(record: CustomLoraRecord) -> CustomLoraPromptGuidance: + """The prompt-enhancer guidance for a saved custom LoRA. + + Uses a generic heading instead of the user's label so the enhancer does not write the + arbitrary label into the prompt text. + """ + return CustomLoraPromptGuidance( + name="Selected LoRA", + instructions=( + (InstructionSection(kind="summary", title="What it does", body=record.description),) + if record.description + else () + ), + trigger=record.trigger, + trigger_placement="anywhere" if record.trigger else None, + enhancement_examples=record.examples, + ) + + +def list_custom_loras(models_dir: Path) -> list[CustomLoraRecord]: + root = custom_loras_root(models_dir) + if not root.is_dir(): + return [] + records: list[CustomLoraRecord] = [] + for entry in sorted(root.iterdir(), key=lambda p: p.name): + if not entry.is_dir() or entry.name == STAGING_DIRNAME: + continue + record = read_custom_lora(models_dir, entry.name) + if record is not None: + records.append(record) + return records diff --git a/backend/runtime_config/device_calibration.py b/backend/runtime_config/device_calibration.py new file mode 100644 index 000000000..1eabc50cc --- /dev/null +++ b/backend/runtime_config/device_calibration.py @@ -0,0 +1,211 @@ +"""What this device has already run cleanly, and whether a finished run counts. + +A clean run of shape (seq, canvas_px, windows) proves every job in the same +bucket whose three numbers are all at or under the run's. Two runs do not +prove the box they span (a long 1080p clip and a short 4K clip say nothing +about a long 4K clip), so each bucket keeps its individual run points and +drops only the points another point covers: a Pareto frontier. +""" + +from __future__ import annotations + +from collections.abc import Mapping +from dataclasses import dataclass, field +from typing import Final, Literal + +from runtime_config.budget_decision import LoadMode +from runtime_config.budget_evidence import JobShape +from runtime_config.measured_cells import BudgetFeature + +# Bump with ltx-core / ltx-pipelines or a law refit: old proofs stop counting. +CALIBRATION_EPOCH: Final = 2 +# Unmeasured (D7): the 1080p retake ladder ran clean about 1.3 GiB under free +# and paged about 0.4 GiB over, so the line sits between them. +PAGING_MARGIN_BYTES: Final = 1 * 1024**3 +MIN_FREE_FLOOR_BYTES: Final = 512 * 1024**2 +SWAP_GROWTH_TOLERANCE_BYTES: Final = 256 * 1024**2 + +CalibrationSystem = Literal["Windows", "Linux", "Darwin"] + + +@dataclass(frozen=True, slots=True) +class DeviceIdentity: + system: CalibrationSystem + gpu_model: str + # CUDA VRAM bytes; total RAM on Darwin (unified memory). + total_memory_bytes: int + + +@dataclass(frozen=True, slots=True) +class CalibrationBucket: + model_id: str + feature: BudgetFeature + adapter_id: str + stage_mode: str + load_mode: LoadMode + tiled: bool + chunked: bool + + +@dataclass(frozen=True, slots=True) +class EnvelopePoint: + seq: float + canvas_px: int + windows: int + tiles: int = field(default=1, compare=False) + + def within(self, other: EnvelopePoint) -> bool: + """Every axis at or under ``other``'s, so an equal re-run is covered.""" + return ( + self.seq <= other.seq + and self.canvas_px <= other.canvas_px + and self.windows <= other.windows + ) + + +@dataclass(frozen=True, slots=True) +class JobEnvelope: + bucket: CalibrationBucket + point: EnvelopePoint + priced_gib: float + + +@dataclass(frozen=True, slots=True) +class FrontierPoint: + point: EnvelopePoint + # Reserved growth over the run; None on Darwin, which has no peak probe. + peak_growth_bytes: int | None + wall_s: float | None = field(default=None, compare=False) + + +@dataclass(frozen=True, slots=True) +class DeviceCalibration: + identity: DeviceIdentity | None + frontier: Mapping[CalibrationBucket, tuple[FrontierPoint, ...]] + machine_factor: float | None = None + + def covering(self, envelope: JobEnvelope) -> FrontierPoint | None: + """A stored point the job is within, preferring the smallest measured growth.""" + covering = [ + stored + for stored in self.frontier.get(envelope.bucket, ()) + if envelope.point.within(stored.point) + ] + if not covering: + return None + return min( + covering, + key=lambda stored: ( + stored.peak_growth_bytes is None, + stored.peak_growth_bytes or 0, + ), + ) + + def with_frontier( + self, + bucket: CalibrationBucket, + points: tuple[FrontierPoint, ...], + *, + machine_factor: float | None = None, + ) -> DeviceCalibration: + return DeviceCalibration( + identity=self.identity, + frontier={**self.frontier, bucket: points}, + machine_factor=self.machine_factor if machine_factor is None else machine_factor, + ) + + def with_machine_factor(self, machine_factor: float | None) -> DeviceCalibration: + return DeviceCalibration( + identity=self.identity, + frontier=self.frontier, + machine_factor=machine_factor, + ) + + +EMPTY_CALIBRATION: Final = DeviceCalibration(identity=None, frontier={}) + + +def merge_frontier( + points: tuple[FrontierPoint, ...], new: FrontierPoint +) -> tuple[FrontierPoint, ...] | None: + """None when ``new`` is within a stored point. Else ``new`` plus the points not within it.""" + if any(new.point.within(stored.point) for stored in points): + return None + return (new, *(stored for stored in points if not stored.point.within(new.point))) + + +def envelope_for(shape: JobShape, load_mode: LoadMode, priced_gib: float) -> JobEnvelope: + return JobEnvelope( + bucket=CalibrationBucket( + model_id=shape.model_id, + feature=shape.feature, + adapter_id=shape.adapter_id, + stage_mode=shape.stage_mode, + load_mode=load_mode, + tiled=shape.tiled, + chunked=shape.chunked, + ), + point=EnvelopePoint( + seq=shape.seq, + canvas_px=shape.canvas_px, + windows=shape.windows, + tiles=shape.tiles, + ), + priced_gib=priced_gib, + ) + + +@dataclass(frozen=True, slots=True) +class RunMemoryBaseline: + free_vram_bytes: int | None + reserved_bytes: int | None + swap_used_bytes: int | None + + +@dataclass(frozen=True, slots=True) +class RunMemoryEnd: + peak_reserved_bytes: int | None + min_free_vram_bytes: int | None + swap_used_bytes: int | None + + +CleanVerdict = Literal["clean", "vram_growth", "free_floor", "swap_growth", "no_evidence"] + + +def clean_run_verdict( + identity: DeviceIdentity, baseline: RunMemoryBaseline, end: RunMemoryEnd +) -> CleanVerdict: + """Did this run have room? A missing probe fails closed as ``no_evidence``. + + CUDA: reserved growth stays under start-free minus the paging margin, + free never hits the floor (another app growing mid-run), and host swap + does not grow when swap readings are present (catches CPU-offload pagefile + thrashing while treating missing swap probes as clean). Darwin: swap did + not grow, which on unified memory is the only signal. + """ + if identity.system != "Darwin": + growth = peak_growth_bytes(baseline, end) + if growth is None or baseline.free_vram_bytes is None or end.min_free_vram_bytes is None: + return "no_evidence" + if growth > baseline.free_vram_bytes - PAGING_MARGIN_BYTES: + return "vram_growth" + if end.min_free_vram_bytes < MIN_FREE_FLOOR_BYTES: + return "free_floor" + if ( + baseline.swap_used_bytes is not None + and end.swap_used_bytes is not None + and end.swap_used_bytes - baseline.swap_used_bytes > SWAP_GROWTH_TOLERANCE_BYTES + ): + return "swap_growth" + return "clean" + if baseline.swap_used_bytes is None or end.swap_used_bytes is None: + return "no_evidence" + if end.swap_used_bytes - baseline.swap_used_bytes > SWAP_GROWTH_TOLERANCE_BYTES: + return "swap_growth" + return "clean" + + +def peak_growth_bytes(baseline: RunMemoryBaseline, end: RunMemoryEnd) -> int | None: + if baseline.reserved_bytes is None or end.peak_reserved_bytes is None: + return None + return max(0, end.peak_reserved_bytes - baseline.reserved_bytes) diff --git a/backend/runtime_config/eta.py b/backend/runtime_config/eta.py index 43a7196da..65d51c72e 100644 --- a/backend/runtime_config/eta.py +++ b/backend/runtime_config/eta.py @@ -1,34 +1,89 @@ -"""Whole-run wall-time estimates for local Fast video (ETA v1). +"""Whole-run and 3-part wall-time estimates for local video generation (ETA). -Reference table measured on one Windows 11 / RTX 5090 / 63.45 GiB RAM box: -cold whole runs (prompt processing through media encoding) plus the -same-session CPU-vs-DISK control behind the DISK column. Scope is -deliberately narrow: +Reference table and 3-part stage law (load + denoise + decode) measured on: +- Windows 11 / RTX 5090 / 63.45 GiB RAM (Fast, Edit, IC-LoRA, 540p to 4K) +- macOS / Apple M5 Max / 128 GB unified memory (Fast, Edit, IC-LoRA, 540p to 4K) +- macOS / Apple M3 Max / 36 GB unified memory (270p to 720p Fast, Custom LoRA, IC-LoRA) -- exact (width, height, frames) match only — no token interpolation; -- cold column (first-run experience); -- measured hardware class only (``is_measured_hardware_class``); -- I2V/A2V reuse T2V numbers flagged ``t2v_reuse`` (memory-equivalent, - timing-unmeasured). +Exact measured cells return their recorded seconds with ``basis="measured"``. +Other shapes use the 3-part stage law (`estimate_stage_breakdown_s`): +1. ``load_s``: cold pipeline + text encoding (fixed per platform/mode) plus + any input-video VAE encoding (`source_frames`). +2. ``denoise_s``: per-step weight streaming (fixed per step) plus GPU token + compute across stage-1 and stage-2 steps, summed over temporal windows and + multiplied by spatial tiles. +3. ``decode_s``: VAE decoding and media encoding proportional to output latent + tokens across windows. + +``machine_factor`` is this computer's speed relative to the platform reference. +On CUDA streaming it scales the per-step weight streaming. Transfer overlaps +compute and bounds each step, so GPU compute, load, and decode stay at the +reference. A 32 GiB-RAM machine on DISK offload cannot page-cache the +transformer and pays ~26 s/step where the reference pays ~6.6 s/step, whatever +the token count. Full-load CUDA and Mac scale the GPU terms. +Evidence: Windows 11 / RTX 4090 / 32 GiB RAM, DISK offload, Fast 270p-1440p +and 24-48 fps: every 1-stage run 229-238 s and every 2-stage run 309-334 s +(26.0-26.9 s/step); scaling only GPU compute clamped the factor at 8.0 and +left ETAs 34-64% short. Unknown anything -> None. An ETA that says unknown beats one that lies. -``machine_factor`` is the calibration-probe seam: 1.0 is the measured class, -None is an uncalibrated machine. Whether one scalar transfers is exactly what -the clock-cap validation phase is for — this module does not assert it. -Per-stage decomposition is out: capture stage timers do not reconcile with -wall, so the table stays whole-run. -Re-measure rather than trust. """ from __future__ import annotations -from dataclasses import dataclass -from typing import Literal, assert_never +import statistics +from collections.abc import Sequence +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, Literal + +from runtime_config.fast_chunking import ( + CARRY_FRAMES, + is_chunked_canvas, + last_window_frames, + window_candidates, + window_count, +) +from runtime_config.ic_lora_tiling import IcLoraTiling + +if TYPE_CHECKING: + from runtime_config.budget_evidence import JobShape + from runtime_config.device_calibration import CalibrationBucket, EnvelopePoint, JobEnvelope EtaBasis = Literal["measured", "scaled"] EtaFeature = Literal["t2v", "i2v", "a2v"] EtaLoadMode = Literal["full_models_loading", "streaming_models_loading"] EtaOffloadMode = Literal["NONE", "CPU", "DISK"] +EtaSystem = Literal["Windows", "Linux", "Darwin"] + +_STAGE_1_STEPS = 8 +_STAGE_2_STEPS = 3 +_HALF_RES_REF_IC_LORAS = frozenset({"video-guide", "motion-track"}) +# Bounds on stored shapes. A tampered row must not size a huge window list (CWE-770). +_MAX_FRAMES = 100_000 +_MAX_WINDOWS = 1_000 +_MIN_MACHINE_FACTOR = 0.25 +_MAX_MACHINE_FACTOR = 8.0 +# CUDA decode term is a DiffVAE rate. ConvVAE (Settings -> Fast decode) decodes the same latents +# at about 0.31x of it. +# Evidence: Windows 11 / RTX 4090, 2026-11-08 ETA matrix: ConvVAE decode / reference term +# median 0.31 (0.22-0.39) over 18 Fast runs 360p-1440p; DiffVAE 540p/720p 5s at 1.12x/1.22x. +_CONV_VAE_DECODE_RATIO = 0.31 + + +def _latent_tokens(height: int, width: int, frames: int) -> float: + return ((max(1, frames) - 1) / 8.0 + 1.0) * (height / 32.0) * (width / 32.0) + + +@dataclass(frozen=True, slots=True) +class WallTimeBreakdown: + load_s: int + denoise_s: int + decode_s: int + stage_1_share: float | None = field(default=None, compare=False) + + @property + def seconds(self) -> int: + return self.load_s + self.denoise_s + self.decode_s @dataclass(frozen=True, slots=True) @@ -36,6 +91,10 @@ class WallTimeEstimate: seconds: int basis: EtaBasis t2v_reuse: bool + load_s: int = field(default=0, compare=False) + denoise_s: int = field(default=0, compare=False) + decode_s: int = field(default=0, compare=False) + stage_1_share: float | None = field(default=None, compare=False) @dataclass(frozen=True, slots=True) @@ -46,26 +105,40 @@ class _Cell: disk_ratio_measured: bool -# Mean of the measured same-session DISK/CPU ratios. Applied only -# where no direct DISK measurement exists, and labelled "scaled" there. -_DEFAULT_DISK_RATIO = 0.8 +# Mean of the measured 1.6.0 same-session DISK/CPU ratios across F1 and F2 +# cold+warm. Applied only where no direct 1.6.0 DISK measurement exists, and +# labelled "scaled" there. +_DEFAULT_DISK_RATIO = 1.07 # (width, height, frames) at 24 fps. 720p/20s and 1080p/10s never full-load, # so their full column is None rather than a guess. Keys are fps-agnostic: a # same-frames job at another rate (5s@25fps is 121f like 5s@24fps) matches the -# same key wherever its (w, h) is listed — no new cells needed there. New -# ratios change (w, h) and need calibration; unlisted stays None. +# same key wherever its (w, h) is listed — no new cells needed there. _TABLE: dict[tuple[int, int, int], _Cell] = { - (1024, 576, 121): _Cell(121, 158, 0.87, True), + (1024, 576, 121): _Cell(121, 158, _DEFAULT_DISK_RATIO, False), (1024, 576, 481): _Cell(206, 222, _DEFAULT_DISK_RATIO, False), - (1280, 704, 481): _Cell(None, 280, 0.81, True), + (1280, 704, 481): _Cell(None, 280, 1.06, True), (1920, 1088, 121): _Cell(215, 232, _DEFAULT_DISK_RATIO, False), - (1920, 1088, 241): _Cell(None, 338, _DEFAULT_DISK_RATIO, False), + (1920, 1088, 241): _Cell(None, 338, 1.10, True), # 4K runs in windows and never full-loads. Both cells come from one run each. (3840, 2176, 73): _Cell(None, 416, _DEFAULT_DISK_RATIO, False), (3840, 2176, 241): _Cell(None, 1537, _DEFAULT_DISK_RATIO, False), } +# Mac M5 Max measured Fast cells (streaming DISK). +_MAC_TABLE: dict[tuple[int, int, int], int] = { + (1024, 576, 121): 177, + (1280, 704, 241): 512, + (1920, 1088, 121): 733, + (1024, 576, 481): 866, + (1280, 704, 481): 1450, + (1920, 1088, 241): 1739, + (2560, 1472, 241): 3528, + (2560, 1472, 481): 7222, + (3840, 2176, 73): 2508, + (3840, 2176, 241): 10154, +} + def is_measured_hardware_class(device_name: str | None) -> bool: """Desktop RTX 5090 class. A substring, deliberately: driver string @@ -78,6 +151,627 @@ def is_measured_hardware_class(device_name: str | None) -> bool: return "5090" in lowered and "laptop" not in lowered +def default_machine_factor(device_name: str | None) -> float | None: + """Baseline compute factor relative to the platform reference (5090 on CUDA, M5 Max on Mac). + + Stage 2 device calibration overrides this with the machine's measured factor. + """ + if not device_name: + return None + if is_measured_hardware_class(device_name): + return 1.0 + lowered = device_name.lower() + if "apple m5 max" in lowered: + return 1.0 + if "apple m4 max" in lowered: + return 1.35 + if "apple m3 max" in lowered: + return 2.0 + if "apple m4 pro" in lowered: + return 3.5 + if "apple m2 max" in lowered or "apple m3 pro" in lowered: + return 2.4 + if "apple m1 max" in lowered or "apple m2 pro" in lowered: + return 2.8 + return None + + +def _window_frames_list( + width: int, + height: int, + frames: int, + chunk_pixel_frames: int | None, + carry_frames: int = CARRY_FRAMES, +) -> list[int]: + win = chunk_pixel_frames + if win is None and is_chunked_canvas(width, height): + candidates = window_candidates(width, height) + if candidates and frames > candidates[0]: + win = candidates[0] + if win is None or frames <= win: + return [frames] + count = window_count(frames, win, carry_frames) + last = last_window_frames(frames, win, carry_frames) + return [win] * (count - 1) + [last] + + +_LATENT_PX = 32 + + +def _axis_tile_count(size: int, tile_size: int, overlap_fraction: float) -> int: + """Tiles on one axis, as upstream ``split_by_size_pinned`` lays them out. + + Upstream works in 32 px latent cells. The overlap is a minimum: the count grows until it is + met, capped so that no cell is covered by three tiles. The cap binds first at high overlap, + so the count stops growing once the overlap is high enough. + """ + if size <= tile_size: + return 1 + dim = size // _LATENT_PX + tile = tile_size // _LATENT_PX + min_overlap = int(tile_size * overlap_fraction) // _LATENT_PX + limit = max(2, 1 + (dim - tile) // ((tile + 1) // 2)) + count = 2 + while count < limit and (count * tile - dim) / (count - 1) < min_overlap: + count += 1 + return count + + +def spatial_tile_count(stage_width: int, stage_height: int, tiling: IcLoraTiling | None) -> int: + """Number of sequential spatial tiles per step on a stage canvas.""" + if tiling is None: + return 1 + tw, th = tiling.tile_size(stage_width, stage_height) + return _axis_tile_count(stage_width, tw, tiling.overlap_fraction) * _axis_tile_count( + stage_height, th, tiling.overlap_fraction + ) + + +def _ic_lora_ref_multiplier(ic_lora_id: str | None) -> float: + return 1.25 if ic_lora_id in _HALF_RES_REF_IC_LORAS else 2.0 + + +def _stage_time_parts( + *, + system: EtaSystem, + load_mode: EtaLoadMode, + offload_mode: EtaOffloadMode, + window_tokens: Sequence[tuple[float, float, float]], + src_tokens: float, + stage_2: bool, + tiles: int, + conv_vae: bool = False, +) -> tuple[float, float, float, float, float]: + """Return ``(fixed_load_s, gpu_src_s, fixed_denoise_s, gpu_denoise_s, gpu_decode_s)`` at factor 1.0. + + Each entry in ``window_tokens`` is ``(seq1, seq2, out_tok)`` for one temporal window. + """ + steps = _STAGE_1_STEPS + (_STAGE_2_STEPS if stage_2 else 0) + windows = len(window_tokens) + if system == "Darwin": + # Streaming starts during denoise, so this load is text encode only. + # A weight-load constant here makes every short clip late and pins + # machine_factor to the floor. 1-stage decode is the half-res ConvVAE + # pass; 2-stage decode walks the full canvas. One rate for both + # overshoots 270p and misses 540p and above. + fixed_load = 4.0 + gpu_src = 0.0040 * src_tokens + fixed_denoise = windows * tiles * (0.6 * steps) + gpu_denoise = 0.0 + gpu_decode = 0.0 + decode_per_token = 0.0095 if stage_2 else 0.0065 + for seq1, seq2, out_tok in window_tokens: + win_den = _STAGE_1_STEPS * (0.0018 * seq1 + 3.6e-8 * (seq1**2)) + if stage_2: + win_den += _STAGE_2_STEPS * (0.0018 * seq2 + 3.6e-8 * (seq2**2)) + gpu_denoise += tiles * win_den + gpu_decode += decode_per_token * out_tok + 2.5e-8 * (out_tok**2) + return fixed_load, gpu_src, fixed_denoise, gpu_denoise, gpu_decode + + fixed_load = 30.0 if offload_mode == "DISK" else 36.0 + gpu_src = 0.0004 * src_tokens + if load_mode == "full_models_loading": + step_stream_s = 5.0 + c_step_tok = 0.00025 + elif offload_mode == "CPU": + step_stream_s = 8.0 + c_step_tok = 0.00025 + else: + step_stream_s = 6.2 * _DEFAULT_DISK_RATIO + c_step_tok = 0.00010 * _DEFAULT_DISK_RATIO + fixed_denoise = windows * tiles * (step_stream_s * steps) + gpu_denoise = 0.0 + gpu_decode = 0.0 + decode_per_token = 0.00145 * (_CONV_VAE_DECODE_RATIO if conv_vae else 1.0) + for seq1, seq2, out_tok in window_tokens: + win_den = _STAGE_1_STEPS * (c_step_tok * seq1) + if stage_2: + win_den += _STAGE_2_STEPS * (c_step_tok * seq2) + gpu_denoise += tiles * win_den + gpu_decode += decode_per_token * out_tok + return fixed_load, gpu_src, fixed_denoise, gpu_denoise, gpu_decode + + +_StageParts = tuple[float, float, float, float, float] + + +def _scales_weight_streaming(system: EtaSystem, load_mode: EtaLoadMode) -> bool: + """CUDA streaming: per-step weight transfer bounds the step and hides GPU compute under it.""" + return system != "Darwin" and load_mode == "streaming_models_loading" + + +def _stage_1_denoise_share( + *, + system: EtaSystem, + load_mode: EtaLoadMode, + parts: _StageParts, + window_tokens: Sequence[tuple[float, float, float]], + stage_2: bool, + tiles: int, + machine_factor: float, +) -> float | None: + """Fraction of a window's denoise cost spent in the 8 stage-1 steps (or None if 1-stage).""" + if not stage_2: + return None + _fixed_load, _gpu_src, fixed_denoise, gpu_denoise, _gpu_decode = parts + steps = _STAGE_1_STEPS + _STAGE_2_STEPS + fixed_s1_ratio = _STAGE_1_STEPS / steps + if system == "Darwin": + gpu_s1 = sum( + tiles * _STAGE_1_STEPS * (0.0018 * seq1 + 3.6e-8 * (seq1**2)) + for seq1, _seq2, _out in window_tokens + ) + else: + gpu_total_tok = sum(_STAGE_1_STEPS * seq1 + _STAGE_2_STEPS * seq2 for seq1, seq2, _ in window_tokens) + gpu_s1 = ( + gpu_denoise * sum(_STAGE_1_STEPS * seq1 for seq1, _, _ in window_tokens) / gpu_total_tok + if gpu_total_tok > 0 + else gpu_denoise * fixed_s1_ratio + ) + if _scales_weight_streaming(system, load_mode): + s1 = machine_factor * fixed_denoise * fixed_s1_ratio + gpu_s1 + total = machine_factor * fixed_denoise + gpu_denoise + else: + s1 = fixed_denoise * fixed_s1_ratio + machine_factor * gpu_s1 + total = fixed_denoise + machine_factor * gpu_denoise + return round(s1 / total, 4) if total > 0 else fixed_s1_ratio + + +def _compose_stages( + system: EtaSystem, load_mode: EtaLoadMode, parts: _StageParts, machine_factor: float +) -> tuple[int, int, int]: + """Apply ``machine_factor`` to the reference parts and return ``(load_s, denoise_s, decode_s)``. + + CUDA streaming scales the per-step weight streaming and keeps GPU compute and decode at + the reference. Everything else scales the GPU terms. + """ + fixed_load, gpu_src, fixed_denoise, gpu_denoise, gpu_decode = parts + load = fixed_load + machine_factor * gpu_src + if _scales_weight_streaming(system, load_mode): + denoise = machine_factor * fixed_denoise + gpu_denoise + decode = gpu_decode + else: + denoise = fixed_denoise + machine_factor * gpu_denoise + decode = machine_factor * gpu_decode + return max(1, round(load)), max(1, round(denoise)), max(1, round(decode)) + + +def _implied_factor( + system: EtaSystem, + load_mode: EtaLoadMode, + parts: _StageParts, + wall_s: float, + *, + reject_clamped: bool = False, +) -> float | None: + """Invert `_compose_stages`: the factor that makes the parts sum to ``wall_s``.""" + fixed_load, gpu_src, fixed_denoise, gpu_denoise, gpu_decode = parts + if _scales_weight_streaming(system, load_mode): + fixed_s = fixed_load + gpu_denoise + gpu_decode + scaled_s = gpu_src + fixed_denoise + else: + fixed_s = fixed_load + fixed_denoise + scaled_s = gpu_src + gpu_denoise + gpu_decode + if scaled_s <= 1.0: + return None + raw = max(1.0, wall_s - fixed_s) / scaled_s + if reject_clamped and not (_MIN_MACHINE_FACTOR < raw < _MAX_MACHINE_FACTOR): + return None + return max(_MIN_MACHINE_FACTOR, min(_MAX_MACHINE_FACTOR, raw)) + + +def estimate_stage_breakdown_s( + *, + width: int, + height: int, + frames: int, + load_mode: EtaLoadMode, + offload_mode: EtaOffloadMode, + system: EtaSystem = "Windows", + machine_factor: float | None = 1.0, + stage_2: bool = True, + ic_lora: bool = False, + ic_lora_id: str | None = None, + stage_2_ic_lora: bool = False, + source_frames: int = 0, + chunk_pixel_frames: int | None = None, + carry_frames: int = CARRY_FRAMES, + tiling: IcLoraTiling | None = None, + conv_vae: bool = False, +) -> WallTimeBreakdown | None: + """Three-part wall-time breakdown (load_s, denoise_s, decode_s) for any local video job.""" + if machine_factor is None or machine_factor <= 0 or width <= 0 or height <= 0: + return None + if not 0 < frames <= _MAX_FRAMES: + return None + if load_mode == "full_models_loading" and offload_mode != "NONE": + return None + if load_mode == "streaming_models_loading" and offload_mode == "NONE": + return None + if system == "Darwin" and (load_mode != "streaming_models_loading" or offload_mode != "DISK"): + return None + + win_list = _window_frames_list(width, height, frames, chunk_pixel_frames, carry_frames) + s1_w = width // 2 if stage_2 else width + s1_h = height // 2 if stage_2 else height + tiles = spatial_tile_count(s1_w, s1_h, tiling) + pass_s1_w, pass_s1_h = tiling.tile_size(s1_w, s1_h) if tiling is not None else (s1_w, s1_h) + src_tokens = _latent_tokens(height, width, source_frames) if source_frames > 0 else 0.0 + ref_mult = _ic_lora_ref_multiplier(ic_lora_id) + + window_tokens = [ + ( + ref_mult * _latent_tokens(pass_s1_h, pass_s1_w, wf) + if ic_lora + else _latent_tokens(pass_s1_h, pass_s1_w, wf), + ( + ref_mult * _latent_tokens(height, width, wf) + if stage_2_ic_lora + else _latent_tokens(height, width, wf) + ) + if stage_2 + else 0.0, + _latent_tokens(height, width, wf), + ) + for wf in win_list + ] + parts = _stage_time_parts( + system=system, + load_mode=load_mode, + offload_mode=offload_mode, + window_tokens=window_tokens, + src_tokens=src_tokens, + stage_2=stage_2, + tiles=tiles, + conv_vae=conv_vae, + ) + load_s, denoise_s, decode_s = _compose_stages(system, load_mode, parts, machine_factor) + s1_share = _stage_1_denoise_share( + system=system, + load_mode=load_mode, + parts=parts, + window_tokens=window_tokens, + stage_2=stage_2, + tiles=tiles, + machine_factor=machine_factor, + ) + return WallTimeBreakdown( + load_s=load_s, denoise_s=denoise_s, decode_s=decode_s, stage_1_share=s1_share + ) + + +def implied_machine_factor( + *, + wall_s: float, + width: int, + height: int, + frames: int, + load_mode: EtaLoadMode = "streaming_models_loading", + offload_mode: EtaOffloadMode = "DISK", + system: EtaSystem = "Windows", + stage_2: bool = True, + ic_lora: bool = False, + ic_lora_id: str | None = None, + stage_2_ic_lora: bool = False, + source_frames: int = 0, + chunk_pixel_frames: int | None = None, + carry_frames: int = CARRY_FRAMES, + tiling: IcLoraTiling | None = None, + conv_vae: bool = False, + reject_clamped: bool = False, +) -> float | None: + """Derive this computer's GPU compute factor from one completed run's wall time.""" + if wall_s <= 0 or width <= 0 or height <= 0 or not 0 < frames <= _MAX_FRAMES: + return None + win_list = _window_frames_list(width, height, frames, chunk_pixel_frames, carry_frames) + s1_w = width // 2 if stage_2 else width + s1_h = height // 2 if stage_2 else height + tiles = spatial_tile_count(s1_w, s1_h, tiling) + pass_s1_w, pass_s1_h = tiling.tile_size(s1_w, s1_h) if tiling is not None else (s1_w, s1_h) + src_tokens = _latent_tokens(height, width, source_frames) if source_frames > 0 else 0.0 + ref_mult = _ic_lora_ref_multiplier(ic_lora_id) + window_tokens = [ + ( + ref_mult * _latent_tokens(pass_s1_h, pass_s1_w, wf) + if ic_lora + else _latent_tokens(pass_s1_h, pass_s1_w, wf), + ( + ref_mult * _latent_tokens(height, width, wf) + if stage_2_ic_lora + else _latent_tokens(height, width, wf) + ) + if stage_2 + else 0.0, + _latent_tokens(height, width, wf), + ) + for wf in win_list + ] + parts = _stage_time_parts( + system=system, + load_mode=load_mode, + offload_mode=offload_mode, + window_tokens=window_tokens, + src_tokens=src_tokens, + stage_2=stage_2, + tiles=tiles, + conv_vae=conv_vae, + ) + return _implied_factor(system, load_mode, parts, wall_s, reject_clamped=reject_clamped) + + +def _envelope_tokens( + *, + feature: str, + adapter_id: str, + stage_mode: str, + seq: float, + canvas_px: int, + windows: int, +) -> tuple[list[tuple[float, float, float]], float, bool]: + ic_lora = feature == "iclora" + stage_2 = stage_mode != "single_stage" and (feature != "fast" or canvas_px > 640 * 368) + stage_2_ic_lora = stage_mode == "stage_2_lora" + ref_mult = _ic_lora_ref_multiplier(adapter_id or None) + if ic_lora and (stage_mode == "single_stage" or stage_2_ic_lora): + out_tok = seq / ref_mult + else: + out_tok = seq + s1_tok = out_tok / 4.0 if stage_2 else out_tok + seq1 = ref_mult * s1_tok if ic_lora else s1_tok + seq2 = (ref_mult * out_tok if stage_2_ic_lora else out_tok) if stage_2 else 0.0 + src_tokens = out_tok * windows if feature in ("edit", "iclora") else 0.0 + return [(seq1, seq2, out_tok)] * windows, src_tokens, stage_2 + + +def estimate_job_shape_seconds( + shape: JobShape, + load_mode: EtaLoadMode, + *, + system: EtaSystem = "Windows", + machine_factor: float | None = 1.0, + offload_mode: EtaOffloadMode | None = None, + conv_vae: bool = False, +) -> int | None: + """Whole-run estimated seconds from a priced ``JobShape``.""" + if machine_factor is None or machine_factor <= 0 or shape.seq <= 0 or shape.canvas_px <= 0 or not 1 <= shape.windows <= _MAX_WINDOWS: + return None + resolved_offload: EtaOffloadMode = ( + offload_mode + if offload_mode is not None + else ("NONE" if load_mode == "full_models_loading" else "DISK") + ) + window_tokens, src_tokens, stage_2 = _envelope_tokens( + feature=shape.feature, + adapter_id=shape.adapter_id, + stage_mode=shape.stage_mode, + seq=shape.seq, + canvas_px=shape.canvas_px, + windows=shape.windows, + ) + tiles = max(1, shape.tiles) if shape.tiled else 1 + parts = _stage_time_parts( + system=system, + load_mode=load_mode, + offload_mode=resolved_offload, + window_tokens=window_tokens, + src_tokens=src_tokens, + stage_2=stage_2, + tiles=tiles, + conv_vae=conv_vae, + ) + return sum(_compose_stages(system, load_mode, parts, machine_factor)) + + +def implied_envelope_factor( + system: EtaSystem, + bucket: CalibrationBucket, + point: EnvelopePoint, + wall_s: float | None, + *, + offload_mode: EtaOffloadMode | None = None, + conv_vae: bool = False, + reject_clamped: bool = False, +) -> float | None: + """Derive ``machine_factor`` from a recorded calibration frontier point.""" + if wall_s is None or wall_s <= 0 or point.seq <= 0 or point.canvas_px <= 0 or not 1 <= point.windows <= _MAX_WINDOWS: + return None + resolved_offload: EtaOffloadMode = ( + offload_mode + if offload_mode is not None + else ("NONE" if bucket.load_mode == "full_models_loading" else "DISK") + ) + window_tokens, src_tokens, stage_2 = _envelope_tokens( + feature=bucket.feature, + adapter_id=bucket.adapter_id, + stage_mode=bucket.stage_mode, + seq=point.seq, + canvas_px=point.canvas_px, + windows=point.windows, + ) + tiles = max(1, point.tiles) if bucket.tiled else 1 + parts = _stage_time_parts( + system=system, + load_mode=bucket.load_mode, + offload_mode=resolved_offload, + window_tokens=window_tokens, + src_tokens=src_tokens, + stage_2=stage_2, + tiles=tiles, + conv_vae=conv_vae, + ) + return _implied_factor(system, bucket.load_mode, parts, wall_s, reject_clamped=reject_clamped) + + +def estimate_envelope_wall_time( + envelope: JobEnvelope, + *, + system: EtaSystem = "Windows", + machine_factor: float | None = 1.0, + offload_mode: EtaOffloadMode | None = None, + conv_vae: bool = False, +) -> WallTimeEstimate | None: + """Three-part wall-time estimate from a priced ``JobEnvelope``.""" + if machine_factor is None or machine_factor <= 0: + return None + bucket = envelope.bucket + point = envelope.point + if point.seq <= 0 or point.canvas_px <= 0 or not 1 <= point.windows <= _MAX_WINDOWS: + return None + resolved_offload: EtaOffloadMode = ( + offload_mode + if offload_mode is not None + else ("NONE" if bucket.load_mode == "full_models_loading" else "DISK") + ) + window_tokens, src_tokens, stage_2 = _envelope_tokens( + feature=bucket.feature, + adapter_id=bucket.adapter_id, + stage_mode=bucket.stage_mode, + seq=point.seq, + canvas_px=point.canvas_px, + windows=point.windows, + ) + tiles = max(1, point.tiles) if bucket.tiled else 1 + parts = _stage_time_parts( + system=system, + load_mode=bucket.load_mode, + offload_mode=resolved_offload, + window_tokens=window_tokens, + src_tokens=src_tokens, + stage_2=stage_2, + tiles=tiles, + conv_vae=conv_vae, + ) + load_s, denoise_s, decode_s = _compose_stages(system, bucket.load_mode, parts, machine_factor) + s1_share = _stage_1_denoise_share( + system=system, + load_mode=bucket.load_mode, + parts=parts, + window_tokens=window_tokens, + stage_2=stage_2, + tiles=tiles, + machine_factor=machine_factor, + ) + return WallTimeEstimate( + seconds=load_s + denoise_s + decode_s, + basis="scaled", + t2v_reuse=False, + load_s=load_s, + denoise_s=denoise_s, + decode_s=decode_s, + stage_1_share=s1_share, + ) + + +def _denoise_progress_fraction( + current_step: int, total_steps: int, stage_1_share: float | None = None +) -> float: + """Cost-weighted denoise progress fraction using the stage-1 cost share from `_stage_time_parts`.""" + per_win = _STAGE_1_STEPS + _STAGE_2_STEPS + if ( + stage_1_share is not None + and 0.0 < stage_1_share < 1.0 + and total_steps > 0 + and total_steps % per_win == 0 + ): + windows = total_steps // per_win + done_wins = min(windows, current_step // per_win) + in_win = current_step - done_wins * per_win + if in_win <= _STAGE_1_STEPS: + win_frac = stage_1_share * (in_win / _STAGE_1_STEPS) + else: + win_frac = stage_1_share + (1.0 - stage_1_share) * ( + (in_win - _STAGE_1_STEPS) / _STAGE_2_STEPS + ) + return min(1.0, (done_wins + win_frac) / windows) + return current_step / total_steps + + +def remaining_wall_time_s( + estimated: WallTimeEstimate | None, + *, + elapsed_s: float, + current_step: int | None, + total_steps: int | None, + decode_elapsed_s: float | None = None, +) -> int | None: + """Live remaining seconds from the 3-part estimate, step progress, and elapsed time.""" + if estimated is None or estimated.seconds <= 0: + return None + load_s = estimated.load_s if estimated.load_s > 0 else max(1, round(estimated.seconds * 0.2)) + denoise_s = ( + estimated.denoise_s if estimated.denoise_s > 0 else max(1, round(estimated.seconds * 0.6)) + ) + decode_s = ( + estimated.decode_s + if estimated.decode_s > 0 + else max(1, estimated.seconds - load_s - denoise_s) + ) + elapsed = max(0.0, elapsed_s) + if current_step is None or total_steps is None or total_steps <= 1 or current_step <= 0: + return max(0, round(estimated.seconds - elapsed)) + if current_step >= total_steps: + dec_elapsed = ( + max(0.0, decode_elapsed_s) + if decode_elapsed_s is not None + else max(0.0, elapsed - load_s - denoise_s) + ) + return max(0, round(decode_s - dec_elapsed)) + frac = _denoise_progress_fraction(current_step, total_steps, estimated.stage_1_share) + prior_rem_denoise = denoise_s * (1.0 - frac) + obs_denoise = max(1.0, elapsed - load_s) + paced_rem_denoise = obs_denoise * (1.0 - frac) / frac + rem_denoise = (1.0 - frac) * prior_rem_denoise + frac * paced_rem_denoise + return max(1, round(rem_denoise + decode_s)) + + +def median_machine_factor(factors: Sequence[float]) -> float | None: + """Cautious upper-quartile (75th percentile) of observed machine factors, or None when empty.""" + valid = sorted(f for f in factors if _MIN_MACHINE_FACTOR <= f <= _MAX_MACHINE_FACTOR) + if not valid: + return None + if len(valid) < 4: + return round(float(statistics.median(valid)), 3) + idx = (3 * (len(valid) - 1)) // 4 + return round(float(valid[idx]), 3) + + +def _scale_breakdown(breakdown: WallTimeBreakdown, target_seconds: int) -> WallTimeBreakdown: + """Scale denoise and decode so the 3 parts sum to ``target_seconds`` while keeping ``load_s``.""" + if breakdown.seconds == target_seconds: + return breakdown + load_s = min(breakdown.load_s, max(1, target_seconds - 2)) + rem = max(2, target_seconds - load_s) + gpu_total = max(1, breakdown.denoise_s + breakdown.decode_s) + denoise_s = max(1, round(rem * breakdown.denoise_s / gpu_total)) + decode_s = max(1, rem - denoise_s) + return WallTimeBreakdown( + load_s=load_s, + denoise_s=denoise_s, + decode_s=decode_s, + stage_1_share=breakdown.stage_1_share, + ) + + def estimate_fast_wall_time_s( *, width: int, @@ -87,35 +781,111 @@ def estimate_fast_wall_time_s( offload_mode: EtaOffloadMode, feature: EtaFeature, machine_factor: float | None, + system: EtaSystem = "Windows", + chunk_pixel_frames: int | None = None, + stage_2: bool = True, + conv_vae: bool = False, ) -> WallTimeEstimate | None: - """Cold whole-run seconds for a Fast cell, or None when unknown. - - Incoherent mode combos (full with offload, streamed with NONE) also return - None: the table has no such measurement and will not invent one. - """ - if machine_factor is None or machine_factor <= 0: - return None - cell = _TABLE.get((width, height, frames)) - if cell is None: + """Cold whole-run seconds and 3-part breakdown for a Fast cell, or None when unknown.""" + breakdown = estimate_stage_breakdown_s( + width=width, + height=height, + frames=frames, + load_mode=load_mode, + offload_mode=offload_mode, + system=system, + machine_factor=machine_factor, + stage_2=stage_2, + chunk_pixel_frames=chunk_pixel_frames, + conv_vae=conv_vae, + ) + if breakdown is None or machine_factor is None: return None - if load_mode == "full_models_loading": - if offload_mode != "NONE" or cell.full_cold_s is None: - return None - seconds = cell.full_cold_s - basis: EtaBasis = "measured" - elif load_mode == "streaming_models_loading": - if offload_mode == "CPU": - seconds = cell.stream_cpu_cold_s + + t2v_reuse = feature != "t2v" + if system == "Darwin": + mac_ref = _MAC_TABLE.get((width, height, frames)) if stage_2 and chunk_pixel_frames is None else None + if mac_ref is not None: + fixed_s = breakdown.load_s + 16 * len(_window_frames_list(width, height, frames, None)) + gpu_ref = max(1, mac_ref - fixed_s) + seconds = round(fixed_s + gpu_ref * machine_factor) + basis: EtaBasis = "measured" if machine_factor == 1.0 else "scaled" + scaled = _scale_breakdown(breakdown, seconds) + return WallTimeEstimate( + seconds=seconds, + basis=basis, + t2v_reuse=t2v_reuse, + load_s=scaled.load_s, + denoise_s=scaled.denoise_s, + decode_s=scaled.decode_s, + stage_1_share=scaled.stage_1_share, + ) + return WallTimeEstimate( + seconds=breakdown.seconds, + basis="scaled", + t2v_reuse=t2v_reuse, + load_s=breakdown.load_s, + denoise_s=breakdown.denoise_s, + decode_s=breakdown.decode_s, + stage_1_share=breakdown.stage_1_share, + ) + + # Table cells are reference-machine wall times, so they apply at factor 1.0 only. A + # calibrated factor is relative to the stage law, and scaling a table cell by it + # double-counts wherever the cell and the law disagree at the reference (540p 5s DISK: + # table 169 s, law 121 s). + cell = ( + _TABLE.get((width, height, frames)) + if stage_2 and chunk_pixel_frames is None and machine_factor == 1.0 + else None + ) + if cell is not None: + if load_mode == "full_models_loading": + if cell.full_cold_s is None: + return None + base_s = cell.full_cold_s + basis = "measured" + elif offload_mode == "CPU": + base_s = cell.stream_cpu_cold_s basis = "measured" - elif offload_mode == "DISK": - seconds = round(cell.stream_cpu_cold_s * cell.disk_ratio) - basis = "measured" if cell.disk_ratio_measured else "scaled" else: - return None - else: - assert_never(load_mode) + base_s = round(cell.stream_cpu_cold_s * cell.disk_ratio) + basis = "measured" if cell.disk_ratio_measured else "scaled" + if conv_vae: + # Cells were measured with the CUDA default DiffVAE decode. Swap in ConvVAE decode. + diff_vae = estimate_stage_breakdown_s( + width=width, + height=height, + frames=frames, + load_mode=load_mode, + offload_mode=offload_mode, + system=system, + machine_factor=machine_factor, + stage_2=stage_2, + ) + if diff_vae is not None: + base_s = max(1, base_s - (diff_vae.decode_s - breakdown.decode_s)) + basis = "scaled" + scaled = _scale_breakdown(breakdown, base_s) + return WallTimeEstimate( + seconds=base_s, + basis=basis, + t2v_reuse=t2v_reuse, + load_s=scaled.load_s, + denoise_s=scaled.denoise_s, + decode_s=scaled.decode_s, + stage_1_share=scaled.stage_1_share, + ) + + if load_mode == "full_models_loading" and is_chunked_canvas(width, height): + return None return WallTimeEstimate( - seconds=round(seconds * machine_factor), - basis=basis, - t2v_reuse=feature != "t2v", + seconds=breakdown.seconds, + basis="scaled", + t2v_reuse=t2v_reuse, + load_s=breakdown.load_s, + denoise_s=breakdown.denoise_s, + decode_s=breakdown.decode_s, + stage_1_share=breakdown.stage_1_share, ) + diff --git a/backend/runtime_config/evict_retry.py b/backend/runtime_config/evict_retry.py index 0c4ed6f69..879f8481f 100644 --- a/backend/runtime_config/evict_retry.py +++ b/backend/runtime_config/evict_retry.py @@ -19,8 +19,9 @@ import logging from collections.abc import Callable +from runtime_config.budget_admission import PricedJob +from runtime_config.budget_decision import VideoJobReject from runtime_config.video_job_budget import ( - BudgetFeature, BudgetRoute, LocalJobFilter, budget_route, @@ -64,7 +65,7 @@ def evict_retry_shortfall_gib( budget = job_filter.budget if budget.free_vram_bytes is None: return None - total = budget.total_vram_gib + total = budget.usable_vram_gib available = budget.available_vram_gib if total is None or available is None: return None @@ -82,11 +83,7 @@ def evict_retry_shortfall_gib( def evict_retry_filter( *, - feature: BudgetFeature, - is_vram_occupancy_miss: bool, - stream_gib: float, - seq: float, - full_gib: float, + priced: PricedJob, job_filter: LocalJobFilter, live_allocated_bytes: int | None, reserved_bytes: int | None, @@ -97,14 +94,17 @@ def evict_retry_filter( """Evict-and-resample once when the W-band covers the shortfall; else None. Logs the first-attempt line, runs the caller's evict, and returns the - caller's rebuilt filter for exactly one re-decide. None means keep the - reject — the policy declined, nothing was touched. The re-decide stays at - the call site, where the decision types differ per feature. + caller's rebuilt filter for exactly one re-price. None means keep the + priced verdict — the policy declined, nothing was touched. """ + is_vram_occupancy_miss = ( + isinstance(priced.decision, VideoJobReject) + and priced.decision.reason == "stream_over" + ) shortfall = evict_retry_shortfall_gib( - route=budget_route(feature, job_filter.profile), + route=budget_route(priced.feature, job_filter.profile), is_vram_occupancy_miss=is_vram_occupancy_miss, - stream_gib=stream_gib, + stream_gib=priced.stream_gib, job_filter=job_filter, live_allocated_bytes=live_allocated_bytes, ) @@ -113,9 +113,9 @@ def evict_retry_filter( logger.info( "[%s] job budget seq=%.0f full=%.1fGiB stream=%.1fGiB -> reject; evict-retry (shortfall %.1fGiB covered by live weights)%s", log_prefix, - seq, - full_gib, - stream_gib, + priced.seq, + priced.full_gib, + priced.stream_gib, shortfall, vram_snapshot_suffix( allocated_bytes=live_allocated_bytes, diff --git a/backend/runtime_config/fast_chunking.py b/backend/runtime_config/fast_chunking.py index 210aa4e3b..8c4b30d5a 100644 --- a/backend/runtime_config/fast_chunking.py +++ b/backend/runtime_config/fast_chunking.py @@ -1,8 +1,9 @@ """Temporal windows for large Fast video jobs (1440p and 4K, and any canvas one pass cannot fit). -The measured Fast budget is calibrated up to a window of about 63k tokens. A 1440p clip of -10 s is 114k tokens and a 4K clip of 10 s is 253k, so a large canvas runs in overlapping -windows (ltx-pipelines ``ChunkConfig``) and the job budget prices one window, not the clip. +The Fast budget laws were fitted up to a window of about 63k tokens, on the RTX 5090 (Windows) +and the M5 Max (Mac). A 1440p clip of 10 s is 114k tokens and a 4K clip of 10 s is 253k, so a +large canvas runs in overlapping windows (ltx-pipelines ``ChunkConfig``) and the job budget +prices one window, not the clip. This module is the one rule for the window. The job budget (``decide_video_job``) picks the largest window that loads and hands its length to the pipeline. @@ -14,13 +15,19 @@ import math from typing import Final -# Canvas pixels above which a clip always runs in windows. A smaller canvas stays on the single-pass -# rows, and runs in windows only when one pass cannot fit the card (``decide_video_job``). The -# smallest 1440p canvas is 3.77M pixels. -CHUNKED_CANVAS_MIN_PIXELS: Final = 3_200_000 - -# The window may not carry more than this many tokens: it is the largest size the budget -# rows were calibrated on. +# Short side in pixels from which a clip longer than one window runs in windows, whatever the +# card can hold (1440p is 1472 px, 1080p is 1088 px). A clip that fits one window is a single +# pass. Matches the 1440p tier floor in ``measured_cells`` so narrower 1440p ratios (1:1 +# 1472x1472, 4:5 1472x1856, 4:3 1984x1472) take the chunked budget law instead of the +# single-pass <=1080p curve. A smaller canvas stays on the single-pass rows, and runs in windows +# only when one pass cannot fit the card (``decide_video_job``). +CHUNKED_CANVAS_MIN_SHORT_SIDE: Final = 1408 + +# The window may not carry more than this many tokens: it is the largest point the budget laws +# were fitted on, and the fit is the RTX 5090's (1080p, 10 s, 24 fps). It is a ceiling for +# cards with room to spare, not a limit on any card: a card the budget cannot give this much is +# held lower by its own budget law, which picks the longest window it loads. Above it there is +# no fit to price a window from, so a card can only be proven there by a clean run of its own. MAX_WINDOW_TOKENS: Final = 63_240 # ltx-pipelines rejects a carry below three latent frames. The window must also be more than @@ -35,7 +42,7 @@ def is_chunked_canvas(width: int, height: int) -> bool: - return width * height >= CHUNKED_CANVAS_MIN_PIXELS + return min(width, height) >= CHUNKED_CANVAS_MIN_SHORT_SIDE def _tokens_per_latent_frame(width: int, height: int) -> float: @@ -60,6 +67,22 @@ def window_count(frames: int, window_frames: int, carry_frames: int = CARRY_FRAM return 1 + math.ceil((frames - window_frames) / (window_frames - carry_frames)) +def last_window_frames( + frames: int, window_frames: int, carry_frames: int = CARRY_FRAMES +) -> int: + """Pixel frames of the last window (``uniform_chunk_layouts``), on the 8k + 1 grid. + + A single-pass clip returns ``frames``. When ``frames - window_frames`` is an exact + multiple of the stride ``window_frames - carry_frames``, the last window is a full + ``window_frames``; otherwise it is ``carry_frames + remainder``. + """ + if frames <= window_frames: + return frames + stride = window_frames - carry_frames + remainder = (frames - window_frames) % stride + return window_frames if remainder == 0 else carry_frames + remainder + + def job_window_count( frames: int, chunk_pixel_frames: int | None, carry_frames: int = CARRY_FRAMES ) -> int: diff --git a/backend/runtime_config/ic_lora_adaptive_window.py b/backend/runtime_config/ic_lora_adaptive_window.py new file mode 100644 index 000000000..1537cee16 --- /dev/null +++ b/backend/runtime_config/ic_lora_adaptive_window.py @@ -0,0 +1,105 @@ +"""Chunk windows an adaptive LoRA (Refine Details) can run, longest first. + +A fixed-window LoRA (Restore) chunks at its window. An adaptive one has no fixed window. The +job budget prices the candidates here from the longest to the shortest, and keeps the safest one +(the longest of equal safety). This is arithmetic done before the job starts. No generation runs +to choose a window. + +The resolution caps the longest window: + +- Above the frame fence (4K) a window over ``DECODE_MAX_UNTILED_WINDOW`` splits the decode frame + axis, and a 97-frame window stalled the decode for more than 19 minutes. +- Above 720p (1080p and 1440p) the window stays at ``ADAPTIVE_MAX_WINDOW_FRAMES``, the length that + the Restore card documents as the drift limit. +- At 720p and below there is no cap, so a clip runs in one pass when the budget admits it, and + a window longer than 97 frames when it does not. + +No imports from the job budget, so the budget can import this module. +""" + +from __future__ import annotations + +from collections.abc import Callable +from dataclasses import dataclass +from typing import Final, Literal + +from frame_math import snap_to_frame_grid +from runtime_config.ic_lora_decode_window import ( + DECODE_MAX_UNTILED_WINDOW, + is_frame_fenced_canvas, + shortest_window, +) +from runtime_config.ic_lora_tiling import ADAPTIVE_MAX_WINDOW_FRAMES, IcLoraTiling + +# Canvas pixels of 720p (1280x704). Above it a window stays at ADAPTIVE_MAX_WINDOW_FRAMES, and a +# tiled job cannot run unchunked past 97 frames (the decode floor). +HIGH_RES_CANVAS_PIXELS: Final = 1280 * 704 + +_WINDOW_STEP: Final = 8 + + +def resolution_window_cap(width: int, height: int) -> int | None: + """The longest window for this canvas, or None when the resolution sets no cap.""" + if is_frame_fenced_canvas(width, height): + return DECODE_MAX_UNTILED_WINDOW + if width * height > HIGH_RES_CANVAS_PIXELS: + return ADAPTIVE_MAX_WINDOW_FRAMES + return None + + +def adaptive_window_candidates( + frames: int, *, cap: int | None, user_max: int | None, carry: int +) -> list[int | None]: + """The windows to price, longest first. None is one pass over the whole clip. + + The ceiling is the lower of the resolution cap and the user maximum. One pass is a candidate + when the clip fits inside the ceiling. The other candidates are the 8k + 1 windows from the + ceiling down to the shortest window that works with the carry. The list is empty when the + ceiling is under that shortest window and the clip is longer than the ceiling. + """ + clip = snap_to_frame_grid(frames, floor=1) + limits = [limit for limit in (cap, user_max) if limit is not None] + ceiling = min(limits) if limits else None + candidates: list[int | None] = [] + if ceiling is None or clip <= ceiling: + candidates.append(None) + top = clip - _WINDOW_STEP if ceiling is None else min(ceiling, clip - _WINDOW_STEP) + candidates.extend(range(top, shortest_window(carry) - 1, -_WINDOW_STEP)) + return candidates + + +# Why no window can run: the maximum of the run is above the cap of the resolution, or the cap is +# under the shortest window that works with the carry. +AdaptiveRefusal = Literal["window_over_cap", "refine_decode_floor"] + + +@dataclass(frozen=True) +class AdaptiveWindow: + """The window an adaptive job runs (None is one pass). ``refusal`` is set when none can run.""" + + window: int | None + refusal: AdaptiveRefusal | None = None + + +def choose_adaptive_window( + frames: int, + *, + tiling: IcLoraTiling, + cap: int | None, + carry: int, + pick: Callable[[list[int | None]], int | None], +) -> AdaptiveWindow: + """The candidate that ``pick`` takes, or the refusal when the cap leaves no candidate. + + ``pick`` gets the candidates longest first and returns one of them. The job budget keeps the + safest price and, among equals, the longest window. + + A maximum above the cap is refused and never run shorter, so the choice stays the user's. + """ + user_max = tiling.max_window_frames + if user_max is not None and cap is not None and user_max > cap: + return AdaptiveWindow(user_max, "window_over_cap") + candidates = adaptive_window_candidates(frames, cap=cap, user_max=user_max, carry=carry) + if not candidates: + return AdaptiveWindow(cap, "refine_decode_floor") + return AdaptiveWindow(pick(candidates)) diff --git a/backend/runtime_config/ic_lora_auto_carry.py b/backend/runtime_config/ic_lora_auto_carry.py new file mode 100644 index 000000000..14fd25c3a --- /dev/null +++ b/backend/runtime_config/ic_lora_auto_carry.py @@ -0,0 +1,47 @@ +"""The carry of an adaptive IC-LoRA job on Auto (Refine Details). + +The shortest window follows the carry, so a shorter carry lets a smaller window run. The job +budget prices the window walk once for each carry that Auto may use and keeps the safest price. +Among equal prices it keeps the longest window, then the longest carry. A clean price (a fitted +or locally verified shape) always beats a bet, so Auto never runs a bet while a clean run exists. + +No generation runs to choose it. The carry reaches the pipeline through ``PricedJob.carry_frames``. +""" + +from __future__ import annotations + +from collections.abc import Callable +from dataclasses import replace + +from runtime_config.budget_admission import PricedJob, safety_rank +from runtime_config.ic_lora_chunking import ic_lora_carry_frames +from runtime_config.ic_lora_tiling import IcLoraTiling, auto_carry_candidates + +_ONE_PASS = float("inf") + + +def _window_length(priced: PricedJob) -> float: + window = priced.decision.chunk_pixel_frames + return _ONE_PASS if window is None else window + + +def price_with_auto_carry(tiling: IcLoraTiling, price: Callable[[IcLoraTiling], PricedJob]) -> PricedJob: + """The best price over the carries Auto may use, tagged with the carry it runs. + + ``price`` prices the job with one tiling, and walks the windows for it. + """ + best: tuple[tuple[int, float, int], PricedJob] | None = None + for carry in auto_carry_candidates(ic_lora_carry_frames(tiling), tiling.max_window_frames): + priced = replace(price(tiling.model_copy(update={"carry_frames": carry})), carry_frames=carry) + key = (safety_rank(priced), _window_length(priced), carry) + if best is None or key > best[0]: + best = (key, priced) + assert best is not None # auto_carry_candidates never returns an empty list + return best[1] + + +def picked_carry_tiling(tiling: IcLoraTiling | None, priced: PricedJob) -> IcLoraTiling | None: + """The tiling the pipeline runs: the carry that Auto picked, else the tiling itself.""" + if tiling is None or priced.carry_frames is None: + return tiling + return tiling.model_copy(update={"carry_frames": priced.carry_frames, "carry_pinned": True}) diff --git a/backend/runtime_config/ic_lora_decode_window.py b/backend/runtime_config/ic_lora_decode_window.py index 3e296ec76..da066bdfa 100644 --- a/backend/runtime_config/ic_lora_decode_window.py +++ b/backend/runtime_config/ic_lora_decode_window.py @@ -51,18 +51,41 @@ # 97-frame window; 1440p (3.8 Mpx) did not. _FRAME_FENCE_MPX: Final = 6.0 -# 41 frames is the shortest window that works with a carry of 17 (``ic_lora_high_res``). -_SHORTEST_WINDOW: Final = 41 _WINDOW_STEP: Final = 8 + +def is_frame_fenced_canvas(width: int, height: int) -> bool: + """True when the canvas is past the frame fence, so no window may pass the frame tile.""" + return width * height / 1e6 > _FRAME_FENCE_MPX + + +def shortest_window(carry_frames: int) -> int: + """The shortest window that works with this carry (``ic_lora_high_res``). + + A middle window keeps ``window - carry`` frames, and upstream needs them to outnumber the + carry it cross-fades. A window and a carry are both 8k + 1, so the shortest window is + ``2 * carry + 7``: 41 for a carry of 17. + """ + return 2 * carry_frames + _WINDOW_STEP - 1 + # Slack kept over the minimum: the budget read 26.5 to 29.7 GiB on window 1 of the same job. _MARGIN_GIB: Final = 1.0 -# VRAM the card holds before a window's decode, by the number of windows in the job. Total VRAM -# minus the decode budget read on the last window: 4.0 (27.8 of 31.84), 9.1 (22.7), 10.9 (20.9). -# Rounded up. Provisional: one run, three windows. -_RESERVE_GIB_BY_WINDOWS: Final = {1: 4.0, 2: 9.2} -_RESERVE_GIB_SATURATED: Final = 11.0 +# VRAM the card holds before a window's decode, by the number of windows in the job, +# scaled linearly by canvas megapixels between the measured 1440p (3.77 Mpx) and 4K +# (8.11 Mpx) anchors and clamped to [0, 1]. +# 4K (3840x2112 on 31.84 GiB): total minus decode budget read 4.0 (27.8), 9.1 (22.7), +# 10.9 (20.9) on windows 1 to 3, rounded up to {1: 4.0, 2: 9.2}, >=3: 11.0. +# 1440p (2560x1472 on 16.0 GiB cap, C2/C3, and uncapped N2): post-evict held VRAM read +# [1.0, 2.3, 3.1..3.2] GiB capped and [2.7, 4.0, 4.8] GiB uncapped across windows 1 to 5, +# leaving 11.20 GiB of decode budget on a 16.0 GiB card (admits 41f windows at 11.02 GiB +# and steps 73f/97f windows down to 41f). +_1440P_MPX: Final = 2560 * 1472 / 1e6 +_4K_MPX: Final = 3840 * 2112 / 1e6 +_RESERVE_1440P_GIB_BY_WINDOWS: Final = {1: 2.0, 2: 4.0} +_RESERVE_1440P_GIB_SATURATED: Final = 4.8 +_RESERVE_4K_GIB_BY_WINDOWS: Final = {1: 4.0, 2: 9.2} +_RESERVE_4K_GIB_SATURATED: Final = 11.0 def decode_need_gib(width: int, height: int, frames: int) -> float: @@ -73,9 +96,15 @@ def decode_need_gib(width: int, height: int, frames: int) -> float: ) -def decode_budget_gib(total_vram_gib: float, windows: int) -> float: +def decode_budget_gib( + total_vram_gib: float, windows: int, *, width: int = 3840, height: int = 2112 +) -> float: """Decode budget of the last window of a job of ``windows`` windows.""" - reserve = _RESERVE_GIB_BY_WINDOWS.get(windows, _RESERVE_GIB_SATURATED) + r1440 = _RESERVE_1440P_GIB_BY_WINDOWS.get(windows, _RESERVE_1440P_GIB_SATURATED) + r4k = _RESERVE_4K_GIB_BY_WINDOWS.get(windows, _RESERVE_4K_GIB_SATURATED) + mpx = width * height / 1e6 + t = min(1.0, max(0.0, (mpx - _1440P_MPX) / (_4K_MPX - _1440P_MPX))) + reserve = r1440 + t * (r4k - r1440) return max(0.0, total_vram_gib - reserve) @@ -94,10 +123,12 @@ def _window_fits( *, frames: int, window: int | None, width: int, height: int, total_vram_gib: float, carry_frames: int ) -> bool: decoded = frames if window is None else window - if width * height / 1e6 > _FRAME_FENCE_MPX and decoded > _FRAME_TILE: + if is_frame_fenced_canvas(width, height) and decoded > _FRAME_TILE: return False windows = job_window_count(frames, window, carry_frames) - return decode_need_gib(width, height, decoded) + _MARGIN_GIB <= decode_budget_gib(total_vram_gib, windows) + return decode_need_gib(width, height, decoded) + _MARGIN_GIB <= decode_budget_gib( + total_vram_gib, windows, width=width, height=height + ) def choose_decode_window( @@ -114,7 +145,8 @@ def choose_decode_window( ``window`` is the window the chunk rule chose (None: the clip runs in one pass). An unchunked clip that does not fit drops to windows. Past the frame fence a window is capped at ``DECODE_MAX_UNTILED_WINDOW``. A LoRA window under the shortest working one - is only tried as given. + is only tried as given. A cap that takes the window under the shortest working one for + the carry leaves no candidate, so the job refuses before denoise. """ clip = snap_to_frame_grid(frames, floor=1) candidates: list[int | None] = [] @@ -123,13 +155,14 @@ def choose_decode_window( top = DECODE_MAX_UNTILED_WINDOW else: top = window - big_canvas = width * height / 1e6 > _FRAME_FENCE_MPX - if big_canvas: + if is_frame_fenced_canvas(width, height): top = min(top, DECODE_MAX_UNTILED_WINDOW) - if top < _SHORTEST_WINDOW: - candidates.append(top) + shortest = shortest_window(carry_frames) + if top < shortest: + if top == window: + candidates.append(top) else: - candidates.extend(range(top, _SHORTEST_WINDOW - 1, -_WINDOW_STEP)) + candidates.extend(range(top, shortest - 1, -_WINDOW_STEP)) for candidate in candidates: if candidate is not None and candidate >= clip: continue diff --git a/backend/runtime_config/ic_lora_high_res.py b/backend/runtime_config/ic_lora_high_res.py index 05a4e272a..2a92178b1 100644 --- a/backend/runtime_config/ic_lora_high_res.py +++ b/backend/runtime_config/ic_lora_high_res.py @@ -1,4 +1,5 @@ -"""IC-LoRA recipes above 1080p: the 1440p and 2160p cells (feature flag ``highResVideoToVideo``). +"""IC-LoRA recipes above 1080p: the 1440p and 2160p cells (feature flag ``highResVideoToVideo``, +except for the LoRAs in ``HIGH_RES_WITHOUT_FLAG_IC_LORAS``). The model runs in tiles, blended inside every denoising step, so the output can be larger than the local 1080p cell. The clip runs in short windows. Each window @@ -6,8 +7,9 @@ (``IcLoraTiling.window_frames`` and ``carry_frames``). The carry needs three latent frames (17 frames) at least. Upstream cross-fades the whole carry, and the frames a middle window keeps must be more than the carry. So 41 frames is the shortest window that works -with a carry of 17, and each window adds 24 new frames. A window of 33 fails on a clip of -three windows or more. +with the default carry of 17, and each window adds 24 new frames. A window of 33 fails on a +clip of three windows or more. A run can set a longer carry, and the shortest window then +grows with it (``ic_lora_decode_window``). Measured on the RTX 5090 at 4K with a 1920x1088 tile (Day to Night and Water Simulation, 233 frames, 9 windows): 50 s per step, about 7.8 minutes per window, 4,226 s for the @@ -21,7 +23,7 @@ from typing import Final, Literal from api_types import IcLoraSettings -from runtime_config.ic_lora_tiling import IcLoraTiling +from runtime_config.ic_lora_tiling import HIGH_RES_CARRY_FRAMES, IC_LORA_TILE_OVERLAP, IcLoraTiling from runtime_config.ltx_capabilities import TWO_PASS_PIXELS_16_9 HighResResolution = Literal["1440p", "2160p"] @@ -38,10 +40,16 @@ _CANVAS_GRID: Final = 64 -# Catalog IC-LoRAs that need the highResVideoToVideo flag, in every cell. Refine Details is the -# detail stage of the 4K ladder (its card: "refines and upscales any clip to 4K"). This list -# only gates the flag. Which cells are measured is measured_cells.py, whatever this says. -HIGH_RES_ONLY_IC_LORAS: Final = frozenset({"refine-details"}) +# Catalog IC-LoRAs that offer the 1440p and 2160p cells without the highResVideoToVideo flag. +# Refine Details is the detail stage of the 4K ladder (its card: "refines and upscales any clip +# to 4K"), so its high cells are the point of the recipe. This list only gates the flag. Which +# cells are measured is measured_cells.py, whatever this says. +HIGH_RES_WITHOUT_FLAG_IC_LORAS: Final = frozenset({"refine-details"}) + + +def high_res_flag_satisfied(catalog_id: str, *, flag_enabled: bool) -> bool: + """True when the 1440p and 2160p cells are open to this catalog LoRA.""" + return flag_enabled or catalog_id in HIGH_RES_WITHOUT_FLAG_IC_LORAS # Tile of a LoRA without its own tile plan. A LoRA with one keeps its tile size. # It is the local spatial cap, the size these LoRAs already run at in one pass. A 4K canvas @@ -54,9 +62,10 @@ def high_res_tiling(base: IcLoraTiling | None) -> IcLoraTiling: """The tile plan of a high cell, for any catalog LoRA. - The LoRA keeps its own tile size and its own window when the catalog sets them. A - LoRA without a window gets the shortest working one. The carry is fixed, and the - spatial cap is raised to the 2160p cell. + The LoRA keeps its own tile size, tile overlap and window when the catalog sets them. An + adaptive LoRA stays adaptive: the job budget picks its window. A LoRA without a window gets + the shortest working one. The carry is the high cell default + (a run can set its own after this), and the spatial cap is raised to the 2160p cell. Every tile of every step streams the whole transformer from disk, and that read costs the same for a short window as for a long one. So a longer window is cheaper @@ -65,14 +74,17 @@ def high_res_tiling(base: IcLoraTiling | None) -> IcLoraTiling: long_side, short_side = ( _DEFAULT_TILE if base is None else (base.long_side, base.short_side) ) - window_frames = _DEFAULT_WINDOW_FRAMES + adaptive = base is not None and base.adaptive_window + window_frames = None if adaptive else _DEFAULT_WINDOW_FRAMES if base is not None and base.window_frames is not None: window_frames = base.window_frames return IcLoraTiling( long_side=long_side, short_side=short_side, window_frames=window_frames, - carry_frames=17, + adaptive_window=adaptive, + carry_frames=HIGH_RES_CARRY_FRAMES, + overlap_fraction=IC_LORA_TILE_OVERLAP if base is None else base.overlap_fraction, max_output_long_side=_CELL_BOX["2160p"][0], max_output_short_side=_CELL_BOX["2160p"][1], ) diff --git a/backend/runtime_config/ic_lora_job_budget.py b/backend/runtime_config/ic_lora_job_budget.py index b72feb573..cbcace963 100644 --- a/backend/runtime_config/ic_lora_job_budget.py +++ b/backend/runtime_config/ic_lora_job_budget.py @@ -4,7 +4,7 @@ from __future__ import annotations from dataclasses import dataclass, field, replace -from typing import Literal +from typing import Final from api_types import ( REFERENCE_STILL_FRAME_IDX, @@ -14,7 +14,14 @@ IcLoraSettings, ) from frame_math import compute_num_frames -from runtime_config.fast_chunking import job_window_count +from runtime_config.fast_chunking import job_window_count, last_window_frames +from runtime_config.ic_lora_adaptive_window import ( + HIGH_RES_CANVAS_PIXELS, + AdaptiveRefusal, + choose_adaptive_window, + resolution_window_cap, +) +from runtime_config.ic_lora_auto_carry import price_with_auto_carry from runtime_config.ic_lora_decode_window import choose_decode_window from runtime_config.ic_lora_chunking import ( IC_LORA_CHUNK_PIXEL_FRAMES, @@ -32,28 +39,53 @@ from runtime_config.ic_lora_loop_fps import DEFAULT_IC_LORA_FPS, resolve_loop_fps from runtime_config.ic_lora_stage_mode import IcLoraStageMode, heavy_pass_size from runtime_config.ic_lora_tiling import IcLoraTiling, transformer_pass_size -from runtime_config.measured_cells import is_unmeasured_high_res -from runtime_config.reject_reasons import IcLoraDroppedReason, JobRiskTier +from runtime_config.eta import spatial_tile_count +from runtime_config.budget_admission import ( + Admission, + Admitted, + PricedJob, + Refused, + RiskAllowance, + admit, + is_clean, + priced_job, + safer, +) +from runtime_config.budget_decision import ( + IcLoraJobDecision, + IcLoraJobLoad, + IcLoraJobReject, + VideoJobLoad, + VideoJobReject, +) +from runtime_config.budget_evidence import ( + Extrapolated, + Fitted, + GenericCurve, + JobShape, + PriceEvidence, +) +from runtime_config.measured_cells import ( + is_unmeasured_high_res, + is_unmeasured_model, +) +from runtime_config.reject_reasons import IcLoraDroppedReason from runtime_config.video_job_budget import ( MPS_SEQUENCE_OVER_MESSAGE, VIDEO_JOB_REJECT_ERRORS, - UNMEASURED_CELL_MESSAGE, VIDEO_JOB_TOO_LARGE, + WINDOWED_PLATEAU_GIB_PER_TOKEN, + WINDOWED_TWO_WINDOW_GIB_PER_TOKEN, BudgetRoute, - LoadMode, LocalJobFilter, - VideoJobLoad, - VideoJobReject, budget_route, decide_load_mode, decide_mac_job, decide_measured_job, estimated_giB, reject_message_and_code, - risk_for_reject, - unmeasured_cell_reject, - untested_readout, video_tokens, + windows_windowed_extra_gib, ) # Compat-matrix preview of a Home IC-LoRA job. Home runs entries that skip stage 2 and @@ -114,9 +146,20 @@ _HIGH_RES_TILED_GIB_PER_MPX = 1.75 _HIGH_RES_TILED_BASE_MPX = 1920 * 1088 / 1e6 _WINDOWS_TILED_MAX_TILE_SEQ = 14_976 +_WINDOWS_TILED_DECODE_MAX_TILE_SEQ = 24_480 _WINDOWS_TILED_MAX_FRAMES = 97 _WINDOWS_TILED_SINGLE_PX = 960 * 512 _WINDOWS_TILED_DECODE_GIB = 1.30 +_IC_LORA_TILED_DECODE_INTERCEPT_GIB = 5.21 +_IC_LORA_TILED_DECODE_GIB_PER_TOKEN = 2.64e-4 + +# Adapters trained with reference_downscale_factor = 2 (-ref0.5.safetensors). +# The reference video is encoded at half spatial resolution ((W/2) x (H/2)), +# appending 0.25 x video_tokens instead of 1.0 x video_tokens (1.25 x total). +_HALF_RES_REF_IC_LORAS: Final = frozenset({"video-guide", "motion-track"}) +_HALF_RES_REF_TOKEN_FACTOR: Final = 1.25 +_IC_LORA_HALF_RES_INTERCEPT_GIB: Final = 5.20 +_IC_LORA_HALF_RES_GIB_PER_SEQ_TOKEN: Final = 2.00e-4 def _windows_iclora_required_gib(seq: float) -> float: @@ -126,6 +169,46 @@ def _windows_iclora_required_gib(seq: float) -> float: ) +def _windows_half_res_ref_required_gib( + seq: float, *, windows: int, canvas_window_tokens: float +) -> float: + base = max( + _IC_LORA_FLOOR_GIB, + _IC_LORA_HALF_RES_INTERCEPT_GIB + _IC_LORA_HALF_RES_GIB_PER_SEQ_TOKEN * seq, + ) + return base + windows_windowed_extra_gib(windows, canvas_window_tokens) + + +def _windows_tiled_decode_base_gib(canvas_tokens: float) -> float: + return max( + _IC_LORA_FLOOR_GIB, + _IC_LORA_TILED_DECODE_INTERCEPT_GIB + + _IC_LORA_TILED_DECODE_GIB_PER_TOKEN * canvas_tokens, + ) + + +def _windows_tiled_canvas_decode_gib( + stage1_width: int, + stage1_height: int, + frames: int, + *, + window_frames: int, + windows: int, + carry_frames: int, +) -> float: + """Full-canvas DiffVAE decode peak plus multi-window accumulation.""" + can_t1 = video_tokens(stage1_height, stage1_width, window_frames) + dec_t1 = _windows_tiled_decode_base_gib(can_t1) + if windows == 1: + return dec_t1 + if windows == 2: + last_frames = last_window_frames(frames, window_frames, carry_frames) + can_t2 = video_tokens(stage1_height, stage1_width, last_frames) + dec_t2 = _windows_tiled_decode_base_gib(can_t2) + return max(dec_t1, dec_t2 + WINDOWED_TWO_WINDOW_GIB_PER_TOKEN * can_t1) + return dec_t1 + WINDOWED_PLATEAU_GIB_PER_TOKEN * can_t1 + + # Mac (Darwin) IC-LoRA stream requirement, Mac-native fit (no transfer from CUDA): # max(9.84, 5.75 + 6.105e-4 * denoise_tokens), +0.50 for ingredients. # Unified memory costs more per token than discrete VRAM: the allocator working @@ -241,24 +324,6 @@ def _mac_iclora_two_stage_required_gib(seq: float) -> float: # boundary rather than tuning it. _IC_LORA_FULL_HEADROOM_GIB = 7.0 -# Two-stage is offered where it is measured and refused past the token ceiling. -# A token rule, not a duration rule: a long small-canvas job can price while an -# unmeasured large-canvas short job must not slip under a clock. It bites opt-in -# two-stage and Layout to Render; single-stage never reaches it. -TWO_STAGE_OVER_MEASURED_MESSAGE = ( - "This two-stage clip is longer than we have measured at this photo size. " - "Try a shorter clip, a smaller photo, or single-stage for the full length." -) -# Mac two-stage past the measured cell refuses, not fenced by the Windows token -# range: both two-stage layouts inside the L2R cell are priced -# (``_mac_two_stage_priced`` owns that cell), so past-1080p, tiled, and -# long unchunked small-canvas still refuse here rather than price on chords that never saw -# them. The picker keeps the durations selectable with this refusal attached; -# generate/preflight 422 with it. -MAC_TWO_STAGE_UNMEASURED_MESSAGE = ( - "Two-stage upscaling isn't measured on Macs yet, so it stays off here. " - "Use single-stage for the full length." -) # Long unchunked tiled Refine past 720p refuses on every route: the DiffVAE decode # cannot fit its minimum tile (stage 4 needs 17.2 GiB vs 11.7 usable at # 1920x1088x241) and the pipeline answers 400 before denoise starts. Canvas pricing @@ -271,7 +336,12 @@ def _mac_iclora_two_stage_required_gib(seq: float) -> float: "This high-resolution clip is too large for this GPU's decoder to finish. " "Try a shorter clip or a lower resolution." ) -_REFINE_DECODE_FENCE_PX = 1280 * 704 +# The maximum chunk length of an adaptive LoRA is above the longest chunk this resolution can +# decode. The run never takes a shorter chunk in its place, so the choice stays the user's. +WINDOW_OVER_CAP_MESSAGE = ( + "This resolution cannot run a chunk that long. " + "Choose a shorter maximum chunk length, or Auto." +) _REFINE_DECODE_FENCE_FRAMES = 97 @@ -280,9 +350,12 @@ def two_stage_exceeds_priced( ) -> bool: """True when a two-stage job runs past the priced token range. - Single source for the rule: decide_ic_lora_job calls it as its first - pre-check, with the window length for a chunked job. A token ceiling needs no - frame-rate grid, so there is no fps argument at all. + A token rule, not a duration rule: a long small-canvas job can price while an + unmeasured large-canvas short job must not slip under a clock. It bites opt-in + two-stage and Layout to Render; single-stage never reaches it. The verdict is + still priced on the curve and only tagged extrapolated, with the window length + for a chunked job. A token ceiling needs no frame-rate grid, so there is no fps + argument at all. """ if stage_mode is IcLoraStageMode.SINGLE_STAGE: return False @@ -314,7 +387,7 @@ def refine_decode_floor_exceeded( return False if window_frames <= _REFINE_DECODE_FENCE_FRAMES: return False - return stage1_width * stage1_height > _REFINE_DECODE_FENCE_PX + return stage1_width * stage1_height > HIGH_RES_CANVAS_PIXELS # List-time duration filter has no user image. skip_stage_2: 9:16 768×1280 through @@ -326,34 +399,6 @@ def refine_decode_floor_exceeded( _CATALOG_PREVIEW_TWO_STAGE_WIDTH = 1920 _CATALOG_PREVIEW_TWO_STAGE_HEIGHT = 1088 -@dataclass(frozen=True, slots=True) -class IcLoraJobLoad: - mode: LoadMode - seq: float - full_gib: float - stream_gib: float - # Window length when the job runs chunked, else None. The pipeline runs this value. - chunk_pixel_frames: int | None = None - - -@dataclass(frozen=True, slots=True) -class IcLoraJobReject: - reason: Literal["spatial", "unsupported", "two_stage_over_measured", "mac_two_stage_unmeasured", "refine_decode_floor"] - seq: float - full_gib: float - stream_gib: float - # Uniform with VideoJobReject; always None (these verdicts never compare - # RAM — spatial is a canvas fence, unsupported short-circuits first, and - # the token-ceiling, Mac-two-stage and decode-floor fences refuse before - # any curve runs). - required_ram_bytes: int | None = None - # Window ``price()`` tried. A reckless downgrade runs this window; - # None would be one unchunked pass. - chunk_pixel_frames: int | None = None - - -IcLoraJobDecision = IcLoraJobLoad | IcLoraJobReject | VideoJobReject - def ic_lora_sequence_tokens(width: int, height: int, frames: int) -> float: """Video tokens plus the appended reference clip (same H×W×frames).""" @@ -367,6 +412,7 @@ def _heaviest_pass_tokens( frames: int, stills: int, tiling: IcLoraTiling | None, + ic_lora_id: str | None = None, ) -> float: """Tokens of the heaviest pass of the job. @@ -377,7 +423,8 @@ def _heaviest_pass_tokens( takes no still. A tiled job (single stage) runs the transformer on one tile at a time. Its pass is the - tile, with the reference cropped to the same tile. + tile, with the reference cropped to the same tile. Half-res reference adapters + (``reference_downscale_factor = 2``) append ``0.25 * video_tokens`` instead of ``1.0 *``. """ width, height = transformer_pass_size(*heavy_pass_size(stage_mode, stage1_width, stage1_height), tiling) if stage_mode is IcLoraStageMode.STAGE_1_LORA: @@ -386,6 +433,8 @@ def _heaviest_pass_tokens( ic_lora_sequence_tokens(stage1_width, stage1_height, frames), ) still_tokens = stills * (height / 32.0) * (width / 32.0) + if ic_lora_id in _HALF_RES_REF_IC_LORAS: + return video_tokens(height, width, frames) * _HALF_RES_REF_TOKEN_FACTOR + still_tokens return ic_lora_sequence_tokens(width, height, frames) + still_tokens @@ -403,10 +452,8 @@ def _mac_two_stage_priced( The chords price both two-stage layouts through the L2R cell (unchunked or chunked per window), untiled, with at most the measured look still. Anything - else two-stage on Mac is unmeasured and refuses. Single-stage never reaches - this predicate (the call site only invokes it past the single-stage check), - but the guard stays so a mis-called single-stage job refuses rather than - prices on the wrong curve. + else two-stage on Mac (past 1080p, tiled, long unchunked small canvas) still + prices on the chord, tagged extrapolated. """ if route != "mac_measured": return False @@ -513,25 +560,31 @@ def _windows_tiled_priced( window_frames: int, stills: int, tiling: IcLoraTiling | None, + ic_lora_id: str | None = None, ) -> bool: - """True when a Windows tiled job sits inside the measured one-window tile cell. + """True when a Windows tiled job sits inside the measured tile-pass cell. The tile-pass seq fence counts stills (a still pushes a tile at the fence back to canvas pricing). Anything outside the cell prices at the canvas. """ + _ = window if route != "windows_measured": return False if stage_mode is not IcLoraStageMode.SINGLE_STAGE: return False if tiling is None: return False - if window is not None: - return False if window_frames > _WINDOWS_TILED_MAX_FRAMES: return False return ( _heaviest_pass_tokens( - stage_mode, stage1_width, stage1_height, window_frames, stills, tiling + stage_mode, + stage1_width, + stage1_height, + window_frames, + stills, + tiling, + ic_lora_id=ic_lora_id, ) <= _WINDOWS_TILED_MAX_TILE_SEQ ) @@ -557,8 +610,73 @@ def decide_ic_lora_job( ic_lora_id: str | None = None, stills: int = 0, tiling: IcLoraTiling | None = None, -) -> IcLoraJobDecision: - """422 definite-over jobs; per-job stream when full will not fit; the chunk window. + allowance: RiskAllowance | None = None, +) -> Admission: + """Price the IC-LoRA job, then admit it under the allowance. + + ``allowance=None`` follows the filter's live mode (request-time gates); + executors pass the stored allowance so a mode flip never re-gates a queued job. + """ + return admit( + price_ic_lora_job( + stage1_width, + stage1_height, + frames, + stage_mode=stage_mode, + job_filter=job_filter, + ic_lora_id=ic_lora_id, + stills=stills, + tiling=tiling, + ), + allowance if allowance is not None else RiskAllowance.for_mode(job_filter.budget_mode), + ) + + +def price_ic_lora_job( + stage1_width: int, + stage1_height: int, + frames: int, + *, + stage_mode: IcLoraStageMode, + job_filter: LocalJobFilter, + ic_lora_id: str | None, + stills: int, + tiling: IcLoraTiling | None, +) -> PricedJob: + """The priced verdict and its chunk window. On Auto carry, it also picks the carry. + + ``PricedJob.carry_frames`` carries that pick to the pipeline (``ic_lora_auto_carry``). + """ + + def price(tiling: IcLoraTiling | None) -> PricedJob: + return _price_ic_lora_carry( + stage1_width, + stage1_height, + frames, + stage_mode=stage_mode, + job_filter=job_filter, + ic_lora_id=ic_lora_id, + stills=stills, + tiling=tiling, + ) + + if tiling is not None and tiling.auto_carry: + return price_with_auto_carry(tiling, price) + return price(tiling) + + +def _price_ic_lora_carry( + stage1_width: int, + stage1_height: int, + frames: int, + *, + stage_mode: IcLoraStageMode, + job_filter: LocalJobFilter, + ic_lora_id: str | None, + stills: int, + tiling: IcLoraTiling | None, +) -> PricedJob: + """The priced verdict and its chunk window, for the carry of ``tiling``. ``stage_mode`` sets the heaviest pass (``heavy_pass_size``). That pass sets the priced token count, the chunk rule and the spatial cap. The spatial cap checks the output @@ -567,9 +685,99 @@ def decide_ic_lora_job( single-stage. This is the one place that decides chunking. A job chunks when the size and token - rule says so, or when it may chunk and does not fit unchunked. + rule says so, or when it may chunk and the unchunked price is not clean (over budget, + or extrapolated) and the chunked price is safer (``safer``). ``IcLoraJobLoad.chunk_pixel_frames`` carries the decision to the pipeline. A chunked - job holds one window at a time, so it is priced (and fenced) as one window. + job holds one window at a time, so it is priced (and tagged) as one window. + """ + route = budget_route("iclora", job_filter.profile) + + def price(window: int | None, refusal: AdaptiveRefusal | None = None) -> PricedJob: + return _price_ic_lora_window( + stage1_width, + stage1_height, + frames, + window=window, + stage_mode=stage_mode, + job_filter=job_filter, + ic_lora_id=ic_lora_id, + stills=stills, + tiling=tiling, + refusal=refusal, + ) + + adaptive_tiling = tiling if tiling is not None and tiling.adaptive_window else None + refusal: AdaptiveRefusal | None = None + if adaptive_tiling is not None: + # Priced before the job starts, longest first. No generation runs to choose it. + def safest(candidates: list[int | None]) -> int | None: + # ``safer`` keeps the first on a tie, so an equal price keeps the longer window. + best_window, best = candidates[0], price(candidates[0]) + for candidate in candidates[1:]: + priced = price(candidate) + kept = safer(best, priced) + if kept is priced: + best_window, best = candidate, priced + return best_window + + chosen = choose_adaptive_window( + frames, + tiling=adaptive_tiling, + cap=resolution_window_cap(stage1_width, stage1_height), + carry=ic_lora_carry_frames(adaptive_tiling), + pick=safest, + ) + window, refusal = chosen.window, chosen.refusal + else: + window = ic_lora_chunk_pixel_frames( + stage1_width, stage1_height, frames, stage_mode=stage_mode, tiling=tiling + ) + total_vram_gib = job_filter.budget.total_vram_gib + if ( + refusal is None + and route == "windows_measured" + and _is_high_res_tiled(route, stage_mode, tiling) + and total_vram_gib is not None + ): + # The decode of the job's last window must fit, or the pipeline refuses after the denoise. + decode_choice = choose_decode_window( + frames=frames, + window=window, + width=stage1_width, + height=stage1_height, + total_vram_gib=total_vram_gib, + carry_frames=ic_lora_carry_frames(tiling), + ) + window = decode_choice.window + refusal = None if decode_choice.fits else "refine_decode_floor" + + first = price(window, refusal) + if ( + adaptive_tiling is None + and window is None + and not is_clean(first) + and ic_lora_may_chunk(stage1_width, stage1_height, frames, stage_mode=stage_mode, tiling=tiling) + ): + # Without this, a clip just under the token rule is priced whole and a longer + # clip is priced as one window, so the longer clip would be cheaper. + return safer(first, price(IC_LORA_CHUNK_PIXEL_FRAMES)) + return first + + +def _price_ic_lora_window( + stage1_width: int, + stage1_height: int, + frames: int, + *, + window: int | None, + stage_mode: IcLoraStageMode, + job_filter: LocalJobFilter, + ic_lora_id: str | None, + stills: int, + tiling: IcLoraTiling | None, + refusal: AdaptiveRefusal | None = None, +) -> PricedJob: + """Hard walls, the route's curve, then the evidence tag on this window. ``stills`` is the number of reference stills. Each adds one latent frame of tokens to each window, so a chunked job pays for it once per window. @@ -587,30 +795,41 @@ def decide_ic_lora_job( measured); long unchunked Refine past 720p refuses outright at the decode floor (``refine_decode_floor_exceeded``). - Per window, in order: unsupported, the spatial cap, the two-stage token fence, the - Mac two-stage refusal (unmeasured two-stage shapes only — both two-stage - layouts inside the L2R cell price on its chords), then the platform curve. Windows prices the measured - reserved line (``_windows_iclora_required_gib``) against min(total, free) with the - feature RAM floor. Darwin prices the Mac-native curves (single-stage on - stage-1 tokens, priced two-stage on the heaviest pass), with the - ingredients adder keyed on ``ic_lora_id``. Everything else keeps the legacy generic - curve. The full-vs-stream pick stays conservative (full fits clean but runs - no faster, so streaming 8s+ costs nothing). + Hard walls, in order: unsupported, the spatial cap, the decode floor. Then the + platform curve. Windows prices the measured reserved line + (``_windows_iclora_required_gib``) against min(total, free) with the feature RAM + floor. Darwin prices the Mac-native curves (single-stage on stage-1 tokens, + two-stage on the heaviest pass), with the ingredients adder keyed on + ``ic_lora_id``. Everything else keeps the legacy generic curve. The full-vs-stream + pick stays conservative (full fits clean but runs no faster, so streaming 8s+ + costs nothing). The evidence tag never refuses: a 1440p or 4K cell no run covers, + a two-stage window past the priced token range, and a Mac two-stage shape outside + the measured cell are priced verdicts tagged ``Extrapolated``. """ token_width, token_height = heavy_pass_size(stage_mode, stage1_width, stage1_height) route = budget_route("iclora", job_filter.profile) - # Set below, once the window is chosen: no window fits the decode of the job's last window. - decode_no_fit = False - - def price(window: int | None) -> IcLoraJobDecision: - def stamped(decision: IcLoraJobDecision) -> IcLoraJobDecision: - # Loads already carry the window. Rejects must too: a reckless - # downgrade runs this window, and None is one unchunked pass. - if isinstance(decision, IcLoraJobLoad): - return decision - return replace(decision, chunk_pixel_frames=window) - window_frames = frames if window is None else window - windows_tiled = _windows_tiled_priced( + window_frames = frames if window is None else window + carry_frames = ic_lora_carry_frames(tiling) + windows = job_window_count(frames, window, carry_frames) + windows_tiled = _windows_tiled_priced( + route=route, + stage_mode=stage_mode, + stage1_width=stage1_width, + stage1_height=stage1_height, + window=window, + window_frames=window_frames, + stills=stills, + tiling=tiling, + ic_lora_id=ic_lora_id, + ) + high_res_tiled = _is_high_res_tiled(route, stage_mode, tiling) + canvas_mpx = stage1_width * stage1_height / 1e6 + priced_tiling = ( + tiling + if route == "legacy" + or windows_tiled + or high_res_tiled + or _mac_tile_priced( route=route, stage_mode=stage_mode, stage1_width=stage1_width, @@ -620,78 +839,136 @@ def stamped(decision: IcLoraJobDecision) -> IcLoraJobDecision: stills=stills, tiling=tiling, ) - high_res_tiled = _is_high_res_tiled(route, stage_mode, tiling) - canvas_mpx = stage1_width * stage1_height / 1e6 - priced_tiling = ( - tiling - if route == "legacy" - or windows_tiled - or high_res_tiled - or _mac_tile_priced( - route=route, - stage_mode=stage_mode, - stage1_width=stage1_width, - stage1_height=stage1_height, - window=window, - window_frames=window_frames, - stills=stills, - tiling=tiling, - ) - else None - ) - seq = _heaviest_pass_tokens( - stage_mode, stage1_width, stage1_height, window_frames, stills, priced_tiling - ) - full_gib = estimated_giB("full_models_loading", seq) - stream_gib = estimated_giB("streaming_models_loading", seq) - - if job_filter.profile.process_mode == "unsupported": - return stamped(IcLoraJobReject(reason="unsupported", seq=seq, full_gib=full_gib, stream_gib=stream_gib)) - # Spatial before the fences: no clip length passes an over-cap canvas, so - # "try a shorter clip" would be the wrong advice. - if over_spatial_cap(token_width, token_height, tiling): - return stamped(IcLoraJobReject(reason="spatial", seq=seq, full_gib=full_gib, stream_gib=stream_gib)) - if two_stage_exceeds_priced( + else None + ) + seq = _heaviest_pass_tokens( + stage_mode, + stage1_width, + stage1_height, + window_frames, + stills, + priced_tiling, + ic_lora_id=ic_lora_id, + ) + full_gib = estimated_giB("full_models_loading", seq) + stream_gib = estimated_giB("streaming_models_loading", seq) + + evidence: PriceEvidence + if is_unmeasured_high_res( + "iclora", + route, + token_width, + token_height, + windows=windows, + ic_lora_id=ic_lora_id, + ): + evidence = Extrapolated(basis="high_res_cell") + elif two_stage_exceeds_priced( + stage_mode=stage_mode, + stage1_width=stage1_width, + stage1_height=stage1_height, + frames=window_frames, + ): + evidence = Extrapolated(basis="two_stage_range") + elif ( + route == "mac_measured" + and stage_mode is not IcLoraStageMode.SINGLE_STAGE + and not _mac_two_stage_priced( + route=route, stage_mode=stage_mode, stage1_width=stage1_width, stage1_height=stage1_height, - frames=window_frames, - ): - return stamped(IcLoraJobReject( - reason="two_stage_over_measured", seq=seq, full_gib=full_gib, stream_gib=stream_gib - )) - if refine_decode_floor_exceeded( - stage1_width=stage1_width, - stage1_height=stage1_height, - window=window, window_frames=window_frames, + stills=stills, tiling=tiling, - ): - return stamped(IcLoraJobReject( - reason="refine_decode_floor", seq=seq, full_gib=full_gib, stream_gib=stream_gib - )) - if decode_no_fit: - return stamped(IcLoraJobReject( - reason="refine_decode_floor", seq=seq, full_gib=full_gib, stream_gib=stream_gib - )) - if ( - stage_mode is not IcLoraStageMode.SINGLE_STAGE - and route == "mac_measured" - and not _mac_two_stage_priced( - route=route, - stage_mode=stage_mode, - stage1_width=stage1_width, - stage1_height=stage1_height, + ) + ): + evidence = Extrapolated(basis="mac_two_stage_cell") + elif route == "legacy": + evidence = GenericCurve() + elif is_unmeasured_model(job_filter.profile.model_id): + evidence = Extrapolated(basis="unmeasured_model") + else: + evidence = Fitted() + + def priced(decision: IcLoraJobDecision) -> PricedJob: + # Rejects carry the window too: an over bet runs this window, and None is + # one unchunked pass. + if not isinstance(decision, IcLoraJobLoad): + decision = replace(decision, chunk_pixel_frames=window) + return priced_job( + "iclora", + decision, + evidence, + JobShape( + feature="iclora", + model_id=job_filter.profile.model_id or "", + adapter_id=ic_lora_id or "", + stage_mode=stage_mode.value, + tiled=tiling is not None, + chunked=window is not None, + seq=decision.seq, + canvas_px=token_width * token_height, + windows=windows, + tiles=spatial_tile_count(stage1_width, stage1_height, tiling), + ), + job_filter=job_filter, + ) + + if job_filter.profile.process_mode == "unsupported": + return priced(IcLoraJobReject(reason="unsupported", seq=seq, full_gib=full_gib, stream_gib=stream_gib)) + # Spatial before the decode floor: no clip length passes an over-cap canvas, so + # "try a shorter clip" would be the wrong advice. + if over_spatial_cap(token_width, token_height, tiling): + return priced(IcLoraJobReject(reason="spatial", seq=seq, full_gib=full_gib, stream_gib=stream_gib)) + if refine_decode_floor_exceeded( + stage1_width=stage1_width, + stage1_height=stage1_height, + window=window, + window_frames=window_frames, + tiling=tiling, + ): + return priced(IcLoraJobReject( + reason="refine_decode_floor", seq=seq, full_gib=full_gib, stream_gib=stream_gib + )) + if refusal is not None: + return priced(IcLoraJobReject(reason=refusal, seq=seq, full_gib=full_gib, stream_gib=stream_gib)) + + if route == "windows_measured": + if high_res_tiled and seq <= _WINDOWS_TILED_DECODE_MAX_TILE_SEQ: + required_gib = _windows_tiled_canvas_decode_gib( + stage1_width, + stage1_height, + frames, window_frames=window_frames, - stills=stills, - tiling=tiling, + windows=windows, + carry_frames=carry_frames, ) + elif windows_tiled and window is not None: + required_gib = max( + _windows_iclora_required_gib(seq), + _windows_tiled_canvas_decode_gib( + stage1_width, + stage1_height, + frames, + window_frames=window_frames, + windows=windows, + carry_frames=carry_frames, + ), + ) + elif ( + stage_mode is IcLoraStageMode.SINGLE_STAGE + and tiling is None + and ic_lora_id in _HALF_RES_REF_IC_LORAS ): - return stamped(IcLoraJobReject( - reason="mac_two_stage_unmeasured", seq=seq, full_gib=full_gib, stream_gib=stream_gib - )) - - if route == "windows_measured": + required_gib = _windows_half_res_ref_required_gib( + seq, + windows=windows, + canvas_window_tokens=video_tokens( + stage1_height, stage1_width, window_frames + ), + ) + else: required_gib = _windows_iclora_required_gib(seq) if high_res_tiled: required_gib += _HIGH_RES_TILED_GIB_PER_MPX * canvas_mpx @@ -703,106 +980,63 @@ def stamped(decision: IcLoraJobDecision) -> IcLoraJobDecision: and window_frames > _WINDOWS_TILED_MAX_FRAMES ): required_gib += _WINDOWS_TILED_DECODE_GIB - decision: VideoJobLoad | VideoJobReject = decide_measured_job( - required_gib=required_gib, - required_ram_bytes=job_filter.profile.windows_iclora_required_ram_bytes, - seq=seq, - full_headroom_gib=_IC_LORA_FULL_HEADROOM_GIB, - job_filter=job_filter, - force_stream=windows_tiled or high_res_tiled, + decision: VideoJobLoad | VideoJobReject = decide_measured_job( + required_gib=required_gib, + required_ram_bytes=job_filter.profile.windows_iclora_required_ram_bytes, + seq=seq, + full_headroom_gib=_IC_LORA_FULL_HEADROOM_GIB, + job_filter=job_filter, + force_stream=windows_tiled or high_res_tiled, + ) + elif route == "mac_measured": + # The single-stage curve was fitted on stage-1 tokens; the heaviest + # pass of a single-stage job is twice that. The two-stage chord was + # fitted on the heaviest pass directly; a two-stage shape outside its + # cell prices on the same chord, tagged extrapolated above. + if high_res_tiled: + # Past the measured 1080p flat pass, the canvas term grows with the pixels. + stream_gib = _MAC_CHUNKED_TILED_FLAT_GIB + _HIGH_RES_TILED_GIB_PER_MPX * max( + 0.0, canvas_mpx - _HIGH_RES_TILED_BASE_MPX ) - elif route == "mac_measured": - # The single-stage curve was fitted on stage-1 tokens; the heaviest - # pass of a single-stage job is twice that. The two-stage chord was - # fitted on the heaviest pass directly; the refusal above fenced out - # everything past its cell, so only priced two-stage reaches here. - if high_res_tiled: - # Past the measured 1080p flat pass, the canvas term grows with the pixels. - stream_gib = _MAC_CHUNKED_TILED_FLAT_GIB + _HIGH_RES_TILED_GIB_PER_MPX * max( - 0.0, canvas_mpx - _HIGH_RES_TILED_BASE_MPX - ) - elif stage_mode is IcLoraStageMode.SINGLE_STAGE: - if _mac_chunked_tiled_flat( - route=route, - stage_mode=stage_mode, - stage1_width=stage1_width, - stage1_height=stage1_height, - frames=frames, - window=window, - window_frames=window_frames, - stills=stills, - tiling=tiling, - ): - stream_gib = _MAC_CHUNKED_TILED_FLAT_GIB - else: - stream_gib = _mac_iclora_stream_required_gib(seq / 2.0, ic_lora_id) + elif stage_mode is IcLoraStageMode.SINGLE_STAGE: + if _mac_chunked_tiled_flat( + route=route, + stage_mode=stage_mode, + stage1_width=stage1_width, + stage1_height=stage1_height, + frames=frames, + window=window, + window_frames=window_frames, + stills=stills, + tiling=tiling, + ): + stream_gib = _MAC_CHUNKED_TILED_FLAT_GIB else: - stream_gib = _mac_iclora_two_stage_required_gib(seq) - decision = decide_mac_job( - seq, - stream_gib, - job_filter=job_filter, - ) + stream_gib = _mac_iclora_stream_required_gib(seq / 2.0, ic_lora_id) else: - decision = decide_load_mode( - seq, - memory_gb=job_filter.budget.memory_gb, - process_mode=job_filter.profile.process_mode, - darwin=job_filter.profile.darwin, - full_headroom_gib=_IC_LORA_FULL_HEADROOM_GIB, - ) - if isinstance(decision, VideoJobReject): - return stamped(decision) - return IcLoraJobLoad( - mode=decision.mode, - seq=decision.seq, - full_gib=decision.full_gib, - stream_gib=decision.stream_gib, - chunk_pixel_frames=window, + stream_gib = _mac_iclora_two_stage_required_gib(seq) + decision = decide_mac_job( + seq, + stream_gib, + job_filter=job_filter, ) - - window = ic_lora_chunk_pixel_frames( - stage1_width, stage1_height, frames, stage_mode=stage_mode, tiling=tiling - ) - total_vram_gib = job_filter.budget.total_vram_gib - if route == "windows_measured" and _is_high_res_tiled(route, stage_mode, tiling) and total_vram_gib is not None: - # The decode of the job's last window must fit, or the pipeline refuses after the denoise. - decode_choice = choose_decode_window( - frames=frames, - window=window, - width=stage1_width, - height=stage1_height, - total_vram_gib=total_vram_gib, - carry_frames=ic_lora_carry_frames(tiling), + else: + decision = decide_load_mode( + seq, + memory_gb=job_filter.budget.memory_gb, + process_mode=job_filter.profile.process_mode, + darwin=job_filter.profile.darwin, + full_headroom_gib=_IC_LORA_FULL_HEADROOM_GIB, ) - window = decode_choice.window - decode_no_fit = not decode_choice.fits - - def gated(verdict: IcLoraJobDecision) -> IcLoraJobDecision: - if isinstance(verdict, IcLoraJobLoad) and is_unmeasured_high_res( - "iclora", - route, - token_width, - token_height, - windows=job_window_count( - frames, verdict.chunk_pixel_frames, ic_lora_carry_frames(tiling) - ), - ic_lora_id=ic_lora_id, - ): - return unmeasured_cell_reject(verdict) - return verdict - - decision = price(window) - if ( - window is None - and isinstance(decision, VideoJobReject) - and decision.reason == "stream_over" - and ic_lora_may_chunk(stage1_width, stage1_height, frames, stage_mode=stage_mode, tiling=tiling) - ): - # Without this, a clip just under the token rule is priced whole and a longer - # clip is priced as one window, so the longer clip would be cheaper. - return gated(price(IC_LORA_CHUNK_PIXEL_FRAMES)) - return gated(decision) + if isinstance(decision, VideoJobReject): + return priced(decision) + return priced(IcLoraJobLoad( + mode=decision.mode, + seq=decision.seq, + full_gib=decision.full_gib, + stream_gib=decision.stream_gib, + chunk_pixel_frames=window, + )) def catalog_preview_stage1(settings: IcLoraSettings) -> tuple[int, int]: @@ -841,33 +1075,21 @@ def catalog_preview_stills(item: IcLoraCatalogItem) -> int: # fixed-copy reason must add a branch there, or it falls through to the # shared builder and prints figures it never compared. _FIXED_COPY_REASONS: frozenset[IcLoraDroppedReason] = frozenset( - {"spatial", "unsupported", "two_stage_over_measured", "mac_two_stage_unmeasured", "refine_decode_floor", "mps_sequence_over"} + {"spatial", "unsupported", "refine_decode_floor", "window_over_cap", "mps_sequence_over"} ) -def iclora_drop_risk_tier(reason: IcLoraDroppedReason) -> JobRiskTier | None: - """Risk tier for an IC-LoRA duration drop. None when a hard fence or - unsupported: those never allow-with-warning in any mode.""" - if reason == "stream_over" or reason == "ram_shortfall": - return "over" - if reason in ("two_stage_over_measured", "mac_two_stage_unmeasured", "unmeasured_cell"): - return "unmeasured" - # spatial, refine_decode_floor, unsupported, mps_sequence_over - return None - - @dataclass(frozen=True, slots=True) class IcLoraDurationOutcome: - """Per-duration verdicts: kept plus why each dropped duration died.""" - - kept: list[int] - rejected: dict[int, IcLoraDroppedReason] - # Full decisions for dropped durations, so list-time drops message without - # re-deciding. Fixed-copy verdicts (spatial, fences, unsupported) carry - # fixed messages instead — never print a number the budget did not compare. - rejects: dict[int, VideoJobReject | IcLoraJobReject] = field( - default_factory=dict[int, VideoJobReject | IcLoraJobReject] - ) + """Per-duration admissions in option order, so list-time drops message + without re-deciding.""" + + admitted: dict[int, Admitted] = field(default_factory=dict[int, Admitted]) + refused: dict[int, Refused] = field(default_factory=dict[int, Refused]) + + @property + def kept(self) -> list[int]: + return list(self.admitted) def decide_ic_lora_durations( @@ -882,19 +1104,17 @@ def decide_ic_lora_durations( stills: int = 0, tiling: IcLoraTiling | None = None, ) -> IcLoraDurationOutcome: - """Decide every duration with one decide call each; the token-ceiling fence rides inside it. + """Admit every duration with one decide call each, under the live mode. ``stage_mode``, ``stills`` and ``tiling`` must be what the pipeline runs, or the filter prices another job. ``ic_lora_id`` threads to the Mac ingredients term so the list-time offer matches the generate-time verdict (offer ≡ verdict); None prices on the line, same as generate's custom path. """ - kept: list[int] = [] - rejected: dict[int, IcLoraDroppedReason] = {} - rejects: dict[int, VideoJobReject | IcLoraJobReject] = {} + outcome = IcLoraDurationOutcome() for seconds in options: frames = compute_num_frames(seconds, max(1, fps)) - decision = decide_ic_lora_job( + admission = decide_ic_lora_job( stage1_width, stage1_height, frames, @@ -904,38 +1124,29 @@ def decide_ic_lora_durations( stills=stills, tiling=tiling, ) - if isinstance(decision, IcLoraJobLoad): - kept.append(seconds) + if isinstance(admission, Admitted): + outcome.admitted[seconds] = admission else: - rejected[seconds] = decision.reason - rejects[seconds] = decision - return IcLoraDurationOutcome( - kept=kept, - rejected=rejected, - rejects=rejects, - ) + outcome.refused[seconds] = admission + return outcome def dropped_duration_message_and_code( decision: VideoJobReject | IcLoraJobReject, job_filter: LocalJobFilter, ) -> tuple[str, str]: - """(message, code) for a dropped duration. Fixed copy for the spatial, - fence, Mac-two-stage, and unsupported verdicts; the shared budget builder - with the compared figures for stream-over and RAM verdicts.""" + """(message, code) for a refused IC-LoRA job. Fixed copy for the spatial, + decode-floor, MPS-sequence, and unsupported verdicts; the shared budget + builder for the memory and untested verdicts.""" reason = decision.reason if reason == "spatial": return IC_LORA_V1_ENVELOPE_MESSAGE, IC_LORA_SOURCE_TOO_LARGE - if reason == "two_stage_over_measured": - return TWO_STAGE_OVER_MEASURED_MESSAGE, VIDEO_JOB_TOO_LARGE - if reason == "mac_two_stage_unmeasured": - return MAC_TWO_STAGE_UNMEASURED_MESSAGE, VIDEO_JOB_TOO_LARGE if reason == "refine_decode_floor": return REFINE_DECODE_FLOOR_MESSAGE, VIDEO_JOB_TOO_LARGE + if reason == "window_over_cap": + return WINDOW_OVER_CAP_MESSAGE, VIDEO_JOB_TOO_LARGE if reason == "mps_sequence_over": return MPS_SEQUENCE_OVER_MESSAGE, VIDEO_JOB_TOO_LARGE - if reason == "unmeasured_cell": - return UNMEASURED_CELL_MESSAGE, VIDEO_JOB_TOO_LARGE if reason == "unsupported": return VIDEO_JOB_REJECT_ERRORS["unsupported"] assert reason not in _FIXED_COPY_REASONS # fixed-copy branches took them @@ -946,33 +1157,25 @@ def dropped_duration_message_and_code( def _dropped_duration_list( outcome: IcLoraDurationOutcome, *, job_filter: LocalJobFilter ) -> list[DroppedIcLoraDuration]: - """Catalog-order refusals for every rejected duration.""" + """Catalog-order refusals for every refused duration.""" dropped: list[DroppedIcLoraDuration] = [] - for seconds, reason in outcome.rejected.items(): - message, _ = dropped_duration_message_and_code( - outcome.rejects[seconds], job_filter - ) - reject = outcome.rejects[seconds] - risk = ( - risk_for_reject(reject, job_filter) - if isinstance(reject, VideoJobReject) - else None - ) + for seconds, refused in outcome.refused.items(): + reject = refused.reject + message, _ = dropped_duration_message_and_code(reject, job_filter) + bet = refused.bet + evidence = refused.priced.evidence dropped.append( DroppedIcLoraDuration( value=seconds, - reason=reason, + reason=reject.reason, message=message, - tier=iclora_drop_risk_tier(reason), - over_gib=(risk.over_gib if risk is not None else None), - over_ram_gb=(risk.over_ram_gb if risk is not None else None), - shortfall_kind=(risk.shortfall_kind if risk is not None else None), - readout=( - risk.readout - if risk is not None - else untested_readout() - if reason in ("two_stage_over_measured", "mac_two_stage_unmeasured", "unmeasured_cell") - else None + tier=(bet.tier if bet is not None else None), + over_gib=(bet.over_gib if bet is not None else None), + over_ram_gb=(bet.over_ram_gb if bet is not None else None), + shortfall_kind=(bet.shortfall_kind if bet is not None else None), + readout=(bet.readout if bet is not None else None), + unmeasured_basis=( + evidence.basis if isinstance(evidence, Extrapolated) else None ), ) ) @@ -1022,7 +1225,7 @@ def with_budgeted_duration_controls( stills=catalog_preview_stills(item), tiling=item.default_settings.tiling, ) - if not outcome.rejected: + if not outcome.refused: controls.append(control) continue dropped = _dropped_duration_list(outcome, job_filter=job_filter) diff --git a/backend/runtime_config/ic_lora_local_envelope.py b/backend/runtime_config/ic_lora_local_envelope.py index 3db86b33c..bad846967 100644 --- a/backend/runtime_config/ic_lora_local_envelope.py +++ b/backend/runtime_config/ic_lora_local_envelope.py @@ -1,6 +1,6 @@ """Measured IC-LoRA spatial envelope (LTX-2 1.3.0). -NOT re-measured on 1.4.1. 1.4 moved the reference encode into the chunk flow, so re-run the +NOT re-measured on 1.5.0 or 1.6.0. 1.4+ moved the reference encode into the chunk flow, so re-run the bump gate's IC-LoRA scenarios (``iclora_stage2_on``, ``iclora_day_to_night``) on CUDA and confirm these limits still hold before tightening or loosening them. diff --git a/backend/runtime_config/ic_lora_tiling.py b/backend/runtime_config/ic_lora_tiling.py index 8778507cd..fe5a35386 100644 --- a/backend/runtime_config/ic_lora_tiling.py +++ b/backend/runtime_config/ic_lora_tiling.py @@ -14,23 +14,54 @@ from __future__ import annotations -from pydantic import BaseModel, ConfigDict, Field, model_validator - -# The overlap fraction we request. It is the most upstream accepts, and the least the -# Refine Details card allows ("never lower the overlap below 0.5"). It is a request, not -# the layout: upstream ``split_by_size_pinned`` still caps the tile count so that no cell -# is covered by three tiles. On a 1920x1088 canvas Restore's 960x544 tiles lay out 3x2, -# Refine's 1024x576 tiles 2x2. The count does not bind the peak: tiles run sequentially, -# so one tile plus the canvas decode is the whole ask — six tiles peak at tile + 1.28, -# not at six tiles. -IC_LORA_TILE_OVERLAP = 0.5 +import json +from pathlib import Path +from typing import Final, Literal + +from pydantic import BaseModel, ConfigDict, Field, ValidationError, model_validator + +# The limits and the defaults of the tile overlap and the window carry. The advanced controls +# of the Home form read the same file (shared/ic-lora-tiling-controls.json). +_CONTROLS_PATH: Final = Path(__file__).resolve().parents[2] / "shared" / "ic-lora-tiling-controls.json" +_CONTROLS: Final = json.loads(_CONTROLS_PATH.read_text(encoding="utf-8")) + +# A run can replace the tile of the catalog entry with one of these. No size keeps the catalog +# tile. The budget prices the tile that runs. +IcLoraTileSize = Literal["large", "extra-large"] +TILE_SIZES: Final[dict[str, tuple[int, int]]] = { + name: (size["long"], size["short"]) for name, size in _CONTROLS["tileSizes"].items() +} + +MIN_TILE_OVERLAP: Final[float] = _CONTROLS["overlap"]["min"] +MAX_TILE_OVERLAP: Final[float] = _CONTROLS["overlap"]["max"] + +# The overlap fraction we request when a run sets none. It is the most upstream accepts, and the +# best for quality. A run can lower it down to ``MIN_TILE_OVERLAP`` for speed, and the cost is +# a risk of visible seams. It is a request, not the layout: upstream ``split_by_size_pinned`` +# still caps the tile count so that no cell is covered by three tiles. On a 1920x1088 canvas +# Restore's 960x544 tiles lay out 3x2, Refine's 1024x576 tiles 2x2. The count does not bind +# the peak: tiles run sequentially, so one tile plus the canvas decode is the whole ask — +# six tiles peak at tile + 1.28, not at six tiles. +# +# At 0 the tiles still overlap, because the layout needs the tiles to cover the frame. +IC_LORA_TILE_OVERLAP: Final[float] = _CONTROLS["overlap"]["default"] _TILE_GRID = 32 # pixel multiple of the transformer latent grid _FRAME_GRID = 8 # pixel frames per latent frame; windows are 8k + 1 frames # ltx-pipelines refuses a window carry shorter than three latent frames (17 pixel frames). -_MIN_CARRY_FRAMES = 2 * _FRAME_GRID + 1 +MIN_CARRY_FRAMES: Final[int] = _CONTROLS["carryFrames"]["min"] +# The shortest window a run can set: more than twice the shortest carry (see ``IcLoraTiling``). +MIN_WINDOW_FRAMES: Final[int] = 2 * MIN_CARRY_FRAMES + _FRAME_GRID - 1 # ltx-pipelines default carry, kept by a tiling that sets a window and no carry. -DEFAULT_CARRY_FRAMES = 25 +DEFAULT_CARRY_FRAMES: Final[int] = _CONTROLS["carryFrames"]["default"] +# The carry of a high cell (1440p, 2160p) when a run sets none. The shortest working window +# follows the carry, so a short carry keeps the windows short (``ic_lora_high_res``). +HIGH_RES_CARRY_FRAMES: Final[int] = _CONTROLS["carryFrames"]["highResDefault"] +# The carries a run can pick in the form. Auto searches the ones at or below its carry. +CARRY_PRESETS: Final[tuple[int, ...]] = tuple(_CONTROLS["carryFrames"]["presets"]) +# The longest maximum window a run can set on an adaptive LoRA. Restore documents that detail is +# lost and colour drifts past 97 frames. +ADAPTIVE_MAX_WINDOW_FRAMES: Final[int] = _CONTROLS["windowFrames"]["max"] class IcLoraTiling(BaseModel): @@ -43,8 +74,20 @@ class IcLoraTiling(BaseModel): frames detail is lost and colour drifts). A clip longer than the window always runs in windows of this length. None leaves the choice to the job budget. + ``adaptive_window`` leaves the window to the job budget for a LoRA that has no measured + drift length (Refine Details). The budget picks the longest window that fits, up to the cap + of the resolution (``ic_lora_adaptive_window``). It excludes ``window_frames``, because a + fixed window chunks every longer clip. ``max_window_frames`` is the run's own maximum + for it. None keeps the cap of the resolution. + ``carry_frames`` is the part of a window that the next window re-renders and pins at - its start. It needs a ``window_frames``. None keeps ``DEFAULT_CARRY_FRAMES``. + its start. It needs a ``window_frames`` or an ``adaptive_window``. None keeps + ``DEFAULT_CARRY_FRAMES``. ``carry_pinned`` is set when the run chose the carry. An adaptive + run that did not is on Auto carry: ``carry_frames`` is then the longest carry that Auto may + use, and the job budget picks the carry that is safest (``ic_lora_auto_carry``). + + ``overlap_fraction`` is the share of a tile that the next tile covers again. A smaller + share means fewer tiles per step, and a faster run with a higher risk of seams. ``max_output_long_side`` and ``max_output_short_side`` raise the spatial cap of the job for this LoRA. The transformer sees one tile at a time, so the output can be @@ -55,7 +98,11 @@ class IcLoraTiling(BaseModel): long_side: int = Field(ge=64) short_side: int = Field(ge=64) window_frames: int | None = Field(default=None, ge=9) - carry_frames: int | None = Field(default=None, ge=_MIN_CARRY_FRAMES) + adaptive_window: bool = False + max_window_frames: int | None = Field(default=None, ge=9) + carry_frames: int | None = Field(default=None, ge=MIN_CARRY_FRAMES) + carry_pinned: bool = False + overlap_fraction: float = Field(default=IC_LORA_TILE_OVERLAP, ge=MIN_TILE_OVERLAP, le=MAX_TILE_OVERLAP) max_output_long_side: int | None = Field(default=None, ge=64) max_output_short_side: int | None = Field(default=None, ge=64) @@ -67,20 +114,30 @@ def _check_grid(self) -> "IcLoraTiling": raise ValueError("short_side must not exceed long_side") if self.window_frames is not None and (self.window_frames - 1) % _FRAME_GRID: raise ValueError(f"window_frames must be {_FRAME_GRID}k + 1") + if self.adaptive_window and self.window_frames is not None: + raise ValueError("an adaptive window takes no window_frames") + if self.max_window_frames is not None: + if not self.adaptive_window: + raise ValueError("max_window_frames needs adaptive_window") + if (self.max_window_frames - 1) % _FRAME_GRID: + raise ValueError(f"max_window_frames must be {_FRAME_GRID}k + 1") + if self.max_window_frames > ADAPTIVE_MAX_WINDOW_FRAMES: + raise ValueError(f"max_window_frames cannot exceed {ADAPTIVE_MAX_WINDOW_FRAMES} frames") if self.carry_frames is not None: - if self.window_frames is None: + if self.window_frames is None and not self.adaptive_window: raise ValueError("carry_frames needs window_frames") if (self.carry_frames - 1) % _FRAME_GRID: raise ValueError(f"carry_frames must be {_FRAME_GRID}k + 1") - if self.carry_frames >= self.window_frames: + if self.window_frames is not None and self.carry_frames >= self.window_frames: raise ValueError("carry_frames must be below window_frames") - if self.window_frames is not None: - # A middle window keeps window - carry frames. Upstream cross-fades the whole - # carry, and it needs the cross-fade to be shorter than the kept frames. A - # window without its own carry runs with the default one. - carry = DEFAULT_CARRY_FRAMES if self.carry_frames is None else self.carry_frames - if self.window_frames <= 2 * carry: - raise ValueError("window_frames must be more than twice carry_frames") + # A middle window keeps window - carry frames. Upstream cross-fades the whole + # carry, and it needs the cross-fade to be shorter than the kept frames. A + # window without its own carry runs with the default one. + carry = DEFAULT_CARRY_FRAMES if self.carry_frames is None else self.carry_frames + if self.window_frames is not None and self.window_frames <= 2 * carry: + raise ValueError("window_frames must be more than twice carry_frames") + if self.max_window_frames is not None and self.max_window_frames <= 2 * carry: + raise ValueError("The maximum chunk length must be more than twice the carry.") if (self.max_output_long_side is None) != (self.max_output_short_side is None): raise ValueError("set both max_output sides or neither") if ( @@ -91,6 +148,11 @@ def _check_grid(self) -> "IcLoraTiling": raise ValueError("max_output_short_side must not exceed max_output_long_side") return self + @property + def auto_carry(self) -> bool: + """True when the job budget picks the carry: an adaptive window and no carry chosen by the run.""" + return self.adaptive_window and not self.carry_pinned + def output_cap(self) -> tuple[int, int] | None: """(long, short) cap of the output size, or None for the local 1080p cell.""" if self.max_output_long_side is None or self.max_output_short_side is None: @@ -115,3 +177,70 @@ def transformer_pass_size(width: int, height: int, tiling: IcLoraTiling | None) if tiling is None: return width, height return tiling.tile_size(width, height) + + +def auto_carry_candidates(bound: int, max_window_frames: int | None) -> list[int]: + """The carries Auto can run, longest first: the presets up to ``bound``, and ``bound``. + + A carry stays a candidate only when the maximum chunk length is more than twice the carry. + """ + carries = sorted({bound, *(c for c in CARRY_PRESETS if MIN_CARRY_FRAMES <= c <= bound)}, reverse=True) + fitting = [c for c in carries if max_window_frames is None or max_window_frames > 2 * c] + return fitting or [bound] + + +def with_tiling_overrides( + tiling: IcLoraTiling, + *, + overlap_fraction: float | None, + carry_frames: int | None, + tile_size: IcLoraTileSize | None = None, + max_window_frames: int | None = None, +) -> IcLoraTiling: + """The tiling of a run that sets its own overlap, carry, tile size or maximum chunk length. + + None keeps the tiling's value. The maximum chunk length is the longest window the run may + use. A LoRA with a fixed window always chunks at it, so a shorter maximum becomes the window + and a longer one is refused: it is outside what the LoRA ran at. An adaptive LoRA keeps the + maximum as a limit. The cap of the resolution applies later, in the job budget, which knows + the canvas (a longer decode window stalled the VAE at 4K). + + Raises ``ValueError`` for a pair the pipeline cannot run, for example a carry that + leaves no frames in a middle window. + """ + window_field = "max_window_frames" if tiling.adaptive_window else "window_frames" + if max_window_frames is not None and not tiling.adaptive_window: + if tiling.window_frames is None: + raise ValueError("this LoRA runs without a fixed window") + if max_window_frames > tiling.window_frames: + raise ValueError( + f"max_window_frames cannot exceed the {tiling.window_frames} frames of the catalog window" + ) + updates: dict[str, object] = { + name: value + for name, value in ( + ("overlap_fraction", overlap_fraction), + ("carry_frames", carry_frames), + (window_field, max_window_frames), + ) + if value is not None + } + if carry_frames is not None: + updates["carry_pinned"] = True + elif tiling.auto_carry and max_window_frames is not None: + # Auto carry under a chosen maximum: start from the longest carry that leaves a valid window. + bound = DEFAULT_CARRY_FRAMES if tiling.carry_frames is None else tiling.carry_frames + updates["carry_frames"] = auto_carry_candidates(bound, max_window_frames)[0] + if tile_size is not None: + updates["long_side"], updates["short_side"] = TILE_SIZES[tile_size] + if not updates: + return tiling + try: + return IcLoraTiling.model_validate({**tiling.model_dump(), **updates}) + except ValidationError as exc: + # The validator raises ValueError. Pydantic stores that exception on the error. + # Reading it avoids a parse of the "Value error, " prefix, which is Pydantic text. + original = exc.errors()[0].get("ctx", {}).get("error") + if not isinstance(original, Exception): + raise ValueError("invalid tiling") from exc + raise ValueError(str(original)) from exc diff --git a/backend/runtime_config/local_compat_matrix.py b/backend/runtime_config/local_compat_matrix.py index 254c75a27..3511db19e 100644 --- a/backend/runtime_config/local_compat_matrix.py +++ b/backend/runtime_config/local_compat_matrix.py @@ -16,10 +16,10 @@ LTXVideoGenerationResolutionSpec, ) from frame_math import compute_num_frames +from runtime_config.budget_admission import Admitted from runtime_config.ic_lora_job_budget import ( HOME_IC_LORA_PREVIEW_SETTINGS, MAC_IC_LORA_FLOOR_GIB, - IcLoraJobLoad, catalog_preview_stage1, decide_ic_lora_job, ) @@ -48,6 +48,7 @@ LocalJobFilter, MemoryBudget, advertised_fast_durations, + mac_disk_stream_host_gib, memory_gb_for_job, ) @@ -185,7 +186,10 @@ def _band_pool_bytes(band: _Band) -> int | None: def _band_filter(band: _Band) -> LocalJobFilter: - """Hardware class as the same filter the app serves, with nominal bytes.""" + """Hardware class as the same filter the app serves, with nominal bytes. + + Strict mode: the published matrix lists only what the lab has measured. + """ return LocalJobFilter( profile=HardwareProfile( system=band.system, @@ -199,6 +203,7 @@ def _band_filter(band: _Band) -> LocalJobFilter: memory_gb=_job_memory(band), mps_pool_bytes=_band_pool_bytes(band), ), + budget_mode="cautious", ) @@ -229,14 +234,14 @@ def _ic_lora_viable(band: _Band) -> bool: on 12-20 GB cards where this returns True. """ stage1_w, stage1_h = catalog_preview_stage1(HOME_IC_LORA_PREVIEW_SETTINGS) - decision = decide_ic_lora_job( + admission = decide_ic_lora_job( stage1_w, stage1_h, compute_num_frames(5, 24), stage_mode=HOME_IC_LORA_PREVIEW_SETTINGS.stage_mode, job_filter=_band_filter(band), ) - return isinstance(decision, IcLoraJobLoad) + return isinstance(admission, Admitted) def _retake_extend_cell(feature: LtxCapabilityFeature, band: _Band) -> str: @@ -304,8 +309,8 @@ def render_compat_matrix() -> str: "Retake/Extend rows are viability + RAM floor (`Yes*` — VRAM depends on", "your source length): no canonical input exists for a representative", "cell, but the floor is input-free. Bands carry no drive class, so", - "Windows bands take the CPU path (64 GB floor; NVMe maps from disk at", - "32 GB instead).", + "Windows bands take the CPU path (64 GB floor; NVMe streams from disk at", + f"{WINDOWS_EDIT_DISK_STREAMING_RAM_GB} GB instead).", "Regenerate: `cd backend && uv run python -m runtime_config.local_compat_matrix`.", "", "| " + " | ".join(headers) + " |", @@ -322,7 +327,8 @@ def render_compat_matrix() -> str: f"Windows streamed Fast needs **{windows_ram_floor}** GiB total RAM;", f"Darwin **{DARWIN_ADVERTISED_FLOOR_GB}** GiB total RAM and macOS **{DARWIN_MIN_MACOS_MAJOR}** or later", "(macOS 14 and 15 run the app but not local generation); Fast cells gate on the MPS pool", - f"({MAC_FAST_FLOOR_GIB} GiB floor); ~72 GB disk for the 2.5 Fast core pack", + f"({MAC_FAST_FLOOR_GIB} GiB floor, plus {mac_disk_stream_host_gib(get_latest_ltx_model_id()):.2f} GiB", + "of loader host buffers); ~72 GB disk for the 2.5 Fast core pack", "(kitchen-sink installs with 2.3, image models, and processors are larger).", "", f"CUDA stream ({_CUDA_STREAM_EXAMPLE_GB} GB) still runs T2V/I2V/A2V;", @@ -330,22 +336,21 @@ def render_compat_matrix() -> str: f"because `decide_video_job` would reject them. CUDA full ({CUDA_FULL_VRAM_GB} GB)", "keeps those cells (they stream) except 1080p/20s, whose stream ask exceeds `CUDA_FULL_VRAM_GB`.", "Darwin stream gates each Fast cell against the sampled MPS", - f"pool (M2/F1 model, {MAC_FAST_FLOOR_GIB} GiB floor); the 48 GB example keeps the full grid except 1080p/20s", + f"pool (M2/F1 model, {MAC_FAST_FLOOR_GIB} GiB floor); the 48 GB example keeps the full grid (1080p/20s in windows)", f"(nominal {NOMINAL_MPS_POOL_RATIO} pool ratio — min of 2 F0 probes, SKU-dependent).", "", - f"Windows stream ({_WINDOWS_STREAM_VRAM_GB} GB VRAM, {_WINDOWS_STREAM_RAM_GB} GB RAM) runs", - "the limited grid (540p through 20s, 720p through 10s, 1080p through 6s); 24 GB VRAM runs the", - "full grid including 1080p/10s, and 12 GB VRAM runs 540p through 10s plus 720p", - f"through 8s (no 1080p — the 5s cell needs 14.14 reserved). Below {windows_ram_floor} GB RAM, streamed Fast cells are not", + f"Windows stream ({_WINDOWS_STREAM_VRAM_GB} GB VRAM, {_WINDOWS_STREAM_RAM_GB} GB RAM) runs every Fast cell", + "through 1080p/20s, in time windows where one pass does not fit (1080p/10s runs in 3); what each card size runs is in", + f"`docs/hardware-compatibility.md`. Below {windows_ram_floor} GB RAM, streamed Fast cells are not", f"offered (`ram_shortfall`). Streamed edit cells gate on E3-measured floors ({WINDOWS_EDIT_CPU_STREAMING_RAM_GB} GB CPU,", f"{WINDOWS_EDIT_DISK_STREAMING_RAM_GB} GB NVMe DISK); streamed IC-LoRA on L5-measured floors ({WINDOWS_ICLORA_CPU_STREAMING_RAM_GB} GB CPU,", - f"{WINDOWS_ICLORA_DISK_STREAMING_RAM_GB} GB DISK, L5-48 holds both temps). The live picker lists every total-fitting cell;", + f"{WINDOWS_ICLORA_DISK_STREAMING_RAM_GB} GB DISK, L5-32 holds both temps). The live picker lists every total-fitting cell;", "GenSpace refuses cells over free VRAM at click, and queued jobs re-check at execute.", - f"On NVMe drives, streamed Fast maps weights from disk and the RAM floor is **{WINDOWS_FAST_DISK_STREAMING_RAM_GB}** GiB instead.", + f"On NVMe drives below {windows_ram_floor} GB, streamed Fast reads weights from disk and the RAM floor is **{WINDOWS_FAST_DISK_STREAMING_RAM_GB}** GiB instead.", "", "1440p and 4K Fast cells run long clips in overlapping time windows, and the job budget prices one window.", - "1440p and 4K are offered for Fast, A2V and the Home recipes; Retake, Extend and IC-LoRA need `highResVideoToVideo`. Both are provisional, and", - "the Mac window extra is a copy of the Windows one. The cells above are the 24 fps / 16:9 anchor and do not list these two rows.", + "1440p and 4K are offered for Fast, A2V and the Home recipes; Retake, Extend and IC-LoRA need `highResVideoToVideo` (Refine Details does not). Both are provisional;", + "Windows and Mac each fit their own window extra. The cells above are the 24 fps / 16:9 anchor and do not list these two rows.", "", ] ) diff --git a/backend/runtime_config/local_runtime.py b/backend/runtime_config/local_runtime.py index 011624cda..f11a66708 100644 --- a/backend/runtime_config/local_runtime.py +++ b/backend/runtime_config/local_runtime.py @@ -18,6 +18,7 @@ class LocalRuntimeConfigKwargs(TypedDict): darwin_unified_memory: bool system: str vram_bytes: int | None + usable_vram_bytes: int | None total_ram_bytes: int | None checkpoint_drive_type: DriveType | None gpu_device_name: str | None @@ -36,6 +37,7 @@ class LocalRuntime: checkpoint_drive_type: DriveType | None gpu_device_name: str | None fp8_capable: bool + usable_vram_bytes: int | None = None def runtime_config_kwargs( self, @@ -49,6 +51,7 @@ def runtime_config_kwargs( "darwin_unified_memory": self.darwin, "system": self.system, "vram_bytes": self.vram_bytes, + "usable_vram_bytes": self.usable_vram_bytes, "total_ram_bytes": self.total_ram_bytes, "checkpoint_drive_type": self.checkpoint_drive_type, "gpu_device_name": self.gpu_device_name, @@ -68,6 +71,7 @@ def resolve_local_runtime( mps_available = gpu_info.get_mps_available() vram_gb = gpu_info.get_vram_total_gb() vram_bytes = gpu_info.get_cuda_total_vram_bytes() + usable_vram_bytes = gpu_info.get_free_cuda_vram_bytes() total_ram_bytes = gpu_info.get_total_ram_bytes() # Darwin has no discrete VRAM (unified memory). Eligibility uses *total* RAM # (``get_vram_total_gb`` / SKU). Job sizing still uses free RAM at launch. @@ -104,6 +108,7 @@ def resolve_local_runtime( darwin=system == "Darwin", system=system, vram_bytes=vram_bytes, + usable_vram_bytes=usable_vram_bytes, total_ram_bytes=total_ram_bytes, checkpoint_drive_type=storage_info.get_drive_type(), gpu_device_name=gpu_info.get_device_name(), diff --git a/backend/runtime_config/lora_catalog.json b/backend/runtime_config/lora_catalog.json index 0bf8f8608..2d3366f7a 100644 --- a/backend/runtime_config/lora_catalog.json +++ b/backend/runtime_config/lora_catalog.json @@ -103,6 +103,7 @@ ], "trigger": "crtanim,", "recommended_strength": 1.0, + "default_negative_prompt": "blurry, low quality, jpeg artifacts, compression artifacts, watermark, signature", "media": { "demo_video": "crt_animation_terminal_demo.mp4" }, @@ -891,6 +892,7 @@ "trigger": "CINEMAGRAPH_MOTION", "trigger_placement": "first_token", "recommended_strength": 2.0, + "default_negative_prompt": "camera movement, pan, tilt, zoom, parallax, whole image moving, background sliding, person moving, flicker on entire image, noisy texture, crawling texture, distorted, blurry, low quality", "media": { "demo_video": "cinemagraph_demo.mp4" }, @@ -1410,6 +1412,7 @@ "resolution_factor": 1.5, "audio_mode": "source" }, + "default_negative_prompt": "person, people, human, figure, limb, arm, hand, leg, body part, shadow of a person, leftover people, leftover figures, ghosting, semi-transparent remnants, blurry, soft, distorted, inconsistent motion, jitter, worst quality, cartoon, video game, ugly", "enhancement_examples": [ "An empty clean plate of the exact same scene: a colorful wooden fishing boat with identical painted hull, fishing nets, ropes and gear floating on calm blue sea, with the same distant boat, rocky breakwater shoreline, water and clear sky as the source video, but with no one aboard. No people, no humans, no men, no fishermen, no figures, and no body parts such as heads, arms, hands or legs anywhere in the frame, on the boats or in the background. No cast shadows or reflections of people on the boat or water. Static photorealistic footage, natural daylight, high detail. Keep the boats, nets and background intact.", "An empty clean plate of the exact same location: a modern open-plan office with identical desks, office chairs, monitor dividers, concrete pillar, exposed ceiling with pipes and acoustic panels, large windows with city view, floor and lighting as the source video. No people, no humans, no figures, and no body parts such as faces, arms, hands or legs anywhere in the frame. No backpack, no ID badge, no lanyard anywhere in the frame. No cast shadows from people on the floor or walls. Static photorealistic footage, natural indoor light, high detail.", @@ -1584,6 +1587,7 @@ "audio_mode": "source", "lora_strength": 1 }, + "default_negative_prompt": "daytime, bright sunlight, blue sky, overexposed, worst quality, inconsistent motion, blurry, jittery, distorted", "enhancement_examples": [ "A realistic nighttime outdoor scene. A mountain landscape under a dark sky filled with bright stars and a prominent Milky Way. Deep natural shadows across the terrain with very faint ambient starlight. Photorealistic night. Only the lighting changes from day to night; identical composition, framing, camera movement and motion.", "A realistic nighttime scene. A cafe interior looking out at a dark city street at night. Warm overhead interior lights cast amber reflections on the furniture, contrasting with the cool ambient streetlights and deep shadows outside. Only the lighting changes from day to night; identical composition, framing, camera movement and motion.", @@ -1858,6 +1862,7 @@ "resolution_factor": 1.5, "audio_mode": "source" }, + "default_negative_prompt": "worst quality, blurry, out of focus, defocused, soft, hazy, smeared, low detail, jittery, distorted, oversharpened, haloing, ringing", "prompt_template": { "template": "Reference shows {reference}, heavily out of focus with soft defocused blur. Edited shows the same scene in sharp focus with crisp detail. DEBLUR {result}.", "placeholders": { @@ -1931,7 +1936,8 @@ "skip_stage_2": true, "resolution_factor": 1.5, "audio_mode": "source" - } + }, + "default_negative_prompt": "worst quality, inconsistent motion, blurry, jittery, distorted, normal eyes, straight eyes, corrected eyes, gaze correction" }, { "id": "water-simulation", @@ -2016,6 +2022,7 @@ "resolution_factor": 1.5, "audio_mode": "source" }, + "default_negative_prompt": "worst quality, inconsistent motion, blurry, jittery, distorted, deformed water, unnatural fluid, frozen water, morphing face, shifting features, inconsistent clothing, warped features", "prompt_template": { "template": "Reference shows {reference}. Edited shows the same scene with water added. ADD WATER {result}.", "placeholders": { @@ -2131,6 +2138,7 @@ "resolution_factor": 1.5, "audio_mode": "generated" }, + "default_negative_prompt": "worst quality, inconsistent motion, blurry, jittery, distorted", "enhancement_examples": [ "Reference sheet: Top Row Left (Setting): A modern \"FreshMart\" grocery store exterior with a grey facade, a prominent green awning displaying the FreshMart logo (a leaf inside a shopping cart), and a white delivery car parked in front on a dark asphalt lot under a bright, partly cloudy sky. Top Row Middle (Setting): A long, brightly lit interior aisle of a grocery store fully stocked with various colorful packaged products on tall shelves, with polished floors reflecting the overhead fluorescent lights. Top Row Right (Character): A 3D animated owl mascot shown from multiple angles (front, sides, back, 3/4 view). The owl has grey and white feathers, large expressive eyes, and wears a green short-sleeved polo shirt, a dark green apron with the FreshMart logo, and a green visor cap. Middle Row Left (Props): Dark blue reusable shopping tote bags with bright green handles and trim. One features the FreshMart logo, and another features the text \"FRESH CHOICES, BETTER LIVING\". Middle Row Right (Props): Multiple angles (front, back, side) of a white 5-door FreshMart delivery hatchback car featuring the FreshMart logo on the side doors and a roof sign. Bottom Row Left (Props): Close-up angles of the FreshMart tote bags, showing their sturdy boxy shape, green fabric trim, and folded handles. Bottom Row Right (Logo): The standalone FreshMart logo featuring a minimalist shopping cart with a green leaf design above bold green text. Generated video: A bright, high-quality 3D animated commercial shot set outside a modern \"FreshMart\" grocery store exterior during a sunny day. The camera holds a steady, static wide shot. In the foreground, standing on the grey pavement, is a cheerful 3D animated owl mascot with grey and white feathers, large expressive eyes, and a small yellow beak. The owl is dressed in a green short-sleeved polo shirt, a dark green apron featuring the FreshMart logo, and a matching green visor cap. Parked directly behind and slightly to the right of the owl is a white 5-door FreshMart delivery hatchback car with the store's leaf-and-cart logo on the side doors and a small roof sign. The store's grey facade and prominent green awning form the background, with the sliding glass entrance doors visible behind the character. The owl warmly spreads its wings outward and upward in an inviting, energetic welcoming gesture, blinking its large eyes naturally. It looks directly into the camera lens with a joyful, enthusiastic expression and opens its beak, confidently delivering its lines: \"Welcome to FreshMart, where we're always ready to help you load up with everything you need. Fresh choices, better living!\" The lighting is crisp and commercial, casting soft natural shadows on the asphalt and highlighting the clean, vibrant green accents of the store.", "Reference sheet: Top Row (Character): A 3D animated young, athletic man shown from multiple turnaround angles. He has short brown hair and brown eyes. He wears a teal hooded sleeveless vest with a high collar over a dark grey undershirt, brown leather bracers on his forearms, a cross-body leather satchel strap, brown pants with thick brown boots, and a glowing blue crystal pendant necklace. Middle Row Left (Prop): A casual short-sleeved button-up Hawaiian shirt in a light cream color, covered with large green tropical pine and palm leaf patterns. Middle Row Right (Prop): A brightly colored tropical soda can shown from three angles. The can has a yellow top transitioning to a teal bottom with abstract wave designs and a silver pull tab. Bottom Row Left (Prop): A magical wooden staff made of dark brown twisting wood. The top holds a large, sharp, glowing blue crystal bound tightly to the wood by dark leather straps. Bottom Row Right (Setting): A bright, sunny open-air tropical beach bar with wooden railings, sturdy wooden pillars, and warm hanging lantern lights. The background features a pristine white sand beach, lush green trees, and clear turquoise ocean water beneath a bright blue sky. Generated video: A vibrant, high-quality 3D animated cinematic shot set inside a sun-drenched, open-air tropical beach bar. The camera frames a steady medium shot of the young, athletic man with short brown hair leaning casually near a sturdy wooden pillar. He is dressed in the light cream Hawaiian shirt covered in green palm leaf patterns, layered under the teal hooded sleeveless vest, wearing brown leather bracers and the glowing blue crystal pendant necklace. In his right hand, he firmly grips the twisting dark wooden staff with the glowing blue crystal at the top. In his left hand, he holds the brightly colored yellow and teal tropical soda can. He takes a slow, deep breath of the ocean air, looking slightly off-camera before turning his warm brown eyes forward. A soft, contented smile spreads across his face as he slightly raises the soda can in a subtle toasting motion. He speaks smoothly in a relaxed and satisfied way: \"Nothing beats a cold drink after a long quest.\" He pauses for a beat, his smile widening as he gently shakes the can, adding: \"Pure magic!\" The background features a shallow depth of field, showcasing the pristine white sand, lush green trees, and clear turquoise ocean water. Warm, bright daylight illuminates his face, casting natural shadows, while a gentle ocean breeze slightly rustles his hair and the collar of his shirt.", @@ -2216,6 +2224,7 @@ "resolution_factor": 1.5, "audio_mode": "source" }, + "default_negative_prompt": "beard, mustache, facial hair, stubble, worst quality, inconsistent motion, blurry, jittery, distorted", "trigger_placement": "first_token" }, { @@ -2986,7 +2995,8 @@ "short_side": 544, "window_frames": 97 } - } + }, + "default_negative_prompt": "blocky compression, banding, mosquito noise, ringing, blurry, soft, plastic, smeared detail, ghosting, oversharpened halos, warped faces, low resolution" }, { "id": "refine-details", @@ -3068,9 +3078,11 @@ "tiling": { "long_side": 1024, "short_side": 576, - "window_frames": 73 + "adaptive_window": true, + "overlap_fraction": 0.25 } - } + }, + "default_negative_prompt": "blurry, soft, plastic, smeared detail, oversharpened halos, warped faces" } ] } diff --git a/backend/runtime_config/ltx_capabilities.py b/backend/runtime_config/ltx_capabilities.py index 88abd506a..f537efd12 100644 --- a/backend/runtime_config/ltx_capabilities.py +++ b/backend/runtime_config/ltx_capabilities.py @@ -374,21 +374,13 @@ def budget_shape( *, mode: CanvasMode, ) -> tuple[int, int]: - """Denoised shape: the 16:9 anchor widened to the selected ratio. - - The shared duration/picker lists are the anchor; only a wider frame can - exceed it. Single source for every budget call site (generate, estimate, - queue preflights, specs). Unsnapped by design: the 64-grid snap prices - display pixels, and every call site prices this same anchor so verdicts - agree with each other. The unsnapped-vs-snapped delta (up to ~0.6 GiB on - legacy 270p/360p at 48-50 fps) applies identically on both sides of every - create/execute comparison, so it cannot skew them. + """Denoised shape for the selected resolution and aspect ratio. + + Single source for every budget call site (generate, estimate, queue + preflights, specs) so list-time per-aspect duration tables, queue + preflights, and execute-time admission price the exact same canvas. """ - anchor_width, anchor_height = budget_size(local_canvas(resolution, mode=mode)) - selected_width, selected_height = budget_pixels(caps, resolution, aspect, mode=mode) - if selected_width * selected_height > anchor_width * anchor_height: - return selected_width, selected_height - return anchor_width, anchor_height + return budget_pixels(caps, resolution, aspect, mode=mode) def pixels_for( diff --git a/backend/runtime_config/measured_cells.py b/backend/runtime_config/measured_cells.py index de6f0974b..0e6ac15f3 100644 --- a/backend/runtime_config/measured_cells.py +++ b/backend/runtime_config/measured_cells.py @@ -1,8 +1,8 @@ """Which 1440p and 4K cells have a measured run behind them. The budget laws are fitted at and below 1080p. A 1440p or 4K cell that no run has -confirmed prices off an extrapolation, so it is an unmeasured bet: Standard mode -refuses it and Reckless mode allows it with an unmeasured warning. This module is the +confirmed prices off an extrapolation, so it is an unmeasured bet: Cautious mode +refuses it and Brave mode allows it with an unmeasured warning. This module is the only place that says which cells are measured. Adding a row here is how a cell opens for everyone. Imports nothing internal by design. @@ -10,7 +10,11 @@ from __future__ import annotations -from typing import Final, Literal +from dataclasses import dataclass +from typing import TYPE_CHECKING, Final, Literal, Never + +if TYPE_CHECKING: + from api_types import LTXLocalModelId BudgetFeature = Literal["fast", "edit", "iclora"] BudgetRoute = Literal["mac_measured", "windows_measured", "legacy"] @@ -36,40 +40,155 @@ # longest completed run: the Mac peak is flat past the third window, but a 15-window job # takes about 6 hours, past any run the heartbeat has covered. ("fast", "mac_measured", "2160p"): 7, + # Mac Fast 1440p: capped runs bracket the allocator edge at 1, 2 and 5 windows of 129 frames, and the + # 5-window job ran to completion, so a longer job is unmeasured. The Mac peak is flat from the third + # window; a 9-window job takes about 4 hours, past any run the heartbeat has covered. Shorter windows + # (smaller pools, and the 9:16 and 21:9 canvases, whose longest window is shorter) carry no floor: the + # windowed term is priced as a share of the window's tokens, which only the Windows runs show. If that + # is wrong, the job runs out of memory in the second or third window, and since the frontier records + # clean runs only, Cautious keeps offering it. + ("fast", "mac_measured", "1440p"): 5, # Windows Fast 1440p: the fence is the 129-frame windows, which a 32 GB card runs and - # which are measured to five windows. Small cards fall back to 41-frame windows, measured - # flat to twenty, but a window count cannot tell the two sizes apart, so those jobs past - # five windows stay unmeasured and refuse in Standard mode. Raising this to twenty would - # open 129-frame jobs of six to twenty windows that no run covers. - ("fast", "windows_measured", "1440p"): 5, - # Windows Fast 4K: held flat from the third window through fifteen (a 50 fps job). + # which are measured flat from the third window through nine (20 s at 48 fps, 961 frames). + # Small cards fall back to 41-frame windows, measured flat to twenty, but a window count + # cannot tell the two sizes apart, so jobs past nine windows stay unmeasured and refuse in + # Cautious mode. Raising this to twenty would open 129-frame jobs of ten to twenty windows + # that no run covers. Non-16:9 aspects (9:16, 1:1, 21:9) sit inside the same token law. + ("fast", "windows_measured", "1440p"): 9, + # Windows Fast 4K: held flat from the third window through fifteen (a 50 fps job, T2V and A2V). + # Non-16:9 aspects (9:16, 1:1) sit inside the same token law (9:16 matches 16:9 per-window to 0.00 GiB). ("fast", "windows_measured", "2160p"): 15, + # Windows Edit 1440p: Retake and Extend never chunk (1 window) and sit inside the 1080p + # reserved law through 193 frames (90,000 tokens, 29.50 GiB vs 29.93 ask; Retake == Extend). + ("edit", "windows_measured", "1440p"): 1, + # Windows Edit 4K: untiled-in-time vae_decode (3.15 + 3.222e-4 * t_decode) is priced in + # _EDIT_DECODE_STREAM and verified clean through 73,440 single-tile decode tokens (65 frames + # at 3840x2176, 26.83 GiB reserved, shared_peak 0.08 GB); decode tiles past 73,440 tokens + # stay unmeasured via MEASURED_MAX_DECODE_TOKENS. + ("edit", "windows_measured", "2160p"): 1, + # Windows IC-LoRA 1440p: the peak grows from the second to the third window and holds flat + # through the fifth (2x2 tiles of 1920x1088, 41-frame windows with carry 17). + ("iclora", "windows_measured", "1440p"): 5, # Windows IC-LoRA 4K: the peak grows through the fourth window and holds to the tenth. ("iclora", "windows_measured", "2160p"): 10, - # Not measured, so absent: Mac 1440p (measured on native runs only, the allocator edge - # never capped), Mac IC-LoRA (the per-Mpx canvas term is a Windows number), Mac edits - # above 1080p (past the fitted token range) and any job past the window counts above. + # Not measured, so absent: Mac IC-LoRA (the per-Mpx canvas term is a Windows number), + # Mac edits above 1080p (past the fitted token range), Windows 4K edits past the 73,440-token + # single-tile decode ceiling (see MEASURED_MAX_DECODE_TOKENS below), and any job past the window + # counts above. +} + + +# (feature, route) -> the largest single-decode-tile token count that a measured run covers +# cleanly without WDDM paging. Upstream DiffVAE splits the frame axis past 80 frames (largest +# 8k+1 untiled window: 73 frames), so a single temporal decode tile processes at most 73 frames. +# Any decode tile with more tokens than this ceiling is an unmeasured bet. +MEASURED_MAX_DECODE_TOKENS: Final[dict[tuple[BudgetFeature, BudgetRoute], float]] = { + # Windows Edit: 4K 49f (57,120 decode tokens, 21.57 GiB) and 4K 65f (73,440 decode tokens, + # 26.83 GiB) ran with zero WDDM paging (shared_peak 0.08 GB), and 1440p 193f (36,000 decode + # tokens per 73f tile) ran clean at 29.50 GiB; 4K 73f (81,600 decode tokens, 29.45 GiB) paged. + ("edit", "windows_measured"): 73_440.0, } -# (feature, route) -> (the longest job in windows, the smallest card in GiB) that a measured run -# covers on a canvas below 1440p that runs in windows because one pass cannot fit the card -# (``fast_chunking``). The window rule holds every window to the token size the budget rows were -# fitted at, so the canvas needs no row of its own: the window count and the card are what a run -# confirms. A job in more windows than the row is an unmeasured bet, as past the rows above. A card -# below the run's size, or a route with no row, keeps its single-pass refusals: the small-card -# envelopes were measured on single passes. -MEASURED_WINDOWED_BELOW_1440P_CELLS: Final[dict[tuple[BudgetFeature, BudgetRoute], tuple[int, float]]] = { - # Windows Fast, 1080p 20 s: one run to completion in 3 windows of 241 frames on the RTX 5090 - # (31.84 GiB). The card floor is a little under that card. Mac has no run. - ("fast", "windows_measured"): (3, 30.0), +@dataclass(frozen=True, slots=True) +class WindowedCover: + """What a measured windowed run covers on a canvas below 1440p.""" + + max_windows: int + # Shortest window, in tokens, the row covers. Zero when the route prices every window size on the + # row's evidence, which both rows do today. + min_window_tokens: int + + +# (feature, route) -> the longest job in windows that a measured run covers, and the smallest window +# the row covers, on a canvas below 1440p that runs in windows (``fast_chunking``). A window is held to +# the token size the budget laws were fitted at and the peak is flat from the third window, so the +# ask is the window's whatever the canvas or the clip length: a long 540p clip and a short 1080p +# one are the same window on the same pipeline. The rows follow the 1440p and 4K runs above, which +# are route-wide and so cover every card on the route. No row names a card, because the window +# the picker takes is already the longest the card's own budget loads. A job past the row, or on a +# route with no row, is an unmeasured bet: the budget still runs it in windows, and Cautious mode +# refuses it while Brave mode allows it with a warning. A clean Brave run records the job in the +# card's calibration frontier and opens it in Cautious mode. +MEASURED_WINDOWED_BELOW_1440P_CELLS: Final[dict[tuple[BudgetFeature, BudgetRoute], WindowedCover]] = { + # Windows Fast: 129-frame windows (62.5k tokens) held flat from the third window through nine, + # and 41-frame windows (22k tokens) flat to twenty, on the RTX 5090 at 1440p. The 1080p 20 s run + # (3 windows of 241 frames, 63k tokens) confirms the same windows below 1440p. The count stays + # at nine because a window count cannot tell the two sizes apart. + ("fast", "windows_measured"): WindowedCover(max_windows=9, min_window_tokens=0), + # Mac Fast: the 1440p runs are 129-frame windows flat through five. No floor on the window size, for + # the reason and with the failure mode given on the Mac Fast 1440p row above. + ("fast", "mac_measured"): WindowedCover(max_windows=5, min_window_tokens=0), } -# IC-LoRAs that run their own tile and window plan with no run behind it. The rows above -# were fitted on a different composition, so every high cell is unmeasured for these, -# whatever the row says. Opening one means a measured run, then removing its id here. +# Catalog IC-LoRA adapters covered by the standard 1440p and 4K tiled rows +# (``MEASURED_HIGH_RES_CELLS[("iclora", ...)]``, measured on Water Simulation and shared by +# architecture-equivalent single-stage tiled adapters) or by ``MEASURED_IC_LORA_COMPOSITION_CELLS``. +# A newly added catalog IC-LoRA not yet listed here defaults to unmeasured at 1440p and 4K until +# its tile/window plan is verified against the shared law or given its own composition row. +HIGH_RES_COVERED_IC_LORA_IDS: Final[frozenset[str]] = frozenset( + { + "clean-plate", + "3d-render-to-real", + "day-to-night", + "colorization", + "decompression", + "deblur", + "cross-eyed", + "water-simulation", + "ingredients", + "instant-shave", + "outpainting", + "greenscreen-avatar", + "upscale", + "crossview-prompt", + "alpha-gen", + "layout-to-render", + "motion-track", + "video-guide", + "restore", + "refine-details", + } +) + + +# IC-LoRAs that run their own tile and window plan. A composition in +# ``UNMEASURED_IC_LORA_COMPOSITIONS`` is unmeasured in every high cell unless +# ``MEASURED_IC_LORA_COMPOSITION_CELLS`` has a measured window count for that +# (ic_lora_id, route, tier). UNMEASURED_IC_LORA_COMPOSITIONS: Final = frozenset({"refine-details"}) +MEASURED_IC_LORA_COMPOSITION_CELLS: Final[dict[tuple[str, BudgetRoute, HighResTier], int]] = { + ("refine-details", "windows_measured", "1440p"): 4, +} + + +def _unmeasured_model_fallback(_: Never) -> bool: + return True + + +def is_unmeasured_model(model_id: LTXLocalModelId | None) -> bool: + """True for a local model id that has not been measured yet. + + Exhaustive over LTXLocalModelId at typecheck time so adding a new model id + fails pyright until it is explicitly classified here. + """ + if model_id is None: + return False + match model_id: + case ( + "ltx-2.5-22b-distilled" + | "ltx-2.3-22b-distilled" + | "ltx-2.3-22b-distilled-1.1" + ): + return False + case _ as unhandled: + return _unmeasured_model_fallback(unhandled) + + +def is_unmeasured_ic_lora(ic_lora_id: str | None) -> bool: + """True for an IC-LoRA adapter id not yet covered by the 1440p/4K law.""" + return ic_lora_id is not None and ic_lora_id not in HIGH_RES_COVERED_IC_LORA_IDS def high_res_tier(width: int, height: int) -> HighResTier | None: @@ -88,43 +207,59 @@ def is_unmeasured_high_res( height: int, *, windows: int, + decode_tokens: float | None = None, ic_lora_id: str | None = None, ) -> bool: """True for a 1440p or 4K job that no measured run covers. - A job is covered when its (feature, route, tier) has a row and the job runs in no - more windows than that row's run did. An IC-LoRA in ``UNMEASURED_IC_LORA_COMPOSITIONS`` - is unmeasured in every high cell. + A job is covered when its (feature, route, tier) has a row, the job runs in no + more windows than that row's run did, and (when a route has a decode-tile token + ceiling) its single-tile decode tokens do not exceed that ceiling. An IC-LoRA in + ``UNMEASURED_IC_LORA_COMPOSITIONS`` or not yet in ``HIGH_RES_COVERED_IC_LORA_IDS`` + is unmeasured unless its own row in ``MEASURED_IC_LORA_COMPOSITION_CELLS`` covers + ``windows``. """ tier = high_res_tier(width, height) if tier is None: return False - if ic_lora_id in UNMEASURED_IC_LORA_COMPOSITIONS: + if ic_lora_id is not None and ( + ic_lora_id in UNMEASURED_IC_LORA_COMPOSITIONS or is_unmeasured_ic_lora(ic_lora_id) + ): + composition_windows = MEASURED_IC_LORA_COMPOSITION_CELLS.get( + (ic_lora_id, route, tier) + ) + if composition_windows is None or windows > composition_windows: + return True + key = (feature, route, tier) + measured_windows = MEASURED_HIGH_RES_CELLS.get(key) + if measured_windows is None or windows > measured_windows: return True - measured_windows = MEASURED_HIGH_RES_CELLS.get((feature, route, tier)) - return measured_windows is None or windows > measured_windows - - -def window_fallback_measured(feature: BudgetFeature, route: BudgetRoute, total_vram_gib: float | None) -> bool: - """True when a measured run covers a window fallback below 1440p on a card this size. - - The budget tries windows for a refused job only then. Without a row, below the run's card, or - with an unknown size, the single-pass verdict stands exactly as before. - """ - cover = MEASURED_WINDOWED_BELOW_1440P_CELLS.get((feature, route)) - return cover is not None and total_vram_gib is not None and total_vram_gib >= cover[1] + max_decode_tokens = MEASURED_MAX_DECODE_TOKENS.get((feature, route)) + if max_decode_tokens is not None and decode_tokens is not None: + return decode_tokens > max_decode_tokens + return False def is_unmeasured_windowed_below_1440p( - feature: BudgetFeature, route: BudgetRoute, width: int, height: int, *, windows: int + feature: BudgetFeature, + route: BudgetRoute, + width: int, + height: int, + *, + windows: int, + window_tokens: float, ) -> bool: - """True for a job below 1440p that runs in more windows than a measured run covers. + """True for a job below 1440p in windows that no measured run covers. - One pass is never unmeasured here: it prices on rows fitted at and below 1080p. Only a job in - more than one window is, and only when its (feature, route) has no row or the job runs in more - windows than that row's run did. 1440p and 4K have their own rows (``is_unmeasured_high_res``). + One pass is never unmeasured here: it prices on rows fitted at and below 1080p. A job in + more than one window is covered only when its (feature, route) has a row, the job runs in + no more windows than that row's run did, and its window is at least the row's floor. + A route with no row is an unmeasured bet. 1440p and 4K have their own rows + (``is_unmeasured_high_res``). """ if windows <= 1 or high_res_tier(width, height) is not None: return False cover = MEASURED_WINDOWED_BELOW_1440P_CELLS.get((feature, route)) - return cover is None or windows > cover[0] + if cover is None: + return True + return windows > cover.max_windows or window_tokens < cover.min_window_tokens diff --git a/backend/runtime_config/memory_meter.py b/backend/runtime_config/memory_meter.py new file mode 100644 index 000000000..d5a92b0e2 --- /dev/null +++ b/backend/runtime_config/memory_meter.py @@ -0,0 +1,142 @@ +"""How sure the Home memory meter may be about a priced job's ask. + +The meter draws ``PricedJob`` asks, so its confidence is read off the same evidence admission +uses. It never changes a verdict. +""" + +from __future__ import annotations + +import math +from typing import TYPE_CHECKING, assert_never + +from api_types import GenerationRisk, JobMemoryAsk, MemoryCapacity, MemoryConfidence +from runtime_config.budget_admission import compared_available_gib +from runtime_config.budget_decision import IcLoraJobLoad, VideoJobLoad +from runtime_config.budget_evidence import Extrapolated, Fitted, GenericCurve +from runtime_config.eta import EtaSystem, default_machine_factor, estimate_job_shape_seconds +from runtime_config.measured_cells import BudgetRoute + +if TYPE_CHECKING: + from runtime_config.budget_admission import PricedJob + from runtime_config.video_job_budget import LocalJobFilter + +_ASK_ROUNDING = 1000 + +# Where a single pass past the fitted range may really land, as ratios of its ask. Drawn as a soft +# trailing edge, never as numbers. Low: past-fit passes land under the ask by about what fitted +# ones do, which on a Mac includes the edge-basis margin above the smallest passing cap. High: a +# stream law that runs past its fit can stop holding, and an under-ask is the failure that matters +# (an OOM, or Windows paging partway through the job), so the top is the worst such miss seen on +# either route. Narrowing either side needs a past-fit run on that route. +ESTIMATE_BAND_RATIOS: dict[BudgetRoute, tuple[float, float]] = { + "windows_measured": (0.975, 1.07), + "mac_measured": (0.95, 1.07), +} + + +def meter_confidence(priced: PricedJob, *, route: BudgetRoute) -> MemoryConfidence: + """Solid, estimate, or rough for the meter. + + Confidence follows the route. The legacy curve is rough whatever its tag: a 1440p cell on it + is tagged unmeasured, but its number is still the generic curve's. A job in parts peaks by its + third part and stays flat after it, so its ask is as sure as a fitted one even past the + longest run. A single pass past the measured range has no such plateau to lean on. A clean + run on this device covers the shape. + """ + if route == "legacy": + return "rough" + evidence = priced.evidence + match evidence: + case GenericCurve(): + return "rough" + case Fitted(): + return "solid" + case Extrapolated(): + if priced.covered or priced.shape.windows >= 2: + return "solid" + return "estimate" + case _: + assert_never(evidence) + + +def estimate_band_gib(ask_gib: float, *, route: BudgetRoute) -> tuple[float, float] | None: + """The soft band of an estimate. None on the legacy route, which never estimates.""" + ratios = ESTIMATE_BAND_RATIOS.get(route) + if ratios is None: + return None + low, high = ratios + return ask_gib * low, ask_gib * high + + +def job_filter_machine_factor(job_filter: LocalJobFilter) -> float | None: + """Calibrated or hardware-class speed factor for ``job_filter``.""" + if job_filter.calibration.machine_factor is not None: + return job_filter.calibration.machine_factor + identity = job_filter.calibration.identity + if identity is not None: + factor = default_machine_factor(identity.gpu_model) + if factor is not None: + return factor + return default_machine_factor(job_filter.profile.device_name) + + +def job_memory_ask( + priced: PricedJob, + *, + route: BudgetRoute, + system: EtaSystem | None = None, + risk: GenerationRisk | None = None, + machine_factor: float | None = None, + conv_vae: bool = False, +) -> JobMemoryAsk: + """The meter's reading of a priced job. The ask rounds up, so over never reads as fitting.""" + ask_gib = math.ceil(priced.decision.stream_gib * _ASK_ROUNDING) / _ASK_ROUNDING + confidence = meter_confidence(priced, route=route) + band = estimate_band_gib(ask_gib, route=route) if confidence == "estimate" else None + load_mode = ( + priced.decision.mode + if isinstance(priced.decision, (VideoJobLoad, IcLoraJobLoad)) + else "streaming_models_loading" + ) + resolved_system: EtaSystem = ( + system + if system is not None + else ("Darwin" if route == "mac_measured" else "Windows") + ) + estimated_seconds = ( + estimate_job_shape_seconds( + priced.shape, + load_mode, + system=resolved_system, + machine_factor=machine_factor, + conv_vae=conv_vae, + ) + if machine_factor is not None + else None + ) + return JobMemoryAsk( + ask_gib=ask_gib, + confidence=confidence, + windows=priced.shape.windows, + tight=priced.tight, + band_low_gib=None if band is None else band[0], + band_high_gib=None if band is None else band[1], + risk=risk, + estimated_seconds=estimated_seconds, + ) + + +def memory_capacity(job_filter: LocalJobFilter) -> MemoryCapacity: + """The figure the meter's end mark stands for: the one admission compares asks against. + + The legacy curve compares the integer GB fallback when exact VRAM bytes are missing, and its + rough scale only needs that much. + """ + darwin = job_filter.profile.system == "Darwin" + compared = compared_available_gib(job_filter) + return MemoryCapacity( + device="mac" if darwin else "gpu", + capacity_gib=( + compared if compared is not None or darwin else job_filter.budget.total_vram_gib + ), + ) diff --git a/backend/runtime_config/model_download_specs.py b/backend/runtime_config/model_download_specs.py index 63ddd8471..8392f0afc 100644 --- a/backend/runtime_config/model_download_specs.py +++ b/backend/runtime_config/model_download_specs.py @@ -6,7 +6,7 @@ from collections.abc import Callable, Sequence from dataclasses import dataclass from pathlib import Path -from typing import assert_never, cast, get_args +from typing import Final, assert_never, cast, get_args from api_types import ( LTXLocalModelId, @@ -101,6 +101,9 @@ class LTXLocalModelSpec: relevance: LTXLocalModelRelevance supported_pipelines: tuple[tuple[LTXVideoGenPipeline, LTXVideoGenerationSpec], ...] version_label: str + # Bytes of the largest transformer block in ``model_cp``. ltx-core disk streaming + # sizes every host read buffer to it, so the Mac pool gate charges it per buffer. + disk_stream_unit_bytes: int supports_api_text_encoding: bool = True # `/v1/prompt-embedding` `model` selector for published checkpoints that omit # `encrypted_wandb_properties` (LTX 2.5 OS split). XOR with checkpoint `model_id`. @@ -463,6 +466,12 @@ def get_model_cp_spec(cp_id: ModelCheckpointID) -> ModelCheckpointSpec: ) +# One transformer block (bf16 weights, f32 tables); all 48 blocks of each checkpoint are +# the same size. The 2.3 and 2.3-1.1 checkpoints share one size; 2.5 is 40,960 bytes smaller. +_LTX_2_3_22B_BLOCK_BYTES: Final = 773_587_328 +_LTX_2_5_22B_BLOCK_BYTES: Final = 773_546_368 + + def get_ltx_model_spec(model_id: LTXLocalModelId) -> LTXLocalModelSpec: match model_id: case "ltx-2.5-22b-distilled": @@ -483,6 +492,7 @@ def get_ltx_model_spec(model_id: LTXLocalModelId) -> LTXLocalModelSpec: ), supported_pipelines=_DISTILLED_PIPELINES_2_5, version_label="LTX 2.5", + disk_stream_unit_bytes=_LTX_2_5_22B_BLOCK_BYTES, api_prompt_embedding_model=LTX_2_5_API_PROMPT_EMBEDDING_MODEL, wants_audio_visual_captions=True, prompt_enhancer_cp="gemma-4-e2b-it", @@ -503,6 +513,7 @@ def get_ltx_model_spec(model_id: LTXLocalModelId) -> LTXLocalModelSpec: ), supported_pipelines=_DISTILLED_PIPELINES_2_3, version_label="LTX 2.3", + disk_stream_unit_bytes=_LTX_2_3_22B_BLOCK_BYTES, ) case "ltx-2.3-22b-distilled": return LTXLocalModelSpec( @@ -517,6 +528,7 @@ def get_ltx_model_spec(model_id: LTXLocalModelId) -> LTXLocalModelSpec: relevance=LTXLocalModelRelevant(upgrade_messages={}), supported_pipelines=_DISTILLED_PIPELINES_2_3, version_label="LTX 2.3 (1.0)", + disk_stream_unit_bytes=_LTX_2_3_22B_BLOCK_BYTES, ) case _: assert_never(model_id) diff --git a/backend/runtime_config/nag_limits.py b/backend/runtime_config/nag_limits.py new file mode 100644 index 000000000..9e1956770 --- /dev/null +++ b/backend/runtime_config/nag_limits.py @@ -0,0 +1,17 @@ +"""Bounds and defaults for Normalized Attention Guidance (NAG).""" + +from __future__ import annotations + +ENV_ENABLED = "LTX_NAG_ENABLED" +ENV_SCALE = "LTX_NAG_SCALE" +ENV_ALPHA = "LTX_NAG_ALPHA" +ENV_TAU = "LTX_NAG_TAU" + +DEFAULT_SCALE = 11.0 +DEFAULT_ALPHA = 0.25 +DEFAULT_TAU = 2.5 + +MAX_SCALE = 100.0 +MAX_ALPHA = 1.0 +MAX_TAU = 10.0 +NEGATIVE_PROMPT_MAX_LENGTH = 2000 diff --git a/backend/runtime_config/reject_reasons.py b/backend/runtime_config/reject_reasons.py index bef148a3a..f7c82fee8 100644 --- a/backend/runtime_config/reject_reasons.py +++ b/backend/runtime_config/reject_reasons.py @@ -9,22 +9,50 @@ from typing import Literal -# ``unmeasured_cell``: a 1440p or 4K cell no run has confirmed (measured_cells.py). -# Standard refuses it with fixed copy; Reckless allows it with an unmeasured warning. +# ``unmeasured_cell``: a priced load outside every lab-measured cell +# (``UnmeasuredBasis``). Produced only by admission: Cautious refuses it with the +# priced figures; Brave allows it with an unmeasured warning. +# ``one_pass_unavailable``: one pass was asked for a 1440p or 4K clip longer than one +# window, which those canvases always run in windows. A wall in every mode. VideoJobRejectReason = Literal[ - "stream_over", "unsupported", "ram_shortfall", "mps_sequence_over", "unmeasured_cell" + "stream_over", + "unsupported", + "ram_shortfall", + "mps_sequence_over", + "unmeasured_cell", + "one_pass_unavailable", +] + +# How a Fast clip is cut. ``auto`` lets the budget pick (one pass when it fits, else +# windows); ``one_pass`` and ``parts`` are a user's explicit choice, or ``one_pass`` from +# the "Never split into parts" setting. +PassShape = Literal["auto", "one_pass", "parts"] + +# Why a priced verdict is an extrapolation: a 1440p or 4K cell no run covers +# (measured_cells.py), a two-stage IC-LoRA window past the priced token range, or +# a Mac two-stage IC-LoRA shape outside the measured Layout to Render cell, or a Fast clip +# below 1440p that runs in more windows than any run, or a Fast single pass larger than the +# windows the laws were fitted on, or a new model not yet in the measured set. +UnmeasuredBasis = Literal[ + "high_res_cell", + "two_stage_range", + "mac_two_stage_cell", + "windowed_range", + "pass_tokens", + "unmeasured_model", ] -# Hardware-budget mode: which measurement tiers block. "reckless" turns an -# over-budget verdict into allow-with-warning and annotates unmeasured loads. -# An unmeasured note does not cover a later memory miss. Hard refusals -# (unsupported, fences, window math) block in every mode. Stored in -# AppSettings, threaded onto LocalJobFilter, echoed on specs responses. -BudgetMode = Literal["standard", "reckless"] +# Hardware-budget mode: which measurement tiers block. "brave" (the default) +# turns an over-budget verdict into allow-with-warning and admits unmeasured +# loads with a warning; "cautious" refuses both. An unmeasured note does not +# cover a later memory miss. Hard refusals (unsupported, spatial, decode floor, +# MPS sequence) block in every mode. Stored in AppSettings, threaded onto +# LocalJobFilter, echoed on specs responses. +BudgetMode = Literal["brave", "cautious"] -# Warning tiers for allow-with-warning UX. A property of the (job, machine) -# pair, never of the mode: the mode only decides which tiers block. -LoadRiskTier = Literal["tight", "unmeasured"] +# Warning tiers on a kept list cell. ``tight`` never confirms; ``over`` and +# ``unmeasured`` are admitted bets the mode allowed. +WarnedCellTier = Literal["tight", "over", "unmeasured"] # Tiers a create-time annotation may carry. Tight fits never block anywhere, # so they are never annotated. @@ -34,11 +62,10 @@ # dropped cells, the risk annotation, and the budget helpers. ShortfallKind = Literal["total", "free"] -# List-time IC-LoRA duration drops: the shared budget reasons plus the four -# IC-LoRA-only verdicts (spatial canvas fence, unpriced two-stage lengths, -# Mac two-stage refused until measured, long Refine past the decode floor). -# Kept separate from VideoJobRejectReason because the shared vocabulary feeds -# the Fast/edit reject table, where these four can never occur. The budget +# List-time IC-LoRA duration drops: the shared budget reasons plus the two +# IC-LoRA-only hard walls (spatial canvas cap, long Refine past the decode +# floor). Kept separate from VideoJobRejectReason because the shared vocabulary +# feeds the Fast/edit reject table, where these two can never occur. The budget # reasons still pass through by name, so extending the shared literal fails # typecheck at the IC-LoRA passthrough until this literal follows. IcLoraDroppedReason = Literal[ @@ -47,10 +74,10 @@ "ram_shortfall", "mps_sequence_over", "unmeasured_cell", + "one_pass_unavailable", "spatial", - "two_stage_over_measured", - "mac_two_stage_unmeasured", "refine_decode_floor", + "window_over_cap", ] # Execute-time budget family: HTTP/capability codes meaning "the job stopped diff --git a/backend/runtime_config/runtime_config.py b/backend/runtime_config/runtime_config.py index 5561dfc92..db81d1bb8 100644 --- a/backend/runtime_config/runtime_config.py +++ b/backend/runtime_config/runtime_config.py @@ -8,6 +8,7 @@ import torch +from runtime_config.assets_layout import in_flight_folder from runtime_config.runtime_policy import LocalGenerationMode if TYPE_CHECKING: @@ -44,6 +45,9 @@ class RuntimeConfig: system: str = "" # Exact CUDA device total VRAM in bytes. None if CUDA is unavailable or the query failed. vram_bytes: int | None = None + # Free CUDA VRAM sampled once at backend startup before any model loads, used as the + # usable ceiling for total_only (picker, model specs, queue create). + usable_vram_bytes: int | None = None # Exact total system RAM in bytes. None if the query failed. total_ram_bytes: int | None = None # Drive class of the checkpoint volume, probed once at startup. None when unknown. @@ -55,6 +59,15 @@ class RuntimeConfig: # measured budget route: pre-Ada streaming runs bf16, which the fp8-fit # laws never saw. Default True preserves current routing where unprobed. fp8_capable: bool = True + # Kill switch for parallel queue lanes. False registers only the local lane: every job + # then runs one at a time on the local slot, as before lanes existed. + parallel_queue_lanes: bool = True + # User-chosen assets folder (LTX_ASSETS_DIR). None means /assets. + assets_dir: Path | None = None + + @property + def in_flight_dir(self) -> Path: + return in_flight_folder(self.app_data_dir, self.assets_dir) @property def force_api_generations(self) -> bool: diff --git a/backend/runtime_config/runtime_policy.py b/backend/runtime_config/runtime_policy.py index 27d8c97c1..f2a004d5f 100644 --- a/backend/runtime_config/runtime_policy.py +++ b/backend/runtime_config/runtime_policy.py @@ -93,7 +93,7 @@ def decide_local_generation_mode( Darwin (no fp8 path on MPS). ``macos_major`` below ``DARWIN_MIN_MACOS_MAJOR`` is unsupported. ``None`` means the version is unknown, and it does not block. - Darwin always streams (mmap via OffloadMode.DISK, not CUDA's pinned-host + Darwin always streams (from disk via OffloadMode.DISK, not CUDA's pinned-host OffloadMode.CPU — see ``offload_mode_for_prefetch_count``). The original reason was corruption: on an M5 Max 128 GB, full-resident plus a LoRA decoded to green/gray frames. That was an unfenced MPS transfer in upstream @@ -154,35 +154,55 @@ def decide_local_generation_mode( def windows_checkpoint_streams_from_disk( system: str, drive_type: DriveType | None ) -> bool: - """Windows + NVMe maps weights from disk; everything else pins from CPU. + """Whether Windows can stream checkpoint weights from disk (NVMe only). - Single source for the DISK path: the offload routing and the profile's - ``streams_from_disk`` both read this rule, so the RAM floors cannot drift - from the routing they price. + Single source for the Windows NVMe disk-streaming gate: + ``should_disk_stream_cuda_weights`` and ``HardwareProfile.streams_from_disk`` + both read this rule, so the lower NVMe RAM floors only open when the drive + can actually take the disk path. """ return system == "Windows" and drive_type == "nvme" def should_disk_stream_cuda_weights( - system: str, ram_gb: int | None, *, drive_type: DriveType | None + system: str, + ram_gb: int | None, + *, + drive_type: DriveType | None, + cpu_ram_floor_gb: int | None = CUDA_CPU_OFFLOAD_RAM_FLOOR_GB, ) -> bool: - """Whether CUDA streaming must mmap weights from disk instead of pinning them in RAM. + """Whether CUDA streaming must read weights from disk instead of pinning them in RAM. Linux actually succeeds at cudaHostRegister, so below the CPU-offload RAM floor (or when RAM is unknown) the pinned transformer cannot fit and weights stream from disk instead (LTX-Desktop#163). Drive class does not route Linux. - Windows routes by checkpoint-drive class instead of RAM: NVMe sustains the - ~70 GB per-generation mapped reads (~20 s); SATA (~130 s) does not earn the - switch, so non-NVMe and unknown drives stay on OffloadMode.CPU with its - pageable host buffers (pinned_pool_fix / LTX-Desktop#141). + Windows needs an NVMe checkpoint drive to stream from disk at all: SATA + (~130 s for the ~70 GB per-generation reads) does not earn the switch, so + non-NVMe and unknown drives stay on OffloadMode.CPU with its pageable host + buffers (pinned_pool_fix / LTX-Desktop#141). On Windows NVMe, ltx-core 1.6.0 + has no os.preadv and opens a fresh unbuffered handle per 8 MiB chunk, making + disk streaming slower than CPU offload on Fast and IC-LoRA once host RAM + clears ``cpu_ram_floor_gb`` (40 GB for Fast, 64 GB for IC-LoRA). Below that + floor — or when ``cpu_ram_floor_gb`` is None (Edit, where full-resolution + stage-1 denoise hides the reads and disk stays faster) — NVMe streams from + disk. """ if system == "Windows": - return windows_checkpoint_streams_from_disk(system, drive_type) + if not windows_checkpoint_streams_from_disk(system, drive_type): + return False + if cpu_ram_floor_gb is None or ram_gb is None: + return True + return ram_gb < cpu_ram_floor_gb if system != "Linux": return False if ram_gb is None: return True - return ram_gb < CUDA_CPU_OFFLOAD_RAM_FLOOR_GB + floor_gb = ( + CUDA_CPU_OFFLOAD_RAM_FLOOR_GB + if cpu_ram_floor_gb is None + else cpu_ram_floor_gb + ) + return ram_gb < floor_gb def streaming_prefetch_count_for_mode(mode: LocalGenerationMode) -> int | None: diff --git a/backend/runtime_config/video_job_budget.py b/backend/runtime_config/video_job_budget.py index 318e0f868..672ce0472 100644 --- a/backend/runtime_config/video_job_budget.py +++ b/backend/runtime_config/video_job_budget.py @@ -32,29 +32,60 @@ from collections.abc import Sequence from dataclasses import dataclass, field, replace -from typing import TYPE_CHECKING, Literal, Protocol, assert_never +from typing import TYPE_CHECKING, Final, Literal, assert_never -from api_types import BudgetReadout, GenerationRisk, LTXLocalModelId +from api_types import LTXLocalModelId from frame_math import compute_num_frames +from runtime_config.budget_admission import ( + Admission, + Admitted, + PricedJob, + Refused, + RiskAllowance, + admit, + priced_job, + unmeasured_refusal_message, +) +from runtime_config.budget_decision import ( + LoadMode, + VideoJobDecision, + VideoJobLoad, + VideoJobReject, +) +from runtime_config.budget_evidence import ( + Extrapolated, + Fitted, + GenericCurve, + JobShape, + PriceEvidence, +) +from runtime_config.device_calibration import ( + EMPTY_CALIBRATION, + DeviceCalibration, + envelope_for, +) from runtime_config.fast_chunking import ( + MAX_WINDOW_TOKENS, PEAK_PLATEAU_WINDOWS, is_chunked_canvas, job_window_count, + last_window_frames, window_candidates, window_count, ) +from runtime_config.ic_lora_decode_window import DECODE_MAX_UNTILED_WINDOW from runtime_config.measured_cells import ( + MEASURED_MAX_DECODE_TOKENS, BudgetFeature, BudgetRoute, is_unmeasured_high_res, + is_unmeasured_model, is_unmeasured_windowed_below_1440p, - window_fallback_measured, ) +from runtime_config.model_download_specs import ALL_LTX_LOCAL_MODEL_IDS, get_ltx_model_spec from runtime_config.reject_reasons import ( BudgetMode, - JobRiskTier, - LoadRiskTier, - ShortfallKind, + PassShape, VideoJobRejectReason, ) from runtime_config.runtime_policy import ( @@ -68,14 +99,12 @@ # Runtime import would cycle (local_runtime imports this module). from runtime_config.runtime_config import RuntimeConfig -LoadMode = Literal["full_models_loading", "streaming_models_loading"] - VIDEO_JOB_TOO_LARGE = "VIDEO_JOB_TOO_LARGE" VIDEO_JOB_TOO_LARGE_MESSAGE = ( "This job is larger than this machine can run locally right now. " "Lower the resolution, duration, frame rate, or aspect width." ) -LOCAL_GENERATION_UNSUPPORTED = "LOCAL_GENERATION_UNSUPPORTED" +LOCAL_GENERATION_UNSUPPORTED: Final = "LOCAL_GENERATION_UNSUPPORTED" LOCAL_GENERATION_UNSUPPORTED_MESSAGE = "This machine cannot run local generation." LOCAL_GENERATION_RAM_SHORTFALL = "LOCAL_GENERATION_RAM_SHORTFALL" LOCAL_GENERATION_RAM_SHORTFALL_MESSAGE = ( @@ -84,14 +113,17 @@ # Fixed copy for the MPS sequence fence: nothing was compared, so no figures. # Rides VIDEO_JOB_TOO_LARGE like the other fence verdicts. MPS_SEQUENCE_OVER_MESSAGE = ( - "This job is too long for this Mac's GPU to run in one pass. " + "This job is too long for this Mac's GPU to run all at once. " "Lower the resolution, duration, frame rate, or aspect width." ) -# Fixed copy for a 1440p or 4K cell no run has confirmed. Nothing was compared, so no figures. +# Fallback copy for an untested job the mode does not allow, when no basis rides +# the reject. Admission always sets one; ``unmeasured_refusal_message`` names it. UNMEASURED_CELL_MESSAGE = ( - "This resolution has not been measured on this machine, so it is not offered " - "yet. Lower the resolution." + "This job hasn't been tested on this machine, so Cautious mode blocks it. " + "Turn off Cautious mode to try it anyway, or make the job smaller." ) +ONE_PASS_UNAVAILABLE = "ONE_PASS_UNAVAILABLE" +ONE_PASS_UNAVAILABLE_MESSAGE = "1440p and 4K clips longer than one part are always made in parts." # Total over VideoJobRejectReason: a new reason must add a row here. Codes come # from this table; messages come from reject_message_and_code (enriched with the # measured numbers) with these rows as the incoherent/unknown fallback — never @@ -103,6 +135,7 @@ "stream_over": (VIDEO_JOB_TOO_LARGE_MESSAGE, VIDEO_JOB_TOO_LARGE), "mps_sequence_over": (MPS_SEQUENCE_OVER_MESSAGE, VIDEO_JOB_TOO_LARGE), "unmeasured_cell": (UNMEASURED_CELL_MESSAGE, VIDEO_JOB_TOO_LARGE), + "one_pass_unavailable": (ONE_PASS_UNAVAILABLE_MESSAGE, ONE_PASS_UNAVAILABLE), } # Default shrink-job advice for stream_over total-short and Darwin pool @@ -113,7 +146,7 @@ # Default free-short advice: closing GPU apps frees VRAM and a retry can # succeed. Queued Home callers override it — a Home re-pad makes retry # futile, so the advice is the same resolution-only shrink as total-short. -_FREE_SHORT_ACTION = "Close other GPU apps and retry." +_FREE_SHORT_ACTION = "Close other heavy apps (like games, browsers, or video editors) and retry." def reject_message_and_code( @@ -145,11 +178,14 @@ def reject_message_and_code( required_gib = decision.stream_gib required_ram_bytes = decision.required_ram_bytes legacy, code = VIDEO_JOB_REJECT_ERRORS[reason] - if reason == "unsupported": + if reason == "unsupported" or reason == "one_pass_unavailable": return (legacy, code) - if reason == "mps_sequence_over" or reason == "unmeasured_cell": + if reason == "mps_sequence_over": # Fence verdict: the pool figures were never compared, so fixed copy. return (legacy, code) + if reason == "unmeasured_cell": + basis = decision.unmeasured_basis + return (unmeasured_refusal_message(basis) if basis is not None else legacy, code) if reason == "ram_shortfall": detected = job_filter.budget.total_ram_bytes if required_ram_bytes is None or detected is None: @@ -171,7 +207,7 @@ def reject_message_and_code( f"{pool:.1f} GB. {action}", code, ) - total = budget.total_vram_gib + total = budget.usable_vram_gib available = budget.available_vram_gib if total is None or available is None: return (legacy, code) @@ -193,343 +229,6 @@ def reject_message_and_code( return (legacy, code) -def budget_readout_for_reject( - decision: VideoJobReject, job_filter: LocalJobFilter -) -> BudgetReadout | None: - """Need and have for the same comparison ``reject_message_and_code`` prints. - - None for a hard wall or when the gate compared no figure. - """ - reason = decision.reason - if reason == "unmeasured_cell": - return untested_readout() - if reason == "unsupported" or reason == "mps_sequence_over": - return None - if reason == "ram_shortfall": - required = decision.required_ram_bytes - detected = job_filter.budget.total_ram_bytes - if required is None or detected is None: - return None - return BudgetReadout( - kind="ram", - need_gb=float(required // _GIB), - have_gb=float(detected // _GIB), - ) - required_gib = decision.stream_gib - if job_filter.profile.system == "Darwin": - pool = job_filter.budget.mps_pool_gib - if pool is None: - return None - return BudgetReadout(kind="mac", need_gb=required_gib, have_gb=pool) - total = job_filter.budget.total_vram_gib - available = job_filter.budget.available_vram_gib - if total is None or available is None: - return None - if required_gib > total: - return BudgetReadout(kind="gpu", need_gb=required_gib, have_gb=total) - if required_gib > available: - return BudgetReadout(kind="gpu_busy", need_gb=required_gib, have_gb=available) - return None - - -def tight_readout(ask_gib: float, available_gib: float) -> BudgetReadout: - return BudgetReadout(kind="tight", need_gb=ask_gib, have_gb=available_gib) - - -def untested_readout() -> BudgetReadout: - return BudgetReadout(kind="untested") - - -TIGHT_FIT_HEADROOM_GIB = 0.5 -TIGHT_FIT_HEADROOM_RATIO = 0.05 - - -def compared_available_gib(job_filter: LocalJobFilter) -> float | None: - """The figure the gate compared the ask against. - - Single home for the figure-selection rule: the MPS pool on Darwin, - min(total, free) — or total under total_only — on CUDA. None means the - gate compared nothing (callers stay silent). - """ - if job_filter.profile.system == "Darwin": - return job_filter.budget.mps_pool_gib - if job_filter.budget.total_vram_bytes is None: - return None - return job_filter.budget.available_vram_gib - - -def load_headroom_gib( - decision: VideoJobLoad, job_filter: LocalJobFilter -) -> float | None: - """Available minus ask on the compared figure. None when uncompared.""" - available = compared_available_gib(job_filter) - if available is None: - return None - return available - decision.stream_gib - - -def risk_allowed(allow_risk: bool | None, job_filter: LocalJobFilter) -> bool: - """Whether an over-budget verdict downgrades to allow-with-warning. - - Tri-state: None follows the filter's live mode (every request-scoped gate - passes None); executors pass an explicit bool from the stored annotation so - a mode flip never re-gates a queued job. Named ``allow_risk`` (not - ``risk_allowance``): ``risk_allowance`` is the plain bool carried on - executor protocols from the stored spec annotation, while ``allow_risk`` - is the tri-state gate input that defaults to the live mode when no stored - value exists. - """ - return allow_risk if allow_risk is not None else job_filter.budget_mode == "reckless" - - -def risk_if_allowed( - risk: GenerationRisk | None, - job_filter: LocalJobFilter, - allow_risk: bool | None, - *, - unmeasured_bet: bool = False, -) -> GenerationRisk | None: - """The bet a refusal may run as, or None when the refusal stands. - - An ``over`` bet runs only when risk is allowed (live mode, or the stored - allowance at execute). An ``unmeasured`` bet also runs when the stored - annotation was unmeasured: that note covers the unmeasured refusal it was - taken for, never a later VRAM or RAM miss, which still reports as ``over``. - """ - if risk is None: - return None - if risk.tier == "unmeasured" and unmeasured_bet: - return risk - return risk if risk_allowed(allow_risk, job_filter) else None - - -def load_risk_tier( - decision: VideoJobLoad, - job_filter: LocalJobFilter, - *, - feature: BudgetFeature, -) -> LoadRiskTier | None: - """Warning tier for an admitted job, if any. - - Legacy-route loads are unmeasured (admitted with no trustworthy model); - measured loads inside max(0.5 GiB, 5% of ask) are tight fits. Unknown - figures stay silent. - """ - if budget_route(feature, job_filter.profile) == "legacy": - return "unmeasured" - headroom = load_headroom_gib(decision, job_filter) - if headroom is None: - return None - threshold = max( - TIGHT_FIT_HEADROOM_GIB, TIGHT_FIT_HEADROOM_RATIO * decision.stream_gib - ) - return "tight" if headroom < threshold else None - - -def reject_risk_tier(reason: VideoJobRejectReason) -> JobRiskTier | None: - """Measurement rejects are over-budget bets, an unmeasured cell is an - unmeasured bet; hard walls return None. - - Allow-list: a new ``VideoJobRejectReason`` fails typecheck here until it - picks a tier. ``unsupported`` (no pipeline) and ``mps_sequence_over`` (the - Metal kernel SIGABRTs past the fence — uncatchable, not a bet) never - downgrade. - """ - match reason: - case "stream_over" | "ram_shortfall": - return "over" - case "unmeasured_cell": - return "unmeasured" - case "unsupported" | "mps_sequence_over": - return None - case _ as unreachable: - assert_never(unreachable) - - -def reject_over_gib( - decision: VideoJobReject, job_filter: LocalJobFilter -) -> float | None: - """VRAM shortfall on a stream_over reject. None for any other reason — - RAM verdicts passed VRAM, so subtracting would print a negative lie.""" - if decision.reason != "stream_over": - return None - available = compared_available_gib(job_filter) - if available is None: - return None - return decision.stream_gib - available - - -def reject_over_ram_gb( - decision: VideoJobReject, job_filter: LocalJobFilter -) -> int | None: - """RAM shortfall in whole GB, message-consistent (required//GiB minus - detected//GiB, the same ints the 422 prints).""" - if decision.reason != "ram_shortfall": - return None - required = decision.required_ram_bytes - detected = job_filter.budget.total_ram_bytes - if required is None or detected is None: - return None - return required // _GIB - detected // _GIB - - -def reject_shortfall_kind( - decision: VideoJobReject, job_filter: LocalJobFilter -) -> ShortfallKind | None: - """Which figure bound a CUDA stream_over reject. - - "free" only when free strictly binds (free < total on exact floats — - min() returns its input, so equality with total is exact). Total-gated - lists, missing samples, and Darwin (pool gate, never free advice) all - report "total"/None respectively: Darwin returns None and the frontend - keys Darwin copy off platform, not kind. - """ - if decision.reason != "stream_over": - return None - if job_filter.profile.system == "Darwin": - return None - total = job_filter.budget.total_vram_gib - available = job_filter.budget.available_vram_gib - if total is None or available is None: - return None - return "total" if available == total else "free" - - -def tight_fit_message(ask_gib: float, available_gib: float, *, darwin: bool) -> str: - if darwin: - return ( - f"Tight fit: this needs ~{ask_gib:.1f} GB of your Mac's " - f"{available_gib:.1f} GB memory allowance. It should run." - ) - return ( - f"Tight fit: this needs ~{ask_gib:.1f} GB and about " - f"{available_gib:.1f} GB is available. It should run, but close " - "other GPU apps first." - ) - - -def over_budget_message( - ask_gib: float, - available_gib: float, - *, - darwin: bool, - shortfall_kind: ShortfallKind | None, -) -> str: - if darwin: - return ( - f"Over budget: this needs {ask_gib:.1f} GB but this Mac allows " - f"{available_gib:.1f} GB. It may run out of memory or stall — " - "lower the resolution or duration to fit." - ) - if shortfall_kind == "free": - return ( - f"Over budget right now: this needs {ask_gib:.1f} GB but only " - f"{available_gib:.1f} GB is free. Close other GPU apps and retry, " - "or lower the resolution or duration." - ) - return ( - f"Over budget: this needs {ask_gib:.1f} GB but this machine's graphics " - f"card has {available_gib:.1f} GB. It may run out of memory or stall — " - "lower the resolution or duration to fit." - ) - - -def over_ram_message(required_gb: int, detected_gb: int) -> str: - return ( - f"Over budget: this needs {required_gb} GB of system RAM but this machine " - f"has {detected_gb} GB. Close heavy programs; on desktops, more RAM " - "is the real fix." - ) - - -def unmeasured_message( - hint: Literal["mac_two_stage"] | None = None, -) -> str: - if hint == "mac_two_stage": - return ( - "Unmeasured: two-stage IC-LoRA isn't measured on Mac yet. " - "It may fail or stall." - ) - return ( - "Unmeasured: we haven't tested this setup on your hardware, so we " - "can't predict whether it fits. It may fail or stall." - ) - - -def unmeasured_load_risk( - decision: VideoJobLoad, - job_filter: LocalJobFilter, - *, - feature: BudgetFeature, - allow_risk: bool | None, -) -> GenerationRisk | None: - """T3 annotation for a legacy load. Reckless only. - - Tight fits stay unmarked. Standard stays unmarked. A stored unmeasured - note does not waive a later VRAM or RAM miss at execute. - """ - if not risk_allowed(allow_risk, job_filter): - return None - if load_risk_tier(decision, job_filter, feature=feature) != "unmeasured": - return None - return GenerationRisk( - tier="unmeasured", - message=unmeasured_message(), - readout=untested_readout(), - ) - - -def risk_for_reject( - decision: VideoJobReject, job_filter: LocalJobFilter -) -> GenerationRisk | None: - """Over-budget annotation for a measurement reject, if downgradable. - - Returns None for unsupported (hard wall) and for uncompared figures. - Legacy-route rejects tier as over: the curve is rough, but a reject is - conservative by construction — the unmeasured bet is the legacy *load*. - """ - tier = reject_risk_tier(decision.reason) - if tier is None: - return None - if tier == "unmeasured": - return GenerationRisk( - tier="unmeasured", - message=unmeasured_message(), - readout=untested_readout(), - ) - darwin = job_filter.profile.system == "Darwin" - if decision.reason == "ram_shortfall": - required = decision.required_ram_bytes - detected = job_filter.budget.total_ram_bytes - if required is None or detected is None: - return None - required_gb = required // _GIB - detected_gb = detected // _GIB - return GenerationRisk( - tier="over", - shortfall_kind=None, - over_gib=None, - over_ram_gb=required_gb - detected_gb, - message=over_ram_message(required_gb, detected_gb), - readout=budget_readout_for_reject(decision, job_filter), - ) - available = compared_available_gib(job_filter) - if available is None: - return None - kind = reject_shortfall_kind(decision, job_filter) - over = decision.stream_gib - available - return GenerationRisk( - tier="over", - shortfall_kind=kind, - over_gib=over, - over_ram_gb=None, - message=over_budget_message( - decision.stream_gib, available, darwin=darwin, shortfall_kind=kind - ), - readout=budget_readout_for_reject(decision, job_filter), - ) - - def vram_snapshot_suffix( *, allocated_bytes: int | None, @@ -578,23 +277,24 @@ def _gib_or_unknown(value_bytes: int | None) -> str: # Streamed jobs pin tens of GiB of transformer in host RAM. Shared with the # Linux CPU-offload floor: same working set, same number — only the consequence # differs (Linux streams from disk below it; Windows declines the cell on the -# CPU path and maps from disk on NVMe). +# CPU path and streams from disk on NVMe). WINDOWS_FAST_STREAMING_RAM_BYTES = CUDA_CPU_OFFLOAD_RAM_FLOOR_GB * _GIB -# Disk-mapped streaming commits little host RAM, but the floor stays well above -# that: with less room the page cache thins and mapped reads balloon per run. -# 32 GB is the lowest figure the evidence supports. Below it stays refused -# until measured. -# Basis note: the low-RAM figures trace only to brief prose -WINDOWS_FAST_DISK_STREAMING_RAM_GB = 32 +# Disk streaming on 1.6.0 reads blocks into four block-sized host buffers plus +# two 64 MiB staging buckets (~5–6 GiB working set on Fast, zero swap at 24 GB). +# Even though positional reads cycle the checkpoint through the OS file cache at +# 32 and 24 GB (4–6x physical NVMe reads), NVMe prefetch holds wall time to +# 1.16–1.30x of native 64 GB. 24 GB is the lowest figure measured. +WINDOWS_FAST_DISK_STREAMING_RAM_GB = 24 # Edit RAM floors: the CPU warm pin exceeds what a 48 GB machine can hold plus -# the OS, so the CPU floor is 64; DISK holds 32 by the Fast precedent (less -# degraded there than Fast at its own floor). +# the OS, so the CPU floor is 64; DISK holds down to 24 GB on 1.6.0 (E3 working +# set ~11 GiB, 1.15x wall time at 24 GB). WINDOWS_EDIT_CPU_STREAMING_RAM_GB = 64 -WINDOWS_EDIT_DISK_STREAMING_RAM_GB = 32 +WINDOWS_EDIT_DISK_STREAMING_RAM_GB = 24 # IC-LoRA RAM floors: reference latents lift the CPU warm pin over Fast's, so -# the CPU floor is 64; DISK degrades steeply at 40 but holds at 48. +# the CPU floor is 64; DISK holds at 32 GB on 1.6.0 (L5 working set ~9.5–11.4 GiB, +# 1.33–1.44x wall time at 32 GB with flat swap). WINDOWS_ICLORA_CPU_STREAMING_RAM_GB = 64 -WINDOWS_ICLORA_DISK_STREAMING_RAM_GB = 48 +WINDOWS_ICLORA_DISK_STREAMING_RAM_GB = 32 @dataclass(frozen=True, slots=True) @@ -658,6 +358,19 @@ def required_gib(self, tokens: float) -> float: intercept_gib=5.00, gib_per_token=2.77e-4, ) +# Windows edit VAE decode reserved law: DiffVAE splits the frame axis past 80 frames +# (largest 8k+1 untiled window: DECODE_MAX_UNTILED_WINDOW = 73), so a single temporal +# decode tile processes ``decode_tokens = video_tokens(H, W, min(F, 73))`` tokens. +# Taking ``max(_EDIT_STREAM(tokens), _EDIT_DECODE_STREAM(decode_tokens))`` across both +# phases prices the whole-run reserved peak continuously with no resolution-tier flags: +# the two lines cross at 40,929 decode tokens (~4.2 Mpx at 73 frames), so <=1440p +# (<=36,800 decode tokens) and 4K 81f+ (denoise 89,760t > decode 81,600t) stay on +# _EDIT_STREAM while untiled 4K 49-73f (57,120-81,600 decode tokens) prices on decode. +_EDIT_DECODE_STREAM = _StreamModel( + floor_gib=8.75, + intercept_gib=3.15, + gib_per_token=3.222e-4, +) # Mac (Darwin) Fast stream requirement, same shape as Windows, Mac-native fit. # The per-token transient transfers from CUDA; the Mac surcharge is working set # only. An upper bound, not a floor. @@ -688,6 +401,11 @@ def video_tokens(height: int, width: int, frames: int) -> float: return temporal * (height / 32.0) * (width / 32.0) +def decode_tile_tokens(height: int, width: int, frames: int) -> float: + """Tokens in a single DiffVAE temporal decode tile (frame axis untiled up to 73 frames).""" + return video_tokens(height, width, min(frames, DECODE_MAX_UNTILED_WINDOW)) + + def estimated_giB(mode: LoadMode, seq: float) -> float: if mode == "full_models_loading": return _FULL_INTERCEPT_GIB + _FULL_GIB_PER_TOKEN * seq @@ -734,6 +452,7 @@ class HardwareProfile: # Native fp8 (compute capability >= 8.9). The measured laws were fit on # fp8; without it the budget takes the legacy curve. fp8_capable: bool = True + device_name: str | None = None @property def darwin(self) -> bool: @@ -742,50 +461,31 @@ def darwin(self) -> bool: @property def is_windows_fast(self) -> bool: - """2.5 measured; 2.3 shares those bands. + """Windows Fast routes through the measured bands whenever a model is set. - Same-clip pairs put 2.3 and 2.5 within a few hundredths of a GiB, the - same family-equivalence Mac Fast already routes on. Both 2.3 checkpoint - ids are included. Anything else on Windows stays on the generic curve. + Measured models (2.5 and 2.3) are Fitted; any new model id still uses + these bands and is tagged Extrapolated(basis="unmeasured_model"). """ - return self.system == "Windows" and self.model_id in ( - "ltx-2.5-22b-distilled", - "ltx-2.3-22b-distilled", - "ltx-2.3-22b-distilled-1.1", - ) + return self.system == "Windows" and self.model_id is not None # Darwin 2.3 routing evidence (for is_mac_fast below): the Windows pair # method plus the archived parity re-proofs. @property def is_mac_fast(self) -> bool: - """Darwin Fast routes 2.5 (measured) and 2.3 (family-equivalence extension). + """Darwin Fast routes through _MAC_FAST_STREAM whenever a model is set. - The 2.3-vs-2.5 equivalence is Windows-measured only; routing Darwin 2.3 - through _MAC_FAST_STREAM is extrapolation. The alternative is the legacy - Darwin branch, which never refuses at all. A future model id fails - closed via assert_never until it is priced — it must never fall through - to the legacy never-reject branch silently. + Measured models (2.5 and 2.3) are Fitted; any new model id still prices + on _MAC_FAST_STREAM and is tagged Extrapolated(basis="unmeasured_model") + instead of crashing or falling through to the legacy never-reject branch. """ - if self.system != "Darwin": - return False - if self.model_id is None: - return False - match self.model_id: - case ( - "ltx-2.5-22b-distilled" - | "ltx-2.3-22b-distilled" - | "ltx-2.3-22b-distilled-1.1" - ): - return True - case _ as unreachable: - assert_never(unreachable) + return self.system == "Darwin" and self.model_id is not None @property def streams_from_disk(self) -> bool: - """Windows + NVMe maps weights from disk; everything else pins from CPU. + """Whether Windows + NVMe can fall back to disk streaming below the CPU floor. - Reads the shared rule, so the RAM floors below price exactly the - DISK path the offload routing takes. + Reads the shared rule, so the lower NVMe RAM floors below open only + when the drive can actually take the disk path. """ return windows_checkpoint_streams_from_disk(self.system, self.drive_type) @@ -795,9 +495,9 @@ def windows_fast_required_ram_bytes(self) -> int: Single source of truth shared by the budget gate and the reported ``local_unavailable_required_ram_gb``: both read the floor from the - profile that produced the verdict. Mirrors the offload routing — the - gate only runs for streaming-selected jobs, so Windows + NVMe here is - exactly the DISK path there, and everything else pins from CPU. + profile that produced the verdict. Mirrors the offload routing — + Windows + NVMe falls back to DISK below the 40 GB CPU floor down to + this 24 GB floor, while everything else requires the 40 GB CPU floor. """ if self.streams_from_disk: return WINDOWS_FAST_DISK_STREAMING_RAM_GB * _GIB @@ -807,8 +507,8 @@ def windows_fast_required_ram_bytes(self) -> int: def windows_edit_required_ram_bytes(self) -> int: """RAM floor gating this profile's streamed Windows edit jobs. - See the WINDOWS_EDIT_* constants: Windows + NVMe maps from disk, - everything else pins from CPU. Read only by decide_edit_job's Windows + See the WINDOWS_EDIT_* constants: Windows + NVMe streams from disk, + everything else uses CPU offload. Read only by decide_edit_job's Windows gate. """ if self.streams_from_disk: @@ -819,9 +519,9 @@ def windows_edit_required_ram_bytes(self) -> int: def windows_iclora_required_ram_bytes(self) -> int: """RAM floor gating this profile's streamed Windows IC-LoRA jobs. - See the WINDOWS_ICLORA_* constants: Windows + NVMe maps from disk, - everything else pins from CPU. Read only by decide_ic_lora_job's - Windows gate. + See the WINDOWS_ICLORA_* constants: Windows + NVMe falls back to disk + below the 64 GB CPU floor down to 32 GB, while everything else requires + the 64 GB CPU floor. Read only by decide_ic_lora_job's Windows gate. """ if self.streams_from_disk: return WINDOWS_ICLORA_DISK_STREAMING_RAM_GB * _GIB @@ -833,9 +533,10 @@ def budget_route(feature: BudgetFeature, profile: HardwareProfile) -> BudgetRout Single place that selects the stream curve. Route names carry the measured flag explicitly: ``mac_measured`` / ``windows_measured`` take - fitted curves, ``legacy`` takes the generic path. Fast on Darwin - consults ``is_mac_fast`` (unknown model ids fail closed there); - Fast on Windows is 2.5 and 2.3 via ``is_windows_fast``; edit and IC-LoRA + fitted curves, ``legacy`` takes the generic path. Fast on Darwin and + Windows consults ``is_mac_fast`` / ``is_windows_fast`` (known models are + Fitted; any new model id still prices on the curve and is tagged + ``unmeasured_model`` via ``is_unmeasured_model``); edit and IC-LoRA are measured on Windows and Darwin for any model. Process floors (``CUDA_VRAM_FLOOR_GB``, ``CUDA_FULL_VRAM_GB``, ``DARWIN_*``) and the per-feature RAM floors stay where they are — this route only selects @@ -919,8 +620,9 @@ def _mps_pool_gib(mps_pool_bytes: int | None) -> float | None: class MemoryBudget: """VRAM + RAM figures plus their precedence, evaluated once per use. - Sampling: VRAM total is startup-frozen device bytes; free VRAM is sampled - fresh per request via ``GpuInfo.get_free_cuda_vram_bytes``; RAM total is the + Sampling: VRAM total is startup-frozen device bytes; ``usable_vram_bytes`` is + free VRAM sampled once at backend startup before any model loads; ``free_vram_bytes`` + is sampled fresh per request via ``GpuInfo.get_free_cuda_vram_bytes``; RAM total is the startup-frozen machine total via ``psutil.virtual_memory().total``; the MPS pool is sampled fresh per request via ``GpuInfo.get_mps_pool_bytes``. ``memory_gb`` is the coarse floored @@ -928,12 +630,12 @@ class MemoryBudget: Precedence lives here so no caller re-derives it: the constructors above own the typed fail-mode asymmetry (free-None opens to total, pool-None closes, both-None closes), and unknown-everything fails closed at the - call site. ``total_only`` gates CUDA availability on total ("will it ever - fit") instead of min(total, free): queued creates and list-time display - admit total-fitting cells while free is momentarily depressed, and the - execute-time re-check — still free-gated — refuses genuine drift. It is - not free-None (unmeasured): the sample is still taken, and the flag names - the policy. Mac pool gating is unchanged. + call site. ``total_only`` gates CUDA availability on ``usable_vram_gib`` + (``min(total, startup_free)``, "will it ever fit") instead of ``min(total, free)``: + queued creates and list-time display admit usable-fitting cells while free is + momentarily depressed, and the execute-time re-check — still free-gated — refuses + genuine drift. It is not free-None (unmeasured): the sample is still taken, and the + flag names the policy. Mac pool gating is unchanged. """ total_vram_bytes: int | None @@ -942,17 +644,23 @@ class MemoryBudget: memory_gb: float | None mps_pool_bytes: int | None total_only: bool = False + usable_vram_bytes: int | None = None @property def total_vram_gib(self) -> float | None: """Exact total VRAM, else the integer fallback. None only if both missing.""" return _total_vram_gib(self.total_vram_bytes, self.memory_gb) + @property + def usable_vram_gib(self) -> float | None: + """Idle-machine consumable ceiling: min(total, startup_free), or total when unprobed.""" + return _available_vram_gib(self.total_vram_gib, self.usable_vram_bytes) + @property def available_vram_gib(self) -> float | None: - """What a new job may actually consume: min(total, free), or total when total_only.""" + """What a new job may actually consume: min(total, free), or usable when total_only.""" if self.total_only: - return self.total_vram_gib + return self.usable_vram_gib return _available_vram_gib(self.total_vram_gib, self.free_vram_bytes) def streaming_ram_state( @@ -979,12 +687,25 @@ class LocalJobFilter: profile: HardwareProfile budget: MemoryBudget - # Live budget mode at build time. Gates read this (never global state) - # to decide raise-vs-annotate; decide_* stays pure and mode-blind. - budget_mode: BudgetMode = "standard" - - def decide(self, width: int, height: int, frames: int) -> VideoJobDecision: - return decide_video_job(width, height, frames, job_filter=self) + # Live budget mode at build time. Admission reads it (never global state) + # through RiskAllowance; pricing stays mode-blind. + budget_mode: BudgetMode = "cautious" + # What this device has run cleanly. Empty keeps pricing on the lab tables. + calibration: DeviceCalibration = EMPTY_CALIBRATION + # How a Fast job is cut: the live "Never split" setting for request-time + # gates and specs, or the shape a queued job stored at create. Every range + # and refusal priced from this filter follows it, so a flip never re-cuts or + # re-sizes a queued job. + pass_shape: PassShape = "auto" + # Settings -> Fast decode resolved for this device. Only the wall-time estimate reads it. + conv_vae: bool = False + + +def resolve_pass_shape(requested: PassShape, *, never_split: bool) -> PassShape: + """An explicit shape wins, even over the switch; ``auto`` follows the switch.""" + if requested != "auto": + return requested + return "one_pass" if never_split else "auto" def build_local_job_filter( @@ -994,7 +715,10 @@ def build_local_job_filter( free_vram_bytes: int | None, mps_pool_bytes: int | None, total_only: bool = False, - budget_mode: BudgetMode = "standard", + budget_mode: BudgetMode = "cautious", + calibration: DeviceCalibration = EMPTY_CALIBRATION, + pass_shape: PassShape = "auto", + conv_vae: bool = False, ) -> LocalJobFilter: """One construction idiom for request filters. Callers sample probes first. @@ -1027,6 +751,7 @@ def build_local_job_filter( process_mode=config.local_generations_mode, drive_type=config.checkpoint_drive_type, fp8_capable=config.fp8_capable, + device_name=config.gpu_device_name, ), budget=MemoryBudget( total_vram_bytes=config.vram_bytes, @@ -1039,43 +764,15 @@ def build_local_job_filter( ), mps_pool_bytes=mps_pool_bytes, total_only=total_only, + usable_vram_bytes=config.usable_vram_bytes, ), budget_mode=budget_mode, + calibration=calibration, + pass_shape=pass_shape, + conv_vae=conv_vae, ) -@dataclass(frozen=True, slots=True) -class VideoJobLoad: - mode: LoadMode - seq: float - full_gib: float - stream_gib: float - # Window length in pixel frames when the job runs in windows, else None (one pass). - # ``seq`` and the GiB figures then describe one window. The pipeline runs this value. - chunk_pixel_frames: int | None = None - - -@dataclass(frozen=True, slots=True) -class VideoJobReject: - seq: float - full_gib: float - stream_gib: float - reason: VideoJobRejectReason = "stream_over" - # RAM floor the gate compared, set only on ram_shortfall (its sole - # producer is _streaming_ram_reject, which holds the figure). Message - # builders read this — never re-derive the floor from the profile, or a - # wrong property prints a number the gate did not compare. - required_ram_bytes: int | None = None - # Set by IC-LoRA and by a Fast canvas that runs in windows, to the window the - # pricing tried. A reckless downgrade must run that window: ``None`` is one - # unchunked pass, which costs more than the over-budget figure the user - # confirmed. Edit leaves it None. - chunk_pixel_frames: int | None = None - - -VideoJobDecision = VideoJobLoad | VideoJobReject - - def decide_from_fits( seq: float, full_gib: float, @@ -1174,96 +871,199 @@ def decide_load_mode( ) -def gate_unmeasured_cell( - decision: VideoJobDecision, - *, - feature: BudgetFeature, +def decide_video_job( width: int, height: int, frames: int, + *, job_filter: LocalJobFilter, -) -> VideoJobDecision: - """Refuse a priced load inside a windowed job no run has confirmed (1440p, 4K, or a smaller - canvas that fell back to windows). + allowance: RiskAllowance | None = None, +) -> Admission: + """Fast t2v/i2v/a2v: price the job, then admit it under the allowance. - Runs after pricing so the refusal carries the figures and the window the - price tried, and so a reckless downgrade runs that window. A reject keeps - its own reason: it already says why the job fails. + ``allowance=None`` follows the filter's live mode (request-time gates); + executors pass the stored allowance so a mode flip never re-gates a queued job. """ - if isinstance(decision, VideoJobReject): - return decision - route = budget_route(feature, job_filter.profile) - windows = job_window_count(frames, decision.chunk_pixel_frames) - if is_unmeasured_high_res( - feature, route, width, height, windows=windows - ) or is_unmeasured_windowed_below_1440p(feature, route, width, height, windows=windows): - return unmeasured_cell_reject(decision) - return decision - - -class PricedLoad(Protocol): - """What a Fast or IC-LoRA load carries into an unmeasured-cell refusal.""" - - @property - def seq(self) -> float: ... - @property - def full_gib(self) -> float: ... - @property - def stream_gib(self) -> float: ... - @property - def chunk_pixel_frames(self) -> int | None: ... - - -def unmeasured_cell_reject(load: PricedLoad) -> VideoJobReject: - return VideoJobReject( - seq=load.seq, - full_gib=load.full_gib, - stream_gib=load.stream_gib, - reason="unmeasured_cell", - chunk_pixel_frames=load.chunk_pixel_frames, + allowance = allowance if allowance is not None else RiskAllowance.for_mode(job_filter.budget_mode) + return admit( + price_video_job(width, height, frames, job_filter=job_filter, allowance=allowance), + allowance, ) -def decide_video_job( +def price_video_job( width: int, height: int, frames: int, *, job_filter: LocalJobFilter, -) -> VideoJobDecision: - """Fast t2v/i2v/a2v: the priced verdict, refused inside an unmeasured 1440p or 4K cell.""" - return gate_unmeasured_cell( - _decide_priced_video_job(width, height, frames, job_filter=job_filter), - feature="fast", + allowance: RiskAllowance | None = None, +) -> PricedJob: + """Pick the window and price it in the filter's ``pass_shape``. Under ``auto``, + ``allowance`` decides whether a one-pass job past the fitted window size runs as one + pass (it may take an unmeasured bet) or in windows. ``one_pass`` and ``parts`` price + that shape whatever it costs, so admission turns an over one pass into a Brave over + bet and a Cautious refusal.""" + allowance = allowance if allowance is not None else RiskAllowance.for_mode(job_filter.budget_mode) + decision = _decide_priced_video_job( + width, + height, + frames, + job_filter=job_filter, + allow_unfitted_pass=allowance.unmeasured, + shape=job_filter.pass_shape, + ) + return _priced_canvas_job( + "fast", + decision, width=width, height=height, - frames=frames, + windows=job_window_count(frames, decision.chunk_pixel_frames), job_filter=job_filter, ) +def _priced_canvas_job( + feature: Literal["fast", "edit"], + decision: VideoJobDecision, + *, + width: int, + height: int, + windows: int, + decode_tokens: float | None = None, + job_filter: LocalJobFilter, +) -> PricedJob: + """Tag a Fast or edit verdict: extrapolated in an unmeasured high-res or windowed cell.""" + route = budget_route(feature, job_filter.profile) + evidence: PriceEvidence + if is_unmeasured_high_res( + feature, + route, + width, + height, + windows=windows, + decode_tokens=decode_tokens, + ): + evidence = Extrapolated(basis="high_res_cell") + elif is_unmeasured_windowed_below_1440p( + feature, + route, + width, + height, + windows=windows, + window_tokens=decision.seq, + ): + evidence = Extrapolated(basis="windowed_range") + elif feature == "fast" and _is_pass_past_fitted_tokens(decision, windows=windows, route=route): + evidence = Extrapolated(basis="pass_tokens") + elif route == "legacy": + evidence = GenericCurve() + elif is_unmeasured_model(job_filter.profile.model_id): + evidence = Extrapolated(basis="unmeasured_model") + else: + evidence = Fitted() + return priced_job( + feature, + decision, + evidence, + _canvas_job_shape(feature, decision, width=width, height=height, windows=windows, job_filter=job_filter), + job_filter=job_filter, + ) + + +def _canvas_job_shape( + feature: Literal["fast", "edit"], + decision: VideoJobDecision, + *, + width: int, + height: int, + windows: int, + job_filter: LocalJobFilter, +) -> JobShape: + return JobShape( + feature=feature, + model_id=job_filter.profile.model_id or "", + adapter_id="", + stage_mode="", + tiled=False, + chunked=decision.chunk_pixel_frames is not None, + seq=decision.seq, + canvas_px=width * height, + windows=windows, + ) + + +def _is_pass_past_fitted_tokens(decision: VideoJobDecision, *, windows: int, route: BudgetRoute) -> bool: + """A one-pass load larger than any window the laws were fitted on, on a measured route.""" + return ( + isinstance(decision, VideoJobLoad) + and windows == 1 + and route != "legacy" + and decision.seq > MAX_WINDOW_TOKENS + ) + + def _decide_priced_video_job( width: int, height: int, frames: int, *, job_filter: LocalJobFilter, + allow_unfitted_pass: bool, + shape: PassShape = "auto", ) -> VideoJobDecision: """Fast t2v/i2v/a2v: advertised (stage-2) pixels, no ×2, no spatial cap. - A 1440p or 4K clip longer than one window runs in windows and prices one window: the - longest window that loads, as ``VideoJobLoad.chunk_pixel_frames``. When none loads, the - verdict is the reject of the shortest window, so the figures name the smallest ask. + A clip runs in one pass when the machine loads it, and in overlapping windows when it + does not. A 1440p or 4K clip longer than one window always runs in windows. Any other + canvas windows once one pass cannot fit the machine at all (``_windows_help``), so a long + or high-fps clip at 720p or 540p runs in as many windows as it needs, with no cap on the + count: the budget prices one window, so the window count never grows the ask past the + plateau. The window is the longest that loads, as ``VideoJobLoad.chunk_pixel_frames``. + When none loads, the verdict is the reject of the shortest window, so the figures name the + smallest ask and a Brave downgrade runs that window. + + A one-pass load past the largest fitted window is an unmeasured bet (``pass_tokens``). When the + allowance takes no unmeasured bet and this device has not run that pass cleanly, the clip + runs in windows at the ceiling instead. + + ``one_pass`` skips the window fallback; a 1440p or 4K clip longer than one window is + ``one_pass_unavailable``. ``parts`` skips one pass whenever the clip is longer than the + shortest window. """ + match shape: + case "one_pass": + single_pass = _decide_fast_pass(width, height, frames, windows=1, job_filter=job_filter) + if is_chunked_canvas(width, height) and frames > window_candidates(width, height)[0]: + return VideoJobReject( + seq=single_pass.seq, + full_gib=single_pass.full_gib, + stream_gib=single_pass.stream_gib, + reason="one_pass_unavailable", + ) + return single_pass + case "parts": + windowed = _decide_windowed_video_job(width, height, frames, job_filter=job_filter) + if windowed is not None: + return windowed + return _decide_fast_pass(width, height, frames, windows=1, job_filter=job_filter) + case "auto": + pass + case _ as unreachable: + assert_never(unreachable) if not is_chunked_canvas(width, height): single_pass = _decide_fast_pass(width, height, frames, windows=1, job_filter=job_filter) - if not _one_pass_cannot_fit_card(single_pass, job_filter): + if isinstance(single_pass, VideoJobLoad): + if allow_unfitted_pass or not _is_unproven_pass_past_fit( + single_pass, width, height, job_filter + ): + return single_pass + windowed = _decide_windowed_video_job(width, height, frames, job_filter=job_filter) + return windowed if isinstance(windowed, VideoJobLoad) else single_pass + if not _windows_help(single_pass, job_filter): return single_pass - # No bare card of this size runs the clip in one pass, so run it in windows. When no window - # loads either, the single-pass reject stays the verdict, so nothing else about the - # refusal (its figures, a reckless downgrade running one pass) changes. windowed = _decide_windowed_video_job(width, height, frames, job_filter=job_filter) - return windowed if isinstance(windowed, VideoJobLoad) else single_pass + return windowed if windowed is not None else single_pass decision: VideoJobDecision | None = None if frames <= window_candidates(width, height)[0]: decision = _decide_fast_pass(width, height, frames, windows=1, job_filter=job_filter) @@ -1276,22 +1076,36 @@ def _decide_priced_video_job( return decision -def _one_pass_cannot_fit_card(single_pass: VideoJobDecision, job_filter: LocalJobFilter) -> bool: - """A one-pass refusal that no empty card of this size would pass, on a card a run covers. +def _is_unproven_pass_past_fit( + single_pass: VideoJobLoad, width: int, height: int, job_filter: LocalJobFilter +) -> bool: + """A one-pass load past the fitted window size that this device has not run cleanly.""" + route = budget_route("fast", job_filter.profile) + if not _is_pass_past_fitted_tokens(single_pass, windows=1, route=route): + return False + shape = _canvas_job_shape("fast", single_pass, width=width, height=height, windows=1, job_filter=job_filter) + envelope = envelope_for(shape, single_pass.mode, single_pass.stream_gib) + return job_filter.calibration.covering(envelope) is None + - Only the GPU refusal, and only when its ask is over the card's total VRAM: a window does not - shorten a RAM shortfall, a fence or an unsupported process. An ask that fits an empty card is a - busy or warm card, which frees up: it keeps its refusal, so the evict-and-retry and the - close-other-apps message stay in charge and a clip that runs in one pass is not windowed. +def _windows_help(single_pass: VideoJobDecision, job_filter: LocalJobFilter) -> bool: + """A one-pass refusal that windows can lift: the pass is past the machine's ceiling. + + ``mps_sequence_over`` is a per-forward fence, so a window under it clears it. A + ``stream_over`` qualifies only when its ask is over the whole card (the MPS pool on a Mac): + an ask that fits an empty card is a busy or warm card, which frees up, so it keeps its + refusal and the evict-and-retry and close-other-apps messages stay in charge. A RAM + shortfall or an unsupported process is not shortened by a window. """ - if isinstance(single_pass, VideoJobLoad) or single_pass.reason != "stream_over": + if isinstance(single_pass, VideoJobLoad): return False - total = job_filter.budget.total_vram_gib - return ( - total is not None - and single_pass.stream_gib > total - and window_fallback_measured("fast", budget_route("fast", job_filter.profile), total) - ) + if single_pass.reason == "mps_sequence_over": + return True + if single_pass.reason != "stream_over": + return False + budget = job_filter.budget + ceiling = budget.mps_pool_gib if job_filter.profile.darwin else budget.usable_vram_gib + return ceiling is not None and single_pass.stream_gib > ceiling def _decide_windowed_video_job( @@ -1303,7 +1117,7 @@ def _decide_windowed_video_job( ) -> VideoJobDecision | None: """The longest window that loads, as ``chunk_pixel_frames``. - When none loads, the reject of the shortest window, so a reckless downgrade runs that + When none loads, the reject of the shortest window, so a Brave downgrade runs that window and the figures name the smallest ask. None when the clip is no longer than the shortest window, so there is nothing to chunk. """ @@ -1318,12 +1132,14 @@ def _decide_windowed_video_job( height, window, windows=window_count(frames, window), + last_frames=last_window_frames(frames, window), job_filter=job_filter, ) if isinstance(decision, VideoJobLoad): return replace(decision, chunk_pixel_frames=chunk_pixel_frames) if decision is None: return None + # A Brave downgrade of this reject runs the shortest window, not one pass. return replace(decision, chunk_pixel_frames=chunk_pixel_frames) @@ -1333,19 +1149,27 @@ def _decide_fast_pass( frames: int, *, windows: int, + last_frames: int | None = None, job_filter: LocalJobFilter, ) -> VideoJobDecision: """One pass of ``frames`` frames, inside a job of ``windows`` windows.""" seq = video_tokens(height, width, frames) + last_tokens = ( + seq + if last_frames is None or last_frames == frames + else video_tokens(height, width, last_frames) + ) route = budget_route("fast", job_filter.profile) if route == "mac_measured": return decide_mac_job( seq, - fast_job_stream_gib(seq, windows=windows, darwin=True), + fast_job_stream_gib(seq, windows=windows, darwin=True, last_tokens=last_tokens), job_filter=job_filter, ) if route == "windows_measured": - return _decide_windows_fast_job(seq, windows=windows, job_filter=job_filter) + return _decide_windows_fast_job( + seq, windows=windows, last_tokens=last_tokens, job_filter=job_filter + ) return decide_load_mode( seq, memory_gb=job_filter.budget.memory_gb, @@ -1356,18 +1180,15 @@ def _decide_fast_pass( @dataclass(frozen=True, slots=True) class FastDurationOutcome: - """Per-cell verdicts: kept durations plus why each dropped cell died.""" - - kept: list[int] - rejected: dict[int, VideoJobRejectReason] - # Full decisions for dropped cells, so the specs layer can message them - # without re-deciding. Unsupported carries fixed copy (figures ignored). - rejects: dict[int, VideoJobReject] = field( - default_factory=dict[int, VideoJobReject] - ) - # Full decisions for kept cells, so the specs layer can tier them - # (tight/unmeasured) without re-deciding. - loads: dict[int, VideoJobLoad] = field(default_factory=dict[int, VideoJobLoad]) + """Per-cell admissions in duration order, so the specs layer can message, + tier, and figure every cell without re-deciding.""" + + admitted: dict[int, Admitted] = field(default_factory=dict[int, Admitted]) + refused: dict[int, Refused] = field(default_factory=dict[int, Refused]) + + @property + def kept(self) -> list[int]: + return list(self.admitted) def decide_fast_durations( @@ -1378,30 +1199,58 @@ def decide_fast_durations( *, job_filter: LocalJobFilter, ) -> FastDurationOutcome: - """Decide every cell, keeping loads and naming each rejection's reason.""" - kept: list[int] = [] - rejected: dict[int, VideoJobRejectReason] = {} - rejects: dict[int, VideoJobReject] = {} - loads: dict[int, VideoJobLoad] = {} + """Admit every cell under the filter's live mode.""" + outcome = FastDurationOutcome() for duration in durations: - decision = decide_video_job( + admission = decide_video_job( width, height, compute_num_frames(duration, fps), job_filter=job_filter, ) - if isinstance(decision, VideoJobLoad): - kept.append(duration) - loads[duration] = decision + if isinstance(admission, Admitted): + outcome.admitted[duration] = admission else: - rejected[duration] = decision.reason - rejects[duration] = decision - return FastDurationOutcome( - kept=kept, - rejected=rejected, - rejects=rejects, - loads=loads, + outcome.refused[duration] = admission + return outcome + + +def price_alternative_pass( + width: int, + height: int, + frames: int, + *, + job_filter: LocalJobFilter, + auto: PricedJob, +) -> PricedJob | None: + """The other shape a Brave user may pick for this clip, priced as create would run it. + + None wherever the "Make it" toggle stays hidden: Cautious (it picks for the user), the + "Never split" switch or any other fixed shape (never means never), 1440p and 4K (always + windows past one), a one pass inside the fitted range (windows buy nothing there), a clip + too short to split, and a shape that a wall refuses even in Brave (the Mac sequence fence). + """ + if job_filter.budget_mode != "brave" or job_filter.pass_shape != "auto" or is_chunked_canvas(width, height): + return None + route = budget_route("fast", job_filter.profile) + if auto.chunk_pixel_frames is None: + decision = auto.decision + if not isinstance(decision, VideoJobLoad) or not _is_pass_past_fitted_tokens( + decision, windows=1, route=route + ): + return None + other: PassShape = "parts" + else: + other = "one_pass" + brave = RiskAllowance.for_mode("brave") + priced = price_video_job( + width, height, frames, job_filter=replace(job_filter, pass_shape=other), allowance=brave ) + if other == "parts" and priced.chunk_pixel_frames is None: + return None + if isinstance(admit(priced, brave), Refused): + return None + return priced def decide_edit_job( @@ -1410,18 +1259,40 @@ def decide_edit_job( frames: int, *, job_filter: LocalJobFilter, -) -> VideoJobDecision: - """Retake/extend: the priced verdict, refused inside an unmeasured 1440p or 4K cell.""" - return gate_unmeasured_cell( + allowance: RiskAllowance | None = None, +) -> Admission: + """Retake/extend: price the job, then admit it under the allowance.""" + return admit( + price_edit_job(width, height, frames, job_filter=job_filter), + allowance if allowance is not None else RiskAllowance.for_mode(job_filter.budget_mode), + ) + + +def price_edit_job( + width: int, + height: int, + frames: int, + *, + job_filter: LocalJobFilter, +) -> PricedJob: + return _priced_canvas_job( + "edit", _decide_priced_edit_job(width, height, frames, job_filter=job_filter), - feature="edit", width=width, height=height, - frames=frames, + windows=1, + decode_tokens=decode_tile_tokens(height, width, frames), job_filter=job_filter, ) +def video_job_reject(refused: Refused) -> VideoJobReject: + """The reject of a Fast or edit refusal: their pricing never yields an IC-LoRA reject.""" + reject = refused.reject + assert isinstance(reject, VideoJobReject) + return reject + + def _decide_priced_edit_job( width: int, height: int, @@ -1447,10 +1318,11 @@ def _decide_priced_edit_job( trims 1080p windows to the pool instead of approving the full cap. """ seq = video_tokens(height, width, frames) + decode_tokens = decode_tile_tokens(height, width, frames) route = budget_route("edit", job_filter.profile) if route == "windows_measured": return decide_measured_job( - required_gib=_edit_stream_required_gib(seq), + required_gib=_edit_stream_required_gib(seq, decode_tokens=decode_tokens), required_ram_bytes=job_filter.profile.windows_edit_required_ram_bytes, seq=seq, full_headroom_gib=_EDIT_FULL_HEADROOM_GIB, @@ -1474,21 +1346,34 @@ def max_edit_frames_that_load( height: int, *, frame_cap: int, + min_frames: int = 1, job_filter: LocalJobFilter, ) -> int: - """Largest frame count at or below ``frame_cap`` that ``decide_edit_job`` loads. + """Largest frame count at or below ``frame_cap`` that edit pricing loads. 1920x1088x505 asks about 41 GiB on the measured reserved curve and 422s everywhere at or under 40 GB. That canvas is the letterbox of a 1080p picture. Home passes this cap into the encode window so that 1080p job runs at the longest window that - fits. When nothing fits, return ``frame_cap`` and let the loader 422. + fits. Single-tile decode tokens stay within ``MEASURED_MAX_DECODE_TOKENS`` + so automatic context padding never grows a short 4K retake into the + 73-frame WDDM paging zone; in Brave mode an explicit selection above that + ceiling (``min_frames``) can still reach the VRAM cap as an unmeasured bet. + When nothing fits, return ``frame_cap`` and let the loader 422. """ if frame_cap < 1: return frame_cap + route = budget_route("edit", job_filter.profile) + max_decode_tokens = MEASURED_MAX_DECODE_TOKENS.get(("edit", route)) def loads(frames: int) -> bool: - # Priced, not gated: shortening a window answers memory. The unmeasured-cell gate does not move with length. + if ( + max_decode_tokens is not None + and (job_filter.budget_mode == "cautious" or frames > min_frames) + and decode_tile_tokens(height, width, frames) > max_decode_tokens + ): + return False + # Priced, not admitted: shortening a window answers memory. decision = _decide_priced_edit_job( width, height, @@ -1520,7 +1405,7 @@ def advertised_fast_durations( *, job_filter: LocalJobFilter, ) -> list[int]: - """Keep Fast cells that ``decide_video_job`` would load. Not a full-mode envelope. + """Keep Fast cells that ``decide_video_job`` admits. Not a full-mode envelope. Filtering with ``fits(..., "full_models_loading")`` would hide 720p/20s on a 5090 that streams it. Darwin never compares free RAM to the CUDA stream curve @@ -1541,39 +1426,50 @@ def advertised_fast_durations( # window over-asked the small 41-frame windows, which refuses jobs a 16 GB card loads, and # under-asked 1440p's 129-frame windows. The coefficients keep a small margin over the 4K # points; lowering either leaves the 4K cells at zero margin. -_WINDOWED_PLATEAU_GIB_PER_TOKEN = 1.05e-4 +WINDOWED_PLATEAU_GIB_PER_TOKEN = 1.05e-4 +_WINDOWED_PLATEAU_GIB_PER_TOKEN = WINDOWED_PLATEAU_GIB_PER_TOKEN # Two windows pay most of the plateau step when the second window is full (1440p at 10 s and -# 24 fps is exactly that: 129 frames then 112 more). A short last window grows much less, and -# the job budget does not see the last window's length, so every two-window job pays the full -# step. That over-asks a short last window (4K at 3 s) until a run measures it. -_WINDOWED_TWO_WINDOW_GIB_PER_TOKEN = 6.5e-5 +# 24 fps is 129 frames then 112 new + 17 carry = 129: G1 peaked at 25.58 GiB vs 26.58 ask). +# When the second window is shorter (G2a 4K 73f has a 41f second window and peaked at 21.80 +# GiB; G2b 1440p 145f has a 33f second window and peaked at 21.88 GiB, with window 2 at 18.52 +# GiB), window 2's own working set scales with its tokens ``last_tokens`` while still carrying +# window 1's overlap state (``_WINDOWED_TWO_WINDOW_GIB_PER_TOKEN * tokens``), and the job peak +# is ``max(base_law(t1), base_law(t2) + c_2w * t1)``. +WINDOWED_TWO_WINDOW_GIB_PER_TOKEN = 6.5e-5 +_WINDOWED_TWO_WINDOW_GIB_PER_TOKEN = WINDOWED_TWO_WINDOW_GIB_PER_TOKEN -def _windows_windowed_extra_gib(windows: int, tokens: float) -> float: +def windows_windowed_extra_gib(windows: int, tokens: float) -> float: if windows >= PEAK_PLATEAU_WINDOWS: - return _WINDOWED_PLATEAU_GIB_PER_TOKEN * tokens + return WINDOWED_PLATEAU_GIB_PER_TOKEN * tokens if windows == 2: - return _WINDOWED_TWO_WINDOW_GIB_PER_TOKEN * tokens + return WINDOWED_TWO_WINDOW_GIB_PER_TOKEN * tokens return 0.0 +_windows_windowed_extra_gib = windows_windowed_extra_gib + + # Mac (MPS) windowed price above the single-pass law, per token of one window, on the same # basis as the law itself: the smallest allocator cap that still passes, not the native # peak, which holds cache the cap would force out. The carry and the earlier windows leave # allocator state behind that grows with the window's tokens, and the peak climbs for two # windows past the first and then holds. The Mac price sits above the Windows one because -# the 4K cap runs landed above where the Windows coefficient would put them. A fixed figure -# under-asks the 4K cap edge and the 1440p windows; lowering either coefficient re-opens the -# 4K edge, which the 4K price covers by about 0.1 GiB. -_MAC_WINDOWED_PLATEAU_GIB_PER_TOKEN = 1.30e-4 - -# Two windows pay most of the plateau step when the second window is full (1440p at 10 s and -# 24 fps). A short last window grows much less (4K at 3 s), and the job budget does not see -# the last window's length, so every two-window job pays the full step. That over-asks the -# 4K 3 s cell by about 3 GiB until a run prices a last window of that length on the Mac. -# The 1440p two-window step is read off native runs, not a capped one. -_MAC_WINDOWED_TWO_WINDOW_GIB_PER_TOKEN = 7.5e-5 +# the 4K and 1440p cap runs landed above where the Windows coefficient would put them. +# A fixed figure under-asks the 4K cap edge and the 1440p windows; the plateau price +# (1.15e-4) clears the 4K 7-window edge in (28.4, 29.2] by +0.06..+0.86 GiB (29.26 ask; +# +0.19 above the 29.07 peak at cap 29.2) and the 1440p 5-window edge in (30.7, 31.7] by +# +0.01..+1.01 GiB (31.71 ask; +0.41 above the 31.30 peak at cap 31.7). +_MAC_WINDOWED_PLATEAU_GIB_PER_TOKEN = 1.15e-4 + +# Two windows pay ``max(base_law(t1), base_law(t2) + _MAC_WINDOWED_TWO_WINDOW_GIB_PER_TOKEN * t1)``, +# matching the Windows rule: a full second window at 1440p (10 s at 24 fps, 241f) asks 29.52 GiB +# (+0.27 above its 29.25 passing cap; 7.5e-5 sat 0.05 under it; 4K 81f full last asks 27.26 vs +# <= 26.0 passing cap), while a short second window asks 24.53 GiB at 4K 73f (41f last, +1.13 +# above its 23.4 passing cap) and 24.51 GiB at 1440p 145f (33f last, where window 1 binds above +# its 23.2 passing cap). +_MAC_WINDOWED_TWO_WINDOW_GIB_PER_TOKEN = 8.0e-5 def _mac_windowed_extra_gib(windows: int, tokens: float) -> float: @@ -1584,20 +1480,51 @@ def _mac_windowed_extra_gib(windows: int, tokens: float) -> float: return 0.0 -def fast_job_stream_gib(tokens: float, *, windows: int, darwin: bool) -> float: +def _fast_base_stream_gib(tokens: float, *, darwin: bool) -> float: + if darwin: + return _mac_fast_stream_required_gib(tokens) + return max( + _windows_fast_stream_required_gib(tokens), + _windows_fast_reserved_required_gib(tokens), + ) + + +def fast_job_stream_gib( + tokens: float, + *, + windows: int, + darwin: bool, + last_tokens: float | None = None, +) -> float: """The stream ask of one Fast pass inside a job of ``windows`` windows. Run logs print it next to the measured peak, so a refit has both numbers.""" + base_t1 = _fast_base_stream_gib(tokens, darwin=darwin) + if windows == 2: + t2 = tokens if last_tokens is None else last_tokens + base_t2 = _fast_base_stream_gib(t2, darwin=darwin) + extra = ( + _mac_windowed_extra_gib(2, tokens) + if darwin + else _windows_windowed_extra_gib(2, tokens) + ) + return max(base_t1, base_t2 + extra) if darwin: - return _mac_fast_stream_required_gib(tokens) + _mac_windowed_extra_gib(windows, tokens) + return base_t1 + _mac_windowed_extra_gib(windows, tokens) return max( _windows_fast_stream_required_gib(tokens), _windows_fast_reserved_required_gib(tokens) + _windows_windowed_extra_gib(windows, tokens), ) -def edit_job_stream_gib(tokens: float, *, darwin: bool) -> float: +def edit_job_stream_gib( + tokens: float, *, darwin: bool, decode_tokens: float | None = None +) -> float: """The stream ask of one Retake or Extend window. Run logs print it next to the peak.""" - return _mac_edit_stream_required_gib(tokens) if darwin else _edit_stream_required_gib(tokens) + return ( + _mac_edit_stream_required_gib(tokens) + if darwin + else _edit_stream_required_gib(tokens, decode_tokens=decode_tokens) + ) def _windows_fast_stream_required_gib(tokens: float) -> float: @@ -1620,9 +1547,14 @@ def _mac_fast_stream_required_gib(tokens: float) -> float: return _MAC_FAST_STREAM.required_gib(tokens) -def _edit_stream_required_gib(tokens: float) -> float: - """Edit stream requirement on the reserved-basis row.""" - return _EDIT_STREAM.required_gib(tokens) +def _edit_stream_required_gib( + tokens: float, *, decode_tokens: float | None = None +) -> float: + """Edit stream requirement: max of denoise and single-tile decode reserved laws.""" + base = _EDIT_STREAM.required_gib(tokens) + if decode_tokens is None: + return base + return max(base, _EDIT_DECODE_STREAM.required_gib(decode_tokens)) def _mac_edit_stream_required_gib(tokens: float) -> float: @@ -1667,6 +1599,7 @@ def _decide_windows_fast_job( seq: float, *, windows: int = 1, + last_tokens: float | None = None, job_filter: LocalJobFilter, ) -> VideoJobDecision: """Windows Fast (2.3 and 2.5) availability from the continuous model, then full-vs-stream pick. @@ -1695,7 +1628,9 @@ def _decide_windows_fast_job( estimated_giB("full_models_loading", seq), _windows_fast_full_reserved_required_gib(seq), ) - stream_gib = fast_job_stream_gib(seq, windows=windows, darwin=False) + stream_gib = fast_job_stream_gib( + seq, windows=windows, darwin=False, last_tokens=last_tokens + ) available = job_filter.budget.available_vram_gib total = job_filter.budget.total_vram_gib @@ -1755,6 +1690,29 @@ def _decide_windows_fast_job( # limit (64-bit indexing), so the fence is Darwin-only by construction. _MPS_TRANSFORMER_TOKEN_FENCE = 116_000 +# ltx-core's disk-streaming read buffers: host_buffers + prefetch_depth (2 + 2 at the +# StreamingConfig defaults Desktop runs), each sized to the largest streamed block, plus +# DeviceStager's two 64 MiB buckets. On MPS they are ordinary host memory outside +# recommended_max, so the Mac ask carries them. Re-check both on an ltx-core bump. +_MAC_DISK_STREAM_HOST_BUFFERS: Final = 4 +_MAC_DEVICE_STAGER_BYTES: Final = 2 * (64 << 20) + + +def mac_disk_stream_host_gib(model_id: LTXLocalModelId | None) -> float: + """Host memory the Mac disk-streaming loader holds outside the MPS pool. + + An unset or future model id (budget pricing outlives the spec table) prices the + largest known block, so it is never under-charged and never crashes the lookup. + """ + if model_id in ALL_LTX_LOCAL_MODEL_IDS: + unit_bytes = get_ltx_model_spec(model_id).disk_stream_unit_bytes + else: + unit_bytes = max( + get_ltx_model_spec(known).disk_stream_unit_bytes + for known in ALL_LTX_LOCAL_MODEL_IDS + ) + return (_MAC_DISK_STREAM_HOST_BUFFERS * unit_bytes + _MAC_DEVICE_STAGER_BYTES) / _GIB + # Full-resident policy evidence (for decide_mac_job below): interleaved # DISK-vs-NONE runs. Per-feature bracket evidence lives with each curve @@ -1774,17 +1732,22 @@ def decide_mac_job( profiles replace. Full resident stays unselectable (interleaved DISK-vs-NONE comparison: full resident only modestly faster at several times the pool — never the better pick on shared unified memory). - Unknown pool fails closed to unsupported. No RAM gate: Mac DISK - streaming maps from disk with no separate pinned set (that pin is - CUDA-offload-specific); the pool lives inside total RAM, so the pool - comparison already covers memory. Process mode flows through, so - unsupported still rejects first. - - Callers supply the feature's stream requirement; this core owns only the - pool comparison and the never-full policy. The MPS sequence fence runs - before the pool comparison (a fence verdict never prints pool figures), - after unsupported (a dead machine reports unsupported, not the fence). + Unknown pool fails closed to unsupported. The ask adds the + disk-streaming loader's host read buffers (``mac_disk_stream_host_gib``, + about 3 GiB for a 22B bf16 transformer): they sit in ordinary memory + outside the pool, and recommended_max leaves the rest of RAM to the OS, so + the pool pays for them. There is no separate RAM gate. Process mode flows + through, so unsupported still rejects first. + + Callers supply the feature's MPS stream requirement; this core adds the + host buffers once, then owns the pool comparison and the never-full + policy. Every verdict carries the charged ask, so readouts, tight-fit and + over figures compare the same number the gate did. The MPS sequence fence + runs before the pool comparison (a fence verdict never prints pool + figures), after unsupported (a dead machine reports unsupported, not the + fence). """ + stream_gib += mac_disk_stream_host_gib(job_filter.profile.model_id) full_gib = estimated_giB("full_models_loading", seq) if ( diff --git a/backend/server_utils/heartbeat.py b/backend/server_utils/heartbeat.py index 036188443..fd811a1b5 100644 --- a/backend/server_utils/heartbeat.py +++ b/backend/server_utils/heartbeat.py @@ -23,6 +23,7 @@ from mps_prebuilt_ext import mps_memory_sample, reset_mps_sdpa_stats from server_utils.generation_liveness import liveness_hold from server_utils.units import gib +from services.gpu_info.run_peak import fold_and_reset_cuda_peak, note_free_sample logger = logging.getLogger(__name__) _active = Lock() @@ -36,6 +37,7 @@ def cuda_memory_sample() -> str | None: return None try: free, total = torch.cuda.mem_get_info() + note_free_sample(int(free)) # Retries are cudaMalloc failures that flushed the cache; a count that climbs # while reserved sits at capacity is allocator thrash, not slow compute. retries = int(torch.cuda.memory_stats().get("num_alloc_retries", 0)) @@ -59,13 +61,7 @@ def _device_sample() -> str | None: def _reset_stats() -> None: """Reset per-run counters so a heartbeat's peak/backend counts start fresh.""" reset_mps_sdpa_stats() # no-op off MPS - try: - import torch # noqa: PLC0415 - - if torch.cuda.is_available(): - torch.cuda.reset_peak_memory_stats() - except Exception: - pass + fold_and_reset_cuda_peak() @contextmanager diff --git a/backend/services/a2v_pipeline/a2v_pipeline.py b/backend/services/a2v_pipeline/a2v_pipeline.py index 47817d503..0e679517e 100644 --- a/backend/services/a2v_pipeline/a2v_pipeline.py +++ b/backend/services/a2v_pipeline/a2v_pipeline.py @@ -5,6 +5,7 @@ from typing import TYPE_CHECKING, Protocol from api_types import ImageConditioningInput +from services.fast_video_pipeline.nag_config import NagConfig if TYPE_CHECKING: import torch @@ -43,4 +44,5 @@ def generate( audio_max_duration: float | None, output_path: str, chunk_pixel_frames: int | None = None, + nag: NagConfig | None = None, ) -> None: ... diff --git a/backend/services/a2v_pipeline/distilled_a2v_pipeline.py b/backend/services/a2v_pipeline/distilled_a2v_pipeline.py index 42ff9674f..71b91775d 100644 --- a/backend/services/a2v_pipeline/distilled_a2v_pipeline.py +++ b/backend/services/a2v_pipeline/distilled_a2v_pipeline.py @@ -9,80 +9,43 @@ from collections.abc import Iterator, Sequence from dataclasses import dataclass, replace -from typing import TYPE_CHECKING, Any, Protocol, cast +from typing import TYPE_CHECKING, Any, cast import torch from services.audio_channels import stereo_waveform -from services.services_utils import AudioOrNone, TilingConfigType +from services.fast_video_pipeline.nag_config import NagConfig +from services.fast_video_pipeline.nag_distilled import ( + prompts_with_negative, + scoped_chunks, + with_negative_context, +) +from services.patches.nag_cross_attention import NagState +from services.services_utils import TilingConfigType if TYPE_CHECKING: from ltx_core.conditioning import ConditioningItem - from ltx_core.loader.primitives import LoraPathStrengthAndSDOps + from ltx_core.loader import LoraPathStrengthAndSDOps from ltx_core.types import Audio as LtxAudio - from ltx_pipelines.chunks import Chunk, ChunkConfig, DecodedChunk + from ltx_pipelines.chunks import Chunk, ChunkConfig, PlaybackSegment from ltx_pipelines.utils.model_paths import ModelPaths from ltx_pipelines.utils.types import ImageConditioningInput as LtxImageInput - from ltx_pipelines.utils.types import OffloadMode + from ltx_pipelines.utils.types import LoadedImageConditioning, OffloadMode, PipelineOutput @dataclass(frozen=True) class _A2VInputs: - """What both run paths need after the prompt, the stills and the source audio are encoded.""" + """What the run needs after the prompt, the stills and the source audio are encoded.""" - images: list[LtxImageInput] + num_frames: int + images: list[LoadedImageConditioning] generator: torch.Generator noiser: Any video_context: torch.Tensor audio_context: torch.Tensor decoded_audio: LtxAudio encoded_audio_latent: torch.Tensor - audio_spec: Any - - -class _ImageCrfResolver(Protocol): - def resolve_crf(self, images: Sequence[LtxImageInput]) -> list[LtxImageInput]: ... - - -def resolve_image_conditionings( - images: Sequence[tuple[str, int, float]], - image_conditioner: _ImageCrfResolver, -) -> list[LtxImageInput]: - """Build LTX image inputs and fill checkpoint CRF via ImageConditioner.resolve_crf.""" - from ltx_pipelines.utils.types import ImageConditioningInput as LtxImageInput - - ltx_images = [LtxImageInput(path, frame_idx, strength) for path, frame_idx, strength in images] - return image_conditioner.resolve_crf(ltx_images) - - -def encode_stage_image_conditionings( - images: list[LtxImageInput], - *, - height: int, - width: int, - video_encoder: Any, - dtype: torch.dtype, - device: torch.device, -) -> list[Any]: - """Pixel-index image conds for distilled A2V stages. - - Same helper as DistilledPipeline and a2vid_two_stage: frame 0 replaces latent 0; - later frames are keyframes at that pixel index. - - Do not use image_conditionings_by_replacing_latent — it treats frame_idx as a - latent index. Last pixel frame (num_frames-1, e.g. 240 at 10s/24fps) is past the - VAE-compressed sequence (~31 latents) and apply_to empty-slices. - """ - from ltx_pipelines.utils.helpers import combined_image_conditionings - - return combined_image_conditionings( - images=images, - height=height, - width=width, - video_encoder=video_encoder, - dtype=dtype, - device=device, - ) + nag_state: NagState | None = None class DistilledA2VPipeline: @@ -100,7 +63,6 @@ def __init__( loras: Sequence[LoraPathStrengthAndSDOps] | None = None, device: torch.device | None = None, quantization: Any | None = None, - streaming_prefetch_count: int | None = None, *, offload_mode: OffloadMode, ) -> None: @@ -112,6 +74,7 @@ def __init__( VideoDecoder, VideoUpsampler, ) + from ltx_pipelines.distilled import should_use_ancestral_sampler from ltx_pipelines.utils.helpers import get_device if device is None: @@ -143,6 +106,15 @@ def __init__( self.video_decoder = VideoDecoder( model_paths.video_vae(), self.dtype, device, ) + self.use_ancestral_sampler = should_use_ancestral_sampler(model_paths.transformer()) + + def _sampler_kwargs(self, seed: int, noise_seed_offset: int) -> dict[str, Any]: + """Ancestral overrides on an LTX 2.5+ checkpoint, as ``DistilledPipeline`` does. Empty keeps Euler.""" + from ltx_pipelines.distilled import ancestral_sampler_kwargs + + if not self.use_ancestral_sampler: + return {} + return ancestral_sampler_kwargs(seed, self.dtype, noise_seed_offset) def _prepare( self, @@ -153,28 +125,38 @@ def _prepare( width: int, num_frames: int, frame_rate: float, - images: list[tuple[str, int, float]], + images: list[LtxImageInput], audio_path: str, audio_start_time: float, audio_max_duration: float | None, + nag: NagConfig | None = None, ) -> _A2VInputs: """Validate, encode the prompt, the stills and the source audio. Shared by both run paths.""" from ltx_core.components.noisers import GaussianNoiser from ltx_core.model.audio_vae import encode_audio as vae_encode_audio from ltx_core.types import AudioLatentShape - from ltx_pipelines.utils.helpers import assert_resolution + from ltx_pipelines.chunks.conditionings import assert_image_frames_in_clip + from ltx_pipelines.utils.helpers import assert_resolution, snap_frames_to_grid from ltx_pipelines.utils.media_io import decode_audio_from_file - from ltx_pipelines.utils.types import ModalitySpec - assert_resolution(height=height, width=width, is_two_stage=True) - ltx_images = resolve_image_conditionings(images, self.image_conditioner) + # Every later step sizes the clip from the snapped count, so a still is checked against it too. + num_frames = snap_frames_to_grid(num_frames) + loaded_images = self.image_conditioner.load_conditionings(images) + assert_image_frames_in_clip(loaded_images, num_frames) generator = torch.Generator(device=self.device).manual_seed(seed) noiser = GaussianNoiser(generator=generator) - # Text encode (positive only). - (ctx_p,) = self.prompt_encoder([prompt]) - video_context = ctx_p.video_encoding + # Text encode (positive, plus negative when NAG is active). + contexts = self.prompt_encoder(prompts_with_negative(prompt, nag)) + ctx_p = contexts[0] + if nag is None: + video_context = ctx_p.video_encoding + nag_state = None + else: + video_context, nag_state = with_negative_context( + ctx_p.video_encoding, contexts[1].video_encoding, nag + ) audio_context = ctx_p.audio_encoding assert audio_context is not None, "A2V pipeline requires audio context from text encoder" @@ -196,23 +178,16 @@ def _prepare( else: encoded_audio_latent = encoded_audio_latent[:, :, :target_frames] - # The same frozen, unnoised source audio drives both stages. - audio_spec = ModalitySpec( - latent=encoded_audio_latent, - conditioning_fps=frame_rate, - context=audio_context, - frozen=True, - noise_scale=0.0, - ) return _A2VInputs( - images=ltx_images, + num_frames=num_frames, + images=loaded_images, generator=generator, noiser=noiser, video_context=video_context, audio_context=audio_context, decoded_audio=decoded_audio, encoded_audio_latent=encoded_audio_latent, - audio_spec=audio_spec, + nag_state=nag_state, ) @torch.inference_mode() @@ -224,19 +199,19 @@ def __call__( width: int, num_frames: int, frame_rate: float, - images: list[tuple[str, int, float]], + images: list[LtxImageInput], audio_path: str, audio_start_time: float = 0.0, audio_max_duration: float | None = None, tiling_config: TilingConfigType | None = None, - ) -> tuple[Iterator[torch.Tensor], AudioOrNone]: - from ltx_core.types import Audio - from ltx_pipelines.utils.constants import DISTILLED_SIGMA_VALUES, STAGE_2_DISTILLED_SIGMA_VALUES - from ltx_pipelines.utils.denoisers import SimpleDenoiser - from ltx_pipelines.utils.helpers import create_initial_video_latent - from ltx_pipelines.utils.types import ModalitySpec, VideoAudio - - run = self._prepare( + nag: NagConfig | None = None, + ) -> PipelineOutput: + """One window over the whole clip: the same two stages as ``stream_chunks``, without carry.""" + from ltx_pipelines.chunks import ChunkConfig, pipeline_output_from_chunks + from ltx_pipelines.utils.helpers import snap_frames_to_grid + + snapped = snap_frames_to_grid(num_frames) + chunks = self.stream_chunks( prompt=prompt, seed=seed, height=height, @@ -245,97 +220,13 @@ def __call__( frame_rate=frame_rate, images=images, audio_path=audio_path, + chunk_config=ChunkConfig(chunk_pixel_frames=snapped, next_video_carry_frames=0), audio_start_time=audio_start_time, audio_max_duration=audio_max_duration, + tiling_config=tiling_config, + nag=nag, ) - dtype = torch.bfloat16 - video_context, audio_context = run.video_context, run.audio_context - decoded_audio = run.decoded_audio - audio_spec = run.audio_spec - - # Stage 1: Half-resolution video generation with frozen audio. - stage_1_sigmas = torch.Tensor(DISTILLED_SIGMA_VALUES).to(self.device) - stage_1_w, stage_1_h = width // 2, height // 2 - stage_1_conditionings = self.image_conditioner( - lambda enc: encode_stage_image_conditionings( - run.images, - height=stage_1_h, - width=stage_1_w, - video_encoder=enc, - dtype=dtype, - device=self.device, - ) - ) - stage_1_video_latent = create_initial_video_latent( - width=stage_1_w, - height=stage_1_h, - frames=num_frames, - fps=frame_rate, - device=self.device, - dtype=dtype, - # Transformer latent geometry, not the decoder's tiling scale (2x8x8 on the 2.5 DiffVAE). - scale_factors=self.stage.video_scale_factors, - ) - - video_state, _ = self.stage( - denoiser=SimpleDenoiser(video_context, audio_context), - sigmas=stage_1_sigmas, - noiser=run.noiser, - modalities=VideoAudio( - video=ModalitySpec( - latent=stage_1_video_latent, - conditioning_fps=frame_rate, - context=video_context, - conditionings=stage_1_conditionings, - ), - audio=audio_spec, - ), - ) - - # Upsample video 2x. - assert video_state is not None - upscaled_video_latent = self.upsampler(video_state.latent[:1]) - - # Stage 2: Full-resolution refinement with frozen audio. - stage_2_sigmas = torch.Tensor(STAGE_2_DISTILLED_SIGMA_VALUES).to(self.device) - stage_2_conditionings = self.image_conditioner( - lambda enc: encode_stage_image_conditionings( - run.images, - height=height, - width=width, - video_encoder=enc, - dtype=dtype, - device=self.device, - ) - ) - - video_state, _ = self.stage( - denoiser=SimpleDenoiser(video_context, audio_context), - sigmas=stage_2_sigmas, - noiser=run.noiser, - modalities=VideoAudio( - video=ModalitySpec( - latent=upscaled_video_latent, - conditioning_fps=frame_rate, - context=video_context, - conditionings=stage_2_conditionings, - noise_scale=stage_2_sigmas[0].item(), - ), - audio=audio_spec, - ), - ) - - # Decode video; return original audio (not VAE-decoded) for fidelity. - assert video_state is not None - decoded_video = self.video_decoder(video_state.latent, tiling_config, run.generator) - - # Trim waveform to target video duration so the muxed output doesn't - # extend beyond the generated video frames. - max_samples = round(num_frames / frame_rate * decoded_audio.sampling_rate) - trimmed_waveform = decoded_audio.waveform.squeeze(0)[..., :max_samples] - original_audio = Audio(waveform=trimmed_waveform, sampling_rate=decoded_audio.sampling_rate) - - return decoded_video, original_audio + return pipeline_output_from_chunks(chunks, num_frames=snapped, tiling_config=tiling_config) @torch.inference_mode() def stream_chunks( @@ -346,13 +237,14 @@ def stream_chunks( width: int, num_frames: int, frame_rate: float, - images: list[tuple[str, int, float]], + images: list[LtxImageInput], audio_path: str, chunk_config: ChunkConfig, audio_start_time: float = 0.0, audio_max_duration: float | None = None, tiling_config: TilingConfigType | None = None, - ) -> Iterator[DecodedChunk]: + nag: NagConfig | None = None, + ) -> Iterator[PlaybackSegment]: """The same two stages in overlapping temporal windows, as ``a2vid_two_stage`` does it. Each window takes its slice of the frozen source audio. The decoded windows carry @@ -366,11 +258,8 @@ def stream_chunks( replace_chunks_audio, spatially_upsample_chunks, ) - from ltx_pipelines.chunks.conditionings import ( - assert_image_frames_in_clip, - image_conditionings_for_chunk, - images_for_chunk, - ) + from ltx_pipelines.chunks.conditionings import image_conditionings_for_chunk, images_for_chunk + from ltx_pipelines.distilled import ANCESTRAL_NOISE_SEED_OFFSET, ANCESTRAL_STAGE_2_NOISE_SEED_OFFSET from ltx_pipelines.utils.constants import DISTILLED_SIGMA_VALUES, STAGE_2_DISTILLED_SIGMA_VALUES from ltx_pipelines.utils.types import VideoAudio @@ -385,15 +274,16 @@ def stream_chunks( audio_path=audio_path, audio_start_time=audio_start_time, audio_max_duration=audio_max_duration, + nag=nag, ) - assert_image_frames_in_clip(run.images, num_frames) + num_frames = run.num_frames def make_video_conditionings(chunk: Chunk) -> list[ConditioningItem]: if chunk.video is None or not images_for_chunk(chunk, run.images): return [] return self.image_conditioner( lambda enc: image_conditionings_for_chunk( - chunk, images=run.images, video_encoder=enc, color_space=None + chunk, images=run.images, video_encoder=enc ) ) @@ -412,7 +302,13 @@ def make_video_conditionings(chunk: Chunk) -> list[ConditioningItem]: stage_1_sigmas = torch.Tensor(DISTILLED_SIGMA_VALUES).to(self.device) stage_2_sigmas = torch.Tensor(STAGE_2_DISTILLED_SIGMA_VALUES).to(self.device) base = denoise_chunks( - chunks, self.stage, sigmas=stage_1_sigmas, noiser=run.noiser, fps=frame_rate, freeze_audio=True + chunks, + self.stage, + sigmas=stage_1_sigmas, + noiser=run.noiser, + fps=frame_rate, + freeze_audio=True, + **self._sampler_kwargs(seed, ANCESTRAL_NOISE_SEED_OFFSET), ) refined = denoise_chunks( spatially_upsample_chunks(base, self.upsampler), @@ -421,6 +317,7 @@ def make_video_conditionings(chunk: Chunk) -> list[ConditioningItem]: noiser=run.noiser, fps=frame_rate, freeze_audio=True, + **self._sampler_kwargs(seed, ANCESTRAL_STAGE_2_NOISE_SEED_OFFSET), ) decoded = decode_chunks( refined, @@ -434,4 +331,5 @@ def make_video_conditionings(chunk: Chunk) -> list[ConditioningItem]: source = Audio( waveform=run.decoded_audio.waveform.squeeze(0), sampling_rate=run.decoded_audio.sampling_rate ) - return replace_chunks_audio(decoded, source, frame_rate) + out = replace_chunks_audio(decoded, source, frame_rate) + return scoped_chunks(out, run.nag_state) if run.nag_state is not None else out diff --git a/backend/services/a2v_pipeline/ltx_a2v_pipeline.py b/backend/services/a2v_pipeline/ltx_a2v_pipeline.py index 20353921a..60a4d37e5 100644 --- a/backend/services/a2v_pipeline/ltx_a2v_pipeline.py +++ b/backend/services/a2v_pipeline/ltx_a2v_pipeline.py @@ -2,19 +2,20 @@ from __future__ import annotations -from collections.abc import Iterator from typing import TYPE_CHECKING import torch from api_types import ImageConditioningInput +from services.fast_video_pipeline.nag_config import NagConfig from services.fast_video_pipeline.windowed_run import encode_result, measured_windows, plan_windows -from services.ic_lora_pipeline.ic_lora_inference import InferenceResult +from services.ic_lora_pipeline.ic_lora_inference import InferenceResult, inference_result_from_output from services.ltx_pipeline_common import ( build_model_paths, resolve_tiling_config, + to_ltx_images, ) -from services.services_utils import AudioOrNone, TilingConfigType, device_supports_fp8 +from services.services_utils import TilingConfigType, device_supports_fp8 if TYPE_CHECKING: from ltx_pipelines.chunks import ChunkConfig @@ -63,7 +64,7 @@ def __init__( audio_vae_path: str | None = None, duration_head_path: str | None = None, ) -> None: - from ltx_core.loader.primitives import LoraPathStrengthAndSDOps + from ltx_core.loader import LoraPathStrengthAndSDOps from ltx_core.loader.sd_ops import LTXV_LORA_COMFY_RENAMING_MAP from ltx_core.quantization.fp8_cast import build_policy as build_fp8_cast_policy @@ -86,7 +87,6 @@ def __init__( loras=lora_entries, device=device, quantization=build_fp8_cast_policy(checkpoint_path) if device_supports_fp8(device) else None, - streaming_prefetch_count=streaming_prefetch_count, offload_mode=offload_mode, ) @@ -105,20 +105,23 @@ def _run_inference( audio_start_time: float, audio_max_duration: float | None, tiling_config: TilingConfigType, - ) -> tuple[torch.Tensor | Iterator[torch.Tensor], AudioOrNone]: - return self.pipeline( + nag: NagConfig | None = None, + ) -> InferenceResult: + output = self.pipeline( prompt=prompt, seed=seed, height=height, width=width, num_frames=num_frames, frame_rate=frame_rate, - images=[(img.path, img.frame_idx, img.strength) for img in images], + images=to_ltx_images(images), audio_path=audio_path, audio_start_time=audio_start_time, audio_max_duration=audio_max_duration, tiling_config=tiling_config, + nag=nag, ) + return inference_result_from_output(output) def _stream_windows( self, @@ -135,9 +138,8 @@ def _stream_windows( audio_max_duration: float | None, tiling_config: TilingConfigType, chunk_config: ChunkConfig, + nag: NagConfig | None = None, ) -> InferenceResult: - from ltx_pipelines.chunks import split_decoded_chunks - chunks = self.pipeline.stream_chunks( prompt=prompt, seed=seed, @@ -145,16 +147,15 @@ def _stream_windows( width=width, num_frames=num_frames, frame_rate=frame_rate, - images=[(img.path, img.frame_idx, img.strength) for img in images], + images=to_ltx_images(images), audio_path=audio_path, chunk_config=chunk_config, audio_start_time=audio_start_time, audio_max_duration=audio_max_duration, tiling_config=tiling_config, + nag=nag, ) - video, audio, audio_sampling_rate = split_decoded_chunks(chunks) - streams = (video, chunks) if audio is None else (video, audio, chunks) - return InferenceResult(video, audio, num_frames, tiling_config, audio_sampling_rate, streams) + return InferenceResult(chunks, num_frames, tiling_config, (chunks,)) @torch.inference_mode() def generate( @@ -173,6 +174,7 @@ def generate( audio_max_duration: float | None, output_path: str, chunk_pixel_frames: int | None = None, + nag: NagConfig | None = None, ) -> None: from services.denoising_progress import distilled_total_steps, track_denoising @@ -193,7 +195,7 @@ def generate( ) with track_denoising(distilled_total_steps() * chunk_count), measured: if chunk_config is None: - video, audio = self._run_inference( + result = self._run_inference( prompt=prompt, negative_prompt=negative_prompt, seed=seed, @@ -207,8 +209,8 @@ def generate( audio_start_time=audio_start_time, audio_max_duration=audio_max_duration, tiling_config=tiling_config, + nag=nag, ) - result = InferenceResult(video, audio, num_frames, tiling_config) else: result = self._stream_windows( prompt=prompt, @@ -223,5 +225,6 @@ def generate( audio_max_duration=audio_max_duration, tiling_config=tiling_config, chunk_config=chunk_config, + nag=nag, ) encode_result(result, fps=int(frame_rate), output_path=output_path, streamed=chunk_config is not None) diff --git a/backend/services/analytics.py b/backend/services/analytics.py index c4e849f55..3756ae24e 100644 --- a/backend/services/analytics.py +++ b/backend/services/analytics.py @@ -9,11 +9,12 @@ from contextlib import contextmanager from typing import Literal, TypedDict, cast -from api_types import PipelineOffloadMode, PromptProvenance, VideoLoadMode +from api_types import PipelineOffloadMode, PromptProvenance, PromptRewriteSource, VideoLoadMode from services.features.ic_lora_recipes import ( get_ic_lora_recipe, ic_lora_skips_prompt_enhancement, ) +from services.features.image.feature_id import FEATURE as TEXT_TO_IMAGE_FEATURE from services.features.lora_recipes import get_lora_recipe from services.http_client.http_client import HTTPClient, HttpTransportError from services.records import GenerationRecord @@ -43,6 +44,7 @@ "error_code", "load_mode", "offload_mode", + "prompt_rewrite", ) _ENDED_LINK_KEYS = ("generation_id", "attempt") @@ -180,6 +182,24 @@ def queued_prompt_provenance( return unenhanced_prompt_provenance(provenance) prompt = params.get("prompt") prompt_text = prompt if isinstance(prompt, str) else "" + if generation.feature == TEXT_TO_IMAGE_FEATURE: + # Image jobs have no text-encoding path: only a rewrite can enhance them. A fal job + # always has one, as fal expands the prompt when no local or Gemini rewrite runs. + enhancer_exists = ( + params.get("provider") == "fal" + or enhancement.local_enhancer_available + or enhancement.gemini_video_enhance + ) + rewrites = ( + enhancement.explore_auto_enhance_prompts + and enhancer_exists + and bool(prompt_text.strip()) + ) + return prompt_provenance_label( + provenance, + enhanced_locally=provenance == "typed" and rewrites, + enhance_via_api=False, + ) resolved = resolution_for_provenance( provenance, prompt=prompt_text, @@ -243,6 +263,7 @@ class QueuedExecutionModes(TypedDict, total=False): load_mode: VideoLoadMode | None offload_mode: PipelineOffloadMode | None + prompt_rewrite: PromptRewriteSource | None def queued_generation_details( @@ -272,6 +293,12 @@ def queued_generation_details( params = generation.spec.get("params") if not isinstance(params, dict): return details + if generation.feature == TEXT_TO_IMAGE_FEATURE: + details["kind"] = "image" + details["execution"] = "fal_api" if params.get("provider") == "fal" else "local" + width, height = params.get("width"), params.get("height") + if isinstance(width, int) and isinstance(height, int): + details["resolution"] = pixel_resolution(width, height) for source, target in ( ("model", "model"), ("duration", "duration_sec"), @@ -335,6 +362,9 @@ def queued_generation_details( offload_mode = modes.get("offload_mode") if offload_mode is not None: details["offload_mode"] = offload_mode + prompt_rewrite = modes.get("prompt_rewrite") + if prompt_rewrite is not None: + details["prompt_rewrite"] = prompt_rewrite return details diff --git a/backend/services/dashboard_stats.py b/backend/services/dashboard_stats.py index 19dd436bb..9345501e0 100644 --- a/backend/services/dashboard_stats.py +++ b/backend/services/dashboard_stats.py @@ -26,6 +26,7 @@ _ACTIVITY_FEATURES = ( "text-to-video", "image-to-video", + "keyframes", "audio-to-video", "lora", "retake", @@ -33,7 +34,7 @@ "ic-lora", ) _RENDER_GROUPS = frozenset( - {"text-to-video", "image-to-video", "audio-to-video", "lora"} + {"text-to-video", "image-to-video", "keyframes", "audio-to-video", "lora"} ) _EDIT_FEATURES = frozenset({"retake", "extend"}) _LORA_GROUPS = frozenset({"lora", "ic-lora"}) diff --git a/backend/services/device_calibration_store.py b/backend/services/device_calibration_store.py new file mode 100644 index 000000000..a35049fd6 --- /dev/null +++ b/backend/services/device_calibration_store.py @@ -0,0 +1,385 @@ +"""SQLite persistence for the per-device calibration Pareto frontier.""" + +from __future__ import annotations + +import json +import sqlite3 +from collections.abc import Callable, Mapping +from typing import Final, TypeGuard + +from pydantic import TypeAdapter + +from runtime_config.budget_decision import LoadMode +from runtime_config.device_calibration import ( + CalibrationBucket, + DeviceIdentity, + EnvelopePoint, + FrontierPoint, + merge_frontier, +) +from runtime_config.eta import ( + implied_envelope_factor, + implied_machine_factor, + median_machine_factor, +) +from runtime_config.measured_cells import BudgetFeature +from services.features.ic_lora_recipes import IC_LORA_RECIPES +from services.records import UnavailableError + +_BUDGET_FEATURE: TypeAdapter[BudgetFeature] = TypeAdapter(BudgetFeature) +_LOAD_MODE: TypeAdapter[LoadMode] = TypeAdapter(LoadMode) + +# Driver updates can shift reported total VRAM by tens of MiB (e.g. 27.2 MiB on +# an RTX 5090 between 591.86 and 595.79), while distinct hardware tiers stay at +# least 4 GiB apart. +TOTAL_MEMORY_TOLERANCE_BYTES: Final = 512 * 1024**2 +# 2026-11-02 UTC: skip pre-1.6.0 runs when bootstrapping from ``generations``. +_MIN_HISTORY_CREATED_AT_MS: Final = 1_793_577_600_000 +_MIN_HISTORY_SAMPLES: Final = 3 + +_IDENTITY_WHERE = ( + "epoch = ? AND system = ? AND gpu_model = ? " + "AND ABS(total_memory_bytes - ?) <= ?" +) +_BUCKET_COLUMNS = ( + "model_id", "feature", "adapter_id", "stage_mode", "load_mode", "tiled", "chunked" +) +_POINT_COLUMNS = ("seq", "canvas_px", "windows", "peak_growth_bytes", "wall_s", "tiles") + + +def _require_int(value: object) -> int: + if isinstance(value, bool) or not isinstance(value, int): + raise TypeError(f"expected int, got {type(value)!r}") + return value + + +def _optional_int(value: object) -> int | None: + if value is None: + return None + return _require_int(value) + + +def _optional_float(value: object) -> float | None: + if value is None or isinstance(value, bool): + return None + if isinstance(value, (int, float)): + return float(value) + return None + + +def _identity_where_params(identity: DeviceIdentity, epoch: int) -> tuple[object, ...]: + return ( + epoch, + identity.system, + identity.gpu_model, + identity.total_memory_bytes, + TOTAL_MEMORY_TOLERANCE_BYTES, + ) + + +def _identity_insert_params(identity: DeviceIdentity, epoch: int) -> tuple[object, ...]: + return (epoch, identity.system, identity.gpu_model, identity.total_memory_bytes) + + +def _bucket_params(bucket: CalibrationBucket) -> tuple[object, ...]: + return ( + bucket.model_id, + bucket.feature, + bucket.adapter_id, + bucket.stage_mode, + bucket.load_mode, + int(bucket.tiled), + int(bucket.chunked), + ) + + +def _calibration_bucket(row: sqlite3.Row) -> CalibrationBucket: + return CalibrationBucket( + model_id=str(row["model_id"]), + feature=_BUDGET_FEATURE.validate_python(row["feature"]), + adapter_id=str(row["adapter_id"]), + stage_mode=str(row["stage_mode"]), + load_mode=_LOAD_MODE.validate_python(row["load_mode"]), + tiled=bool(row["tiled"]), + chunked=bool(row["chunked"]), + ) + + +def _frontier_point(row: sqlite3.Row) -> FrontierPoint: + return FrontierPoint( + point=EnvelopePoint( + seq=float(row["seq"]), + canvas_px=_require_int(row["canvas_px"]), + windows=_require_int(row["windows"]), + tiles=_require_int(row["tiles"]), + ), + peak_growth_bytes=_optional_int(row["peak_growth_bytes"]), + wall_s=_optional_float(row["wall_s"]), + ) + + +def _is_str_object_dict(value: object) -> TypeGuard[dict[str, object]]: + return isinstance(value, dict) + + +def _history_row_factor(system: str, row: sqlite3.Row) -> float | None: + """The row's machine factor, or None. Odd stored values skip the row instead of raising.""" + try: + return _unchecked_history_row_factor(system, row) + except (TypeError, ValueError, OverflowError): + return None + + +def _unchecked_history_row_factor(system: str, row: sqlite3.Row) -> float | None: + started_at = _optional_int(row["started_at"]) + finished_at = _optional_int(row["finished_at"]) + raw_meta = row["output_metadata"] + if started_at is None or finished_at is None or finished_at <= started_at or raw_meta is None: + return None + wall_s = (finished_at - started_at) / 1000.0 + try: + meta_obj: object = json.loads(str(raw_meta)) + spec_obj: object = json.loads(str(row["spec"])) if row["spec"] is not None else {} + except (ValueError, TypeError): + return None + if not _is_str_object_dict(meta_obj) or meta_obj.get("mediaType") != "video": + return None + inner = meta_obj.get("metadata") + if not _is_str_object_dict(inner): + return None + width = _optional_int(inner.get("width")) + height = _optional_int(inner.get("height")) + duration_ms = _optional_int(inner.get("durationMs")) + fps = _optional_float(inner.get("fps")) or 24.0 + if width is None or height is None or duration_ms is None or duration_ms <= 0: + return None + frames = max(1, round((duration_ms / 1000.0) * fps)) + feature = str(row["feature"]) + params = spec_obj.get("params") if _is_str_object_dict(spec_obj) else None + resolution = params.get("resolution") if _is_str_object_dict(params) else None + ic_lora = feature in IC_LORA_RECIPES + stage_2 = not (resolution in ("270p", "360p") or ic_lora) + has_video_src = feature in ("retake", "extend", "motion-track", "revelio", "deblur", "video-guide") or ( + ic_lora and _is_str_object_dict(params) and params.get("duration") is None + ) + eta_sys = system if system in ("Windows", "Linux", "Darwin") else "Windows" + return implied_machine_factor( + wall_s=wall_s, + width=width, + height=height, + frames=frames, + system=eta_sys, + stage_2=stage_2, + ic_lora=ic_lora, + ic_lora_id=feature if ic_lora else None, + source_frames=frames if has_video_src else 0, + reject_clamped=True, + ) + + + +class DeviceCalibrationStore: + def __init__( + self, + connect: Callable[[], sqlite3.Connection], + now_ms: Callable[[], int], + ) -> None: + self._connect = connect + self._now_ms = now_ms + + def load_device_frontier( + self, identity: DeviceIdentity, epoch: int + ) -> Mapping[CalibrationBucket, tuple[FrontierPoint, ...]]: + conn = self._connect() + try: + rows = conn.execute( + f""" + SELECT {", ".join(_BUCKET_COLUMNS)}, {", ".join(_POINT_COLUMNS)} + FROM device_calibration_frontier + WHERE {_IDENTITY_WHERE} + ORDER BY id + """, + _identity_where_params(identity, epoch), + ).fetchall() + except (sqlite3.Error, OSError) as exc: + raise UnavailableError() from exc + finally: + conn.close() + frontier: dict[CalibrationBucket, tuple[FrontierPoint, ...]] = {} + for row in rows: + bucket = _calibration_bucket(row) + merged = merge_frontier(frontier.get(bucket, ()), _frontier_point(row)) + if merged is not None: + frontier[bucket] = merged + return frontier + + def widen_device_frontier( + self, + identity: DeviceIdentity, + epoch: int, + bucket: CalibrationBucket, + point: FrontierPoint, + *, + priced_gib: float, + generation_id: str | None, + conv_vae: bool = False, + ) -> tuple[FrontierPoint, ...] | None: + bucket_params = _bucket_params(bucket) + conn = self._connect() + try: + conn.execute("BEGIN IMMEDIATE") + rows = conn.execute( + f""" + SELECT id, {", ".join(_POINT_COLUMNS)} + FROM device_calibration_frontier + WHERE {_IDENTITY_WHERE} + AND {" AND ".join(f"{column} = ?" for column in _BUCKET_COLUMNS)} + ORDER BY id + """, + (*_identity_where_params(identity, epoch), *bucket_params), + ).fetchall() + stored: dict[int, FrontierPoint] = {} + current: tuple[FrontierPoint, ...] = () + for row in rows: + row_id = _require_int(row["id"]) + row_point = _frontier_point(row) + stored[row_id] = row_point + deduped = merge_frontier(current, row_point) + if deduped is not None: + current = deduped + merged = merge_frontier(current, point) + if merged is None: + # Refresh the wall time only on a row of the same shape. A dominating row is a + # bigger job; its factor must not be derived from a smaller job's wall time. + if point.wall_s is not None: + conn.execute( + f""" + UPDATE device_calibration_frontier + SET wall_s = ?, conv_vae = ?, generation_id = ? + WHERE id = ( + SELECT id FROM device_calibration_frontier + WHERE {_IDENTITY_WHERE} + AND {" AND ".join(f"{column} = ?" for column in _BUCKET_COLUMNS)} + AND seq = ? AND canvas_px = ? AND windows = ? + ORDER BY id DESC + LIMIT 1 + ) + """, + ( + point.wall_s, + int(conv_vae), + generation_id, + *_identity_where_params(identity, epoch), + *bucket_params, + point.point.seq, + point.point.canvas_px, + point.point.windows, + ), + ) + conn.commit() + return None + conn.executemany( + "DELETE FROM device_calibration_frontier WHERE id = ?", + [(row_id,) for row_id, kept in stored.items() if kept not in merged], + ) + values = ( + *_identity_insert_params(identity, epoch), + *bucket_params, + point.point.seq, + point.point.canvas_px, + point.point.windows, + point.peak_growth_bytes, + point.wall_s, + point.point.tiles, + priced_gib, + generation_id, + self._now_ms(), + int(conv_vae), + ) + conn.execute( + f""" + INSERT INTO device_calibration_frontier ( + epoch, system, gpu_model, total_memory_bytes, + {", ".join(_BUCKET_COLUMNS)}, {", ".join(_POINT_COLUMNS)}, + priced_gib, generation_id, recorded_at, conv_vae + ) VALUES ({", ".join("?" for _ in values)}) + """, + values, + ) + conn.commit() + return merged + except (sqlite3.Error, OSError) as exc: + raise UnavailableError() from exc + finally: + conn.close() + + def load_device_machine_factor( + self, identity: DeviceIdentity, epoch: int + ) -> float | None: + conn = self._connect() + try: + frontier_rows = conn.execute( + f""" + SELECT {", ".join(_BUCKET_COLUMNS)}, {", ".join(_POINT_COLUMNS)}, + conv_vae, generation_id + FROM device_calibration_frontier + WHERE {_IDENTITY_WHERE} AND wall_s IS NOT NULL + ORDER BY id DESC + LIMIT 20 + """, + _identity_where_params(identity, epoch), + ).fetchall() + history_rows = conn.execute( + """ + SELECT g.id, g.feature, g.spec, g.started_at, g.finished_at, + a.metadata AS output_metadata + FROM generations g + JOIN assets a ON a.producer_generation_id = g.id AND a.output_ordinal = 0 + WHERE g.status = 'succeeded' + AND g.lane = 'local' + AND g.provider_job_id IS NULL + AND g.started_at IS NOT NULL + AND g.finished_at IS NOT NULL + AND g.created_at >= ? + AND COALESCE(json_extract(g.spec, '$.params.model'), '') NOT IN ( + 'fast', 'pro', 'fast-2.5', 'pro-2.5' + ) + AND json_extract(a.metadata, '$.mediaType') = 'video' + ORDER BY g.created_at DESC + LIMIT 20 + """, + (_MIN_HISTORY_CREATED_AT_MS,), + ).fetchall() + except (sqlite3.Error, OSError) as exc: + raise UnavailableError() from exc + finally: + conn.close() + + factors: list[float] = [] + seen_ids: set[str] = set() + for row in frontier_rows: + bucket = _calibration_bucket(row) + pt = _frontier_point(row) + gen_id = row["generation_id"] + if isinstance(gen_id, str) and gen_id: + seen_ids.add(gen_id) + # NULL rows predate the column and ran the CUDA default, DiffVAE. + factor = implied_envelope_factor( + identity.system, + bucket, + pt.point, + pt.wall_s, + conv_vae=bool(_optional_int(row["conv_vae"])), + reject_clamped=True, + ) + if factor is not None: + factors.append(factor) + history_factors = [ + factor + for row in history_rows + if str(row["id"]) not in seen_ids + and (factor := _history_row_factor(identity.system, row)) is not None + ] + if len(history_factors) >= _MIN_HISTORY_SAMPLES: + factors.extend(history_factors) + return median_machine_factor(factors) diff --git a/backend/services/displaced_provider_jobs.py b/backend/services/displaced_provider_jobs.py new file mode 100644 index 000000000..ba6134872 --- /dev/null +++ b/backend/services/displaced_provider_jobs.py @@ -0,0 +1,122 @@ +"""Provider job ids that a retry replaced, kept in a JSON file until a cancel of them succeeds. + +A row of the store holds the provider job id of its newest attempt only. A retry moves the id of +the failed attempt here, so the id is not lost while the provider can still run and bill that job. +Boot recovery and the runner read the file, ask the provider to cancel each job, and then remove +the entry. The file is deleted when no entry is left. + +A file is enough for this data: it is small, short lived, and no query joins it. The store writes +an entry before it commits the retry, so a crash between the two leaves the id in both places. +That is harmless: a cancel is safe to repeat, and the readers skip a duplicate. +""" + +from __future__ import annotations + +import json +import logging +import os +import threading +from pathlib import Path + +from pydantic import BaseModel, JsonValue + +from services.records import ProviderOrphan + +logger = logging.getLogger(__name__) + +DISPLACED_PROVIDER_JOBS_FILENAME = "displaced_provider_jobs.json" +_FORMAT_VERSION = 1 + +# One lock for every instance: the readers and the writers of a file can be different objects. +_LOCK = threading.Lock() + + +class _StoredFile(BaseModel): + """The file as a whole. An entry is checked one by one, so one bad entry does not hide the rest.""" + + jobs: list[JsonValue] + + +class DisplacedProviderJobs: + def __init__(self, path: Path) -> None: + self._path = path + + def add(self, orphan: ProviderOrphan) -> None: + """Keep an id. Adding the same id twice keeps one entry.""" + with _LOCK: + jobs = self._read() + if any(_same_job(job, orphan) for job in jobs): + return + jobs.append(orphan) + self._write(jobs) + + def remove(self, generation_id: str, provider_job_id: str) -> bool: + """Forget an id once the provider dropped it. False when the file does not hold it.""" + with _LOCK: + jobs = self._read() + kept = [ + job + for job in jobs + if (job.generation_id, job.provider_job_id) != (generation_id, provider_job_id) + ] + if len(kept) == len(jobs): + return False + self._write(kept) + return True + + def list(self, generation_id: str | None = None) -> list[ProviderOrphan]: + """The kept ids in the order they were added, of one job or of all jobs.""" + with _LOCK: + jobs = self._read() + if generation_id is None: + return jobs + return [job for job in jobs if job.generation_id == generation_id] + + def _read(self) -> list[ProviderOrphan]: + try: + raw = self._path.read_text(encoding="utf-8") + except FileNotFoundError: + return [] + try: + entries = _StoredFile.model_validate_json(raw).jobs + except ValueError: + self._set_aside() + return [] + jobs: list[ProviderOrphan] = [] + for entry in entries: + try: + job = ProviderOrphan.model_validate(entry) + except ValueError: + logger.warning("Skipped an invalid entry in %s", self._path.name) + continue + if not any(_same_job(kept, job) for kept in jobs): + jobs.append(job) + return jobs + + def _write(self, jobs: list[ProviderOrphan]) -> None: + if not jobs: + self._path.unlink(missing_ok=True) + return + payload = { + "version": _FORMAT_VERSION, + "jobs": [job.model_dump(mode="json") for job in jobs], + } + temporary = self._path.with_name(f"{self._path.name}.tmp") + with temporary.open("w", encoding="utf-8") as handle: + json.dump(payload, handle) + handle.flush() + os.fsync(handle.fileno()) + os.replace(temporary, self._path) + + def _set_aside(self) -> None: + """Keep an unreadable file for a person to inspect, and start with an empty list.""" + aside = self._path.with_name(f"{self._path.name}.corrupt") + logger.warning("%s is not readable. It is moved to %s.", self._path.name, aside.name) + try: + os.replace(self._path, aside) + except OSError: + logger.warning("Could not move %s aside", self._path.name, exc_info=True) + + +def _same_job(a: ProviderOrphan, b: ProviderOrphan) -> bool: + return (a.generation_id, a.provider_job_id) == (b.generation_id, b.provider_job_id) diff --git a/backend/services/fast_video_pipeline/distilled_keyframe_guiding.py b/backend/services/fast_video_pipeline/distilled_keyframe_guiding.py deleted file mode 100644 index 917963d7d..000000000 --- a/backend/services/fast_video_pipeline/distilled_keyframe_guiding.py +++ /dev/null @@ -1,36 +0,0 @@ -"""Per-call helper swap for multi-keyframe generate. - -``combined_image_conditionings`` replaces frame 0 and treats later images as -keyframes. MKF interpolation needs ``image_conditionings_by_adding_guiding_latent``, -which keeps every image (including frame 0) as a keyframe. The swap is scoped -to one Fast generate so first/last i2v keeps replace-at-0. - -v1.4 calls the helper from ``ltx_pipelines.chunks.conditionings``, which binds -the name at import, and the stage-1-only path looks it up on ``helpers``. -""" - -from __future__ import annotations - -import threading -from collections.abc import Iterator -from contextlib import contextmanager - -_SWAP_LOCK = threading.Lock() - - -@contextmanager -def distilled_keyframe_guiding() -> Iterator[None]: - import ltx_pipelines.chunks.conditionings as chunk_conditionings - import ltx_pipelines.utils.helpers as helpers - from ltx_pipelines.utils.helpers import image_conditionings_by_adding_guiding_latent - - with _SWAP_LOCK: - original_helpers = helpers.combined_image_conditionings - original_chunks = chunk_conditionings.combined_image_conditionings - helpers.combined_image_conditionings = image_conditionings_by_adding_guiding_latent - chunk_conditionings.combined_image_conditionings = image_conditionings_by_adding_guiding_latent - try: - yield - finally: - helpers.combined_image_conditionings = original_helpers - chunk_conditionings.combined_image_conditionings = original_chunks diff --git a/backend/services/fast_video_pipeline/distilled_skip_stage_2.py b/backend/services/fast_video_pipeline/distilled_skip_stage_2.py index 3d9b6e65a..5d76851fd 100644 --- a/backend/services/fast_video_pipeline/distilled_skip_stage_2.py +++ b/backend/services/fast_video_pipeline/distilled_skip_stage_2.py @@ -2,7 +2,7 @@ The vendor method has no ``skip_stage_2`` and always upsamples and refines. ``skip_stage_2=False`` forwards to that method. ``skip_stage_2=True`` denoises -the half-resolution canvas and decodes it, using the v1.4 latent-entry stage. +the half-resolution canvas and decodes it, using the latent-entry stage. Delete this file when a tag adds ``skip_stage_2`` to ``DistilledPipeline``. """ @@ -10,27 +10,22 @@ from __future__ import annotations import logging -from collections.abc import Sequence +from collections.abc import Iterator, Sequence from typing import Any import torch -from ltx_core.components.noisers import GaussianNoiser from ltx_core.model.video_vae import AUTO_TILING, AutoTiling, TilingConfig from ltx_core.types import VideoPixelShape import ltx_pipelines.distilled as distilled -import ltx_pipelines.utils.helpers as ltx_helpers -from ltx_pipelines.distilled import ANCESTRAL_NOISE_SEED_OFFSET -from ltx_pipelines.utils.blocks import require_num_frames_source, resolve_num_frames +from ltx_pipelines.distilled import ANCESTRAL_NOISE_SEED_OFFSET, _DistilledRunContext # pyright: ignore[reportPrivateUsage] +from ltx_pipelines.chunks.conditionings import assert_image_frames_in_clip from ltx_pipelines.utils.constants import DISTILLED_SIGMAS from ltx_pipelines.utils.denoisers import SimpleDenoiser from ltx_pipelines.utils.helpers import ( - assert_stage_supports_generated_keyframes, create_initial_av_latents, ensure_tiling_config, generated_keyframe_conditionings, - has_generated_keyframes, - snap_frames_to_grid, - tiling_scale_factors_for_vae, + image_conditionings, ) from ltx_pipelines.utils.media_io import EXRColorSpace from ltx_pipelines.utils.types import ( @@ -42,14 +37,20 @@ VideoAudio, ) +from services.fast_video_pipeline.nag_config import NagConfig +from services.fast_video_pipeline.nag_distilled import NagDistilledMixin + logger = logging.getLogger(__name__) -class DistilledPipelineWithSkipStage2(distilled.DistilledPipeline): - def __call__(self, *args: Any, skip_stage_2: bool = False, **kwargs: Any) -> PipelineOutput: - if skip_stage_2: - return self._call_stage_1_only(*args, **kwargs) - return super().__call__(*args, **kwargs) +class DistilledPipelineWithSkipStage2(NagDistilledMixin[_DistilledRunContext], distilled.DistilledPipeline): + def __call__( + self, *args: Any, skip_stage_2: bool = False, nag: NagConfig | None = None, **kwargs: Any + ) -> PipelineOutput: + with self._nag_request(nag): + if skip_stage_2: + return self._call_stage_1_only(*args, **kwargs) + return super().__call__(*args, **kwargs) def _call_stage_1_only( # noqa: PLR0913 self, @@ -73,100 +74,94 @@ def _call_stage_1_only( # noqa: PLR0913 Stage 2, keyframe decode, and chunking arguments are deliberately not accepted, so a caller that passes one fails with ``TypeError`` instead of being ignored. """ - require_num_frames_source(num_frames, self.duration_predictor) - images = self.image_conditioner.resolve_crf(images) - distilled.assert_resolution(height=height, width=width, is_two_stage=True) - if has_generated_keyframes(generated_keyframes): - assert_stage_supports_generated_keyframes(self.stage) - - generator = torch.Generator(device=self.device).manual_seed(seed) - noiser = GaussianNoiser(generator=generator) - dtype = torch.bfloat16 - if vae_dtype is None: - vae_dtype = dtype - - (ctx_p,) = self.prompt_encoder( - [prompt], - enhance_first_prompt=enhance_prompt, + # tiling_config=None leaves the shared prologue untiled: it sizes decode tiles for the + # post-upsample canvas, and this path decodes the half-resolution canvas instead. + ctx = self._prepare_run( + prompt=prompt, + seed=seed, + height=height, + width=width, + frame_rate=frame_rate, + images=images, + color_space=color_space, + num_frames=num_frames, + vae_dtype=vae_dtype, + tiling_config=None, + enhance_prompt=enhance_prompt, enhance_static_cache=enhance_static_cache, - enhance_prompt_image=images[0][0] if len(images) > 0 else None, - ) - video_context, audio_context = ctx_p.video_encoding, ctx_p.audio_encoding - - num_frames = snap_frames_to_grid( - resolve_num_frames( - num_frames, - self.duration_predictor, - video_encoding=video_context, - audio_encoding=audio_context, - frame_rate=frame_rate, - ) + generated_keyframes=generated_keyframes, + decode_with_keyframes=False, ) + assert_image_frames_in_clip(ctx.images, ctx.num_frames) - # Decode shape is stage-1 pixels (canvas/2). Distilled sizes tiling for the - # post-upsample canvas because it always runs stage 2. - stage_1_w, stage_1_h = width // 2, height // 2 - scale_factors = tiling_scale_factors_for_vae(self.video_decoder.checkpoint_path) + num_frames = ctx.num_frames + stage_1_w, stage_1_h = ctx.stage_1_width, ctx.stage_1_height tiling_config = ensure_tiling_config( tiling_config, - scale_factors=scale_factors, vae_checkpoint_path=self.video_decoder.checkpoint_path, video_shape=VideoPixelShape( batch=1, frames=num_frames, height=stage_1_h, width=stage_1_w, fps=frame_rate ), diffvae_optimization=self.video_decoder.diffvae_optimization, device=self.device, + vae_dtype=ctx.vae_dtype, ) stage_1_sigmas = stage_1_sigmas.to(dtype=torch.float32, device=self.device) - # Look up on helpers so a keyframe patch can swap the helper. stage_1_conditionings = self.image_conditioner( - lambda enc: ltx_helpers.combined_image_conditionings( - images=images, + lambda enc: image_conditionings( + images=ctx.images, height=stage_1_h, width=stage_1_w, video_encoder=enc, - dtype=dtype, + dtype=ctx.dtype, device=self.device, - color_space=color_space, ) ) stage_1_conditionings.extend(generated_keyframe_conditionings(generated_keyframes, num_frames)) video_latent, audio_latent = create_initial_av_latents( - width=stage_1_w, - height=stage_1_h, - frames=num_frames, - fps=frame_rate, + pixel_shape=VideoPixelShape( + batch=1, frames=num_frames, height=stage_1_h, width=stage_1_w, fps=frame_rate + ), device=self.device, - dtype=dtype, - # Transformer latent geometry. `scale_factors` above is the decoder's tiling scale - # (2x8x8 on the 2.5 DiffVAE) and is only right for sizing decode tiles. + dtype=ctx.dtype, + # Transformer latent geometry, not the decoder's tiling scale (2x8x8 on the 2.5 + # DiffVAE), which only sizes decode tiles. video_scale_factors=self.stage.video_scale_factors, ) - video_state, audio_state = self.stage( - denoiser=SimpleDenoiser(video_context, audio_context), - sigmas=stage_1_sigmas, - noiser=noiser, - modalities=VideoAudio( - video=ModalitySpec( - latent=video_latent, - conditioning_fps=frame_rate, - context=video_context, - conditionings=stage_1_conditionings, - ), - audio=ModalitySpec( - latent=audio_latent, - conditioning_fps=frame_rate, - context=audio_context, + with self._nag_denoise_scope(): + video_state, audio_state = self.stage( + denoiser=SimpleDenoiser(), + sigmas=stage_1_sigmas, + noiser=ctx.noiser, + modalities=VideoAudio( + video=ModalitySpec( + latent=video_latent, + conditioning_fps=frame_rate, + context=ctx.video_context, + conditionings=stage_1_conditionings, + ), + audio=ModalitySpec( + latent=audio_latent, + conditioning_fps=frame_rate, + context=ctx.audio_context, + ), ), - ), - **self._sampler_kwargs(seed, ANCESTRAL_NOISE_SEED_OFFSET), - ) + **self._sampler_kwargs(seed, ANCESTRAL_NOISE_SEED_OFFSET), + ) logger.info("[fast] Skipping Stage 2 (skip_stage_2=True); decode %dx%d", stage_1_w, stage_1_h) assert video_state is not None assert audio_state is not None - decoded_video = self.video_decoder(video_state.latent, tiling_config, generator, dtype=vae_dtype) + latent = video_state.latent decoded_audio = self.audio_decoder(audio_state.latent) - return PipelineOutput(decoded_video, decoded_audio, num_frames, tiling_config) + return PipelineOutput(self._decode_lazily(latent, tiling_config, ctx), decoded_audio, num_frames, tiling_config) + + def _decode_lazily(self, latent: torch.Tensor, tiling_config: TilingConfig | None, ctx: _DistilledRunContext) -> Iterator[torch.Tensor]: + """Build the decoder when the first chunk is requested. + + ``VideoDecoder.__call__`` builds eagerly but frees the model only once its iterator has + started, so a stream closed before it is read would leave the decoder resident. + """ + yield from self.video_decoder(latent, tiling_config, ctx.generator, dtype=ctx.vae_dtype) diff --git a/backend/services/fast_video_pipeline/fast_video_pipeline.py b/backend/services/fast_video_pipeline/fast_video_pipeline.py index 8fad9a5cf..47e992c86 100644 --- a/backend/services/fast_video_pipeline/fast_video_pipeline.py +++ b/backend/services/fast_video_pipeline/fast_video_pipeline.py @@ -6,6 +6,7 @@ from api_types import ImageConditioningInput from frame_math import AutoDurationSpec +from services.fast_video_pipeline.nag_config import NagConfig if TYPE_CHECKING: import torch @@ -45,6 +46,7 @@ def generate( guide_all_images: bool = False, skip_stage_2: bool = False, chunk_pixel_frames: int | None = None, + nag: NagConfig | None = None, ) -> None: ... diff --git a/backend/services/fast_video_pipeline/ltx_fast_video_pipeline.py b/backend/services/fast_video_pipeline/ltx_fast_video_pipeline.py index 7466bd292..40a4cc7e6 100644 --- a/backend/services/fast_video_pipeline/ltx_fast_video_pipeline.py +++ b/backend/services/fast_video_pipeline/ltx_fast_video_pipeline.py @@ -2,7 +2,6 @@ from __future__ import annotations -from contextlib import nullcontext import os from typing import TYPE_CHECKING, Final @@ -10,11 +9,13 @@ from api_types import ImageConditioningInput from frame_math import AutoDurationSpec +from services.fast_video_pipeline.nag_config import NagConfig from services.fast_video_pipeline.windowed_run import encode_result, measured_windows, plan_windows -from services.ic_lora_pipeline.ic_lora_inference import InferenceResult +from services.ic_lora_pipeline.ic_lora_inference import InferenceResult, inference_result_from_output from services.ltx_pipeline_common import ( auto_tiling_config, build_model_paths, + to_ltx_images, ) from services.services_utils import PipelineTilingType, device_supports_fp8 @@ -69,7 +70,7 @@ def __init__( audio_vae_path: str | None = None, duration_head_path: str | None = None, ) -> None: - from ltx_core.loader.primitives import LoraPathStrengthAndSDOps + from ltx_core.loader import LoraPathStrengthAndSDOps from ltx_core.loader.sd_ops import LTXV_LORA_COMFY_RENAMING_MAP from ltx_core.quantization.fp8_cast import build_policy as build_fp8_cast_policy from services.fast_video_pipeline.distilled_skip_stage_2 import DistilledPipelineWithSkipStage2 @@ -116,12 +117,13 @@ def _run_inference( images: list[ImageConditioningInput], tiling_config: PipelineTilingType, *, + guide_all_images: bool = False, skip_stage_2: bool = False, chunk_config: ChunkConfig | None = None, + nag: NagConfig | None = None, ) -> InferenceResult: """Run the pipeline. A windowed job streams, so the caller must encode inside the - keyframe-guiding scope and the progress scope, and close the streams after.""" - from ltx_pipelines.utils.types import ImageConditioningInput as _LtxImageInput + progress scope and close the streams after.""" from ltx_pipelines.utils.types import AutoDuration pipeline_num_frames: int | AutoDuration = ( @@ -129,7 +131,7 @@ def _run_inference( if isinstance(num_frames, AutoDurationSpec) else num_frames ) - ltx_images = [_LtxImageInput(img.path, img.frame_idx, img.strength) for img in images] + ltx_images = to_ltx_images(images, guide_all=guide_all_images) if chunk_config is None: result = self.pipeline( prompt=prompt, @@ -141,12 +143,11 @@ def _run_inference( images=ltx_images, tiling_config=tiling_config, skip_stage_2=skip_stage_2, + nag=nag, ) - return InferenceResult(result.video, result.audio, result.num_frames, result.tiling_config) + return inference_result_from_output(result) if skip_stage_2: raise ValueError("A windowed job runs both stages") - from ltx_pipelines.chunks import split_decoded_chunks - chunks, resolved_frames, resolved_tiling = self.pipeline.stream_chunks( prompt=prompt, seed=seed, @@ -157,10 +158,9 @@ def _run_inference( images=ltx_images, tiling_config=tiling_config, chunk_config=chunk_config, + nag=nag, ) - video, audio, audio_sampling_rate = split_decoded_chunks(chunks) - streams = (video, chunks) if audio is None else (video, audio, chunks) - return InferenceResult(video, audio, resolved_frames, resolved_tiling, audio_sampling_rate, streams) + return InferenceResult(chunks, resolved_frames, resolved_tiling, (chunks,)) @torch.inference_mode() def generate( @@ -177,20 +177,19 @@ def generate( guide_all_images: bool = False, skip_stage_2: bool = False, chunk_pixel_frames: int | None = None, + nag: NagConfig | None = None, ) -> None: from services.denoising_progress import distilled_total_steps, track_denoising - from services.fast_video_pipeline.distilled_keyframe_guiding import distilled_keyframe_guiding chunk_config, chunk_count = plan_windows( chunk_pixel_frames, width=width, height=height, num_frames=num_frames, frame_rate=frame_rate ) steps = distilled_total_steps(stage_2=not skip_stage_2) * chunk_count - guiding = distilled_keyframe_guiding() if guide_all_images else nullcontext() measured = measured_windows( chunk_config, width=width, height=height, window_count=chunk_count, num_frames=num_frames, frame_rate=frame_rate, device=self._device, ) - with track_denoising(steps), guiding, measured: + with track_denoising(steps), measured: result = self._run_inference( prompt=prompt, seed=seed, @@ -200,8 +199,10 @@ def generate( frame_rate=frame_rate, images=images, tiling_config=auto_tiling_config(), + guide_all_images=guide_all_images, skip_stage_2=skip_stage_2, chunk_config=chunk_config, + nag=nag, ) encode_result(result, fps=int(frame_rate), output_path=output_path, streamed=chunk_config is not None) @@ -226,7 +227,7 @@ def warmup(self, output_path: str) -> None: os.unlink(output_path) def compile_transformer(self) -> None: - from ltx_core.loader.primitives import LoraPathStrengthAndSDOps + from ltx_core.loader import LoraPathStrengthAndSDOps from ltx_core.loader.sd_ops import LTXV_LORA_COMFY_RENAMING_MAP from ltx_core.model.transformer.compiling import CompilationConfig from services.fast_video_pipeline.distilled_skip_stage_2 import DistilledPipelineWithSkipStage2 diff --git a/backend/services/fast_video_pipeline/nag_config.py b/backend/services/fast_video_pipeline/nag_config.py new file mode 100644 index 000000000..8930a216a --- /dev/null +++ b/backend/services/fast_video_pipeline/nag_config.py @@ -0,0 +1,209 @@ +"""Request-side settings for Normalized Attention Guidance (NAG). + +No torch or ltx imports: handlers and the pipeline protocol import this module. +The attention patch lives in ``services/patches/nag_cross_attention.py``. + +NAG runs whenever ``negative_prompt`` is non-empty and ``scale > 0`` (unless +``LTX_NAG_ENABLED=0``). The scale follows the KJNodes ``LTX2_NAG`` convention: +``guidance = scale * Z_pos - (scale - 1) * Z_neg``. +""" + +from __future__ import annotations + +import logging +from collections.abc import Mapping +from dataclasses import dataclass +from enum import StrEnum + +from runtime_config.nag_limits import ( + DEFAULT_ALPHA, + DEFAULT_SCALE, + DEFAULT_TAU, + ENV_ALPHA, + ENV_ENABLED, + ENV_SCALE, + ENV_TAU, + MAX_ALPHA, + MAX_SCALE, + MAX_TAU, +) + + +class NagOffReason(StrEnum): + DISABLED_BY_ENV = "disabled_by_env" + NO_NEGATIVE = "no_negative" + STRENGTH_ZERO = "strength_zero" + API_ENCODING = "api_encoding" + TORCH_COMPILE = "torch_compile" + + +NAG_OFF_MESSAGE: Mapping[NagOffReason, str | None] = { + NagOffReason.DISABLED_BY_ENV: None, + NagOffReason.NO_NEGATIVE: None, + NagOffReason.STRENGTH_ZERO: ( + "Negative prompt guidance (NAG) is turned off in Settings (strength is 0)." + ), + NagOffReason.API_ENCODING: ( + "Negative prompt guidance (NAG) requires the local text encoder and is " + "skipped while LTX API text encoding is active." + ), + NagOffReason.TORCH_COMPILE: ( + "Negative prompt guidance (NAG) is skipped while Torch Compile is " + "enabled in Settings." + ), +} + +_NAG_SKIP_LOG_REASON: Mapping[NagOffReason, str | None] = { + NagOffReason.DISABLED_BY_ENV: None, + NagOffReason.NO_NEGATIVE: None, + NagOffReason.STRENGTH_ZERO: None, + NagOffReason.API_ENCODING: "the negative prompt needs local text encoding", + NagOffReason.TORCH_COMPILE: "torch.compile is enabled", +} + + +@dataclass(frozen=True) +class NagConfig: + negative_prompt: str + scale: float = DEFAULT_SCALE + alpha: float = DEFAULT_ALPHA + tau: float = DEFAULT_TAU + + +@dataclass(frozen=True) +class NagDecision: + config: NagConfig | None + reason: NagOffReason | None = None + + @property + def active(self) -> bool: + return self.config is not None + + @property + def enhancer_negative(self) -> str: + return self.config.negative_prompt if self.config is not None else "" + + @property + def user_message(self) -> str | None: + return NAG_OFF_MESSAGE.get(self.reason) if self.reason is not None else None + + +def _read_float( + environ: Mapping[str, str], + name: str, + default: float, + *, + low: float, + high: float, +) -> float: + raw = environ.get(name, "").strip() + if not raw: + return default + try: + value = float(raw) + except ValueError as exc: + raise ValueError(f"{name} must be a number, got {raw!r}") from exc + if not low <= value <= high: + raise ValueError(f"{name} must be between {low:g} and {high:g}, got {value:g}") + return value + + +def decide_nag( + negative_prompt: str, + environ: Mapping[str, str], + *, + scale: float | None = None, + alpha: float | None = None, + tau: float | None = None, + default_scale: float = DEFAULT_SCALE, + local_encoding: bool = True, + compiled: bool = False, +) -> NagDecision: + """Decide whether NAG runs for one job, and why when it stays off.""" + if environ.get(ENV_ENABLED, "").strip() == "0": + return NagDecision(config=None, reason=NagOffReason.DISABLED_BY_ENV) + negative = negative_prompt.strip() + if not negative: + return NagDecision(config=None, reason=NagOffReason.NO_NEGATIVE) + resolved_scale = ( + scale + if scale is not None + else _read_float(environ, ENV_SCALE, default_scale, low=0.0, high=MAX_SCALE) + ) + if resolved_scale <= 0.0: + return NagDecision(config=None, reason=NagOffReason.STRENGTH_ZERO) + if not local_encoding: + return NagDecision(config=None, reason=NagOffReason.API_ENCODING) + if compiled: + return NagDecision(config=None, reason=NagOffReason.TORCH_COMPILE) + resolved_alpha = ( + alpha + if alpha is not None + else _read_float(environ, ENV_ALPHA, DEFAULT_ALPHA, low=0.0, high=MAX_ALPHA) + ) + resolved_tau = ( + tau + if tau is not None + else _read_float(environ, ENV_TAU, DEFAULT_TAU, low=0.0, high=MAX_TAU) + ) + return NagDecision( + config=NagConfig( + negative_prompt=negative, + scale=resolved_scale, + alpha=resolved_alpha, + tau=resolved_tau, + ), + reason=None, + ) + + +def nag_config_for_request( + negative_prompt: str, + environ: Mapping[str, str], + *, + scale: float | None = None, + alpha: float | None = None, + tau: float | None = None, + default_scale: float = DEFAULT_SCALE, + local_encoding: bool = True, + compiled: bool = False, +) -> NagConfig | None: + """Return the NAG settings for one job, or ``None`` when NAG must stay off. + + ``None`` keeps the unguided path, so output stays bit-identical to a job + without NAG. + """ + return decide_nag( + negative_prompt, + environ, + scale=scale, + alpha=alpha, + tau=tau, + default_scale=default_scale, + local_encoding=local_encoding, + compiled=compiled, + ).config + + +def log_nag_decision( + log: logging.Logger, capability: str, decision: NagDecision +) -> NagConfig | None: + """Log ``NAG on`` or ``NAG skipped`` for a run and return ``decision.config``.""" + if decision.config is not None: + cfg = decision.config + log.info( + "[%s] NAG on (scale=%g, alpha=%g, tau=%g)", + capability, + cfg.scale, + cfg.alpha, + cfg.tau, + ) + return cfg + skip_reason = ( + _NAG_SKIP_LOG_REASON.get(decision.reason) + if decision.reason is not None + else None + ) + if skip_reason is not None: + log.warning("[%s] NAG skipped: %s", capability, skip_reason) + return None diff --git a/backend/services/fast_video_pipeline/nag_distilled.py b/backend/services/fast_video_pipeline/nag_distilled.py new file mode 100644 index 000000000..bdc000ab5 --- /dev/null +++ b/backend/services/fast_video_pipeline/nag_distilled.py @@ -0,0 +1,131 @@ +"""NAG negative prompt support for ``DistilledPipeline``. + +``NagDistilledMixin`` goes before ``DistilledPipeline`` in the base list. It: + +1. encodes the negative prompt in the same Gemma pass as the prompt (one load), +2. appends the negative embedding to the video text context along the sequence axis, +3. turns NAG on only while the denoise calls run (``nag_scope``). + +The attention change is in ``services/patches/nag_cross_attention.py``. A job +with no ``NagConfig`` takes none of these steps. +""" + +from __future__ import annotations + +import dataclasses +from collections.abc import Iterator +from contextlib import AbstractContextManager, contextmanager, nullcontext +from typing import Any, Generic, Protocol, TypeVar, cast + +import torch +from ltx_core.text_encoders.gemma.embeddings_processor import EmbeddingsProcessorOutput + +from services.fast_video_pipeline.nag_config import NagConfig +from services.patches.nag_cross_attention import NagState, nag_scope + +_T = TypeVar("_T") +_RunCtx = TypeVar("_RunCtx") + + +class _PromptEncoderLike(Protocol): + def __call__(self, prompts: list[str], **kwargs: Any) -> list[EmbeddingsProcessorOutput]: ... + + +def prompts_with_negative(prompt: str, nag: NagConfig | None) -> list[str]: + """Prompts to pass to ``prompt_encoder`` when NAG is active vs. off.""" + return [prompt, nag.negative_prompt] if nag is not None else [prompt] + + +def with_negative_context( + positive: torch.Tensor, negative: torch.Tensor, nag: NagConfig +) -> tuple[torch.Tensor, NagState]: + """Concatenate positive and negative video text contexts and build ``NagState``.""" + return ( + torch.cat([positive, negative], dim=1), + NagState(config=nag, positive_length=positive.shape[1]), + ) + + +class _NegativeCapture: + """Adds the negative prompt to the encode call and keeps its embedding. + + The caller sees one output per prompt it asked for. The enhancer only touches + the first prompt, so the negative prompt is never rewritten. + """ + + def __init__(self, inner: _PromptEncoderLike, negative_prompt: str) -> None: + self._inner = inner + self._negative_prompt = negative_prompt + self.negative: EmbeddingsProcessorOutput | None = None + + def __call__(self, prompts: list[str], **kwargs: Any) -> list[EmbeddingsProcessorOutput]: + outputs = self._inner([*prompts, self._negative_prompt], **kwargs) + self.negative = outputs[-1] + return outputs[:-1] + + +def scoped_chunks(chunks: Iterator[_T], state: NagState) -> Iterator[_T]: + """Yield from a lazy chunk stream with NAG on only while a chunk is being computed. + + Denoising runs inside ``next()``. The scope must not stay open while the caller + holds a chunk, because the caller can start another job in between. + """ + iterator = iter(chunks) + while True: + with nag_scope(state): + try: + chunk = next(iterator) + except StopIteration: + return + yield chunk + + +class NagDistilledMixin(Generic[_RunCtx]): + prompt_encoder: Any # set by DistilledPipeline.__init__ + _nag_pending: NagConfig | None = None + _nag_state: NagState | None = None + + @contextmanager + def _nag_request(self, config: NagConfig | None) -> Iterator[None]: + previous = self._nag_pending + self._nag_pending = config + try: + yield + finally: + self._nag_pending = previous + + def _nag_denoise_scope(self) -> AbstractContextManager[None]: + """Scope for a denoise call made directly (not through ``stream_chunks``).""" + state, self._nag_state = self._nag_state, None + return nag_scope(state) if state is not None else nullcontext() + + def _prepare_run(self, **kwargs: Any) -> _RunCtx: + config = self._nag_pending + parent = cast(Any, super()) + self._nag_state = None + if config is None: + return cast("_RunCtx", parent._prepare_run(**kwargs)) + encoder = self.prompt_encoder + capture = _NegativeCapture(encoder, config.negative_prompt) + self.prompt_encoder = capture + try: + ctx = parent._prepare_run(**kwargs) + finally: + self.prompt_encoder = encoder + negative = capture.negative + if negative is None: + raise RuntimeError("The negative prompt was not encoded") + video_context, self._nag_state = with_negative_context( + ctx.video_context, negative.video_encoding, config + ) + return cast("_RunCtx", dataclasses.replace(ctx, video_context=video_context)) + + def stream_chunks(self, *args: Any, nag: NagConfig | None = None, **kwargs: Any) -> Any: + parent = cast(Any, super()) + config = nag if nag is not None else self._nag_pending + with self._nag_request(config): + chunks, num_frames, tiling_config = parent.stream_chunks(*args, **kwargs) + state, self._nag_state = self._nag_state, None + if state is not None: + chunks = scoped_chunks(chunks, state) + return chunks, num_frames, tiling_config diff --git a/backend/services/fast_video_pipeline/windowed_run.py b/backend/services/fast_video_pipeline/windowed_run.py index 4d77f6616..41bf0dfab 100644 --- a/backend/services/fast_video_pipeline/windowed_run.py +++ b/backend/services/fast_video_pipeline/windowed_run.py @@ -4,22 +4,25 @@ import logging import sys -from collections.abc import Iterator from contextlib import AbstractContextManager, nullcontext from typing import TYPE_CHECKING import torch from frame_math import AutoDurationSpec, compute_num_frames -from runtime_config.fast_chunking import CARRY_FRAMES, is_chunked_canvas -from runtime_config.video_job_budget import edit_job_stream_gib, fast_job_stream_gib, video_tokens +from runtime_config.fast_chunking import CARRY_FRAMES, is_chunked_canvas, last_window_frames +from runtime_config.video_job_budget import ( + decode_tile_tokens, + edit_job_stream_gib, + fast_job_stream_gib, + video_tokens, +) from services.ic_lora_pipeline.ic_lora_inference import ( InferenceResult, close_streams, - encode_streamed_output, plan_chunks, ) -from services.ltx_pipeline_common import encode_video_output, video_chunks_number +from services.ltx_pipeline_common import encode_segments_output, video_chunks_number from services.phase_log import measured_gpu_phase if TYPE_CHECKING: @@ -71,9 +74,15 @@ def measured_windows( if not is_chunked_canvas(width, height): return nullcontext() frames = _longest_frames(num_frames, frame_rate) + last_frames = frames label = f"{width}x{height}, {frames} frames in one pass" else: frames = chunk_config.chunk_pixel_frames + last_frames = last_window_frames( + _longest_frames(num_frames, frame_rate), + frames, + chunk_config.next_video_carry_frames, + ) label = ( f"{width}x{height} in {window_count} window(s) of {frames} frames " f"(carry {chunk_config.next_video_carry_frames})" @@ -87,6 +96,7 @@ def measured_windows( video_tokens(height, width, frames), windows=window_count, darwin=sys.platform == "darwin", + last_tokens=video_tokens(height, width, last_frames), ), ) @@ -101,7 +111,9 @@ def measured_edit(width: int, height: int, frames: int) -> AbstractContextManage device=torch.device("cuda"), prefix=LOG_PREFIX, estimate_gib=edit_job_stream_gib( - video_tokens(height, width, frames), darwin=sys.platform == "darwin" + video_tokens(height, width, frames), + darwin=sys.platform == "darwin", + decode_tokens=decode_tile_tokens(height, width, frames), ), ) @@ -109,18 +121,11 @@ def measured_edit(width: int, height: int, frames: int) -> AbstractContextManage def encode_result(result: InferenceResult, *, fps: int, output_path: str, streamed: bool) -> None: """Encode the video. A windowed job runs its windows while the encoder reads them.""" try: - if streamed: - encode_streamed_output( - result.video, result.audio, result.audio_sampling_rate, fps=fps, output_path=output_path - ) - else: - assert not isinstance(result.audio, Iterator) # a one-pass job never streams audio - encode_video_output( - video=result.video, - audio=result.audio, - fps=fps, - output_path=output_path, - video_chunks_number_value=video_chunks_number(result.num_frames, result.tiling_config), - ) + encode_segments_output( + result.segments, + fps=fps, + output_path=output_path, + video_chunks_number_value=None if streamed else video_chunks_number(result.num_frames, result.tiling_config), + ) finally: close_streams(result) diff --git a/backend/services/features/custom_loras.py b/backend/services/features/custom_loras.py new file mode 100644 index 000000000..9b8971b05 --- /dev/null +++ b/backend/services/features/custom_loras.py @@ -0,0 +1,156 @@ +"""Create-time and execution-time rules for a custom LoRA run. + +The client names a saved custom LoRA by id and sends a strength. Create stores an empty ``ref`` +and ``customLoraId``, and ``make_custom_lora_resolver`` resolves the weights path at execution +time, so a client never sends a path and SQLite never persists one. A Start Frame is optional: +with one the run is image to video, without one it is text to video. +""" + +from __future__ import annotations + +from collections.abc import Callable, Mapping +from pathlib import Path + +from _routes._errors import HTTPError +from api_types import ( + CreateCustomLoraRequest, + ImageToVideoInputs, + ImageToVideoRecipeParams, + LoraEntry, + TextToVideoParams, +) +from runtime_config.custom_loras import read_custom_lora +from runtime_config.models_scanner import resolve_lora_ref +from services.features.video.custom_lora import ( + CUSTOM_LORA_FEATURE, + CUSTOM_LORA_NOT_DOWNLOADED, + stored_lora, +) +from services.records import UnavailableError +from services.store import Store + +CUSTOM_LORA_NOT_FOUND = "CUSTOM_LORA_NOT_FOUND" +INVALID_GENERATION_SPEC = "INVALID_GENERATION_SPEC" + +# Params of the create body that the stored row does not keep: the row keeps ``loras`` instead. +_CLIENT_ONLY_PARAMS = {"customLoraId", "scale"} + + +class CustomLoraCreateError(Exception): + """A create-time miss for a custom LoRA run. ``status`` is the HTTP status the route answers.""" + + def __init__(self, message: str, *, code: str, status: int = 422) -> None: + super().__init__(message) + self.code = code + self.status = status + + +def custom_lora_id_of_spec(spec: Mapping[str, object]) -> str | None: + """The saved LoRA a stored run uses, or ``None`` when the run names none or the row is junk.""" + lora = stored_lora(spec) + return lora.customLoraId if lora is not None else None + + +def custom_lora_in_use(store: Store, custom_lora_id: str) -> bool: + """Whether a queued, running or cancelling run holds this saved LoRA. + + Deleting the weights while a run is queued or running would fail the run, or fail the delete + on Windows where the open file cannot be removed. + """ + try: + queue = store.list_queue_generations() + except UnavailableError as exc: + raise HTTPError(503, "STORE_UNAVAILABLE") from exc + return any( + entry.generation.feature == CUSTOM_LORA_FEATURE + and custom_lora_id_of_spec(entry.generation.spec) == custom_lora_id + for entry in queue + ) + + +def resolve_custom_lora_create( + req: CreateCustomLoraRequest, *, models_dir: Path +) -> tuple[str, TextToVideoParams | ImageToVideoRecipeParams, ImageToVideoInputs | None]: + """Validate a custom LoRA create and build its queued params. + + Returns ``(feature, params, inputs)``. Every miss raises :class:`CustomLoraCreateError` before + the caller enqueues anything. + """ + params = req.params + record = read_custom_lora(models_dir, params.customLoraId) + if record is None: + raise CustomLoraCreateError( + f"Custom LoRA '{params.customLoraId}' was not found", + code=CUSTOM_LORA_NOT_FOUND, + status=404, + ) + if not record.downloaded: + raise CustomLoraCreateError( + f"The weights of '{record.name}' are not on this computer. Add them first.", + code=CUSTOM_LORA_NOT_DOWNLOADED, + ) + stored = { + **params.model_dump(exclude=_CLIENT_ONLY_PARAMS), + "loras": [ + LoraEntry( + ref="", + scale=params.scale, + displayName=record.name, + customLoraId=record.id, + ) + ], + } + if req.inputs is not None: + if req.inputs.endFrame is not None: + raise CustomLoraCreateError( + "A custom LoRA does not take an end frame", code=INVALID_GENERATION_SPEC + ) + return ( + CUSTOM_LORA_FEATURE, + ImageToVideoRecipeParams.model_validate(stored), + ImageToVideoInputs(startFrame=req.inputs.startFrame), + ) + + if params.aspectRatio == "auto": + raise CustomLoraCreateError( + "aspectRatio 'auto' needs a Start Frame to size from", code=INVALID_GENERATION_SPEC + ) + return CUSTOM_LORA_FEATURE, TextToVideoParams.model_validate(stored), None + + +def make_custom_lora_resolver( + models_dir: Callable[[], Path], +) -> Callable[[list[LoraEntry]], list[LoraEntry]]: + """Hydrate a custom LoRA's ``ref`` from ``customLoraId`` at execution time. + + The stored spec carries ``customLoraId`` + ``scale`` (empty ``ref``); this resolver checks + that the weights file is still on disk and fills ``ref`` just before the job runs. + """ + + def resolve(loras: list[LoraEntry]) -> list[LoraEntry]: + resolved: list[LoraEntry] = [] + base = models_dir() + for entry in loras: + if entry.customLoraId is None: + resolved.append(entry) + continue + record = read_custom_lora(base, entry.customLoraId) + name = (record.name if record is not None else entry.displayName) or "This LoRA" + if record is None or not record.downloaded: + raise HTTPError( + 409, + f"The weights of '{name}' are not on this computer. Add them again, then retry.", + code=CUSTOM_LORA_NOT_DOWNLOADED, + ) + try: + resolve_lora_ref(base, record.ref) + except ValueError as exc: + raise HTTPError( + 409, + f"The weights of '{name}' are not on this computer. Add them again, then retry.", + code=CUSTOM_LORA_NOT_DOWNLOADED, + ) from exc + resolved.append(entry.model_copy(update={"ref": record.ref})) + return resolved + + return resolve diff --git a/backend/services/features/ic_lora_recipes.py b/backend/services/features/ic_lora_recipes.py index a50a73c26..60ee00a70 100644 --- a/backend/services/features/ic_lora_recipes.py +++ b/backend/services/features/ic_lora_recipes.py @@ -239,9 +239,14 @@ def _resolve_checkpoint( *, models_dir: Path, hf_authenticated: bool, + require_prompt: bool = True, ) -> tuple[IcLoraAudioMode, list[LoraEntry]]: - """The checks both bodies share. Returns the audio mode and the one LoRA this run uses.""" - if params.prompt.strip() == "" and not item.allows_empty_prompt: + """The checks both bodies share. Returns the audio mode and the one LoRA this run uses. + + ``require_prompt`` is false only for the tile preflight. That route judges the budget, + and the budget does not read the prompt. Create keeps the check. + """ + if require_prompt and params.prompt.strip() == "" and not item.allows_empty_prompt: raise RecipeCreateError("Prompt is required.", code="INVALID_GENERATION_SPEC") require_catalog_runnable( item, @@ -319,6 +324,7 @@ def resolve_ic_lora_recipe_create( models_dir: Path, hf_authenticated: bool, source_fps: float, + require_prompt: bool = True, ) -> tuple[IcLoraRecipe, IcLoraCatalogItem, IcLoraVideoRecipeStoredParams]: """Validate a recipe create and return the stored params, including ``loras``.""" recipe, item = _recipe_item(recipe_id, catalog, kind="video") @@ -332,7 +338,11 @@ def resolve_ic_lora_recipe_create( ) control_type = _resolve_control_type(item, req) audio_mode, loras = _resolve_checkpoint( - item, req.params, models_dir=models_dir, hf_authenticated=hf_authenticated + item, + req.params, + models_dir=models_dir, + hf_authenticated=hf_authenticated, + require_prompt=require_prompt, ) stored = IcLoraVideoRecipeStoredParams.model_validate( { diff --git a/backend/services/features/image/__init__.py b/backend/services/features/image/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/backend/services/features/image/feature_id.py b/backend/services/features/image/feature_id.py new file mode 100644 index 000000000..7a22e327e --- /dev/null +++ b/backend/services/features/image/feature_id.py @@ -0,0 +1 @@ +FEATURE = "text-to-image" diff --git a/backend/services/features/image/grid.py b/backend/services/features/image/grid.py new file mode 100644 index 000000000..47f45c593 --- /dev/null +++ b/backend/services/features/image/grid.py @@ -0,0 +1,10 @@ +"""Snap an image side down to the model grid. + +The side limits stay on the request DTO. This is the rounding the create path applies. +""" + +from api_types import IMAGE_SIDE_GRID + + +def floor_to_image_grid(side: int) -> int: + return (side // IMAGE_SIDE_GRID) * IMAGE_SIDE_GRID diff --git a/backend/services/features/image/prompt_rewrite.py b/backend/services/features/image/prompt_rewrite.py new file mode 100644 index 000000000..4ec27ffea --- /dev/null +++ b/backend/services/features/image/prompt_rewrite.py @@ -0,0 +1,16 @@ +"""What the automatic rewrite did to an image prompt.""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Literal + + +@dataclass(frozen=True) +class ImagePromptRewrite: + """``source`` is None when nothing rewrote the prompt. ``wanted`` is False when no rewrite + was asked for: auto-enhance is off, or the prompt is already enhanced.""" + + prompt: str + source: Literal["local", "gemini"] | None + wanted: bool diff --git a/backend/services/features/image/text_to_image.py b/backend/services/features/image/text_to_image.py new file mode 100644 index 000000000..925f71729 --- /dev/null +++ b/backend/services/features/image/text_to_image.py @@ -0,0 +1,174 @@ +from __future__ import annotations + +from collections.abc import Callable, Mapping +from dataclasses import dataclass +from pathlib import Path +from typing import Final, Protocol, assert_never + +from _routes._errors import HTTPError +from api_types import ( + ImageGenerationStatusResponse, + ImageProviderBlocker, + TextToImageParams, + PromptRewriteSource, + TextToImageStoredParams, +) +from runtime_config.video_job_budget import ( + LOCAL_GENERATION_UNSUPPORTED, + LOCAL_GENERATION_UNSUPPORTED_MESSAGE, +) +from services.features.image.grid import floor_to_image_grid +from services.features.video.job_common import capability_failed_from_http, model_from_spec +from services.generation_interrupt import GenerationCancelledError, is_cancel_exception +from services.generation_queue.lanes import FAL_LANE +from services.generation_queue.sessions import JobSession +from services.generation_queue.types import ( + ExecutionOutcome, + OutputAllocation, + OutputPlan, +) +from services.records import LOCAL_LANE, GenerationRecord + +IMAGE_OUTPUT_PLAN = OutputPlan( + slot="output", + media_kind="image", + mime_type="image/png", + name="output.png", +) +_SUPPORTED_CONTRACT_VERSION = 1 + +FAL_API_KEY_NOT_CONFIGURED: Final = "FAL_API_KEY_NOT_CONFIGURED" +IMAGE_MODEL_NOT_DOWNLOADED: Final = "IMAGE_MODEL_NOT_DOWNLOADED" + + +@dataclass(frozen=True) +class QueuedImageResult: + # The prompt the provider expanded, to replace the typed one on the finished row. + written_prompt: str | None = None + prompt_rewrite: PromptRewriteSource | None = None + + +class QueuedImageRenderer(Protocol): + def generate_queued( + self, + params: TextToImageStoredParams, + *, + generation_id: str, + output_path: Path, + session: JobSession, + ) -> QueuedImageResult: ... + + +def image_generation_status( + *, + force_api: bool, + default_to_fal: bool, + has_fal_key: bool, + local_model_downloaded: Callable[[], bool], +) -> ImageGenerationStatusResponse: + local_blocker: ImageProviderBlocker | None = None + if force_api: + local_blocker = LOCAL_GENERATION_UNSUPPORTED + elif not local_model_downloaded(): + local_blocker = IMAGE_MODEL_NOT_DOWNLOADED + return ImageGenerationStatusResponse( + defaultProvider="fal" if default_to_fal else "local", + localBlocker=local_blocker, + falBlocker=None if has_fal_key else FAL_API_KEY_NOT_CONFIGURED, + ) + + +def _refusal(blocker: ImageProviderBlocker) -> HTTPError: + """One shape for every create refusal: status, a readable message, and the blocker code. + + 409 stays for a missing model. The other two are request errors. + """ + if blocker == IMAGE_MODEL_NOT_DOWNLOADED: + return HTTPError(409, "Download the Z-Image Turbo model.", code=blocker) + if blocker == LOCAL_GENERATION_UNSUPPORTED: + return HTTPError(422, LOCAL_GENERATION_UNSUPPORTED_MESSAGE, code=blocker) + if blocker == FAL_API_KEY_NOT_CONFIGURED: + return HTTPError(422, "Add a fal API key.", code=blocker) + assert_never(blocker) + + +def resolve_text_to_image_params( + params: TextToImageParams, status: ImageGenerationStatusResponse +) -> TextToImageStoredParams: + """Pick the provider and refuse a job that can never run, before it is queued. + + An omitted provider follows the settings. The stored provider is always explicit, so a + retry after the settings change keeps the provider the user chose. + """ + provider = params.provider or status.defaultProvider + blocker = status.localBlocker if provider == "local" else status.falBlocker + if blocker is not None: + raise _refusal(blocker) + return TextToImageStoredParams( + **params.model_dump(exclude={"provider", "width", "height"}), + width=floor_to_image_grid(params.width), + height=floor_to_image_grid(params.height), + provider=provider, + ) + + +class TextToImageExecutor: + """Queued text-to-image on Z-Image Turbo, local or fal. No image input and no edit.""" + + def __init__(self, renderer: QueuedImageRenderer) -> None: + self._renderer = renderer + + def validate_params( + self, spec: Mapping[str, object], *, contract_version: int + ) -> None: + require_supported_contract_version(contract_version) + params_from_spec(spec) + + def lane_for(self, spec: Mapping[str, object]) -> str: + """A fal job waits on the provider, not on the GPU, so it has its own lane.""" + return FAL_LANE if params_from_spec(spec).provider == "fal" else LOCAL_LANE + + def plan_outputs(self, generation: GenerationRecord) -> tuple[OutputPlan, ...]: + self._params(generation) + return (IMAGE_OUTPUT_PLAN,) + + def execute( + self, + generation: GenerationRecord, + outputs: tuple[OutputAllocation, ...], + session: JobSession, + ) -> ExecutionOutcome: + params = self._params(generation) + if len(outputs) != 1 or outputs[0].plan.slot != "output": + raise ValueError("text-to-image requires a single 'output' allocation") + try: + result = self._renderer.generate_queued( + params, + generation_id=generation.id, + output_path=Path(outputs[0].dest_path), + session=session, + ) + except Exception as exc: + if is_cancel_exception(exc): + raise GenerationCancelledError() from exc + if isinstance(exc, HTTPError): + raise capability_failed_from_http(exc) from exc + raise + return ExecutionOutcome( + written_prompt=result.written_prompt, prompt_rewrite=result.prompt_rewrite + ) + + def _params(self, generation: GenerationRecord) -> TextToImageStoredParams: + require_supported_contract_version(generation.contract_version) + return params_from_spec(generation.spec) + + +def require_supported_contract_version(contract_version: int) -> None: + if contract_version != _SUPPORTED_CONTRACT_VERSION: + raise ValueError( + f"text-to-image does not support contract_version {contract_version}" + ) + + +def params_from_spec(spec: Mapping[str, object]) -> TextToImageStoredParams: + return model_from_spec(spec, "params", TextToImageStoredParams) diff --git a/backend/services/features/lora_recipes.py b/backend/services/features/lora_recipes.py index 9c075cba9..8ad1d4aaa 100644 --- a/backend/services/features/lora_recipes.py +++ b/backend/services/features/lora_recipes.py @@ -392,11 +392,15 @@ def resolve_recipe_create( model=params.model, cameraMotion=params.cameraMotion, negativePrompt=params.negativePrompt, + nagScale=params.nagScale, + nagAlpha=params.nagAlpha, + nagTau=params.nagTau, duration=params.duration, fps=params.fps, seed=params.seed, aspectRatio=params.aspectRatio, promptProvenance=params.promptProvenance, + passShape=params.passShape, loras=loras, ) return ( @@ -424,11 +428,15 @@ def resolve_recipe_create( model=params.model, cameraMotion=params.cameraMotion, negativePrompt=params.negativePrompt, + nagScale=params.nagScale, + nagAlpha=params.nagAlpha, + nagTau=params.nagTau, duration=params.duration, fps=params.fps, seed=params.seed, aspectRatio=params.aspectRatio, promptProvenance=params.promptProvenance, + passShape=params.passShape, loras=loras, ) return recipe.recipe_id, tt_params, None diff --git a/backend/services/features/queued_features.py b/backend/services/features/queued_features.py index 399041812..9671f6322 100644 --- a/backend/services/features/queued_features.py +++ b/backend/services/features/queued_features.py @@ -10,9 +10,11 @@ from services.features.lora_recipes import queued_lora_recipes from services.features.video import ( AUDIO_TO_VIDEO_FEATURE, + CUSTOM_LORA_FEATURE, EXTEND_FEATURE, FEATURE as TEXT_TO_VIDEO_FEATURE, IMAGE_TO_VIDEO_FEATURE, + KEYFRAMES_FEATURE, RETAKE_FEATURE, ) @@ -20,9 +22,11 @@ { TEXT_TO_VIDEO_FEATURE, IMAGE_TO_VIDEO_FEATURE, + KEYFRAMES_FEATURE, AUDIO_TO_VIDEO_FEATURE, RETAKE_FEATURE, EXTEND_FEATURE, + CUSTOM_LORA_FEATURE, } | {recipe.recipe_id for recipe in queued_lora_recipes()} | {recipe.recipe_id for recipe in queued_ic_lora_recipes()} diff --git a/backend/services/features/video/__init__.py b/backend/services/features/video/__init__.py index 36f1ed06f..7a7955144 100644 --- a/backend/services/features/video/__init__.py +++ b/backend/services/features/video/__init__.py @@ -15,6 +15,14 @@ ImageToVideoExecutor, RebindableAssetResolver, ) +from services.features.video.keyframes import ( + FEATURE as KEYFRAMES_FEATURE, + KeyframesExecutor, +) +from services.features.video.custom_lora import ( + CUSTOM_LORA_FEATURE, + CustomLoraExecutor, +) from services.features.video.extend import ( FEATURE as EXTEND_FEATURE, ExtendExecutor, @@ -39,6 +47,8 @@ __all__ = [ "AUDIO_TO_VIDEO_FEATURE", + "CUSTOM_LORA_FEATURE", + "CustomLoraExecutor", "IcLoraRecipeExecutor", "IcLoraSheetRecipeExecutor", "IcLoraTrackRecipeExecutor", @@ -51,6 +61,8 @@ "FEATURE", "IMAGE_TO_VIDEO_FEATURE", "ImageToVideoExecutor", + "KEYFRAMES_FEATURE", + "KeyframesExecutor", "RETAKE_FEATURE", "RebindableAssetResolver", "ReservedVideoGenerator", diff --git a/backend/services/features/video/audio_to_video.py b/backend/services/features/video/audio_to_video.py index 4306264e9..e101422e5 100644 --- a/backend/services/features/video/audio_to_video.py +++ b/backend/services/features/video/audio_to_video.py @@ -17,8 +17,8 @@ model_from_spec, require_existing_asset, resolve_job_local_model_id, + spec_pass_shape, spec_risk_allowance, - spec_unmeasured_bet, ) from services.features.video.text_to_video import ( ReservedVideoGenerator, @@ -29,6 +29,7 @@ ) from runtime_config.model_download_specs import local_aspect_ratios from services.generation_interrupt import GenerationCancelledError, is_cancel_exception +from services.generation_queue.sessions import JobSession from services.generation_queue.types import ExecutionOutcome, OutputAllocation, OutputPlan from services.records import AssetRecord, GenerationRecord @@ -63,6 +64,7 @@ def execute( self, generation: GenerationRecord, outputs: tuple[OutputAllocation, ...], + session: JobSession, ) -> ExecutionOutcome: self.validate_params( generation.spec, contract_version=generation.contract_version @@ -86,9 +88,10 @@ def execute( payload["aspectRatio"] = "16:9" req = GenerateVideoRequest.model_validate(payload) output = require_video_output(outputs) + pass_shape = spec_pass_shape(generation.spec) try: self._video_generation.validate_local_a2v_request( - params, audio_duration_ms=_audio_duration_ms(audio) + params, audio_duration_ms=_audio_duration_ms(audio), pass_shape=pass_shape ) result = self._video_generation.generate_local_reserved( req, @@ -99,8 +102,8 @@ def execute( local_model_id=resolve_job_local_model_id( self._video_generation.models_dir, offering ), - risk_allowance=spec_risk_allowance(generation.spec), - unmeasured_bet=spec_unmeasured_bet(generation.spec), + allowance=spec_risk_allowance(generation.spec), + pass_shape=pass_shape, ) except Exception as exc: if is_cancel_exception(exc): diff --git a/backend/services/features/video/custom_lora.py b/backend/services/features/video/custom_lora.py new file mode 100644 index 000000000..663da34f8 --- /dev/null +++ b/backend/services/features/video/custom_lora.py @@ -0,0 +1,75 @@ +from __future__ import annotations + +from collections.abc import Mapping + +from pydantic import BaseModel, ConfigDict, Field, ValidationError + +from api_types import LoraEntry +from services.features.video.image_to_video import ImageToVideoExecutor +from services.features.video.text_to_video import TextToVideoExecutor +from services.generation_queue.sessions import JobSession +from services.generation_queue.types import ExecutionOutcome, OutputAllocation, OutputPlan +from services.records import GenerationRecord + +CUSTOM_LORA_FEATURE = "custom-lora" +CUSTOM_LORA_NOT_DOWNLOADED = "CUSTOM_LORA_NOT_DOWNLOADED" + + +class _StoredLoras(BaseModel): + """The ``loras`` of a stored run. Every other param is ignored.""" + + model_config = ConfigDict(extra="ignore") + + loras: list[LoraEntry] = Field(default_factory=list[LoraEntry]) + + +def stored_lora(spec: Mapping[str, object]) -> LoraEntry | None: + """The one LoRA a stored custom LoRA run holds, or ``None`` when the row has none or is junk.""" + params = spec.get("params") + if not isinstance(params, dict): + return None + try: + stored = _StoredLoras.model_validate(params) + except ValidationError: + return None + return stored.loras[0] if stored.loras else None + + +class CustomLoraExecutor: + """Queued custom LoRA. One feature id for both forms. + + A run without a Start Frame stores no inputs and runs on the text-to-video executor. A run + with a Start Frame runs on the image-to-video executor. The row decides, so a custom LoRA + keeps one Home screen and one result list. + """ + + def __init__( + self, + text_to_video: TextToVideoExecutor, + image_to_video: ImageToVideoExecutor, + ) -> None: + self._text_to_video = text_to_video + self._image_to_video = image_to_video + + def validate_params( + self, spec: Mapping[str, object], *, contract_version: int + ) -> None: + self._delegate(spec).validate_params(spec, contract_version=contract_version) + + def plan_outputs(self, generation: GenerationRecord) -> tuple[OutputPlan, ...]: + return self._delegate(generation.spec).plan_outputs(generation) + + def execute( + self, + generation: GenerationRecord, + outputs: tuple[OutputAllocation, ...], + session: JobSession, + ) -> ExecutionOutcome | None: + return self._delegate(generation.spec).execute(generation, outputs, session) + + def _delegate( + self, spec: Mapping[str, object] + ) -> TextToVideoExecutor | ImageToVideoExecutor: + inputs = spec.get("inputs") + has_start_frame = isinstance(inputs, Mapping) and "startFrame" in inputs + return self._image_to_video if has_start_frame else self._text_to_video diff --git a/backend/services/features/video/edit_executor.py b/backend/services/features/video/edit_executor.py index 349d13ec9..336ce2b0c 100644 --- a/backend/services/features/video/edit_executor.py +++ b/backend/services/features/video/edit_executor.py @@ -3,6 +3,7 @@ from __future__ import annotations import logging +import os from abc import ABC, abstractmethod from collections.abc import Callable, Mapping from dataclasses import dataclass @@ -11,6 +12,8 @@ from api_types import LTXLocalModelId, OfferingId, PromptProvenance from _routes._errors import HTTPError +from runtime_config.budget_admission import RiskAllowance +from runtime_config.device_calibration import JobEnvelope from runtime_config.ltx_capabilities import LtxCapabilityFeature from runtime_config.video_job_budget import ( LOCAL_GENERATION_RAM_SHORTFALL, @@ -24,7 +27,6 @@ require_existing_asset, resolve_generation_seed, spec_risk_allowance, - spec_unmeasured_bet, ) from services.features.video.text_to_video import ( VIDEO_OUTPUT_PLAN, @@ -32,6 +34,14 @@ require_video_output, ) from services.generation_interrupt import GenerationCancelledError, is_cancel_exception +from services.fast_video_pipeline.nag_config import ( + DEFAULT_SCALE as DEFAULT_NAG_SCALE, + NagConfig, + NagDecision, + decide_nag, + log_nag_decision, +) +from services.generation_queue.sessions import JobSession from services.generation_queue.types import ExecutionOutcome, OutputAllocation, OutputPlan from services.prompt_enhancement.source_video import SourceVideo from services.records import ( @@ -59,9 +69,13 @@ class _AfterProbe: class GpuJobSlot(Protocol): - def start_generation(self, generation_id: str) -> None: ... + def start_generation( + self, generation_id: str, *, ran: JobEnvelope | None = None + ) -> None: ... - def complete_generation(self, result: str | list[str] | None = None) -> None: ... + def complete_generation( + self, result: str | list[str] | None = None, *, ran: JobEnvelope | None = None + ) -> None: ... def fail_generation(self, error: str) -> None: ... @@ -76,9 +90,8 @@ def load_retake_pipeline( height: int | None = None, frames: int | None = None, queued_home: bool = False, - allow_risk: bool | None = None, - unmeasured_bet: bool = False, - ) -> RetakePipelineState: ... + allowance: RiskAllowance | None = None, + ) -> tuple[RetakePipelineState, JobEnvelope | None]: ... def edit_encode_frame_cap( self, width: int, height: int, *, total_only: bool = False @@ -97,6 +110,10 @@ def prepare_text_encoding( def clear_api_embeddings(self) -> None: ... + def should_use_local_encoding( + self, model_id: LTXLocalModelId | None = None + ) -> bool: ... + class _ResolvedPrompt(Protocol): @property @@ -116,6 +133,7 @@ def resolve_for_generation( local_model_id: LTXLocalModelId | None, explore_generation: bool, source_video: SourceVideo | None, + negative_prompt: str = "", ) -> _ResolvedPrompt: ... @@ -123,6 +141,10 @@ class VideoEditParams(Protocol): model: OfferingId seed: int | None prompt: str + negativePrompt: str + nagScale: float | None + nagAlpha: float | None + nagTau: float | None promptProvenance: PromptProvenance def model_copy(self, *, update: Mapping[str, object]) -> Self: ... @@ -139,9 +161,14 @@ class VideoEditInputs(Protocol): def video(self) -> _VideoRef: ... +class PreparedEdit(Protocol): + @property + def ran(self) -> JobEnvelope | None: ... + + PParams = TypeVar("PParams", bound=VideoEditParams) PInputs = TypeVar("PInputs", bound=VideoEditInputs) -PPrepared = TypeVar("PPrepared") +PPrepared = TypeVar("PPrepared", bound=PreparedEdit) class VideoEditExecutor(ABC, Generic[PParams, PInputs, PPrepared]): @@ -159,6 +186,7 @@ def __init__( default_negative_prompt: str, generation: GpuJobSlot, prompt_enhancement: SourceVideoPromptResolver, + default_nag_scale: Callable[[], float] | None = None, ) -> None: self._pipelines = pipelines self._assets = assets @@ -167,6 +195,7 @@ def __init__( self._default_negative_prompt = default_negative_prompt self._generation = generation self._prompt_enhancement = prompt_enhancement + self._default_nag_scale = default_nag_scale or (lambda: DEFAULT_NAG_SCALE) def validate_params( self, spec: Mapping[str, object], *, contract_version: int @@ -188,9 +217,8 @@ def _load_pipeline( width: int, height: int, frames: int, - allow_risk: bool, - unmeasured_bet: bool = False, - ) -> RetakePipelineState: + allowance: RiskAllowance, + ) -> tuple[RetakePipelineState, JobEnvelope | None]: return self._pipelines.load_retake_pipeline( distilled=True, ltx_model_id=local_model_id, @@ -198,8 +226,7 @@ def _load_pipeline( height=height, frames=frames, queued_home=True, - allow_risk=allow_risk, - unmeasured_bet=unmeasured_bet, + allowance=allowance, ) def _after_probe( @@ -209,7 +236,7 @@ def _after_probe( width: int, height: int, total_cap: int, - allow_risk: bool, + allowance: RiskAllowance, ) -> _AfterProbe: """What to do after the no-bet probe refuses. @@ -220,14 +247,14 @@ def _after_probe( total, reloads the original window with the bet. """ if exc.code == LOCAL_GENERATION_RAM_SHORTFALL: - if not allow_risk: + if not allowance.over: raise exc return _AfterProbe(kind="bet") if exc.code != VIDEO_JOB_TOO_LARGE: raise exc free_cap = self._pipelines.edit_encode_frame_cap(width, height) if free_cap >= total_cap: - if not allow_risk: + if not allowance.over: raise exc return _AfterProbe(kind="bet") if total_cap - free_cap > MAX_SHRINK_GAP_FRAMES: @@ -252,18 +279,18 @@ def _load_edit_window( height: int, frames: int, total_cap: int, - allow_risk: bool, - unmeasured_bet: bool = False, + allowance: RiskAllowance, generation_id: str, log_name: str, rewindow: Callable[[int], int], - ) -> RetakePipelineState: - """Probe without the bet, then shrink or cover what shrink cannot. - - The first load passes ``allow_risk=False`` so a free-gate refusal is - visible. A re-windowable dip calls ``rewindow`` and loads that frame - count with the real bet. A mask ``rewindow`` cannot fit raises there - and does not fall through to the original window. + ) -> tuple[RetakePipelineState, JobEnvelope | None]: + """Probe without the over bet, then shrink or cover what shrink cannot. + + The first load passes ``allowance.without_over()`` so a free-gate refusal + is visible while any stored unmeasured bet still carries through. A + re-windowable dip calls ``rewindow`` and loads that frame count with the + real allowance. A mask ``rewindow`` cannot fit raises there and does not + fall through to the original window. """ try: return self._load_pipeline( @@ -271,8 +298,7 @@ def _load_edit_window( width=width, height=height, frames=frames, - allow_risk=False, - unmeasured_bet=unmeasured_bet, + allowance=allowance.without_over(), ) except HTTPError as exc: decision = self._after_probe( @@ -280,7 +306,7 @@ def _load_edit_window( width=width, height=height, total_cap=total_cap, - allow_risk=allow_risk, + allowance=allowance, ) if decision.kind == "bet": logger.info( @@ -296,8 +322,7 @@ def _load_edit_window( width=width, height=height, frames=frames, - allow_risk=True, - unmeasured_bet=unmeasured_bet, + allowance=allowance, ) except HTTPError as bet_exc: raise bet_exc from exc @@ -307,14 +332,14 @@ def _load_edit_window( width=width, height=height, frames=rewindow(decision.free_cap), - allow_risk=allow_risk, - unmeasured_bet=unmeasured_bet, + allowance=allowance, ) def execute( self, generation: GenerationRecord, outputs: tuple[OutputAllocation, ...], + session: JobSession, ) -> ExecutionOutcome | None: self.validate_params( generation.spec, contract_version=generation.contract_version @@ -344,6 +369,10 @@ def execute( # the VRAM a resident pipeline holds. The server-side API flag stays off (it cannot see # the video), so enhance_prompt=False below is unchanged. typed_prompt = params.prompt + nag_decision = self.decide_nag( + params, + local_encoding=self._text.should_use_local_encoding(local_model_id), + ) enhanced_prompt = self._prompt_enhancement.resolve_for_generation( typed_prompt, provenance=params.promptProvenance, @@ -356,6 +385,7 @@ def execute( replaced_window=self.replaced_window(params), writes_blank_prompt=True, ), + negative_prompt=nag_decision.enhancer_negative, ).prompt params = params.model_copy(update={"prompt": enhanced_prompt}) try: @@ -377,8 +407,7 @@ def execute( seed, dest, windowed_path, - allow_risk=spec_risk_allowance(generation.spec), - unmeasured_bet=spec_unmeasured_bet(generation.spec), + allowance=spec_risk_allowance(generation.spec), ) def _infer() -> None: @@ -389,7 +418,7 @@ def _infer() -> None: finally: Path(windowed_path).unlink(missing_ok=True) - run_gpu_job(self._generation, generation.id, str(dest), _infer) + run_gpu_job(self._generation, generation.id, str(dest), _infer, ran=prepared.ran) if not typed_prompt.strip() and enhanced_prompt.strip(): return ExecutionOutcome(written_prompt=enhanced_prompt) # Modes unknown: the retake pipeline does not surface its load/offload @@ -419,6 +448,35 @@ def replaced_window(self, params: PParams) -> tuple[float, float] | None: del params return None + def decide_nag( + self, params: PParams, *, local_encoding: bool + ) -> NagDecision: + return decide_nag( + params.negativePrompt, + os.environ, + scale=params.nagScale, + alpha=params.nagAlpha, + tau=params.nagTau, + default_scale=self._default_nag_scale(), + local_encoding=local_encoding, + compiled=False, + ) + + def resolve_nag( + self, params: PParams, pipeline_state: RetakePipelineState + ) -> NagConfig | None: + return log_nag_decision( + logger, + self.capability, + self.decide_nag( + params, + local_encoding=( + self._text.should_use_local_encoding(pipeline_state.ltx_model_id) + and pipeline_state.gemma_root is not None + ), + ), + ) + @abstractmethod def prepare( self, @@ -430,8 +488,7 @@ def prepare( dest: Path, windowed_path: str, *, - allow_risk: bool, - unmeasured_bet: bool = False, + allowance: RiskAllowance = RiskAllowance.none(), ) -> PPrepared: ... @abstractmethod @@ -446,12 +503,14 @@ def run_gpu_job( generation_id: str, result_path: str, run: Callable[[], None], + *, + ran: JobEnvelope | None = None, ) -> None: - slot.start_generation(generation_id) + slot.start_generation(generation_id, ran=ran) try: run() except Exception as exc: if not is_cancel_exception(exc): slot.fail_generation(str(exc)) raise - slot.complete_generation(result_path) + slot.complete_generation(result_path, ran=ran) diff --git a/backend/services/features/video/extend.py b/backend/services/features/video/extend.py index b18fad10e..acd88137f 100644 --- a/backend/services/features/video/extend.py +++ b/backend/services/features/video/extend.py @@ -12,6 +12,8 @@ read_source_metadata, resolve_requested_home_edit_size, ) +from runtime_config.budget_admission import RiskAllowance +from runtime_config.device_calibration import JobEnvelope from services.features.video.edit_executor import VideoEditExecutor from services.features.video.job_common import model_from_spec from services.fast_video_pipeline.windowed_run import measured_edit @@ -44,6 +46,7 @@ class _PreparedExtend: extend_frames: int dest_path: Path windowed_path: str + ran: JobEnvelope | None class ExtendExecutor(VideoEditExecutor[ExtendParams, ExtendInputs, _PreparedExtend]): @@ -70,8 +73,7 @@ def prepare( dest: Path, windowed_path: str, *, - allow_risk: bool, - unmeasured_bet: bool = False, + allowance: RiskAllowance = RiskAllowance.none(), ) -> _PreparedExtend: fps, source_width, source_height, source_frames = read_source_metadata( video.path @@ -158,14 +160,13 @@ def rewindow(free_cap: int) -> int: window, extend_frames = shrunk.window, shrunk.extend_frames return window.context_frames + extend_frames - pipeline_state = self._load_edit_window( + pipeline_state, ran = self._load_edit_window( local_model_id=local_model_id, width=box.canvas_width, height=box.canvas_height, frames=window.context_frames + extend_frames, total_cap=frame_cap, - allow_risk=allow_risk, - unmeasured_bet=unmeasured_bet, + allowance=allowance, generation_id=generation.id, log_name="Extend", rewindow=rewindow, @@ -201,6 +202,7 @@ def rewindow(free_cap: int) -> int: extend_frames=extend_frames, dest_path=dest, windowed_path=windowed_path, + ran=ran, ) def generate(self, prepared: _PreparedExtend) -> None: @@ -209,6 +211,7 @@ def generate(self, prepared: _PreparedExtend) -> None: self._generate(prepared) def _generate(self, prepared: _PreparedExtend) -> None: + nag = self.resolve_nag(prepared.params, prepared.pipeline_state) prepared.pipeline_state.pipeline.extend( video_path=prepared.video.path, prompt=prepared.params.prompt, @@ -216,7 +219,7 @@ def _generate(self, prepared: _PreparedExtend) -> None: mode=prepared.params.mode, seed=prepared.seed, output_path=prepared.windowed_path, - negative_prompt=self._default_negative_prompt, + negative_prompt=prepared.params.negativePrompt or self._default_negative_prompt, regenerate_audio=True, enhance_prompt=False, distilled=True, @@ -227,6 +230,7 @@ def _generate(self, prepared: _PreparedExtend) -> None: target_frames=prepared.window.context_frames, encode_start_time=prepared.window.start_time(prepared.fps), encode_max_duration=prepared.window.max_duration(prepared.fps), + nag=nag, ) def stitch(self, prepared: _PreparedExtend) -> None: diff --git a/backend/services/features/video/ic_lora_recipe.py b/backend/services/features/video/ic_lora_recipe.py index c58810cb3..a70c0c57e 100644 --- a/backend/services/features/video/ic_lora_recipe.py +++ b/backend/services/features/video/ic_lora_recipe.py @@ -25,9 +25,10 @@ TargetResolution, ) from _routes._errors import HTTPError +from runtime_config.budget_admission import RiskAllowance from runtime_config.ic_lora_high_res import ( HIGH_RES_NOT_ENABLED, - HIGH_RES_ONLY_IC_LORAS, + high_res_flag_satisfied, high_res_cell, high_res_stage1, ) @@ -60,7 +61,6 @@ resolve_generation_seed, resolve_job_local_model_id, spec_risk_allowance, - spec_unmeasured_bet, ) from services.features.video.text_to_video import ( VIDEO_OUTPUT_PLAN, @@ -69,6 +69,7 @@ ) from services.ffmpeg import FFMPEG_PROTOCOL_WHITELIST, run_ffmpeg, timeout_for_pixels from services.generation_interrupt import GenerationCancelledError, is_cancel_exception +from services.generation_queue.sessions import JobSession from services.generation_queue.types import ( ExecutionOutcome, OutputAllocation, @@ -87,9 +88,6 @@ def _frame_outcome(clip_frames: int, run_frames: int) -> str: return "no change, already on the frame grid" -logger = logging.getLogger(__name__) - - class ReservedIcLoraGenerator(Protocol): def generate_local_reserved( self, @@ -102,8 +100,7 @@ def generate_local_reserved( explore_generation: bool = True, explicit_generation_seed: bool = False, high_res: bool = False, - risk_allowance: bool | None = None, - unmeasured_bet: bool = False, + allowance: RiskAllowance | None = None, panel_paths: Sequence[str] = (), ) -> object: ... @@ -116,8 +113,7 @@ def recipe_run_frames( stored: IcLoraRecipeStoredParams, clip_frames: int, upscale: bool, - risk_allowance: bool | None, - unmeasured_bet: bool, + allowance: RiskAllowance | None = None, ) -> tuple[int, GenerationRisk | None]: """Frame count the run uses for a clip: snapped up, or down when up is over budget. @@ -205,8 +201,8 @@ def __init__( self._high_res_enabled = high_res_enabled or (lambda: False) def _require_high_res(self) -> None: - """The 1440p and 2160p cells need the highResVideoToVideo flag.""" - if not self._high_res_enabled(): + """The 1440p and 2160p cells need the highResVideoToVideo flag, for most recipes.""" + if not high_res_flag_satisfied(self._catalog_id, flag_enabled=self._high_res_enabled()): logger.warning( "%s high-res cell refused: recipe=%s highResVideoToVideo=%s", PREFIX, self._catalog_id, self._high_res_enabled(), @@ -246,6 +242,7 @@ def execute( self, generation: GenerationRecord, outputs: tuple[OutputAllocation, ...], + session: JobSession, ) -> ExecutionOutcome: self.validate_params( generation.spec, contract_version=generation.contract_version @@ -314,7 +311,7 @@ def execute( # Inside the try so a resolution with no local cell becomes a capability # failure, the same as image-to-video's pixel lookup. high_res = high_res_cell(params.resolution) - if high_res is not None or self._catalog_id in HIGH_RES_ONLY_IC_LORAS: + if high_res is not None: self._require_high_res() if high_res is not None: width, height = stage_canvas = high_res_stage1( @@ -363,6 +360,7 @@ def execute( fit = None clip_frames = video_frame_count(source) keep_source_audio = params.audioMode == "source" and meta.audioStreamCount > 0 + allowance = spec_risk_allowance(generation.spec) if cutout_dest is None: # The pipeline snaps a frame count down. Repeat the last frame up to the # next valid count, and cut the output back to `clip_frames` after the run. @@ -376,8 +374,7 @@ def execute( stored=params, clip_frames=clip_frames, upscale=self._upscales_to_cell, - risk_allowance=spec_risk_allowance(generation.spec), - unmeasured_bet=spec_unmeasured_bet(generation.spec), + allowance=allowance, ) logger.info( "[ic-lora] recipe %s frames: clip=%d run=%d (%s)", @@ -416,11 +413,19 @@ def execute( ic_lora_id=self._catalog_id, input_path=str(model_input), prompt=params.prompt, + negative_prompt=params.negativePrompt, + nag_scale=params.nagScale, + nag_alpha=params.nagAlpha, + nag_tau=params.nagTau, prompt_provenance=params.promptProvenance, conditioning_type="custom", resolution=TargetResolution(width=width, height=height), audio_mode=params.audioMode, lora_strength=params.loras[0].scale, + tile_overlap=params.tilingOverlap, + tile_size=params.tilingSize, + carry_frames=params.carryFrames, + max_window_frames=params.maxWindowFrames, variant_id=params.loras[0].variantId, control_values=( {IC_LORA_CONTROL_TYPE_ID: params.controlType} @@ -444,8 +449,7 @@ def execute( seed=seed, explicit_generation_seed=params.seed is not None, high_res=high_res is not None, - risk_allowance=spec_risk_allowance(generation.spec), - unmeasured_bet=spec_unmeasured_bet(generation.spec), + allowance=allowance, ) if isinstance(result, IcLoraGenerateCancelledResponse): raise GenerationCancelledError() diff --git a/backend/services/features/video/ic_lora_sheet_recipe.py b/backend/services/features/video/ic_lora_sheet_recipe.py index 86cd7bc9f..b49cd2d54 100644 --- a/backend/services/features/video/ic_lora_sheet_recipe.py +++ b/backend/services/features/video/ic_lora_sheet_recipe.py @@ -39,14 +39,11 @@ def prepare( ).path for ref in inputs.images ] - app_data_dir = ( - control.parent.parent.parent - if control.parent.name == ".in-flight" - else control.parent - ) + # The sheet goes beside the job output, in the store's in-flight folder. + in_flight_dir = control.parent try: sheet = ensure_reference_sheet( - image_paths, *canvas, app_data_dir=app_data_dir + image_paths, *canvas, in_flight_dir=in_flight_dir ) except (OSError, ValueError) as exc: # A corrupt or unreadable panel image (Pillow raises OSError subclasses). diff --git a/backend/services/features/video/image_to_video.py b/backend/services/features/video/image_to_video.py index 3c25aaf6d..fa2f58e5c 100644 --- a/backend/services/features/video/image_to_video.py +++ b/backend/services/features/video/image_to_video.py @@ -18,8 +18,8 @@ model_from_spec, require_existing_asset, resolve_job_local_model_id, + spec_pass_shape, spec_risk_allowance, - spec_unmeasured_bet, ) from services.features.video.text_to_video import ( ReservedVideoGenerator, @@ -31,6 +31,7 @@ from runtime_config.model_download_specs import local_aspect_ratios from services.aspect_ratio import find_closest_aspect_ratio_option from services.generation_interrupt import GenerationCancelledError, is_cancel_exception +from services.generation_queue.sessions import JobSession from services.generation_queue.types import ExecutionOutcome, OutputAllocation, OutputPlan from services.records import AssetRecord, GenerationRecord @@ -65,7 +66,7 @@ def __init__( self._assets = assets # Recipe-scoped: post-enhancement prompt scaffold. None for plain i2v. self._prompt_wrap = prompt_wrap - # Recipe-scoped: fills the LoRA ref from its catalog id at execution. None for plain i2v. + # Recipe/custom-LoRA scoped: fills the LoRA ref at execution. None for plain i2v. self._lora_resolver = lora_resolver def validate_params( @@ -85,6 +86,7 @@ def execute( self, generation: GenerationRecord, outputs: tuple[OutputAllocation, ...], + session: JobSession, ) -> ExecutionOutcome: self.validate_params( generation.spec, contract_version=generation.contract_version @@ -105,7 +107,9 @@ def execute( try: # Inside the try so a resolution with no local cell becomes a capability # failure, the same as generate_local_reserved's pixel lookup. - request_payload["aspectRatio"] = _resolve_aspect_ratio(params, start) + request_payload["aspectRatio"] = resolve_image_aspect_ratio( + params.aspectRatio, params.resolution, start + ) req = GenerateVideoRequest.model_validate(request_payload) if self._lora_resolver is not None: # Inside the try so a missing/removed adapter becomes a capability failure. @@ -118,8 +122,8 @@ def execute( local_model_id=resolve_job_local_model_id( self._video_generation.models_dir, offering ), - risk_allowance=spec_risk_allowance(generation.spec), - unmeasured_bet=spec_unmeasured_bet(generation.spec), + allowance=spec_risk_allowance(generation.spec), + pass_shape=spec_pass_shape(generation.spec), ) except Exception as exc: if is_cancel_exception(exc): @@ -149,16 +153,17 @@ def _resolve_image(self, asset_id: str, *, slot: str) -> AssetRecord: ) -def _resolve_aspect_ratio( - params: ImageToVideoParams, start: AssetRecord +def resolve_image_aspect_ratio( + aspect_ratio: str, resolution: str, image: AssetRecord ) -> str: - if params.aspectRatio != "auto": - return params.aspectRatio - metadata = start.metadata + """An explicit aspect passes through. Auto is the local option closest to the image.""" + if aspect_ratio != "auto": + return aspect_ratio + metadata = image.metadata if metadata.mediaType != "image": raise ValueError("startFrame must have image metadata") try: - options = local_aspect_ratios(params.resolution, is_a2v=False) + options = local_aspect_ratios(resolution, is_a2v=False) except KeyError as exc: raise HTTPError(400, "INVALID_LOCAL_RESOLUTION") from exc return find_closest_aspect_ratio_option( diff --git a/backend/services/features/video/job_common.py b/backend/services/features/video/job_common.py index b561aac38..f06537daf 100644 --- a/backend/services/features/video/job_common.py +++ b/backend/services/features/video/job_common.py @@ -5,26 +5,32 @@ import random from collections.abc import Mapping from pathlib import Path -from typing import Protocol, TypeGuard, TypeVar +from typing import Protocol, TypeVar -from pydantic import BaseModel, ValidationError +from pydantic import BaseModel from api_types import ( - GenerationRisk, IcLoraRecipeResolution, IcLoraSynthesizedStoredParams, LTXLocalModelId, LTXVideoGenAspectRatio, OfferingId, ) -from runtime_config.ic_lora_high_res import high_res_cell from _routes._errors import HTTPError +from runtime_config.budget_admission import ( + RiskAllowance, + stored_generation_risk as stored_generation_risk, +) +from runtime_config.ic_lora_high_res import high_res_cell from runtime_config.ltx_capabilities import LtxCapabilityFeature, budget_pixels, local_caps, supports +from runtime_config.reject_reasons import PassShape from runtime_config.offerings import resolve_offering_local_model_id from services.records import AssetRecord, CapabilityFailedError from state.app_settings import MAX_GENERATION_SEED INPUT_ASSET_NOT_FOUND = "INPUT_ASSET_NOT_FOUND" +# Private spec key beside ``_risk``: the Fast shape create resolved. +PASS_SHAPE_SPEC_KEY = "_passShape" TModel = TypeVar("TModel", bound=BaseModel) @@ -66,40 +72,31 @@ def model_from_spec( return model.model_validate(value) -def _is_str_object_dict(value: object) -> TypeGuard[dict[str, object]]: - return isinstance(value, dict) - +def spec_risk_allowance(spec: Mapping[str, object]) -> RiskAllowance: + """The stored bet as a RiskAllowance. -def stored_generation_risk(spec: Mapping[str, object]) -> GenerationRisk | None: - """The stored bet, or None when it is missing or junk. - - Junk fails closed: execute must not waive a limit off a corrupt row. + Only ``over`` waives a later memory shortfall; ``unmeasured`` waives an + untested fence without covering a VRAM or RAM miss. A missing field or junk + fails closed. Executors pass this — never the live mode — so switching to + Cautious does not cancel a job already in the queue. """ - risk = spec.get("_risk") - if not _is_str_object_dict(risk): - return None - try: - return GenerationRisk.model_validate(risk) - except ValidationError: - return None + return RiskAllowance.from_stored(spec) -def spec_risk_allowance(spec: Mapping[str, object]) -> bool: - """Whether the stored bet waives a later memory shortfall. +def spec_pass_shape(spec: Mapping[str, object]) -> PassShape: + """The shape create resolved, as stored. - Only ``over`` does. ``unmeasured`` means the route had no fitted curve, - not that a VRAM or RAM miss may run. A missing field or junk fails closed. - Executors pass this — never the live mode — so turning Reckless off does - not cancel an over-budget job already in the queue. + Executors pass this, never the live "Never split" setting, so a flip does + not re-cut a queued job. A missing field (jobs queued before shapes were + stored) or junk means ``auto``. """ - risk = stored_generation_risk(spec) - return risk is not None and risk.tier == "over" - - -def spec_unmeasured_bet(spec: Mapping[str, object]) -> bool: - """Whether the stored bet is an unmeasured route, not a memory shortfall.""" - risk = stored_generation_risk(spec) - return risk is not None and risk.tier == "unmeasured" + match spec.get(PASS_SHAPE_SPEC_KEY): + case "one_pass": + return "one_pass" + case "parts": + return "parts" + case _: + return "auto" def resolve_generation_seed(seed: int | None) -> int: diff --git a/backend/services/features/video/keyframes.py b/backend/services/features/video/keyframes.py new file mode 100644 index 000000000..4aebe9dca --- /dev/null +++ b/backend/services/features/video/keyframes.py @@ -0,0 +1,117 @@ +"""Home Keyframes: several stills at chosen frames guide one local clip.""" + +from __future__ import annotations + +from collections.abc import Mapping +from pathlib import Path + +from api_types import ( + GenerateVideoCancelledResponse, + GenerateVideoRequest, + KeyframeRef, + KeyframesInputs, + KeyframesParams, +) +from _routes._errors import HTTPError +from keyframe_request import validate_keyframe_frames +from services.features.video.image_to_video import AssetResolver, resolve_image_aspect_ratio +from services.features.video.job_common import ( + capability_failed_from_http, + model_from_spec, + require_existing_asset, + resolve_job_local_model_id, + spec_pass_shape, + spec_risk_allowance, +) +from services.features.video.text_to_video import ( + ReservedVideoGenerator, + VIDEO_OUTPUT_PLAN, + offering_payload_from_params, + require_video_output, + require_supported_contract_version, +) +from services.generation_interrupt import GenerationCancelledError, is_cancel_exception +from services.generation_queue.sessions import JobSession +from services.generation_queue.types import ExecutionOutcome, OutputAllocation, OutputPlan +from services.records import AssetRecord, GenerationRecord + +FEATURE = "keyframes" +_INPUT_ASSET_UNAVAILABLE = "keyframe image is no longer available" + + +class KeyframesExecutor: + def __init__(self, video_generation: ReservedVideoGenerator, assets: AssetResolver) -> None: + self._video_generation = video_generation + self._assets = assets + + def validate_params(self, spec: Mapping[str, object], *, contract_version: int) -> None: + require_supported_contract_version(contract_version) + params = model_from_spec(spec, "params", KeyframesParams) + inputs = model_from_spec(spec, "inputs", KeyframesInputs) + if params.duration is None: + raise ValueError("Keyframes cannot be combined with automatic duration") + error = validate_keyframe_frames( + [keyframe.frameIndex for keyframe in inputs.keyframes], + duration=params.duration, + fps=params.fps, + ) + if error is not None: + raise ValueError(error) + + def plan_outputs(self, generation: GenerationRecord) -> tuple[OutputPlan, ...]: + self.validate_params(generation.spec, contract_version=generation.contract_version) + return (VIDEO_OUTPUT_PLAN,) + + def execute( + self, + generation: GenerationRecord, + outputs: tuple[OutputAllocation, ...], + session: JobSession, + ) -> ExecutionOutcome: + self.validate_params(generation.spec, contract_version=generation.contract_version) + params = model_from_spec(generation.spec, "params", KeyframesParams) + inputs = model_from_spec(generation.spec, "inputs", KeyframesInputs) + stills = [(keyframe, self._resolve_image(keyframe)) for keyframe in inputs.keyframes] + request_payload, offering = offering_payload_from_params(params) + request_payload["keyframes"] = [ + {"imagePath": still.path, "frameIndex": keyframe.frameIndex, "strength": keyframe.strength} + for keyframe, still in stills + ] + output = require_video_output(outputs) + try: + # Auto follows the first still on the timeline, the one the prompt enhancer sees. + _, first_still = min(stills, key=lambda pair: pair[0].frameIndex) + request_payload["aspectRatio"] = resolve_image_aspect_ratio( + params.aspectRatio, params.resolution, first_still + ) + req = GenerateVideoRequest.model_validate(request_payload) + result = self._video_generation.generate_local_reserved( + req, + generation_id=generation.id, + output_path=Path(output.dest_path), + prompt_wrap=None, + local_model_id=resolve_job_local_model_id( + self._video_generation.models_dir, offering + ), + allowance=spec_risk_allowance(generation.spec), + pass_shape=spec_pass_shape(generation.spec), + ) + except Exception as exc: + if is_cancel_exception(exc): + raise GenerationCancelledError() from exc + if isinstance(exc, HTTPError): + raise capability_failed_from_http( + exc, unavailable=_INPUT_ASSET_UNAVAILABLE + ) from exc + raise + if isinstance(result, GenerateVideoCancelledResponse): + raise GenerationCancelledError() + return ExecutionOutcome(load_mode=result.load_mode, offload_mode=result.offload_mode) + + def _resolve_image(self, keyframe: KeyframeRef) -> AssetRecord: + return require_existing_asset( + self._assets, + keyframe.assetId, + media_kind="image", + unavailable=_INPUT_ASSET_UNAVAILABLE, + ) diff --git a/backend/services/features/video/reference_sheet.py b/backend/services/features/video/reference_sheet.py index bcdbb5755..7c7074311 100644 --- a/backend/services/features/video/reference_sheet.py +++ b/backend/services/features/video/reference_sheet.py @@ -29,10 +29,6 @@ _MAX_CACHED_SHEETS = 8 -def _in_flight_dir(app_data_dir: Path) -> Path: - return app_data_dir / "assets" / ".in-flight" - - def _sheet_key(paths: Sequence[str], width: int, height: int) -> str: digest = hashlib.sha256(f"{width}x{height}".encode()) for raw in paths: @@ -61,14 +57,15 @@ def _evict_old_sheets(in_flight_dir: Path, *, keep: Path) -> None: def ensure_reference_sheet( - paths: Sequence[str], width: int, height: int, *, app_data_dir: Path + paths: Sequence[str], width: int, height: int, *, in_flight_dir: Path ) -> Path: """Return the cached reference sheet in ``.in-flight``, building it if absent. Only ``sheet-*.png`` files are evicted; other files in ``.in-flight`` are untouched. """ - in_flight = _in_flight_dir(app_data_dir) - in_flight.mkdir(parents=True, exist_ok=True) + in_flight = in_flight_dir + # No parents: a gone custom assets folder must not be created without its marker. + in_flight.mkdir(exist_ok=True) dest = in_flight / f"{_SHEET_PREFIX}{_sheet_key(paths, width, height)}{_SHEET_SUFFIX}" if not dest.is_file(): # A unique name, so two builders of the same sheet do not replace each other's file. diff --git a/backend/services/features/video/retake.py b/backend/services/features/video/retake.py index 4a90e3786..61a77e6a9 100644 --- a/backend/services/features/video/retake.py +++ b/backend/services/features/video/retake.py @@ -12,6 +12,8 @@ read_source_metadata, resolve_requested_home_edit_size, ) +from runtime_config.budget_admission import RiskAllowance +from runtime_config.device_calibration import JobEnvelope from services.features.video.edit_executor import VideoEditExecutor from services.features.video.job_common import model_from_spec from services.fast_video_pipeline.windowed_run import measured_edit @@ -51,6 +53,7 @@ class _PreparedRetake: regenerate_audio: bool dest_path: Path windowed_path: str + ran: JobEnvelope | None class RetakeExecutor(VideoEditExecutor[RetakeParams, RetakeInputs, _PreparedRetake]): @@ -80,8 +83,7 @@ def prepare( dest: Path, windowed_path: str, *, - allow_risk: bool, - unmeasured_bet: bool = False, + allowance: RiskAllowance = RiskAllowance.none(), ) -> _PreparedRetake: try: regenerate_video, regenerate_audio = resolve_retake_mode(params.mode) @@ -152,14 +154,13 @@ def rewindow(free_cap: int) -> int: region_start, region_end = feathered_mask_times(window, fps) return window.encode_frames - pipeline_state = self._load_edit_window( + pipeline_state, ran = self._load_edit_window( local_model_id=local_model_id, width=box.canvas_width, height=box.canvas_height, frames=window.encode_frames, total_cap=frame_cap, - allow_risk=allow_risk, - unmeasured_bet=unmeasured_bet, + allowance=allowance, generation_id=generation.id, log_name="Retake", rewindow=rewindow, @@ -199,6 +200,7 @@ def rewindow(free_cap: int) -> int: regenerate_audio=regenerate_audio, dest_path=dest, windowed_path=windowed_path, + ran=ran, ) def generate(self, prepared: _PreparedRetake) -> None: @@ -206,6 +208,7 @@ def generate(self, prepared: _PreparedRetake) -> None: self._generate(prepared) def _generate(self, prepared: _PreparedRetake) -> None: + nag = self.resolve_nag(prepared.params, prepared.pipeline_state) prepared.pipeline_state.pipeline.generate( video_path=prepared.video.path, prompt=prepared.params.prompt, @@ -213,7 +216,7 @@ def _generate(self, prepared: _PreparedRetake) -> None: end_time=prepared.region_end, seed=prepared.seed, output_path=prepared.windowed_path, - negative_prompt=self._default_negative_prompt, + negative_prompt=prepared.params.negativePrompt or self._default_negative_prompt, num_inference_steps=40, video_guider_params=None, audio_guider_params=None, @@ -228,6 +231,7 @@ def _generate(self, prepared: _PreparedRetake) -> None: target_frames=prepared.window.encode_frames, encode_start_time=prepared.window.encode_start_time(prepared.fps), encode_max_duration=prepared.window.encode_duration(prepared.fps), + nag=nag, ) def stitch(self, prepared: _PreparedRetake) -> None: diff --git a/backend/services/features/video/synthesized_ic_lora.py b/backend/services/features/video/synthesized_ic_lora.py index b6fda0451..f6303affc 100644 --- a/backend/services/features/video/synthesized_ic_lora.py +++ b/backend/services/features/video/synthesized_ic_lora.py @@ -35,7 +35,6 @@ resolve_generation_seed, resolve_job_local_model_id, spec_risk_allowance, - spec_unmeasured_bet, ) from services.features.video.text_to_video import ( VIDEO_OUTPUT_PLAN, @@ -43,6 +42,7 @@ require_video_output, ) from services.generation_interrupt import GenerationCancelledError, is_cancel_exception +from services.generation_queue.sessions import JobSession from services.generation_queue.types import ( ExecutionOutcome, OutputAllocation, @@ -99,6 +99,10 @@ def generate_request( prompt=apply_recipe_prompt_template( recipe, params.prompt.strip() if recipe.prompt_template else params.prompt ), + negative_prompt=params.negativePrompt, + nag_scale=params.nagScale, + nag_alpha=params.nagAlpha, + nag_tau=params.nagTau, prompt_provenance=params.promptProvenance, conditioning_type="custom", resolution=TargetResolution(width=canvas[0], height=canvas[1]), @@ -142,6 +146,7 @@ def execute( self, generation: GenerationRecord, outputs: tuple[OutputAllocation, ...], + session: JobSession, ) -> ExecutionOutcome: self.validate_params( generation.spec, contract_version=generation.contract_version @@ -166,8 +171,7 @@ def execute( local_model_id=local_model_id, seed=resolve_generation_seed(params.seed), explicit_generation_seed=params.seed is not None, - risk_allowance=spec_risk_allowance(generation.spec), - unmeasured_bet=spec_unmeasured_bet(generation.spec), + allowance=spec_risk_allowance(generation.spec), panel_paths=job.panel_paths, ) except Exception as exc: diff --git a/backend/services/features/video/text_to_video.py b/backend/services/features/video/text_to_video.py index 57a0114e5..8303b4837 100644 --- a/backend/services/features/video/text_to_video.py +++ b/backend/services/features/video/text_to_video.py @@ -17,14 +17,17 @@ TextToVideoParams, ) from _routes._errors import HTTPError +from runtime_config.budget_admission import RiskAllowance from runtime_config.offerings import OFFERING_IDS, local_pipeline_for_offering +from runtime_config.reject_reasons import PassShape from services.features.video.job_common import ( model_from_spec, resolve_job_local_model_id, + spec_pass_shape, spec_risk_allowance, - spec_unmeasured_bet, ) from services.generation_interrupt import GenerationCancelledError, is_cancel_exception +from services.generation_queue.sessions import JobSession from services.generation_queue.types import ExecutionOutcome, OutputAllocation, OutputPlan from services.records import CapabilityFailedError, GenerationRecord @@ -44,7 +47,11 @@ class ReservedVideoGenerator(Protocol): def models_dir(self) -> Path: ... def validate_local_a2v_request( - self, params: AudioToVideoParams, audio_duration_ms: int + self, + params: AudioToVideoParams, + audio_duration_ms: int, + *, + pass_shape: PassShape, ) -> None: ... def generate_local_reserved( @@ -57,8 +64,8 @@ def generate_local_reserved( a2v_num_frames: int | None = None, a2v_audio_duration_seconds: float | None = None, local_model_id: LTXLocalModelId, - risk_allowance: bool | None = None, - unmeasured_bet: bool = False, + allowance: RiskAllowance | None = None, + pass_shape: PassShape | None = None, ) -> GenerateVideoResponse: ... @@ -102,6 +109,7 @@ def execute( self, generation: GenerationRecord, outputs: tuple[OutputAllocation, ...], + session: JobSession, ) -> ExecutionOutcome: params = self._params(generation) output = require_video_output(outputs) @@ -118,8 +126,8 @@ def execute( output_path=Path(output.dest_path), prompt_wrap=self._prompt_wrap, local_model_id=local_model_id, - risk_allowance=spec_risk_allowance(generation.spec), - unmeasured_bet=spec_unmeasured_bet(generation.spec), + allowance=spec_risk_allowance(generation.spec), + pass_shape=spec_pass_shape(generation.spec), ) except Exception as exc: if is_cancel_exception(exc): @@ -160,6 +168,8 @@ def offering_payload_from_params( params: BaseModel, ) -> tuple[dict[str, object], OfferingId]: payload = params.model_dump(mode="python") + # Queue-only: executors read the stored `_passShape`, and the request model forbids extras. + payload.pop("passShape", None) raw_model = payload["model"] if not isinstance(raw_model, str) or raw_model not in OFFERING_IDS: raise HTTPError(422, "INVALID_VIDEO_GENERATION_SPEC") diff --git a/backend/services/generation_interrupt.py b/backend/services/generation_interrupt.py index 4a1e47c60..f683335af 100644 --- a/backend/services/generation_interrupt.py +++ b/backend/services/generation_interrupt.py @@ -38,6 +38,11 @@ def is_requested() -> bool: return _cancel.is_set() +def wait_requested(timeout: float) -> bool: + """Sleep up to ``timeout`` seconds. Wakes at once when a cancel is requested.""" + return _cancel.wait(timeout) + + def raise_if_requested() -> None: if _cancel.is_set(): raise GenerationCancelledError() diff --git a/backend/services/generation_queue/control.py b/backend/services/generation_queue/control.py index a2fed9bf7..ad19c44ed 100644 --- a/backend/services/generation_queue/control.py +++ b/backend/services/generation_queue/control.py @@ -1,17 +1,30 @@ from __future__ import annotations -from collections.abc import Callable +from collections.abc import Callable, Collection from contextlib import AbstractContextManager from threading import Event +from dataclasses import dataclass from typing import Protocol +from api_types import ApiActivityStatus, QueueProgress from services.store import Store from services.records import GenerationRecord +@dataclass(frozen=True) +class QueueLiveState: + """What the queue knows about a running job that the database does not.""" + + progress: QueueProgress | None + api_status: ApiActivityStatus | None + # A cancel stops the job. False for a provider job that is billed once it runs. + cancellable: bool + + class QueueControl(Protocol): def wake(self) -> None: ... def interrupt(self, generation_id: str, attempt_count: int) -> None: ... + def live_state(self, generation_id: str) -> QueueLiveState | None: ... class SharedGenerationSlot(Protocol): @@ -41,13 +54,21 @@ def wake(self) -> None: def interrupt(self, generation_id: str, attempt_count: int) -> None: del generation_id, attempt_count + def live_state(self, generation_id: str) -> QueueLiveState | None: + del generation_id + return None + def cancel_queued_generation( db: Store, generation_id: str, interrupt: Callable[[str, int], None], + *, + uncancellable_lanes: Collection[str] = (), ) -> GenerationRecord: - generation = db.request_generation_cancellation(generation_id) + generation = db.request_generation_cancellation( + generation_id, uncancellable_lanes=uncancellable_lanes + ) if generation.status == "cancelling": interrupt(generation.id, generation.attempt_count) return generation diff --git a/backend/services/generation_queue/dispatcher.py b/backend/services/generation_queue/dispatcher.py new file mode 100644 index 000000000..ef12ccfd7 --- /dev/null +++ b/backend/services/generation_queue/dispatcher.py @@ -0,0 +1,106 @@ +"""One facade over the per-lane runners. + +The rest of the app sees a single queue: start, stop, wake, interrupt. Each lane +has its own runner, so a job in one lane never waits for a job in another. +""" + +from __future__ import annotations + +import logging +import time +from collections.abc import Callable, Sequence + +from api_types import QueueProgress +from services.generation_queue.control import QueueLiveState +from services.generation_queue.runner import QueueRunner +from services.storage_info.storage_info import DriveType + +logger = logging.getLogger(__name__) + + +class QueueDispatcher: + def __init__( + self, + runners: Sequence[QueueRunner], + *, + checkpoint_drive_type: DriveType | None = None, + stop_join_timeout_seconds: float = 600.0, + ) -> None: + if not runners: + raise ValueError("a dispatcher needs at least one lane runner") + self._runners = tuple(runners) + self._stop_join_timeout_seconds = stop_join_timeout_seconds + self._checkpoint_drive_type = checkpoint_drive_type + self._finished_listener: Callable[[str], None] | None = None + + def start(self) -> None: + for runner in self._runners: + runner.start() + + def stop(self) -> None: + # Signal every lane first, so the lanes stop together against one deadline. + for runner in self._runners: + runner.request_stop() + deadline = time.monotonic() + self._stop_join_timeout_seconds + for runner in self._runners: + runner.join(deadline) + + def wake(self) -> None: + for runner in self._runners: + runner.wake() + + def interrupt(self, generation_id: str, attempt_count: int) -> None: + """Stop one running attempt. Only the lane that runs it acts.""" + for runner in self._runners: + if runner.owns(generation_id, attempt_count): + runner.interrupt(generation_id, attempt_count) + return + + def lane_is_idle(self, lane_id: str) -> bool: + """True when the lane has no running job and no queued row. False when unsure.""" + for runner in self._runners: + if runner.lane.id == lane_id: + try: + return runner.is_idle() + except Exception: + # False keeps a caller from using a lane it could not prove idle. + logger.warning( + "Could not read idle state for lane %s", lane_id, exc_info=True + ) + return False + return True + + def live_state(self, generation_id: str) -> QueueLiveState | None: + """Progress, provider status and cancel support of a running job, read from its lane.""" + for runner in self._runners: + session = runner.session_for(generation_id) + if session is not None: + progress = session.progress() + return QueueLiveState( + progress=None + if progress is None + else QueueProgress( + phase=progress.phase, + progress=progress.progress, + currentStep=progress.current_step, + totalSteps=progress.total_steps, + remainingSeconds=progress.remaining_seconds, + ), + api_status=session.api_status(), + cancellable=runner.lane.cancellable_while_running, + ) + return None + + def set_finished_listener(self, listener: Callable[[str], None] | None) -> None: + self._finished_listener = listener + for runner in self._runners: + runner.set_finished_listener(listener) + + def set_checkpoint_drive_type(self, drive_type: DriveType | None) -> None: + self._checkpoint_drive_type = drive_type + for runner in self._runners: + runner.set_checkpoint_drive_type(drive_type) + + @property + def is_running(self) -> bool: + return any(runner.is_running for runner in self._runners) diff --git a/backend/services/generation_queue/lane_sessions.py b/backend/services/generation_queue/lane_sessions.py new file mode 100644 index 000000000..6dda103f1 --- /dev/null +++ b/backend/services/generation_queue/lane_sessions.py @@ -0,0 +1,112 @@ +"""The session of a job on a lane that runs beside the local GPU lane. + +All of its state is its own: progress, provider status and the cancel flag. It never +touches the process-wide generation state, so two lanes cannot read each other's job. +""" + +from __future__ import annotations + +import logging +import threading +from collections.abc import Callable + +from api_types import ApiActivityStatus +from services.generation_interrupt import GenerationCancelledError +from services.generation_queue.sessions import JobProgress + +logger = logging.getLogger(__name__) + +# Stores the provider job id of an attempt: (generation_id, attempt_count, provider_job_id). +# Returns False when that attempt is no longer running, so the id was not stored. +ProviderJobIdSink = Callable[[str, int, str], bool] + + +class LaneJobSession: + def __init__( + self, + generation_id: str, + attempt_count: int, + record_provider_job_id: ProviderJobIdSink, + ) -> None: + self._generation_id = generation_id + self._attempt_count = attempt_count + self._record_provider_job_id = record_provider_job_id + self._lock = threading.Lock() + self._progress: JobProgress | None = None + self._api_status: ApiActivityStatus | None = None + self._cancelled = threading.Event() + + @property + def generation_id(self) -> str: + return self._generation_id + + @property + def holds_gpu_slot(self) -> bool: + return False + + def start_api(self) -> None: + return None + + def set_progress( + self, + phase: str, + progress: int, + current_step: int | None = None, + total_steps: int | None = None, + ) -> None: + with self._lock: + self._progress = JobProgress(phase, progress, current_step, total_steps) + + def set_api_status(self, status: ApiActivityStatus) -> None: + with self._lock: + self._api_status = status + + def set_provider_job_id(self, provider_job_id: str) -> bool: + logger.info( + "Generation %s accepted by its provider as job %s", self._generation_id, provider_job_id + ) + # A store failure must not fail the job: the provider already runs it. The caller + # learns from the result and can cancel at the provider. + try: + stored = self._record_provider_job_id( + self._generation_id, self._attempt_count, provider_job_id + ) + except Exception: + logger.error( + "Could not store provider job %s of generation %s", + provider_job_id, + self._generation_id, + exc_info=True, + ) + return False + if not stored: + logger.warning( + "Provider job %s of generation %s was not stored: the job is no longer running", + provider_job_id, + self._generation_id, + ) + return stored + + def progress(self) -> JobProgress | None: + with self._lock: + return self._progress + + def api_status(self) -> ApiActivityStatus | None: + with self._lock: + return self._api_status + + def raise_if_cancelled(self) -> None: + if self._cancelled.is_set(): + raise GenerationCancelledError() + + def wait_cancelled(self, timeout: float) -> bool: + return self._cancelled.wait(timeout) + + def cancel(self) -> None: + self._cancelled.set() + + def complete(self, result: str | list[str] | None) -> None: + del result + + def fail(self, error: str) -> None: + del error diff --git a/backend/services/generation_queue/lane_slots.py b/backend/services/generation_queue/lane_slots.py new file mode 100644 index 000000000..010790be2 --- /dev/null +++ b/backend/services/generation_queue/lane_slots.py @@ -0,0 +1,44 @@ +"""Capacity slot for a lane that does not hold the GPU.""" + +from __future__ import annotations + +from collections.abc import Iterator +from contextlib import contextmanager +from threading import Condition, Event + +from services.generation_queue.control import GenerationSlotWaitAborted + +# shutdown is an Event, not the Condition; waiters must re-check it after a bounded wait. +_WAIT_POLL_SECONDS = 0.05 + + +class CountingLaneSlot: + """Up to ``capacity`` jobs hold the slot at once. No global state, no GPU.""" + + def __init__(self, capacity: int) -> None: + if capacity < 1: + raise ValueError("a lane slot needs a capacity of at least 1") + self._capacity = capacity + self._held = 0 + self._condition = Condition() + + @contextmanager + def wait_for_generation_slot(self, shutdown: Event) -> Iterator[None]: + with self._condition: + while self._held >= self._capacity: + if shutdown.is_set(): + raise GenerationSlotWaitAborted() + self._condition.wait(timeout=_WAIT_POLL_SECONDS) + if shutdown.is_set(): + raise GenerationSlotWaitAborted() + self._held += 1 + try: + yield + finally: + with self._condition: + self._held -= 1 + self._condition.notify() + + def cancel_generation(self) -> object: + """A lane job is stopped through its own session. The slot has nothing to stop.""" + return None diff --git a/backend/services/generation_queue/lanes.py b/backend/services/generation_queue/lanes.py new file mode 100644 index 000000000..db68b440a --- /dev/null +++ b/backend/services/generation_queue/lanes.py @@ -0,0 +1,90 @@ +"""Execution lanes: capacity pools that run queued generations side by side. + +A lane is keyed by resource or provider, never by feature. Jobs in one lane run +in queue order, up to the lane's concurrency. Jobs in different lanes never wait +for each other. The lane of a job is computed once, when the job is inserted. + +Invariant: every executor runs correctly on the local lane. A lane that is not +registered (an old row, a removed provider, or parallel lanes turned off) falls back to local. + +The local lane and the fal lane are registered. Another provider lane adds one LaneSpec. +""" + +from __future__ import annotations + +from collections.abc import Callable, Iterable, Mapping +from dataclasses import dataclass + +from services.records import LOCAL_LANE + +LaneId = str + +FAL_LANE: LaneId = "fal" + + +@dataclass(frozen=True) +class LaneSpec: + id: LaneId + # Jobs of this lane that run at the same time. + concurrency: int + # The lane holds the GPU. Only a GPU lane evicts GPU caches and samples GPU hardware. + uses_gpu: bool + # A running job can be stopped. False for a provider job that is billed once started. + cancellable_while_running: bool + # Seconds a stopping app waits for a running job. None waits as long as the caller allows. + stop_grace_seconds: float | None = None + # Asks the provider to drop a job that was running when the app stopped. Gets the + # provider job id. Best effort and safe to repeat. None for a lane with no provider. + cancel_orphan: Callable[[str], None] | None = None + + def __post_init__(self) -> None: + if self.concurrency < 1: + raise ValueError(f"lane {self.id} needs a concurrency of at least 1") + + +LOCAL_LANE_SPEC = LaneSpec( + id=LOCAL_LANE, + concurrency=1, + uses_gpu=True, + cancellable_while_running=True, +) + +# One fal queue request per job. A cancel frees the lane at once. The provider cancel +# callback needs the fal client, so AppHandler adds it with dataclasses.replace. +FAL_LANE_SPEC = LaneSpec( + id=FAL_LANE, + concurrency=1, + uses_gpu=False, + cancellable_while_running=True, + stop_grace_seconds=5.0, +) + + +class LaneRegistry: + def __init__(self, lanes: Iterable[LaneSpec] = (LOCAL_LANE_SPEC,)) -> None: + by_id = {lane.id: lane for lane in lanes} + if LOCAL_LANE not in by_id: + raise ValueError("the local lane must be registered") + self._lanes: Mapping[LaneId, LaneSpec] = by_id + + @property + def lanes(self) -> tuple[LaneSpec, ...]: + return tuple(self._lanes.values()) + + @property + def ids(self) -> tuple[LaneId, ...]: + return tuple(self._lanes) + + @property + def uncancellable_ids(self) -> tuple[LaneId, ...]: + """Lanes whose running job a cancel cannot stop.""" + return tuple( + lane.id for lane in self._lanes.values() if not lane.cancellable_while_running + ) + + def spec(self, lane_id: LaneId) -> LaneSpec | None: + return self._lanes.get(lane_id) + + def resolve(self, lane_id: LaneId) -> LaneId: + """The lane a job runs on: its own when registered, else local.""" + return lane_id if lane_id in self._lanes else LOCAL_LANE diff --git a/backend/services/generation_queue/orphans.py b/backend/services/generation_queue/orphans.py new file mode 100644 index 000000000..fbda535a9 --- /dev/null +++ b/backend/services/generation_queue/orphans.py @@ -0,0 +1,106 @@ +"""Drop jobs that may still run at a provider. + +A job at a provider has its own id there, and the provider can bill it. The store keeps that id +on the row of a job that failed or was cancelled, until a cancel at the provider succeeds. +The lane of the job knows how to cancel it (LaneSpec.cancel_orphan). + +Two callers use this module: + +- The runner, right after a job of a provider lane failed or was cancelled. +- The boot, for every row that still holds an id. + +A cancel that fails, or a process that stops first, leaves the id on the row. The next boot +tries again. A lane with no callback, or a lane that is not registered, is skipped and its +rows keep their id. +""" + +from __future__ import annotations + +import logging +import threading +from collections.abc import Callable, Sequence + +from services.generation_queue.lanes import LaneSpec +from services.records import ProviderOrphan +from services.store import Store + +logger = logging.getLogger(__name__) + +# Finds the lane spec of a lane id. None when the lane is not registered. +SpecFor = Callable[[str], LaneSpec | None] +# Called with an orphan the provider dropped, to forget its id. +OnCancelled = Callable[[ProviderOrphan], None] + + +def forget_in(db: Store) -> OnCancelled: + """An OnCancelled that clears the stored id of the orphan.""" + + def forget(orphan: ProviderOrphan) -> None: + db.clear_provider_job_id(orphan.generation_id, orphan.provider_job_id) + + return forget + + +def cancel_provider_orphans( + orphans: Sequence[ProviderOrphan], spec_for: SpecFor, on_cancelled: OnCancelled +) -> int: + """Ask each lane to cancel its orphans, one by one. Returns how many calls succeeded. + + Best effort: a failure is logged and never stops the others. The callback must be + safe to repeat and must bound its own network time. + """ + cancelled = 0 + for orphan in orphans: + spec = spec_for(orphan.lane) + if spec is None or spec.cancel_orphan is None: + logger.warning( + "Provider job %s of generation %s cannot be cancelled: lane %s has no cancel. " + "The id stays on the row.", + orphan.provider_job_id, + orphan.generation_id, + orphan.lane, + ) + continue + logger.info( + "Cancelling provider job %s of generation %s (lane %s)", + orphan.provider_job_id, + orphan.generation_id, + orphan.lane, + ) + try: + spec.cancel_orphan(orphan.provider_job_id) + except Exception: + logger.warning( + "Could not cancel provider job %s of generation %s", + orphan.provider_job_id, + orphan.generation_id, + exc_info=True, + ) + continue + cancelled += 1 + try: + on_cancelled(orphan) + except Exception: + logger.warning( + "Provider job %s of generation %s was cancelled but its id was not cleared", + orphan.provider_job_id, + orphan.generation_id, + exc_info=True, + ) + return cancelled + + +def cancel_provider_orphans_in_background( + orphans: Sequence[ProviderOrphan], spec_for: SpecFor, on_cancelled: OnCancelled +) -> threading.Thread | None: + """Run cancel_provider_orphans on a daemon thread, so a slow provider never holds a worker.""" + if not orphans: + return None + thread = threading.Thread( + target=cancel_provider_orphans, + args=(tuple(orphans), spec_for, on_cancelled), + name="provider-orphan-cancel", + daemon=True, + ) + thread.start() + return thread diff --git a/backend/services/generation_queue/registry.py b/backend/services/generation_queue/registry.py index 5ebe32ba8..8ccba0ee1 100644 --- a/backend/services/generation_queue/registry.py +++ b/backend/services/generation_queue/registry.py @@ -2,12 +2,22 @@ from collections.abc import Mapping -from services.generation_queue.types import GenerationExecutor +from services.generation_queue.lanes import LOCAL_LANE, LaneId, LaneRegistry +from services.generation_queue.types import GenerationExecutor, LaneAwareExecutor class ExecutorRegistry: - def __init__(self, executors: Mapping[str, GenerationExecutor]) -> None: + def __init__( + self, + executors: Mapping[str, GenerationExecutor], + lanes: LaneRegistry | None = None, + ) -> None: self._executors = dict(executors) + self._lanes = lanes if lanes is not None else LaneRegistry() + + @property + def lanes(self) -> LaneRegistry: + return self._lanes def get(self, feature: str) -> GenerationExecutor: executor = self._executors.get(feature) @@ -19,3 +29,9 @@ def validate_params( self, feature: str, spec: Mapping[str, object], *, contract_version: int ) -> None: self.get(feature).validate_params(spec, contract_version=contract_version) + + def lane_for(self, feature: str, spec: Mapping[str, object]) -> LaneId: + """The lane a new job of this feature runs on. Local unless the executor says otherwise.""" + executor = self.get(feature) + lane = executor.lane_for(spec) if isinstance(executor, LaneAwareExecutor) else LOCAL_LANE + return self._lanes.resolve(lane) diff --git a/backend/services/generation_queue/runner.py b/backend/services/generation_queue/runner.py index d03827ca1..a307d4efa 100644 --- a/backend/services/generation_queue/runner.py +++ b/backend/services/generation_queue/runner.py @@ -1,6 +1,7 @@ from __future__ import annotations import logging +import time from collections.abc import Callable from dataclasses import dataclass from pathlib import Path @@ -15,6 +16,7 @@ GenerationRecord, MarkSucceededError, OutputSpec, + ProviderOrphan, StatusError, UnavailableError, ) @@ -32,8 +34,11 @@ GenerationSlotWaitAborted, SharedGenerationSlot, ) +from services.generation_queue.lanes import LOCAL_LANE_SPEC, LaneSpec +from services.generation_queue.orphans import cancel_provider_orphans_in_background, forget_in from services.generation_queue.output_names import output_asset_name from services.generation_queue.registry import ExecutorRegistry +from services.generation_queue.sessions import JobSession, SlotCancelSession from services.generation_queue.types import ExecutionOutcome, OutputAllocation from services.generation_interrupt import is_cancel_exception from services.gpu_info.gpu_info import GpuInfo @@ -53,6 +58,7 @@ # the log; anything else keeps the branch default. _LTX_INVALID_API_KEY_CODE: GenerationErrorCode = "LTX_INVALID_API_KEY" _LTX_API_PROMPT_EMBEDDING_FAILED_CODE: GenerationErrorCode = "LTX_API_PROMPT_EMBEDDING_FAILED" +_IMAGE_BLOCKED_CODE: GenerationErrorCode = "IMAGE_BLOCKED_BY_SAFETY_CHECKER" def _error_code_for(exc: BaseException, default: GenerationErrorCode) -> GenerationErrorCode: @@ -83,6 +89,8 @@ def _capability_error_code(exc: CapabilityFailedError) -> GenerationErrorCode: return _LTX_INVALID_API_KEY_CODE if exc.code == _LTX_API_PROMPT_EMBEDDING_FAILED_CODE: return _LTX_API_PROMPT_EMBEDDING_FAILED_CODE + if exc.code == _IMAGE_BLOCKED_CODE: + return _IMAGE_BLOCKED_CODE if exc.code in BUDGET_MISS_CODES: return _JOB_TOO_LARGE_CODE return _CAPABILITY_FAILURE_CODE @@ -99,15 +107,20 @@ def _http_budget_error_code(exc: HTTPError) -> GenerationErrorCode: class _ActiveGeneration: generation_id: str attempt_count: int + session: JobSession class QueueRunner: + """Runs the queued jobs of one lane, up to the lane's concurrency.""" + def __init__( self, *, db: Store, generation: SharedGenerationSlot, executors: ExecutorRegistry, + lane: LaneSpec = LOCAL_LANE_SPEC, + session_factory: Callable[[GenerationRecord], JobSession] | None = None, analytics: AnalyticsService | None = None, enhancement_policy: Callable[[GenerationRecord], QueuedEnhancement] | None = None, gpu_info: GpuInfo | None = None, @@ -117,6 +130,8 @@ def __init__( ) -> None: self._db = db self._generation = generation + self._lane = lane + self._session_factory = session_factory self._executors = executors self._analytics = analytics self._enhancement_policy = enhancement_policy @@ -128,8 +143,8 @@ def __init__( self._shutdown = Event() self._wake_event = Event() self._lifecycle_lock = Lock() - self._thread: Thread | None = None - self._active: _ActiveGeneration | None = None + self._threads: list[Thread] = [] + self._active: dict[tuple[str, int], _ActiveGeneration] = {} self._finished_listener: Callable[[str], None] | None = None def set_finished_listener(self, listener: Callable[[str], None] | None) -> None: @@ -141,50 +156,91 @@ def set_checkpoint_drive_type(self, drive_type: DriveType | None) -> None: def start(self) -> None: try: - self._db.has_queued() + self._db.has_queued(self._lane.id) except UnavailableError: return with self._lifecycle_lock: - if self._thread is not None and self._thread.is_alive(): + if any(thread.is_alive() for thread in self._threads): return self._shutdown.clear() self._wake_event.clear() - self._thread = Thread( - target=self._run, - name="generation-queue-runner", - daemon=True, - ) - self._thread.start() + self._threads = [ + Thread( + target=self._run, + name=f"generation-queue-{self._lane.id}-{index}", + daemon=True, + ) + for index in range(self._lane.concurrency) + ] + for thread in self._threads: + thread.start() - def stop(self) -> None: + def request_stop(self) -> None: + """Tell the workers to stop. Does not wait for them. + + A lane with a stop grace runs provider jobs that a stopping app cannot wait for. They + are cancelled now, so each one frees its provider request inside the grace time. + """ with self._lifecycle_lock: - thread = self._thread - if thread is None: + if not self._threads: return self._shutdown.set() self._wake_event.set() + sessions = ( + [active.session for active in self._active.values()] + if self._lane.stop_grace_seconds is not None + else [] + ) + for session in sessions: + try: + session.cancel() + except Exception: + logger.warning("Could not cancel a running job at stop", exc_info=True) - if thread is not current_thread(): - thread.join(timeout=self._stop_join_timeout_seconds) + def join(self, deadline: float) -> None: + """Wait for the workers until the monotonic deadline. + A lane with a stop grace waits at most that long, so a slow provider call does + not hold up shutdown. + """ with self._lifecycle_lock: - if self._thread is thread and not thread.is_alive(): - self._thread = None + threads = list(self._threads) + if self._lane.stop_grace_seconds is not None: + deadline = min(deadline, time.monotonic() + self._lane.stop_grace_seconds) + for thread in threads: + if thread is not current_thread(): + thread.join(timeout=max(0.0, deadline - time.monotonic())) + with self._lifecycle_lock: + if self._threads == threads and not any(t.is_alive() for t in threads): + self._threads = [] + + def stop(self) -> None: + self.request_stop() + self.join(time.monotonic() + self._stop_join_timeout_seconds) def wake(self) -> None: self._wake_event.set() + def owns(self, generation_id: str, attempt_count: int) -> bool: + with self._lifecycle_lock: + return (generation_id, attempt_count) in self._active + + def session_for(self, generation_id: str) -> JobSession | None: + with self._lifecycle_lock: + for (active_id, _), active in self._active.items(): + if active_id == generation_id: + return active.session + return None + def interrupt(self, generation_id: str, attempt_count: int) -> None: + # The lock stays held while the session cancels. The worker needs it to leave the + # active set, so the generation slot is not freed before the cancel returns. with self._lifecycle_lock: - active = self._active - if ( - active is None - or active.generation_id != generation_id - or active.attempt_count != attempt_count - ): + active = self._active.get((generation_id, attempt_count)) + if active is None: return try: - self._generation.cancel_generation() + active.session.cancel() except Exception as exc: logger.warning( "Generation %s attempt %s interrupt failed: %s", @@ -193,17 +249,29 @@ def interrupt(self, generation_id: str, attempt_count: int) -> None: exc, ) + def is_idle(self) -> bool: + """No job runs and none waits in this lane. + + Takes no runner lock: a cancel holds the runner lock while it takes the state lock. The + GPU lease calls it before it takes the state lock, because it reads SQLite. + """ + return not self._active and not self._db.has_queued(self._lane.id) + @property def is_running(self) -> bool: with self._lifecycle_lock: - return self._thread is not None and self._thread.is_alive() + return any(thread.is_alive() for thread in self._threads) + + @property + def lane(self) -> LaneSpec: + return self._lane def _run(self) -> None: while True: if self._shutdown.is_set(): return try: - if not self._db.has_queued(): + if not self._db.has_queued(self._lane.id): self._wake_event.wait(timeout=self._idle_wait_seconds) self._wake_event.clear() continue @@ -214,10 +282,19 @@ def _run(self) -> None: if self._shutdown.is_set(): return continue + job, session = claimed + started = time.monotonic() try: - self._process(claimed) + self._process(job, session) + self._release_provider_job(job) finally: - self._clear_active(claimed) + self._clear_active(job) + logger.info( + "Generation %s left lane %s after %.1fs", + job.id, + self._lane.id, + time.monotonic() - started, + ) except GenerationSlotWaitAborted: return except Exception as exc: @@ -225,17 +302,71 @@ def _run(self) -> None: if self._shutdown.wait(timeout=self._idle_wait_seconds): return - def _claim_and_register_active(self) -> GenerationRecord | None: + def _release_provider_job(self, job: GenerationRecord) -> None: + """Ask the provider to drop the jobs of this generation that nobody runs any more. + + These are the job of an attempt that failed or was cancelled, and the ids of older + attempts that a retry replaced (a retry can land before this runs). The provider can + still run them. The executor only stops waiting. The call runs on its own thread, so a + slow provider never holds this worker. An id stays stored until the call succeeds, so a + failed call is tried again at the next boot. + """ + if self._lane.cancel_orphan is None: + return + try: + orphans = [ + orphan + for orphan in self._db.list_displaced_provider_jobs(job.id) + if orphan.lane == self._lane.id + ] + latest = self._db.get_generation(job.id) + except Exception as exc: + log_background_exception(_BACKGROUND_TASK_NAME, exc) + return + if ( + latest is not None + and latest.attempt_count == job.attempt_count + and latest.status in {"failed", "cancelled"} + and latest.provider_job_id + ): + orphans.append( + ProviderOrphan( + generation_id=latest.id, + lane=self._lane.id, + provider_job_id=latest.provider_job_id, + ) + ) + if not orphans: + return + cancel_provider_orphans_in_background( + orphans, lambda _lane_id: self._lane, forget_in(self._db) + ) + + def _new_session(self, generation: GenerationRecord) -> JobSession: + if self._session_factory is not None: + return self._session_factory(generation) + return SlotCancelSession(self._generation, generation.id) + + def _claim_and_register_active(self) -> tuple[GenerationRecord, JobSession] | None: if self._shutdown.is_set(): return None - claimed = self._db.claim_next_queued() + claimed = self._db.claim_next_queued(self._lane.id) if claimed is None: return None + session = self._new_session(claimed) with self._lifecycle_lock: - self._active = _ActiveGeneration( + self._active[(claimed.id, claimed.attempt_count)] = _ActiveGeneration( generation_id=claimed.id, attempt_count=claimed.attempt_count, + session=session, ) + # request_stop only sees jobs registered before it took this lock. A job that + # registers after it must be cancelled here, or it would run past the stop. + stopped_while_claiming = ( + self._shutdown.is_set() and self._lane.stop_grace_seconds is not None + ) + if stopped_while_claiming: + session.cancel() try: latest = self._db.get_generation(claimed.id) except Exception as exc: @@ -254,9 +385,16 @@ def _claim_and_register_active(self) -> GenerationRecord | None: self._clear_active(claimed) return None self._send_generation_started(latest) - return claimed + logger.info( + "Generation %s (%s) started on lane %s, attempt %s", + claimed.id, + claimed.feature, + self._lane.id, + claimed.attempt_count, + ) + return claimed, session - def _process(self, claimed: GenerationRecord) -> None: + def _process(self, claimed: GenerationRecord, session: JobSession) -> None: allocations: list[OutputAllocation] = [] partial_paths: list[str] = [] try: @@ -284,14 +422,15 @@ def _process(self, claimed: GenerationRecord) -> None: # Best-effort: a reclaim failure must never fail the job it was # trying to save. try: - diffusion_stage_cache.evict() + if self._lane.uses_gpu: + diffusion_stage_cache.evict() except Exception: logger.warning( "Generation %s reclaim before execute failed; continuing", claimed.id, exc_info=True, ) - outcome = executor.execute(claimed, tuple(allocations)) + outcome = executor.execute(claimed, tuple(allocations), session) allocations = [ allocation for allocation in allocations @@ -496,7 +635,7 @@ def _snapshot_hardware(self) -> QueuedHardwareSnapshot | None: anything unexpected degrades the whole snapshot. Telemetry never breaks generation. """ - if self._gpu_info is None: + if self._gpu_info is None or not self._lane.uses_gpu: return None try: return QueuedHardwareSnapshot( @@ -534,7 +673,11 @@ def _send_generation_ended( return try: modes: QueuedExecutionModes | None = ( - {"load_mode": summary.load_mode, "offload_mode": summary.offload_mode} + { + "load_mode": summary.load_mode, + "offload_mode": summary.offload_mode, + "prompt_rewrite": summary.prompt_rewrite, + } if summary is not None else None ) @@ -563,9 +706,4 @@ def _send_generation_ended( def _clear_active(self, generation: GenerationRecord) -> None: with self._lifecycle_lock: - if ( - self._active is not None - and self._active.generation_id == generation.id - and self._active.attempt_count == generation.attempt_count - ): - self._active = None + self._active.pop((generation.id, generation.attempt_count), None) diff --git a/backend/services/generation_queue/sessions.py b/backend/services/generation_queue/sessions.py new file mode 100644 index 000000000..b5a1b489a --- /dev/null +++ b/backend/services/generation_queue/sessions.py @@ -0,0 +1,240 @@ +"""Per-job view of a running queued generation. + +An executor reports progress, checks for cancellation and records the end state +through its JobSession. It never reaches for process-wide state. The local lane +maps a session onto GenerationHandler (the shared GPU slot, one global job). A +lane that runs beside it keeps its own state per job (see lane_sessions.py). +""" + +from __future__ import annotations + +import time +from dataclasses import dataclass +from typing import Protocol + +from api_types import ApiActivityStatus, GenerationProgressResponse +from services import generation_interrupt +from services.generation_queue.control import SharedGenerationSlot + + +@dataclass(frozen=True) +class JobProgress: + phase: str + progress: int + current_step: int | None + total_steps: int | None + remaining_seconds: int | None = None + + +class JobSession(Protocol): + @property + def generation_id(self) -> str: ... + + @property + def holds_gpu_slot(self) -> bool: + """True when this job holds the shared GPU slot, so it can use the GPU without a lease.""" + ... + + def start_api(self) -> None: + """Mark the job as running on a provider API (no GPU).""" + ... + + def set_progress( + self, + phase: str, + progress: int, + current_step: int | None = None, + total_steps: int | None = None, + ) -> None: ... + + def set_api_status(self, status: ApiActivityStatus) -> None: ... + + def set_provider_job_id(self, provider_job_id: str) -> bool: + """Record the id of this job at its provider, right after the provider accepts it. + + The queue stores it, so a job left running at app stop can be cancelled at boot. + Never raises for a store failure. Returns False when a store failed to keep the id. Boot + cannot then cancel the job, so the executor must cancel it at the provider itself. A + session with no store has nothing to keep and returns True: the job goes on. + """ + ... + + def progress(self) -> JobProgress | None: + """The live progress of this job, for the queue panel. None before the first report.""" + ... + + def api_status(self) -> ApiActivityStatus | None: + """What the provider reports for this job. None for a job that has no provider.""" + ... + + def raise_if_cancelled(self) -> None: ... + + def wait_cancelled(self, timeout: float) -> bool: + """Sleep up to ``timeout`` seconds. Return True as soon as the job is cancelled.""" + ... + + def cancel(self) -> None: + """Ask this job to stop. Called by the queue, not by the executor. + + It must return at once and do no network I/O: the queue calls it while it holds the + lane lock. A provider is asked to drop the job after the executor returns, with + LaneSpec.cancel_orphan. + """ + ... + + def complete(self, result: str | list[str] | None) -> None: ... + + def fail(self, error: str) -> None: ... + + +class LocalGenerationOps(Protocol): + """The GenerationHandler methods a local-lane session calls.""" + + def start_api_generation(self, generation_id: str) -> None: ... + + def get_generation_progress(self) -> GenerationProgressResponse: ... + + def update_progress( + self, + phase: str, + progress: int, + current_step: int | None = None, + total_steps: int | None = None, + ) -> None: ... + + def raise_if_cancelled(self) -> None: ... + + def is_generation_cancelled(self) -> bool: ... + + def cancel_generation(self) -> object: ... + + def complete_generation(self, result: str | list[str] | None = None) -> None: ... + + def fail_generation(self, error: str) -> None: ... + + +class LocalJobSession: + """A session on the shared generation slot: GenerationHandler holds the one global job.""" + + def __init__(self, generation: LocalGenerationOps, generation_id: str) -> None: + self._generation = generation + self._generation_id = generation_id + + @property + def generation_id(self) -> str: + return self._generation_id + + @property + def holds_gpu_slot(self) -> bool: + return True + + def start_api(self) -> None: + self._generation.start_api_generation(self._generation_id) + + def set_progress( + self, + phase: str, + progress: int, + current_step: int | None = None, + total_steps: int | None = None, + ) -> None: + self._generation.update_progress(phase, progress, current_step, total_steps) + + def set_api_status(self, status: ApiActivityStatus) -> None: + del status + + def set_provider_job_id(self, provider_job_id: str) -> bool: + # The local lane keeps no provider ids and has no boot cancel. A fal job on this lane + # (the kill switch) loses only that recovery: the job itself goes on. + del provider_job_id + return True + + def progress(self) -> JobProgress | None: + # The global slot holds one job. Report its progress only while it is this one. + state = self._generation.get_generation_progress() + if state.id != self._generation_id: + return None + return JobProgress( + phase=state.phase, + progress=state.progress, + current_step=state.currentStep, + total_steps=state.totalSteps, + remaining_seconds=state.remainingSeconds, + ) + + def api_status(self) -> ApiActivityStatus | None: + return None + + def raise_if_cancelled(self) -> None: + self._generation.raise_if_cancelled() + + def wait_cancelled(self, timeout: float) -> bool: + # The interrupt Event is the cancel signal of the running job (see raise_if_cancelled). + # The generation state is not: it stays "cancelled" after the slot is released. + return generation_interrupt.wait_requested(timeout) + + def cancel(self) -> None: + self._generation.cancel_generation() + + def complete(self, result: str | list[str] | None) -> None: + self._generation.complete_generation(result) + + def fail(self, error: str) -> None: + self._generation.fail_generation(error) + + +class SlotCancelSession: + """The session of a lane whose only control is its slot: cancel goes to the slot.""" + + def __init__(self, slot: SharedGenerationSlot, generation_id: str) -> None: + self._slot = slot + self._generation_id = generation_id + + @property + def generation_id(self) -> str: + return self._generation_id + + @property + def holds_gpu_slot(self) -> bool: + return False + + def start_api(self) -> None: + return None + + def set_progress( + self, + phase: str, + progress: int, + current_step: int | None = None, + total_steps: int | None = None, + ) -> None: + del phase, progress, current_step, total_steps + + def set_api_status(self, status: ApiActivityStatus) -> None: + del status + + def set_provider_job_id(self, provider_job_id: str) -> bool: + del provider_job_id + return False + + def progress(self) -> JobProgress | None: + return None + + def api_status(self) -> ApiActivityStatus | None: + return None + + def raise_if_cancelled(self) -> None: + return None + + def wait_cancelled(self, timeout: float) -> bool: + time.sleep(timeout) + return False + + def cancel(self) -> None: + self._slot.cancel_generation() + + def complete(self, result: str | list[str] | None) -> None: + del result + + def fail(self, error: str) -> None: + del error diff --git a/backend/services/generation_queue/types.py b/backend/services/generation_queue/types.py index 0bc692225..a7b18542f 100644 --- a/backend/services/generation_queue/types.py +++ b/backend/services/generation_queue/types.py @@ -2,9 +2,10 @@ from collections.abc import Mapping from dataclasses import dataclass -from typing import Protocol +from typing import Protocol, runtime_checkable -from api_types import MediaKind, PipelineOffloadMode, VideoLoadMode +from api_types import MediaKind, PipelineOffloadMode, PromptRewriteSource, VideoLoadMode +from services.generation_queue.sessions import JobSession from services.records import GenerationRecord @@ -38,6 +39,9 @@ class ExecutionOutcome: written_prompt: str | None = None load_mode: VideoLoadMode | None = None offload_mode: PipelineOffloadMode | None = None + # Who rewrote the prompt, when a rewrite ran. None means none ran or the executor + # does not report it. + prompt_rewrite: PromptRewriteSource | None = None class GenerationExecutor(Protocol): @@ -51,4 +55,15 @@ def execute( self, generation: GenerationRecord, outputs: tuple[OutputAllocation, ...], + session: JobSession, ) -> ExecutionOutcome | None: ... + + +@runtime_checkable +class LaneAwareExecutor(Protocol): + """An executor that picks the lane its jobs run on. Others run on the local lane. + + A pure function of the stored spec. The queue computes it once, at insert. + """ + + def lane_for(self, spec: Mapping[str, object]) -> str: ... diff --git a/backend/services/generation_stats_sql.py b/backend/services/generation_stats_sql.py index 33f80a383..419795b3f 100644 --- a/backend/services/generation_stats_sql.py +++ b/backend/services/generation_stats_sql.py @@ -1,12 +1,13 @@ """The generation stats projection. JSON paths for the dashboard live here. fps is null unless the JSON value is a number, so a string like "24" cannot -pass for a real frame rate. +pass for a real frame rate. The dashboard measures video, so image runs are left out. """ from __future__ import annotations from services.features.ic_lora_recipes import queued_ic_lora_recipes +from services.features.image.feature_id import FEATURE as TEXT_TO_IMAGE_FEATURE _IC_LORA_IDS = ", ".join( f"'{recipe.recipe_id}'" for recipe in queued_ic_lora_recipes() @@ -38,6 +39,7 @@ {_IC_LORA_GROUP}WHEN feature IN ( 'text-to-video', 'image-to-video', + 'keyframes', 'audio-to-video', 'retake', 'extend' @@ -71,6 +73,7 @@ deleted_at IS NOT NULL AS is_deleted FROM generations WHERE status IN ('succeeded', 'failed', 'cancelled') + AND feature != '{TEXT_TO_IMAGE_FEATURE}' ) """ diff --git a/backend/services/gpu_info/gpu_info.py b/backend/services/gpu_info/gpu_info.py index dab82abe1..1ab65c96b 100644 --- a/backend/services/gpu_info/gpu_info.py +++ b/backend/services/gpu_info/gpu_info.py @@ -4,6 +4,8 @@ from typing import Protocol, TypedDict +from runtime_config.device_calibration import RunMemoryBaseline, RunMemoryEnd + class GpuTelemetryPayload(TypedDict): name: str @@ -67,3 +69,14 @@ def get_mps_pool_bytes(self) -> int | None: Fail-None probe: Mac-profiled callers fail closed to unsupported. Sampled live per call — never frozen into config. """ + + def get_swap_used_bytes(self) -> int | None: + """Swap in use (pagefile on Windows), or None when unknowable.""" + + def begin_run_memory_watch(self) -> RunMemoryBaseline: + """Sample free, reserved, and swap, and start the run peak. Fail-None per field.""" + ... + + def end_run_memory_watch(self) -> RunMemoryEnd: + """Close the run peak and sample swap. Fail-None per field.""" + ... diff --git a/backend/services/gpu_info/gpu_info_impl.py b/backend/services/gpu_info/gpu_info_impl.py index fa83507ab..e6f677f5c 100644 --- a/backend/services/gpu_info/gpu_info_impl.py +++ b/backend/services/gpu_info/gpu_info_impl.py @@ -12,6 +12,8 @@ import psutil import torch +from runtime_config.device_calibration import RunMemoryBaseline, RunMemoryEnd +from services.gpu_info import run_peak from services.gpu_info.gpu_info import GpuTelemetryPayload logger = logging.getLogger(__name__) @@ -256,3 +258,27 @@ def get_mps_pool_bytes(self) -> int | None: except Exception: logger.debug("MPS pool probe failed; Mac callers fail closed", exc_info=True) return None + + def get_swap_used_bytes(self) -> int | None: + try: + return int(psutil.swap_memory().used) + except Exception: + logger.debug("swap probe failed; the run is not recorded", exc_info=True) + return None + + def begin_run_memory_watch(self) -> RunMemoryBaseline: + baseline = RunMemoryBaseline( + free_vram_bytes=self.get_free_cuda_vram_bytes(), + reserved_bytes=self.get_cuda_reserved_bytes(), + swap_used_bytes=self.get_swap_used_bytes(), + ) + run_peak.begin_run() + return baseline + + def end_run_memory_watch(self) -> RunMemoryEnd: + peak_reserved, min_free = run_peak.end_run() + return RunMemoryEnd( + peak_reserved_bytes=peak_reserved, + min_free_vram_bytes=min_free, + swap_used_bytes=self.get_swap_used_bytes(), + ) diff --git a/backend/services/gpu_info/run_peak.py b/backend/services/gpu_info/run_peak.py new file mode 100644 index 000000000..ce3cf7053 --- /dev/null +++ b/backend/services/gpu_info/run_peak.py @@ -0,0 +1,105 @@ +"""Whole-run CUDA reserved peak and lowest free VRAM, across per-phase peak resets. + +Phase logs, the IC-LoRA pipeline, and the heartbeat each reset torch's peak +counter so their own lines read one phase. Device calibration needs the peak +of the whole run, so every reset goes through ``fold_and_reset_cuda_peak``, +which folds the phase peak into the run first. Process-wide: one GPU job runs +at a time. +""" + +from __future__ import annotations + +import logging +from threading import Lock + +import torch + +logger = logging.getLogger(__name__) + + +class _RunWatch: + def __init__(self) -> None: + self.lock = Lock() + self.active = False + self.peak_reserved_bytes: int | None = None + self.min_free_bytes: int | None = None + + def fold_peak(self, peak: int | None) -> None: + if not self.active or peak is None: + return + current = self.peak_reserved_bytes + self.peak_reserved_bytes = peak if current is None else max(current, peak) + + def fold_free(self, free: int | None) -> None: + if not self.active or free is None: + return + current = self.min_free_bytes + self.min_free_bytes = free if current is None else min(current, free) + + +_watch = _RunWatch() + + +def _cuda_ready() -> bool: + try: + return bool(torch.cuda.is_available()) + except Exception: + return False + + +def _max_reserved(device: torch.device | None) -> int | None: + if not _cuda_ready(): + return None + try: + return int(torch.cuda.max_memory_reserved(device)) + except Exception: + logger.debug("run peak read failed", exc_info=True) + return None + + +def _reset_peak(device: torch.device | None) -> None: + if not _cuda_ready(): + return + try: + torch.cuda.reset_peak_memory_stats(device) + except Exception: + logger.debug("peak reset failed", exc_info=True) + + +def _free_now() -> int | None: + if not _cuda_ready(): + return None + try: + return int(torch.cuda.mem_get_info()[0]) + except Exception: + logger.debug("free VRAM read failed", exc_info=True) + return None + + +def begin_run() -> None: + with _watch.lock: + _watch.active = True + _watch.peak_reserved_bytes = None + _watch.min_free_bytes = None + _reset_peak(None) + + +def fold_and_reset_cuda_peak(device: torch.device | None = None) -> None: + with _watch.lock: + _watch.fold_peak(_max_reserved(device)) + _reset_peak(device) + + +def note_free_sample(free_bytes: int) -> None: + with _watch.lock: + _watch.fold_free(free_bytes) + + +def end_run() -> tuple[int | None, int | None]: + """(peak reserved, lowest free) over the run; None for a probe that never read.""" + with _watch.lock: + _watch.fold_peak(_max_reserved(None)) + _watch.fold_free(_free_now()) + result = (_watch.peak_reserved_bytes, _watch.min_free_bytes) + _watch.active = False + return result diff --git a/backend/services/http_client/__init__.py b/backend/services/http_client/__init__.py index c9ba9d710..86096c14b 100644 --- a/backend/services/http_client/__init__.py +++ b/backend/services/http_client/__init__.py @@ -1,3 +1,15 @@ -from services.http_client.http_client import HTTPClient, HttpResponseLike, HttpTransportError +from services.http_client.http_client import ( + HTTPClient, + HttpBodyTooLargeError, + HttpRedirectRefusedError, + HttpResponseLike, + HttpTransportError, +) -__all__ = ["HTTPClient", "HttpResponseLike", "HttpTransportError"] +__all__ = [ + "HTTPClient", + "HttpBodyTooLargeError", + "HttpRedirectRefusedError", + "HttpResponseLike", + "HttpTransportError", +] diff --git a/backend/services/http_client/http_client.py b/backend/services/http_client/http_client.py index 67e4ea23a..c56af5cba 100644 --- a/backend/services/http_client/http_client.py +++ b/backend/services/http_client/http_client.py @@ -13,6 +13,14 @@ class HttpTransportError(Exception): connection reset, or broken chunked stream) — the request didn't complete.""" +class HttpBodyTooLargeError(Exception): + """Raised by a capped GET when the response body is larger than the allowed size.""" + + +class HttpRedirectRefusedError(Exception): + """Raised by a capped GET when a redirect changes the scheme to an unsafe one or loops (CWE-918).""" + + class HttpResponseLike(Protocol): @property def status_code(self) -> int: @@ -50,7 +58,13 @@ def get( url: str, headers: dict[str, str] | None = None, timeout: int = 30, + max_bytes: int | None = None, ) -> HttpResponseLike: + """With max_bytes, a body larger than that raises HttpBodyTooLargeError (CWE-770). + + A capped GET follows at most 3 redirects, never from https to another scheme, sends + ``headers`` only to the first host, and gives up when ``timeout`` seconds pass in total. + """ ... def put( diff --git a/backend/services/http_client/http_client_impl.py b/backend/services/http_client/http_client_impl.py index df129656f..0ad80feeb 100644 --- a/backend/services/http_client/http_client_impl.py +++ b/backend/services/http_client/http_client_impl.py @@ -2,12 +2,20 @@ from __future__ import annotations +import json import logging +import time from collections.abc import Mapping +from dataclasses import dataclass +from urllib.parse import urljoin, urlsplit import requests -from services.http_client.http_client import HttpTransportError +from services.http_client.http_client import ( + HttpBodyTooLargeError, + HttpRedirectRefusedError, + HttpTransportError, +) from services.services_utils import JSONValue, RequestData logger = logging.getLogger(__name__) @@ -22,6 +30,82 @@ ) +_STREAM_CHUNK_BYTES = 64 * 1024 +_MAX_REDIRECTS = 3 +# A stalled read ends after this long at most, so the download overruns its deadline by no more. +_MAX_READ_STALL_SECONDS = 10 + + +@dataclass(frozen=True) +class _BufferedResponse: + """A response whose body was read under a size cap.""" + + status_code: int + headers: Mapping[str, str] + content: bytes + + @property + def text(self) -> str: + return self.content.decode("utf-8", errors="replace") + + def json(self) -> object: + return json.loads(self.content) + + +def _redirect_target(url: str, location: str) -> str: + """The next URL of a redirect. A redirect may keep the scheme or upgrade to https, never downgrade.""" + target = urljoin(url, location) + scheme = urlsplit(target).scheme + if scheme != "https" and scheme != urlsplit(url).scheme: + raise HttpRedirectRefusedError("Redirect to a different scheme") + return target + + +def _get_capped( + url: str, headers: dict[str, str] | None, timeout: int, max_bytes: int +) -> _BufferedResponse: + """Read the body in chunks and stop at max_bytes, so a huge body never fills memory. + + ``timeout`` is the total time for every hop and read together (CWE-770). Each hop gets the + time left, and a read that stalls ends after ``_MAX_READ_STALL_SECONDS`` at most, so the + call overruns the deadline by that much and no more. Redirects are followed by hand, so each + hop is checked (CWE-918). + """ + deadline = time.monotonic() + timeout + first_host = urlsplit(url).netloc + for _ in range(_MAX_REDIRECTS + 1): + remaining = deadline - time.monotonic() + if remaining <= 0: + raise HttpTransportError(f"Download took longer than {timeout} seconds") + # A credential header goes only to the host the caller named. + hop_headers = headers if urlsplit(url).netloc == first_host else None + with requests.get( + url, + headers=hop_headers, + timeout=(remaining, min(remaining, _MAX_READ_STALL_SECONDS)), + stream=True, + allow_redirects=False, + ) as response: + location = response.headers.get("Location") + if response.is_redirect and location: + url = _redirect_target(url, location) + continue + declared = response.headers.get("Content-Length", "") + if declared.isdigit() and int(declared) > max_bytes: + raise HttpBodyTooLargeError(f"Response is larger than {max_bytes} bytes") + chunks: list[bytes] = [] + total = 0 + for chunk in response.iter_content(chunk_size=_STREAM_CHUNK_BYTES): + if time.monotonic() > deadline: + raise HttpTransportError(f"Download took longer than {timeout} seconds") + total += len(chunk) + if total > max_bytes: + raise HttpBodyTooLargeError(f"Response is larger than {max_bytes} bytes") + chunks.append(chunk) + return _BufferedResponse(response.status_code, response.headers, b"".join(chunks)) + raise HttpRedirectRefusedError(f"More than {_MAX_REDIRECTS} redirects") + + class HTTPClientImpl: """Wraps requests.* for external API calls.""" @@ -44,8 +128,11 @@ def get( url: str, headers: dict[str, str] | None = None, timeout: int = 30, - ) -> requests.Response: + max_bytes: int | None = None, + ) -> requests.Response | _BufferedResponse: try: + if max_bytes is not None: + return _get_capped(url, headers, timeout, max_bytes) return requests.get(url, headers=headers, timeout=timeout) except _TRANSPORT_ERRORS as exc: logger.error("HTTP GET failed (transport): %s", url, exc_info=True) diff --git a/backend/services/ic_lora_pipeline/ic_lora_inference.py b/backend/services/ic_lora_pipeline/ic_lora_inference.py index c528cd5bc..e2e580f46 100644 --- a/backend/services/ic_lora_pipeline/ic_lora_inference.py +++ b/backend/services/ic_lora_pipeline/ic_lora_inference.py @@ -11,12 +11,15 @@ from runtime_config.ic_lora_chunking import IC_LORA_CHUNK_CARRY_FRAMES from services.audio_channels import stereo_waveform -from services.ltx_pipeline_common import encode_video_output, video_chunks_number -from services.services_utils import AudioOrNone, AudioType, PipelineTilingType, TilingConfigType +from services.fast_video_pipeline.nag_config import NagConfig +from services.ltx_pipeline_common import encode_segments_output, video_chunks_number +from services.services_utils import AudioOrNone, PipelineTilingType, TilingConfigType if TYPE_CHECKING: from ltx_pipelines.chunks import ChunkConfig + from ltx_pipelines.utils.media_io import PlaybackSegment from ltx_pipelines.utils.types import ImageConditioningInput as LtxImageInput + from ltx_pipelines.utils.types import PipelineOutput logger = logging.getLogger(__name__) @@ -35,55 +38,54 @@ class PipelineKwargs(TypedDict): tiling_config: PipelineTilingType skip_stage_2: bool conditioning_attention_mask: torch.Tensor | None + nag: NagConfig | None @dataclass(frozen=True, slots=True) class InferenceResult: """What one IC-LoRA run hands to the encoder. - A chunked job streams: ``video`` (and ``audio``, when the model made it) are iterators - that run the windows while the caller reads them. The caller must encode inside the - denoising progress scope. ``audio_sampling_rate`` is set only for that streamed audio. - ``streams`` lists the generators behind a streamed run. Call ``close_streams`` when the - encode ends, also on failure or cancel, so the reference video is released. + ``segments`` is the ordered playback stream the encoder consumes. A chunked job streams: + the iterator runs the windows while the caller reads it, so the caller must encode inside + the denoising progress scope. ``streams`` lists the generators behind it. Call + ``close_streams`` when the encode ends, also on failure or cancel, so the reference video + is released. """ - video: torch.Tensor | Iterator[torch.Tensor] - audio: AudioOrNone | Iterator[AudioType] + segments: Iterator[PlaybackSegment] num_frames: int tiling_config: TilingConfigType | None - audio_sampling_rate: int | None = None streams: tuple[Iterator[object], ...] = () +def segments_from_output(output: PipelineOutput) -> Iterator[PlaybackSegment]: + """One-pass ``__call__`` output as playback segments: the complete track rides on the first.""" + from ltx_pipelines.utils.media_io import PlaybackSegment + + for index, video in enumerate(output.video): + yield PlaybackSegment(video=video, audio=output.audio if index == 0 else None) + + +def inference_result_from_output(output: PipelineOutput) -> InferenceResult: + segments = segments_from_output(output) + return InferenceResult(segments, output.num_frames, output.tiling_config, (segments,)) + + +def replace_segment_audio(segments: Iterator[PlaybackSegment], audio: AudioOrNone) -> Iterator[PlaybackSegment]: + """Swap the audio of a segment stream for one complete track (or none), carried by the first segment.""" + from ltx_pipelines.utils.media_io import PlaybackSegment + + for index, segment in enumerate(segments): + yield PlaybackSegment(video=segment.video, audio=audio if index == 0 else None) + + def close_streams(result: InferenceResult) -> None: - """Close the generators of a streamed run. A stream already finished closes cleanly.""" + """Close the generators of a run. A stream already finished closes cleanly.""" for stream in result.streams: if isinstance(stream, Generator): stream.close() -def encode_streamed_output( - video: torch.Tensor | Iterator[torch.Tensor], - audio: AudioOrNone | Iterator[AudioType], - audio_sampling_rate: int | None, - *, - fps: int, - output_path: str, -) -> None: - """Encode a chunked job. The windows are one video stream, like the upstream CLI.""" - from ltx_pipelines.utils.media_io import encode_video - - encode_video( - video=video, - fps=fps, - audio=audio, - output_path=output_path, - video_chunks_number=1, - audio_sampling_rate=audio_sampling_rate, - ) - - def plan_chunks( chunk_pixel_frames: int | None, *, @@ -132,7 +134,7 @@ def _load_source_audio(path: str, device: torch.device) -> AudioOrNone: return replace(src, waveform=waveform) -def resolve_output_audio( +def resolve_output_segments( result: InferenceResult, *, mute_audio: bool, @@ -140,19 +142,19 @@ def resolve_output_audio( num_frames: int, frame_rate: float, device: torch.device, -) -> tuple[AudioOrNone | Iterator[AudioType], int | None]: - """Audio and sample rate to encode. +) -> Iterator[PlaybackSegment]: + """Playback segments carrying the audio to encode. "off" drops it entirely; "source" muxes the input clip's soundtrack and discards the prompt-synthesized model audio; otherwise keep the generated audio. """ if mute_audio: - return None, None + return replace_segment_audio(result.segments, None) if source_audio_path is None: - return result.audio, result.audio_sampling_rate + return result.segments audio = _load_source_audio(source_audio_path, device) if audio is None: - return None, None + return replace_segment_audio(result.segments, None) v_dur = num_frames / frame_rate # Trim the source soundtrack to the generated video's length. A longer # source (e.g. an 8s clip rendered to 5s) would otherwise keep playing @@ -166,7 +168,7 @@ def resolve_output_audio( audio.sampling_rate, audio.waveform.shape[0], a_dur, v_dur, "" if abs(a_dur - v_dur) < 0.1 else " MISMATCH", ) - return audio, None + return replace_segment_audio(result.segments, audio) def encode_result( @@ -185,7 +187,7 @@ def encode_result( That releases the reference video, which a temp file delete needs on Windows. """ try: - audio, audio_rate = resolve_output_audio( + segments = resolve_output_segments( result, mute_audio=mute_audio, source_audio_path=source_audio_path, @@ -193,18 +195,12 @@ def encode_result( frame_rate=frame_rate, device=device, ) - # round(), not int(): avoids truncating e.g. 23.976 -> 23 (encode_video int()s again). - fps = round(frame_rate) - if streamed: - encode_streamed_output(result.video, audio, audio_rate, fps=fps, output_path=output_path) - else: - assert not isinstance(audio, Iterator) # a one-pass job never streams audio - encode_video_output( - video=result.video, - audio=audio, - fps=fps, - output_path=output_path, - video_chunks_number_value=video_chunks_number(result.num_frames, result.tiling_config), - ) + # round(), not int(): avoids truncating e.g. 23.976 -> 23. + encode_segments_output( + segments, + fps=round(frame_rate), + output_path=output_path, + video_chunks_number_value=None if streamed else video_chunks_number(result.num_frames, result.tiling_config), + ) finally: close_streams(result) diff --git a/backend/services/ic_lora_pipeline/ic_lora_pipeline.py b/backend/services/ic_lora_pipeline/ic_lora_pipeline.py index f5903ccd3..64a04b312 100644 --- a/backend/services/ic_lora_pipeline/ic_lora_pipeline.py +++ b/backend/services/ic_lora_pipeline/ic_lora_pipeline.py @@ -6,6 +6,7 @@ from api_types import ImageConditioningInput from runtime_config.ic_lora_tiling import IcLoraTiling +from services.fast_video_pipeline.nag_config import NagConfig if TYPE_CHECKING: import torch @@ -50,5 +51,6 @@ def generate( mute_audio: bool = False, conditioning_mask_path: str | None = None, chunk_pixel_frames: int | None = None, + nag: NagConfig | None = None, ) -> None: ... diff --git a/backend/services/ic_lora_pipeline/ltx_ic_lora_pipeline.py b/backend/services/ic_lora_pipeline/ltx_ic_lora_pipeline.py index 8314b86d6..a3590d3f2 100644 --- a/backend/services/ic_lora_pipeline/ltx_ic_lora_pipeline.py +++ b/backend/services/ic_lora_pipeline/ltx_ic_lora_pipeline.py @@ -18,11 +18,14 @@ from api_types import ImageConditioningInput from runtime_config.ic_lora_chunking import ic_lora_carry_frames -from runtime_config.ic_lora_tiling import IC_LORA_TILE_OVERLAP, IcLoraTiling +from runtime_config.ic_lora_tiling import IcLoraTiling +from services.fast_video_pipeline.nag_config import NagConfig +from services.gpu_info.run_peak import fold_and_reset_cuda_peak from services.ic_lora_pipeline.ic_lora_inference import ( InferenceResult, PipelineKwargs, encode_result, + inference_result_from_output, plan_chunks, ) from services.ltx_pipeline_common import ( @@ -31,6 +34,7 @@ is_decode_tile_shortage, resolve_cuda_decode_tiling_retry, resolve_tiling_config, + to_ltx_images, ) from services.services_utils import PipelineTilingType, TilingConfigType, device_supports_fp8 @@ -92,7 +96,7 @@ def __init__( stage_2_ic_lora: bool = False, tiling: IcLoraTiling | None = None, ) -> None: - from ltx_core.loader.primitives import LoraPathStrengthAndSDOps + from ltx_core.loader import LoraPathStrengthAndSDOps from ltx_core.loader.sd_ops import LTXV_LORA_COMFY_RENAMING_MAP from ltx_core.quantization.fp8_cast import build_policy as build_fp8_cast_policy from ltx_pipelines.ic_lora import DEFAULT_IC_LORA_STAGES @@ -168,11 +172,14 @@ def _tile_stage_1(self, stage_width: int, stage_height: int, tiling: IcLoraTilin from ltx_pipelines.ic_lora import spatial_tiled_ic_lora_stages tile_width, tile_height = tiling.tile_size(stage_width, stage_height) - logger.info("[ic-lora] tiled: %dx%d tiles on %dx%d", tile_width, tile_height, stage_width, stage_height) + logger.info( + "[ic-lora] tiled: %dx%d tiles on %dx%d, overlap %.2f", + tile_width, tile_height, stage_width, stage_height, tiling.overlap_fraction, + ) self.pipeline.stages = spatial_tiled_ic_lora_stages( tile_height=tile_height, tile_width=tile_width, - overlap_fraction=IC_LORA_TILE_OVERLAP, + overlap_fraction=tiling.overlap_fraction, apply_ic_lora=(True, False), ) @@ -254,11 +261,10 @@ def _run_inference( skip_stage_2: bool, conditioning_attention_mask: torch.Tensor | None, chunk_config: ChunkConfig | None = None, + nag: NagConfig | None = None, ) -> InferenceResult: """Run the pipeline. A chunked job streams: ``__call__`` would collect every decoded window on the GPU first.""" - from ltx_pipelines.utils.types import ImageConditioningInput as _LtxImageInput - kwargs = PipelineKwargs( prompt=prompt, seed=seed, @@ -266,23 +272,20 @@ def _run_inference( width=width, num_frames=num_frames, frame_rate=frame_rate, - images=[_LtxImageInput(img.path, img.frame_idx, img.strength) for img in images], + images=to_ltx_images(images), video_conditioning=video_conditioning, tiling_config=tiling_config, skip_stage_2=skip_stage_2, conditioning_attention_mask=conditioning_attention_mask, + nag=nag, ) if chunk_config is None: result = self.pipeline(**kwargs) - return InferenceResult(result.video, result.audio, result.num_frames, result.tiling_config) - from ltx_pipelines.chunks import split_decoded_chunks - + return inference_result_from_output(result) chunks, resolved_frames, resolved_tiling = self.pipeline.stream_chunks( **kwargs, chunk_config=chunk_config ) - video, audio, audio_sampling_rate = split_decoded_chunks(chunks) - streams = (video, chunks) if audio is None else (video, audio, chunks) - return InferenceResult(video, audio, resolved_frames, resolved_tiling, audio_sampling_rate, streams) + return InferenceResult(chunks, resolved_frames, resolved_tiling, (chunks,)) def _load_mask_tensor(self, path: str, num_frames: int) -> torch.Tensor: """Load an outpaint mask video as a (1, 1, F, H, W) float tensor in [0, 1]. @@ -324,6 +327,7 @@ def generate( mute_audio: bool = False, conditioning_mask_path: str | None = None, chunk_pixel_frames: int | None = None, + nag: NagConfig | None = None, ) -> None: if use_lora_in_stage_2: logger.warning("[ic-lora] use_lora_in_stage_2 is deprecated and ignored (LTXP-514)") @@ -379,7 +383,7 @@ def generate( cuda = torch.cuda.is_available() and self._device.type == "cuda" base_gb = 0.0 if cuda: - torch.cuda.reset_peak_memory_stats(self._device) + fold_and_reset_cuda_peak(self._device) base_gb = torch.cuda.memory_allocated(self._device) / 1e9 free_gb = torch.cuda.mem_get_info(self._device)[0] / 1e9 if free_gb < 3.0: @@ -406,6 +410,7 @@ def _attempt(tiling_config: PipelineTilingType) -> None: skip_stage_2=skip_stage_2, conditioning_attention_mask=conditioning_attention_mask, chunk_config=chunk_config, + nag=nag, ) encode_result( result, diff --git a/backend/services/ic_lora_pipeline/tiled_ic_lora_pipeline.py b/backend/services/ic_lora_pipeline/tiled_ic_lora_pipeline.py index 3edad5c4b..ce95ed54a 100644 --- a/backend/services/ic_lora_pipeline/tiled_ic_lora_pipeline.py +++ b/backend/services/ic_lora_pipeline/tiled_ic_lora_pipeline.py @@ -19,14 +19,19 @@ import logging +from typing import Any + from ltx_core.conditioning import ConditioningItem from ltx_core.model.video_vae import TileSizeConfig, VideoEncoder from ltx_core.types import VIDEO_SCALE_FACTORS from ltx_pipelines.chunks import Chunk, MakeVideoConditionings, SequentialVideoFrameSource from ltx_pipelines.ic_lora import ICLoraPipeline, ICLoraStageConfig, _ICLoraRunContext # pyright: ignore[reportPrivateUsage] -from ltx_pipelines.utils.helpers import combined_image_conditionings +from ltx_pipelines.utils.helpers import image_conditionings +from ltx_pipelines.utils.types import PipelineOutput from api_types import REFERENCE_STILL_FRAME_IDX +from services.fast_video_pipeline.nag_config import NagConfig +from services.fast_video_pipeline.nag_distilled import NagDistilledMixin logger = logging.getLogger(__name__) @@ -69,7 +74,11 @@ def encode_tiling_for_canvas( return reference_encode_tiling(encode_height, encode_width, num_frames) -class TiledICLoraPipeline(ICLoraPipeline): +class TiledICLoraPipeline(NagDistilledMixin[_ICLoraRunContext], ICLoraPipeline): + def __call__(self, *args: Any, nag: NagConfig | None = None, **kwargs: Any) -> PipelineOutput: + with self._nag_request(nag): + return super().__call__(*args, **kwargs) + def _video_conditionings( self, ctx: _ICLoraRunContext, @@ -127,7 +136,6 @@ def encode(enc: VideoEncoder) -> list[ConditioningItem]: chunk, images=frame_images, video_encoder=enc, - color_space=ctx.color_space, ), *reference_video_conditionings_for_chunk( chunk, @@ -141,16 +149,16 @@ def encode(enc: VideoEncoder) -> list[ConditioningItem]: encode_tiling=encode_tiling, color_space=ctx.color_space, ), - # frame_idx != 0 becomes a VideoConditionByKeyframeIndex. Its time - # offset puts a -1 still at [-1, 0) / fps, as a 1-frame token. - *combined_image_conditionings( + # A still at a negative index is an ImageGuide, so it becomes a + # VideoConditionByKeyframeIndex. Its time offset puts a -1 still at + # [-1, 0) / fps, as a 1-frame token. + *image_conditionings( images=stills, height=height, width=width, video_encoder=enc, dtype=dtype, device=device, - color_space=ctx.color_space, ), ] diff --git a/backend/services/ltx_pipeline_common.py b/backend/services/ltx_pipeline_common.py index 7899d27c9..e3ecb6268 100644 --- a/backend/services/ltx_pipeline_common.py +++ b/backend/services/ltx_pipeline_common.py @@ -2,25 +2,42 @@ from __future__ import annotations -from collections.abc import Iterator +from collections.abc import Iterator, Sequence import logging from typing import TYPE_CHECKING import torch from runtime_config.runtime_policy import CUDA_CPU_OFFLOAD_RAM_FLOOR_GB, should_disk_stream_cuda_weights -from services.services_utils import AudioOrNone, PipelineTilingType, TilingConfigType +from services.services_utils import PipelineTilingType, TilingConfigType from services.storage_info.storage_info import DriveType logger = logging.getLogger(__name__) if TYPE_CHECKING: + from api_types import ImageConditioningInput from ltx_core.components.guiders import MultiModalGuiderParams from ltx_core.model.video_vae.transformer.config import DiffVAEMode + from ltx_pipelines.utils.media_io import PlaybackSegment from ltx_pipelines.utils.model_paths import ModelPaths + from ltx_pipelines.utils.types import ImageConditioningInput as LtxImageInput from ltx_pipelines.utils.types import OffloadMode +def to_ltx_images(images: Sequence[ImageConditioningInput], *, guide_all: bool = False) -> list[LtxImageInput]: + """Desktop stills as ltx-pipelines inputs, with the CRF left to the checkpoint default. + + A still at frame 0 replaces that frame and a later one guides. A negative index (the + IC-LoRA reference token) is a guide. ``guide_all`` also guides frame 0, which multi-keyframe + interpolation needs so that the first still stays a keyframe instead of a replacement. + """ + from ltx_pipelines.utils.types import ImageConditioningInput as LtxImageInput + + if guide_all: + return [LtxImageInput.guide(img.path, img.frame_idx, img.strength) for img in images] + return [LtxImageInput.at(img.path, img.frame_idx, img.strength) for img in images] + + def auto_tiling_config() -> PipelineTilingType: """Let the pipeline derive decode tiling from the VAE it will decode with. @@ -212,17 +229,34 @@ def video_chunks_number(num_frames: int, tiling_config: TilingConfigType | None) return int(get_video_chunks_number(num_frames, tiling_config)) -def _disk_stream_reason(system: str, ram_gb: int | None) -> str: +def _disk_stream_reason( + system: str, ram_gb: int | None, cpu_ram_floor_gb: int | None +) -> str: if system == "Windows": - return "checkpoint volume is NVMe on Windows CUDA" + if cpu_ram_floor_gb is None: + return "checkpoint volume is NVMe on Windows CUDA (edit pipeline)" + if ram_gb is None: + return ( + "host RAM unknown on Windows CUDA NVMe; failing closed below the " + f"{cpu_ram_floor_gb} GiB CPU-streaming floor" + ) + return ( + f"host RAM {ram_gb} GiB on Windows CUDA NVMe is below the " + f"{cpu_ram_floor_gb} GiB CPU-streaming floor" + ) + floor_gb = ( + CUDA_CPU_OFFLOAD_RAM_FLOOR_GB + if cpu_ram_floor_gb is None + else cpu_ram_floor_gb + ) if ram_gb is None: return ( "host RAM unknown on Linux CUDA; failing closed below the " - f"{CUDA_CPU_OFFLOAD_RAM_FLOOR_GB} GiB pinned-CPU floor (LTX-Desktop#163)" + f"{floor_gb} GiB pinned-CPU floor (LTX-Desktop#163)" ) return ( f"host RAM {ram_gb} GiB on Linux CUDA is below the " - f"{CUDA_CPU_OFFLOAD_RAM_FLOOR_GB} GiB floor for pinned CPU streaming (LTX-Desktop#163)" + f"{floor_gb} GiB floor for pinned CPU streaming (LTX-Desktop#163)" ) @@ -233,6 +267,7 @@ def offload_mode_for_prefetch_count( drive_type: DriveType | None, system: str, ram_bytes: int | None, + cpu_ram_floor_gb: int | None = CUDA_CPU_OFFLOAD_RAM_FLOOR_GB, ) -> OffloadMode: """Translate the desktop's streaming_prefetch_count knob to ltx_pipelines' OffloadMode. @@ -241,18 +276,23 @@ def offload_mode_for_prefetch_count( CUDA streaming kind. Callers pass frozen startup facts — no platform or psutil reads inside, so the verdict is stable and trivially testable. - - CUDA: system RAM is separate from VRAM, so OffloadMode.CPU pins the blocks in host - RAM and streams them to the smaller VRAM — the fast streaming path. On Linux, - that pin is unswappable and needs ~36 GB host RAM; 32 GB machines (the advertised - local-gen floor) must use OffloadMode.DISK instead (LTX-Desktop#163). On Windows, - the checkpoint drive routes instead: NVMe maps ~70 GB per generation in ~20 s - (and commits ~5 GB host RAM against ~34 pinned), so NVMe streams from DISK while - SATA and unknown drives stay on CPU. + - CUDA: system RAM is separate from VRAM, so OffloadMode.CPU holds the blocks in host + RAM and streams them to the smaller VRAM — the fast streaming path when RAM fits. On + Linux, that buffer is page-locked (unswappable) and needs ~36 GB host RAM; 32 GB + machines (the advertised local-gen floor) must use OffloadMode.DISK instead + (LTX-Desktop#163). On Windows, non-NVMe and unknown drives stay on OffloadMode.CPU + (SATA takes ~130 s for ~70 GB of reads per generation). On Windows NVMe, ltx-core + 1.6.0 has no os.preadv and opens an unbuffered handle per 8 MiB chunk, making disk + streaming slower than CPU offload on Fast and IC-LoRA once RAM clears + ``cpu_ram_floor_gb`` (40 GB for Fast, 64 GB for IC-LoRA); below that floor (or when + ``cpu_ram_floor_gb`` is None, as on Edit where full-resolution stage-1 denoise hides + the reads and disk stays faster), NVMe streams from DISK. - MPS (Apple Silicon): CPU-pinned weights live in the *same* unified RAM as the GPU, so OffloadMode.CPU (which pins every block, ~46 GB for the bf16 transformer) OOMs. - OffloadMode.DISK mmaps blocks from the checkpoint through a small pinned buffer - (~5 GB), the only memory-safe streaming path on unified memory. This is the "mmap - streaming" the upstream MPS-support work validated on an M4 Pro. + OffloadMode.DISK reads blocks from the checkpoint with positional reads into block-sized + host buffers (2 plus the prefetch depth) and two 64 MiB staging buckets, all unpinned + on MPS, the only memory-safe streaming path on unified memory. Measurements taken + before ltx-core 1.6.0 describe the older mmap path. """ from ltx_pipelines.utils.types import OffloadMode @@ -261,26 +301,36 @@ def offload_mode_for_prefetch_count( if device.type == "mps": return OffloadMode.DISK if device.type == "cuda": - ram_gb = ram_bytes // (1024**3) if ram_bytes is not None else None - if should_disk_stream_cuda_weights(system, ram_gb, drive_type=drive_type): - logger.info("Using OffloadMode.DISK: %s", _disk_stream_reason(system, ram_gb)) + ram_gb = ( + (ram_bytes + 1024**3 - 1) // (1024**3) + if ram_bytes is not None + else None + ) + if should_disk_stream_cuda_weights( + system, + ram_gb, + drive_type=drive_type, + cpu_ram_floor_gb=cpu_ram_floor_gb, + ): + logger.info( + "Using OffloadMode.DISK: %s", + _disk_stream_reason(system, ram_gb, cpu_ram_floor_gb), + ) return OffloadMode.DISK return OffloadMode.CPU -def encode_video_output( - video: torch.Tensor | Iterator[torch.Tensor], - audio: AudioOrNone, +def encode_segments_output( + segments: Iterator[PlaybackSegment], fps: int, output_path: str, - video_chunks_number_value: int, + video_chunks_number_value: int | None, ) -> None: - from ltx_pipelines.utils.media_io import encode_video + from ltx_pipelines.utils.media_io import encode_media_segments - encode_video( - video=video, + encode_media_segments( + segments, fps=fps, - audio=audio, output_path=output_path, video_chunks_number=video_chunks_number_value, ) diff --git a/backend/services/migrations.py b/backend/services/migrations.py index e4401ed19..9314887eb 100644 --- a/backend/services/migrations.py +++ b/backend/services/migrations.py @@ -6,6 +6,18 @@ MIGRATIONS_DIR = Path(__file__).resolve().parent / "schema" +# Version 3 was also issued to the device calibration migration on some builds, so a store at +# version 3 can be missing what 0003_generation_lane.sql adds. Keep these in step with that file. +_GENERATION_LANE_COLUMNS = ( + ("lane", "ALTER TABLE generations ADD COLUMN lane TEXT NOT NULL DEFAULT 'local'"), + ("provider_job_id", "ALTER TABLE generations ADD COLUMN provider_job_id TEXT"), +) +_GENERATION_LANE_INDEX = """ +CREATE INDEX IF NOT EXISTS idx_generations_pending_lane_rank + ON generations(lane, queue_rank ASC, id ASC) + WHERE status = 'queued' AND deleted_at IS NULL +""" + def _sql_statements(script: str) -> list[str]: statements: list[str] = [] @@ -89,3 +101,25 @@ def apply_migrations(conn: sqlite3.Connection, migrations_dir: Path) -> None: if restore_foreign_keys: conn.execute("PRAGMA foreign_keys = ON") conn.isolation_level = previous_isolation + + +def repair_generation_lane(conn: sqlite3.Connection) -> None: + """Add the lane columns and index of 0003_generation_lane.sql where they are missing.""" + previous_isolation = conn.isolation_level + conn.isolation_level = None + try: + conn.execute("BEGIN IMMEDIATE") + try: + columns = { + str(row[1]) for row in conn.execute("PRAGMA table_info(generations)").fetchall() + } + for name, statement in _GENERATION_LANE_COLUMNS: + if name not in columns: + conn.execute(statement) + conn.execute(_GENERATION_LANE_INDEX) + conn.execute("COMMIT") + except Exception: + conn.execute("ROLLBACK") + raise + finally: + conn.isolation_level = previous_isolation diff --git a/backend/services/patches/diffusion_stage_cache.py b/backend/services/patches/diffusion_stage_cache.py index 00c15daf4..88f252e11 100644 --- a/backend/services/patches/diffusion_stage_cache.py +++ b/backend/services/patches/diffusion_stage_cache.py @@ -2,7 +2,7 @@ calls within one generation when nothing about its config actually changed. ``DiffusionStage`` "builds on each call, frees on exit" (ltx_pipelines/utils/ -blocks.py) unconditionally -- it rebuilds the transformer from the checkpoint +blocks/diffusion_stage.py) unconditionally -- it rebuilds the transformer from the checkpoint file (disk read + fp8 cast + H2D copy) on *every* call and tears it down (or ``.to("meta")`` + reclaim) on exit, regardless of whether the checkpoint/ LoRAs/quantization are identical to the previous call. For a two-stage @@ -22,13 +22,12 @@ Scoped to the standard (non-streaming, non-multi-GPU) build path: caching only applies when ``self._is_streaming`` is False (i.e. ``local_generations_mode == "full_models_loading"`` -- high-VRAM cards where holding one build resident is -affordable) AND the prepared builder is a plain ``SingleGPUModelBuilder``. +affordable) AND the prepared builder is a plain ``SimpleBuilder``. Streaming instances (the low-VRAM path) are untouched -- forcing residency there would defeat the point of streaming. Multi-GPU tiled builders are also excluded: they use ``video_tools`` to shard identically-shaped work across -devices, whereas ``SingleGPUModelBuilder.build()`` ignores all extra kwargs -(``**kwargs: object, # noqa: ARG002`` in single_gpu_model_builder.py) -- -confirmed inert for the path we cache, not assumed. +devices, whereas ``DiffusionStage._build_transformer`` drops ``video_tools`` for a +``SimpleBuilder`` -- confirmed inert for the path we cache, not assumed. GENERATION-SCOPED, not session-scoped (found live on an RTX 5090): letting the cache survive PAST the generation that built it collides with every other @@ -101,7 +100,7 @@ EXPERIMENTAL: depends on DiffusionStage's private ``_is_streaming``, ``_prepared_builder()``, ``_build_transformer()``, ``_quantization``, ``_compilation_config``, ``_dtype``, ``_device`` staying as-is, and on -``__call__`` continuing to route through ``_transformer_ctx`` -- re-verify +``__call__`` continuing to route through ``_transformer_ctx`` (1.6.0 verified) -- re-verify against ltx_pipelines.utils.blocks.DiffusionStage on rev bumps. Usage: @@ -119,7 +118,7 @@ from contextlib import contextmanager from ltx_core.devices import synchronize_device -from ltx_core.loader.single_gpu_model_builder import SingleGPUModelBuilder +from ltx_core.loader.simple_builder import SimpleBuilder from ltx_pipelines.utils.blocks import DiffusionStage from ltx_pipelines.utils.helpers import cleanup_memory @@ -171,9 +170,12 @@ def set_enabled(value: bool) -> None: def _cacheable(stage: DiffusionStage) -> bool: # Desktop constructs DiffusionStage with bare CompilationConfig() (capture=False, # mode=None) and never calls with_model_wrapper. A set _model_wrapper is an - # uncovered cache key — 1.3.0 through 1.4.1 apply it after _transformer_ctx yields. Skip the + # uncovered cache key — 1.3.0 through 1.6.0 apply it after _transformer_ctx yields. Skip the # cache (do not raise): a live generate must degrade to uncached, not crash. # python -O would also strip an assert here and silently reuse wrong weights. + # 1.6.0 adds DiffusionStage ``active_weights`` (a shared transformer allocation released by + # release_transformer). Desktop never passes it, so the cache does not read it. A Desktop + # path that adopts it must decide who owns the transformer lifetime first. if getattr(stage, "_model_wrapper", None) is not None: global _logged_wrapper_skip if not _logged_wrapper_skip: @@ -183,14 +185,14 @@ def _cacheable(stage: DiffusionStage) -> bool: ) _logged_wrapper_skip = True return False - return not stage._is_streaming and isinstance(stage._prepared_builder(), SingleGPUModelBuilder) # noqa: SLF001 + return not stage._is_streaming and isinstance(stage._prepared_builder(), SimpleBuilder) # noqa: SLF001 def _cache_key(stage: DiffusionStage) -> _CacheKey: builder = stage._prepared_builder() # noqa: SLF001 return ( - builder.model_path, - builder.model_sd_ops, + builder.paths, + builder.sd_ops, builder.module_ops, builder.loras, # Policy objects aren't structurally comparable; identity is safe here diff --git a/backend/services/patches/diffvae_decode_vram.py b/backend/services/patches/diffvae_decode_vram.py index a38f47ada..aab28b357 100644 --- a/backend/services/patches/diffvae_decode_vram.py +++ b/backend/services/patches/diffvae_decode_vram.py @@ -151,10 +151,23 @@ def _clamp_diffvae_tiles(tiling: Any, height: int, width: int, num_frames: int) ) -def _release_denoise_weights() -> None: +def _decoder_label(decoder: Any) -> str: + """Log name of the VAE this decoder loads: ``DiffVAE``, ``ConvVAE``, or ``video VAE`` when unknown.""" + checkpoint = getattr(decoder, "checkpoint_path", None) + if not isinstance(checkpoint, str): + checkpoint = getattr(decoder, "_checkpoint_path", None) + if not isinstance(checkpoint, str): + return "video VAE" + try: + return "DiffVAE" if is_diffusion_video_vae(checkpoint) else "ConvVAE" + except Exception: # noqa: BLE001 the label is for a log line only; it must never fail a generation + return "video VAE" + + +def _release_denoise_weights(decoder: Any) -> None: diffusion_stage_cache.evict() cleanup_memory() - logger.info("Freed resident transformer before DiffVAE decode") + logger.info("Freed resident transformer before %s decode", _decoder_label(decoder)) def _decode_budget_cap_bytes() -> int | None: @@ -341,7 +354,7 @@ def _dump_latent_for_replay(decoder: Any, args: tuple[Any, ...], kwargs: dict[st def _patched_video_decoder_call(self: VideoDecoder, *args: Any, **kwargs: Any) -> Any: - _release_denoise_weights() + _release_denoise_weights(self) args, kwargs = _with_post_evict_cuda_tiling(self, args, kwargs) args, kwargs = _with_mps_clamped_tiles(self, args, kwargs) _dump_latent_for_replay(self, args, kwargs) diff --git a/backend/services/patches/disk_streaming_pread.py b/backend/services/patches/disk_streaming_pread.py deleted file mode 100644 index 650db447b..000000000 --- a/backend/services/patches/disk_streaming_pread.py +++ /dev/null @@ -1,107 +0,0 @@ -"""Open disk-streaming checkpoints with safetensors' ``pread`` backend on Darwin. - -``DiskTensorReader`` keeps a ``safe_open`` handle and ``get_tensor``s each block -during every denoise step. With no ``backend`` argument that handle is mmap. -On Apple Silicon mmap is about half the throughput of ``pread`` and varies run -to run once the checkpoint no longer fits in the page cache -(https://github.com/Lightricks/LTX-2/issues/304). - -The same reader is the CUDA disk-streaming path (``OffloadMode.DISK``): Linux -hosts that cannot pin the transformer, and any other machine that streams -blocks from the checkpoint instead of keeping them resident. Pinned and -fully resident loads do not construct ``DiskTensorReader``. ``pread`` does -not shrink the allocation. It only changes the read. On Windows, safetensors -implements it with ``File::seek_read``. - -That Windows read is slower than mmap. Measured on an RTX 5090 / Samsung -9100 PRO NVMe, 63.45 GiB RAM, streamed T2V, DISK forced, Sage on, cold -process (same bytes, same allocation peak): - -- 720p/20s: mmap 232 s, pread 394.82 s (1.70x), 68.1 GiB read, alloc 14.15 GiB -- 1080p/10s: mmap 258 s, pread 420.11 s (1.63x), 74.6 GiB read, alloc 16.37 GiB - -Windows DISK-vs-CPU evidence was measured with mmap (DISK ~0.79x CPU). Under -pread, DISK is ~1.4x slower than that CPU control. Linux DISK is unmeasured, -and the MPS result does not transfer. ``install`` therefore no-ops unless -``sys.platform == "darwin"``. The reader never sees the consuming device, so -the platform check is the scoping we can implement. - -The issue's patch is ``SafetensorsStateDictLoader.load``. Desktop streaming does -not use that loader for the denoise loop, so this wraps ``DiskTensorReader`` -instead. - -Remove once ltx-core passes ``backend="pread"`` from ``DiskTensorReader`` on -Darwin only. An unconditional upstream ``pread`` would regress Windows. - -Usage: - import services.patches.disk_streaming_pread as disk_streaming_pread - disk_streaming_pread.install() -""" - -from __future__ import annotations - -import inspect -import logging -import sys -from typing import Any - -logger = logging.getLogger(__name__) - -_installed = False -_checked = False -_original_init: Any = None - - -def install() -> None: - """Use ``backend="pread"`` for disk-streaming opens on Darwin. Idempotent. - - No-op on every other platform. Does not log. This runs at import time, - before ``logging.basicConfig``, and an info record then is dropped. Call - ``log_status`` once logging exists. - """ - global _installed, _checked, _original_init - if _installed: - return - if sys.platform != "darwin": - _checked = True - return - - import safetensors # noqa: PLC0415 - - from ltx_core.block_streaming.disk import DiskTensorReader # noqa: PLC0415 - - if "backend" not in inspect.signature(safetensors.safe_open).parameters: - _checked = True - return - - _original_init = DiskTensorReader.__init__ - - def _init(self: DiskTensorReader, paths: list[str]) -> None: - original_open = safetensors.safe_open - - def _open(*args: Any, **kwargs: Any) -> Any: - kwargs.setdefault("backend", "pread") - return original_open(*args, **kwargs) - - safetensors.safe_open = _open # type: ignore[assignment] - try: - _original_init(self, paths) - finally: - safetensors.safe_open = original_open - - DiskTensorReader.__init__ = _init # type: ignore[method-assign] - _installed = True - _checked = True - - -def log_status() -> None: - """Report the disk-streaming read backend. Call after logging is configured.""" - if not _checked: - return - if _installed: - logger.info("Disk streaming opens safetensors with backend=pread") - return - if sys.platform != "darwin": - logger.info("Disk streaming keeps mmap; pread is Darwin-only") - return - logger.warning("safetensors.safe_open has no backend=; disk streaming stays on mmap") diff --git a/backend/services/patches/linux_disk_streaming_backend.py b/backend/services/patches/linux_disk_streaming_backend.py deleted file mode 100644 index 18e72f435..000000000 --- a/backend/services/patches/linux_disk_streaming_backend.py +++ /dev/null @@ -1,183 +0,0 @@ -"""Linux only: open disk-streaming checkpoints with ``pread`` when mmap would hit ENOMEM. - -``DiskTensorReader`` keeps a ``safe_open`` handle and ``get_tensor``s each block -during every denoise step (``OffloadMode.DISK``). With no ``backend`` argument -that handle is mmap. safetensors' torch mmap backend calls -``torch.UntypedStorage.from_file(shared=False)`` on the whole file. That is a -private writable mapping, so the kernel charges its full size against the commit -limit. With ``vm.overcommit_memory=0`` the kernel refuses any single mapping -larger than RAM + swap, and with ``=2`` any mapping above the free commit -headroom. A 46 GB checkpoint on a 32 GB / 11 GB-swap host fails with -``unable to mmap 46149345334 bytes ... Cannot allocate memory (12)`` -(https://github.com/Lightricks/LTX-Desktop/issues/163). ``pread`` never maps the -file, so it is not charged. - -``install`` uses ``pread`` only for a file the kernel would refuse. Every other -Linux open stays on mmap, because Linux DISK ``pread`` throughput is unmeasured. - -Isolation: this module is separate from ``disk_streaming_pread`` (the Darwin -patch) on purpose. ``install`` returns before it imports torch, safetensors or -ltx-core unless ``sys.platform`` starts with ``linux``. On macOS and Windows it -touches nothing, and ``disk_streaming_pread`` is the only patch on -``DiskTensorReader``. - -Override: ``LTX_LINUX_DISK_STREAM_BACKEND`` is ``auto`` (default, the rule -above), ``mmap`` (never ``pread``; the kernel refusal returns) or ``pread`` -(always ``pread``, to benchmark it). Set it where the app starts, for example -``LTX_LINUX_DISK_STREAM_BACKEND=pread ./LTX-Desktop``. Electron passes its -environment to the backend. - -Remove once safetensors maps read-only. - -Usage: - import services.patches.linux_disk_streaming_backend as linux_disk_streaming_backend - linux_disk_streaming_backend.install() -""" - -from __future__ import annotations - -import inspect -import logging -import os -import sys -from pathlib import Path -from typing import Any - -logger = logging.getLogger(__name__) - -ENV_BACKEND = "LTX_LINUX_DISK_STREAM_BACKEND" -_BACKEND_CHOICES = ("auto", "mmap", "pread") - -_PROC_OVERCOMMIT = Path("/proc/sys/vm/overcommit_memory") -_PROC_MEMINFO = Path("/proc/meminfo") - -_installed = False -_checked = False -_original_init: Any = None - - -def _is_linux() -> bool: - return sys.platform.startswith("linux") - - -def _read_meminfo_bytes() -> dict[str, int]: - """Parse ``/proc/meminfo`` into bytes. Every value there is in kB.""" - fields: dict[str, int] = {} - for line in _PROC_MEMINFO.read_text().splitlines(): - key, _, rest = line.partition(":") - value = rest.split() - if value: - fields[key] = int(value[0]) * 1024 - return fields - - -def mmap_would_be_refused(size_bytes: int) -> bool: - """Whether the kernel refuses a private writable mapping of ``size_bytes``. - - Mirrors ``__vm_enough_memory``: mode 0 refuses a mapping above RAM + swap, - mode 2 refuses one above ``CommitLimit - Committed_AS``, mode 1 never refuses. - When the policy cannot be read, answer False so the open keeps its current - mmap behaviour. - """ - try: - mode = int(_PROC_OVERCOMMIT.read_text()) - meminfo = _read_meminfo_bytes() - if mode == 1: - return False - if mode == 2: - return size_bytes > meminfo["CommitLimit"] - meminfo["Committed_AS"] - return size_bytes > meminfo["MemTotal"] + meminfo["SwapTotal"] - except (OSError, ValueError, KeyError): - return False - - -def _backend_choice() -> str: - """Read ``LTX_LINUX_DISK_STREAM_BACKEND``: ``auto`` (default), ``mmap`` or ``pread``. - - An unknown value warns and acts as ``auto``. It must not stop generation. - """ - raw = os.environ.get(ENV_BACKEND, "").strip().lower() - if raw == "": - return "auto" - if raw not in _BACKEND_CHOICES: - logger.warning( - "Ignoring %s=%r; expected one of %s. Using auto.", ENV_BACKEND, raw, ", ".join(_BACKEND_CHOICES) - ) - return "auto" - return raw - - -def _backend_for(path: str) -> str | None: - """The safetensors backend to force for ``path``, or None to keep the default.""" - choice = _backend_choice() - if choice == "mmap": - return None - if choice == "pread": - logger.info("Disk streaming opens %s with backend=pread: %s=pread", path, ENV_BACKEND) - return "pread" - size = os.path.getsize(path) - if mmap_would_be_refused(size): - logger.info( - "Disk streaming opens %s (%d bytes) with backend=pread: mmap would be refused " - "by vm.overcommit_memory", - path, - size, - ) - return "pread" - return None - - -def install() -> None: - """Choose the ``DiskTensorReader`` read backend on Linux. Idempotent. - - No-op on every other platform, before any heavy import. Does not log. This - runs at import time, before ``logging.basicConfig``, and an info record then - is dropped. Call ``log_status`` once logging exists. - """ - global _installed, _checked, _original_init - if _installed: - return - if not _is_linux(): - return - - import safetensors # noqa: PLC0415 - - from ltx_core.block_streaming.disk import DiskTensorReader # noqa: PLC0415 - - _checked = True - if "backend" not in inspect.signature(safetensors.safe_open).parameters: - return - - _original_init = DiskTensorReader.__init__ - - def _init(self: DiskTensorReader, paths: list[str]) -> None: - original_open = safetensors.safe_open - - def _open(path: Any, *args: Any, **kwargs: Any) -> Any: - backend = _backend_for(str(path)) - if backend is not None: - kwargs.setdefault("backend", backend) - return original_open(path, *args, **kwargs) - - safetensors.safe_open = _open # type: ignore[assignment] - try: - _original_init(self, paths) - finally: - safetensors.safe_open = original_open - - DiskTensorReader.__init__ = _init # type: ignore[method-assign] - _installed = True - - -def log_status() -> None: - """Report the Linux disk-streaming read backend. Call after logging is configured.""" - if not _checked: - return - if not _installed: - logger.warning("safetensors.safe_open has no backend=; Linux disk streaming stays on mmap") - return - choice = _backend_choice() - if choice == "auto": - logger.info("Linux disk streaming keeps mmap; pread only when the kernel would refuse the mapping") - else: - logger.info("Linux disk streaming backend forced by %s=%s", ENV_BACKEND, choice) diff --git a/backend/services/patches/mps_conv3d_as_conv2d.py b/backend/services/patches/mps_conv3d_as_conv2d.py new file mode 100644 index 000000000..ca596db4d --- /dev/null +++ b/backend/services/patches/mps_conv3d_as_conv2d.py @@ -0,0 +1,139 @@ +"""Run MPS ``nn.Conv3d`` as a sum of ``conv2d`` calls, one per temporal tap. + +The conv video VAE decoder (``ltx-2.5-video-vae-conv``, the Fast decode path) is +built from 3x3x3 ``CausalConv3d`` layers. On Apple Silicon, torch's MPS +``conv3d`` runs at a much lower throughput than ``conv2d`` on the same GPU. A +stride-1 Conv3d with no temporal padding is exactly the sum over its temporal +taps of a Conv2d on time-shifted frames batched into N, so the decoder can take +the conv2d path without changing its math. Decoded frames match stock at +rounding-noise level. ``performance_runner/bench_mps_conv3d.py`` measures the +speedup and the PSNR on the machine it runs on. + +MPS ``conv2d`` returns wrong values, with no error, when its weight or input is +a strided view (observed with torch 2.11): ``weight[:, :, i]``, or a channel +slice of the decoder's ``channels_last_3d`` workspace. Both are copied to a +dense layout before each call. Frames are processed in ~512 MiB chunks to bound +these copies, so peak MPS driver memory rises only a little. + +Any other Conv3d (non-MPS, stride, dilation, groups, temporal padding, +non-zero padding mode) runs the original ``forward``. + +EXPERIMENTAL, off by default. The speedup and the MPS ``conv2d`` behavior can +differ by chip, macOS version, and torch version, so the patch is gated behind +``AppSettings.mps_conv3d_as_conv2d_enabled`` (Settings, under Fast decode, +Apple Silicon only). It also requires Fast decode to be on. +``GenerationHandler.start_generation`` pushes the live setting into +:func:`set_enabled` on every generation. With the setting off, every Conv3d runs +the original ``forward``. + +Remove once torch MPS ``conv3d`` reaches ``conv2d`` throughput. + +Credit: found, implemented, and benchmarked by Sabbagh Fares (@Sabmit) in +https://github.com/Lightricks/LTX-Desktop/pull/189 + +Usage: + import services.patches.mps_conv3d_as_conv2d as mps_conv3d_as_conv2d + mps_conv3d_as_conv2d.install(enabled=False) + mps_conv3d_as_conv2d.set_enabled(True) +""" + +from __future__ import annotations + +import logging +import sys + +import torch +import torch.nn.functional as F +from torch import nn + +logger = logging.getLogger(__name__) + +# Input bytes per conv2d batch. Bounds the dense copies and the partial sums. +_CHUNK_BYTES = 512 * 2**20 + +_installed = False +_enabled = False +_original_forward = nn.Conv3d.forward + + +def _supported(conv: nn.Conv3d, x: torch.Tensor) -> bool: + return ( + x.device.type == "mps" + and x.dim() == 5 + and conv.stride == (1, 1, 1) + and conv.dilation == (1, 1, 1) + and conv.groups == 1 + and conv.padding_mode == "zeros" + and not isinstance(conv.padding, str) + and conv.padding[0] == 0 + and x.shape[2] >= conv.kernel_size[0] + ) + + +def _conv3d_as_conv2d(conv: nn.Conv3d, x: torch.Tensor) -> torch.Tensor: + weight = conv.weight + taps = [weight[:, :, tap].contiguous() for tap in range(weight.shape[2])] + batch, in_channels, in_frames, height, width = x.shape + out_frames = in_frames - len(taps) + 1 + kernel_height, kernel_width = conv.kernel_size[1], conv.kernel_size[2] + pad_height, pad_width = conv.padding[1], conv.padding[2] + out_height = height + 2 * pad_height - kernel_height + 1 + out_width = width + 2 * pad_width - kernel_width + 1 + memory_format = ( + torch.channels_last_3d if x.is_contiguous(memory_format=torch.channels_last_3d) else torch.contiguous_format + ) + out = torch.empty( + (batch, conv.out_channels, out_frames, out_height, out_width), + device=x.device, + dtype=x.dtype, + memory_format=memory_format, + ) + frames_per_chunk = max(1, _CHUNK_BYTES // (batch * in_channels * height * width * x.element_size())) + for start in range(0, out_frames, frames_per_chunk): + end = min(start + frames_per_chunk, out_frames) + chunk_frames = batch * (end - start) + + def tap_input(tap: int) -> torch.Tensor: + # Frames start+tap .. end+tap, batched into N and copied dense: MPS conv2d misreads strided views. + shifted = x[:, :, start + tap : end + tap].transpose(1, 2).reshape(chunk_frames, in_channels, height, width) + return shifted.contiguous(memory_format=torch.channels_last) + + total = F.conv2d(tap_input(0), taps[0], conv.bias, padding=(pad_height, pad_width)) + for tap in range(1, len(taps)): + total.add_(F.conv2d(tap_input(tap), taps[tap], padding=(pad_height, pad_width))) + out[:, :, start:end] = total.reshape(batch, end - start, conv.out_channels, out_height, out_width).transpose(1, 2) + return out + + +def _forward(self: nn.Conv3d, input: torch.Tensor) -> torch.Tensor: # noqa: A002 # torch's parameter name + if not _enabled or not _supported(self, input): + return _original_forward(self, input) + return _conv3d_as_conv2d(self, input) + + +def install(*, enabled: bool = True) -> None: + """Hook ``nn.Conv3d.forward`` on Darwin. Idempotent. No-op elsewhere. + + The hook runs the original ``forward`` until :func:`set_enabled` turns the + patch on. Does not log: this runs at import time, before logging is configured. + """ + global _installed + if sys.platform != "darwin": + return + if not _installed: + nn.Conv3d.forward = _forward # type: ignore[method-assign] + _installed = True + set_enabled(enabled) + + +def set_enabled(value: bool) -> None: + """Turn the per-tap conv2d path on or off. Takes effect on the next Conv3d call. + + Pushed from ``AppSettings.mps_conv3d_as_conv2d_enabled`` (and Fast decode) by + ``GenerationHandler.start_generation`` on every generation. No effect until + :func:`install` ran, and :func:`install` is a no-op off Darwin. + """ + global _enabled + if value != _enabled and _installed: + logger.info("MPS Conv3d per-tap conv2d %s", "enabled" if value else "disabled") + _enabled = value diff --git a/backend/services/patches/mps_transfer_sync.py b/backend/services/patches/mps_transfer_sync.py new file mode 100644 index 000000000..94d365f5e --- /dev/null +++ b/backend/services/patches/mps_transfer_sync.py @@ -0,0 +1,56 @@ +"""Monkey-patch: wait for queued GPU compute before each MPS weight transfer. + +ltx-core 1.6.0 streams transformer weights through ``MpsTransport.transfer`` +(``ltx_core/loader/streaming_transport.py``). A read-ahead worker stages the next units while the +consumer thread computes. Each transfer is ordered after earlier compute only through +``torch.mps.Event`` markers on MPS's single queue. ltx-core 1.5.0 had no read-ahead and no +host-blocking event wait on a worker thread. + +On an M4 Pro (48 GB), a 1080p stage 2 (about 32k video tokens, about 7 s per block) then stalled in +the first blocks of step 1. The worker blocked in ``torch.mps.Event.synchronize()``, the event never +signalled, and Metal ended a command buffer with ``kIOGPUCommandBufferCallbackErrorTimeout``. The +backend then hung until it was killed. 720p and stage 1 were not affected. An M5 Max (128 GB), which +runs a block in about 2.6 s, did not hit it. + +Measured on the M4 Pro (same case, same seed, ``mpsgraph_zc`` active, no swap growth): + +- No sync: fails at stage 2 block 385 to 389 (two runs). +- ``torch.mps.synchronize()`` only after the copy: fails at block 387. +- ``torch.mps.synchronize()`` before the copy, with or without one after it: stage 2 passes, at + about 320 s per step (1.5.0: 319 s). + +This patch adds the sync before the copy. Why a missing wait before the copy produces an event that +never signals is not proven. The measurements above are what the patch rests on. + +Only ``MpsTransport`` is patched. CUDA and CPU transports are untouched, so this is a no-op off Mac. + +Remove once ltx-core waits for queued MPS compute before a transfer, and a 1080p stage 2 passes on a +48 GB Mac without this patch. + +Usage: + import services.patches.mps_transfer_sync # noqa: F401 +""" + +from __future__ import annotations + +from collections.abc import Iterator +from contextlib import contextmanager +from typing import Any + +import torch +from ltx_core.loader import streaming_transport as _transport + +_orig_transfer = _transport.MpsTransport.transfer + + +@contextmanager +def _transfer_after_compute(self: Any, after: Any) -> Iterator[Any]: + """Like upstream ``MpsTransport.transfer``, but only after all queued MPS work has finished.""" + torch.mps.synchronize() + with _orig_transfer(self, after) as handle: + yield handle + + +if not hasattr(_orig_transfer, "__wrapped__"): + raise RuntimeError("MpsTransport.transfer is no longer a context manager function — patch needs updating.") +_transport.MpsTransport.transfer = _transfer_after_compute # type: ignore[method-assign] diff --git a/backend/services/patches/nag_cross_attention.py b/backend/services/patches/nag_cross_attention.py new file mode 100644 index 000000000..2a81a0e59 --- /dev/null +++ b/backend/services/patches/nag_cross_attention.py @@ -0,0 +1,185 @@ +"""Monkey-patch: Normalized Attention Guidance (NAG) on video text cross-attention. + +The distilled LTX models run unguided (CFG = 1), so a negative prompt has no +negative branch. NAG (Chen et al., 2025) guides inside the text cross-attention +instead: one extra K/V attention per layer, no second forward pass. + +For each guided layer, with ``s`` = scale, ``a`` = alpha, ``t`` = tau (KJNodes +``LTX2_NAG`` convention): + + Z~ = s * Z_pos - (s - 1) * Z_neg + r = ||Z~||_1 / ||Z_pos||_1 (L1 over the feature dim) + Z^ = Z~ * min(r, t) / r + out = a * Z^ + (1 - a) * Z_pos + +``Z_pos`` and ``Z_neg`` share one query. They are the attention outputs after +``V`` and before ``to_out`` and the per-head gate, which both stay shared. + +How the negative context reaches the layer: the pipeline concatenates the +negative embedding to ``Modality.context`` along the sequence axis (see +``DistilledPipelineWithSkipStage2._prepare_run``). The transformer then applies +``caption_projection`` to both halves. In the AdaLN branch the context is +modulated before attention (``context * (1 + scale_kv) + shift_kv``), and the +modulation broadcasts over the sequence axis, so it reaches both halves too. +This patch only splits the halves inside ``attn2``. + +Only ``BasicAVTransformerBlock.attn2`` is guided. ``audio_attn2``, self-attention +and the audio/video cross-attention modules keep the upstream call. + +Strict no-op: with no active ``nag_scope`` the upstream method runs unchanged. + +Usage: + import services.patches.nag_cross_attention # noqa: F401 +""" + +from __future__ import annotations + +from collections.abc import Iterator +from contextlib import contextmanager +from dataclasses import dataclass +from typing import Any + +import torch +from ltx_core.model.transformer.attention import Attention +from ltx_core.model.transformer.transformer import BasicAVTransformerBlock + +from services.fast_video_pipeline.nag_config import NagConfig + +assert callable(getattr(BasicAVTransformerBlock, "_apply_text_cross_attention", None)), ( + "BasicAVTransformerBlock._apply_text_cross_attention missing - " + "re-verify this patch on rev bump" +) +_original_apply_text_cross_attention = BasicAVTransformerBlock._apply_text_cross_attention + + +@dataclass(frozen=True) +class NagState: + config: NagConfig + # Sequence length of the positive text context. Tokens after it are the negative context. + positive_length: int + + +# One generation runs at a time (GenerationHandler serializes them), so a module global is +# enough. It is not a ContextVar: torch.compile traces a plain global read. +_active: NagState | None = None + + +def active_state() -> NagState | None: + return _active + + +@contextmanager +def nag_scope(state: NagState) -> Iterator[None]: + """Turn NAG on for the denoise calls inside the block. Always turns it off on exit.""" + global _active + if _active is not None: + raise RuntimeError("NAG scope is already active") + _active = state + try: + yield + finally: + _active = None + + +def normalized_attention_guidance( + z_pos: torch.Tensor, z_neg: torch.Tensor, *, scale: float, alpha: float, tau: float +) -> torch.Tensor: + guidance = z_pos * scale - z_neg * (scale - 1.0) + # Norms accumulate in float32 without a full float32 copy of the token tensor. + norm_pos = torch.linalg.vector_norm(z_pos, ord=1, dim=-1, keepdim=True, dtype=torch.float32) + norm_guidance = torch.linalg.vector_norm(guidance, ord=1, dim=-1, keepdim=True, dtype=torch.float32) + ratio = torch.nan_to_num(norm_guidance / norm_pos, nan=10.0) + clip = torch.where(ratio > tau, norm_pos * tau / (norm_guidance + 1e-7), torch.ones_like(ratio)) + guidance = guidance * clip.to(guidance.dtype) + return guidance * alpha + z_pos * (1.0 - alpha) + + +def _attend(attn: Attention, q: torch.Tensor, context: torch.Tensor, mask: torch.Tensor | None) -> torch.Tensor: + k = attn.k_norm(attn.to_k(context)) + v = attn.to_v(context) + if mask is None: + return attn.attention_function(q, k, v, attn.heads) + return attn.masked_attention_function(q, k, v, attn.heads, mask) + + +class _NagTextAttention: + """Stands in for ``attn2`` inside the upstream cross-attention helpers. + + Same call shape as ``Attention.forward`` for a text cross-attention call + (no RoPE, no perturbation mask). + """ + + def __init__(self, attn: Attention, state: NagState) -> None: + self._attn = attn + self._state = state + + def __call__( + self, x: torch.Tensor, context: torch.Tensor | None = None, mask: torch.Tensor | None = None + ) -> torch.Tensor: + attn = self._attn + config = self._state.config + if context is None: + raise RuntimeError("NAG text attention needs a context") + length = self._state.positive_length + q = attn.q_norm(attn.to_q(x)) + # The text mask is None in ltx-pipelines. A mask, if present, fits the positive half only. + z_pos = _attend(attn, q, context[:, :length], mask) + z_neg = _attend(attn, q, context[:, length:], None) + out = normalized_attention_guidance( + z_pos, z_neg, scale=config.scale, alpha=config.alpha, tau=config.tau + ) + if attn.to_gate_logits is not None: + batch, tokens, _ = out.shape + gates = 2.0 * torch.sigmoid(attn.to_gate_logits(x)) + out = (out.view(batch, tokens, attn.heads, attn.dim_head) * gates.unsqueeze(-1)).view( + batch, tokens, attn.heads * attn.dim_head + ) + return attn.to_out(out) + + +def _apply_text_cross_attention( + self: BasicAVTransformerBlock, + x_normed: torch.Tensor, + context: torch.Tensor, + attn: Any, + scale_shift_table: torch.Tensor, + prompt_scale_shift_table: torch.Tensor | None, + timestep_embedding: Any, + prompt_timestep: torch.Tensor | None, + context_mask: torch.Tensor | None, + cross_attention_adaln: bool = False, +) -> torch.Tensor: + state = _active + if state is None or attn is not getattr(self, "attn2", None): + return _original_apply_text_cross_attention( + self, + x_normed, + context, + attn, + scale_shift_table, + prompt_scale_shift_table, + timestep_embedding, + prompt_timestep, + context_mask, + cross_attention_adaln, + ) + if context.shape[1] <= state.positive_length: + raise RuntimeError("NAG is active but the text context has no negative tokens") + if cross_attention_adaln and prompt_timestep is not None and prompt_timestep.shape[1] != 1: + # A per-token prompt modulation would not broadcast over the concatenated halves. + raise RuntimeError("NAG needs a prompt timestep with one entry per sample") + return _original_apply_text_cross_attention( + self, + x_normed, + context, + _NagTextAttention(attn, state), + scale_shift_table, + prompt_scale_shift_table, + timestep_embedding, + prompt_timestep, + context_mask, + cross_attention_adaln, + ) + + +BasicAVTransformerBlock._apply_text_cross_attention = _apply_text_cross_attention # type: ignore[method-assign] diff --git a/backend/services/patches/natten_libnatten_gate.py b/backend/services/patches/natten_libnatten_gate.py index 0c94e2bd4..7e9763e9a 100644 --- a/backend/services/patches/natten_libnatten_gate.py +++ b/backend/services/patches/natten_libnatten_gate.py @@ -8,7 +8,7 @@ Our Windows GCS wheel has ``HAS_LIBNATTEN=True``. This gate keeps that path and fails closed for Flex-only installs. -1.3.0 through 1.4.1 ``resolve_attention_for_host`` read ``natten_available()`` (this +1.3.0 through 1.6.0 ``resolve_attention_for_host`` read ``natten_available()`` (this module's ``_NATTEN_AVAILABLE``). Clearing the flag is the input to that remap, not a second remap of the same recipe. diff --git a/backend/services/patches/pinned_pool_fix.py b/backend/services/patches/pinned_pool_fix.py index 1def88c42..d4b38327a 100644 --- a/backend/services/patches/pinned_pool_fix.py +++ b/backend/services/patches/pinned_pool_fix.py @@ -1,28 +1,36 @@ -"""Monkey-patch: do not report pinned-host allocation failure as CUDA VRAM OOM. - -``OffloadMode.CPU`` streaming pre-allocates one pinned host buffer per -transformer block via ``ltx_core.block_streaming.utils.alloc_buffer``. For the -22B distilled checkpoint that is ~23 GiB of page-locked RAM (more if PyTorch's -CachingHostAllocator rounds each block up to the next power of two). - -``alloc_buffer`` first tries ``cudaHostRegister`` on a regular CPU tensor. On -Windows that call typically fails (pointer/size are not page-aligned for WDDM). -The failure is left as CUDA's sticky last error. The fallback -``torch.empty(..., pin_memory=True)`` then raises ``CUDA error: out of memory`` -even with ~14 GiB VRAM free, and every later CUDA call (including -``cudaMemGetInfo``) fails until the process is restarted. - -See https://github.com/Lightricks/LTX-Desktop/issues/141 - -This patch: -- On Windows, skips both ``cudaHostRegister`` and the CachingHostAllocator - fallback and allocates pageable host memory. H2D copies stay correct; they - just will not overlap compute. -- On other platforms, clears the sticky CUDA error after a failed register and - falls back to pageable memory if ``pin_memory=True`` itself OOMs. - -Remove once ltx-core ``alloc_buffer`` does not poison the CUDA context or -mis-report pinned-host failure as VRAM OOM. +"""Monkey-patch: page-locked host buffers must degrade to pageable memory, never crash. + +``OffloadMode.CPU`` and ``OffloadMode.DISK`` streaming on CUDA ask ``ltx_core.loader.buffers.host_bytes`` +for page-locked host buffers (``pin=True``). For the 22B distilled checkpoint that is ~23 GiB of +RAM-resident blocks, or the staging pool of disk streaming. + +``host_bytes`` builds a pinned buffer of 2 MiB or more from an anonymous ``mmap`` created with +``mmap.MAP_PRIVATE | mmap.MAP_ANONYMOUS`` and registers it with ``cudaHostRegister``. Those mmap +flags do not exist on Windows, so every pinned request raises ``AttributeError`` there. Where the +flags exist, a failed registration raises ``RuntimeError`` and leaves CUDA's sticky last error set; +a later fallback that pins through torch's caching host allocator can then surface as +``CUDA error: out of memory`` with VRAM free, and every later CUDA call fails until restart +(https://github.com/Lightricks/LTX-Desktop/issues/141). + +This patch wraps ``host_bytes``: +- On Windows, requests of ``_EXACT_PIN_BYTES`` or more skip pinning and return pageable host + memory. H2D copies stay correct; they just do not overlap compute. Smaller requests take + upstream's ``torch.empty(pin_memory=True)`` path, which works on Windows. +- Elsewhere it uses upstream, and when pinning fails it clears the sticky CUDA error and returns + pageable memory. An ``OSError`` from the anonymous mapping (``vm.overcommit_memory=2``) counts + as a failed pin too. + +``registry`` and ``state_loader`` record placement from the result (``buffer.is_pinned()``), so +they stay correct with a pageable buffer. ``streaming_builder`` records the placement it +requested instead; on Windows that says pinned for a pageable buffer. Nothing in ltx-core +asserts on it. + +Not covered: ``DeviceStager`` (``ltx_core/loader/raw.py``) pins two 64 MiB staging buckets per +device with ``torch.empty(pin_memory=True)``, which goes through torch's host allocator and +not ``host_bytes``. It normally works on Windows, but if it fails the error can surface as the +misleading "CUDA out of memory" of LTX-Desktop#141 and leave the sticky error set. + +Remove once ltx-core ``host_bytes`` works on Windows and does not leave a sticky CUDA error. Usage: import services.patches.pinned_pool_fix # noqa: F401 @@ -34,23 +42,16 @@ import sys import torch -from ltx_core.block_streaming import utils as bs_utils +from ltx_core.loader import buffers as _buffers +from ltx_core.loader import registry as _registry +from ltx_core.loader import state_loader as _state_loader +from ltx_core.loader import streaming_builder as _streaming_builder logger = logging.getLogger(__name__) +_REBOUND_MODULES = (_registry, _state_loader, _streaming_builder) -def _require_attr(name: str) -> None: - # Explicit raise so this still fires under `python -O` (asserts are stripped). - if not hasattr(bs_utils, name): - raise RuntimeError( - f"ltx_core.block_streaming.utils.{name} not found — patch needs updating." - ) - - -_require_attr("alloc_buffer") -_require_attr("_alloc_pinned_exact") - -_orig_alloc_pinned_exact = bs_utils._alloc_pinned_exact +_orig_host_bytes = _buffers.host_bytes _windows_pageable_logged = False @@ -76,48 +77,51 @@ def is_cuda_oom_error(exc: BaseException) -> bool: return "out of memory" in msg or "cudaerrormemoryallocation" in msg -def _alloc_pinned_exact_cleared(nbytes: int) -> torch.Tensor | None: - buf = _orig_alloc_pinned_exact(nbytes) - if buf is None: - # cudaHostRegister returns the error to Python but also sets the thread's - # sticky last error. Clear it before any later CUDA call. - _clear_cuda_sticky_error() - return buf +def _is_pin_failure(exc: BaseException) -> bool: + if isinstance(exc, OSError): + return True + return isinstance(exc, RuntimeError) and ("page-lock" in str(exc) or is_cuda_oom_error(exc)) -def _patched_alloc_buffer(nbytes: int, device: torch.device | None, pin_memory: bool) -> torch.Tensor: - """Like upstream ``alloc_buffer``, but never raises a misleading CUDA VRAM OOM.""" - if pin_memory and not torch.cuda.is_available(): - pin_memory = False - cpu_pin = pin_memory and (device is None or torch.device(device).type == "cpu") - if cpu_pin and sys.platform == "win32": +def _patched_host_bytes(nbytes: int, *, pin: bool = False) -> torch.Tensor: + """Like upstream ``host_bytes``, but a pin request made through it never fails the load.""" + if not pin: + return _orig_host_bytes(nbytes, pin=False) + if sys.platform == "win32" and nbytes >= _buffers._EXACT_PIN_BYTES: # pyright: ignore[reportPrivateUsage] global _windows_pageable_logged if not _windows_pageable_logged: logger.warning( "Using pageable host memory for streaming weight buffers on Windows. " - "ltx-core would pin via cudaHostRegister / CachingHostAllocator, which " - "fails as a misleading CUDA OOM while VRAM is free (LTX-Desktop#141)." + "ltx-core would pin through an anonymous mmap that Windows does not support " + "(LTX-Desktop#141)." ) _windows_pageable_logged = True - return torch.empty(nbytes, dtype=torch.uint8, device=device, pin_memory=False) - if cpu_pin: - buf = _alloc_pinned_exact_cleared(nbytes) - if buf is not None: - return buf - try: - return torch.empty(nbytes, dtype=torch.uint8, device=device, pin_memory=True) - except Exception as exc: - if not is_cuda_oom_error(exc): - raise - _clear_cuda_sticky_error() - logger.warning( - "Pinned host-memory allocation of %s bytes failed (%s). " - "Falling back to pageable CPU memory. This is not a GPU VRAM shortage.", - nbytes, - exc, - ) - pin_memory = False - return torch.empty(nbytes, dtype=torch.uint8, device=device, pin_memory=pin_memory) - - -bs_utils.alloc_buffer = _patched_alloc_buffer + return torch.empty(nbytes, dtype=torch.uint8) + try: + return _orig_host_bytes(nbytes, pin=True) + except (RuntimeError, OSError) as exc: + if not _is_pin_failure(exc): + raise + _clear_cuda_sticky_error() + logger.warning( + "Pinned host-memory allocation of %s bytes failed (%s). " + "Falling back to pageable CPU memory. This is not a GPU VRAM shortage.", + nbytes, + exc, + ) + return torch.empty(nbytes, dtype=torch.uint8) + + +for _module in _REBOUND_MODULES: + if getattr(_module, "host_bytes", None) is not _orig_host_bytes: + raise RuntimeError(f"{_module.__name__}.host_bytes is not ltx_core.loader.buffers.host_bytes — patch needs updating.") + _module.host_bytes = _patched_host_bytes # type: ignore[attr-defined] +_buffers.host_bytes = _patched_host_bytes + +_stale = sorted( + name + for name, module in list(sys.modules.items()) + if name.startswith("ltx_core.") and getattr(module, "host_bytes", None) is _orig_host_bytes +) +if _stale: + raise RuntimeError(f"{', '.join(_stale)} still hold the unpatched host_bytes — patch needs updating.") diff --git a/backend/services/patches/safetensors_loader_fix.py b/backend/services/patches/safetensors_loader_fix.py deleted file mode 100644 index 2587e0cd1..000000000 --- a/backend/services/patches/safetensors_loader_fix.py +++ /dev/null @@ -1,122 +0,0 @@ -"""Monkey-patch: replace safetensors safe_open with Python mmap loader. - -safetensors' safe_open uses torch.UntypedStorage.from_file internally, which -causes access violations (STATUS_ACCESS_VIOLATION / 0xC0000005) under memory -pressure on Windows. The crash occurs in UntypedStorage.__getitem__ when the -OS cannot service an mmap page fault. - -This patch replaces the load method of SafetensorsStateDictLoader with a -custom implementation that uses Python's mmap module + torch.frombuffer, -which handles memory pressure gracefully (raises a Python exception instead -of crashing the process). - -Each tensor's storage holds a reference to the mmap via _ltx_tensor_mmap_refs, -ensuring the mapping stays alive exactly as long as the tensor does. - -Remove this patch once safetensors / PyTorch fix the underlying issue. - -Usage: - import services.patches.safetensors_loader_fix # noqa: F401 -""" - -from __future__ import annotations - -import json -import mmap -import os -import struct -import warnings -from typing import Any - -import torch - -from ltx_core.loader.sft_loader import SafetensorsStateDictLoader -from ltx_core.loader.primitives import StateDict -from ltx_core.loader.sd_ops import SDOps - -_DTYPES = { - "F64": torch.float64, - "F32": torch.float32, - "F16": torch.float16, - "BF16": torch.bfloat16, - "I64": torch.int64, - "I32": torch.int32, - "I16": torch.int16, - "I8": torch.int8, - "U8": torch.uint8, - "BOOL": torch.bool, - "F8_E4M3": torch.float8_e4m3fn, - "F8_E5M2": torch.float8_e5m2, -} - - -def _load_safetensors_direct(shard_path: str) -> dict[str, torch.Tensor]: - """Load tensors from a safetensors file using Python mmap + torch.frombuffer.""" - f = open(shard_path, "rb") - mm = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) - mv = memoryview(mm) - - header_size = struct.unpack(" StateDict: - sd: dict[str, Any] = {} - size = 0 - dtype: set[torch.dtype] = set() - device = device or torch.device("cpu") - model_paths = path if isinstance(path, list) else [path] - for shard_path in model_paths: - tensors = _load_safetensors_direct(shard_path) - for name, value in tensors.items(): - expected_name = name if sd_ops is None else sd_ops.apply_to_key(name) - if expected_name is None: - continue - # Async H2D is only ordered against later compute on CUDA - # (same-stream). ltx_core.devices.allow_async_transfer fences the rest. - # Pure transfers like this one happen to be safe on MPS today, but - # blocking costs nothing at load time. - value = value.to(device=device, non_blocking=(device.type == "cuda"), copy=False) - key_value_pairs = ((expected_name, value),) - if sd_ops is not None: - key_value_pairs = sd_ops.apply_to_key_value(expected_name, value) - for key, value in key_value_pairs: - size += value.nbytes - dtype.add(value.dtype) - sd[key] = value - - return StateDict(sd=sd, device=device, size=size, dtype=dtype) - - -# Apply patch — assert the original method exists so a rename doesn't silently regress. -assert hasattr(SafetensorsStateDictLoader, "load") and callable(getattr(SafetensorsStateDictLoader, "load")), \ - "SafetensorsStateDictLoader.load not found — was it renamed? The safetensors_loader_fix patch needs updating." -SafetensorsStateDictLoader.load = _patched_load # type: ignore[assignment] diff --git a/backend/services/patches/safetensors_metadata_fix.py b/backend/services/patches/safetensors_metadata_fix.py index a5991b6fd..69b89df70 100644 --- a/backend/services/patches/safetensors_metadata_fix.py +++ b/backend/services/patches/safetensors_metadata_fix.py @@ -5,11 +5,22 @@ checkpoint, this reserves 22GB of commit charge just to read a small JSON header. Under memory pressure, this causes "paging file too small" errors. -This patch replaces metadata-only safe_open calls — and the FP8 scale / streaming -key-scan reads that still used safe_open on the full checkpoint — with direct -file reads that parse the safetensors header without mmap or commit charge. - -Remove this patch once safetensors supports read-only file mapping. +ltx-core 1.6.0 reads checkpoint headers and weights itself (``CheckpointReader``, +positional reads), so the model-loading and FP8 scale reads no longer need this +patch. The reads below still go through ``safe_open`` upstream and are replaced +with direct file reads that parse the safetensors header without mmap or commit +charge: the IC-LoRA reference downscale, the checkpoint ``model_version``, and +the checkpoint model id. + +``safe_open`` calls that remain upstream and are deliberately not replaced: +- ``estimate_diffusion_decoder_weight_bytes`` and ``read_lora_reference_temporal_scale_factor``: + they open the small split DiffVAE file or a LoRA, so the commit charge is bounded. +- ``GemmaAssets.from_single_file`` and the Gemma 4 key probes: they open the single-file + text encoder (~26 GB). This predates 1.6.0 (1.5.0 has the same calls) and is unpatched; + the Windows paging-file check in the manual test plan (D17) covers it. + +Remove once safetensors supports read-only file mapping, or ltx-pipelines reads +these headers without ``safe_open``. Usage: import services.patches.safetensors_metadata_fix # noqa: F401 @@ -19,27 +30,7 @@ import json import struct -from pathlib import Path -from typing import Any, BinaryIO, cast - -import torch -from ltx_core.loader.sd_ops import SDOps -from ltx_core.quantization.fp8_cast import _RAW_DIFFUSION_MODEL_PREFIX - -_DTYPES = { - "F64": torch.float64, - "F32": torch.float32, - "F16": torch.float16, - "BF16": torch.bfloat16, - "I64": torch.int64, - "I32": torch.int32, - "I16": torch.int16, - "I8": torch.int8, - "U8": torch.uint8, - "BOOL": torch.bool, - "F8_E4M3": torch.float8_e4m3fn, - "F8_E5M2": torch.float8_e5m2, -} +from typing import Any, cast def _read_safetensors_header(path: str) -> tuple[dict[str, Any], int]: @@ -59,56 +50,7 @@ def _read_safetensors_metadata(path: str) -> dict[str, str] | None: return cast(dict[str, str], meta) -def _read_tensor(path: str, info: dict[str, Any], data_offset: int, fh: BinaryIO | None = None) -> torch.Tensor: - """Read one tensor by seeking to its payload. Does not map the rest of the file.""" - dtype = _DTYPES[info["dtype"]] - shape = info["shape"] - start, end = info["data_offsets"] - if start == end: - return torch.empty(shape, dtype=dtype) - - def _load(handle: BinaryIO) -> torch.Tensor: - handle.seek(data_offset + start) - raw = handle.read(end - start) - return torch.frombuffer(bytearray(raw), dtype=dtype).reshape(shape).clone() - - if fh is not None: - return _load(fh) - with open(path, "rb") as handle: - return _load(handle) - - -# --- Patch 1: SafetensorsModelStateDictLoader.metadata --- - -from ltx_core.loader.sft_loader import SafetensorsModelStateDictLoader - - -def _patched_model_metadata(self: SafetensorsModelStateDictLoader, path: str) -> dict: - """Full ``__metadata__`` dict with JSON-encoded values parsed, mirroring upstream. - - Callers index into it themselves (``config``, ``model_version``, - ``gemma_source_checkpoint``), so returning only ``config`` silently hides the - sibling keys. - """ - meta = _read_safetensors_metadata(path) - if meta is None: - return {} - parsed: dict[str, object] = {} - for key, value in meta.items(): - try: - parsed[key] = json.loads(value) - except json.JSONDecodeError: - parsed[key] = value - return parsed - - -assert hasattr(SafetensorsModelStateDictLoader, "metadata") and callable( - getattr(SafetensorsModelStateDictLoader, "metadata") -), "SafetensorsModelStateDictLoader.metadata not found — patch needs updating." -SafetensorsModelStateDictLoader.metadata = _patched_model_metadata # type: ignore[assignment] - - -# --- Patch 2: ltx_pipelines read_lora_reference_downscale_factor --- +# --- ltx_pipelines read_lora_reference_downscale_factor --- # The upstream MPS-support work moved this helper to ltx_pipelines.iclora_utils and renamed it # (dropped the leading underscore); ic_lora re-imports it, so both bindings are patched. # The upstream version still uses safetensors safe_open (Windows commit-charge concern), so @@ -140,7 +82,7 @@ def _patched_read_lora_reference_downscale_factor(lora_path: str) -> int: setattr(_ic_lora_module, _DOWNSCALE_FN, _patched_read_lora_reference_downscale_factor) -# --- Patch 3: ltx_pipelines.utils.constants.detect_model_version --- +# --- ltx_pipelines.utils.constants.detect_model_version --- # Only the metadata read is replaced; the version -> params mapping stays upstream's # (``detect_params`` calls this by module global), so new generations keep their own defaults. @@ -179,7 +121,7 @@ def _patched_detect_model_version(checkpoint_path: str) -> tuple[int, ...]: setattr(_distilled_module, _DETECT_VERSION_FN, _patched_detect_model_version) -# --- Patch 4: services.text_encoder.ltx_text_encoder.TextHandler.get_model_id_from_checkpoint --- +# --- services.text_encoder.ltx_text_encoder.LTXTextEncoder.get_model_id_from_checkpoint --- from services.text_encoder.ltx_text_encoder import LTXTextEncoder @@ -199,79 +141,3 @@ def _patched_get_model_id_from_checkpoint(self: LTXTextEncoder, checkpoint_path: "LTXTextEncoder.get_model_id_from_checkpoint not found — patch needs updating." ) LTXTextEncoder.get_model_id_from_checkpoint = _patched_get_model_id_from_checkpoint # type: ignore[assignment] - - -# --- Patch 5: ltx_core.quantization.fp8_cast._read_scales (Lightricks/LTX-Desktop#158) --- -# build_fp8_cast_policy runs this on the 46 GB distilled-1.1 checkpoint. safe_open -# reserves commit charge equal to the file size (os error 1455) before inference. - -import ltx_core.quantization.fp8_cast as _fp8_cast_module - - -def _patched_read_scales(checkpoint_path: str | Path) -> dict[str, torch.Tensor]: - """Same contract as upstream ``_read_scales``, without mapping the whole file.""" - path = str(checkpoint_path) - header, data_offset = _read_safetensors_header(path) - out: dict[str, torch.Tensor] = {} - with open(path, "rb") as fh: - for key, info in header.items(): - if key == "__metadata__": - continue - if not key.endswith("_scale"): - continue - if not key.startswith(_RAW_DIFFUSION_MODEL_PREFIX): - raise ValueError( - f"Scale key {key!r} does not start with the expected raw prefix {_RAW_DIFFUSION_MODEL_PREFIX!r}" - ) - param_key = key.removeprefix(_RAW_DIFFUSION_MODEL_PREFIX).removesuffix("_scale") - out[param_key] = _read_tensor(path, info, data_offset, fh) - return out - - -assert hasattr(_fp8_cast_module, "_read_scales") and callable(_fp8_cast_module._read_scales), ( - "fp8_cast._read_scales not found — patch needs updating." -) -_fp8_cast_module._read_scales = _patched_read_scales # type: ignore[assignment] - - -# --- Patch 6: ltx_core.block_streaming.builder._scan_checkpoint_keys --- -# Same 46 GB safe_open during StreamingModelBuilder.build (next 1455 after #158). - -import ltx_core.block_streaming.builder as _streaming_builder_module - - -def _patched_scan_checkpoint_keys( - checkpoint_paths: list[str], - sd_ops: SDOps | None, - blocks_prefix: str, -) -> tuple[dict[int, list[tuple[str, str]]], list[tuple[str, str]]]: - """Same contract as upstream ``_scan_checkpoint_keys``, header-only.""" - block_key_map: dict[int, list[tuple[str, str]]] = {} - non_block_keys: list[tuple[str, str]] = [] - prefix_dot = blocks_prefix + "." - for path in checkpoint_paths: - header, _ = _read_safetensors_header(path) - for sft_key in header: - if sft_key == "__metadata__": - continue - model_key = sft_key if sd_ops is None else sd_ops.apply_to_key(sft_key) - if model_key is None: - continue - if model_key.startswith(prefix_dot): - rest = model_key[len(prefix_dot) :] - idx_str, _, param_name = rest.partition(".") - try: - block_idx = int(idx_str) - except ValueError: - non_block_keys.append((sft_key, model_key)) - continue - block_key_map.setdefault(block_idx, []).append((sft_key, param_name)) - else: - non_block_keys.append((sft_key, model_key)) - return block_key_map, non_block_keys - - -assert hasattr(_streaming_builder_module, "_scan_checkpoint_keys") and callable( - _streaming_builder_module._scan_checkpoint_keys -), "block_streaming.builder._scan_checkpoint_keys not found — patch needs updating." -_streaming_builder_module._scan_checkpoint_keys = _patched_scan_checkpoint_keys # type: ignore[assignment] diff --git a/backend/services/phase_log.py b/backend/services/phase_log.py index 0715bd2fb..6d7f88d76 100644 --- a/backend/services/phase_log.py +++ b/backend/services/phase_log.py @@ -15,6 +15,7 @@ import psutil from server_utils.heartbeat import log_heartbeat +from services.gpu_info.run_peak import fold_and_reset_cuda_peak if TYPE_CHECKING: import torch @@ -76,7 +77,7 @@ def measured_gpu_phase( cuda = device.type == "cuda" and torch.cuda.is_available() if cuda: - torch.cuda.reset_peak_memory_stats(device) + fold_and_reset_cuda_peak(device) try: with logged_phase(logger, label, heartbeat=True, prefix=prefix): yield diff --git a/backend/services/pose_processor_pipeline/dw_pose_pipeline.py b/backend/services/pose_processor_pipeline/dw_pose_pipeline.py index f05fd89b9..e7449ed17 100644 --- a/backend/services/pose_processor_pipeline/dw_pose_pipeline.py +++ b/backend/services/pose_processor_pipeline/dw_pose_pipeline.py @@ -38,10 +38,11 @@ def __init__( ) -> None: self._device = device jit_module = cast(Any, torch.jit) - self._pose_model = cast(torch.jit.ScriptModule, jit_module.load(pose_model_path, map_location=device)) + # dw-ll_ucoco_384_bs5 embeds float64 scalar constants in HardSigmoid; map_location=mps fails. + self._pose_model = cast(torch.jit.ScriptModule, jit_module.load(pose_model_path, map_location="cpu")).to(device) self._pose_model.eval() - self._detector_model = cast(torch.jit.ScriptModule, jit_module.load(person_detector_model_path, map_location=device)) + self._detector_model = cast(torch.jit.ScriptModule, jit_module.load(person_detector_model_path, map_location="cpu")).to(device) self._detector_model.eval() def _module_device_dtype(self, module: torch.nn.Module) -> tuple[torch.device, torch.dtype]: diff --git a/backend/services/prompt_enhancement/__init__.py b/backend/services/prompt_enhancement/__init__.py index 21e0e2d45..48e414cc3 100644 --- a/backend/services/prompt_enhancement/__init__.py +++ b/backend/services/prompt_enhancement/__init__.py @@ -6,6 +6,7 @@ resolve_video_frames, ) from services.prompt_enhancement.system_prompt import ( + LoraPromptGuidance, build_audio_visual_caption_system_prompt, build_conditioning_system_prompt, build_default_free_rewrite_system_prompt, @@ -23,10 +24,13 @@ parse_template_fill_response, render_catalog_item_block, video_role_max_output_tokens, + with_negative_prompt_rules, + with_user_negative_prompt, with_video_role_rules, ) __all__ = [ + "LoraPromptGuidance", "build_audio_visual_caption_system_prompt", "build_conditioning_system_prompt", "build_default_free_rewrite_system_prompt", @@ -44,6 +48,8 @@ "parse_template_fill_response", "render_catalog_item_block", "video_role_max_output_tokens", + "with_negative_prompt_rules", + "with_user_negative_prompt", "with_video_role_rules", "KeyframeStill", "SceneFrame", diff --git a/backend/services/prompt_enhancement/resolve_enhance_assets.py b/backend/services/prompt_enhancement/resolve_enhance_assets.py index b58075e9a..709ff258f 100644 --- a/backend/services/prompt_enhancement/resolve_enhance_assets.py +++ b/backend/services/prompt_enhancement/resolve_enhance_assets.py @@ -5,14 +5,14 @@ from typing import Literal from _routes._errors import HTTPError -from api_types import EnhancePromptRequest +from api_types import EnhancePromptRequest, KeyframeInput from handlers.asset_handler import AssetHandler def resolve_enhance_media_assets( assets: AssetHandler, req: EnhancePromptRequest ) -> EnhancePromptRequest: - """Fill imagePath / lastImagePath / videoPath / imagePaths from asset ids. No-op when ids are absent.""" + """Fill imagePath / lastImagePath / videoPath / imagePaths / keyframes from asset ids. No-op when ids are absent.""" updates: dict[str, object] = {} if req.imageAssetId: updates["imagePath"] = _asset_path(assets, req.imageAssetId, "image") @@ -23,6 +23,16 @@ def resolve_enhance_media_assets( if req.imageAssetIds: updates["imagePaths"] = [_asset_path(assets, asset_id, "image") for asset_id in req.imageAssetIds] updates["imageAssetIds"] = [] + if req.keyframeAssets: + updates["keyframes"] = [ + KeyframeInput( + imagePath=_asset_path(assets, keyframe.assetId, "image"), + frameIndex=keyframe.frameIndex, + strength=keyframe.strength, + ) + for keyframe in req.keyframeAssets + ] + updates["keyframeAssets"] = [] if req.videoAssetId: updates["videoPath"] = _asset_path(assets, req.videoAssetId, "video") updates["videoAssetId"] = None diff --git a/backend/services/prompt_enhancement/system_prompt.py b/backend/services/prompt_enhancement/system_prompt.py index 0d755b900..05a5a1369 100644 --- a/backend/services/prompt_enhancement/system_prompt.py +++ b/backend/services/prompt_enhancement/system_prompt.py @@ -10,7 +10,8 @@ import json import re -from typing import Literal, cast +from collections.abc import Sequence +from typing import Literal, Protocol, cast from api_types import IcLoraCatalogItem, InstructionSection, LoraCatalogItem, PromptTemplateSpec, TriggerPlacement from services.prompt_enhancement.i2v_frames import VideoRole @@ -18,7 +19,26 @@ _INCLUDED_KINDS = ("summary", "prompting") -def _instruction_text(instructions: list[InstructionSection], kind: str) -> list[str]: +class LoraPromptGuidance(Protocol): + """The prompt-enhancement fields of a catalog LoRA or a saved custom LoRA.""" + + @property + def name(self) -> str: ... + + @property + def instructions(self) -> Sequence[InstructionSection]: ... + + @property + def trigger(self) -> str | None: ... + + @property + def trigger_placement(self) -> TriggerPlacement | None: ... + + @property + def enhancement_examples(self) -> Sequence[str]: ... + + +def _instruction_text(instructions: Sequence[InstructionSection], kind: str) -> list[str]: texts: list[str] = [] for instr in instructions: if instr.kind != kind: @@ -27,7 +47,7 @@ def _instruction_text(instructions: list[InstructionSection], kind: str) -> list return texts -def _trigger_instruction(item: LoraCatalogItem) -> str | None: +def _trigger_instruction(item: LoraPromptGuidance) -> str | None: if item.trigger is None or item.trigger_placement is None: return None if item.trigger_placement == "first_token": @@ -42,7 +62,7 @@ def _trigger_instruction(item: LoraCatalogItem) -> str | None: ) -def render_catalog_item_block(item: LoraCatalogItem, *, include_trigger: bool = True) -> str: +def render_catalog_item_block(item: LoraPromptGuidance, *, include_trigger: bool = True) -> str: """Render one LoRA/IC-LoRA's catalog metadata as a block of text for Gemma to read. Only `summary`/`prompting`-kind instructions are included — `tips`/`input` are human-facing @@ -379,7 +399,7 @@ def build_conditioning_system_prompt(conditioning_type: Literal["canny", "depth" ) -def build_lora_enhancement_system_prompt(loras: list[LoraCatalogItem]) -> str: +def build_lora_enhancement_system_prompt(loras: Sequence[LoraPromptGuidance]) -> str: """System prompt for the free-rewrite path with one or more selected plain LoRAs. Callers must not pass an item whose `prompt_template` is set — that item goes through the @@ -454,7 +474,7 @@ def enforce_trigger_placement(text: str, trigger: str, placement: TriggerPlaceme return f"{text} {trigger}" -def enforce_trigger_placements(text: str, items: list[LoraCatalogItem]) -> str: +def enforce_trigger_placements(text: str, items: Sequence[LoraPromptGuidance]) -> str: """Apply `enforce_trigger_placement` for every selected item that has one. Only one trigger can lead a prompt — if more than one selected item wants @@ -501,6 +521,28 @@ def build_template_fill_system_prompt(item: LoraCatalogItem) -> str: _JSON_FENCE_RE = re.compile(r"```(?:json)?\s*(\{.*?\})\s*```", re.DOTALL) +_NEGATIVE_PROMPT_EXCLUSION_RULES = ( + "The user turn includes a list of excluded elements (negative prompt). " + "Do NOT include, mention, describe, or imply any of those excluded elements, styles, or actions " + "in your rewritten prompt, even if they appear in a reference image or video frame. " + "Describe the scene without them, and do not write negative phrasing (like 'no X' or 'without X') — " + "only describe what IS present in the desired shot." +) + + +def with_negative_prompt_rules(system_prompt: str, negative_prompt: str) -> str: + if not negative_prompt.strip(): + return system_prompt + return f"{system_prompt}\n\n{_NEGATIVE_PROMPT_EXCLUSION_RULES}" + + +def with_user_negative_prompt(user_text: str, negative_prompt: str) -> str: + neg = negative_prompt.strip() + if not neg: + return user_text + return f"{user_text}\nExcluded elements (do not include or mention in the prompt): {neg}" + + def parse_template_fill_response(raw: str, placeholder_names: set[str]) -> dict[str, str]: """Parse Gemma's template-fill response, defensively extracting the JSON object from surrounding text (a leading/trailing fragment, or a markdown code fence) despite being told diff --git a/backend/services/prompt_enhancer_pipeline/gemini_prompt_enhancer_pipeline.py b/backend/services/prompt_enhancer_pipeline/gemini_prompt_enhancer_pipeline.py index 688f58dad..b424f114b 100644 --- a/backend/services/prompt_enhancer_pipeline/gemini_prompt_enhancer_pipeline.py +++ b/backend/services/prompt_enhancer_pipeline/gemini_prompt_enhancer_pipeline.py @@ -19,6 +19,8 @@ resolve_i2v_frames, resolve_video_frames, video_role_max_output_tokens, + with_negative_prompt_rules, + with_user_negative_prompt, with_video_role_rules, ) from services.prompt_enhancement.i2v_frames import KeyframeStill, SceneFrame, VideoRole @@ -45,9 +47,19 @@ class GeminiPromptEnhancerPipeline: def __init__(self, http: HTTPClient) -> None: self._http = http - def enhance_t2v(self, prompt: str, system_prompt: str | None, seed: int, *, api_key: str, model: str) -> str: - contents: list[JSONValue] = [{"role": "user", "parts": [{"text": prompt}]}] - return self._call(contents, system_prompt, seed, api_key, model) + def enhance_t2v( + self, + prompt: str, + system_prompt: str | None, + seed: int, + *, + api_key: str, + model: str, + negative_prompt: str = "", + ) -> str: + user_text = with_user_negative_prompt(prompt, negative_prompt) + contents: list[JSONValue] = [{"role": "user", "parts": [{"text": user_text}]}] + return self._call(contents, system_prompt, seed, api_key, model, negative_prompt=negative_prompt) def enhance_i2v( self, @@ -62,6 +74,7 @@ def enhance_i2v( keyframes: list[KeyframeStill] | None = None, duration: int | None = None, fps: int | None = None, + negative_prompt: str = "", ) -> str: frames = resolve_i2v_frames(image_path, last_image_path, keyframes, fps=fps) image_parts = self._inline_image_parts(frames) @@ -79,6 +92,7 @@ def enhance_i2v( user_text = prompt.strip() or build_i2v_user_prompt_text(prompt, has_last=True) else: user_text = prompt if prompt.strip() else build_i2v_user_prompt_text(prompt, has_last=False) + user_text = with_user_negative_prompt(user_text, negative_prompt) # Single unlabeled still keeps the original Gemini turn (caption, then image). # Labeled first/last and keyframe sequences interleave a label before each still. @@ -92,7 +106,7 @@ def enhance_i2v( parts.append(image_part) parts.append({"text": user_text}) contents: list[JSONValue] = [{"role": "user", "parts": parts}] - return self._call(contents, system_prompt, seed, api_key, model) + return self._call(contents, system_prompt, seed, api_key, model, negative_prompt=negative_prompt) def enhance_with_video_frames( self, @@ -104,6 +118,7 @@ def enhance_with_video_frames( *, api_key: str, model: str, + negative_prompt: str = "", ) -> str: # Each still is preceded by its label, then the typed prompt closes the turn. parts: list[JSONValue] = [] @@ -113,8 +128,11 @@ def enhance_with_video_frames( has_look_reference = any(frame.is_reference for frame in frames) parts.append( { - "text": build_video_user_prompt_text( - prompt, role=role, has_look_reference=has_look_reference + "text": with_user_negative_prompt( + build_video_user_prompt_text( + prompt, role=role, has_look_reference=has_look_reference + ), + negative_prompt, ) } ) @@ -130,6 +148,7 @@ def enhance_with_video_frames( api_key, model, max_output_tokens=video_role_max_output_tokens(role) or _DEFAULT_MAX_OUTPUT_TOKENS, + negative_prompt=negative_prompt, ) def _inline_image_parts( @@ -184,11 +203,14 @@ def _call( model: str, *, max_output_tokens: int = _DEFAULT_MAX_OUTPUT_TOKENS, + negative_prompt: str = "", ) -> str: # Unlike the local Gemma pipeline, Gemini has no implicit default system prompt of its # own — omitting systemInstruction entirely gets a chatty, markdown-formatted essay # instead of a rewritten prompt. Always resolve to something. - resolved_system_prompt = system_prompt or build_default_free_rewrite_system_prompt() + resolved_system_prompt = with_negative_prompt_rules( + system_prompt or build_default_free_rewrite_system_prompt(), negative_prompt + ) return call_gemini_generate_content( self._http, api_key=api_key, diff --git a/backend/services/prompt_enhancer_pipeline/ltx_prompt_enhancer_pipeline.py b/backend/services/prompt_enhancer_pipeline/ltx_prompt_enhancer_pipeline.py index a3b2bdbaa..677754134 100644 --- a/backend/services/prompt_enhancer_pipeline/ltx_prompt_enhancer_pipeline.py +++ b/backend/services/prompt_enhancer_pipeline/ltx_prompt_enhancer_pipeline.py @@ -26,6 +26,7 @@ from __future__ import annotations from collections.abc import Sequence +from pathlib import Path from typing import TYPE_CHECKING, Any, cast import torch @@ -99,7 +100,7 @@ def _build_text_encoder(self) -> "LTXGemmaTextEncoder": # Mirrors ltx_pipelines.utils.blocks.PromptEncoder's non-streaming text-encoder build, # minus the embeddings-processor half — enhancement never needs video/audio embeddings. from ltx_core.loader.registry import DummyRegistry - from ltx_core.loader.single_gpu_model_builder import SingleGPUModelBuilder + from ltx_core.loader.simple_builder import SimpleBuilder from ltx_core.text_encoders.gemma import ( GemmaTextEncoderConfigurator, get_gemma_ops, @@ -108,23 +109,37 @@ def _build_text_encoder(self) -> "LTXGemmaTextEncoder": sd_ops, module_ops = get_gemma_ops(self._gemma_root) weight_paths = resolve_gemma_weight_paths(self._gemma_root) - builder = SingleGPUModelBuilder( - model_path=weight_paths, - model_class_configurator=GemmaTextEncoderConfigurator.with_gemma_model_path(self._gemma_root), - model_sd_ops=sd_ops, - module_ops=module_ops, + builder = SimpleBuilder( + GemmaTextEncoderConfigurator.with_gemma_model_path(self._gemma_root), + tuple(Path(path) for path in weight_paths), + (sd_ops,), + module_ops, registry=DummyRegistry(), ) return builder.build(device=torch.device(self._device), dtype=torch.bfloat16).eval() - def enhance_t2v(self, prompt: str, system_prompt: str | None, seed: int) -> str: + def enhance_t2v( + self, + prompt: str, + system_prompt: str | None, + seed: int, + negative_prompt: str = "", + ) -> str: from ltx_pipelines.utils.gpu_model import gpu_model + from services.prompt_enhancement import ( + with_negative_prompt_rules, + with_user_negative_prompt, + ) + with gpu_model(self._build_text_encoder()) as text_encoder: - resolved_system_prompt = system_prompt or _default_system_prompt(text_encoder, t2v=True) + resolved_system_prompt = with_negative_prompt_rules( + system_prompt or _default_system_prompt(text_encoder, t2v=True), + negative_prompt, + ) messages: list[dict[str, object]] = [ {"role": "system", "content": resolved_system_prompt}, - {"role": "user", "content": f"user prompt: {prompt}"}, + {"role": "user", "content": with_user_negative_prompt(f"user prompt: {prompt}", negative_prompt)}, ] return _generate(text_encoder, messages, image=None, seed=seed) @@ -138,6 +153,7 @@ def enhance_i2v( keyframes: list[KeyframeStill] | None = None, duration: int | None = None, fps: int | None = None, + negative_prompt: str = "", ) -> str: from services.prompt_enhancement import build_i2v_user_prompt_text, resolve_i2v_frames @@ -149,7 +165,7 @@ def enhance_i2v( duration=duration, fps=fps, ) - return self._generate_with_images(frames, user_text, system_prompt, seed) + return self._generate_with_images(frames, user_text, system_prompt, seed, negative_prompt=negative_prompt) def enhance_with_video_frames( self, @@ -158,6 +174,7 @@ def enhance_with_video_frames( system_prompt: str | None, seed: int, role: VideoRole, + negative_prompt: str = "", ) -> str: from services.prompt_enhancement import build_video_user_prompt_text, resolve_video_frames @@ -169,6 +186,7 @@ def enhance_with_video_frames( system_prompt, seed, role=role, + negative_prompt=negative_prompt, ) def _generate_with_images( @@ -178,10 +196,16 @@ def _generate_with_images( system_prompt: str | None, seed: int, role: VideoRole | None = None, + negative_prompt: str = "", ) -> str: from ltx_pipelines.utils.gpu_model import gpu_model - from services.prompt_enhancement import video_role_max_output_tokens, with_video_role_rules + from services.prompt_enhancement import ( + video_role_max_output_tokens, + with_negative_prompt_rules, + with_user_negative_prompt, + with_video_role_rules, + ) user_content: list[dict[str, object]] = [] tensors: list[torch.Tensor] = [] @@ -190,12 +214,13 @@ def _generate_with_images( user_content.append({"type": "text", "text": label}) user_content.append({"type": "image"}) tensors.append(_image_tensor(path)) - user_content.append({"type": "text", "text": user_text}) + user_content.append({"type": "text", "text": with_user_negative_prompt(user_text, negative_prompt)}) with gpu_model(self._build_text_encoder()) as text_encoder: resolved_system_prompt = system_prompt or _default_system_prompt(text_encoder, t2v=False) if role is not None: resolved_system_prompt = with_video_role_rules(resolved_system_prompt, role) + resolved_system_prompt = with_negative_prompt_rules(resolved_system_prompt, negative_prompt) messages: list[dict[str, object]] = [ {"role": "system", "content": resolved_system_prompt}, {"role": "user", "content": user_content}, diff --git a/backend/services/prompt_enhancer_pipeline/prompt_enhancer_pipeline.py b/backend/services/prompt_enhancer_pipeline/prompt_enhancer_pipeline.py index 8030e3682..ee07f7e82 100644 --- a/backend/services/prompt_enhancer_pipeline/prompt_enhancer_pipeline.py +++ b/backend/services/prompt_enhancer_pipeline/prompt_enhancer_pipeline.py @@ -14,7 +14,13 @@ class PromptEnhancerPipeline(Protocol): def create(gemma_root: str, device: str) -> "PromptEnhancerPipeline": ... - def enhance_t2v(self, prompt: str, system_prompt: str | None, seed: int) -> str: + def enhance_t2v( + self, + prompt: str, + system_prompt: str | None, + seed: int, + negative_prompt: str = "", + ) -> str: ... def enhance_i2v( @@ -27,6 +33,7 @@ def enhance_i2v( keyframes: list[KeyframeStill] | None = None, duration: int | None = None, fps: int | None = None, + negative_prompt: str = "", ) -> str: ... @@ -37,5 +44,6 @@ def enhance_with_video_frames( system_prompt: str | None, seed: int, role: VideoRole, + negative_prompt: str = "", ) -> str: ... diff --git a/backend/services/records.py b/backend/services/records.py index ca679c2ca..aecd7fe26 100644 --- a/backend/services/records.py +++ b/backend/services/records.py @@ -131,6 +131,11 @@ class PairedDeviceRecord(_RecordModel): revoked_at: int | None = None +# The lane that runs a job unless an executor picks another. Defined here, a leaf module, +# so the store can name it without importing the queue package. +LOCAL_LANE = "local" + + class GenerationRecord(_RecordModel): id: str = Field(min_length=1) feature: str = Field(min_length=1) @@ -143,6 +148,11 @@ class GenerationRecord(_RecordModel): attempt_count: int = Field(ge=0) started_at: int | None = None finished_at: int | None = None + # Set once at insert. Names the capacity pool that runs this job. + lane: str = LOCAL_LANE + # The id of the newest attempt at its provider. Set when the provider accepts it. A retry + # moves it to the displaced file until a provider cancel of it succeeds. + provider_job_id: str | None = None outputs: tuple[AssetRecord, ...] @model_validator(mode="after") @@ -151,6 +161,14 @@ def _failed_has_error_code(self) -> GenerationRecord: return self +class ProviderOrphan(_RecordModel): + """A job that was running at a provider when the app stopped.""" + + generation_id: str = Field(min_length=1) + lane: str = Field(min_length=1) + provider_job_id: str = Field(min_length=1) + + class AssistantRunRecord(_RecordModel): id: str = Field(min_length=1) conversation_id: str = Field(min_length=1) diff --git a/backend/services/retake_pipeline/ltx_retake_pipeline.py b/backend/services/retake_pipeline/ltx_retake_pipeline.py index 6e2e926a0..08d8890e9 100644 --- a/backend/services/retake_pipeline/ltx_retake_pipeline.py +++ b/backend/services/retake_pipeline/ltx_retake_pipeline.py @@ -19,6 +19,7 @@ from __future__ import annotations import logging +from contextlib import nullcontext from dataclasses import replace from collections.abc import Iterator from typing import Any @@ -35,7 +36,13 @@ from ltx_pipelines.utils.types import ModalitySpec, OffloadMode, VideoAudio from api_types import ExtendMode +from services.fast_video_pipeline.nag_config import NagConfig +from services.fast_video_pipeline.nag_distilled import ( + prompts_with_negative, + with_negative_context, +) from services.ltx_pipeline_common import build_model_paths, resolve_tiling_config +from services.patches.nag_cross_attention import NagState, nag_scope from services.services_utils import TilingConfigType from services.retake_pipeline.frame_rate import restamp_to_source_rate from services.retake_pipeline.retake_pipeline import RetakePipeline @@ -237,6 +244,7 @@ def _run( # noqa: PLR0913, PLR0915 encode_max_duration: float | None = None, content_width: int | None = None, content_height: int | None = None, + nag: NagConfig | None = None, ) -> tuple[Iterator[torch.Tensor], Audio, TilingConfigType]: from ltx_core.components.guiders import MultiModalGuider from ltx_core.components.noisers import GaussianNoiser @@ -357,7 +365,11 @@ def _run( # noqa: PLR0913, PLR0915 # --- Text encoding --- - prompts_to_encode = [prompt] if distilled else [prompt, negative_prompt] + prompts_to_encode = ( + prompts_with_negative(prompt, nag) + if distilled + else [prompt, negative_prompt] + ) contexts = self.prompt_encoder( prompts_to_encode, enhance_first_prompt=enhance_prompt, @@ -366,6 +378,11 @@ def _run( # noqa: PLR0913, PLR0915 v_context_p, a_context_p = contexts[0].video_encoding, contexts[0].audio_encoding + nag_state: NagState | None = None + if distilled and nag is not None: + v_context_p, nag_state = with_negative_context( + v_context_p, contexts[1].video_encoding, nag + ) # --- Build modality specs --- video_modality_spec = ModalitySpec( @@ -395,29 +412,28 @@ def _run( # noqa: PLR0913, PLR0915 # --- Build denoiser --- if distilled: sigmas = torch.tensor(_distilled_sigmas).to(dtype=torch.float32, device=self.device) - denoiser = SimpleDenoiser(v_context=v_context_p, a_context=a_context_p) + denoiser = SimpleDenoiser() else: sigmas = LTX2Scheduler().execute(steps=num_inference_steps).to(dtype=torch.float32, device=self.device) # type: ignore[no-untyped-call] assert video_guider_params is not None, "video_guider_params required for non-distilled" assert audio_guider_params is not None, "audio_guider_params required for non-distilled" v_context_n, a_context_n = contexts[1].video_encoding, contexts[1].audio_encoding denoiser = GuidedDenoiser( - v_context=v_context_p, - a_context=a_context_p, video_guider=MultiModalGuider(params=video_guider_params, negative_context=v_context_n), audio_guider=MultiModalGuider(params=audio_guider_params, negative_context=a_context_n), ) # --- Run diffusion stage --- - video_state, audio_state = self._denoise_masked_latents( - distilled=distilled, - seed=effective_seed, - denoiser=denoiser, - sigmas=sigmas, - noiser=noiser, - video=video_modality_spec, - audio=audio_modality_spec, - ) + with nag_scope(nag_state) if nag_state is not None else nullcontext(): + video_state, audio_state = self._denoise_masked_latents( + distilled=distilled, + seed=effective_seed, + denoiser=denoiser, + sigmas=sigmas, + noiser=noiser, + video=video_modality_spec, + audio=audio_modality_spec, + ) # --- Decode audio first (eager, small) --- assert audio_state is not None @@ -461,6 +477,7 @@ def generate( encode_max_duration: float | None = None, content_width: int | None = None, content_height: int | None = None, + nag: NagConfig | None = None, ) -> None: meta = get_videostream_metadata(video_path) fps = meta.fps @@ -496,6 +513,7 @@ def generate( encode_max_duration=encode_max_duration, content_width=content_width, content_height=content_height, + nag=nag, ) audio_out: Audio | None = audio video_chunks = get_video_chunks_number(num_frames, tiling_config) @@ -529,6 +547,7 @@ def extend( encode_max_duration: float | None = None, content_width: int | None = None, content_height: int | None = None, + nag: NagConfig | None = None, ) -> None: meta = get_videostream_metadata(video_path) fps = meta.fps @@ -566,6 +585,7 @@ def extend( encode_max_duration=encode_max_duration, content_width=content_width, content_height=content_height, + nag=nag, ) video_chunks = get_video_chunks_number(total_frames, tiling_config) encode_video( diff --git a/backend/services/retake_pipeline/retake_pipeline.py b/backend/services/retake_pipeline/retake_pipeline.py index fd4fb8c8a..19aa0c206 100644 --- a/backend/services/retake_pipeline/retake_pipeline.py +++ b/backend/services/retake_pipeline/retake_pipeline.py @@ -5,6 +5,7 @@ from typing import TYPE_CHECKING, Protocol from api_types import ExtendMode +from services.fast_video_pipeline.nag_config import NagConfig if TYPE_CHECKING: import torch @@ -54,6 +55,7 @@ def generate( encode_max_duration: float | None = None, content_width: int | None = None, content_height: int | None = None, + nag: NagConfig | None = None, ) -> None: ... def extend( @@ -76,4 +78,5 @@ def extend( encode_max_duration: float | None = None, content_width: int | None = None, content_height: int | None = None, + nag: NagConfig | None = None, ) -> None: ... diff --git a/backend/services/retake_pipeline/rgb_stitch.py b/backend/services/retake_pipeline/rgb_stitch.py index 4b6508cab..35a4a40fe 100644 --- a/backend/services/retake_pipeline/rgb_stitch.py +++ b/backend/services/retake_pipeline/rgb_stitch.py @@ -202,24 +202,32 @@ def write_rgb_video( ) -> None: dest.parent.mkdir(parents=True, exist_ok=True) rate = exact_rate(fps) - with av.open(str(dest), mode="w") as container: - stream = container.add_stream("libx264", rate=rate) # type: ignore[reportUnknownMemberType] - stream.width = width - stream.height = height - stream.pix_fmt = "yuv420p" - # yuv420p is limited-range. Tagging these full-range RGB frames as - # JPEG/full makes the decoder skip the limited-to-full expand, so black - # comes back as 16. Limited (MPEG) is the tag that round-trips. - stream.codec_context.colorspace = 1 - stream.codec_context.color_primaries = 1 - stream.codec_context.color_trc = 1 - stream.codec_context.color_range = 1 - pts = 0 - for pixels in frames: - video_frame = av.VideoFrame.from_ndarray(pixels, format="rgb24") - video_frame.pts = pts - pts += 1 - for packet in stream.encode(video_frame): + try: + with av.open(str(dest), mode="w") as container: + stream = container.add_stream("libx264", rate=rate) # type: ignore[reportUnknownMemberType] + stream.width = width + stream.height = height + stream.pix_fmt = "yuv420p" + # yuv420p is limited-range. Tagging these full-range RGB frames as + # JPEG/full makes the decoder skip the limited-to-full expand, so black + # comes back as 16. Limited (MPEG) is the tag that round-trips. + stream.codec_context.colorspace = 1 + stream.codec_context.color_primaries = 1 + stream.codec_context.color_trc = 1 + stream.codec_context.color_range = 1 + pts = 0 + for pixels in frames: + video_frame = av.VideoFrame.from_ndarray(pixels, format="rgb24") + video_frame.pts = pts + pts += 1 + for packet in stream.encode(video_frame): + container.mux(packet) + for packet in stream.encode(): container.mux(packet) - for packet in stream.encode(): - container.mux(packet) + finally: + # A failed encode leaves the frame generator suspended inside its own `with av.open(...)`, + # which keeps the source file open. On Windows that blocks the caller's cleanup unlink + # (WinError 32) and hides the real error, so close the generator here. + close = getattr(frames, "close", None) + if close is not None: + close() diff --git a/backend/services/schema/0003_generation_lane.sql b/backend/services/schema/0003_generation_lane.sql new file mode 100644 index 000000000..4c7c69878 --- /dev/null +++ b/backend/services/schema/0003_generation_lane.sql @@ -0,0 +1,11 @@ +-- The lane a job runs in: a capacity pool such as local or a provider. Set once at insert. +-- Existing rows run on the local lane. +ALTER TABLE generations ADD COLUMN lane TEXT NOT NULL DEFAULT 'local'; + +-- The id of the job at the provider, for a job that runs on a provider lane. Set when the +-- provider accepts the job, cleared when the job is retried. NULL for a local job. +ALTER TABLE generations ADD COLUMN provider_job_id TEXT; + +CREATE INDEX IF NOT EXISTS idx_generations_pending_lane_rank + ON generations(lane, queue_rank ASC, id ASC) + WHERE status = 'queued' AND deleted_at IS NULL; diff --git a/backend/services/schema/0004_device_calibration.sql b/backend/services/schema/0004_device_calibration.sql new file mode 100644 index 000000000..8798ce027 --- /dev/null +++ b/backend/services/schema/0004_device_calibration.sql @@ -0,0 +1,34 @@ +CREATE TABLE IF NOT EXISTS device_calibration_frontier ( + id INTEGER PRIMARY KEY, + epoch INTEGER NOT NULL CHECK (epoch > 0), + system TEXT NOT NULL CHECK (system IN ('Windows','Linux','Darwin')), + gpu_model TEXT NOT NULL CHECK (gpu_model <> ''), + total_memory_bytes INTEGER NOT NULL CHECK (total_memory_bytes > 0), + model_id TEXT NOT NULL, + feature TEXT NOT NULL CHECK (feature IN ('fast','edit','iclora')), + adapter_id TEXT NOT NULL DEFAULT '', + stage_mode TEXT NOT NULL DEFAULT '', + load_mode TEXT NOT NULL CHECK (load_mode IN ('full_models_loading','streaming_models_loading')), + tiled INTEGER NOT NULL CHECK (tiled IN (0,1)), + chunked INTEGER NOT NULL CHECK (chunked IN (0,1)), + seq REAL NOT NULL CHECK (seq > 0), + canvas_px INTEGER NOT NULL CHECK (canvas_px > 0), + windows INTEGER NOT NULL CHECK (windows >= 1), + peak_growth_bytes INTEGER CHECK (peak_growth_bytes IS NULL OR peak_growth_bytes >= 0), + -- Wall seconds of the run, for the machine factor. NULL when the run was not timed. + wall_s REAL CHECK (wall_s IS NULL OR wall_s > 0), + -- Fast decode the run used: 1 ConvVAE, 0 DiffVAE. + conv_vae INTEGER NOT NULL DEFAULT 0 CHECK (conv_vae IN (0,1)), + -- Spatial tiles per step of the run. The ETA multiplies the denoise time by it. + tiles INTEGER NOT NULL DEFAULT 1 CHECK (tiles >= 1), + priced_gib REAL NOT NULL, + -- Provenance only; no FK, so deleting history keeps the device fact. + generation_id TEXT, + recorded_at INTEGER NOT NULL +); + +CREATE INDEX IF NOT EXISTS idx_device_calibration_frontier_bucket + ON device_calibration_frontier( + epoch, system, gpu_model, total_memory_bytes, model_id, + feature, adapter_id, stage_mode, load_mode, tiled, chunked + ); diff --git a/backend/services/sqlite_store.py b/backend/services/sqlite_store.py index f8a8d827f..c0b57bc69 100644 --- a/backend/services/sqlite_store.py +++ b/backend/services/sqlite_store.py @@ -6,21 +6,28 @@ import sqlite3 import time import uuid -from collections.abc import Collection +from collections.abc import Collection, Mapping from datetime import datetime from pathlib import Path -from typing import cast, get_args +from typing import TYPE_CHECKING, cast, get_args from pydantic import BaseModel, ConfigDict, JsonValue, TypeAdapter +from services.displaced_provider_jobs import ( + DISPLACED_PROVIDER_JOBS_FILENAME, + DisplacedProviderJobs, +) from services.dashboard_stats import DashboardSnapshot, DashboardWindow, compute_dashboard -from services.migrations import MIGRATIONS_DIR, apply_migrations +from services.device_calibration_store import DeviceCalibrationStore +from services.migrations import MIGRATIONS_DIR, apply_migrations, repair_generation_lane from services.media_probe import ( extension_for_mime, probe_file, validate_ingest_source, ) +from runtime_config.assets_layout import assets_folder, in_flight_folder from services.records import ( + LOCAL_LANE, AssetInUseError, AssetListPage, AssetMetadata, @@ -36,17 +43,32 @@ MediaKind, OutputSpec, PairedDeviceRecord, + ProviderOrphan, QueueGenerationRecord, StatusError, UnavailableError, ) -from services.thumbnails import PillowAvThumbnailWriter, ThumbnailWriter +from services.thumbnails import ( + PillowAvThumbnailWriter, + ThumbnailWriter, + resolve_stored_thumbnail, +) + +if TYPE_CHECKING: + from runtime_config.device_calibration import ( + CalibrationBucket, + DeviceIdentity, + FrontierPoint, + ) _RUNNING_STATUSES: set[str] = {"running"} _CANCELLING_STATUSES: set[str] = {"cancelling"} _IN_FLIGHT_STATUSES: set[str] = _RUNNING_STATUSES | _CANCELLING_STATUSES _RETRYABLE_STATUSES: set[str] = {"failed"} -_IN_FLIGHT_DIRNAME = ".in-flight" +# Electron writes this file in a custom assets folder after the copy is verified. Its absence +# means the folder is not the library (unplugged drive, empty mount point). The name is pinned +# to shared/assets-marker.json by tests on both sides. +ASSETS_MARKER_FILENAME = ".ltx-assets" _UNLINK_RETRY_ATTEMPTS = 5 _UNLINK_RETRY_BASE_SECONDS = 0.05 _QUEUE_RANK_SPACING = 1_000_000 @@ -90,6 +112,14 @@ def _optional_str(value: object) -> str | None: return str(value) +def _provider_orphan(row: sqlite3.Row) -> ProviderOrphan: + return ProviderOrphan( + generation_id=str(row["generation_id"]), + lane=str(row["lane"]), + provider_job_id=str(row["provider_job_id"]), + ) + + def _optional_int(value: object) -> int | None: if value is None: return None @@ -194,14 +224,27 @@ def __init__( self, app_data_dir: Path, thumbnail_writer: ThumbnailWriter | None = None, + assets_dir: Path | None = None, ) -> None: try: - self._assets_dir = app_data_dir / "assets" - self._in_flight_dir = self._assets_dir / _IN_FLIGHT_DIRNAME + self._custom_assets_dir = assets_dir is not None + self._assets_dir = assets_folder(app_data_dir, assets_dir) + self._in_flight_dir = in_flight_folder(app_data_dir, assets_dir) + app_data_dir.mkdir(parents=True, exist_ok=True) self._db_path = app_data_dir / "store.sqlite3" - self._assets_dir.mkdir(parents=True, exist_ok=True) + self._displaced_jobs = DisplacedProviderJobs( + app_data_dir / DISPLACED_PROVIDER_JOBS_FILENAME + ) + if self._custom_assets_dir: + # Never create a custom folder: on an unmounted drive that would make an + # empty folder on the system disk. + if not self._assets_dir_ready(): + raise FileNotFoundError(self._assets_dir) + else: + self._assets_dir.mkdir(parents=True, exist_ok=True) conn = self._connect() apply_migrations(conn, MIGRATIONS_DIR) + repair_generation_lane(conn) conn.commit() conn.close() self._thumbnail_writer: ThumbnailWriter = ( @@ -209,9 +252,29 @@ def __init__( if thumbnail_writer is not None else PillowAvThumbnailWriter() ) + self._calibration = DeviceCalibrationStore(self._connect, self._now_ms) except (sqlite3.Error, OSError) as exc: raise UnavailableError() from exc + def _assets_dir_ready(self) -> bool: + """False when the assets folder is gone. A custom folder also needs its marker.""" + try: + if not self._assets_dir.is_dir(): + return False + return not self._custom_assets_dir or ( + self._assets_dir / ASSETS_MARKER_FILENAME + ).is_file() + except OSError: + return False + + def _require_assets_dir(self) -> None: + """A gone custom folder is an unavailable store. The default folder is made again.""" + if self._custom_assets_dir: + if not self._assets_dir_ready(): + raise UnavailableError() + else: + self._assets_dir.mkdir(parents=True, exist_ok=True) + def _connect(self) -> sqlite3.Connection: conn = sqlite3.connect(self._db_path, timeout=5.0) conn.row_factory = sqlite3.Row @@ -578,7 +641,10 @@ def _asset_record(self, row: sqlite3.Row) -> AssetRecord: mime_type = str(row["mime_type"]) asset_id = str(row["id"]) raw_thumb = row["thumbnail_path"] - thumbnail_path = None if raw_thumb is None else str(raw_thumb) + thumbnail = resolve_stored_thumbnail( + self._assets_dir, None if raw_thumb is None else str(raw_thumb) + ) + thumbnail_path = None if thumbnail is None else str(thumbnail) return AssetRecord.model_validate( { "id": asset_id, @@ -602,6 +668,7 @@ def ingest_upload(self, source_path: str) -> AssetRecord: if not is_file: raise FileNotFoundError(source) validate_ingest_source(source) + self._require_assets_dir() asset_id = self._new_id() dest = self._assets_dir / f"{asset_id}{source.suffix}" created_at = self._now_ms() @@ -674,7 +741,8 @@ def _persist_thumbnail(self, record: AssetRecord) -> AssetRecord: try: cursor = conn.execute( "UPDATE assets SET thumbnail_path = ? WHERE id = ? AND deleted_at IS NULL", - (written, record.id), + # The column holds the file name only, so a moved assets folder stays valid. + (Path(written).name, record.id), ) conn.commit() persisted = cursor.rowcount == 1 @@ -733,6 +801,8 @@ def list_assets( ) -> AssetListPage: if sort not in ("created_at-desc", "created_at-asc"): raise ValueError(f"invalid sort: {sort}") + # A gone custom folder is an unavailable library, not an empty one. + self._require_assets_dir() descending = sort == "created_at-desc" after: tuple[int, str] | None = ( _decode_cursor(cursor) if cursor is not None else None @@ -773,6 +843,9 @@ def _tombstone_missing_assets(self, asset_ids: tuple[str, ...]) -> None: """Stamp deleted_at only. Skip live inputs. Do not unlink or hide the producer.""" if not asset_ids: return + if not self._assets_dir_ready(): + # A missing folder is not a deleted library. Keep every row. + return conn = self._connect() try: conn.execute("BEGIN IMMEDIATE") @@ -808,7 +881,8 @@ def allocate_output_path( if media_kind not in get_args(MediaKind): raise ValueError(f"invalid media_kind: {media_kind}") asset_id = self._new_id() - self._in_flight_dir.mkdir(parents=True, exist_ok=True) + self._require_assets_dir() + self._in_flight_dir.mkdir(exist_ok=True) dest = _derived_path(self._in_flight_dir, asset_id, mime_type) return (asset_id, str(dest)) @@ -819,6 +893,7 @@ def insert_generation( *, contract_version: int = 1, generation_id: str | None = None, + lane: str = LOCAL_LANE, ) -> GenerationRecord: if contract_version < 1: raise ValueError("contract_version must be >= 1") @@ -857,8 +932,8 @@ def insert_generation( INSERT INTO generations ( id, feature, contract_version, status, spec, error_code, created_at, queued_at, queue_rank, attempt_count, started_at, finished_at, - deleted_at - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + deleted_at, lane + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) """, ( generation_id, @@ -874,6 +949,7 @@ def insert_generation( None, None, None, + lane, ), ) conn.commit() @@ -884,11 +960,16 @@ def insert_generation( raise RuntimeError(f"generation {generation_id} missing after insert") return record - def has_queued(self) -> bool: + def has_queued(self, lane: str = LOCAL_LANE) -> bool: conn = self._connect() try: row = conn.execute( - "SELECT 1 FROM generations WHERE status = 'queued' AND deleted_at IS NULL LIMIT 1" + """ + SELECT 1 FROM generations + WHERE status = 'queued' AND lane = ? AND deleted_at IS NULL + LIMIT 1 + """, + (lane,), ).fetchone() return row is not None finally: @@ -1019,12 +1100,24 @@ def reorder_queued_generation( finally: conn.close() - def request_generation_cancellation(self, generation_id: str) -> GenerationRecord: + def request_generation_cancellation( + self, generation_id: str, *, uncancellable_lanes: Collection[str] = () + ) -> GenerationRecord: + """Cancel a queued job, or ask a running one to stop. + + A running job on one of uncancellable_lanes keeps running: StatusError. + """ conn = self._connect() try: conn.execute("BEGIN IMMEDIATE") status = self._require_status(conn, generation_id, {"queued", "running"}) now = self._now_ms() + if status == "running" and uncancellable_lanes: + lane = conn.execute( + "SELECT lane FROM generations WHERE id = ?", (generation_id,) + ).fetchone()["lane"] + if lane in uncancellable_lanes: + raise StatusError(generation_id, status) if status == "queued": conn.execute( """ @@ -1050,9 +1143,12 @@ def request_generation_cancellation(self, generation_id: str) -> GenerationRecor finally: conn.close() - def claim_next_queued(self) -> GenerationRecord | None: + def claim_next_queued(self, lane: str = LOCAL_LANE) -> GenerationRecord | None: while True: - claimed = self._claim_one_queued() + if not self._assets_dir_ready(): + # A missing folder must not fail the queued jobs that need their inputs. + return None + claimed = self._claim_one_queued(lane) if claimed is None: return None if self._has_missing_input(claimed): @@ -1104,7 +1200,7 @@ def _has_missing_input(self, claimed: GenerationRecord) -> bool: finally: conn.close() - def _claim_one_queued(self) -> GenerationRecord | None: + def _claim_one_queued(self, lane: str) -> GenerationRecord | None: conn = self._connect() try: conn.execute("BEGIN IMMEDIATE") @@ -1112,10 +1208,11 @@ def _claim_one_queued(self) -> GenerationRecord | None: """ SELECT id FROM generations - WHERE status = 'queued' AND deleted_at IS NULL + WHERE status = 'queued' AND lane = ? AND deleted_at IS NULL ORDER BY queue_rank ASC, id ASC LIMIT 1 - """ + """, + (lane,), ).fetchone() if row is None: conn.commit() @@ -1150,7 +1247,10 @@ def _claim_one_queued(self) -> GenerationRecord | None: finally: conn.close() - def retry_generation(self, generation_id: str) -> GenerationRecord: + def retry_generation( + self, generation_id: str, lane: str | None = None + ) -> GenerationRecord: + """Queue a failed job again. ``lane`` moves it to the lane that is valid now.""" conn = self._connect() try: conn.execute("BEGIN IMMEDIATE") @@ -1159,6 +1259,11 @@ def retry_generation(self, generation_id: str) -> GenerationRecord: now = self._now_ms() queued_at = self._next_queued_at(conn, now) queue_rank = self._next_queue_rank(conn) + # The row keeps the id of the newest attempt only. The id of the failed attempt + # goes to the displaced file until a provider cancel of it succeeds. The file is + # written before the commit: a crash in between leaves the id in both places, and + # a duplicate is harmless, but a lost id is not. + self._keep_displaced_job(conn, generation_id) conn.execute( """ UPDATE generations @@ -1168,10 +1273,12 @@ def retry_generation(self, generation_id: str) -> GenerationRecord: error_code = NULL, started_at = NULL, finished_at = NULL, - attempt_count = attempt_count + 1 + attempt_count = attempt_count + 1, + lane = COALESCE(?, lane), + provider_job_id = NULL WHERE id = ? AND status = 'failed' """, - (queued_at, queue_rank, generation_id), + (queued_at, queue_rank, lane, generation_id), ) record = self._commit_loaded(conn, generation_id) self._unlink_under_assets(generated_paths) @@ -1179,6 +1286,28 @@ def retry_generation(self, generation_id: str) -> GenerationRecord: finally: conn.close() + def _keep_displaced_job(self, conn: sqlite3.Connection, generation_id: str) -> None: + row = conn.execute( + """ + SELECT lane, provider_job_id FROM generations + WHERE id = ? AND status = 'failed' + AND provider_job_id IS NOT NULL AND provider_job_id != '' + """, + (generation_id,), + ).fetchone() + if row is None: + return + try: + self._displaced_jobs.add( + ProviderOrphan( + generation_id=generation_id, + lane=str(row["lane"]), + provider_job_id=str(row["provider_job_id"]), + ) + ) + except OSError as exc: + raise UnavailableError() from exc + def _require_status( self, conn: sqlite3.Connection, generation_id: str, allowed: set[str] ) -> str: @@ -1695,6 +1824,8 @@ def _record_from_generation_row( "attempt_count": _require_int(row["attempt_count"]), "started_at": _optional_int(row["started_at"]), "finished_at": _optional_int(row["finished_at"]), + "lane": str(row["lane"]), + "provider_job_id": _optional_str(row["provider_job_id"]), "outputs": tuple(outputs), } ) @@ -1733,6 +1864,8 @@ def delete_asset(self, asset_id: str) -> bool: """True if deleted or already deleted. False if the id never existed. Raises AssetInUseError, StatusError (producer running or cancelling). Canonical and thumbnail unlinks are best-effort after commit.""" + # With the folder gone, the unlink would skip the files and leave orphans. + self._require_assets_dir() unlink_paths: list[Path] = [] conn = self._connect() try: @@ -1796,9 +1929,11 @@ def delete_asset(self, asset_id: str) -> bool: unlink_paths.append( _derived_path(self._assets_dir, asset_id, str(row["mime_type"])) ) - thumbnail_path = _optional_str(row["thumbnail_path"]) - if thumbnail_path is not None: - unlink_paths.append(Path(thumbnail_path)) + thumbnail = resolve_stored_thumbnail( + self._assets_dir, _optional_str(row["thumbnail_path"]) + ) + if thumbnail is not None: + unlink_paths.append(thumbnail) conn.commit() finally: conn.close() @@ -1813,6 +1948,125 @@ def delete_asset(self, asset_id: str) -> bool: ) return True + def reassign_unknown_lanes(self, known: Collection[str]) -> int: + """Move every queued job whose lane is not registered onto the local lane. + + Runs at boot, before a runner claims. A lane that is no longer registered + (parallel lanes turned off, a removed provider) would otherwise hold its + queued rows forever. Finished rows keep their lane. A retry picks a valid lane. + """ + placeholders = ",".join("?" * len(known)) + try: + conn = self._connect() + try: + conn.execute("BEGIN IMMEDIATE") + cursor = conn.execute( + f""" + UPDATE generations SET lane = ? + WHERE lane NOT IN ({placeholders}) AND status = 'queued' + AND deleted_at IS NULL + """, + (LOCAL_LANE, *known), + ) + conn.commit() + return cursor.rowcount + except Exception: + conn.rollback() + raise + finally: + conn.close() + except (sqlite3.Error, OSError) as exc: + raise UnavailableError() from exc + + def set_provider_job_id( + self, generation_id: str, attempt_count: int, provider_job_id: str + ) -> bool: + """Record the id of a running attempt at its provider. A job that is not running keeps none. + + The attempt guard keeps a late write of an old attempt off the row of a retry. + Raises ValueError for an empty id: it would make the boot orphan list unreadable. + """ + if not provider_job_id: + raise ValueError("provider_job_id must not be empty") + conn = self._connect() + try: + cursor = conn.execute( + """ + UPDATE generations SET provider_job_id = ? + WHERE id = ? AND attempt_count = ? AND status IN ('running', 'cancelling') + AND deleted_at IS NULL + """, + (provider_job_id, generation_id, attempt_count), + ) + conn.commit() + return cursor.rowcount == 1 + except Exception: + conn.rollback() + raise + finally: + conn.close() + + def clear_provider_job_id(self, generation_id: str, provider_job_id: str) -> bool: + """Forget a provider job once the provider dropped it. + + The id is on the row or, after a retry, in the displaced file. False if neither holds it. + """ + conn = self._connect() + try: + on_row = conn.execute( + "UPDATE generations SET provider_job_id = NULL WHERE id = ? AND provider_job_id = ?", + (generation_id, provider_job_id), + ).rowcount + conn.commit() + except Exception: + conn.rollback() + raise + finally: + conn.close() + displaced = self._displaced_jobs.remove(generation_id, provider_job_id) + return on_row > 0 or displaced + + def list_provider_orphans(self) -> list[ProviderOrphan]: + """Jobs that may still run at a provider: an id is stored and not yet cancelled. + + A job that ended as failed or cancelled keeps its id until a provider cancel + succeeds, so a failed cancel is tried again at the next boot. A succeeded job + is done at the provider and is never listed. A deleted row and an older attempt + that a retry replaced are listed too: the provider can still run them. + """ + try: + conn = self._connect() + try: + rows = conn.execute( + """ + SELECT id AS generation_id, lane, provider_job_id + FROM generations + WHERE status IN ('running', 'cancelling', 'failed', 'cancelled') + AND provider_job_id IS NOT NULL AND provider_job_id != '' + ORDER BY queued_at ASC, id ASC + """ + ).fetchall() + finally: + conn.close() + displaced = self._displaced_jobs.list() + except (sqlite3.Error, OSError) as exc: + raise UnavailableError() from exc + orphans = [_provider_orphan(row) for row in rows] + # A crash between the file write and the commit of a retry leaves one id in both places. + listed = {(orphan.generation_id, orphan.provider_job_id) for orphan in orphans} + orphans.extend( + job for job in displaced if (job.generation_id, job.provider_job_id) not in listed + ) + return orphans + + def list_displaced_provider_jobs(self, generation_id: str) -> list[ProviderOrphan]: + """The ids of the older attempts of one job that a retry replaced and nobody cancelled.""" + try: + jobs = self._displaced_jobs.list(generation_id) + except OSError as exc: + raise UnavailableError() from exc + return sorted(jobs, key=lambda job: job.provider_job_id) + def fail_running_on_boot(self) -> int: now = self._now_ms() try: @@ -1978,6 +2232,37 @@ def _get_paired_device( finally: conn.close() + def load_device_frontier( + self, identity: DeviceIdentity, epoch: int + ) -> Mapping[CalibrationBucket, tuple[FrontierPoint, ...]]: + return self._calibration.load_device_frontier(identity, epoch) + + def load_device_machine_factor( + self, identity: DeviceIdentity, epoch: int + ) -> float | None: + return self._calibration.load_device_machine_factor(identity, epoch) + + def widen_device_frontier( + self, + identity: DeviceIdentity, + epoch: int, + bucket: CalibrationBucket, + point: FrontierPoint, + *, + priced_gib: float, + generation_id: str | None, + conv_vae: bool = False, + ) -> tuple[FrontierPoint, ...] | None: + return self._calibration.widen_device_frontier( + identity, + epoch, + bucket, + point, + priced_gib=priced_gib, + generation_id=generation_id, + conv_vae=conv_vae, + ) + def _paired_device_from_row(self, row: sqlite3.Row) -> PairedDeviceRecord: return PairedDeviceRecord( id=str(row["id"]), diff --git a/backend/services/storage_info/storage_info_impl.py b/backend/services/storage_info/storage_info_impl.py index fa289e803..40cc82a8a 100644 --- a/backend/services/storage_info/storage_info_impl.py +++ b/backend/services/storage_info/storage_info_impl.py @@ -1,6 +1,6 @@ """Drive-type probe for the checkpoint volume (Windows Fast DISK routing). -Disk-mapped streaming reads ~70 GB per generation: seconds on NVMe, minutes on +Disk streaming reads ~70 GB per generation: seconds on NVMe, minutes on spinning rust. This probe classifies the volume holding the checkpoints so the offload decision can tell them apart. Checkpoints live under the app-data tree, so the app-data volume answers for them (volume granularity, not the file). diff --git a/backend/services/store.py b/backend/services/store.py index 2bfc315ee..32744cdf4 100644 --- a/backend/services/store.py +++ b/backend/services/store.py @@ -1,14 +1,16 @@ from __future__ import annotations -from collections.abc import Collection +from collections.abc import Collection, Mapping from datetime import datetime from typing import Protocol from pydantic import JsonValue +from runtime_config.device_calibration import CalibrationBucket, DeviceIdentity, FrontierPoint from services.dashboard_stats import DashboardSnapshot, DashboardWindow from services.records import ( + LOCAL_LANE, AssetListPage, AssetRecord, AssistantQueueRecord, @@ -17,11 +19,34 @@ GenerationRecord, MediaKind, OutputSpec, + ProviderOrphan, QueueGenerationRecord, ) -class Store(Protocol): +class CalibrationStore(Protocol): + def load_device_frontier( + self, identity: DeviceIdentity, epoch: int + ) -> Mapping[CalibrationBucket, tuple[FrontierPoint, ...]]: ... + def load_device_machine_factor( + self, identity: DeviceIdentity, epoch: int + ) -> float | None: ... + def widen_device_frontier( + self, + identity: DeviceIdentity, + epoch: int, + bucket: CalibrationBucket, + point: FrontierPoint, + *, + priced_gib: float, + generation_id: str | None, + conv_vae: bool = False, + ) -> tuple[FrontierPoint, ...] | None: + """The bucket's frontier after adding ``point``; None when a stored point covers it.""" + ... + + +class Store(CalibrationStore, Protocol): def get_assistant_run(self, run_id: str) -> AssistantRunRecord | None: ... def get_latest_assistant_run(self, conversation_id: str) -> AssistantRunRecord | None: ... def insert_assistant_run(self, run: AssistantRunRecord, *, title: str, after: str | None, queued: bool = False) -> bool: ... @@ -66,9 +91,10 @@ def insert_generation( *, contract_version: int = 1, generation_id: str | None = None, + lane: str = LOCAL_LANE, ) -> GenerationRecord: ... - def has_queued(self) -> bool: ... - def claim_next_queued(self) -> GenerationRecord | None: ... + def has_queued(self, lane: str = LOCAL_LANE) -> bool: ... + def claim_next_queued(self, lane: str = LOCAL_LANE) -> GenerationRecord | None: ... def dashboard( self, *, @@ -80,8 +106,14 @@ def list_queue_generations(self) -> list[QueueGenerationRecord]: ... def reorder_queued_generation( self, generation_id: str, before_generation_id: str | None ) -> GenerationRecord: ... - def request_generation_cancellation(self, generation_id: str) -> GenerationRecord: ... - def retry_generation(self, generation_id: str) -> GenerationRecord: ... + def request_generation_cancellation( + self, generation_id: str, *, uncancellable_lanes: Collection[str] = () + ) -> GenerationRecord: + """Raises StatusError for a running job on one of uncancellable_lanes.""" + ... + def retry_generation( + self, generation_id: str, lane: str | None = None + ) -> GenerationRecord: ... def mark_succeeded( self, generation_id: str, @@ -117,4 +149,21 @@ def delete_asset(self, asset_id: str) -> bool: Canonical and thumbnail unlinks are best-effort after commit.""" ... def fail_running_on_boot(self) -> int: ... + def reassign_unknown_lanes(self, known: Collection[str]) -> int: ... + def set_provider_job_id( + self, generation_id: str, attempt_count: int, provider_job_id: str + ) -> bool: + """Record the id of a running attempt at its provider. False when it is not running.""" + ... + def clear_provider_job_id(self, generation_id: str, provider_job_id: str) -> bool: + """Forget a provider job once the provider dropped it. False if nothing holds that id.""" + ... + def list_provider_orphans(self) -> list[ProviderOrphan]: + """Jobs that may still run at a provider: an id is stored and not yet cancelled. + + Includes the older attempts that a retry replaced, and deleted rows.""" + ... + def list_displaced_provider_jobs(self, generation_id: str) -> list[ProviderOrphan]: + """The ids of older attempts of one job that a retry replaced and nobody cancelled.""" + ... def unlink_partial_outputs(self, paths: list[str]) -> None: ... diff --git a/backend/services/text_encoder/ltx_text_encoder.py b/backend/services/text_encoder/ltx_text_encoder.py index 3a548ca7f..c1b0b7fcd 100644 --- a/backend/services/text_encoder/ltx_text_encoder.py +++ b/backend/services/text_encoder/ltx_text_encoder.py @@ -90,12 +90,10 @@ def __init__(self, device: torch.device, http: HTTPClient, ltx_api_base_url: str self.ltx_api_base_url = ltx_api_base_url self._prompt_encoder_init_patched = False self._prompt_encoder_patched = False - self._cleanup_memory_patched = False def install_patches(self, state_getter: Callable[[], AppState]) -> None: self._install_prompt_encoder_init_patch() self._install_prompt_encoder_patch(state_getter) - self._install_cleanup_memory_patch(state_getter) def _install_prompt_encoder_init_patch(self) -> None: """Patch PromptEncoder.__init__ to accept a text-encoder-less ModelPaths (API encoding mode). @@ -190,50 +188,6 @@ def patched_call( except Exception as exc: logger.warning("Failed to patch PromptEncoder: %s", exc, exc_info=True) - def _install_cleanup_memory_patch(self, state_getter: Callable[[], AppState]) -> None: - """Patch cleanup_memory to move cached text encoder to CPU before cleanup.""" - if self._cleanup_memory_patched: - return - - try: - from ltx_pipelines.utils import helpers as ltx_utils - - original_cleanup_memory = ltx_utils.cleanup_memory - - def patched_cleanup_memory() -> None: - state = state_getter() - te_state = state.text_encoder - if te_state is not None and te_state.cached_encoder is not None: - try: - te_state.cached_encoder.to(torch.device("cpu")) - except Exception: - logger.warning("Failed to move cached text encoder to CPU", exc_info=True) - original_cleanup_memory() - - setattr(ltx_utils, "cleanup_memory", patched_cleanup_memory) - - for module_name in ( - "ltx_pipelines.utils.helpers", - "ltx_pipelines.distilled", - "ltx_pipelines.ti2vid_one_stage", - "ltx_pipelines.ti2vid_two_stages", - "ltx_pipelines.ic_lora", - "ltx_pipelines.a2vid_two_stage", - "ltx_pipelines.retake", - "ltx_pipelines.retake_pipeline", - ): - try: - module = __import__(module_name, fromlist=["cleanup_memory"]) - if hasattr(module, "cleanup_memory"): - setattr(module, "cleanup_memory", patched_cleanup_memory) - except Exception: - logger.warning("Failed to patch cleanup_memory for module %s", module_name, exc_info=True) - - self._cleanup_memory_patched = True - logger.info("Installed cleanup_memory patch") - except Exception as exc: - logger.warning("Failed to patch cleanup_memory: %s", exc, exc_info=True) - def get_model_id_from_checkpoint(self, checkpoint_path: str) -> str | None: try: from safetensors import safe_open diff --git a/backend/services/thumbnails.py b/backend/services/thumbnails.py index 5afc44708..1ae85aad1 100644 --- a/backend/services/thumbnails.py +++ b/backend/services/thumbnails.py @@ -23,6 +23,17 @@ _ALPHA_FRAME_TIMEOUT_SECONDS = 30.0 +def resolve_stored_thumbnail(assets_dir: Path, stored: str | None) -> Path | None: + """Thumbnail path for a stored value. Old rows hold an absolute path, so only the + file name is used. A name that is empty, ``.`` or ``..`` is rejected (CWE-22).""" + if stored is None: + return None + name = Path(stored).name + if name in ("", ".", ".."): + return None + return assets_dir / name + + class ThumbnailWriter(Protocol): def write(self, source_path: str, media_kind: MediaKind) -> str | None: """JPEG path beside the media, or None (audio / failure). Never raises.""" diff --git a/backend/services/unavailable_store.py b/backend/services/unavailable_store.py index 5313969cb..97372bf86 100644 --- a/backend/services/unavailable_store.py +++ b/backend/services/unavailable_store.py @@ -1,14 +1,16 @@ from __future__ import annotations -from collections.abc import Collection +from collections.abc import Collection, Mapping from datetime import datetime from typing import NoReturn from pydantic import JsonValue +from runtime_config.device_calibration import CalibrationBucket, DeviceIdentity, FrontierPoint from services.dashboard_stats import DashboardSnapshot, DashboardWindow from services.records import ( + LOCAL_LANE, AssetListPage, AssetRecord, AssistantQueueRecord, @@ -17,6 +19,7 @@ GenerationRecord, MediaKind, OutputSpec, + ProviderOrphan, QueueGenerationRecord, UnavailableError, ) @@ -118,13 +121,14 @@ def insert_generation( *, contract_version: int = 1, generation_id: str | None = None, + lane: str = LOCAL_LANE, ) -> GenerationRecord: _unavailable() - def has_queued(self) -> bool: + def has_queued(self, lane: str = LOCAL_LANE) -> bool: _unavailable() - def claim_next_queued(self) -> GenerationRecord | None: + def claim_next_queued(self, lane: str = LOCAL_LANE) -> GenerationRecord | None: _unavailable() def dashboard( @@ -146,11 +150,15 @@ def reorder_queued_generation( del generation_id, before_generation_id _unavailable() - def request_generation_cancellation(self, generation_id: str) -> GenerationRecord: - del generation_id + def request_generation_cancellation( + self, generation_id: str, *, uncancellable_lanes: Collection[str] = () + ) -> GenerationRecord: + del generation_id, uncancellable_lanes _unavailable() - def retry_generation(self, generation_id: str) -> GenerationRecord: + def retry_generation( + self, generation_id: str, lane: str | None = None + ) -> GenerationRecord: _unavailable() def mark_succeeded( @@ -203,5 +211,52 @@ def delete_asset(self, asset_id: str) -> bool: def fail_running_on_boot(self) -> int: return 0 + def load_device_frontier( + self, identity: DeviceIdentity, epoch: int + ) -> Mapping[CalibrationBucket, tuple[FrontierPoint, ...]]: + del identity, epoch + return {} + + def load_device_machine_factor( + self, identity: DeviceIdentity, epoch: int + ) -> float | None: + del identity, epoch + return None + + def widen_device_frontier( + self, + identity: DeviceIdentity, + epoch: int, + bucket: CalibrationBucket, + point: FrontierPoint, + *, + priced_gib: float, + generation_id: str | None, + conv_vae: bool = False, + ) -> tuple[FrontierPoint, ...] | None: + del identity, epoch, bucket, point, priced_gib, generation_id, conv_vae + return None + + def reassign_unknown_lanes(self, known: Collection[str]) -> int: + del known + return 0 + + def set_provider_job_id( + self, generation_id: str, attempt_count: int, provider_job_id: str + ) -> bool: + del generation_id, attempt_count, provider_job_id + return False + + def clear_provider_job_id(self, generation_id: str, provider_job_id: str) -> bool: + del generation_id, provider_job_id + return False + + def list_provider_orphans(self) -> list[ProviderOrphan]: + return [] + + def list_displaced_provider_jobs(self, generation_id: str) -> list[ProviderOrphan]: + del generation_id + return [] + def unlink_partial_outputs(self, paths: list[str]) -> None: del paths diff --git a/backend/services/url_downloader/__init__.py b/backend/services/url_downloader/__init__.py new file mode 100644 index 000000000..b098eebeb --- /dev/null +++ b/backend/services/url_downloader/__init__.py @@ -0,0 +1,4 @@ +from services.url_downloader.hf_model_card import CardSuggestions, parse_model_card +from services.url_downloader.url_downloader import UrlDownloader, UrlDownloadError + +__all__ = ["CardSuggestions", "UrlDownloader", "UrlDownloadError", "parse_model_card"] diff --git a/backend/services/url_downloader/hf_model_card.py b/backend/services/url_downloader/hf_model_card.py new file mode 100644 index 000000000..489fc059f --- /dev/null +++ b/backend/services/url_downloader/hf_model_card.py @@ -0,0 +1,302 @@ +"""Suggestions for the custom LoRA form, read from a Hugging Face model card. + +A model card is a README with an optional YAML header. Three things in it help prompt +enhancement: the trigger word, a short description, and example prompts. The reader never +fails: a card that has none of them gives empty suggestions, and the user fills the form. + +- Trigger: a YAML key (``instance_prompt`` / ``trigger_word``), an explicit ``Trigger word:`` + or ``Trained words:`` label, or the first value under a ``# Trigger Word`` heading. +- Examples: the YAML ``widget`` texts, ``Example prompt: "..."`` lines, or the lines under an + ``# Example Prompts`` heading. +- Description: the first plain paragraph before the first section heading, or under a heading + such as ``Model description``. Generated boilerplate gives no description. +""" + +from __future__ import annotations + +import re +from dataclasses import dataclass +from typing import cast + +import yaml + +from api_types import ( + CUSTOM_LORA_DESCRIPTION_MAX, + CUSTOM_LORA_EXAMPLE_MAX, + CUSTOM_LORA_EXAMPLES_MAX, + CUSTOM_LORA_TRIGGER_MAX, +) + +# TODO(security): CWE-400 (resource exhaustion). The card is untrusted text. ``yaml.safe_load`` +# builds plain data only (no Python objects, CWE-502). The header is cut to this size so a +# crafted header cannot make the parser run long. Every pattern below is linear: none nests a +# repeat inside a repeat. +_MAX_HEADER_CHARS = 32 * 1024 +_MAX_TRIGGER_WORDS = 6 +_SECTION_SCAN_LINES = 8 +_TRIGGER_KEYS = ("instance_prompt", "trigger_word") + +_HEADER = re.compile(r"\A---[ \t]*\r?\n(?P
.*?)\r?\n---[ \t]*(?:\r?\n|\Z)", re.DOTALL) +_COMMENT = re.compile(r"", re.DOTALL) +_MARKDOWN_LINK = re.compile(r"\[([^\]]*)\]\([^)]*\)") +_HTML_TAG = re.compile(r"<[^>]*>") +_EMPHASIS = re.compile(r"\*+|__|`") +_BOLD = re.compile(r"\*\*|__") +_LIST_MARKER = re.compile(r"^(?:[-*+]|\d+[.)])\s*") +_CODE_SPAN = re.compile(r"`([^`\n]+)`") +_CONTROL = re.compile(r"[\x00-\x08\x0b-\x1f\x7f]") +_SPACES = re.compile(r"\s+") +_QUOTES = "\"'“”‘’`" + +_TRIGGER_LABEL = ( + r"\b(?:triggers?(?:\s+(?:words?|tokens?|phrases?|keywords?))?" + r"|trained\s+words?|activation\s+(?:words?|tokens?|phrases?)|instance\s+prompt)\b" +) +_TRIGGER_HEADING = re.compile(_TRIGGER_LABEL, re.IGNORECASE) +_COLON = r"\s*[:=]\s*" +_QUOTED = r"(?:\"([^\"\n]+)\"|“([^”\n]+)”|'([^'\n]+)'|`([^`\n]+)`)" +# A quoted value needs no delimiter: ``Trigger word "SPROUT"``. +_TRIGGER_QUOTED = re.compile(rf"{_TRIGGER_LABEL}(?:{_COLON}|\s+){_QUOTED}", re.IGNORECASE) +_TRIGGER_AFTER_COLON = re.compile(rf"{_TRIGGER_LABEL}{_COLON}(?P[^,;()\n\"`“'][^,;()\n]*)", re.IGNORECASE) +# "Trained words" lists the exact words the LoRA was trained with. A descriptive phrase there is the +# trigger, so it needs no code-like shape. +_TRAINED_WORDS = re.compile(r"\btrained\s+words?\s*[:=]\s*(?P[^,\n]+)", re.IGNORECASE) +_NEGATED = re.compile( + r"\b(?:no|without|never|doesn.?t\s+need|does\s+not\s+need)\b[^.\n]{0,25}\btrigger" + r"|\btrigger[^.\n]{0,25}\b(?:not\s+(?:needed|required)|unnecessary)", + re.IGNORECASE, +) +_NOT_A_TRIGGER = frozenset( + {"none", "n/a", "na", "no", "not", "any", "use", "add", "include", "your", "the", "a", "an", "see", "for", "optional", "required", "none."} +) + +_EXAMPLE_LABEL = ( + r"\b(?:(?:example|sample)\s+prompts?|prompts?\s+examples?|an?\s+example\s+of\s+(?:a\s+)?prompt)\b" +) +_EXAMPLE_HEADING = re.compile(_EXAMPLE_LABEL, re.IGNORECASE) +_EXAMPLE_LINE = re.compile(rf"{_EXAMPLE_LABEL}\s*[:=]?\s*(?P[\"“'].+)$", re.IGNORECASE) + +_DESCRIPTION_HEADING = re.compile(r"description|about|overview|introduction|summary|what", re.IGNORECASE) +_METADATA_LINE = re.compile( + r"^(?:base\s+model|trained\s+words?|trigger(?:\s+\w+)?|activation\s+\w+|strength|license|" + r"recommended\s+\w+|steps|seed|(?:example|sample)\s+prompts?|prompt\s+examples?)\s*[:=]", + re.IGNORECASE, +) +_BOILERPLATE = re.compile( + r"lora\s+finetune\s+of\s+model|generated\s+automatically|base\s+template\s+for\s+new\s+models", + re.IGNORECASE, +) +_RULE = re.compile(r"^[-*_]{3,}$") + + +@dataclass(frozen=True, slots=True) +class CardSuggestions: + trigger: str | None = None + description: str = "" + examples: tuple[str, ...] = () + + +def _clean(text: str) -> str: + return _SPACES.sub(" ", _CONTROL.sub("", text)).strip() + + +def _header_and_body(card: str) -> tuple[dict[str, object], str]: + match = _HEADER.match(card) + if match is None: + return {}, _COMMENT.sub("", card) + body = _COMMENT.sub("", card[match.end() :]) + header_text = match.group("header")[:_MAX_HEADER_CHARS] + try: + loaded: object = yaml.safe_load(header_text) + except (yaml.YAMLError, ValueError, RecursionError): + return {}, body + if not isinstance(loaded, dict): + return {}, body + return cast("dict[str, object]", loaded), body + + +def _plain(line: str) -> str: + """One line without bold marks, HTML tags and a list marker.""" + text = _HTML_TAG.sub("", _BOLD.sub("", line)).strip() + return _LIST_MARKER.sub("", text).strip() + + +def _heading_text(line: str) -> str | None: + """The text of a Markdown heading line, or ``None`` for any other line.""" + stripped = line.strip() + if not stripped.startswith("#"): + return None + return _plain(stripped.lstrip("#")) + + +def _trigger_value(raw: str) -> str | None: + """A trigger candidate if it is short and not a sentence or a filler word.""" + value = _clean(raw).strip(_QUOTES + " ,.;:") + if not value or len(value) > CUSTOM_LORA_TRIGGER_MAX: + return None + if len(value.split(" ")) > _MAX_TRIGGER_WORDS or value.lower() in _NOT_A_TRIGGER: + return None + if value.split(" ", 1)[0].lower() in _NOT_A_TRIGGER: + return None + return value + + +def _yaml_trigger(header: dict[str, object]) -> str | None: + for key in _TRIGGER_KEYS: + value = header.get(key) + if isinstance(value, str): + trigger = _trigger_value(value) + if trigger is not None: + return trigger + return None + + +def _trigger_on_line(line: str) -> str | None: + """A trigger named on one line: ``Trigger word: `X` ``, ``Trigger word "X"``, ``Trained words: X``.""" + if _NEGATED.search(line): + return None + trained = _TRAINED_WORDS.search(line) + if trained is not None: + value = _clean(trained.group("v")).strip(_QUOTES + " .;:") + if value and len(value) <= CUSTOM_LORA_TRIGGER_MAX: + return value + quoted = _TRIGGER_QUOTED.search(line) + if quoted is not None: + trigger = _trigger_value(next(group for group in quoted.groups() if group is not None)) + if trigger is not None: + return trigger + after_colon = _TRIGGER_AFTER_COLON.search(line) + if after_colon is not None: + # A list of triggers: the first one is the main one. + trigger = _trigger_value(after_colon.group("v").split(". ")[0]) + if trigger is not None: + return trigger + return None + + +def _section_trigger(line: str) -> str | None: + """The value on one content line under a ``Trigger Word`` heading.""" + if line.startswith(("```", "|", ">")) or line.endswith(":"): + return None + span = _CODE_SPAN.search(line) + if span is not None: + return _trigger_value(span.group(1)) + return _trigger_value(line.split(",")[0]) + + +def _body_trigger(body: str) -> str | None: + in_section = False + scanned = 0 + for raw in body.splitlines(): + heading = _heading_text(raw) + if heading is not None: + in_section = _TRIGGER_HEADING.search(heading) is not None and _NEGATED.search(heading) is None + scanned = 0 + continue + line = _plain(raw) + if not line or line.startswith("|"): + continue + if in_section and scanned < _SECTION_SCAN_LINES: + scanned += 1 + trigger = _section_trigger(line) + if trigger is not None: + return trigger + trigger = _trigger_on_line(line) + if trigger is not None: + return trigger + return None + + +def _widget_examples(header: dict[str, object]) -> list[str]: + widget = header.get("widget") + if not isinstance(widget, list): + return [] + found: list[str] = [] + for entry in cast("list[object]", widget): + text = cast("dict[str, object]", entry).get("text") if isinstance(entry, dict) else None + if isinstance(text, str): + _add_example(found, text) + return found + + +def _add_example(found: list[str], text: str) -> None: + example = _clean(text).strip(_QUOTES + " ") + if example and len(example) <= CUSTOM_LORA_EXAMPLE_MAX and example not in found: + found.append(example) + + +def _body_examples(body: str, found: list[str]) -> None: + """Add ``Example prompt: "..."`` lines and the lines under an ``Example prompts`` heading.""" + in_section = False + scanned = 0 + for raw in body.splitlines(): + if len(found) >= CUSTOM_LORA_EXAMPLES_MAX: + return + heading = _heading_text(raw) + if heading is not None: + in_section = _EXAMPLE_HEADING.search(heading) is not None + scanned = 0 + continue + line = _plain(raw) + if not line or line.startswith(("```", "|", ">")): + continue + if in_section and scanned < _SECTION_SCAN_LINES: + scanned += 1 + if not line.endswith(":"): + _add_example(found, line) + continue + match = _EXAMPLE_LINE.search(line) + if match is not None: + value = match.group("v") + # The example runs from the first quote to the last one on the line. + _add_example(found, value[: max(value.rfind(quote) for quote in "\"”'") + 1] or value) + + +def _is_prose(line: str) -> bool: + """Whether a line is a sentence. Images, tables, HTML, code fences and links alone are not.""" + return not line.startswith(("!", "|", "<", "```", "[![", "http")) and _RULE.match(line) is None + + +def _description(body: str) -> str: + paragraph: list[str] = [] + for raw in body.splitlines(): + heading = _heading_text(raw) + if heading is not None: + if paragraph: + break + # A section heading before any prose ends the search, unless it introduces a description. + if raw.strip().startswith("##") and _DESCRIPTION_HEADING.search(heading) is None: + return "" + continue + line = raw.strip() + if not line or not _is_prose(line): + if paragraph: + break + continue + text = _plain(line) + if _METADATA_LINE.match(text): + if paragraph: + break + continue + if line.startswith(("- ", "* ")) and not paragraph: + continue + paragraph.append(_HTML_TAG.sub("", _MARKDOWN_LINK.sub(r"\1", text))) + text = _clean(_EMPHASIS.sub("", " ".join(paragraph))) + if _BOILERPLATE.search(text): + return "" + if len(text) <= CUSTOM_LORA_DESCRIPTION_MAX: + return text + cut = text[:CUSTOM_LORA_DESCRIPTION_MAX].rsplit(" ", 1)[0] + return cut.rstrip(",;:") + + +def parse_model_card(card: str) -> CardSuggestions: + """The trigger word, description and example prompts a card holds. Missing parts stay empty.""" + header, body = _header_and_body(card) + examples = _widget_examples(header) + _body_examples(body, examples) + return CardSuggestions( + trigger=_yaml_trigger(header) or _body_trigger(body), + description=_description(body), + examples=tuple(examples[:CUSTOM_LORA_EXAMPLES_MAX]), + ) diff --git a/backend/services/url_downloader/public_address_adapter.py b/backend/services/url_downloader/public_address_adapter.py new file mode 100644 index 000000000..94ac24af8 --- /dev/null +++ b/backend/services/url_downloader/public_address_adapter.py @@ -0,0 +1,82 @@ +"""A ``requests`` adapter that connects to public internet addresses only. + +``check_fetch_url`` reads the text of a link. It cannot see where a name points: a public name +can resolve to 127.0.0.1 or to a LAN address. This adapter looks up the name when it opens the +connection, refuses it if any address is not global, and connects to the checked address. The +lookup and the connection use the same address, so a name that answers differently a second +time (DNS rebinding) cannot send the request to a private host. The TLS name check still uses +the host name, so the certificate must match it. + +A proxy would open the connection instead and hide the address from this adapter. +``public_only_session`` therefore turns off ``trust_env``, so the system proxy settings are not used. +""" + +from __future__ import annotations + +import ipaddress +import socket +from collections.abc import Iterable +from typing import Any + +from requests.adapters import HTTPAdapter +from urllib3.connection import HTTPSConnection +from urllib3.connectionpool import HTTPSConnectionPool +from urllib3.exceptions import NewConnectionError +from urllib3.util.connection import create_connection + +from services.url_downloader.url_downloader import UrlDownloadError + +PRIVATE_ADDRESS_MESSAGE = "The link points to this computer or a private network." + + +def public_addresses(host: str, port: int) -> list[str]: + """The addresses of ``host``, or ``UrlDownloadError`` if any of them is not a global address. + + One private address is enough to refuse: a client that tries the addresses in turn would + reach it when the public ones fail. + """ + try: + infos = socket.getaddrinfo(host.rstrip("."), port, type=socket.SOCK_STREAM) + except socket.gaierror as exc: + raise UrlDownloadError("Could not find the server.") from exc + addresses = list(dict.fromkeys(str(info[4][0]).split("%", 1)[0] for info in infos)) + if not addresses or not _all_global(addresses): + raise UrlDownloadError(PRIVATE_ADDRESS_MESSAGE) + return addresses + + +def _all_global(addresses: Iterable[str]) -> bool: + try: + return all(ipaddress.ip_address(address).is_global for address in addresses) + except ValueError: + return False + + +class _PublicOnlyHTTPSConnection(HTTPSConnection): + def _new_conn(self) -> socket.socket: + last_error: OSError | None = None + for address in public_addresses(self.host, self.port): + try: + return create_connection( + (address, self.port), + self.timeout, + source_address=self.source_address, + socket_options=self.socket_options, + ) + except OSError as exc: + last_error = exc + raise NewConnectionError(self, f"Failed to establish a new connection: {last_error}") + + +class _PublicOnlyHTTPSConnectionPool(HTTPSConnectionPool): + # urllib3 types this slot with a protocol that its own HTTPSConnection does not satisfy. + ConnectionCls = _PublicOnlyHTTPSConnection # pyright: ignore[reportAssignmentType] + + +class PublicAddressAdapter(HTTPAdapter): + def init_poolmanager(self, *args: Any, **kwargs: Any) -> None: + super().init_poolmanager(*args, **kwargs) + self.poolmanager.pool_classes_by_scheme = { + **self.poolmanager.pool_classes_by_scheme, + "https": _PublicOnlyHTTPSConnectionPool, + } diff --git a/backend/services/url_downloader/url_downloader.py b/backend/services/url_downloader/url_downloader.py new file mode 100644 index 000000000..20f59108d --- /dev/null +++ b/backend/services/url_downloader/url_downloader.py @@ -0,0 +1,47 @@ +"""URL downloader service protocol definitions.""" + +from __future__ import annotations + +from collections.abc import Callable +from pathlib import Path +from typing import Protocol + +from runtime_config.custom_lora_urls import HuggingFaceRepo + + +class UrlDownloadError(Exception): + """A download that cannot finish. The message is safe to show to the user.""" + + +class UrlDownloader(Protocol): + def list_hugging_face_files(self, repo: HuggingFaceRepo, *, hf_token: str | None) -> list[str]: + """The file names in a Hugging Face model repo, for the revision the link names. + + Raises ``UrlDownloadError`` when the repo is missing, needs access, or the server fails. + """ + ... + + def fetch_hugging_face_card(self, repo: HuggingFaceRepo, *, hf_token: str | None) -> str: + """The README text (the model card) of a Hugging Face model repo, capped in size. + + Returns an empty string when the repo has no README. Raises ``UrlDownloadError`` when the + repo is missing, needs access, or the server fails. + """ + ... + + def download( + self, + url: str, + dest: Path, + *, + hf_token: str | None, + max_bytes: int, + on_progress: Callable[[int, int], None] | None = None, + ) -> None: + """Stream ``url`` to ``dest``. + + ``on_progress`` gets ``(bytes_written, expected_bytes)``; ``expected_bytes`` is 0 when + the server sends no length. Raises ``UrlDownloadError`` on a refused link, a server + error, a sign-in wall, or a file larger than ``max_bytes``. + """ + ... diff --git a/backend/services/url_downloader/url_downloader_impl.py b/backend/services/url_downloader/url_downloader_impl.py new file mode 100644 index 000000000..05cfd3d77 --- /dev/null +++ b/backend/services/url_downloader/url_downloader_impl.py @@ -0,0 +1,217 @@ +"""Streaming URL downloader built on ``requests``.""" + +from __future__ import annotations + +import logging +from collections.abc import Callable +from pathlib import Path +from typing import cast +from urllib.parse import quote, urljoin + +import requests + +from runtime_config.custom_lora_urls import ( + CIVITAI_HOSTS, + CustomLoraUrl, + CustomLoraUrlError, + HuggingFaceRepo, + check_fetch_url, +) +from services.url_downloader.public_address_adapter import PublicAddressAdapter +from services.url_downloader.url_downloader import UrlDownloadError + +logger = logging.getLogger(__name__) + +_CHUNK_BYTES = 1024 * 1024 +_MAX_REDIRECTS = 5 +_REDIRECT_STATUSES = frozenset({301, 302, 303, 307, 308}) +# (connect, read) seconds. The read timeout applies to each chunk, not to the whole file. +_TIMEOUT = (10, 60) +# A model card is a few kilobytes. The cap stops a repo that serves a huge README. +_MAX_CARD_BYTES = 256 * 1024 + + +def _check(url: str) -> CustomLoraUrl: + try: + return check_fetch_url(url) + except CustomLoraUrlError as exc: + raise UrlDownloadError(str(exc)) from exc + + +def _auth_error(host: str) -> UrlDownloadError: + if host in CIVITAI_HOSTS: + return UrlDownloadError( + "Civitai needs a sign-in for this file. Download it in your browser, " + "then add it as a file." + ) + return UrlDownloadError( + "The server needs a sign-in for this file. Download it in your browser, " + "then add it as a file." + ) + + +def public_only_session() -> requests.Session: + """A session that opens connections to public addresses only (see ``PublicAddressAdapter``).""" + session = requests.Session() + # TODO(security): CWE-918. With a system proxy, the proxy opens the connection and the adapter + # cannot see its address. Ignore HTTPS_PROXY, ALL_PROXY and .netrc so every connection is ours. + # A user behind a mandatory proxy adds the file instead of a link. + session.trust_env = False + session.mount("https://", PublicAddressAdapter()) + return session + + +class UrlDownloaderImpl: + def __init__(self, session_factory: Callable[[], requests.Session] = public_only_session) -> None: + # Tests pass a session with a fake transport. The default checks every address it connects to. + self._session_factory = session_factory + + def list_hugging_face_files(self, repo: HuggingFaceRepo, *, hf_token: str | None) -> list[str]: + revision = quote(repo.revision, safe="") + # The host is fixed, so this request never follows a user-supplied address. + url = f"https://huggingface.co/api/models/{repo.repo_id}/revision/{revision}" + headers = {"User-Agent": "LTX-Desktop"} + if hf_token is not None: + headers["Authorization"] = f"Bearer {hf_token}" + try: + with self._session_factory() as session: + response = session.get(url, headers=headers, allow_redirects=False, timeout=_TIMEOUT) + except requests.exceptions.RequestException as exc: + logger.warning("Could not reach Hugging Face to list %s", repo.repo_id) + raise UrlDownloadError("Could not reach Hugging Face.") from exc + with response: + if response.status_code in (401, 403): + raise UrlDownloadError( + "This Hugging Face repository needs access. Sign in to Hugging Face in " + "Settings > Models and accept its license on the model page." + ) + if response.status_code == 404: + raise UrlDownloadError("The Hugging Face repository was not found.") + if response.status_code in _REDIRECT_STATUSES: + # A renamed or moved repository answers with a redirect. The link is not followed. + raise UrlDownloadError("The repository moved. Copy the new link from the model page.") + if response.status_code != 200: + raise UrlDownloadError(f"Hugging Face answered with status {response.status_code}.") + try: + payload: object = response.json() + except ValueError as exc: + raise UrlDownloadError("Hugging Face sent an answer that could not be read.") from exc + siblings = cast("dict[str, object]", payload).get("siblings") if isinstance(payload, dict) else None + if not isinstance(siblings, list): + raise UrlDownloadError("Hugging Face sent an answer that could not be read.") + names: list[str] = [] + for sibling in cast("list[object]", siblings): + name = cast("dict[str, object]", sibling).get("rfilename") if isinstance(sibling, dict) else None + if isinstance(name, str): + names.append(name) + return names + + def fetch_hugging_face_card(self, repo: HuggingFaceRepo, *, hf_token: str | None) -> str: + revision = quote(repo.revision, safe="") + # The host is fixed, so this request never follows a user-supplied address. + url = f"https://huggingface.co/{repo.repo_id}/raw/{revision}/README.md" + headers = {"User-Agent": "LTX-Desktop"} + if hf_token is not None: + headers["Authorization"] = f"Bearer {hf_token}" + try: + with self._session_factory() as session: + response = session.get( + url, headers=headers, allow_redirects=False, timeout=_TIMEOUT, stream=True + ) + with response: + if response.status_code == 404: + return "" + if response.status_code in (401, 403): + raise UrlDownloadError("This Hugging Face repository needs access.") + if response.status_code != 200: + raise UrlDownloadError(f"Hugging Face answered with status {response.status_code}.") + data = bytearray() + for chunk in response.iter_content(chunk_size=16 * 1024): + data.extend(chunk) + if len(data) >= _MAX_CARD_BYTES: + break + except requests.exceptions.RequestException as exc: + logger.warning("Could not reach Hugging Face to read the card of %s", repo.repo_id) + raise UrlDownloadError("Could not reach Hugging Face.") from exc + return bytes(data[:_MAX_CARD_BYTES]).decode("utf-8", errors="replace") + + def download( + self, + url: str, + dest: Path, + *, + hf_token: str | None, + max_bytes: int, + on_progress: Callable[[int, int], None] | None = None, + ) -> None: + current = _check(url) + # One session for the whole redirect chain. A streamed response needs it open until saved. + with self._session_factory() as session: + for _ in range(_MAX_REDIRECTS + 1): + # Built again for each hop, so the token never reaches a redirect target such as a + # signed CDN URL. + headers = {"User-Agent": "LTX-Desktop"} + if hf_token is not None and current.is_hugging_face: + headers["Authorization"] = f"Bearer {hf_token}" + try: + response = session.get( + current.url, + headers=headers, + stream=True, + allow_redirects=False, + timeout=_TIMEOUT, + ) + except requests.exceptions.RequestException as exc: + logger.warning("Custom LoRA download could not reach %s", current.host) + raise UrlDownloadError("Could not reach the server.") from exc + with response: + if response.status_code in _REDIRECT_STATUSES: + location = response.headers.get("Location") + if not location: + raise UrlDownloadError("The server sent a bad redirect.") + current = _check(urljoin(current.url, location)) + continue + self._save(response, current, dest, max_bytes, on_progress) + return + raise UrlDownloadError("The link redirects too many times.") + + @staticmethod + def _save( + response: requests.Response, + source: CustomLoraUrl, + dest: Path, + max_bytes: int, + on_progress: Callable[[int, int], None] | None, + ) -> None: + status = response.status_code + if status in (401, 403): + raise _auth_error(source.host) + if status == 404: + raise UrlDownloadError("The file was not found at this link.") + if status != 200: + raise UrlDownloadError(f"The server answered with status {status}.") + if "text/html" in response.headers.get("Content-Type", "").lower(): + # A web page, not a file: most often a sign-in or error page. + raise UrlDownloadError("The link opens a web page, not a file.") + length_header = response.headers.get("Content-Length", "") + expected = int(length_header) if length_header.isdigit() else 0 + if expected > max_bytes: + raise UrlDownloadError("The file is too large for a LoRA.") + written = 0 + try: + with open(dest, "wb") as out: + for data in response.iter_content(chunk_size=_CHUNK_BYTES): + if not data: + continue + written += len(data) + if written > max_bytes: + raise UrlDownloadError("The file is too large for a LoRA.") + out.write(data) + if on_progress is not None: + on_progress(written, expected) + except requests.exceptions.RequestException as exc: + raise UrlDownloadError("The download was interrupted.") from exc + # A compressed transfer is decoded on the fly, so its byte count never matches the header. + compressed = bool(response.headers.get("Content-Encoding")) + if expected and not compressed and written != expected: + raise UrlDownloadError("The download was interrupted.") diff --git a/backend/services/zit_api_client/zit_api_client.py b/backend/services/zit_api_client/zit_api_client.py index 1fb24aade..57cd4568f 100644 --- a/backend/services/zit_api_client/zit_api_client.py +++ b/backend/services/zit_api_client/zit_api_client.py @@ -2,8 +2,23 @@ from __future__ import annotations +from collections.abc import Callable +from dataclasses import dataclass from typing import Protocol +from api_types import ApiActivityStatus + + +class ZitImageBlockedError(RuntimeError): + """The provider returned no usable image because its safety checker blocked the prompt.""" + + +@dataclass(frozen=True) +class ZitQueuedImage: + image_bytes: bytes + # The prompt the provider used. It differs from the sent one when it expanded the prompt. + prompt: str | None + class ZitAPIClient(Protocol): def generate_text_to_image( @@ -16,6 +31,41 @@ def generate_text_to_image( seed: int, num_inference_steps: int, ) -> bytes: + """One blocking request. A safety-checker block returns the provider's placeholder image.""" + ... + + def generate_text_to_image_queued( + self, + *, + api_key: str, + prompt: str, + width: int, + height: int, + seed: int, + num_inference_steps: int, + enable_prompt_expansion: bool, + on_status: Callable[[ApiActivityStatus], None], + on_submitted: Callable[[str], bool], + wait_cancelled: Callable[[float], bool], + ) -> ZitQueuedImage: + """Submit to the provider queue, poll, and fetch the result. + + ``on_submitted(request_id)`` runs right after the provider accepts the request and + before the first status check. It returns False when the id was not stored. A boot + cannot then cancel the request, so it is cancelled at once and the call raises. + + ``wait_cancelled(seconds)`` sleeps and returns True once the caller cancelled. The + request is then cancelled at the provider (best effort) and GenerationCancelledError + is raised. A safety-checker block raises ZitImageBlockedError. + """ + ... + + def cancel_queued(self, *, api_key: str, request_id: str) -> None: + """Ask the provider to drop a queued request. Safe to repeat. + + A request that already finished or is unknown counts as dropped. Any other failure + raises, so the caller keeps the request id and tries again later. + """ ... def generate_image_to_image( diff --git a/backend/services/zit_api_client/zit_api_client_impl.py b/backend/services/zit_api_client/zit_api_client_impl.py index 2884a2e6b..fe498a810 100644 --- a/backend/services/zit_api_client/zit_api_client_impl.py +++ b/backend/services/zit_api_client/zit_api_client_impl.py @@ -3,24 +3,71 @@ from __future__ import annotations import base64 +import logging +import re +import time +from collections.abc import Callable from typing import Any, cast +from urllib.parse import urlsplit -from services.http_client.http_client import HTTPClient +from api_types import ApiActivityStatus +from services.generation_interrupt import GenerationCancelledError +from services.http_client.http_client import ( + HTTPClient, + HttpBodyTooLargeError, + HttpRedirectRefusedError, + HttpTransportError, +) +from services.zit_api_client.zit_api_client import ZitImageBlockedError, ZitQueuedImage from services.services_utils import JSONValue +logger = logging.getLogger(__name__) + FAL_API_BASE_URL = "https://fal.run" +FAL_QUEUE_BASE_URL = "https://queue.fal.run" FAL_TEXT_TO_IMAGE_ENDPOINT = "/fal-ai/z-image/turbo" +# The app id of the queued endpoint. fal puts it, not the sub-path, in the request URLs. +FAL_QUEUE_APP = "/".join(FAL_TEXT_TO_IMAGE_ENDPOINT.split("/")[:3]) FAL_IMAGE_TO_IMAGE_ENDPOINT = "/fal-ai/z-image/turbo/image-to-image" DEFAULT_OUTPUT_FORMAT = "png" DEFAULT_ACCELERATION = "regular" DEFAULT_ENABLE_SAFETY_CHECKER = True +QUEUE_POLL_INTERVAL_SECONDS = 1.0 +# A request that waits or runs longer than this fails the job. +QUEUE_TIMEOUT_SECONDS = 600.0 +# Status checks that fail in a row before the job fails. One dropped poll is not an error. +_MAX_CONSECUTIVE_STATUS_FAILURES = 3 +# Shorter than the fal lane stop grace, so a cancel at shutdown can finish inside it. +_PROVIDER_CANCEL_TIMEOUT_SECONDS = 4 +# The largest image the app reads from fal. A Z-Image PNG at the top size is a few MB. +_MAX_IMAGE_DOWNLOAD_BYTES = 50 * 1024 * 1024 + +# A fal request id is a UUID. It goes into a URL path, so nothing else is accepted. +_REQUEST_ID = re.compile(r"[A-Za-z0-9-]{1,100}") + +_STATUS_TO_API_STATUS: dict[str, ApiActivityStatus] = { + "IN_QUEUE": "pending", + "IN_PROGRESS": "processing", +} + class ZitAPIClientImpl: - def __init__(self, http: HTTPClient, *, fal_api_base_url: str = FAL_API_BASE_URL) -> None: + def __init__( + self, + http: HTTPClient, + *, + fal_api_base_url: str = FAL_API_BASE_URL, + fal_queue_base_url: str = FAL_QUEUE_BASE_URL, + queue_poll_interval_seconds: float = QUEUE_POLL_INTERVAL_SECONDS, + queue_timeout_seconds: float = QUEUE_TIMEOUT_SECONDS, + ) -> None: self._http = http self._base_url = fal_api_base_url.rstrip("/") + self._queue_base_url = fal_queue_base_url.rstrip("/") + self._poll_interval = queue_poll_interval_seconds + self._queue_timeout = queue_timeout_seconds def generate_text_to_image( self, @@ -32,20 +79,68 @@ def generate_text_to_image( seed: int, num_inference_steps: int, ) -> bytes: - payload: dict[str, JSONValue] = { - "prompt": prompt, - "image_size": {"width": width, "height": height}, - "num_inference_steps": num_inference_steps, - "seed": seed, - "num_images": 1, - "output_format": DEFAULT_OUTPUT_FORMAT, - "acceleration": DEFAULT_ACCELERATION, - "enable_safety_checker": DEFAULT_ENABLE_SAFETY_CHECKER, - } - return self._submit_and_download( - endpoint=FAL_TEXT_TO_IMAGE_ENDPOINT, - api_key=api_key, - payload=payload, + payload = self._text_to_image_payload( + prompt=prompt, + width=width, + height=height, + seed=seed, + num_inference_steps=num_inference_steps, + # fal defaults this to false. The explicit value keeps GenSpace off the paid expansion. + enable_prompt_expansion=False, + ) + response_payload = self._post_blocking( + endpoint=FAL_TEXT_TO_IMAGE_ENDPOINT, api_key=api_key, payload=payload + ) + return self._download(self._extract_image_url(response_payload)) + + def generate_text_to_image_queued( + self, + *, + api_key: str, + prompt: str, + width: int, + height: int, + seed: int, + num_inference_steps: int, + enable_prompt_expansion: bool, + on_status: Callable[[ApiActivityStatus], None], + on_submitted: Callable[[str], bool], + wait_cancelled: Callable[[float], bool], + ) -> ZitQueuedImage: + payload = self._text_to_image_payload( + prompt=prompt, + width=width, + height=height, + seed=seed, + num_inference_steps=num_inference_steps, + enable_prompt_expansion=enable_prompt_expansion, + ) + submitted = self._submit_queued(api_key, payload) + headers = self._json_headers(api_key) + try: + # The id must be stored before the first status request. A boot cannot cancel a + # request it has no id for, so a request that is not recorded is dropped now. + if not on_submitted(submitted["request_id"]): + raise RuntimeError("FAL request id was not stored, so the request was cancelled") + # A cancel that landed during the submit must not start a status request first. + self._raise_if_cancelled(wait_cancelled) + self._wait_until_completed( + submitted, headers, on_status=on_status, wait_cancelled=wait_cancelled + ) + self._raise_if_cancelled(wait_cancelled) + result = self._fetch_result(submitted["response_url"], headers) + self._raise_if_cancelled(wait_cancelled) + except Exception: + # Cancel, timeout and every failure free the provider side too. Best effort. + self._cancel_at_provider(submitted["cancel_url"], headers) + raise + if self._is_blocked(result): + raise ZitImageBlockedError("FAL safety checker blocked the image") + image = self._download(self._extract_image_url(result)) + used = result.get("prompt") + return ZitQueuedImage( + image_bytes=image, + prompt=used if isinstance(used, str) and used.strip() else None, ) def generate_image_to_image( @@ -70,19 +165,37 @@ def generate_image_to_image( "acceleration": DEFAULT_ACCELERATION, "enable_safety_checker": DEFAULT_ENABLE_SAFETY_CHECKER, } - return self._submit_and_download( - endpoint=FAL_IMAGE_TO_IMAGE_ENDPOINT, - api_key=api_key, - payload=payload, + response_payload = self._post_blocking( + endpoint=FAL_IMAGE_TO_IMAGE_ENDPOINT, api_key=api_key, payload=payload ) + return self._download(self._extract_image_url(response_payload)) - def _submit_and_download( - self, + @staticmethod + def _text_to_image_payload( *, - endpoint: str, - api_key: str, - payload: dict[str, JSONValue], - ) -> bytes: + prompt: str, + width: int, + height: int, + seed: int, + num_inference_steps: int, + enable_prompt_expansion: bool, + ) -> dict[str, JSONValue]: + # One builder for the blocking and the queued request, so the two cannot drift. + return { + "prompt": prompt, + "image_size": {"width": width, "height": height}, + "num_inference_steps": num_inference_steps, + "seed": seed, + "num_images": 1, + "output_format": DEFAULT_OUTPUT_FORMAT, + "acceleration": DEFAULT_ACCELERATION, + "enable_safety_checker": DEFAULT_ENABLE_SAFETY_CHECKER, + "enable_prompt_expansion": enable_prompt_expansion, + } + + def _post_blocking( + self, *, endpoint: str, api_key: str, payload: dict[str, JSONValue] + ) -> dict[str, Any]: response = self._http.post( f"{self._base_url}{endpoint}", headers=self._json_headers(api_key), @@ -92,14 +205,131 @@ def _submit_and_download( if response.status_code != 200: detail = response.text[:500] if response.text else "Unknown error" raise RuntimeError(f"FAL submit failed ({response.status_code}): {detail}") + return self._json_object(response.json(), context="submit") + + def _submit_queued(self, api_key: str, payload: dict[str, JSONValue]) -> dict[str, str]: + response = self._http.post( + f"{self._queue_base_url}{FAL_TEXT_TO_IMAGE_ENDPOINT}", + headers=self._json_headers(api_key), + json_payload=payload, + timeout=60, + ) + if response.status_code != 200: + detail = response.text[:500] if response.text else "Unknown error" + raise RuntimeError(f"FAL submit failed ({response.status_code}): {detail}") + body = self._json_object(response.json(), context="submit") + # Use the URLs fal returns. For an endpoint with a sub-path they differ from a built URL. + # Every later request sends the API key, so a URL on another host is refused. + queue_origin = urlsplit(self._queue_base_url)[:2] + urls: dict[str, str] = {} + for key in ("status_url", "response_url", "cancel_url"): + value = body.get(key) + if not isinstance(value, str) or not value: + raise RuntimeError(f"FAL queue response missing {key}") + if urlsplit(value)[:2] != queue_origin: + raise RuntimeError(f"FAL queue response has a {key} on an unexpected host") + urls[key] = value + request_id = body.get("request_id") + if not isinstance(request_id, str) or not _REQUEST_ID.fullmatch(request_id): + raise RuntimeError("FAL queue response has no usable request_id") + urls["request_id"] = request_id + return urls + + def _wait_until_completed( + self, + submitted: dict[str, str], + headers: dict[str, str], + *, + on_status: Callable[[ApiActivityStatus], None], + wait_cancelled: Callable[[float], bool], + ) -> None: + deadline = time.monotonic() + self._queue_timeout + failures = 0 + while True: + try: + status = self._poll_status(submitted["status_url"], headers) + except (HttpTransportError, RuntimeError) as exc: + failures += 1 + if failures >= _MAX_CONSECUTIVE_STATUS_FAILURES: + raise RuntimeError(f"FAL status check failed: {exc}") from exc + else: + failures = 0 + if status.get("status") == "COMPLETED": + error = status.get("error") + if error: + raise RuntimeError(f"FAL request failed: {str(error)[:500]}") + return + on_status(_STATUS_TO_API_STATUS.get(str(status.get("status")), "pending")) + if time.monotonic() >= deadline: + raise RuntimeError("FAL request timed out") + if wait_cancelled(self._poll_interval): + raise GenerationCancelledError() + + @staticmethod + def _raise_if_cancelled(wait_cancelled: Callable[[float], bool]) -> None: + """A cancel that lands during a request must not start the next, longer one.""" + if wait_cancelled(0): + raise GenerationCancelledError() + + def _poll_status(self, status_url: str, headers: dict[str, str]) -> dict[str, Any]: + response = self._http.get(status_url, headers=headers, timeout=30) + if response.status_code not in (200, 202): + detail = response.text[:200] if response.text else "Unknown error" + raise RuntimeError(f"({response.status_code}) {detail}") + try: + body = response.json() + except ValueError as exc: + # A proxy page with status 200 is a transient failure, like a bad status code. + raise RuntimeError("FAL status response is not JSON") from exc + return self._json_object(body, context="status") + + def _fetch_result(self, response_url: str, headers: dict[str, str]) -> dict[str, Any]: + response = self._http.get(response_url, headers=headers, timeout=60) + if response.status_code != 200: + detail = response.text[:500] if response.text else "Unknown error" + raise RuntimeError(f"FAL result failed ({response.status_code}): {detail}") + return self._json_object(response.json(), context="result") + + def cancel_queued(self, *, api_key: str, request_id: str) -> None: + """Drop a request that a stopped app left at fal. Used at boot, with only the id. - response_payload = self._json_object(response.json(), context="submit") - image_url = self._extract_image_url(response_payload) + Only the text-to-image endpoint is queued. fal builds its request URLs from the app id + (the first two path segments), not from the sub-path, so the URL is derived from that. + 202 (cancelling), 400 (already completed) and 404 (unknown or expired) all mean there + is nothing left to drop. + """ + if not _REQUEST_ID.fullmatch(request_id): + raise ValueError("not a fal request id") + response = self._http.put( + f"{self._queue_base_url}{FAL_QUEUE_APP}/requests/{request_id}/cancel", + headers=self._json_headers(api_key), + timeout=_PROVIDER_CANCEL_TIMEOUT_SECONDS, + ) + if response.status_code not in (200, 202, 400, 404): + raise RuntimeError(f"FAL cancel failed ({response.status_code})") - download = self._http.get(image_url, timeout=120) + def _cancel_at_provider(self, cancel_url: str, headers: dict[str, str]) -> None: + """Ask fal to drop the request. 202 and 400 ALREADY_COMPLETED are both fine.""" + try: + self._http.put(cancel_url, headers=headers, timeout=_PROVIDER_CANCEL_TIMEOUT_SECONDS) + except Exception as exc: + logger.warning("FAL cancel request failed: %s", exc) + + def _download(self, image_url: str) -> bytes: + # The URL comes from the fal response. Refuse a plain-http URL (CWE-918) and cap the + # body (CWE-770). The error text has the status only, not the body (CWE-209). + if urlsplit(image_url).scheme != "https": + raise RuntimeError("FAL image URL is not https") + try: + download = self._http.get( + image_url, timeout=120, max_bytes=_MAX_IMAGE_DOWNLOAD_BYTES + ) + except HttpBodyTooLargeError as exc: + raise RuntimeError("FAL image is too large") from exc + except HttpRedirectRefusedError as exc: + raise RuntimeError("FAL image redirect refused") from exc if download.status_code != 200: - detail = download.text[:500] if download.text else "Unknown error" - raise RuntimeError(f"FAL image download failed ({download.status_code}): {detail}") + raise RuntimeError(f"FAL image download failed ({download.status_code})") if not download.content: raise RuntimeError("FAL image download returned empty body") return download.content @@ -111,6 +341,14 @@ def _json_headers(api_key: str) -> dict[str, str]: "Content-Type": "application/json", } + @staticmethod + def _is_blocked(payload: dict[str, Any]) -> bool: + flags = payload.get("has_nsfw_concepts") + if isinstance(flags, list) and any(flag is True for flag in cast(list[object], flags)): + return True + images = payload.get("images") + return isinstance(images, list) and not images + @staticmethod def _extract_image_url(payload: dict[str, Any]) -> str: images = payload.get("images") diff --git a/backend/state/app_settings.py b/backend/state/app_settings.py index 4685eb8ba..45b6022f4 100644 --- a/backend/state/app_settings.py +++ b/backend/state/app_settings.py @@ -9,6 +9,7 @@ from api_types import LTXLocalModelId, LocalAssistantModel from runtime_config.reject_reasons import BudgetMode +from services.fast_video_pipeline.nag_config import DEFAULT_SCALE as DEFAULT_NAG_SCALE, MAX_SCALE as MAX_NAG_SCALE RemoteExposure = Literal["off", "lan"] DashboardRange = Literal["7d", "30d", "all"] @@ -23,8 +24,12 @@ def _parse_remote_exposure(value: object) -> RemoteExposure: RemoteExposureSetting = Annotated[RemoteExposure, BeforeValidator(_parse_remote_exposure)] -def _parse_budget_mode(value: object) -> BudgetMode: - return "standard" if value == "standard" else "reckless" +def _parse_budget_mode(value: object) -> object: + """None passes through, so a settings patch without a mode leaves the saved + one alone. Legacy spellings ("standard", "reckless") and junk map to Brave.""" + if value is None: + return None + return "cautious" if value == "cautious" else "brave" BudgetModeSetting = Annotated[BudgetMode, BeforeValidator(_parse_budget_mode)] @@ -68,6 +73,11 @@ class SettingsPatchModel(SettingsBaseModel): extra="forbid", ) + @field_validator("budget_mode", mode="before", check_fields=False) + @classmethod + def _fold_legacy_budget_mode(cls, value: object) -> object: + return _parse_budget_mode(value) + SelectionValues = list[Annotated[str, StringConstraints(max_length=64)]] @@ -99,7 +109,14 @@ class GenerationSeedUpdate(SettingsBaseModel): class AppSettings(SettingsBaseModel): use_torch_compile: bool = False diffusion_stage_cache_enabled: bool = False - budget_mode: BudgetModeSetting = "reckless" + # EXPERIMENTAL (Apple Silicon): decode the conv VAE with per-tap conv2d instead of MPS conv3d. + mps_conv3d_as_conv2d_enabled: bool = False + budget_mode: BudgetModeSetting = "brave" + # Brave's generate-time risk confirm. Turning "Ask before risky generate" + # back on in Settings is the reset. + skip_budget_risk_confirm: bool = False + # Fast clips run in one pass, never in windows (parts), unless a request asks for parts. + never_split_into_parts: bool = False ltx_api_key: str = "" user_prefers_ltx_api_video_generations: bool = False fal_api_key: str = "" @@ -111,6 +128,8 @@ class AppSettings(SettingsBaseModel): prompt_enhancer_enabled: bool = True # Home / Remote Explore: automatic prompt rewrite before Generate. Gen Space is unchanged. explore_auto_enhance_prompts: bool = True + # Shows the Advanced section of Refine Details. Other features ignore it for now. + advanced_controls: bool = False # The user's explicit choice, persisted so it survives restarts. None means no active choice # has been made yet — the UI defaults to whichever provider is available, preferring local, # without writing that default back here. Only an explicit user pick (not an automatic @@ -131,12 +150,23 @@ class AppSettings(SettingsBaseModel): active_ltx_model_id: LTXLocalModelId | None = None # None = platform default (Mac on, CUDA/Linux off). An explicit bool is a user override. use_conv_vae: bool | None = None + nag_scale: float = DEFAULT_NAG_SCALE + # Show the "Negative prompt strength" row (presets and raw NAG scale, alpha, tau) under + # the negative prompt on Home features. Off by default. Remote follows it through the + # prompt enhancer status, so the phone shows the row only when the Desktop does. + show_nag_strength_controls: bool = False # Remote client HTTP server. Serving only when this is not off. Default off so a leftover # settings.json cannot expose the engine after an upgrade. Unknown values (PoC tunnel modes) # coerce to off. remote_exposure: RemoteExposureSetting = "off" activity_dashboard_selections: DashboardSelection = Field(default_factory=DashboardSelection) + @field_validator("budget_mode", mode="before") + @classmethod + def _stored_null_budget_mode_is_brave(cls, value: object) -> object: + """A stored null must not fail the whole settings load.""" + return "brave" if value is None else value + @field_validator("prompt_cache_size", mode="before") @classmethod def _clamp_prompt_cache_size(cls, value: Any) -> int: @@ -147,6 +177,14 @@ def _clamp_prompt_cache_size(cls, value: Any) -> int: def _clamp_locked_seed(cls, value: Any) -> int: return _clamp_int(value, minimum=0, maximum=MAX_GENERATION_SEED, default=42) + @field_validator("nag_scale", mode="before") + @classmethod + def _clamp_nag_scale(cls, value: Any) -> float: + if value is None: + return DEFAULT_NAG_SCALE + parsed = float(value) + return max(0.0, min(MAX_NAG_SCALE, parsed)) + @field_validator("activity_dashboard_selections", mode="before") @classmethod def _tolerate_unknown_dashboard_range(cls, value: object) -> object: @@ -206,7 +244,10 @@ def _is_settings_model_annotation(annotation: object) -> TypeGuard[type[Settings class SettingsResponse(SettingsBaseModel): use_torch_compile: bool = False diffusion_stage_cache_enabled: bool = False - budget_mode: BudgetModeSetting = "reckless" + mps_conv3d_as_conv2d_enabled: bool = False + budget_mode: BudgetMode = "brave" + skip_budget_risk_confirm: bool = False + never_split_into_parts: bool = False has_ltx_api_key: bool = False user_prefers_ltx_api_video_generations: bool = False has_fal_api_key: bool = False @@ -215,6 +256,7 @@ class SettingsResponse(SettingsBaseModel): prompt_cache_size: int = 100 prompt_enhancer_enabled: bool = True explore_auto_enhance_prompts: bool = True + advanced_controls: bool = False prompt_enhancer_provider_preference: Literal["local", "api"] | None = None has_gemini_api_key: bool = False gemini_model: str = "" @@ -226,6 +268,8 @@ class SettingsResponse(SettingsBaseModel): models_dir: str = "" active_ltx_model_id: LTXLocalModelId | None = None use_conv_vae: bool = False + nag_scale: float = DEFAULT_NAG_SCALE + show_nag_strength_controls: bool = False remote_exposure: RemoteExposureSetting = "off" activity_dashboard_selections: DashboardSelection = Field(default_factory=DashboardSelection) @@ -234,10 +278,12 @@ def remote_is_on(exposure: RemoteExposure) -> bool: return exposure != "off" -def resolved_use_conv_vae(settings: AppSettings) -> bool: +def resolved_use_conv_vae(settings: AppSettings, *, system: str | None = None) -> bool: """Effective Fast decode setting: user override, else Mac on / CUDA off.""" if settings.use_conv_vae is not None: return settings.use_conv_vae + if system is not None: + return system == "Darwin" return sys.platform == "darwin" diff --git a/backend/state/app_state_types.py b/backend/state/app_state_types.py index 508c991f1..cf4706cee 100644 --- a/backend/state/app_state_types.py +++ b/backend/state/app_state_types.py @@ -3,9 +3,15 @@ from __future__ import annotations from dataclasses import dataclass, field -from typing import TYPE_CHECKING, NewType, Protocol, Union +import time +from typing import TYPE_CHECKING, NewType, Union from api_types import AssistantModelDownloadProgress, LTXLocalModelId, ModelCheckpointID +from runtime_config.device_calibration import ( + EMPTY_CALIBRATION, + DeviceCalibration, + RunMemoryBaseline, +) from runtime_config.eta import WallTimeEstimate from runtime_config.ic_lora_tiling import IcLoraTiling from runtime_config.runtime_policy import LocalGenerationMode @@ -78,6 +84,8 @@ class CatalogDownloadSession: downloaded_bytes: int expected_bytes: int speed_bytes_per_sec: float = 0.0 + last_sample_time: float = field(default_factory=time.monotonic) + last_sample_bytes: int = 0 def _default_completed_ic_lora_download_sessions() -> dict[DownloadSessionId, DownloadSessionResult]: @@ -88,6 +96,10 @@ def _default_completed_lora_download_sessions() -> dict[DownloadSessionId, Downl return {} +def _default_completed_custom_lora_import_sessions() -> dict[DownloadSessionId, DownloadSessionResult]: + return {} + + # ============================================================ # Text encoding # ============================================================ @@ -99,11 +111,6 @@ class TextEncodingResult: audio_context: torch.Tensor | None -class CachedTextEncoder(Protocol): - def to(self, device: torch.device) -> "CachedTextEncoder": - ... - - def _new_prompt_cache() -> dict[tuple[str, bool, str], TextEncodingResult]: return {} @@ -113,7 +120,6 @@ class TextEncoderState: service: TextEncoder prompt_cache: dict[tuple[str, bool, str], TextEncodingResult] = field(default_factory=_new_prompt_cache) api_embeddings: TextEncodingResult | None = None - cached_encoder: CachedTextEncoder | None = None # ============================================================ @@ -211,6 +217,12 @@ class GenerationRunning: # Whole-run wall-time estimate fixed at start (ETA v1: local Fast video on # measured hardware only). None means unknown, not zero. estimated: WallTimeEstimate | None = None + # Memory sampled at start for device calibration; None when the device is unknown. + memory_baseline: RunMemoryBaseline | None = None + started_monotonic: float | None = None + decode_started_monotonic: float | None = None + # Fast decode setting this run decodes with; calibration inverts its wall time with it. + conv_vae: bool = False @dataclass @@ -317,6 +329,12 @@ class AppState: default_factory=_default_completed_ic_lora_download_sessions ) lora_download_session: CatalogDownloadSession | None = None + # A custom LoRA import (file copy or URL download). One at a time, with its own slot so it + # never blocks a catalog download. ``item_id`` is the custom LoRA id. + custom_lora_import_session: CatalogDownloadSession | None = None + completed_custom_lora_import_sessions: dict[DownloadSessionId, DownloadSessionResult] = field( + default_factory=_default_completed_custom_lora_import_sessions + ) assistant_model_download: AssistantModelDownloadProgress | None = None completed_lora_download_sessions: dict[DownloadSessionId, DownloadSessionResult] = field( default_factory=_default_completed_lora_download_sessions @@ -338,3 +356,6 @@ class AppState: # pipeline.generate() is still on the GPU; the next Start double-loads weights # (meta vs cuda:0). generation_in_flight: bool = False + # Replaced wholesale (never mutated) from the store's post-commit frontier, + # so budget gates read it without the lock. + device_calibration: DeviceCalibration = EMPTY_CALIBRATION diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index 5efdc0be5..cead6aeaf 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -10,7 +10,16 @@ from app_factory import create_app from app_handler import ServiceBundle -from api_types import AudioToVideoParams, GenerateVideoCompleteResponse, GenerateVideoRequest +from api_types import ( + AudioToVideoParams, + GenerateVideoCompleteResponse, + GenerateVideoRequest, + TextToImageStoredParams, +) +from handlers.queued_image_handler import QueuedImageHandler +import runtime_config.video_job_budget as video_job_budget +from runtime_config.budget_admission import RiskAllowance +from runtime_config.reject_reasons import PassShape from runtime_config.model_download_specs import ( DEPTH_PROCESSOR_CP_ID, IMG_GEN_MODEL_CP_ID, @@ -24,8 +33,10 @@ from state.app_settings import AppSettings from state.app_state_types import HfAuthenticated from services.features.ic_lora_recipes import queued_ic_lora_recipes +from services.features.image.text_to_image import QueuedImageResult, TextToImageExecutor from services.features.lora_recipes import queued_lora_recipes -from services.features.video import AudioToVideoExecutor +from services.features.video import AudioToVideoExecutor, KeyframesExecutor +from services.generation_queue.sessions import JobSession from services.gemini_text_client import clear_gemini_models_cache from services.sqlite_store import SqliteStore from tests.fake_camera_motion_prompts import FAKE_CAMERA_MOTION_PROMPTS @@ -37,9 +48,8 @@ "excessive noise, grainy texture" ) -# The app defaults to reckless, but these suites assert the standard refusals the -# budget layer still implements. Tests that need reckless set it explicitly. -DEFAULT_APP_SETTINGS = AppSettings(budget_mode="standard") +# Cautious is the strict refusal surface most budget tests assert; Brave cases set it. +DEFAULT_APP_SETTINGS = AppSettings(budget_mode="cautious") class _UnusedReservedVideoGenerator: @@ -48,9 +58,13 @@ def models_dir(self) -> Path: return Path("/unused-reserved-video-generator") def validate_local_a2v_request( - self, params: AudioToVideoParams, audio_duration_ms: int + self, + params: AudioToVideoParams, + audio_duration_ms: int, + *, + pass_shape: PassShape, ) -> None: - del params, audio_duration_ms + del params, audio_duration_ms, pass_shape def generate_local_reserved( self, @@ -62,16 +76,37 @@ def generate_local_reserved( a2v_num_frames: int | None = None, a2v_audio_duration_seconds: float | None = None, local_model_id=None, - risk_allowance: bool | None = None, - unmeasured_bet: bool = False, + allowance: RiskAllowance | None = None, + pass_shape: PassShape | None = None, ) -> GenerateVideoCompleteResponse: - del req, generation_id, prompt_wrap, a2v_num_frames, a2v_audio_duration_seconds, local_model_id, risk_allowance, unmeasured_bet + del req, generation_id, prompt_wrap, a2v_num_frames, a2v_audio_duration_seconds, local_model_id, allowance + del pass_shape return GenerateVideoCompleteResponse( status="complete", video_path=str(output_path) if output_path is not None else "", ) +class _AppImageRenderer: + """Defers to the AppHandler's image handler, which is built after the executors.""" + + def __init__(self) -> None: + self.target: QueuedImageHandler | None = None + + def generate_queued( + self, + params: TextToImageStoredParams, + *, + generation_id: str, + output_path: Path, + session: JobSession, + ) -> QueuedImageResult: + assert self.target is not None + return self.target.generate_queued( + params, generation_id=generation_id, output_path=output_path, session=session + ) + + @pytest.fixture(autouse=True) def _reset_generation_interrupt() -> None: from services.generation_interrupt import clear @@ -95,8 +130,14 @@ def fake_services() -> FakeServices: return FakeServices() +@pytest.fixture +def parallel_lanes(request: pytest.FixtureRequest) -> bool: + """On by default. A test turns the kill switch on with indirect parametrization.""" + return getattr(request, "param", True) + + @pytest.fixture(autouse=True) -def test_state(tmp_path: Path, fake_services: FakeServices): +def test_state(tmp_path: Path, fake_services: FakeServices, parallel_lanes: bool): """Provide a fresh AppHandler per test and register it in DI.""" clear_gemini_models_cache() app_data = tmp_path / "app_data" @@ -114,6 +155,7 @@ def test_state(tmp_path: Path, fake_services: FakeServices): settings_file=app_data / "settings.json", ltx_api_base_url="https://api.ltx.video", local_generations_mode="full_models_loading", + parallel_queue_lanes=parallel_lanes, vram_gb=31, use_sage_attention=False, camera_motion_prompts=FAKE_CAMERA_MOTION_PROMPTS, @@ -124,6 +166,7 @@ def test_state(tmp_path: Path, fake_services: FakeServices): ) store = SqliteStore(config.app_data_dir) + image_renderer = _AppImageRenderer() bundle = ServiceBundle( assistant_provider=fake_services.assistant_provider, assistant_models=fake_services.assistant_models, @@ -135,6 +178,7 @@ def test_state(tmp_path: Path, fake_services: FakeServices): video_processor=fake_services.video_processor, text_encoder=fake_services.text_encoder, task_runner=fake_services.task_runner, + url_downloader=fake_services.url_downloader, ltx_api_client=fake_services.ltx_api_client, zit_api_client=fake_services.zit_api_client, fast_video_pipeline_class=type(fake_services.fast_video_pipeline), @@ -147,8 +191,10 @@ def test_state(tmp_path: Path, fake_services: FakeServices): prompt_enhancer_pipeline_class=type(fake_services.prompt_enhancer_pipeline), store=store, generation_executors={ + "text-to-image": TextToImageExecutor(image_renderer), "text-to-video": FakeGenerationExecutor(), "image-to-video": FakeGenerationExecutor(), + "custom-lora": FakeGenerationExecutor(feature="custom-lora"), # Injecting generation_executors skips AppHandler's real per-recipe # registration loop, so mirror it from the recipe table — a new recipe # then can't 422 at validate_params for a missing executor. @@ -163,6 +209,8 @@ def test_state(tmp_path: Path, fake_services: FakeServices): "audio-to-video": AudioToVideoExecutor( _UnusedReservedVideoGenerator(), store ), + # The real executor, so the queue refuses a bad timeline at create time. + "keyframes": KeyframesExecutor(_UnusedReservedVideoGenerator(), store), "retake": FakeGenerationExecutor(feature="retake"), "extend": FakeGenerationExecutor(feature="extend"), }, @@ -173,6 +221,7 @@ def test_state(tmp_path: Path, fake_services: FakeServices): DEFAULT_APP_SETTINGS.model_copy(deep=True), service_bundle=bundle, ) + image_renderer.target = handler.queued_image handler.state.hf_auth_state = HfAuthenticated( access_token="fake-hf-token", expires_at=1e18, @@ -306,3 +355,11 @@ def _make(w: int = 64, h: int = 64, color: str = "red"): return buf return _make + + +@pytest.fixture +def single_pass_only(monkeypatch: pytest.MonkeyPatch) -> None: + """Price the single-pass envelope: the window fallback is off, so a pass that no card + can hold keeps its refusal. Tests of one-pass cell boundaries use this; the window + picker has its own tests.""" + monkeypatch.setattr(video_job_budget, "_windows_help", lambda *_a, **_k: False) diff --git a/backend/tests/fakes/fake_gpu_info.py b/backend/tests/fakes/fake_gpu_info.py index 963d20724..502fadc42 100644 --- a/backend/tests/fakes/fake_gpu_info.py +++ b/backend/tests/fakes/fake_gpu_info.py @@ -4,6 +4,8 @@ from collections.abc import Callable +from runtime_config.device_calibration import RunMemoryBaseline, RunMemoryEnd +from services.gpu_info import run_peak from services.interfaces import GpuTelemetryPayload @@ -25,6 +27,11 @@ def __init__(self) -> None: # one gate call, so a static field cannot model the freed memory). self.free_vram_bytes_fn: Callable[[], int | None] | None = None self.live_allocated_bytes_fn: Callable[[], int | None] | None = None + self.swap_used_bytes: int | None = None + # What the run watch reports at the end; all-None reads as no evidence. + self.run_end = RunMemoryEnd( + peak_reserved_bytes=None, min_free_vram_bytes=None, swap_used_bytes=None + ) def get_gpu_info(self) -> GpuTelemetryPayload: return self.gpu_info @@ -68,3 +75,18 @@ def get_cuda_reserved_bytes(self) -> int | None: def get_mps_pool_bytes(self) -> int | None: return self.mps_pool_bytes + + def get_swap_used_bytes(self) -> int | None: + return self.swap_used_bytes + + def begin_run_memory_watch(self) -> RunMemoryBaseline: + run_peak.begin_run() + return RunMemoryBaseline( + free_vram_bytes=self.get_free_cuda_vram_bytes(), + reserved_bytes=self.reserved_bytes, + swap_used_bytes=self.swap_used_bytes, + ) + + def end_run_memory_watch(self) -> RunMemoryEnd: + run_peak.end_run() + return self.run_end diff --git a/backend/tests/fakes/generation.py b/backend/tests/fakes/generation.py index 98b745096..100d405d5 100644 --- a/backend/tests/fakes/generation.py +++ b/backend/tests/fakes/generation.py @@ -12,8 +12,10 @@ from PIL import Image from api_types import ( + ApiActivityStatus, IcLoraRecipeInputs, IcLoraVideoRecipeStoredParams, + QueueProgress, IcLoraSheetInputs, IcLoraSynthesizedStoredParams, IcLoraTrackInputs, @@ -28,6 +30,8 @@ from services.features.ic_lora_recipes import get_ic_lora_recipe from services.generation_interrupt import GenerationCancelledError, is_requested from services.features.video import require_supported_contract_version +from services.generation_queue.control import QueueLiveState +from services.generation_queue.sessions import JobProgress, JobSession, LocalGenerationOps, LocalJobSession from services.generation_queue.types import ExecutionOutcome, OutputAllocation, OutputPlan from services.records import GenerationRecord @@ -130,6 +134,7 @@ def execute( self, generation: GenerationRecord, outputs: tuple[OutputAllocation, ...], + session: JobSession, ) -> ExecutionOutcome: if self._seen_prompts is not None: prompt = _spec_params(generation.spec).get("prompt") @@ -143,3 +148,93 @@ def execute( for allocation in outputs: _write_valid_output(allocation) return ExecutionOutcome() + + +class FakeJobSession: + """A JobSession that records cancellation and nothing else. For executors under test.""" + + def __init__(self, generation_id: str = "test-generation") -> None: + self._generation_id = generation_id + self.cancelled = False + self.progress_updates: list[tuple[str, int]] = [] + self.provider_job_ids: list[str] = [] + + @property + def generation_id(self) -> str: + return self._generation_id + + @property + def holds_gpu_slot(self) -> bool: + return False + + def start_api(self) -> None: + return None + + def set_progress( + self, + phase: str, + progress: int, + current_step: int | None = None, + total_steps: int | None = None, + ) -> None: + del current_step, total_steps + self.progress_updates.append((phase, progress)) + + def set_api_status(self, status: ApiActivityStatus) -> None: + del status + + def set_provider_job_id(self, provider_job_id: str) -> bool: + self.provider_job_ids.append(provider_job_id) + return True + + def progress(self) -> JobProgress | None: + return None + + def api_status(self) -> ApiActivityStatus | None: + return None + + def raise_if_cancelled(self) -> None: + if self.cancelled: + raise GenerationCancelledError() + + def wait_cancelled(self, timeout: float) -> bool: + del timeout + return self.cancelled + + def cancel(self) -> None: + self.cancelled = True + + def complete(self, result: str | list[str] | None) -> None: + del result + + def fail(self, error: str) -> None: + del error + + +class LocalLiveQueueControl: + """A queue control for tests that run no runner: it reads progress from the shared slot.""" + + def __init__(self, generation: LocalGenerationOps) -> None: + self._generation = generation + + def wake(self) -> None: + return None + + def interrupt(self, generation_id: str, attempt_count: int) -> None: + del generation_id, attempt_count + + def live_state(self, generation_id: str) -> QueueLiveState: + progress = LocalJobSession(self._generation, generation_id).progress() + return QueueLiveState( + progress=None + if progress is None + else QueueProgress( + phase=progress.phase, + progress=progress.progress, + currentStep=progress.current_step, + totalSteps=progress.total_steps, + remainingSeconds=progress.remaining_seconds, + ), + api_status=None, + cancellable=True, + ) diff --git a/backend/tests/fakes/lanes.py b/backend/tests/fakes/lanes.py new file mode 100644 index 000000000..9f8384b2e --- /dev/null +++ b/backend/tests/fakes/lanes.py @@ -0,0 +1,19 @@ +"""A second lane for tests. Production registers only the local lane.""" + +from __future__ import annotations + +from services.generation_queue.lanes import LaneSpec + +TEST_LANE = "test-remote" + +# A provider-like lane: no GPU, one job at a time, a short stop grace. +TEST_LANE_SPEC = LaneSpec( + id=TEST_LANE, + concurrency=1, + uses_gpu=False, + cancellable_while_running=True, + stop_grace_seconds=5.0, +) + +# The feature name tests give to jobs that run on the test lane. +TEST_FEATURE = "remote-feature" diff --git a/backend/tests/fakes/services.py b/backend/tests/fakes/services.py index 19f5e496b..46d164f40 100644 --- a/backend/tests/fakes/services.py +++ b/backend/tests/fakes/services.py @@ -14,6 +14,7 @@ from frame_math import AutoDurationSpec from ltx_pipelines.utils.types import OffloadMode from api_types import ( + ApiActivityStatus, ExtendMode, ImageConditioningInput, InstructionSection, @@ -29,10 +30,16 @@ RetakeMode, VideoCameraMotion, ) +from runtime_config.custom_lora_urls import HuggingFaceRepo from runtime_config.ic_lora_tiling import IcLoraTiling +from services.fast_video_pipeline.nag_config import NagConfig +from services.generation_interrupt import GenerationCancelledError +from services.http_client import HttpBodyTooLargeError from services.interfaces import VideoInfoPayload from services.ltx_api_client.ltx_api_client import LTXRetakeResult from services.prompt_enhancement.i2v_frames import SceneFrame, VideoRole +from services.url_downloader import UrlDownloadError +from services.zit_api_client.zit_api_client import ZitQueuedImage from tests.fakes.assistant import FakeAssistantModels, FakeAssistantProvider from tests.fakes.fake_gpu_info import FakeGpuInfo @@ -68,6 +75,7 @@ class HttpCall: json_payload: dict[str, Any] | None data: Any timeout: int + max_bytes: int | None = None class FakeHTTPClient: @@ -107,9 +115,13 @@ def get( url: str, headers: dict[str, str] | None = None, timeout: int = 30, + max_bytes: int | None = None, ) -> FakeResponse: - self.calls.append(HttpCall("get", url, headers, None, None, timeout)) - return self._dequeue("get") + self.calls.append(HttpCall("get", url, headers, None, None, timeout, max_bytes)) + response = self._dequeue("get") + if max_bytes is not None and len(response.content) > max_bytes: + raise HttpBodyTooLargeError(f"Response is larger than {max_bytes} bytes") + return response def put( self, @@ -146,6 +158,50 @@ def run_background( on_error(exc) +class FakeUrlDownloader: + """Writes ``payload`` to the destination. Set ``error`` to refuse the download. + + ``repo_files`` is what a Hugging Face repo lists. Set ``list_error`` to refuse the listing. + ``card_text`` is the README. Set ``card_error`` to refuse it. + """ + + def __init__(self) -> None: + self.payload: bytes = b"" + self.error: UrlDownloadError | None = None + self.repo_files: list[str] = [] + self.list_error: UrlDownloadError | None = None + self.card_text: str = "" + self.card_error: UrlDownloadError | None = None + + def fetch_hugging_face_card(self, repo: HuggingFaceRepo, *, hf_token: str | None) -> str: + del repo, hf_token + if self.card_error is not None: + raise self.card_error + return self.card_text + + def list_hugging_face_files(self, repo: HuggingFaceRepo, *, hf_token: str | None) -> list[str]: + del hf_token + if self.list_error is not None: + raise self.list_error + return list(self.repo_files) + + def download( + self, + url: str, + dest: Path, + *, + hf_token: str | None, + max_bytes: int, + on_progress: Callable[[int, int], None] | None = None, + ) -> None: + del url, hf_token, max_bytes + if self.error is not None: + raise self.error + dest.write_bytes(self.payload) + if on_progress is not None: + on_progress(len(self.payload), len(self.payload)) + + class FakeLTXAPIClient: def __init__(self) -> None: self.upload_file_calls: list[dict[str, Any]] = [] @@ -335,6 +391,15 @@ def __init__(self) -> None: self.raise_on_text_to_image: Exception | None = None self.fail_text_to_image_after: int | None = None # raise once len(calls) exceeds this self.text_to_image_result = b"fake-zit-api-image" + # Queued requests stay open until `queued_release` is set. Set it by default. + self.queued_entered = threading.Event() + self.queued_release = threading.Event() + self.queued_release.set() + self.queued_provider_prompt: str | None = None + # Requests the client cancelled at the provider, and the ids a boot asked to cancel. + self.cancelled_request_ids: list[str] = [] + self.cancel_queued_calls: list[str] = [] + self.raise_on_cancel_queued: Exception | None = None self.image_to_image_calls: list[dict[str, Any]] = [] self.raise_on_image_to_image: Exception | None = None self.fail_image_to_image_after: int | None = None # raise once len(calls) exceeds this @@ -353,6 +418,60 @@ def generate_text_to_image( seed: int, num_inference_steps: int, ) -> bytes: + self._record_text_to_image( + api_key, prompt, width, height, seed, num_inference_steps, enable_prompt_expansion=False + ) + return self.text_to_image_result + + def generate_text_to_image_queued( + self, + *, + api_key: str, + prompt: str, + width: int, + height: int, + seed: int, + num_inference_steps: int, + enable_prompt_expansion: bool, + on_status: Callable[[ApiActivityStatus], None], + on_submitted: Callable[[str], bool], + wait_cancelled: Callable[[float], bool], + ) -> ZitQueuedImage: + self._record_text_to_image( + api_key, prompt, width, height, seed, num_inference_steps, enable_prompt_expansion + ) + request_id = f"fake-fal-{len(self.text_to_image_calls)}" + if not on_submitted(request_id): + self.cancelled_request_ids.append(request_id) + raise RuntimeError("FAL request id was not stored, so the request was cancelled") + self.queued_entered.set() + on_status("pending") + # Hold the request open until the test releases it or the job is cancelled. + while not self.queued_release.is_set(): + if wait_cancelled(0.01): + raise GenerationCancelledError() + on_status("processing") + return ZitQueuedImage( + image_bytes=self.text_to_image_result, + prompt=self.queued_provider_prompt, + ) + + def cancel_queued(self, *, api_key: str, request_id: str) -> None: + del api_key + self.cancel_queued_calls.append(request_id) + if self.raise_on_cancel_queued is not None: + raise self.raise_on_cancel_queued + + def _record_text_to_image( + self, + api_key: str, + prompt: str, + width: int, + height: int, + seed: int, + num_inference_steps: int, + enable_prompt_expansion: bool, + ) -> None: self.text_to_image_calls.append( { "api_key": api_key, @@ -361,12 +480,12 @@ def generate_text_to_image( "height": height, "seed": seed, "num_inference_steps": num_inference_steps, + "enable_prompt_expansion": enable_prompt_expansion, } ) if self.raise_on_text_to_image is not None: if self.fail_text_to_image_after is None or len(self.text_to_image_calls) > self.fail_text_to_image_after: raise self.raise_on_text_to_image - return self.text_to_image_result def generate_image_to_image( self, @@ -909,6 +1028,7 @@ def generate( guide_all_images: bool = False, skip_stage_2: bool = False, chunk_pixel_frames: int | None = None, + nag: NagConfig | None = None, ) -> None: payload = { "prompt": prompt, @@ -922,6 +1042,7 @@ def generate( "guide_all_images": guide_all_images, "skip_stage_2": skip_stage_2, "chunk_pixel_frames": chunk_pixel_frames, + "nag": nag, } if self.inference_steps: from services.generation_interrupt import raise_if_requested @@ -1027,8 +1148,21 @@ def __init__(self) -> None: self.raise_on_enhance: Exception | None = None self.enhanced_prompt: str = "enhanced prompt" - def enhance_t2v(self, prompt: str, system_prompt: str | None, seed: int) -> str: - self.enhance_t2v_calls.append({"prompt": prompt, "system_prompt": system_prompt, "seed": seed}) + def enhance_t2v( + self, + prompt: str, + system_prompt: str | None, + seed: int, + negative_prompt: str = "", + ) -> str: + self.enhance_t2v_calls.append( + { + "prompt": prompt, + "negative_prompt": negative_prompt, + "system_prompt": system_prompt, + "seed": seed, + } + ) if self.raise_on_enhance is not None: raise self.raise_on_enhance return self.enhanced_prompt @@ -1043,10 +1177,12 @@ def enhance_i2v( keyframes: list[tuple[str, int, float]] | None = None, duration: int | None = None, fps: int | None = None, + negative_prompt: str = "", ) -> str: self.enhance_i2v_calls.append( { "prompt": prompt, + "negative_prompt": negative_prompt, "image_path": image_path, "last_image_path": last_image_path, "keyframes": keyframes, @@ -1067,11 +1203,13 @@ def enhance_with_video_frames( system_prompt: str | None, seed: int, role: VideoRole, + negative_prompt: str = "", ) -> str: # The frame files are temporary, so a test reads what they were while the call runs. self.enhance_video_frames_calls.append( { "prompt": prompt, + "negative_prompt": negative_prompt, "frame_times": [frame.time_seconds for frame in frames], "frame_paths": [frame.path for frame in frames], "look_images": sum(1 for frame in frames if frame.is_reference), @@ -1380,6 +1518,7 @@ class FakeServices: video_processor: FakeVideoProcessor = field(default_factory=FakeVideoProcessor) text_encoder: FakeTextEncoder = field(default_factory=FakeTextEncoder) task_runner: FakeTaskRunner = field(default_factory=FakeTaskRunner) + url_downloader: FakeUrlDownloader = field(default_factory=FakeUrlDownloader) ltx_api_client: FakeLTXAPIClient = field(default_factory=FakeLTXAPIClient) zit_api_client: FakeZitAPIClient = field(default_factory=FakeZitAPIClient) fast_video_pipeline: FakeFastVideoPipeline = field(default_factory=FakeFastVideoPipeline) diff --git a/backend/tests/test_alpha_cutout.py b/backend/tests/test_alpha_cutout.py index 880bb00ff..372ba6fea 100644 --- a/backend/tests/test_alpha_cutout.py +++ b/backend/tests/test_alpha_cutout.py @@ -29,6 +29,7 @@ from services.features.video.ic_lora_recipe import IcLoraRecipeExecutor from services.media_probe import video_frame_count from services.generation_queue.types import OutputAllocation +from tests.fakes.generation import FakeJobSession from services.records import AssetRecord, GenerationRecord _SOURCE_RGB = (200, 40, 40) @@ -322,7 +323,7 @@ def get_asset(self, asset_id: str) -> AssetRecord | None: ("matte", "video/mp4"), ("gif", "image/gif"), ] - executor.execute(generation, outputs) + executor.execute(generation, outputs, FakeJobSession()) return outputs diff --git a/backend/tests/test_analytics.py b/backend/tests/test_analytics.py index dfd0539f7..6c31ab4b9 100644 --- a/backend/tests/test_analytics.py +++ b/backend/tests/test_analytics.py @@ -6,10 +6,7 @@ import pytest from api_model_specs import video_generation_feature -from handlers.prompt_enhancement_handler import ( - ResolvedGenerationPrompt, - prompt_provenance_label, -) +from handlers.resolved_generation_prompt import ResolvedGenerationPrompt, prompt_provenance_label from services.analytics import ( ENDED_DETAIL_KEYS, AnalyticsService, @@ -196,7 +193,7 @@ def test_started_detail_keys_match_the_shared_contract() -> None: A writer key missing from shared/generation-detail-keys.json is silently dropped from generate_started; a contract key nothing emits is dead. - outcome/runtime_ms/error_code/output_count are ended-only by design. + outcome/runtime_ms/error_code/output_count/prompt_rewrite are ended-only by design. """ record = _home_record( feature="text-to-video", @@ -224,7 +221,13 @@ def test_started_detail_keys_match_the_shared_contract() -> None: assert details is not None contract_path = Path(__file__).resolve().parents[2] / "shared" / "generation-detail-keys.json" contract = set(json.loads(contract_path.read_text())) - assert set(details) == contract - {"outcome", "runtime_ms", "error_code", "output_count"} + assert set(details) == contract - { + "outcome", + "runtime_ms", + "error_code", + "output_count", + "prompt_rewrite", + } def test_video_generation_feature_prefers_keyframes_then_audio() -> None: @@ -488,6 +491,49 @@ def test_ended_event_keeps_load_and_offload_modes() -> None: assert ended["offload_mode"] == "DISK" +def test_a_fal_image_job_with_no_enhancer_is_auto_enhanced_by_fal_expansion() -> None: + # Bug caught: a fal job that fal expands is reported as raw when no local or Gemini rewrite exists. + no_enhancer = QueuedEnhancement( + explore_auto_enhance_prompts=True, prompt_enhancer_enabled=False, use_local_encoding=False + ) + auto_off = QueuedEnhancement( + explore_auto_enhance_prompts=False, prompt_enhancer_enabled=False, use_local_encoding=False + ) + + def image(provider: str, provenance: str = "typed") -> GenerationRecord: + return _home_record( + feature="text-to-image", + params={"prompt": "a fox", "promptProvenance": provenance, "provider": provider}, + ) + + def label(record: GenerationRecord, enhancement: QueuedEnhancement) -> object: + return (queued_generation_details(record, enhancement=enhancement) or {})["prompt_provenance"] + + assert label(image("fal"), no_enhancer) == "auto-enhanced" + assert label(image("local"), no_enhancer) == "raw" + assert label(image("fal"), auto_off) == "raw" + assert label(image("fal", "enhanced"), no_enhancer) == "manually-enhanced" + + +def test_ended_event_keeps_the_prompt_rewrite_source() -> None: + # Bug caught: the rewrite source is dropped by the ended allowlist, so fal expansion cost + # cannot be told apart from a free local or Gemini rewrite. + http = FakeHTTPClient() + http.queue("post", FakeResponse()) + service = _service(http) + record = _home_record(feature="text-to-image", params={"prompt": "a fox"}) + details = queued_generation_details(record, modes={"prompt_rewrite": "fal_expansion"}) + assert details is not None + + service.send_generation_ended(details, outcome="succeeded", runtime_ms=1000) + + payload = http.calls[0].json_payload + assert payload is not None + ended = payload["extraDetails"] + assert isinstance(ended, dict) + assert ended["prompt_rewrite"] == "fal_expansion" + + def test_extend_with_gemini_video_enhance_is_auto_enhanced_even_with_api_text_encoding() -> None: extend = _home_record( feature="extend", diff --git a/backend/tests/test_reckless_mode.py b/backend/tests/test_budget_mode.py similarity index 79% rename from backend/tests/test_reckless_mode.py rename to backend/tests/test_budget_mode.py index c4fe0e177..e02322086 100644 --- a/backend/tests/test_reckless_mode.py +++ b/backend/tests/test_budget_mode.py @@ -1,4 +1,4 @@ -"""Reckless-mode warning tier: setting, gates, annotations, execute downgrade.""" +"""Brave/Cautious budget mode: setting, gates, annotations, execute downgrade.""" from __future__ import annotations @@ -32,11 +32,9 @@ VideoAssetMetadata, VideoMeta, ) -from runtime_config.ic_lora_job_budget import ( - REFINE_DECODE_FLOOR_MESSAGE, - TWO_STAGE_OVER_MEASURED_MESSAGE, - iclora_drop_risk_tier, -) +from runtime_config.budget_admission import RiskAllowance, unmeasured_refusal_message +from runtime_config.reject_reasons import PassShape +from runtime_config.ic_lora_job_budget import REFINE_DECODE_FLOOR_MESSAGE from runtime_config.ic_lora_tiling import IcLoraTiling from frame_math import compute_num_frames from runtime_config.ltx_capabilities import budget_shape, local_caps @@ -45,43 +43,58 @@ from tests.http_error_assertions import assert_http_error from tests.lora_catalog_helpers import add_ic_lora, download_spec from services.features.ic_lora_recipes import IC_LORA_RECIPES, IcLoraRecipe -from services.features.video.job_common import spec_risk_allowance, spec_unmeasured_bet +from services.features.video.job_common import spec_risk_allowance from services.features.video.ic_lora_recipe import IcLoraRecipeExecutor from services.features.video.text_to_video import TextToVideoExecutor from services.generation_interrupt import GenerationCancelledError from services.generation_queue.types import OutputAllocation +from tests.fakes.generation import FakeJobSession from services.records import AssetRecord, GenerationRecord +from state.app_settings import AppSettings from services.sqlite_store import SqliteStore from tests.video_fixtures import write_mp4 -def test_settings_round_trip_budget_mode(client: TestClient) -> None: - # The bug is a missing alias/wire field so the frontend toggle POSTs into - # the void (extra="forbid" would 422; a missing echo would read back stale). - posted = client.post("/api/settings", json={"budgetMode": "reckless"}) +def test_saved_standard_or_reckless_settings_load_as_brave() -> None: + # The bug is a legacy spelling failing the settings load, or migrating to + # anything but Brave (a missing key or junk must also land on Brave). + for stored in ("standard", "reckless", "bogus"): + assert AppSettings.model_validate({"budgetMode": stored}).budget_mode == "brave" + assert AppSettings.model_validate({"budgetMode": "cautious"}).budget_mode == "cautious" + assert AppSettings().budget_mode == "brave" + + +def test_settings_patch_without_budget_mode_keeps_saved_cautious(client: TestClient) -> None: + # The bug is the legacy validator turning a null into the default, so an + # unrelated settings patch overwrites the saved mode. + posted = client.post("/api/settings", json={"budgetMode": "cautious"}) assert posted.status_code == 200, posted.text - fetched = client.get("/api/settings") - assert fetched.status_code == 200, fetched.text - assert fetched.json()["budgetMode"] == "reckless" + patched = client.post("/api/settings", json={"budgetMode": None, "seedLocked": True}) + assert patched.status_code == 200, patched.text + assert client.get("/api/settings").json()["budgetMode"] == "cautious" + + +def test_skip_budget_risk_confirm_survives_restart( + client: TestClient, test_state, default_app_settings: AppSettings +) -> None: + # The bug is "Don't ask again" living only in memory or never echoed, so + # the confirm comes back after a restart. + posted = client.post("/api/settings", json={"skipBudgetRiskConfirm": True}) + assert posted.status_code == 200, posted.text + assert client.get("/api/settings").json()["skipBudgetRiskConfirm"] is True + test_state.state.app_settings = default_app_settings + reloaded = test_state.settings.load_settings(default_app_settings) + assert reloaded.skip_budget_risk_confirm is True def test_local_job_filter_carries_live_budget_mode(test_state) -> None: # The bug is specs/preflights rendering with a stale or default mode # after the user toggles, because the filter never picked up the setting. - test_state.state.app_settings.budget_mode = "reckless" + test_state.state.app_settings.budget_mode = "cautious" job_filter = test_state.video_generation._local_job_filter( model_id="ltx-2.5-22b-distilled" ) - assert job_filter.budget_mode == "reckless" - - -def test_local_job_filter_defaults_to_standard_mode(test_state) -> None: - # The bug is a fail-open default that admits over-budget jobs on filters - # built without an explicit mode (every existing construction site). - job_filter = test_state.video_generation._local_job_filter( - model_id="ltx-2.5-22b-distilled" - ) - assert job_filter.budget_mode == "standard" + assert job_filter.budget_mode == "cautious" _GIB = 1024**3 @@ -105,6 +118,12 @@ def _configure_windows_fast(test_state, *, vram_gib: float, total_ram_gib: float test_state.config.local_generations_mode = "streaming_models_loading" +_NO_WINDOW_FITS_GIB = 8 +# On an 8 GB card the shortest window of a 1080p 21:9 clip still asks 11.6 GB, +# so windows cannot rescue it and the verdict stays an over-budget bet. +_SHORTEST_WINDOW_ASK_GIB = 11.6 + + def _local_fast_spec(payload: dict, pipeline: str = "fast") -> dict: return next(item["spec"] for item in payload["local_models"] if item["pipeline"] == pipeline) @@ -114,18 +133,18 @@ def test_specs_echo_live_budget_mode(test_state, create_fake_model_files, surfac # The bug is pickers rendering disabled-vs-warned off a stale mode because # the specs payload never carries it (Remote has no settings surface). create_fake_model_files() - test_state.state.app_settings.budget_mode = "reckless" + test_state.state.app_settings.budget_mode = "brave" with _surface_client(test_state, surface) as (client, headers): response = client.get("/api/generate/models-specs", headers=headers) assert response.status_code == 200, response.text - assert response.json()["budgetMode"] == "reckless" + assert response.json()["budgetMode"] == "brave" def test_tight_cell_warned_with_headroom_in_both_modes( test_state, client: TestClient, create_fake_model_files ) -> None: # The bug is a tight fit rendering identical to a comfortable one: no - # warned cell, so the picker cannot mark it. T1 shows in standard too. + # warned cell, so the picker cannot mark it. T1 shows in cautious too. create_fake_model_files() _configure_windows_fast(test_state, vram_gib=14.5) response = client.get("/api/generate/models-specs") @@ -148,7 +167,7 @@ def test_dropped_cell_carries_figures_matching_the_422( # The bug is picker "over by X" chrome disagreeing with the dialog because # the drop carries prose without the compared figures. create_fake_model_files() - _configure_windows_fast(test_state, vram_gib=16) + _configure_windows_fast(test_state, vram_gib=_NO_WINDOW_FITS_GIB) response = client.get("/api/generate/models-specs") assert response.status_code == 200, response.text dropped = _local_fast_spec(response.json())["dropped_cells"] @@ -158,27 +177,27 @@ def test_dropped_cell_carries_figures_matching_the_422( ) assert cell["reason"] == "stream_over" assert cell["shortfall_kind"] == "total" - assert cell["over_gib"] == pytest.approx(22.7 - 16.0, abs=0.05) + assert cell["over_gib"] == pytest.approx(11.19 - _NO_WINDOW_FITS_GIB, abs=0.05) -def test_reckless_empty_kept_grid_with_downgradable_drops_has_no_reason( +def test_brave_empty_kept_grid_with_downgradable_drops_has_no_reason( test_state, client: TestClient, create_fake_model_files ) -> None: - # The bug is reckless rendering the empty-state card instead of the + # The bug is brave rendering the empty-state card instead of the # warned form: a ram_shortfall reason survives the mode flip. create_fake_model_files() _configure_windows_fast(test_state, vram_gib=16, total_ram_gib=32) - test_state.state.app_settings.budget_mode = "reckless" + test_state.state.app_settings.budget_mode = "brave" response = client.get("/api/generate/models-specs") assert response.status_code == 200, response.text payload = response.json() assert payload["local_unavailable_reason"] is None -def test_standard_empty_kept_grid_keeps_ram_reason( +def test_cautious_empty_kept_grid_keeps_ram_reason( test_state, client: TestClient, create_fake_model_files ) -> None: - # Control: the viability change must not leak into standard mode. + # Control: the viability change must not leak into cautious mode. create_fake_model_files() _configure_windows_fast(test_state, vram_gib=16, total_ram_gib=32) response = client.get("/api/generate/models-specs") @@ -186,27 +205,15 @@ def test_standard_empty_kept_grid_keeps_ram_reason( assert response.json()["local_unavailable_reason"] == "ram_shortfall" -def test_iclora_drop_tier_mapping() -> None: - # The bug is a hard fence (spatial/decode floor) mapped to a bet tier, - # converting a known hang into an allowed job. - assert iclora_drop_risk_tier("stream_over") == "over" - assert iclora_drop_risk_tier("ram_shortfall") == "over" - assert iclora_drop_risk_tier("two_stage_over_measured") == "unmeasured" - assert iclora_drop_risk_tier("mac_two_stage_unmeasured") == "unmeasured" - assert iclora_drop_risk_tier("spatial") is None - assert iclora_drop_risk_tier("refine_decode_floor") is None - assert iclora_drop_risk_tier("unsupported") is None - - @pytest.mark.parametrize("surface", ["home", "remote"]) def test_iclora_list_echoes_budget_mode(test_state, create_fake_model_files, surface: str) -> None: # The bug is IC-LoRA pickers never learning the mode (controls render - # disabled in reckless because the list payload has no echo). - test_state.state.app_settings.budget_mode = "reckless" + # disabled in brave because the list payload has no echo). + test_state.state.app_settings.budget_mode = "brave" with _surface_client(test_state, surface) as (client, headers): response = client.get("/api/ic-loras", headers=headers) assert response.status_code == 200, response.text - assert response.json()["budgetMode"] == "reckless" + assert response.json()["budgetMode"] == "brave" def _t2v_body(*, resolution="540p", duration=5, aspect_ratio="16:9", fps=24): @@ -235,14 +242,14 @@ def _surface_client(test_state, surface: str) -> Iterator[tuple[TestClient, dict @pytest.mark.parametrize("surface", ["home", "remote"]) -def test_reckless_over_budget_create_enqueues_with_risk_annotation( +def test_brave_over_budget_create_enqueues_with_risk_annotation( test_state, create_fake_model_files, surface: str ) -> None: - # The bug is a reckless T2 create 422ing (mode not honored) or enqueueing + # The bug is a brave T2 create 422ing (mode not honored) or enqueueing # without the annotation (execute then kills a confirmed bet). create_fake_model_files() - _configure_windows_fast(test_state, vram_gib=16) - test_state.state.app_settings.budget_mode = "reckless" + _configure_windows_fast(test_state, vram_gib=_NO_WINDOW_FITS_GIB) + test_state.state.app_settings.budget_mode = "brave" with _surface_client(test_state, surface) as (client, headers): response = client.post( "/api/generations/text-to-video", @@ -252,8 +259,8 @@ def test_reckless_over_budget_create_enqueues_with_risk_annotation( assert response.status_code == 200, response.text body = response.json() assert body["risk"]["tier"] == "over" - assert "Over budget" in body["risk"]["message"] - assert body["risk"]["over_gib"] == pytest.approx(17.2 - 16.0, abs=0.05) + assert "Needs too much memory" in body["risk"]["message"] + assert body["risk"]["over_gib"] == pytest.approx(_SHORTEST_WINDOW_ASK_GIB - _NO_WINDOW_FITS_GIB, abs=0.05) # The annotation survives insert→read (queue badge reads GET, not POST). with _surface_client(test_state, surface) as (client, headers): fetched = client.get(f"/api/generations/{body['id']}", headers=headers) @@ -261,32 +268,32 @@ def test_reckless_over_budget_create_enqueues_with_risk_annotation( assert fetched.json()["risk"]["tier"] == "over" -def test_standard_over_budget_create_still_422s_without_insert( +def test_cautious_over_budget_create_still_422s_without_insert( test_state, client: TestClient, create_fake_model_files ) -> None: - # Control: reckless must not leak into standard creates. + # Control: brave must not leak into cautious creates. create_fake_model_files() - _configure_windows_fast(test_state, vram_gib=16) + _configure_windows_fast(test_state, vram_gib=_NO_WINDOW_FITS_GIB) response = client.post( "/api/generations/text-to-video", json=_t2v_body(resolution="1080p", duration=5, aspect_ratio="21:9"), ) assert_http_error(response, status_code=422, code="VIDEO_JOB_TOO_LARGE", message=( - "This job needs 17.2 GB of GPU memory but this card has 16.0 GB. " + "This job needs 11.6 GB of GPU memory but this card has 8.0 GB. " "Lower the resolution, duration, frame rate, or aspect width." )) assert test_state.queued_generations.list_generations("text-to-video") == [] -def test_reckless_unsupported_create_still_422s( +def test_brave_unsupported_create_still_422s( test_state, client: TestClient, create_fake_model_files ) -> None: - # The bug is reckless annotating a missing pipeline (no bet exists when + # The bug is brave annotating a missing pipeline (no bet exists when # nothing can run it). Flip the process mode: preflight must still refuse. create_fake_model_files() _configure_windows_fast(test_state, vram_gib=16) test_state.config.local_generations_mode = "unsupported" - test_state.state.app_settings.budget_mode = "reckless" + test_state.state.app_settings.budget_mode = "brave" response = client.post( "/api/generations/text-to-video", json=_t2v_body(resolution="540p", duration=5), @@ -302,8 +309,8 @@ def test_downgraded_job_streams_never_full( # The bug is an over-budget job picking full and paging to death: the # downgrade must pin streaming. create_fake_model_files() - _configure_windows_fast(test_state, vram_gib=16) - test_state.state.app_settings.budget_mode = "reckless" + _configure_windows_fast(test_state, vram_gib=_NO_WINDOW_FITS_GIB) + test_state.state.app_settings.budget_mode = "brave" job_filter = test_state.video_generation._local_job_filter( model_id="ltx-2.5-22b-distilled", total_only=True ) @@ -317,13 +324,13 @@ def test_downgraded_job_streams_never_full( def test_evict_win_beats_risk_annotation( test_state, fake_services, create_fake_model_files ) -> None: - # The bug is reckless recording a bet (and warning the user) for a job a + # The bug is brave recording a bet (and warning the user) for a job a # free eviction would have won. W-band shape (720p/20s asks 20.03 on a # 24 GB card): occupied free 19.0 rejects, evicting the warm weights frees # to 23.5, so the re-decide loads and the annotation stays None. create_fake_model_files() _configure_windows_fast(test_state, vram_gib=24) - test_state.state.app_settings.budget_mode = "reckless" + test_state.state.app_settings.budget_mode = "brave" width, height = budget_shape( local_caps("ltx-2.5-22b-distilled"), "720p", "16:9", mode="video" ) @@ -441,14 +448,14 @@ def _install_refine_catalog(fake_services) -> None: @pytest.mark.parametrize("surface", ["home", "remote"]) -def test_reckless_over_budget_retake_enqueues_with_risk( +def test_brave_over_budget_retake_enqueues_with_risk( test_state, client: TestClient, create_fake_model_files, surface: str, tmp_path: Path ) -> None: - # The bug is a reckless edit create 422ing while Fast creates annotate + # The bug is a brave edit create 422ing while Fast creates annotate # (one feature's mode wiring missed), or annotating without figures. create_fake_model_files() _configure_windows_edit(test_state, vram_gib=8, total_ram_gib=64) - test_state.state.app_settings.budget_mode = "reckless" + test_state.state.app_settings.budget_mode = "brave" clip = write_mp4(tmp_path / "clip.mp4", seconds=4, fps=24, width=1920, height=1080) asset_id = _upload_video(client, clip)["id"] with _surface_client(test_state, surface) as (surface_client, headers): @@ -468,14 +475,14 @@ def test_reckless_over_budget_retake_enqueues_with_risk( assert fetched.json()["risk"]["tier"] == "over" -def test_reckless_overlong_selection_still_422s( +def test_brave_overlong_selection_still_422s( test_state, client: TestClient, create_fake_model_files, tmp_path: Path ) -> None: - # The bug is reckless waiving window math (product rules, not VRAM): + # The bug is brave waiving window math (product rules, not VRAM): # an over-long selection must refuse in every mode. create_fake_model_files() _configure_windows_edit(test_state, vram_gib=12, total_ram_gib=64) - test_state.state.app_settings.budget_mode = "reckless" + test_state.state.app_settings.budget_mode = "brave" clip = write_mp4(tmp_path / "clip.mp4", seconds=241 / 24, fps=24, width=1920, height=1080) asset_id = _upload_video(client, clip)["id"] with _surface_client(test_state, "home") as (surface_client, headers): @@ -497,16 +504,16 @@ def test_reckless_overlong_selection_still_422s( @pytest.mark.parametrize("surface", ["home", "remote"]) -def test_reckless_unmeasured_iclora_create_enqueues_with_risk( +def test_brave_unmeasured_iclora_create_enqueues_with_risk( test_state, client: TestClient, create_fake_model_files, fake_services, surface: str, tmp_path: Path ) -> None: # The bug is a T3 IC-LoRA config (unmeasured two-stage length) 422ing in - # reckless, or annotating as "over" with fabricated figures. + # brave, or annotating as "over" with fabricated figures. create_fake_model_files() _configure_mac_iclora(test_state, fake_services, pool_gib=64) _install_layout_catalog(fake_services) _write_recipe_weights(test_state, "layout-to-render") - test_state.state.app_settings.budget_mode = "reckless" + test_state.state.app_settings.budget_mode = "brave" clip = write_mp4(tmp_path / "clip.mp4", seconds=10, fps=24, width=1920, height=1088) video = _upload_video(client, clip) test_state.video_processor.register_video( @@ -536,15 +543,13 @@ def test_reckless_unmeasured_iclora_create_enqueues_with_risk( assert fetched.json()["risk"]["tier"] == "unmeasured" -def test_deleted_t3_branch_regresses_windows_two_stage_create_to_422( +def test_two_stage_iclora_past_token_cap_that_cannot_chunk_carries_priced_figures( test_state, fake_services, create_fake_model_files, tmp_path: Path ) -> None: - # The bug is a deleted or mis-mapped two_stage_over_measured branch in - # _risk_for_iclora_verdict regressing Windows T3 creates to 422: standard - # must still refuse with the fence copy, reckless must annotate unmeasured - # with no figures. Pinned at direct preflight because no recipe POST can - # reach it — the only never-chunking two-stage layout (STAGE_1_LORA) fails - # the home-recipe gate before the budget gate. + # The bug is the token-cap fence returning before the curve: the strict + # refusal and the bet then carry no estimate. Pinned at direct preflight + # because no recipe POST can reach it — the only never-chunking two-stage + # layout (STAGE_1_LORA) fails the home-recipe gate before the budget gate. create_fake_model_files() _configure_windows_edit(test_state, vram_gib=32, total_ram_gib=64) item = add_ic_lora( @@ -594,22 +599,24 @@ def test_deleted_t3_branch_regresses_windows_two_stage_create_to_422( ) assert exc_info.value.status_code == 422 assert exc_info.value.code == VIDEO_JOB_TOO_LARGE - assert exc_info.value.detail == TWO_STAGE_OVER_MEASURED_MESSAGE - test_state.state.app_settings.budget_mode = "reckless" + assert exc_info.value.detail == unmeasured_refusal_message("two_stage_range") + test_state.state.app_settings.budget_mode = "brave" risk = test_state.ic_lora.preflight_queued_recipe_job( item=item, video=video, stored=stored, source_fps=24.0 ) assert risk is not None assert risk.tier == "unmeasured" + assert risk.unmeasured_basis == "two_stage_range" assert risk.over_gib is None - assert risk.over_ram_gb is None + assert risk.readout is not None + assert risk.readout.need_gb == pytest.approx(24.6, abs=0.05) @pytest.mark.parametrize("surface", ["home", "remote"]) -def test_reckless_decode_floor_iclora_create_still_422s( +def test_brave_decode_floor_iclora_create_still_422s( test_state, client: TestClient, create_fake_model_files, fake_services, surface: str, tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: - # Substitutes the planned test_reckless_spatial_iclora_create_still_422s: + # Substitutes the planned test_brave_spatial_iclora_create_still_422s: # IC_LORA_SOURCE_TOO_LARGE is unreachable through recipe creates — inputs # clamp via fit_ic_lora_stage1 # (backend/runtime_config/ic_lora_local_envelope.py:123) / fit_in_box @@ -617,7 +624,7 @@ def test_reckless_decode_floor_iclora_create_still_422s( # reasons share the same hard-wall `return None` in _risk_for_iclora_verdict # (backend/handlers/ic_lora_handler.py:408), so this test pins the branch # the spatial case would have pinned. - # The bug is reckless waiving a pipeline limit (a known decode failure, + # The bug is brave waiving a pipeline limit (a known decode failure, # not a bet): a tiled Refine job past the one-pass shape must refuse in # every mode. create_fake_model_files() @@ -629,7 +636,7 @@ def test_reckless_decode_floor_iclora_create_still_422s( IcLoraRecipe(recipe_id="probe-refine", catalog_id="probe-refine"), ) _write_recipe_weights(test_state, "probe-refine", "refine.safetensors") - test_state.state.app_settings.budget_mode = "reckless" + test_state.state.app_settings.budget_mode = "brave" clip = write_mp4(tmp_path / "clip.mp4", seconds=10, fps=24, width=1920, height=1080) video = _upload_video(client, clip) test_state.video_processor.register_video( @@ -660,16 +667,16 @@ def test_allow_risk_none_follows_live_mode(test_state, create_fake_model_files) # The bug is request paths ignoring the toggle (hardcoded False) or # executors inheriting it (None passed through). create_fake_model_files() - _configure_windows_fast(test_state, vram_gib=16) - standard_filter = test_state.video_generation._local_job_filter( + _configure_windows_fast(test_state, vram_gib=_NO_WINDOW_FITS_GIB) + cautious_filter = test_state.video_generation._local_job_filter( model_id="ltx-2.5-22b-distilled", total_only=True ) - # standard mode + None ⇒ raises + # cautious mode + None ⇒ raises with pytest.raises(HTTPError): test_state.video_generation._video_job_load_mode( - 2560, 1088, 121, job_filter=standard_filter + 2560, 1088, 121, job_filter=cautious_filter ) - test_state.state.app_settings.budget_mode = "reckless" + test_state.state.app_settings.budget_mode = "brave" live_filter = test_state.video_generation._local_job_filter( model_id="ltx-2.5-22b-distilled", total_only=True ) @@ -680,36 +687,41 @@ def test_allow_risk_none_follows_live_mode(test_state, create_fake_model_files) assert risk is not None and risk.tier == "over" -def test_explicit_allow_risk_false_overrides_reckless_mode( +@pytest.mark.usefixtures("single_pass_only") +def test_explicit_allow_risk_false_overrides_brave_mode( test_state, create_fake_model_files ) -> None: # The bug is an unconfirmed drifted job running because the toggle moved: - # executors pass explicit False for unannotated jobs in reckless mode. + # executors pass explicit False for unannotated jobs in brave mode. create_fake_model_files() _configure_windows_fast(test_state, vram_gib=16) - test_state.state.app_settings.budget_mode = "reckless" - reckless_filter = test_state.video_generation._local_job_filter( + test_state.state.app_settings.budget_mode = "brave" + brave_filter = test_state.video_generation._local_job_filter( model_id="ltx-2.5-22b-distilled", total_only=True ) with pytest.raises(HTTPError) as exc_info: test_state.video_generation._video_job_load_mode( - 2560, 1088, 121, job_filter=reckless_filter, allow_risk=False + 2560, 1088, 121, job_filter=brave_filter, allowance=RiskAllowance.none() ) assert exc_info.value.status_code == 422 -def test_explicit_allow_risk_true_survives_standard_mode( +def test_explicit_allow_risk_true_survives_cautious_mode( test_state, create_fake_model_files ) -> None: # The bug is a confirmed bet dying because the toggle moved: stored - # annotation ⇒ explicit True ⇒ downgrades on a standard filter. + # annotation ⇒ explicit True ⇒ downgrades on a cautious filter. create_fake_model_files() - _configure_windows_fast(test_state, vram_gib=16) - standard_filter = test_state.video_generation._local_job_filter( + _configure_windows_fast(test_state, vram_gib=_NO_WINDOW_FITS_GIB) + cautious_filter = test_state.video_generation._local_job_filter( model_id="ltx-2.5-22b-distilled", total_only=True ) mode, risk = test_state.video_generation._video_job_load_mode( - 2560, 1088, 121, job_filter=standard_filter, allow_risk=True + 2560, + 1088, + 121, + job_filter=cautious_filter, + allowance=RiskAllowance(over=True, unmeasured=False), ) assert mode == "streaming_models_loading" assert risk is not None and risk.tier == "over" @@ -728,7 +740,11 @@ def test_allow_risk_never_waives_hard_reject( ) with pytest.raises(HTTPError): test_state.video_generation._video_job_load_mode( - 2560, 1088, 121, job_filter=unsupported_filter, allow_risk=True + 2560, + 1088, + 121, + job_filter=unsupported_filter, + allowance=RiskAllowance(over=True, unmeasured=False), ) @@ -740,9 +756,13 @@ def __init__(self, models_dir: Path) -> None: self.seen: dict[str, object] = {} def validate_local_a2v_request( - self, params: AudioToVideoParams, audio_duration_ms: int + self, + params: AudioToVideoParams, + audio_duration_ms: int, + *, + pass_shape: PassShape, ) -> None: - del params, audio_duration_ms + del params, audio_duration_ms, pass_shape def generate_local_reserved( self, @@ -754,8 +774,8 @@ def generate_local_reserved( a2v_num_frames: int | None = None, a2v_audio_duration_seconds: float | None = None, local_model_id: LTXLocalModelId, - risk_allowance: bool | None = None, - unmeasured_bet: bool = False, + allowance: RiskAllowance | None = None, + pass_shape: PassShape | None = None, ) -> GenerateVideoResponse: del ( req, @@ -765,9 +785,9 @@ def generate_local_reserved( a2v_num_frames, a2v_audio_duration_seconds, local_model_id, - unmeasured_bet, + pass_shape, ) - self.seen = {"risk_allowance": risk_allowance} + self.seen = {"allowance": allowance} raise GenerationCancelledError() @@ -792,8 +812,7 @@ def generate_local_reserved( explore_generation: bool = True, explicit_generation_seed: bool = False, high_res: bool = False, - risk_allowance: bool | None = None, - unmeasured_bet: bool = False, + allowance: RiskAllowance | None = None, ) -> object: del ( req, @@ -805,10 +824,7 @@ def generate_local_reserved( explicit_generation_seed, high_res, ) - self.seen = { - "risk_allowance": risk_allowance, - "unmeasured_bet": unmeasured_bet, - } + self.seen = {"allowance": allowance} raise GenerationCancelledError() @@ -827,14 +843,16 @@ def test_executor_passes_stored_allowance_to_generator( ) -> None: # The bug is the executor dropping the annotation on the floor: generate # never receives the allowance and the confirmed bet dies at execute. - assert spec_risk_allowance({"params": {}, "_risk": _stored_risk("over")}) is True - assert spec_risk_allowance({"params": {}, "_risk": _stored_risk("unmeasured")}) is False - assert spec_unmeasured_bet({"params": {}, "_risk": _stored_risk("unmeasured")}) is True - assert spec_unmeasured_bet({"params": {}, "_risk": _stored_risk("over")}) is False - assert spec_risk_allowance({"params": {}}) is False - assert spec_risk_allowance({"params": {}, "_risk": {"tier": "tight", "message": "x"}}) is False - assert spec_risk_allowance({"params": {}, "_risk": "junk"}) is False - assert spec_risk_allowance({"params": {}, "_risk": {"tier": "over"}}) is False + assert spec_risk_allowance({"params": {}, "_risk": _stored_risk("over")}) == RiskAllowance( + over=True, unmeasured=False + ) + assert spec_risk_allowance({"params": {}, "_risk": _stored_risk("unmeasured")}) == RiskAllowance( + over=False, unmeasured=True + ) + assert spec_risk_allowance({"params": {}}) == RiskAllowance.none() + assert spec_risk_allowance({"params": {}, "_risk": {"tier": "tight", "message": "x"}}) == RiskAllowance.none() + assert spec_risk_allowance({"params": {}, "_risk": "junk"}) == RiskAllowance.none() + assert spec_risk_allowance({"params": {}, "_risk": {"tier": "over"}}) == RiskAllowance.none() # And the executor threads it: capture the kwarg with a tiny Protocol fake. create_fake_model_files() generator = _CaptureGenerator(test_state.config.default_models_dir) @@ -870,8 +888,8 @@ def test_executor_passes_stored_allowance_to_generator( ), ) with pytest.raises(GenerationCancelledError): - executor.execute(generation, outputs) - assert generator.seen == {"risk_allowance": True} + executor.execute(generation, outputs, FakeJobSession()) + assert generator.seen == {"allowance": RiskAllowance(over=True, unmeasured=False)} def test_retry_preserves_risk_annotation( @@ -880,8 +898,8 @@ def test_retry_preserves_risk_annotation( # The bug is a retry dropping _risk: the same confirmed bet dies at # execute the second time around. create_fake_model_files() - _configure_windows_fast(test_state, vram_gib=16) - test_state.state.app_settings.budget_mode = "reckless" + _configure_windows_fast(test_state, vram_gib=_NO_WINDOW_FITS_GIB) + test_state.state.app_settings.budget_mode = "brave" # Hold the GPU slot so the app's queue runner cannot claim the row first. assert test_state.generation.try_reserve_generation_start() is True try: @@ -933,14 +951,14 @@ def test_corrupt_stored_risk_does_not_fail_generation_reads( test_state.generation.release_generation_start_reservation() -def test_estimate_returns_risk_not_422_in_reckless( +def test_estimate_returns_risk_not_422_in_brave( test_state, client: TestClient, create_fake_model_files ) -> None: # The bug is estimate 422ing a selection the form allows: any UI that # prices before generating needs the annotation, not the refusal. create_fake_model_files() - _configure_windows_fast(test_state, vram_gib=16) - test_state.state.app_settings.budget_mode = "reckless" + _configure_windows_fast(test_state, vram_gib=_NO_WINDOW_FITS_GIB) + test_state.state.app_settings.budget_mode = "brave" response = client.post( "/api/generate/estimate", json={"resolution": "1080p", "aspectRatio": "21:9", "duration": 5, "fps": 24}, @@ -951,18 +969,18 @@ def test_estimate_returns_risk_not_422_in_reckless( assert "estimate" in body # ETA or null, never an error -def test_estimate_still_422s_in_standard( +def test_estimate_still_422s_in_cautious( test_state, client: TestClient, create_fake_model_files ) -> None: - # Control: estimate keeps today's 422s in standard mode. + # Control: estimate keeps today's 422s in cautious mode. create_fake_model_files() - _configure_windows_fast(test_state, vram_gib=16) + _configure_windows_fast(test_state, vram_gib=_NO_WINDOW_FITS_GIB) response = client.post( "/api/generate/estimate", json={"resolution": "1080p", "aspectRatio": "21:9", "duration": 5, "fps": 24}, ) assert_http_error(response, status_code=422, code="VIDEO_JOB_TOO_LARGE", message=( - "This job needs 17.2 GB of GPU memory but this card has 16.0 GB. " + "This job needs 11.6 GB of GPU memory but this card has 8.0 GB. " "Lower the resolution, duration, frame rate, or aspect width." )) @@ -974,8 +992,8 @@ def test_queue_snapshot_carries_risk_on_both_surfaces( # The bug is the queue badge starving: the annotation exists on the row # but the snapshot (or the Remote projection) drops it. create_fake_model_files() - _configure_windows_fast(test_state, vram_gib=16) - test_state.state.app_settings.budget_mode = "reckless" + _configure_windows_fast(test_state, vram_gib=_NO_WINDOW_FITS_GIB) + test_state.state.app_settings.budget_mode = "brave" with _surface_client(test_state, surface) as (client, headers): created = client.post( "/api/generations/text-to-video", @@ -987,55 +1005,21 @@ def test_queue_snapshot_carries_risk_on_both_surfaces( assert snapshot.status_code == 200, snapshot.text body = snapshot.json() entries = list(body["queued"]) - if body["active"] is not None: - entries.append(body["active"]) + entries.extend(body["active"]) entries.extend(body["done"]) entries.extend(body["failed"]) risky = [e for e in entries if e["generation"]["id"] == created.json()["id"]] assert risky and risky[0]["generation"]["risk"]["tier"] == "over" -def test_reckless_dropped_a2v_row_reports_budget_not_invalid( - test_state, client: TestClient, create_fake_model_files, tmp_path: Path -) -> None: - # The bug is reckless swallowing the derive-time budget refusal (the - # downgrade path returns a risk instead of raising), so a fully-dropped - # A2V row 422s INVALID instead of the mode-stable VIDEO_JOB_TOO_LARGE. - create_fake_model_files() - _configure_windows_fast(test_state, vram_gib=12) - test_state.state.app_settings.budget_mode = "reckless" - audio = client.post( - "/api/assets", - json={"path": str(_wav(tmp_path / "line.wav", duration_seconds=5.0))}, - ).json() - response = client.post( - "/api/generations/audio-to-video", - json={ - "params": { - "prompt": "the character speaks", - "resolution": "1080p", - "model": "ltx-2.5-fast", - "fps": 24, - }, - "inputs": {"audio": {"assetId": audio["id"]}}, - }, - ) - assert response.status_code == 422, response.text - assert_http_error(response, status_code=422, code="VIDEO_JOB_TOO_LARGE", message=( - "This job needs 13.6 GB of GPU memory but this card has 12.0 GB. " - "Lower the resolution, duration, frame rate, or aspect width." - )) - assert SqliteStore(test_state.config.app_data_dir).list_generations("audio-to-video") == [] - - -@pytest.mark.parametrize("budget_mode", ["standard", "reckless"]) +@pytest.mark.usefixtures("single_pass_only") def test_fully_dropped_a2v_row_admits_audio_shorter_than_every_cell( - test_state, client: TestClient, create_fake_model_files, tmp_path: Path, budget_mode: str + test_state, client: TestClient, create_fake_model_files, tmp_path: Path ) -> None: - # 4s audio loads on 12 GB 1080p after every cell was dropped; both modes must 422 that cell, not enqueue. + # 4s audio loads on 12 GB 1080p after every cell was dropped; the strict mode must 422 that cell, not enqueue. create_fake_model_files() _configure_windows_fast(test_state, vram_gib=12) - test_state.state.app_settings.budget_mode = budget_mode + test_state.state.app_settings.budget_mode = "cautious" specs = client.get("/api/generate/models-specs") assert specs.status_code == 200, specs.text spec = _local_fast_spec(specs.json()) @@ -1075,10 +1059,10 @@ def test_fully_dropped_a2v_row_admits_audio_shorter_than_every_cell( def test_partial_a2v_drop_refuses_the_static_duration_not_invalid_audio( test_state, client: TestClient, create_fake_model_files, tmp_path: Path ) -> None: - # 1080p keeps 5–6s at 16 GB and drops 10s. 10s audio is inside the static + # An 8 GB card drops 1080p 10s. 10s audio is inside the static # ceiling, so the refusal is the budget, not "audio is too long". create_fake_model_files() - _configure_windows_fast(test_state, vram_gib=16) + _configure_windows_fast(test_state, vram_gib=_NO_WINDOW_FITS_GIB) audio = client.post( "/api/assets", json={"path": str(_wav(tmp_path / "line.wav", duration_seconds=10.0))}, @@ -1097,20 +1081,20 @@ def test_partial_a2v_drop_refuses_the_static_duration_not_invalid_audio( ) assert response.status_code == 422, response.text assert_http_error(response, status_code=422, code="VIDEO_JOB_TOO_LARGE", message=( - "This job needs 22.1 GB of GPU memory but this card has 16.0 GB. " + "This job needs 11.2 GB of GPU memory but this card has 8.0 GB. " "Lower the resolution, duration, frame rate, or aspect width." )) assert SqliteStore(test_state.config.app_data_dir).list_generations("audio-to-video") == [] -def test_reckless_partial_a2v_drop_enqueues_the_static_duration( +def test_brave_partial_a2v_drop_enqueues_the_static_duration( test_state, client: TestClient, create_fake_model_files, tmp_path: Path ) -> None: - # Same dropped 10s cell. Reckless must enqueue the static 10s shape + # Same dropped 10s cell. Brave must enqueue the static 10s shape # (233 frames), not trim it to the kept 6s cell (137 frames). create_fake_model_files() - _configure_windows_fast(test_state, vram_gib=16) - test_state.state.app_settings.budget_mode = "reckless" + _configure_windows_fast(test_state, vram_gib=_NO_WINDOW_FITS_GIB) + test_state.state.app_settings.budget_mode = "brave" assert test_state.generation.try_reserve_generation_start() is True try: audio = client.post( @@ -1151,14 +1135,14 @@ def _extend_body(asset_id: str, *, duration: float = 2.0, mode: str = "end") -> @pytest.mark.parametrize("surface", ["home", "remote"]) -def test_reckless_over_budget_extend_enqueues_with_risk( +def test_brave_over_budget_extend_enqueues_with_risk( test_state, client: TestClient, create_fake_model_files, surface: str, tmp_path: Path ) -> None: - # The bug is a reckless extend create 422ing while retake creates annotate + # The bug is a brave extend create 422ing while retake creates annotate # (one feature's mode wiring missed), or annotating without figures. create_fake_model_files() _configure_windows_edit(test_state, vram_gib=8, total_ram_gib=64) - test_state.state.app_settings.budget_mode = "reckless" + test_state.state.app_settings.budget_mode = "brave" clip = write_mp4(tmp_path / "clip.mp4", seconds=4, fps=24, width=1920, height=1080) asset_id = _upload_video(client, clip)["id"] with _surface_client(test_state, surface) as (surface_client, headers): @@ -1251,14 +1235,14 @@ def _run(risk: dict[str, object] | None) -> None: ), ) with pytest.raises(GenerationCancelledError): - executor.execute(generation, outputs) + executor.execute(generation, outputs, FakeJobSession()) _run(_stored_risk("unmeasured")) - assert generator.seen == {"risk_allowance": False, "unmeasured_bet": True} + assert generator.seen == {"allowance": RiskAllowance(over=False, unmeasured=True)} _run(_stored_risk("over")) - assert generator.seen == {"risk_allowance": True, "unmeasured_bet": False} + assert generator.seen == {"allowance": RiskAllowance(over=True, unmeasured=False)} _run(None) - assert generator.seen == {"risk_allowance": False, "unmeasured_bet": False} + assert generator.seen == {"allowance": RiskAllowance.none()} def test_edit_preflight_echoes_live_budget_mode( @@ -1268,7 +1252,7 @@ def test_edit_preflight_echoes_live_budget_mode( # because the matrix payload never carries it. create_fake_model_files() _configure_windows_edit(test_state, vram_gib=12, total_ram_gib=64) - test_state.state.app_settings.budget_mode = "reckless" + test_state.state.app_settings.budget_mode = "brave" clip = write_mp4(tmp_path / "clip.mp4", seconds=6) asset_id = _upload_video(client, clip)["id"] response = client.post( @@ -1283,7 +1267,7 @@ def test_edit_preflight_echoes_live_budget_mode( }, ) assert response.status_code == 200, response.text - assert response.json()["budgetMode"] == "reckless" + assert response.json()["budgetMode"] == "brave" def test_iclora_preflight_echoes_live_budget_mode( @@ -1293,7 +1277,7 @@ def test_iclora_preflight_echoes_live_budget_mode( # because the preflight payload never carries it. create_fake_model_files() _configure_windows_edit(test_state, vram_gib=12, total_ram_gib=64) - test_state.state.app_settings.budget_mode = "reckless" + test_state.state.app_settings.budget_mode = "brave" client.post("/api/ic-loras/download", json={"ic_lora_id": "colorize-v1"}) src = tmp_path / "clip.mp4" src.write_bytes(b"\x00" * 100) @@ -1310,14 +1294,14 @@ def test_iclora_preflight_echoes_live_budget_mode( }, ) assert response.status_code == 200, response.text - assert response.json()["budgetMode"] == "reckless" + assert response.json()["budgetMode"] == "brave" -def test_legacy_load_is_annotated_only_while_reckless( +def test_legacy_route_load_does_not_confirm_in_brave( test_state, create_fake_model_files ) -> None: - # The bug is a Linux job the picker marks unmeasured enqueueing with no - # bet, so the queue never shows it and a later check can still block it. + # The bug is Brave nagging every generic-curve job: a Linux load must + # admit silently in both modes. create_fake_model_files() test_state.config.system = "Linux" test_state.config.vram_gb = 24 @@ -1331,21 +1315,51 @@ def test_legacy_load_is_annotated_only_while_reckless( "aspect_ratio": "16:9", "duration": 5, "fps": 24, + "pass_shape": "auto", } - test_state.state.app_settings.budget_mode = "standard" + test_state.state.app_settings.budget_mode = "cautious" + assert handler.preflight_queued_fast_job(**kwargs) is None + test_state.state.app_settings.budget_mode = "brave" assert handler.preflight_queued_fast_job(**kwargs) is None - test_state.state.app_settings.budget_mode = "reckless" + + +def test_cautious_preflight_runs_on_legacy_route( + test_state, create_fake_model_files +) -> None: + # Cautious must refuse an unmeasured 1440p cell on a legacy route at queue + # insert instead of skipping the preflight and letting Brave be stricter. + create_fake_model_files() + test_state.config.system = "Linux" + test_state.config.vram_gb = 24 + test_state.config.vram_bytes = 24 * _GIB + test_state.config.total_ram_bytes = 64 * _GIB + test_state.config.local_generations_mode = "streaming_models_loading" + handler = test_state.video_generation + kwargs = { + "offering": "ltx-2.5-fast", + "resolution": "1440p", + "aspect_ratio": "16:9", + "duration": 5, + "fps": 24, + "pass_shape": "auto", + } + test_state.state.app_settings.budget_mode = "cautious" + with pytest.raises(HTTPError) as exc_info: + handler.preflight_queued_fast_job(**kwargs) + assert exc_info.value.status_code == 422 + test_state.state.app_settings.budget_mode = "brave" risk = handler.preflight_queued_fast_job(**kwargs) assert risk is not None and risk.tier == "unmeasured" -def test_flip_to_standard_still_streams_the_confirmed_bet( +@pytest.mark.usefixtures("single_pass_only") +def test_flip_to_cautious_still_streams_the_confirmed_bet( test_state, client: TestClient, create_fake_model_files ) -> None: # The bug is a mode flip re-blocking a job the user already confirmed. create_fake_model_files() _configure_windows_fast(test_state, vram_gib=16) - test_state.state.app_settings.budget_mode = "reckless" + test_state.state.app_settings.budget_mode = "brave" response = client.post( "/api/generations/text-to-video", json=_t2v_body(resolution="1080p", duration=5, aspect_ratio="21:9"), @@ -1353,7 +1367,7 @@ def test_flip_to_standard_still_streams_the_confirmed_bet( assert response.status_code == 200, response.text record = SqliteStore(test_state.config.app_data_dir).get_generation(response.json()["id"]) assert record is not None - test_state.state.app_settings.budget_mode = "standard" + test_state.state.app_settings.budget_mode = "cautious" handler = test_state.video_generation width, height = budget_shape( local_caps("ltx-2.5-22b-distilled"), "1080p", "21:9", mode="video" @@ -1365,7 +1379,7 @@ def test_flip_to_standard_still_streams_the_confirmed_bet( height, frames, job_filter=job_filter, - allow_risk=spec_risk_allowance(record.spec), + allowance=spec_risk_allowance(record.spec), ) assert mode == "streaming_models_loading" with pytest.raises(HTTPError) as exc_info: @@ -1374,7 +1388,7 @@ def test_flip_to_standard_still_streams_the_confirmed_bet( height, frames, job_filter=job_filter, - allow_risk=False, + allowance=RiskAllowance.none(), ) assert exc_info.value.status_code == 422 @@ -1384,8 +1398,8 @@ def test_unmeasured_note_does_not_waive_a_vram_shortfall( ) -> None: # The bug is an unmeasured note streaming a cell that does not fit. create_fake_model_files() - _configure_windows_fast(test_state, vram_gib=16) - test_state.state.app_settings.budget_mode = "standard" + _configure_windows_fast(test_state, vram_gib=_NO_WINDOW_FITS_GIB) + test_state.state.app_settings.budget_mode = "cautious" handler = test_state.video_generation width, height = budget_shape( local_caps("ltx-2.5-22b-distilled"), "1080p", "21:9", mode="video" @@ -1398,7 +1412,7 @@ def test_unmeasured_note_does_not_waive_a_vram_shortfall( height, frames, job_filter=job_filter, - allow_risk=spec_risk_allowance({"_risk": _stored_risk("unmeasured")}), + allowance=spec_risk_allowance({"_risk": _stored_risk("unmeasured")}), ) assert exc_info.value.status_code == 422 mode, _risk = handler._video_job_load_mode( @@ -1406,7 +1420,7 @@ def test_unmeasured_note_does_not_waive_a_vram_shortfall( height, frames, job_filter=job_filter, - allow_risk=spec_risk_allowance({"_risk": _stored_risk("over")}), + allowance=spec_risk_allowance({"_risk": _stored_risk("over")}), ) assert mode == "streaming_models_loading" @@ -1421,7 +1435,7 @@ def test_unmeasured_note_still_runs_a_job_that_loads( test_state.config.vram_bytes = 24 * _GIB test_state.config.total_ram_bytes = 64 * _GIB test_state.config.local_generations_mode = "streaming_models_loading" - test_state.state.app_settings.budget_mode = "standard" + test_state.state.app_settings.budget_mode = "cautious" handler = test_state.video_generation width, height = budget_shape( local_caps("ltx-2.5-22b-distilled"), "540p", "16:9", mode="video" @@ -1433,17 +1447,17 @@ def test_unmeasured_note_still_runs_a_job_that_loads( height, frames, job_filter=job_filter, - allow_risk=spec_risk_allowance({"_risk": _stored_risk("unmeasured")}), + allowance=spec_risk_allowance({"_risk": _stored_risk("unmeasured")}), ) assert mode == "streaming_models_loading" -def test_iclora_preflight_names_a_downgradable_cell_in_standard( +def test_iclora_preflight_names_a_downgradable_cell_in_cautious( test_state, client: TestClient, create_fake_model_files, tmp_path: Path ) -> None: # The bug is a failing preflight cell looking identical for a hard refusal - # and a cell Reckless would run. 32 GB RAM is under the IC-LoRA floor, so - # the clip fails on memory and Reckless could still run it. + # and a cell Brave would run. 32 GB RAM is under the IC-LoRA floor, so + # the clip fails on memory and Brave could still run it. create_fake_model_files() _configure_windows_edit(test_state, vram_gib=24, total_ram_gib=32) client.post("/api/ic-loras/download", json={"ic_lora_id": "colorize-v1"}) diff --git a/backend/tests/test_custom_lora.py b/backend/tests/test_custom_lora.py new file mode 100644 index 000000000..6cfcd2d64 --- /dev/null +++ b/backend/tests/test_custom_lora.py @@ -0,0 +1,714 @@ +"""Custom LoRA: import from a file or a link, run, and delete.""" + +from __future__ import annotations + +import json +import shutil +import struct +from pathlib import Path + +import pytest +from PIL import Image +from starlette.testclient import TestClient + +from api_types import ( + CreateCustomLoraRequest, + CustomLoraParams, + ImageToVideoRecipeParams, + InputAssetRef, + LoraEntry, + LoraRecipeInputs, + TextToVideoParams, +) +from pydantic import ValidationError +from remote.app import create_remote_app +from runtime_config.custom_loras import ( + CustomLoraRecord, + custom_lora_dir, + read_custom_lora, + write_meta, +) +from services.features.custom_loras import ( + CustomLoraCreateError, + make_custom_lora_resolver, + resolve_custom_lora_create, +) +from services.features.video import TextToVideoExecutor +from services.features.video.custom_lora import CustomLoraExecutor +from services.features.video.image_to_video import ImageToVideoExecutor +from services.generation_queue.types import OutputAllocation +from services.records import CapabilityFailedError +from services.sqlite_store import SqliteStore +from services.url_downloader import UrlDownloadError +from state.app_state_types import CatalogDownloadSession, DownloadSessionId +from tests.fakes.generation import FakeJobSession +from tests.http_error_assertions import assert_http_error +from tests.test_generation_queue import _generation + +AUTH = {"Authorization": "Bearer pair-token"} +_IC_LORA_MARKER = {"reference_downscale_factor": "1"} +_DESCRIPTION = "A soft ink wash style." + + +def _safetensors(*, metadata: dict[str, str] | None = None, cut_bytes: int = 0) -> bytes: + header: dict[str, object] = { + "transformer_blocks.0.attn1.to_q.lora_A.weight": { + "dtype": "F32", + "shape": [2, 2], + "data_offsets": [0, 16], + }, + "transformer_blocks.0.attn1.to_q.lora_B.weight": { + "dtype": "F32", + "shape": [2, 2], + "data_offsets": [16, 32], + }, + } + if metadata is not None: + header["__metadata__"] = metadata + raw = json.dumps(header).encode("utf-8") + blob = struct.pack(" Path: + path = tmp_path / name + path.write_bytes(_safetensors(**kwargs)) + return path + + +def _import_file(client: TestClient, path: Path, *, name: str = "Ink Wash", **about): + return client.post( + "/api/custom-loras", + json={ + "name": name, + "source_path": str(path), + "description": _DESCRIPTION, + **about, + }, + ) + + +def _import_status(client: TestClient, started) -> dict[str, object]: + assert started.status_code == 200, started.text + progress = client.get( + "/api/custom-loras/import/progress", params={"sessionId": started.json()["sessionId"]} + ) + assert progress.status_code == 200, progress.text + return progress.json() + + +def _install_lora( + test_state, + *, + name: str = "Ink Wash", + lora_id: str = "ink-wash", + trigger: str | None = None, + examples: tuple[str, ...] = (), +) -> None: + directory = custom_lora_dir(test_state.config.default_models_dir, lora_id) + directory.mkdir(parents=True) + filename = f"{lora_id}.safetensors" + (directory / filename).write_bytes(_safetensors()) + write_meta( + directory, + CustomLoraRecord( + id=lora_id, + name=name, + filename=filename, + size_bytes=0, + source="file", + trigger=trigger, + description=_DESCRIPTION, + examples=examples, + ), + ) + + +def _create_body(lora_id: str = "ink-wash", **params): + return { + "params": { + "prompt": "a fox on a skateboard", + "model": "ltx-2.5-fast", + "customLoraId": lora_id, + "scale": 0.8, + "resolution": "720p", + "duration": 8, + "fps": 24, + **params, + } + } + + +# --- import --- + + +def test_import_with_only_a_name_and_weights_is_accepted_and_lists_empty_info( + client: TestClient, tmp_path: Path +) -> None: + started = client.post( + "/api/custom-loras", + json={"name": "Ink Wash", "source_path": str(_weights_file(tmp_path))}, + ) + assert _import_status(client, started)["status"] == "complete" + + (item,) = client.get("/api/custom-loras").json()["loras"] + assert item["trigger"] is None + assert item["description"] == "" + assert item["examples"] == [] + + +def test_the_trigger_description_and_examples_of_an_import_come_back_in_the_list( + client: TestClient, tmp_path: Path +) -> None: + started = _import_file( + client, + _weights_file(tmp_path), + trigger="InkW4sh", + examples=["a fox in InkW4sh style"], + ) + assert _import_status(client, started)["status"] == "complete" + + (item,) = client.get("/api/custom-loras").json()["loras"] + assert item["trigger"] == "InkW4sh" + assert item["description"] == _DESCRIPTION + assert item["examples"] == ["a fox in InkW4sh style"] + + +def test_import_rejects_truncated_weights_instead_of_failing_at_run_time( + client: TestClient, tmp_path: Path +) -> None: + started = _import_file(client, _weights_file(tmp_path, cut_bytes=8)) + + status = _import_status(client, started) + assert status["status"] == "error" + assert "incomplete" in str(status["error"]) + assert client.get("/api/custom-loras").json() == {"loras": []} + + +def test_import_rejects_ic_lora_weights(client: TestClient, tmp_path: Path) -> None: + started = _import_file(client, _weights_file(tmp_path, metadata=_IC_LORA_MARKER)) + + status = _import_status(client, started) + assert status["status"] == "error" + assert "IC-LoRA" in str(status["error"]) + assert client.get("/api/custom-loras").json() == {"loras": []} + + +def test_import_rejects_safetensors_without_lora_tensors( + client: TestClient, tmp_path: Path +) -> None: + header = json.dumps({"w": {"dtype": "F32", "shape": [4], "data_offsets": [0, 16]}}).encode() + non_lora = tmp_path / "plain.safetensors" + non_lora.write_bytes(struct.pack(" None: + first = _import_file(client, _weights_file(tmp_path, "a.safetensors"), name="Ink Wash") + assert _import_status(client, first)["status"] == "complete" + original = custom_lora_dir(test_state.config.default_models_dir, "ink-wash") / "ink-wash.safetensors" + original_bytes = original.read_bytes() + + second = _import_file( + client, _weights_file(tmp_path, "b.safetensors", metadata={"x": "y"}), name="ink-wash" + ) + + assert_http_error( + second, + status_code=409, + code="CUSTOM_LORA_NAME_TAKEN", + message="A custom LoRA with this name already exists.", + ) + assert original.read_bytes() == original_bytes + assert [item["id"] for item in client.get("/api/custom-loras").json()["loras"]] == ["ink-wash"] + + +def test_url_import_refuses_a_private_network_host(client: TestClient) -> None: + for url in ("https://192.168.1.5/lora.safetensors", "https://localhost/lora.safetensors"): + response = client.post( + "/api/custom-loras", json={"name": "Local", "url": url, "description": _DESCRIPTION} + ) + assert response.status_code == 422 + assert response.json()["code"] == "CUSTOM_LORA_URL_INVALID" + assert client.get("/api/custom-loras").json() == {"loras": []} + + +def test_url_import_refuses_a_civitai_page_without_a_version(client: TestClient) -> None: + response = client.post( + "/api/custom-loras", + json={ + "name": "Page", + "url": "https://civitai.com/models/123/some-lora", + "description": _DESCRIPTION, + }, + ) + + assert response.status_code == 422 + assert response.json()["code"] == "CUSTOM_LORA_URL_INVALID" + assert client.get("/api/custom-loras").json() == {"loras": []} + + +def test_url_import_turns_a_civitai_page_with_a_version_into_the_download_link( + client: TestClient, fake_services, test_state +) -> None: + fake_services.url_downloader.payload = _safetensors() + + started = client.post( + "/api/custom-loras", + json={ + "name": "Versioned", + "description": _DESCRIPTION, + "url": "https://civitai.com/models/123/some-lora?modelVersionId=456", + }, + ) + + assert _import_status(client, started)["status"] == "complete" + saved = read_custom_lora(test_state.config.default_models_dir, "versioned") + assert saved is not None + assert saved.source_url == "https://civitai.com/api/download/models/456" + + +def test_url_import_shows_the_downloader_message_for_a_sign_in_wall( + client: TestClient, fake_services +) -> None: + fake_services.url_downloader.error = UrlDownloadError("This file needs a sign-in.") + + started = client.post( + "/api/custom-loras", + json={ + "name": "Gated", + "description": _DESCRIPTION, + "url": "https://huggingface.co/acme/lora/resolve/main/lora.safetensors", + }, + ) + + status = _import_status(client, started) + assert status["status"] == "error" + assert status["error"] == "This file needs a sign-in." + assert client.get("/api/custom-loras").json() == {"loras": []} + + +# --- Hugging Face repo link --- + +_REPO_URL = "https://huggingface.co/acme/dolly-in" + + +def _import_url(client: TestClient, url: str, *, name: str = "Dolly In"): + return client.post( + "/api/custom-loras", + json={"name": name, "url": url, "description": _DESCRIPTION}, + ) + + +def test_repo_link_downloads_the_one_weights_file_and_not_the_readme( + client: TestClient, fake_services, test_state +) -> None: + fake_services.url_downloader.repo_files = [".gitattributes", "README.md", "dolly-in.safetensors"] + fake_services.url_downloader.payload = _safetensors() + + started = _import_url(client, _REPO_URL) + + assert _import_status(client, started)["status"] == "complete" + saved = read_custom_lora(test_state.config.default_models_dir, "dolly-in") + assert saved is not None + assert saved.source_url == "https://huggingface.co/acme/dolly-in/resolve/main/dolly-in.safetensors" + + +def test_repo_link_without_a_weights_file_tells_the_user_and_downloads_nothing( + client: TestClient, fake_services +) -> None: + fake_services.url_downloader.repo_files = [".gitattributes", "README.md"] + + response = _import_url(client, _REPO_URL) + + assert response.status_code == 422 + assert response.json()["code"] == "CUSTOM_LORA_URL_INVALID" + assert "no .safetensors file" in response.json()["message"] + assert client.get("/api/custom-loras").json() == {"loras": []} + + +def test_repo_link_with_two_weights_files_names_both_instead_of_guessing( + client: TestClient, fake_services +) -> None: + fake_services.url_downloader.repo_files = ["dolly-in-v1.safetensors", "dolly-in-v2.safetensors"] + + response = _import_url(client, _REPO_URL) + + assert response.status_code == 422 + assert response.json()["code"] == "CUSTOM_LORA_URL_INVALID" + assert "dolly-in-v1.safetensors" in response.json()["message"] + assert "dolly-in-v2.safetensors" in response.json()["message"] + assert client.get("/api/custom-loras").json() == {"loras": []} + + +# --- Hugging Face page link --- + + +def test_only_a_lora_from_a_hugging_face_link_has_a_model_page_link( + client: TestClient, fake_services, tmp_path: Path +) -> None: + fake_services.url_downloader.payload = _safetensors() + fake_services.url_downloader.repo_files = ["dolly-in.safetensors"] + assert _import_status(client, _import_url(client, _REPO_URL, name="From HF"))["status"] == "complete" + civitai = _import_url( + client, "https://civitai.com/models/123/some-lora?modelVersionId=456", name="From Civitai" + ) + assert _import_status(client, civitai)["status"] == "complete" + from_file = _import_file(client, _weights_file(tmp_path), name="From File") + assert _import_status(client, from_file)["status"] == "complete" + + pages = { + item["name"]: item["page_url"] for item in client.get("/api/custom-loras").json()["loras"] + } + + assert pages == { + "From HF": "https://huggingface.co/acme/dolly-in", + "From Civitai": None, + "From File": None, + } + + +# --- delete --- + + +def test_deleting_the_weights_keeps_the_lora_listed_and_refuses_a_run( + client: TestClient, test_state +) -> None: + _install_lora(test_state) + + deleted = client.delete("/api/custom-loras/ink-wash/weights") + + assert deleted.status_code == 200 + listed = client.get("/api/custom-loras").json()["loras"] + assert [(item["id"], item["downloaded"]) for item in listed] == [("ink-wash", False)] + run = client.post("/api/generations/custom-lora", json=_create_body()) + assert run.status_code == 422 + assert run.json()["code"] == "CUSTOM_LORA_NOT_DOWNLOADED" + + +def test_delete_is_refused_while_the_same_lora_is_importing(client: TestClient, test_state) -> None: + _install_lora(test_state) + test_state.state.custom_lora_import_session = CatalogDownloadSession( + id=DownloadSessionId("session-1"), + item_id="ink-wash", + downloaded_bytes=0, + expected_bytes=0, + ) + + response = client.delete("/api/custom-loras/ink-wash") + + assert response.status_code == 409 + assert response.json()["message"] == "CUSTOM_LORA_IMPORT_RUNNING" + assert custom_lora_dir(test_state.config.default_models_dir, "ink-wash").is_dir() + + +def test_delete_is_refused_while_a_queued_run_holds_the_lora_and_only_for_that_lora( + client: TestClient, test_state +) -> None: + _install_lora(test_state) + _install_lora(test_state, name="Moss", lora_id="moss") + queued = client.post("/api/generations/custom-lora", json=_create_body("ink-wash")) + assert queued.status_code == 200, queued.text + + for path in ("/api/custom-loras/ink-wash/weights", "/api/custom-loras/ink-wash"): + refused = client.delete(path) + assert refused.status_code == 409 + assert refused.json()["code"] == "CUSTOM_LORA_IN_USE" + assert client.delete("/api/custom-loras/moss").status_code == 200 + ink = custom_lora_dir(test_state.config.default_models_dir, "ink-wash") + assert (ink / "ink-wash.safetensors").is_file() + + +# --- run --- + + +def test_retrying_a_run_after_its_weights_were_deleted_fails_with_a_typed_error_not_a_path( + test_state, create_fake_model_files, tmp_path: Path +) -> None: + create_fake_model_files() + test_state.state.app_settings.use_local_text_encoder = True + _install_lora(test_state) + models_dir = test_state.config.default_models_dir + resolver = make_custom_lora_resolver(lambda: models_dir) + executor = CustomLoraExecutor( + TextToVideoExecutor(test_state.video_generation, lora_resolver=resolver), + ImageToVideoExecutor( + test_state.video_generation, + SqliteStore(test_state.config.app_data_dir), + lora_resolver=resolver, + ), + ) + generation = _generation( + feature="custom-lora", + params={ + "prompt": "fox", + "model": "ltx-2.5-fast", + "resolution": "720p", + "duration": 8, + "fps": 24, + "loras": [ + { + "ref": "", + "scale": 0.8, + "customLoraId": "ink-wash", + "displayName": "Ink Wash", + } + ], + }, + ) + shutil.rmtree(custom_lora_dir(models_dir, "ink-wash")) + plan = executor.plan_outputs(generation)[0] + outputs = (OutputAllocation(plan=plan, asset_id="asset-1", dest_path=str(tmp_path / "out.mp4")),) + + with pytest.raises(CapabilityFailedError) as raised: + executor.execute(generation, outputs, FakeJobSession()) + + assert raised.value.code == "CUSTOM_LORA_NOT_DOWNLOADED" + assert "Ink Wash" in str(raised.value) + assert "loras/custom" not in str(raised.value) + + +def test_custom_lora_with_auto_aspect_ratio_and_no_start_frame_is_rejected( + client: TestClient, test_state +) -> None: + _install_lora(test_state) + + response = client.post("/api/generations/custom-lora", json=_create_body(aspectRatio="auto")) + + assert response.status_code == 422 + assert response.json()["code"] == "INVALID_GENERATION_SPEC" + + +def test_a_start_frame_makes_the_run_image_to_video_and_no_start_frame_makes_it_text_to_video( + test_state, +) -> None: + _install_lora(test_state) + models_dir = test_state.config.default_models_dir + params = CustomLoraParams.model_validate(_create_body()["params"]) + start = LoraRecipeInputs(startFrame=InputAssetRef(assetId="asset-1")) + + _, text_params, text_inputs = resolve_custom_lora_create( + CreateCustomLoraRequest(params=params), models_dir=models_dir + ) + _, image_params, image_inputs = resolve_custom_lora_create( + CreateCustomLoraRequest(params=params, inputs=start), models_dir=models_dir + ) + + assert isinstance(text_params, TextToVideoParams) + assert text_inputs is None + assert isinstance(image_params, ImageToVideoRecipeParams) + assert image_inputs is not None + assert image_inputs.startFrame.assetId == "asset-1" + + +def test_custom_lora_with_an_end_frame_is_refused(test_state) -> None: + _install_lora(test_state) + inputs = LoraRecipeInputs( + startFrame=InputAssetRef(assetId="asset-1"), endFrame=InputAssetRef(assetId="asset-2") + ) + + with pytest.raises(CustomLoraCreateError): + resolve_custom_lora_create( + CreateCustomLoraRequest( + params=CustomLoraParams.model_validate(_create_body()["params"]), inputs=inputs + ), + models_dir=test_state.config.default_models_dir, + ) + + +def test_a_lora_saved_with_the_old_mode_key_still_loads(test_state) -> None: + _install_lora(test_state) + meta_path = custom_lora_dir(test_state.config.default_models_dir, "ink-wash") / "meta.json" + meta = json.loads(meta_path.read_text()) + meta["mode"] = "i2v" + meta_path.write_text(json.dumps(meta)) + + assert read_custom_lora(test_state.config.default_models_dir, "ink-wash") is not None + + +def test_run_after_the_lora_is_deleted_returns_not_found(client: TestClient, test_state) -> None: + _install_lora(test_state) + assert client.delete("/api/custom-loras/ink-wash").status_code == 200 + + response = client.post("/api/generations/custom-lora", json=_create_body()) + + assert response.status_code == 404 + assert response.json()["code"] == "CUSTOM_LORA_NOT_FOUND" + + +def test_a_cover_is_stored_with_the_lora_and_the_phone_gets_a_signed_url_not_the_path( + client: TestClient, test_state, tmp_path: Path +) -> None: + cover = tmp_path / "chosen.png" + Image.new("RGB", (8, 8), (10, 20, 30)).save(cover) + started = _import_file(client, _weights_file(tmp_path), cover_path=str(cover)) + assert _import_status(client, started)["status"] == "complete" + + stored = custom_lora_dir(test_state.config.default_models_dir, "ink-wash") / "cover.png" + assert stored.is_file() + (item,) = client.get("/api/custom-loras").json()["loras"] + assert item["cover_url"] == str(stored.resolve()) + + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as remote: + listed = remote.get("/api/custom-loras", headers=AUTH) + cover_url = listed.json()["loras"][0]["cover_url"] + assert cover_url.startswith("/api/custom-loras/ink-wash/cover?") + assert str(test_state.config.default_models_dir) not in listed.text + fetched = remote.get(cover_url) + assert fetched.status_code == 200 + assert fetched.headers["content-type"].startswith("image/png") + + +def test_the_phone_router_cannot_add_restore_or_delete_a_lora(test_state, tmp_path: Path) -> None: + _install_lora(test_state) + weights = _weights_file(tmp_path) + app = create_remote_app(handler=test_state, remote_token="pair-token") + + with TestClient(app) as remote: + attempts = [ + remote.post( + "/api/custom-loras", + headers=AUTH, + json={"name": "Phone", "source_path": str(weights)}, + ), + remote.post( + "/api/custom-loras/ink-wash/weights", headers=AUTH, json={"source_path": str(weights)} + ), + remote.delete("/api/custom-loras/ink-wash/weights", headers=AUTH), + remote.delete("/api/custom-loras/ink-wash", headers=AUTH), + ] + listed = remote.get("/api/custom-loras", headers=AUTH) + + assert [attempt.status_code in (404, 405) for attempt in attempts] == [True] * 4 + assert [item["id"] for item in listed.json()["loras"]] == ["ink-wash"] + assert listed.json()["loras"][0]["downloaded"] is True + + +def test_run_stores_an_empty_ref_until_execute_and_the_phone_never_sees_loras(test_state) -> None: + _install_lora(test_state) + app = create_remote_app(handler=test_state, remote_token="pair-token") + + with TestClient(app) as remote: + created = remote.post("/api/generations/custom-lora", headers=AUTH, json=_create_body()) + + assert created.status_code == 200, created.text + body = created.json() + params = body["spec"]["params"] + assert params["customLoraId"] == "ink-wash" + assert params["customLoraName"] == "Ink Wash" + assert params["scale"] == 0.8 + assert "loras" not in params + assert "safetensors" not in created.text + stored = SqliteStore(test_state.config.app_data_dir).get_generation(body["id"]) + assert stored is not None + stored_params = stored.spec["params"] + assert isinstance(stored_params, dict) + lora = stored_params["loras"][0] + assert lora["ref"] == "" + assert lora["customLoraId"] == "ink-wash" + + +# --- link info (model card) --- + + +def test_a_failed_card_request_gives_empty_suggestions_and_not_an_error( + client: TestClient, fake_services +) -> None: + fake_services.url_downloader.card_error = UrlDownloadError("Could not reach Hugging Face.") + + response = client.post( + "/api/custom-loras/link-info", json={"url": "https://huggingface.co/acme/dolly-in"} + ) + + assert response.status_code == 200 + assert response.json() == { + "accepted": True, + "trigger": None, + "description": "", + "examples": [], + } + + +def test_link_info_marks_accepted_links_and_rejects_local_or_unversioned_links( + client: TestClient, +) -> None: + accepted = ( + "https://huggingface.co/owner/repo", + "https://huggingface.co/owner/repo/resolve/main/model.safetensors", + "https://civitai.com/api/download/models/123", + "https://civitai.com/models/123?modelVersionId=9", + "https://example.com/weights/model.safetensors", + ) + rejected = ( + "https://localhost/model.safetensors", + "https://127.0.0.1/model.safetensors", + "https://10.0.0.1/model.safetensors", + "https://192.168.1.5/model.safetensors", + "https://huggingface.co/owner/repo/resolve/model.safetensors", + "https://civitai.com/models/123", + "https://example.com/weights/model.bin", + ) + + for url in accepted: + response = client.post("/api/custom-loras/link-info", json={"url": url}) + assert response.status_code == 200 + assert response.json()["accepted"] is True, url + for url in rejected: + response = client.post("/api/custom-loras/link-info", json={"url": url}) + assert response.status_code == 200 + assert response.json()["accepted"] is False, url + + +# --- prompt enhancement with a saved LoRA --- + +_LOCAL_ENHANCER_MODEL_ID = "ltx-2.3-22b-distilled-1.1" + + +def test_manual_enhance_gives_the_enhancer_the_trigger_and_description_of_a_custom_lora( + client: TestClient, fake_services, test_state, create_fake_model_files +) -> None: + create_fake_model_files(model_id=_LOCAL_ENHANCER_MODEL_ID) + _install_lora(test_state, trigger="InkW4sh") + fake_services.prompt_enhancer_pipeline.enhanced_prompt = "a fox in a garden" + + response = client.post( + "/api/enhance-prompt", json={"prompt": "a fox", "customLoraIds": ["ink-wash"]} + ) + + assert response.status_code == 200 + assert response.json()["enhancedPrompt"] == "a fox in a garden InkW4sh" + call = fake_services.prompt_enhancer_pipeline.enhance_t2v_calls[0] + assert _DESCRIPTION in call["system_prompt"] + assert "Ink Wash" not in call["system_prompt"] + + +def test_manual_enhance_with_an_unknown_custom_lora_is_refused_and_not_rewritten_generically( + client: TestClient, create_fake_model_files +) -> None: + create_fake_model_files(model_id=_LOCAL_ENHANCER_MODEL_ID) + + response = client.post( + "/api/enhance-prompt", json={"prompt": "a fox", "customLoraIds": ["missing"]} + ) + + assert_http_error(response, status_code=404, code="CUSTOM_LORA_NOT_FOUND") + + +def test_lora_entry_rejects_path_traversal_custom_lora_id_and_dir_helper_refuses_it( + tmp_path: Path, +) -> None: + for bad_id in ("../other", "/tmp/evil", r"\\host\share", "Upper", "a" * 65, ""): + with pytest.raises(ValidationError): + LoraEntry(ref="", customLoraId=bad_id) + with pytest.raises(ValueError): + custom_lora_dir(tmp_path, bad_id) + assert read_custom_lora(tmp_path, bad_id) is None diff --git a/backend/tests/test_custom_lora_urls.py b/backend/tests/test_custom_lora_urls.py new file mode 100644 index 000000000..259e3c1f5 --- /dev/null +++ b/backend/tests/test_custom_lora_urls.py @@ -0,0 +1,110 @@ +"""Rules for a pasted custom LoRA link: which hosts are refused and what is saved.""" + +from __future__ import annotations + +import json +import struct +from pathlib import Path + +import pytest + +from runtime_config.custom_lora_urls import ( + CustomLoraUrlError, + check_fetch_url, + hugging_face_repo_of, + resolve_custom_lora_url, + saved_source_url, +) +from runtime_config.custom_loras import CustomLoraFileError, validate_safetensors_weights + + +@pytest.mark.parametrize( + "url", + [ + "https://127.1/x.safetensors", # short form of 127.0.0.1 + "https://2130706433/x.safetensors", # the same address as one number + "https://0x7f.1/x.safetensors", # hex form + "https://localhost./x.safetensors", # trailing dot is the same host + "https://intranet/x.safetensors", # one label: a private name + "https://[::1]/x.safetensors", + ], +) +def test_private_hosts_in_their_other_spellings_are_refused(url: str) -> None: + with pytest.raises(CustomLoraUrlError, match="private network"): + check_fetch_url(url) + + +def test_a_normal_host_with_a_trailing_dot_is_accepted() -> None: + assert check_fetch_url("https://cdn.example.com./x.safetensors").host == "cdn.example.com" + + +def test_a_civitai_download_link_is_saved_without_its_token_but_fetched_with_it() -> None: + pasted = "https://civitai.com/api/download/models/456?type=Model&token=SECRET" + + fetched = resolve_custom_lora_url(pasted).url + + assert "token=SECRET" in fetched + assert saved_source_url(fetched) == "https://civitai.com/api/download/models/456" + + +@pytest.mark.parametrize( + "link", + [ + "https://cdn.example.com/f/lora.safetensors?X-Amz-Signature=SECRET&X-Amz-Expires=60", + "https://huggingface.co/acme/dolly/resolve/main/dolly.safetensors?token=SECRET#frag", + "https://civitai.com/api/download/models/456?token=SECRET", + ], +) +def test_a_saved_link_keeps_no_query_or_fragment_on_any_host(link: str) -> None: + saved = saved_source_url(link) + + assert "SECRET" not in saved + assert "?" not in saved and "#" not in saved + assert saved.split("?")[0].split("#")[0] == saved + + +def _header_file(tmp_path: Path, offsets: list[object]) -> Path: + header = json.dumps({"w": {"dtype": "F32", "shape": [4], "data_offsets": offsets}}).encode() + path = tmp_path / "w.safetensors" + path.write_bytes(struct.pack(" None: + with pytest.raises(CustomLoraFileError, match="not a .safetensors file"): + validate_safetensors_weights(_header_file(tmp_path, offsets)) + + +@pytest.mark.parametrize( + ("link", "repo_id", "revision"), + [ + ("https://huggingface.co/acme/dolly", "acme/dolly", "main"), + ("https://huggingface.co/acme/dolly/tree/v2", "acme/dolly", "v2"), + ("https://huggingface.co/acme/dolly/blob/main/dolly.safetensors", "acme/dolly", "main"), + ("https://huggingface.co/acme/dolly/resolve/v2/dolly.safetensors", "acme/dolly", "v2"), + ("https://hf.co/acme/dolly", "acme/dolly", "main"), + ], +) +def test_every_kind_of_hugging_face_repo_link_names_its_repo_and_revision( + link: str, repo_id: str, revision: str +) -> None: + repo = hugging_face_repo_of(link) + + assert repo is not None + assert (repo.repo_id, repo.revision) == (repo_id, revision) + + +@pytest.mark.parametrize( + "link", + [ + "https://huggingface.co/datasets/acme/data", # a dataset is not a model card + "https://huggingface.co/spaces/acme/demo", + "https://example.com/acme/dolly", + "http://huggingface.co/acme/dolly", + ], +) +def test_a_link_that_is_not_a_hugging_face_model_repo_has_no_card(link: str) -> None: + assert hugging_face_repo_of(link) is None diff --git a/backend/tests/test_dashboard_image_runs.py b/backend/tests/test_dashboard_image_runs.py new file mode 100644 index 000000000..8a1ac8e34 --- /dev/null +++ b/backend/tests/test_dashboard_image_runs.py @@ -0,0 +1,36 @@ +"""The video dashboard leaves image runs out.""" + +from __future__ import annotations + +from pathlib import Path + +from services.features.image.feature_id import FEATURE as TEXT_TO_IMAGE_FEATURE +from tests.test_dashboard_stats import DAY, NOW, _insert, _open, _spec + + +def test_image_runs_are_left_out_of_the_video_dashboard(tmp_path: Path) -> None: + # Bug caught: image runs count as video generations in the activity chart. + store, conn = _open(tmp_path) + for generation_id, feature, status in ( + ("video", "text-to-video", "succeeded"), + ("image", TEXT_TO_IMAGE_FEATURE, "succeeded"), + ("image-failed", TEXT_TO_IMAGE_FEATURE, "failed"), + ): + _insert( + conn, + generation_id=generation_id, + feature=feature, + status=status, + finished=DAY, + run_ms=1_000, + spec=_spec(), + error_code="IMAGE_BLOCKED_BY_SAFETY_CHECKER" if status == "failed" else None, + ) + conn.commit() + conn.close() + + snapshot = store.dashboard(window="7d", tz="UTC", now=NOW) + + counts = snapshot.activity[-1].counts + assert counts["text-to-video"] == 1 + assert sum(counts.values()) == 1 diff --git a/backend/tests/test_dashboard_stats.py b/backend/tests/test_dashboard_stats.py index 9b314c541..744c7426f 100644 --- a/backend/tests/test_dashboard_stats.py +++ b/backend/tests/test_dashboard_stats.py @@ -753,6 +753,7 @@ def test_every_queued_feature_lands_in_a_chart_series(tmp_path: Path) -> None: plain = { "text-to-video", "image-to-video", + "keyframes", "audio-to-video", "retake", "extend", @@ -779,6 +780,7 @@ def test_every_queued_feature_lands_in_a_chart_series(tmp_path: Path) -> None: assert set(snapshot.activity[-1].counts) == { "text-to-video", "image-to-video", + "keyframes", "audio-to-video", "lora", "retake", diff --git a/backend/tests/test_day_to_night.py b/backend/tests/test_day_to_night.py index d42488f8a..fb69530ba 100644 --- a/backend/tests/test_day_to_night.py +++ b/backend/tests/test_day_to_night.py @@ -36,7 +36,7 @@ from app_factory import create_app from app_handler import ServiceBundle from handlers.base import resolve_models_dir -from runtime_config.ic_lora_high_res import HIGH_RES_ONLY_IC_LORAS +from runtime_config.ic_lora_high_res import HIGH_RES_WITHOUT_FLAG_IC_LORAS from runtime_config.ltx_capabilities import budget_pixels, local_caps from runtime_config.model_download_specs import resolve_ic_lora_path from runtime_config.video_job_budget import VIDEO_JOB_TOO_LARGE @@ -49,6 +49,7 @@ from services.features.video.ic_lora_recipe import IcLoraRecipeExecutor from services.generation_interrupt import GenerationCancelledError from services.generation_queue.types import OutputAllocation, OutputPlan +from tests.fakes.generation import FakeJobSession from services.media_probe import _stream_fps, probe_file from services.records import AssetRecord, CapabilityFailedError, GenerationRecord from services.sqlite_store import SqliteStore @@ -1017,6 +1018,7 @@ def get_asset(self, asset_id: str) -> AssetRecord | None: dest_path=str(tmp_path / "output.mp4"), ), ), + FakeJobSession(), ) except GenerationCancelledError: pass @@ -1041,10 +1043,10 @@ def test_ic_lora_recipe_table_matches_shared_json() -> None: recipe.recipe_id: (recipe.catalog_id, recipe.kind) for recipe in IC_LORA_RECIPES.values() } assert actual == expected - # The frontend hides these recipes without the flag. The backend refuses the same set. + # The frontend offers the high cells of these recipes without the flag. The backend allows the same set. assert { - entry["catalogId"] for entry in contract if entry.get("requiresHighRes") is True - } == HIGH_RES_ONLY_IC_LORAS + entry["catalogId"] for entry in contract if entry.get("highResWithoutFlag") is True + } == HIGH_RES_WITHOUT_FLAG_IC_LORAS _GIB = 1024**3 diff --git a/backend/tests/test_device_calibration.py b/backend/tests/test_device_calibration.py new file mode 100644 index 000000000..1e13aead5 --- /dev/null +++ b/backend/tests/test_device_calibration.py @@ -0,0 +1,610 @@ +"""A clean local run proves its own shape on this device, and nothing wider.""" + +from __future__ import annotations + +import dataclasses +import sqlite3 +from collections.abc import Mapping +from pathlib import Path + +import pytest + +from runtime_config.budget_evidence import JobShape +from runtime_config.device_calibration import ( + CALIBRATION_EPOCH, + EMPTY_CALIBRATION, + CalibrationBucket, + DeviceCalibration, + DeviceIdentity, + EnvelopePoint, + FrontierPoint, + JobEnvelope, + RunMemoryBaseline, + RunMemoryEnd, + clean_run_verdict, + envelope_for, + merge_frontier, +) +from runtime_config.eta import estimate_envelope_wall_time +from runtime_config.video_job_budget import VIDEO_JOB_TOO_LARGE +from services.gpu_info import run_peak +from services.records import UnavailableError +from services.sqlite_store import SqliteStore + +_GIB = 1024**3 +_MIB = 1024**2 +_5090 = DeviceIdentity( + system="Windows", gpu_model="NVIDIA GeForce RTX 5090", total_memory_bytes=int(31.84 * _GIB) +) +_MAC = DeviceIdentity(system="Darwin", gpu_model="Apple M4 Max", total_memory_bytes=128 * _GIB) +_BUCKET = CalibrationBucket( + model_id="ltx-2.5-22b-distilled", + feature="fast", + adapter_id="", + stage_mode="", + load_mode="streaming_models_loading", + tiled=False, + chunked=False, +) +_UNMEASURED_1440P = {"prompt": "test", "resolution": "1440p", "model": "fast", "duration": 20, "fps": 50} +_START = RunMemoryBaseline( + free_vram_bytes=int(24.0 * _GIB), reserved_bytes=int(0.5 * _GIB), swap_used_bytes=2 * _GIB +) + + +def _point(seq: float, canvas_px: int, windows: int = 1) -> FrontierPoint: + return FrontierPoint( + point=EnvelopePoint(seq=seq, canvas_px=canvas_px, windows=windows), + peak_growth_bytes=20 * _GIB, + ) + + +def _job(seq: float, canvas_px: int, windows: int = 1) -> JobEnvelope: + return JobEnvelope( + bucket=_BUCKET, + point=EnvelopePoint(seq=seq, canvas_px=canvas_px, windows=windows), + priced_gib=27.0, + ) + + +def _calibration(*runs: FrontierPoint) -> DeviceCalibration: + frontier: tuple[FrontierPoint, ...] = () + for run in runs: + frontier = merge_frontier(frontier, run) or frontier + return DeviceCalibration(identity=_5090, frontier={_BUCKET: frontier}) + + +def _widen(store: SqliteStore, run: FrontierPoint) -> tuple[FrontierPoint, ...] | None: + return store.widen_device_frontier( + _5090, CALIBRATION_EPOCH, _BUCKET, run, priced_gib=27.0, generation_id="g" + ) + + +def _end(peak_gib: float, *, min_free_gib: float = 4.0) -> RunMemoryEnd: + return RunMemoryEnd( + peak_reserved_bytes=int(peak_gib * _GIB), + min_free_vram_bytes=int(min_free_gib * _GIB), + swap_used_bytes=2 * _GIB, + ) + + +def _configure_5090(test_state, fake_services, create_fake_model_files) -> None: + create_fake_model_files() + test_state.config.system = "Windows" + test_state.config.gpu_device_name = _5090.gpu_model + test_state.config.vram_gb = 31 + test_state.config.vram_bytes = _5090.total_memory_bytes + test_state.config.total_ram_bytes = 64 * _GIB + test_state.config.local_generations_mode = "streaming_models_loading" + test_state.state.app_settings.use_local_text_encoder = True + gpu = fake_services.gpu_info + gpu.free_vram_bytes = _START.free_vram_bytes + gpu.reserved_bytes = _START.reserved_bytes + gpu.swap_used_bytes = _START.swap_used_bytes + gpu.run_end = _end(peak_gib=20.0) + + +def _post_unmeasured(client, test_state, mode: str) -> int: + test_state.state.app_settings.budget_mode = mode + return client.post("/api/generate", json=_UNMEASURED_1440P).status_code + + +def test_two_incomparable_runs_do_not_cover_their_corner() -> None: + long_1080p = _point(seq=60_000, canvas_px=1920 * 1088) + short_4k = _point(seq=30_000, canvas_px=3840 * 2176) + calibration = _calibration(long_1080p, short_4k) + + assert calibration.covering(_job(60_000, 3840 * 2176)) is None + assert calibration.covering(_job(50_000, 1920 * 1088)) == long_1080p + assert calibration.covering(_job(25_000, 2560 * 1472)) == short_4k + + +def test_equal_shape_rerun_graduates() -> None: + ran = _point(seq=60_000, canvas_px=2560 * 1472, windows=2) + + assert _calibration(ran).covering(_job(60_000, 2560 * 1472, windows=2)) == ran + + +def test_dominated_run_adds_no_row(tmp_path: Path) -> None: + store = SqliteStore(tmp_path) + big = _point(seq=60_000, canvas_px=2560 * 1472) + + assert _widen(store, big) == (big,) + assert _widen(store, _point(seq=40_000, canvas_px=1920 * 1088)) is None + assert store.load_device_frontier(_5090, CALIBRATION_EPOCH) == {_BUCKET: (big,)} + + +def test_dominating_run_prunes_only_points_within_it(tmp_path: Path) -> None: + store = SqliteStore(tmp_path) + small = _point(seq=30_000, canvas_px=1920 * 1088) + neighbor = _point(seq=20_000, canvas_px=3840 * 2176) + dominating = _point(seq=60_000, canvas_px=2560 * 1472) + _widen(store, small) + _widen(store, neighbor) + + assert _widen(store, dominating) == (dominating, neighbor) + loaded = store.load_device_frontier(_5090, CALIBRATION_EPOCH) + assert set(loaded[_BUCKET]) == {dominating, neighbor} + + +def test_run_whose_reserved_growth_exceeds_start_free_is_not_recorded() -> None: + # The 1080p retake that paged 0.4 GiB past free and still finished. + assert clean_run_verdict(_5090, _START, _end(peak_gib=25.0)) == "vram_growth" + assert clean_run_verdict(_5090, _START, _end(peak_gib=23.0)) == "clean" + + +def test_run_that_hit_free_floor_is_not_recorded() -> None: + squeezed = _end(peak_gib=20.0, min_free_gib=0.25) + + assert clean_run_verdict(_5090, _START, squeezed) == "free_floor" + assert clean_run_verdict(_5090, _START, _end(peak_gib=20.0, min_free_gib=1.0)) == "clean" + + +def test_darwin_run_with_swap_growth_is_not_recorded() -> None: + start = RunMemoryBaseline(free_vram_bytes=None, reserved_bytes=None, swap_used_bytes=_GIB) + stalled = RunMemoryEnd( + peak_reserved_bytes=None, min_free_vram_bytes=None, swap_used_bytes=_GIB + 512 * _MIB + ) + steady = RunMemoryEnd( + peak_reserved_bytes=None, min_free_vram_bytes=None, swap_used_bytes=_GIB + 100 * _MIB + ) + + assert clean_run_verdict(_MAC, start, stalled) == "swap_growth" + assert clean_run_verdict(_MAC, start, steady) == "clean" + + +def test_cuda_run_with_swap_growth_is_not_recorded() -> None: + # A host-RAM-shortfall run on Windows/Linux can stay within VRAM limits while + # paging host RAM to swap during CPU offload. + paged_swap = dataclasses.replace(_end(peak_gib=20.0), swap_used_bytes=2 * _GIB + 512 * _MIB) + steady_swap = dataclasses.replace(_end(peak_gib=20.0), swap_used_bytes=2 * _GIB + 100 * _MIB) + + assert clean_run_verdict(_5090, _START, paged_swap) == "swap_growth" + assert clean_run_verdict(_5090, _START, steady_swap) == "clean" + + +def test_cuda_run_without_swap_probe_still_graduates_on_vram_signals() -> None: + start_no_swap = dataclasses.replace(_START, swap_used_bytes=None) + end_no_swap = dataclasses.replace(_end(peak_gib=20.0), swap_used_bytes=None) + + assert clean_run_verdict(_5090, start_no_swap, end_no_swap) == "clean" + + +def test_missing_cuda_peak_probe_records_nothing() -> None: + no_peak = RunMemoryEnd( + peak_reserved_bytes=None, min_free_vram_bytes=4 * _GIB, swap_used_bytes=2 * _GIB + ) + + assert clean_run_verdict(_5090, _START, no_peak) == "no_evidence" + assert clean_run_verdict(_5090, _START, _end(peak_gib=20.0)) == "clean" + + +def test_cancelled_generation_records_nothing( + test_state, fake_services, create_fake_model_files +) -> None: + _configure_5090(test_state, fake_services, create_fake_model_files) + test_state.pipelines.load_gpu_pipeline("fast") + store = SqliteStore(test_state.config.app_data_dir) + ran = _job(60_000, 2560 * 1472) + + assert test_state.generation.try_reserve_generation_start() + test_state.generation.start_generation("cancelled") + assert run_peak._watch.active is True + test_state.generation.cancel_generation() + assert run_peak._watch.active is False + test_state.generation.complete_generation("/out.mp4", ran=ran) + test_state.generation.release_generation_start_reservation() + assert store.load_device_frontier(_5090, CALIBRATION_EPOCH) == {} + + assert test_state.generation.try_reserve_generation_start() + test_state.generation.start_generation("failed") + assert run_peak._watch.active is True + test_state.generation.fail_generation("boom") + assert run_peak._watch.active is False + test_state.generation.release_generation_start_reservation() + assert store.load_device_frontier(_5090, CALIBRATION_EPOCH) == {} + + assert test_state.generation.try_reserve_generation_start() + test_state.generation.start_generation("finished") + assert run_peak._watch.active is True + test_state.generation.complete_generation("/out.mp4", ran=ran) + assert run_peak._watch.active is False + test_state.generation.release_generation_start_reservation() + assert store.load_device_frontier(_5090, CALIBRATION_EPOCH) == { + _BUCKET: (FrontierPoint(point=ran.point, peak_growth_bytes=int(19.5 * _GIB)),) + } + + +class _FailingCalibrationStore: + def load_device_frontier( + self, identity: DeviceIdentity, epoch: int + ) -> Mapping[CalibrationBucket, tuple[FrontierPoint, ...]]: + del identity, epoch + return {} + + def load_device_machine_factor( + self, identity: DeviceIdentity, epoch: int + ) -> float | None: + del identity, epoch + return None + + def widen_device_frontier( + self, + identity: DeviceIdentity, + epoch: int, + bucket: CalibrationBucket, + point: FrontierPoint, + *, + priced_gib: float, + generation_id: str | None, + conv_vae: bool = False, + ) -> tuple[FrontierPoint, ...] | None: + del identity, epoch, bucket, point, priced_gib, generation_id, conv_vae + raise UnavailableError("database is locked") + + +def test_calibration_store_error_does_not_fail_generation( + client, test_state, fake_services, create_fake_model_files +) -> None: + _configure_5090(test_state, fake_services, create_fake_model_files) + test_state.calibration.bind(_FailingCalibrationStore()) + + test_state.state.app_settings.budget_mode = "brave" + response = client.post("/api/generate", json=_UNMEASURED_1440P) + + assert response.status_code == 200 + assert response.json()["status"] == "complete" + assert _post_unmeasured(client, test_state, "cautious") == 422 + + +def test_extrapolated_load_inside_recorded_envelope_admitted_in_cautious( + client, test_state, fake_services, create_fake_model_files +) -> None: + _configure_5090(test_state, fake_services, create_fake_model_files) + test_state.state.app_settings.budget_mode = "cautious" + refused = client.post("/api/generate", json=_UNMEASURED_1440P) + assert refused.status_code == 422 + assert refused.json()["code"] == VIDEO_JOB_TOO_LARGE + + assert _post_unmeasured(client, test_state, "brave") == 200 + + assert _post_unmeasured(client, test_state, "cautious") == 200 + + +def test_chunked_run_does_not_graduate_unchunked_job() -> None: + chunked = JobShape( + feature="fast", + model_id="ltx-2.5-22b-distilled", + adapter_id="", + stage_mode="", + tiled=False, + chunked=True, + seq=30_000, + canvas_px=2560 * 1472, + windows=3, + ) + ran = envelope_for(chunked, "streaming_models_loading", 20.0) + proof = FrontierPoint(point=ran.point, peak_growth_bytes=18 * _GIB) + calibration = DeviceCalibration(identity=_5090, frontier={ran.bucket: (proof,)}) + unchunked = envelope_for( + dataclasses.replace(chunked, chunked=False), "streaming_models_loading", 27.0 + ) + + assert calibration.covering(unchunked) is None + assert calibration.covering(ran) == proof + + +def test_old_epoch_rows_do_not_graduate(tmp_path: Path) -> None: + store = SqliteStore(tmp_path) + ran = _point(seq=60_000, canvas_px=2560 * 1472) + _widen(store, ran) + + assert store.load_device_frontier(_5090, CALIBRATION_EPOCH + 1) == {} + assert store.load_device_frontier(_5090, CALIBRATION_EPOCH) == {_BUCKET: (ran,)} + + +def test_frontier_reloaded_on_boot( + client, test_state, fake_services, create_fake_model_files, default_app_settings +) -> None: + _configure_5090(test_state, fake_services, create_fake_model_files) + assert _post_unmeasured(client, test_state, "brave") == 200 + + test_state.state.device_calibration = EMPTY_CALIBRATION + test_state.load_persistent_state(default_app_settings) + test_state.state.app_settings.use_local_text_encoder = True + + assert _post_unmeasured(client, test_state, "cautious") == 200 + + +def test_device_calibration_frontier_matches_and_coalesces_rows_within_512_mib_total_memory_drift( + tmp_path: Path, +) -> None: + store = SqliteStore(tmp_path) + pre_reboot = _5090 + post_reboot = dataclasses.replace(_5090, total_memory_bytes=_5090.total_memory_bytes - 256 * _MIB) + different_sku = dataclasses.replace(_5090, total_memory_bytes=16 * _GIB) + small = _point(seq=30_000, canvas_px=1920 * 1088) + dominating = _point(seq=60_000, canvas_px=2560 * 1472) + + store.widen_device_frontier( + pre_reboot, CALIBRATION_EPOCH, _BUCKET, small, priced_gib=20.0, generation_id="g1" + ) + assert store.load_device_frontier(post_reboot, CALIBRATION_EPOCH) == {_BUCKET: (small,)} + assert store.load_device_frontier(different_sku, CALIBRATION_EPOCH) == {} + + widened = store.widen_device_frontier( + post_reboot, CALIBRATION_EPOCH, _BUCKET, dominating, priced_gib=27.0, generation_id="g2" + ) + assert widened == (dominating,) + assert store.load_device_frontier(pre_reboot, CALIBRATION_EPOCH) == {_BUCKET: (dominating,)} + assert store.load_device_frontier(post_reboot, CALIBRATION_EPOCH) == {_BUCKET: (dominating,)} + + +def test_clean_run_and_history_calibrate_device_machine_factor(tmp_path: Path) -> None: + store = SqliteStore(tmp_path) + timed = FrontierPoint( + point=EnvelopePoint(seq=9216, canvas_px=1024 * 576, windows=1), + peak_growth_bytes=8 * _GIB, + wall_s=240.0, + ) + store.widen_device_frontier( + _5090, CALIBRATION_EPOCH, _BUCKET, timed, priced_gib=10.0, generation_id="g-timed" + ) + factor = store.load_device_machine_factor(_5090, CALIBRATION_EPOCH) + assert factor is not None and factor > 1.5 + + + + +def test_smaller_run_does_not_rewrite_dominating_point_wall_time(tmp_path: Path) -> None: + store = SqliteStore(tmp_path) + big = FrontierPoint( + point=EnvelopePoint(seq=9216, canvas_px=1024 * 576, windows=1), + peak_growth_bytes=8 * _GIB, + wall_s=312.0, + ) + small = FrontierPoint( + point=EnvelopePoint(seq=1440, canvas_px=512 * 288, windows=1), + peak_growth_bytes=4 * _GIB, + wall_s=229.0, + ) + store.widen_device_frontier( + _5090, CALIBRATION_EPOCH, _BUCKET, big, priced_gib=10.0, generation_id="g-big" + ) + before = store.load_device_machine_factor(_5090, CALIBRATION_EPOCH) + store.widen_device_frontier( + _5090, CALIBRATION_EPOCH, _BUCKET, small, priced_gib=10.0, generation_id="g-small" + ) + assert store.load_device_frontier(_5090, CALIBRATION_EPOCH) == {_BUCKET: (big,)} + assert store.load_device_machine_factor(_5090, CALIBRATION_EPOCH) == before + + rerun = dataclasses.replace(big, wall_s=300.0) + store.widen_device_frontier( + _5090, CALIBRATION_EPOCH, _BUCKET, rerun, priced_gib=10.0, generation_id="g-rerun" + ) + assert store.load_device_frontier(_5090, CALIBRATION_EPOCH) == {_BUCKET: (rerun,)} + + +def test_frontier_inverts_wall_time_with_the_decode_the_run_used(tmp_path: Path) -> None: + timed = FrontierPoint( + point=EnvelopePoint(seq=17280, canvas_px=1280 * 704, windows=1), + peak_growth_bytes=8 * _GIB, + wall_s=314.0, + ) + factors: dict[bool, float | None] = {} + for conv_vae in (False, True): + store = SqliteStore(tmp_path / str(conv_vae)) + store.widen_device_frontier( + _5090, + CALIBRATION_EPOCH, + _BUCKET, + timed, + priced_gib=10.0, + generation_id="g", + conv_vae=conv_vae, + ) + factors[conv_vae] = store.load_device_machine_factor(_5090, CALIBRATION_EPOCH) + diff_vae, conv = factors[False], factors[True] + # ConvVAE decodes faster, so more of the same wall time is streaming. + assert diff_vae is not None and conv is not None and conv > diff_vae + + +def test_fresh_store_creates_the_frontier_with_timing_and_tile_columns(tmp_path: Path) -> None: + SqliteStore(tmp_path) + conn = sqlite3.connect(tmp_path / "store.sqlite3") + columns = {str(row[1]) for row in conn.execute("PRAGMA table_info(device_calibration_frontier)")} + conn.close() + assert {"wall_s", "conv_vae", "tiles"} <= columns + + +def test_tiled_run_is_inverted_with_the_tile_count_it_ran_with(tmp_path: Path) -> None: + """The stored row keeps its tile count, so the factor does not absorb the tiles.""" + tiled_bucket = CalibrationBucket( + model_id="ltx-2.5-22b-distilled", + feature="iclora", + adapter_id="restore", + stage_mode="single_stage", + load_mode="streaming_models_loading", + tiled=True, + chunked=False, + ) + ran = EnvelopePoint(seq=9216, canvas_px=1280 * 704 * 2, windows=1, tiles=4) + wall = estimate_envelope_wall_time( + JobEnvelope(bucket=tiled_bucket, point=ran, priced_gib=10.0), + system="Windows", + machine_factor=1.0, + ) + assert wall is not None + store = SqliteStore(tmp_path) + store.widen_device_frontier( + _5090, + CALIBRATION_EPOCH, + tiled_bucket, + FrontierPoint(point=ran, peak_growth_bytes=8 * _GIB, wall_s=float(wall.seconds)), + priced_gib=10.0, + generation_id="g-tiled", + ) + + stored = store.load_device_frontier(_5090, CALIBRATION_EPOCH)[tiled_bucket] + assert [point.point.tiles for point in stored] == [4] + factor = store.load_device_machine_factor(_5090, CALIBRATION_EPOCH) + assert factor is not None and factor == pytest.approx(1.0, abs=0.05) + + +def test_history_bootstrap_ignores_api_models_and_fast_lora_recipes_as_ic_lora( + tmp_path: Path, +) -> None: + store = SqliteStore(tmp_path) + conn = sqlite3.connect(tmp_path / "store.sqlite3") + t0 = 1_794_000_000_000 + meta = '{"mediaType":"video","metadata":{"width":1024,"height":576,"durationMs":5000,"fps":24}}' + rows = [ + ("api-1", "text-to-video", '{"params":{"model":"fast-2.5","resolution":"540p"}}', 45_000), + ("local-1", "claymation", '{"params":{"model":"ltx-2.5-fast","resolution":"540p"}}', 240_000), + ("local-2", "text-to-video", '{"params":{"model":"ltx-2.5-fast","resolution":"540p"}}', 240_000), + ("local-3", "jib-up", '{"params":{"model":"ltx-2.5-fast","resolution":"540p"}}', 240_000), + ] + for idx, (gid, feature, spec, dur_ms) in enumerate(rows): + conn.execute( + """ + INSERT INTO generations ( + id, feature, status, lane, contract_version, spec, + created_at, queued_at, started_at, finished_at + ) VALUES (?, ?, 'succeeded', 'local', 1, ?, ?, ?, ?, ?) + """, + (gid, feature, spec, t0 + idx, t0 + idx, t0, t0 + dur_ms), + ) + conn.execute( + """ + INSERT INTO assets ( + id, media_kind, origin, producer_generation_id, output_ordinal, + mime_type, name, metadata, created_at + ) VALUES (?, 'video', 'generated', ?, 0, 'video/mp4', ?, ?, ?) + """, + (f"asset-{gid}", gid, f"{gid}.mp4", meta, t0 + idx), + ) + conn.commit() + conn.close() + + factor = store.load_device_machine_factor(_5090, CALIBRATION_EPOCH) + assert factor is not None and 2.5 < factor < 3.5 + + +def _insert_history_run( + conn: sqlite3.Connection, gid: str, feature: str, meta: str, *, dur_ms: int, idx: int +) -> None: + t0 = 1_794_000_000_000 + conn.execute( + """ + INSERT INTO generations ( + id, feature, status, lane, contract_version, spec, + created_at, queued_at, started_at, finished_at + ) VALUES (?, ?, 'succeeded', 'local', 1, ?, ?, ?, ?, ?) + """, + ( + gid, + feature, + '{"params":{"model":"ltx-2.5-fast","resolution":"540p"}}', + t0 + idx, + t0 + idx, + t0, + t0 + dur_ms, + ), + ) + conn.execute( + """ + INSERT INTO assets ( + id, media_kind, origin, producer_generation_id, output_ordinal, + mime_type, name, metadata, created_at + ) VALUES (?, 'video', 'generated', ?, 0, 'video/mp4', ?, ?, ?) + """, + (f"asset-{gid}", gid, f"{gid}.mp4", meta, t0 + idx), + ) + + +def test_history_skips_rows_with_odd_stored_values_instead_of_raising(tmp_path: Path) -> None: + """A float or an absurd duration in stored metadata must not abort the startup load.""" + store = SqliteStore(tmp_path) + conn = sqlite3.connect(tmp_path / "store.sqlite3") + good = '{"mediaType":"video","metadata":{"width":1024,"height":576,"durationMs":5000,"fps":24}}' + float_ms = '{"mediaType":"video","metadata":{"width":1024,"height":576,"durationMs":5000.5,"fps":24}}' + huge_ms = '{"mediaType":"video","metadata":{"width":1024,"height":576,"durationMs":1000000000000,"fps":24}}' + runs = [(good, 240_000)] * 3 + [(float_ms, 240_000), (huge_ms, 240_000)] + for idx, (meta, dur_ms) in enumerate(runs): + _insert_history_run(conn, f"run-{idx}", "text-to-video", meta, dur_ms=dur_ms, idx=idx) + conn.commit() + conn.close() + + factor = store.load_device_machine_factor(_5090, CALIBRATION_EPOCH) + + # The three good rows still calibrate. The odd rows are skipped. + assert factor is not None and 2.5 < factor < 3.5 + + +def test_same_shape_rerun_takes_over_the_frontier_row_generation_id(tmp_path: Path) -> None: + """The refreshed row belongs to the new run, so the history query does not count it twice.""" + store = SqliteStore(tmp_path) + point = FrontierPoint( + point=EnvelopePoint(seq=9216, canvas_px=1024 * 576, windows=1), + peak_growth_bytes=8 * _GIB, + wall_s=312.0, + ) + store.widen_device_frontier( + _5090, CALIBRATION_EPOCH, _BUCKET, point, priced_gib=10.0, generation_id="g-first" + ) + store.widen_device_frontier( + _5090, + CALIBRATION_EPOCH, + _BUCKET, + dataclasses.replace(point, wall_s=300.0), + priced_gib=10.0, + generation_id="g-rerun", + ) + + conn = sqlite3.connect(tmp_path / "store.sqlite3") + rows = conn.execute("SELECT generation_id, wall_s FROM device_calibration_frontier").fetchall() + conn.close() + + assert rows == [("g-rerun", 300.0)] + + +class _RefreshFailsStore(SqliteStore): + def load_device_machine_factor(self, identity, epoch): # type: ignore[no-untyped-def] + raise UnavailableError() + + +def test_failed_machine_factor_refresh_keeps_the_recorded_frontier_point( + test_state, fake_services, create_fake_model_files, tmp_path: Path +) -> None: + _configure_5090(test_state, fake_services, create_fake_model_files) + handler = test_state.calibration + handler.bind(_RefreshFailsStore(tmp_path)) + ran = _job(9216, 1024 * 576) + + verdict = handler.record_if_clean(ran, _START, _end(peak_gib=20.0), generation_id="g", wall_s=240.0) + + assert verdict == "clean" + recorded = test_state.state.device_calibration.frontier[_BUCKET] + assert [point.point for point in recorded] == [ran.point] + assert test_state.state.device_calibration.machine_factor is None + diff --git a/backend/tests/test_diffusion_stage_cache.py b/backend/tests/test_diffusion_stage_cache.py index aa1e058d7..ced626c1d 100644 --- a/backend/tests/test_diffusion_stage_cache.py +++ b/backend/tests/test_diffusion_stage_cache.py @@ -1,22 +1,27 @@ """Tests for the diffusion_stage_cache patch (experiment/diffusion-stage-cache). -Uses the real (but cheap-to-construct, side-effect-free) SingleGPUModelBuilder / -StreamingModelBuilder classes from ltx_core as data holders, and a minimal fake +Uses the real (but cheap-to-construct, side-effect-free) SimpleBuilder / +StreamingBuilder classes from ltx_core as data holders, and a minimal fake DiffusionStage duck-typing only the private surface diffusion_stage_cache.py reads (_is_streaming, _prepared_builder, _build_transformer, _quantization, -_compilation_config, _dtype, _device) -- no mocking library, no real GPU, no real -checkpoint files. The cache's own internal functions are exercised directly rather +_compilation_config, _dtype, _device), plus the ``_transformer_lifetime`` +members the upstream ``_transformer_ctx`` reads when the cache is bypassed -- no mocking +library, no real GPU, no real checkpoint files. The cache's own internal functions are exercised directly rather than through the real (monkeypatched) DiffusionStage._transformer_ctx, so these tests do not depend on the patch actually being installed on the class. """ from __future__ import annotations +from contextlib import AbstractContextManager +from pathlib import Path + import pytest -from ltx_core.block_streaming import StreamingModelBuilder -from ltx_core.loader.single_gpu_model_builder import SingleGPUModelBuilder +from ltx_core.loader.simple_builder import LoRARequest, SimpleBuilder +from ltx_core.loader.streaming_builder import StreamingBuilder, StreamingConfig from ltx_core.allocator_trim_strategy import AllocatorTrimStrategy +from ltx_pipelines.utils.gpu_model import gpu_model from services.patches import diffusion_stage_cache as dsc @@ -63,9 +68,12 @@ def _build_transformer(self, **_kwargs: object) -> _FakeModel: self.build_count += 1 return _FakeModel() + def _transformer_lifetime(self, transformer: _FakeModel) -> AbstractContextManager[_FakeModel]: + return gpu_model(transformer, alloc_trim_strategy=self._alloc_trim_strategy) + -def _single_gpu_builder(model_path: str, loras: tuple[object, ...] = ()) -> SingleGPUModelBuilder: - return SingleGPUModelBuilder(model_class_configurator=object, model_path=model_path, loras=loras) +def _single_gpu_builder(model_path: str, loras: tuple[LoRARequest, ...] = ()) -> SimpleBuilder: + return SimpleBuilder(object, (Path(model_path),), loras=loras) # type: ignore[arg-type] @pytest.fixture(autouse=True) @@ -108,7 +116,7 @@ def test_cache_miss_on_different_checkpoint_evicts_old_model() -> None: def test_different_loras_are_treated_as_a_different_config() -> None: stage_a = _FakeStage(_single_gpu_builder("ckpt.safetensors", loras=())) - stage_b = _FakeStage(_single_gpu_builder("ckpt.safetensors", loras=(("lora.safetensors", 1.0),))) + stage_b = _FakeStage(_single_gpu_builder("ckpt.safetensors", loras=(LoRARequest((Path("lora.safetensors"),), 1.0),))) with dsc._cached_transformer_ctx(stage_a): pass @@ -120,7 +128,9 @@ def test_different_loras_are_treated_as_a_different_config() -> None: def test_cacheable_returns_false_for_a_streaming_stage() -> None: - streaming_builder = StreamingModelBuilder(model_class_configurator=object, model_path="ckpt.safetensors") + streaming_builder = StreamingBuilder( + _single_gpu_builder("ckpt.safetensors"), StreamingConfig("transformer_blocks", "disk") + ) streaming_stage = _FakeStage(streaming_builder, is_streaming=True) assert dsc._cacheable(streaming_stage) is False @@ -133,15 +143,15 @@ def test_cacheable_skips_when_model_wrapper_is_set() -> None: class _OtherBuilder: - """Stand-in for a non-SingleGPUModelBuilder, non-streaming builder (e.g. a multi-GPU tiled builder).""" + """Stand-in for a non-SimpleBuilder, non-streaming builder (e.g. a multi-GPU tiled builder).""" - model_path = "ckpt.safetensors" - model_sd_ops = None + paths = (Path("ckpt.safetensors"),) + sd_ops: tuple[object, ...] = () module_ops: tuple[object, ...] = () loras: tuple[object, ...] = () -def test_non_single_gpu_builder_bypasses_cache_and_evicts_resident_model() -> None: +def test_non_simple_builder_bypasses_cache_and_evicts_resident_model() -> None: cacheable_stage = _FakeStage(_single_gpu_builder("ckpt.safetensors")) with dsc._cached_transformer_ctx(cacheable_stage) as cached_model: pass @@ -269,3 +279,16 @@ def test_set_enabled_false_while_in_use_raises() -> None: dsc.set_enabled(False) # Evict runs before the flag flips, so a rejected toggle stays un-applied. assert dsc._enabled is True, "failed toggle-off must not half-apply" + + +def test_patch_is_installed_on_a_real_stage_that_the_cache_accepts() -> None: + """A rename of ``_transformer_ctx`` or of a private attribute the cache reads turns the cache off silently.""" + import torch + from ltx_pipelines.utils.blocks import DiffusionStage + + stage = DiffusionStage.from_checkpoint("ckpt.safetensors", torch.bfloat16, torch.device("cpu")) + twin = DiffusionStage.from_checkpoint("ckpt.safetensors", torch.bfloat16, torch.device("cpu")) + + assert DiffusionStage._transformer_ctx is dsc._cached_transformer_ctx # noqa: SLF001 + assert dsc._cacheable(stage) # noqa: SLF001 + assert dsc._cache_key(stage) == dsc._cache_key(twin) # noqa: SLF001 diff --git a/backend/tests/test_diffvae_decode_vram.py b/backend/tests/test_diffvae_decode_vram.py index 1493d2373..1cbc7fe6d 100644 --- a/backend/tests/test_diffvae_decode_vram.py +++ b/backend/tests/test_diffvae_decode_vram.py @@ -366,3 +366,24 @@ def test_conv_vae_keeps_pipeline_tiling(monkeypatch) -> None: old_tiling = object() args, _kwargs = patch._patched_video_decoder_call(_FakeDecoder(torch.device("cuda")), latent, old_tiling) assert args[1] is old_tiling + + +@pytest.mark.parametrize( + ("is_diffvae", "expected"), + [(True, "before DiffVAE decode"), (False, "before ConvVAE decode")], +) +def test_release_log_names_the_vae_being_decoded(monkeypatch, caplog, is_diffvae: bool, expected: str) -> None: + monkeypatch.setattr(patch, "is_diffusion_video_vae", lambda _path: is_diffvae) + monkeypatch.setattr(patch.diffusion_stage_cache, "evict", lambda: None) + monkeypatch.setattr(patch, "cleanup_memory", lambda: None) + with caplog.at_level("INFO", logger=patch.logger.name): + patch._release_denoise_weights(_FakeDecoder(torch.device("cpu"))) + assert expected in caplog.text + + +def test_release_log_falls_back_when_decoder_has_no_checkpoint(monkeypatch, caplog) -> None: + monkeypatch.setattr(patch.diffusion_stage_cache, "evict", lambda: None) + monkeypatch.setattr(patch, "cleanup_memory", lambda: None) + with caplog.at_level("INFO", logger=patch.logger.name): + patch._release_denoise_weights(object()) + assert "before video VAE decode" in caplog.text diff --git a/backend/tests/test_disk_streaming_pread.py b/backend/tests/test_disk_streaming_pread.py deleted file mode 100644 index 3a11bb603..000000000 --- a/backend/tests/test_disk_streaming_pread.py +++ /dev/null @@ -1,113 +0,0 @@ -"""Disk streaming opens safetensors with the pread backend on Darwin only.""" - -from __future__ import annotations - -import logging -import sys -from pathlib import Path - -import pytest -import safetensors -import torch -from ltx_core.block_streaming.disk import DiskTensorReader -from safetensors.torch import save_file - -import services.patches.disk_streaming_pread as pread - - -@pytest.fixture(autouse=True) -def _restore_reader() -> None: - original = DiskTensorReader.__init__ - yield - DiskTensorReader.__init__ = original # type: ignore[method-assign] - pread._installed = False - pread._checked = False - pread._original_init = None - - -@pytest.fixture -def on_darwin(monkeypatch: pytest.MonkeyPatch) -> None: - monkeypatch.setattr(sys, "platform", "darwin") - - -def test_disk_reader_passes_pread(tmp_path: Path, on_darwin: None) -> None: - path = tmp_path / "tiny.safetensors" - save_file({"weight": torch.ones(2, 2)}, str(path)) - pread.install() - seen: list[dict[str, object]] = [] - original_open = safetensors.safe_open - - def _spy(*args: object, **kwargs: object): - seen.append(dict(kwargs)) - return original_open(*args, **kwargs) - - safetensors.safe_open = _spy # type: ignore[assignment] - try: - reader = DiskTensorReader([str(path)]) - try: - torch.testing.assert_close(reader.get_tensor("weight"), torch.ones(2, 2)) - finally: - reader.close() - finally: - safetensors.safe_open = original_open - - assert seen == [{"framework": "pt", "device": "cpu", "backend": "pread"}] - - -def test_install_is_idempotent(on_darwin: None) -> None: - pread.install() - first = DiskTensorReader.__init__ - pread.install() - assert DiskTensorReader.__init__ is first - - -def test_install_leaves_mmap_when_backend_is_unsupported( - monkeypatch: pytest.MonkeyPatch, on_darwin: None -) -> None: - monkeypatch.setattr(pread.inspect, "signature", lambda _fn: type("Sig", (), {"parameters": {}})()) - before = DiskTensorReader.__init__ - pread.install() - assert DiskTensorReader.__init__ is before - assert pread._installed is False - assert pread._checked is True - - -def test_log_status_reports_pread_after_logging_is_configured( - caplog: pytest.LogCaptureFixture, on_darwin: None -) -> None: - pread.install() - with caplog.at_level(logging.INFO, logger=pread.logger.name): - pread.log_status() - assert "Disk streaming opens safetensors with backend=pread" in caplog.text - - -def test_log_status_reports_mmap_when_backend_is_unsupported( - monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, on_darwin: None -) -> None: - monkeypatch.setattr(pread.inspect, "signature", lambda _fn: type("Sig", (), {"parameters": {}})()) - pread.install() - with caplog.at_level(logging.WARNING, logger=pread.logger.name): - pread.log_status() - assert "disk streaming stays on mmap" in caplog.text - assert "Darwin-only" not in caplog.text - - -@pytest.mark.parametrize("platform", ["win32", "linux"]) -def test_install_is_noop_off_darwin(platform: str, monkeypatch: pytest.MonkeyPatch) -> None: - monkeypatch.setattr(sys, "platform", platform) - before = DiskTensorReader.__init__ - pread.install() - assert DiskTensorReader.__init__ is before - assert pread._installed is False - assert pread._checked is True - - -def test_log_status_reports_darwin_only_skip( - monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture -) -> None: - monkeypatch.setattr(sys, "platform", "win32") - pread.install() - with caplog.at_level(logging.INFO, logger=pread.logger.name): - pread.log_status() - assert "pread is Darwin-only" in caplog.text - assert "safetensors.safe_open has no backend" not in caplog.text diff --git a/backend/tests/test_displaced_provider_jobs.py b/backend/tests/test_displaced_provider_jobs.py new file mode 100644 index 000000000..a25cd2583 --- /dev/null +++ b/backend/tests/test_displaced_provider_jobs.py @@ -0,0 +1,88 @@ +"""The file that keeps the provider job ids that a retry replaced.""" + +from __future__ import annotations + +import json +from pathlib import Path + +from services.displaced_provider_jobs import ( + DISPLACED_PROVIDER_JOBS_FILENAME, + DisplacedProviderJobs, +) +from services.records import ProviderOrphan + + +def _job(generation_id: str = "gen-1", provider_job_id: str = "req-1") -> ProviderOrphan: + return ProviderOrphan(generation_id=generation_id, lane="fal", provider_job_id=provider_job_id) + + +def _file(tmp_path: Path) -> Path: + return tmp_path / DISPLACED_PROVIDER_JOBS_FILENAME + + +def test_a_new_file_is_empty_and_is_not_created_by_a_read(tmp_path: Path) -> None: + jobs = DisplacedProviderJobs(_file(tmp_path)) + + assert jobs.list() == [] + assert not _file(tmp_path).exists() + + +def test_an_added_id_is_kept_across_instances_in_the_order_it_was_added(tmp_path: Path) -> None: + # Bug caught: a retry keeps an id in memory only, and a restart loses the handle to a paid job. + DisplacedProviderJobs(_file(tmp_path)).add(_job("gen-2", "req-b")) + DisplacedProviderJobs(_file(tmp_path)).add(_job("gen-1", "req-a")) + + kept = DisplacedProviderJobs(_file(tmp_path)).list() + + assert [(job.generation_id, job.provider_job_id) for job in kept] == [ + ("gen-2", "req-b"), + ("gen-1", "req-a"), + ] + assert [job.provider_job_id for job in DisplacedProviderJobs(_file(tmp_path)).list("gen-1")] == ["req-a"] + + +def test_adding_the_same_id_twice_keeps_one_entry(tmp_path: Path) -> None: + jobs = DisplacedProviderJobs(_file(tmp_path)) + + jobs.add(_job()) + jobs.add(_job()) + + assert len(jobs.list()) == 1 + + +def test_a_removed_id_is_gone_and_the_file_is_deleted_with_the_last_entry(tmp_path: Path) -> None: + # Bug caught: the file stays on disk for ever, and the boot cancels the same jobs again. + jobs = DisplacedProviderJobs(_file(tmp_path)) + jobs.add(_job(provider_job_id="req-1")) + jobs.add(_job(provider_job_id="req-2")) + + assert jobs.remove("gen-1", "req-1") is True + assert [job.provider_job_id for job in jobs.list()] == ["req-2"] + assert _file(tmp_path).exists() + assert jobs.remove("gen-1", "req-1") is False + + assert jobs.remove("gen-1", "req-2") is True + assert not _file(tmp_path).exists() + + +def test_an_unreadable_file_is_moved_aside_and_the_list_is_empty(tmp_path: Path) -> None: + # Bug caught: a half-written file stops the app at every boot. + _file(tmp_path).write_text("{not json", encoding="utf-8") + jobs = DisplacedProviderJobs(_file(tmp_path)) + + assert jobs.list() == [] + + assert not _file(tmp_path).exists() + assert (tmp_path / f"{DISPLACED_PROVIDER_JOBS_FILENAME}.corrupt").read_text(encoding="utf-8") == "{not json" + jobs.add(_job()) + assert len(jobs.list()) == 1 + + +def test_an_invalid_entry_is_skipped_and_the_valid_ones_are_kept(tmp_path: Path) -> None: + good = _job().model_dump(mode="json") + _file(tmp_path).write_text( + json.dumps({"version": 1, "jobs": [{"generation_id": "gen-1"}, good, {**good, "provider_job_id": ""}]}), + encoding="utf-8", + ) + + assert [job.provider_job_id for job in DisplacedProviderJobs(_file(tmp_path)).list()] == ["req-1"] diff --git a/backend/tests/test_distilled_a2v_image_crf.py b/backend/tests/test_distilled_a2v_image_crf.py deleted file mode 100644 index 60d1f9ae3..000000000 --- a/backend/tests/test_distilled_a2v_image_crf.py +++ /dev/null @@ -1,70 +0,0 @@ -"""CPU-only checks for distilled A2V image CRF resolution. - -Image+audio generation failed because DistilledA2VPipeline built -ImageConditioningInput tuples with crf=None and never called -ImageConditioner.resolve_crf, which DistilledPipeline runs for image-only. -""" - -from __future__ import annotations - -from collections.abc import Sequence - -from ltx_pipelines.utils.types import ImageConditioningInput as LtxImageInput -from services.a2v_pipeline.distilled_a2v_pipeline import resolve_image_conditionings - -_CHECKPOINT_CRF = 29 - - -class _FakeImageConditioner: - def __init__(self) -> None: - self.received: list[LtxImageInput] | None = None - - def resolve_crf(self, images: Sequence[LtxImageInput]) -> list[LtxImageInput]: - self.received = list(images) - return [ - image if image.crf is not None else image._replace(crf=_CHECKPOINT_CRF) - for image in images - ] - - -def test_resolve_image_conditionings_builds_inputs_and_calls_resolve_crf() -> None: - conditioner = _FakeImageConditioner() - - result = resolve_image_conditionings( - [("start.png", 0, 0.8), ("end.png", 24, 1.0)], - conditioner, - ) - - assert conditioner.received is not None - assert [(image.path, image.frame_idx, image.strength, image.crf) for image in conditioner.received] == [ - ("start.png", 0, 0.8, None), - ("end.png", 24, 1.0, None), - ] - assert [(image.path, image.frame_idx, image.strength, image.crf) for image in result] == [ - ("start.png", 0, 0.8, _CHECKPOINT_CRF), - ("end.png", 24, 1.0, _CHECKPOINT_CRF), - ] - - -def test_encode_stage_image_conditionings_uses_combined_not_replacing_latent(monkeypatch) -> None: - """Last-frame A2V crashed: replacing_latent treats pixel frame_idx as a latent index.""" - from services.a2v_pipeline.distilled_a2v_pipeline import encode_stage_image_conditionings - - monkeypatch.setattr( - "ltx_pipelines.utils.helpers.combined_image_conditionings", - lambda **kwargs: "combined", - ) - monkeypatch.setattr( - "ltx_pipelines.utils.helpers.image_conditionings_by_replacing_latent", - lambda **kwargs: "replacing", - ) - - result = encode_stage_image_conditionings( - [], - height=352, - width=640, - video_encoder=object(), - dtype=object(), - device=object(), - ) - assert result == "combined" diff --git a/backend/tests/test_distilled_a2v_stages.py b/backend/tests/test_distilled_a2v_stages.py index d932c791d..af2472391 100644 --- a/backend/tests/test_distilled_a2v_stages.py +++ b/backend/tests/test_distilled_a2v_stages.py @@ -1,12 +1,9 @@ -"""Distilled A2V stage flow against the real v1.4 latent and stage-call types. +"""Distilled A2V stage flow against the real v1.5 chunk operators. A2V has no GPU-free coverage of its two ``DiffusionStage`` calls. This drives -``DistilledA2VPipeline.__call__`` with a recording stage and the real latent -helpers, so a mis-sized latent changes a tensor shape here. - -The stage uses non-default scale factors on purpose. Sizing latents from the -decoder's tiling scale or from the module default would then give a different -shape and fail the assertions. +``DistilledA2VPipeline.__call__`` (one window through ``stream_chunks``) with a +recording stage, a fake upsampler and decoder, and the real chunk planner, so a +mis-sized latent or a wrong stage argument changes what the stage sees here. """ from __future__ import annotations @@ -17,12 +14,14 @@ import pytest import torch from ltx_core.types import Audio, SpatioTemporalScaleFactors +from ltx_core.conditioning import VideoConditionByKeyframeIndex, VideoConditionByLatentIndex from ltx_pipelines.utils.constants import STAGE_2_DISTILLED_SIGMA_VALUES +from ltx_pipelines.utils.types import ImageConditioningInput, LoadedImageConditioning from services.a2v_pipeline.distilled_a2v_pipeline import DistilledA2VPipeline -# Not the module default (8x32x32) and not a 2.5 DiffVAE decoder scale (2x8x8). -_STAGE_SCALE = SpatioTemporalScaleFactors(time=4, height=16, width=16) +# The transformer latent geometry. Upstream sizes stills from the module default (8x32x32), not from the 2.5 DiffVAE decoder scale (2x8x8). +_STAGE_SCALE = SpatioTemporalScaleFactors(time=8, height=32, width=32) _CHANNELS = 128 _FRAMES = 9 _HEIGHT, _WIDTH = 576, 1024 @@ -30,16 +29,28 @@ class _State: + generated_keyframes = None + generated_keyframe_layout = None + def __init__(self, latent: torch.Tensor) -> None: self.latent = latent +class _Still: + def tensor(self, height, width, dtype, device): + return torch.zeros(1, 3, 1, height, width, dtype=dtype, device=device) + + +def _encoder(pixels: torch.Tensor) -> torch.Tensor: + return torch.zeros(1, _CHANNELS, 1, pixels.shape[-2] // 32, pixels.shape[-1] // 32) + + class _Conditioner: - def resolve_crf(self, images): - return list(images) + def load_conditionings(self, images, color_space=None): # noqa: ARG002 + return [LoadedImageConditioning(still=_Still(), strength=i.strength, binding=i.binding) for i in images] def __call__(self, build): - return build(object()) + return build(_encoder) def _pipeline(monkeypatch: pytest.MonkeyPatch) -> tuple[DistilledA2VPipeline, list[dict[str, Any]], list[torch.Tensor]]: @@ -69,16 +80,22 @@ def prompt_encoder(prompts: list[str]) -> tuple[Any]: pipe = cast(DistilledA2VPipeline, object.__new__(DistilledA2VPipeline)) pipe.device = torch.device("cpu") pipe.dtype = torch.bfloat16 + pipe.use_ancestral_sampler = False pipe.prompt_encoder = prompt_encoder # type: ignore[assignment] pipe.image_conditioner = _Conditioner() # type: ignore[assignment] pipe.audio_conditioner = lambda _build: torch.zeros(1, 8, 4, 16) # type: ignore[assignment] pipe.stage = stage # type: ignore[assignment] pipe.upsampler = upsampler # type: ignore[assignment] - pipe.video_decoder = lambda latent, _tiling, _generator: latent # type: ignore[assignment] + + def video_decoder(latent: torch.Tensor, _tiling: Any, _generator: Any, **_kwargs: Any) -> Any: + pixel_frames = (latent.shape[2] - 1) * _STAGE_SCALE.time + 1 + yield torch.zeros(pixel_frames, latent.shape[3] * _STAGE_SCALE.height, latent.shape[4] * _STAGE_SCALE.width, 3) + + pipe.video_decoder = video_decoder # type: ignore[assignment] return pipe, stage_calls, upsampler_inputs -def _run(pipe: DistilledA2VPipeline) -> tuple[Any, Audio]: +def _run(pipe: DistilledA2VPipeline, images: list[ImageConditioningInput] | None = None) -> tuple[Any, Audio]: return pipe( # type: ignore[return-value] prompt="a clip", seed=3, @@ -86,7 +103,7 @@ def _run(pipe: DistilledA2VPipeline) -> tuple[Any, Audio]: width=_WIDTH, num_frames=_FRAMES, frame_rate=24.0, - images=[], + images=images or [], audio_path="speech.wav", ) @@ -135,7 +152,7 @@ def test_audio_stays_frozen_and_unnoised_in_both_stages(monkeypatch: pytest.Monk def test_returns_the_source_audio_trimmed_to_the_video_duration(monkeypatch: pytest.MonkeyPatch) -> None: pipe, _, _ = _pipeline(monkeypatch) - _, audio = _run(pipe) + audio = _run(pipe).audio assert audio.sampling_rate == _SAMPLE_RATE assert audio.waveform.shape[-1] == round(_FRAMES / 24.0 * _SAMPLE_RATE) @@ -191,3 +208,72 @@ def recording_decode(*args: Any, **_kwargs: Any) -> Audio: assert len(seen) == 1 path, _device, start, max_duration = seen[0] assert (path, start, max_duration) == ("speech.wav", 1.5, 4.0) + + +def test_first_and_last_pixel_frame_stills_condition_both_stages_at_their_canvas(monkeypatch: pytest.MonkeyPatch) -> None: + """The last pixel frame is past the latent count. It must stay a keyframe guide and the first frame a replace.""" + pipe, calls, _ = _pipeline(monkeypatch) + last = _FRAMES - 1 + + _run( + pipe, + [ImageConditioningInput.at("start.png", 0, 1.0), ImageConditioningInput.at("end.png", last, 1.0)], + ) + + for call, divisor in zip(calls, (2, 1), strict=True): + first, end = call["modalities"].video.conditionings + assert isinstance(first, VideoConditionByLatentIndex) + assert isinstance(end, VideoConditionByKeyframeIndex) + assert end.frame_idx == last + assert tuple(end.keyframes.shape[-2:]) == (_HEIGHT // divisor // 32, _WIDTH // divisor // 32) + + +@pytest.mark.parametrize("ancestral", [True, False], ids=["ltx_2_5", "ltx_2_3"]) +def test_both_stages_use_the_ancestral_loop_only_on_ancestral_checkpoints( + monkeypatch: pytest.MonkeyPatch, ancestral: bool +) -> None: + """A2V ran plain Euler on LTX 2.5 while DistilledPipeline and retake ran the ancestral loop.""" + pipe, calls, _ = _pipeline(monkeypatch) + pipe.use_ancestral_sampler = ancestral + + _run(pipe) + + assert [call["loop"] is not None for call in calls] == [ancestral, ancestral] + + +def test_a_still_past_the_snapped_clip_is_rejected_before_any_denoising(monkeypatch: pytest.MonkeyPatch) -> None: + """10 frames snap to 9, so a still at frame 9 passed the unsnapped check and was dropped later.""" + pipe, calls, _ = _pipeline(monkeypatch) + + with pytest.raises(ValueError): + pipe( + prompt="a clip", + seed=3, + height=_HEIGHT, + width=_WIDTH, + num_frames=_FRAMES + 1, + frame_rate=24.0, + images=[ImageConditioningInput.at("end.png", _FRAMES, 1.0)], + audio_path="speech.wav", + ) + + assert calls == [] + + +def test_a_clip_longer_than_the_default_window_still_runs_as_one_window(monkeypatch: pytest.MonkeyPatch) -> None: + """Without a window sized to the clip, 121 frames split at the default 97 and ran stage 1 and 2 twice.""" + pipe, calls, _ = _pipeline(monkeypatch) + + output = pipe( + prompt="a clip", + seed=3, + height=_HEIGHT, + width=_WIDTH, + num_frames=121, + frame_rate=24.0, + images=[], + audio_path="speech.wav", + ) + + assert len(calls) == 2 + assert sum(frames.shape[0] for frames in output.video) == 121 diff --git a/backend/tests/test_distilled_keyframe_guiding.py b/backend/tests/test_distilled_keyframe_guiding.py deleted file mode 100644 index 0131b2e6b..000000000 --- a/backend/tests/test_distilled_keyframe_guiding.py +++ /dev/null @@ -1,32 +0,0 @@ -"""CPU-only checks for the Distilled MKF guiding-helper swap.""" - -from __future__ import annotations - -import pytest - -import ltx_pipelines.chunks.conditionings as chunk_conditionings -import ltx_pipelines.utils.helpers as helpers -from ltx_pipelines.utils.helpers import image_conditionings_by_adding_guiding_latent -from services.fast_video_pipeline.distilled_keyframe_guiding import distilled_keyframe_guiding - - -def test_guiding_context_swaps_combined_helper() -> None: - original_helpers = helpers.combined_image_conditionings - original_chunks = chunk_conditionings.combined_image_conditionings - with distilled_keyframe_guiding(): - assert helpers.combined_image_conditionings is image_conditionings_by_adding_guiding_latent - assert chunk_conditionings.combined_image_conditionings is image_conditionings_by_adding_guiding_latent - assert helpers.combined_image_conditionings is original_helpers - assert chunk_conditionings.combined_image_conditionings is original_chunks - - -def test_guiding_context_restores_helper_after_exception() -> None: - original_helpers = helpers.combined_image_conditionings - original_chunks = chunk_conditionings.combined_image_conditionings - with pytest.raises(RuntimeError, match="swap-failed"): - with distilled_keyframe_guiding(): - assert helpers.combined_image_conditionings is image_conditionings_by_adding_guiding_latent - assert chunk_conditionings.combined_image_conditionings is image_conditionings_by_adding_guiding_latent - raise RuntimeError("swap-failed") - assert helpers.combined_image_conditionings is original_helpers - assert chunk_conditionings.combined_image_conditionings is original_chunks diff --git a/backend/tests/test_distilled_skip_stage_2.py b/backend/tests/test_distilled_skip_stage_2.py index 97536ce54..94c5718e2 100644 --- a/backend/tests/test_distilled_skip_stage_2.py +++ b/backend/tests/test_distilled_skip_stage_2.py @@ -9,7 +9,7 @@ from ltx_core.types import SpatioTemporalScaleFactors import ltx_pipelines.distilled as distilled -from ltx_pipelines.utils.types import PipelineOutput +from ltx_pipelines.utils.types import ImageConditioningInput, LoadedImageConditioning, PipelineOutput from services.fast_video_pipeline.distilled_skip_stage_2 import DistilledPipelineWithSkipStage2 @@ -19,8 +19,8 @@ class _Encoding: class _Conditioner: - def resolve_crf(self, images): - return images + def load_conditionings(self, images, color_space=None): # noqa: ARG002 + return [LoadedImageConditioning(still=image.path, strength=image.strength, binding=image.binding) for image in images] def __call__(self, build): return build(object()) @@ -38,29 +38,29 @@ def __init__(self, latent: torch.Tensor) -> None: def _pipeline(monkeypatch, *, real_latents: bool = False, decoder_scale: object = _DECODER_SCALE, stage_scale: object = _TRANSFORMER_SCALE): stage_pixels: list[tuple[int, int]] = [] latent_scales: list[object] = [] + image_calls: list[dict] = [] + prompt_kwargs: list[dict] = [] - def fake_combined(**kwargs): + def fake_image_conditionings(**kwargs): + image_calls.append(kwargs) return [] - def fake_latents(*, width, height, frames, video_scale_factors, **_kwargs): + def fake_latents(*, pixel_shape, video_scale_factors, **_kwargs): latent_scales.append(video_scale_factors) - video = torch.zeros(1, 4, frames, height, width) - audio = torch.zeros(1, 8, frames, 16) + video = torch.zeros(1, 4, pixel_shape.frames, pixel_shape.height, pixel_shape.width) + audio = torch.zeros(1, 8, pixel_shape.frames, 16) return video, audio monkeypatch.setattr( - "services.fast_video_pipeline.distilled_skip_stage_2.ltx_helpers.combined_image_conditionings", - fake_combined, + "services.fast_video_pipeline.distilled_skip_stage_2.image_conditionings", + fake_image_conditionings, ) if not real_latents: monkeypatch.setattr( "services.fast_video_pipeline.distilled_skip_stage_2.create_initial_av_latents", fake_latents, ) - monkeypatch.setattr( - "services.fast_video_pipeline.distilled_skip_stage_2.tiling_scale_factors_for_vae", - lambda _path: decoder_scale, - ) + monkeypatch.setattr("ltx_pipelines.utils.helpers.tiling_scale_factors_for_vae", lambda _path: decoder_scale) pipe = DistilledPipelineWithSkipStage2.__new__(DistilledPipelineWithSkipStage2) pipe.device = torch.device("cpu") @@ -69,7 +69,8 @@ def fake_latents(*, width, height, frames, video_scale_factors, **_kwargs): pipe.duration_predictor = None pipe.image_conditioner = _Conditioner() - def prompt_encoder(*_args, **_kwargs): + def prompt_encoder(*_args, **kwargs): + prompt_kwargs.append(kwargs) return (_Encoding(),) def stage(**kwargs): @@ -84,21 +85,23 @@ class _Decoder: def __call__(self, latent, _tiling, _generator, dtype=None): # noqa: ARG002 del latent, dtype height, width = stage_pixels[-1] - return torch.zeros(1, 3, 9, height, width) + return iter((torch.zeros(1, 3, 9, height, width),)) def audio_decoder(latent): # noqa: ARG001 return None stage.video_scale_factors = stage_scale # type: ignore[attr-defined] pipe.prompt_encoder = prompt_encoder + pipe.image_calls = image_calls # type: ignore[attr-defined] + pipe.prompt_kwargs = prompt_kwargs # type: ignore[attr-defined] pipe.stage = stage pipe.video_decoder = _Decoder() pipe.audio_decoder = audio_decoder return pipe, stage_pixels, latent_scales -# ltx-pipelines v1.4.x DistilledPipeline.__call__ (unchanged between 1.4.0 and 1.4.1). -_DISTILLED_CALL_PARAMS_V1_4 = ( +# ltx-pipelines v1.6.0 DistilledPipeline.__call__. +_DISTILLED_CALL_PARAMS_V1_6 = ( "self", "prompt", "seed", @@ -120,9 +123,9 @@ def audio_decoder(latent): # noqa: ARG001 ) -def test_distilled_call_signature_is_v1_4() -> None: +def test_distilled_call_signature_is_v1_6() -> None: params = tuple(inspect.signature(distilled.DistilledPipeline.__call__).parameters) - assert params == _DISTILLED_CALL_PARAMS_V1_4 + assert params == _DISTILLED_CALL_PARAMS_V1_6 def test_skip_stage_2_decodes_half_canvas_without_upsampling(monkeypatch) -> None: @@ -188,9 +191,9 @@ def test_skip_stage_2_snaps_frames_to_the_vae_grid(monkeypatch, requested: int, pipe, _, _ = _pipeline(monkeypatch) frames_seen: list[int] = [] - def recording_latents(*, width, height, frames, **_kwargs): - frames_seen.append(frames) - return torch.zeros(1, 4, 1, height, width), torch.zeros(1, 8, 1, 16) + def recording_latents(*, pixel_shape, **_kwargs): + frames_seen.append(pixel_shape.frames) + return torch.zeros(1, 4, 1, pixel_shape.height, pixel_shape.width), torch.zeros(1, 8, 1, 16) monkeypatch.setattr( "services.fast_video_pipeline.distilled_skip_stage_2.create_initial_av_latents", @@ -258,3 +261,42 @@ def fake_call(self, *args, **kwargs): # noqa: ARG001 assert forwarded["kwargs"]["prompt"] == "a clip" assert (forwarded["kwargs"]["height"], forwarded["kwargs"]["width"]) == (704, 1280) assert tuple(output.video.shape) == (1, 3, 9, 8, 8) + + +def test_skip_stage_2_encodes_loaded_stills_at_half_canvas_and_enhances_from_the_first_path(monkeypatch) -> None: + """``LoadedImageConditioning`` has no ``path``: it must be read before loading, and the stage-1 encode must use the loaded objects.""" + pipe, _, _ = _pipeline(monkeypatch) + still = ImageConditioningInput.at("first.png", 0, 1.0) + + pipe( + prompt="a clip", + seed=1, + height=576, + width=1024, + frame_rate=24, + images=[still], + num_frames=9, + tiling_config=None, + skip_stage_2=True, + ) + + assert pipe.prompt_kwargs[0]["enhance_prompt_image"] == "first.png" + (call,) = pipe.image_calls + assert [(image.still, image.frame_idx) for image in call["images"]] == [("first.png", 0)] + assert (call["height"], call["width"]) == (288, 512) + + +def test_skip_stage_2_rejects_a_still_outside_the_clip(monkeypatch) -> None: + pipe, _, _ = _pipeline(monkeypatch) + with pytest.raises(ValueError, match="outside the planned stitched range"): + pipe( + prompt="a clip", + seed=1, + height=576, + width=1024, + frame_rate=24, + images=[ImageConditioningInput.guide("late.png", 9, 1.0)], + num_frames=9, + tiling_config=None, + skip_stage_2=True, + ) diff --git a/backend/tests/test_edit_executor_prompt_enhancement.py b/backend/tests/test_edit_executor_prompt_enhancement.py index f559c6e57..18c231c1c 100644 --- a/backend/tests/test_edit_executor_prompt_enhancement.py +++ b/backend/tests/test_edit_executor_prompt_enhancement.py @@ -13,6 +13,8 @@ import pytest from api_types import ExtendParams, RetakeParams +from runtime_config.budget_admission import RiskAllowance +from runtime_config.device_calibration import JobEnvelope from services.features.video.edit_executor import VideoEditExecutor from services.features.video.extend import ExtendExecutor from services.features.video.retake import RetakeExecutor @@ -27,40 +29,58 @@ class _Slot: - def start_generation(self, generation_id: str) -> None: ... + def start_generation( + self, generation_id: str, *, ran: JobEnvelope | None = None + ) -> None: ... - def complete_generation(self, result: str | list[str] | None = None) -> None: ... + def complete_generation( + self, result: str | list[str] | None = None, *, ran: JobEnvelope | None = None + ) -> None: ... def fail_generation(self, error: str) -> None: ... +class _Prepared(NamedTuple): + dest: Path + ran: JobEnvelope | None = None + + class _Text: - def __init__(self) -> None: + def __init__(self, *, local_encoding: bool = True) -> None: self.encoded: list[tuple[str, bool]] = [] + self.local_encoding = local_encoding def prepare_text_encoding(self, prompt: str, enhance_prompt: bool, model_id: Any = None) -> None: self.encoded.append((prompt, enhance_prompt)) def clear_api_embeddings(self) -> None: ... + def should_use_local_encoding(self, model_id: Any = None) -> bool: + del model_id + return self.local_encoding + class _StubbedGpuRetake(RetakeExecutor): prepared_prompts: list[str] fail_in_gpu_stage = False def prepare( - self, generation: Any, params: RetakeParams, *rest: Any, allow_risk: bool = False, unmeasured_bet: bool = False + self, + generation: Any, + params: RetakeParams, + *rest: Any, + allowance: RiskAllowance = RiskAllowance.none(), ) -> Any: - del allow_risk, unmeasured_bet + del allowance self.prepared_prompts = [*getattr(self, "prepared_prompts", []), params.prompt] - return rest[3] + return _Prepared(rest[3]) def generate(self, prepared: Any) -> None: if self.fail_in_gpu_stage: raise RuntimeError("gpu stage failed") def stitch(self, prepared: Any) -> None: - write_mp4(Path(prepared), seconds=1) + write_mp4(prepared.dest, seconds=1) class _StubbedGpuExtend(ExtendExecutor): @@ -68,18 +88,22 @@ class _StubbedGpuExtend(ExtendExecutor): fail_in_gpu_stage = False def prepare( - self, generation: Any, params: ExtendParams, *rest: Any, allow_risk: bool = False, unmeasured_bet: bool = False + self, + generation: Any, + params: ExtendParams, + *rest: Any, + allowance: RiskAllowance = RiskAllowance.none(), ) -> Any: - del allow_risk, unmeasured_bet + del allowance self.prepared_prompts = [*getattr(self, "prepared_prompts", []), params.prompt] - return rest[3] + return _Prepared(rest[3]) def generate(self, prepared: Any) -> None: if self.fail_in_gpu_stage: raise RuntimeError("gpu stage failed") def stitch(self, prepared: Any) -> None: - write_mp4(Path(prepared), seconds=1) + write_mp4(prepared.dest, seconds=1) _EXECUTORS: dict[str, tuple[type[VideoEditExecutor[Any, Any, Any]], dict[str, object]]] = { @@ -104,16 +128,18 @@ def _run( create_fake_model_files, tmp_path: Path, typed_prompt: str = _TYPED, + negative_prompt: str = "", + local_encoding: bool = True, fail_in_gpu_stage: bool = False, ) -> _Result: create_fake_model_files(include_prompt_enhancer=True) - test_state.state.app_settings.use_local_text_encoder = True + test_state.state.app_settings.use_local_text_encoder = local_encoding asset = client.post( "/api/assets", json={"path": str(write_mp4(tmp_path / "source.mp4", seconds=6))} ).json() executor_class, feature_params = _EXECUTORS[feature] store = SqliteStore(test_state.config.app_data_dir) - text = _Text() + text = _Text(local_encoding=local_encoding) executor = executor_class( test_state.pipelines, store, @@ -129,6 +155,7 @@ def _run( { "params": { "prompt": typed_prompt, + "negativePrompt": negative_prompt, "model": "ltx-2.5-fast", "promptProvenance": provenance, **feature_params, @@ -302,3 +329,41 @@ def test_an_extend_samples_the_whole_clip_because_it_replaces_no_part_of_it( times = fake_services.prompt_enhancer_pipeline.enhance_video_frames_calls[0]["frame_times"] assert min(times) < 1 + + +@pytest.mark.parametrize("feature", ["retake", "extend"]) +def test_edit_executor_passes_negative_prompt_to_enhancer_only_when_local_encoding_is_active( + feature, client, test_state, fake_services, create_fake_model_files, tmp_path +): + fake_services.prompt_enhancer_pipeline.enhanced_prompt = _ENHANCED + + _run( + feature, + provenance="typed", + client=client, + test_state=test_state, + create_fake_model_files=create_fake_model_files, + tmp_path=tmp_path, + negative_prompt="blurry, flicker", + local_encoding=True, + ) + assert ( + fake_services.prompt_enhancer_pipeline.enhance_video_frames_calls[-1]["negative_prompt"] + == "blurry, flicker" + ) + + _run( + feature, + provenance="typed", + client=client, + test_state=test_state, + create_fake_model_files=create_fake_model_files, + tmp_path=tmp_path, + negative_prompt="blurry, flicker", + local_encoding=False, + ) + assert ( + fake_services.prompt_enhancer_pipeline.enhance_video_frames_calls[-1]["negative_prompt"] + == "" + ) + diff --git a/backend/tests/test_edit_shrink_then_run.py b/backend/tests/test_edit_shrink_then_run.py index a2e283416..5bfc6fd20 100644 --- a/backend/tests/test_edit_shrink_then_run.py +++ b/backend/tests/test_edit_shrink_then_run.py @@ -15,6 +15,8 @@ from _routes._errors import HTTPError from api_types import ExtendParams, LTXLocalModelId, RetakeParams +from runtime_config.budget_admission import RiskAllowance +from runtime_config.device_calibration import JobEnvelope from runtime_config.video_job_budget import ( LOCAL_GENERATION_RAM_SHORTFALL, VIDEO_JOB_TOO_LARGE, @@ -22,6 +24,7 @@ from services.features.video.extend import ExtendExecutor from services.features.video.retake import RetakeExecutor from services.generation_queue.types import OutputAllocation +from tests.fakes.generation import FakeJobSession from services.records import CapabilityFailedError from services.sqlite_store import SqliteStore from tests.video_fixtures import write_mp4 @@ -120,7 +123,7 @@ def test_edit_budget_lines_carry_vram_triple( frames=369, queued_home=True, ) - state = test_state.pipelines.load_retake_pipeline( + state, _ = test_state.pipelines.load_retake_pipeline( distilled=True, ltx_model_id=_LOCAL_2_5, width=1920, @@ -171,7 +174,7 @@ def test_retake_prepare_shrinks_free_refused_window_instead_of_raising( 7, tmp_path / "out.mp4", str(tmp_path / "out.window.mp4"), - allow_risk=allow_risk, + allowance=RiskAllowance(over=allow_risk, unmeasured=False), ) assert prepared.window.encode_frames == 345 @@ -219,7 +222,7 @@ def test_extend_prepare_shrinks_free_refused_window_instead_of_raising( 7, tmp_path / "out.mp4", str(tmp_path / "out.window.mp4"), - allow_risk=allow_risk, + allowance=RiskAllowance(over=allow_risk, unmeasured=False), ) assert prepared.extend_frames == 96 @@ -266,7 +269,7 @@ def test_retake_prepare_refuses_when_selection_exceeds_free_fitting_window( 7, tmp_path / "out.mp4", str(tmp_path / "out.window.mp4"), - allow_risk=allow_risk, + allowance=RiskAllowance(over=allow_risk, unmeasured=False), ) assert exc_info.value.code == VIDEO_JOB_TOO_LARGE @@ -306,7 +309,7 @@ def test_extend_prepare_shrinks_context_below_floor_instead_of_refusing( 7, tmp_path / "out.mp4", str(tmp_path / "out.window.mp4"), - allow_risk=False, + allowance=RiskAllowance.none(), ) assert prepared.extend_frames == 240 @@ -351,7 +354,7 @@ def test_extend_prepare_from_start_shrink_trims_tail_context( 7, tmp_path / "out.mp4", str(tmp_path / "out.window.mp4"), - allow_risk=False, + allowance=RiskAllowance.none(), ) assert prepared.extend_frames == 240 @@ -392,7 +395,7 @@ def test_extend_prepare_refuses_when_selection_exceeds_total_cap( 7, tmp_path / "out.mp4", str(tmp_path / "out.window.mp4"), - allow_risk=allow_risk, + allowance=RiskAllowance(over=allow_risk, unmeasured=False), ) assert exc_info.value.code == VIDEO_JOB_TOO_LARGE @@ -441,7 +444,7 @@ def test_retake_prepare_refuses_when_free_gap_exceeds_shrink_limit( 7, tmp_path / "out.mp4", str(tmp_path / "out.window.mp4"), - allow_risk=allow_risk, + allowance=RiskAllowance(over=allow_risk, unmeasured=False), ) assert exc_info.value.status_code == 422 @@ -492,7 +495,7 @@ def test_extend_prepare_refuses_when_free_gap_exceeds_shrink_limit( 7, tmp_path / "out.mp4", str(tmp_path / "out.window.mp4"), - allow_risk=allow_risk, + allowance=RiskAllowance(over=allow_risk, unmeasured=False), ) assert exc_info.value.status_code == 422 @@ -544,7 +547,7 @@ def test_stored_over_still_runs_retake_ram_shortfall_shrink_cannot_salvage( 7, tmp_path / "out.mp4", str(tmp_path / "out.window.mp4"), - allow_risk=False, + allowance=RiskAllowance.none(), ) assert refused.value.code == LOCAL_GENERATION_RAM_SHORTFALL caplog.set_level(logging.INFO) @@ -556,7 +559,7 @@ def test_stored_over_still_runs_retake_ram_shortfall_shrink_cannot_salvage( 7, tmp_path / "out.mp4", str(tmp_path / "out.window.mp4"), - allow_risk=True, + allowance=RiskAllowance(over=True, unmeasured=False), ) assert prepared.window.encode_frames == 481 assert not any( @@ -595,7 +598,7 @@ def test_stored_over_still_runs_extend_ram_shortfall_shrink_cannot_salvage( 7, tmp_path / "out.mp4", str(tmp_path / "out.window.mp4"), - allow_risk=False, + allowance=RiskAllowance.none(), ) assert refused.value.code == LOCAL_GENERATION_RAM_SHORTFALL caplog.set_level(logging.INFO) @@ -607,7 +610,7 @@ def test_stored_over_still_runs_extend_ram_shortfall_shrink_cannot_salvage( 7, tmp_path / "out.mp4", str(tmp_path / "out.window.mp4"), - allow_risk=True, + allowance=RiskAllowance(over=True, unmeasured=False), ) assert prepared.extend_frames == 96 assert prepared.window.context_frames + prepared.extend_frames == 505 @@ -617,11 +620,15 @@ def test_stored_over_still_runs_extend_ram_shortfall_shrink_cannot_salvage( class _Slot: - def start_generation(self, generation_id: str) -> None: - del generation_id + def start_generation( + self, generation_id: str, *, ran: JobEnvelope | None = None + ) -> None: + del generation_id, ran - def complete_generation(self, result: str | list[str] | None = None) -> None: - del result + def complete_generation( + self, result: str | list[str] | None = None, *, ran: JobEnvelope | None = None + ) -> None: + del result, ran def fail_generation(self, error: str) -> None: del error @@ -667,6 +674,7 @@ def _execute_retake(test_state, store, generation) -> _RecordingRetake: dest_path=str(generation.id) + ".mp4", ), ), + FakeJobSession(), ) return executor diff --git a/backend/tests/test_eta.py b/backend/tests/test_eta.py index d84071ff4..ad7795d50 100644 --- a/backend/tests/test_eta.py +++ b/backend/tests/test_eta.py @@ -5,11 +5,21 @@ import pytest from frame_math import compute_num_frames +from runtime_config.budget_evidence import JobShape +from runtime_config.device_calibration import envelope_for from runtime_config.eta import ( + WallTimeBreakdown, WallTimeEstimate, + estimate_envelope_wall_time, estimate_fast_wall_time_s, + estimate_stage_breakdown_s, + implied_envelope_factor, + implied_machine_factor, is_measured_hardware_class, + remaining_wall_time_s, + spatial_tile_count, ) +from runtime_config.ic_lora_tiling import IcLoraTiling # (width, height, seconds, full_cold, stream_cpu_cold) _CELLS = [ @@ -56,13 +66,13 @@ def test_table_pins_cold_seconds( @pytest.mark.parametrize( ("width", "height", "seconds", "expected", "basis"), [ - # Same-session measured ratios: 0.87 (540p/5s), 0.81 (720p/20s). - (1024, 576, 5, round(158 * 0.87), "measured"), - (1280, 704, 20, round(280 * 0.81), "measured"), - # Default 0.8 ratio elsewhere, labelled scaled. - (1024, 576, 20, round(222 * 0.8), "scaled"), - (1920, 1088, 5, round(232 * 0.8), "scaled"), - (1920, 1088, 10, round(338 * 0.8), "scaled"), + # 1.6.0 W1 measured ratios: 1.06 (720p/20s), 1.10 (1080p/10s). + (1280, 704, 20, round(280 * 1.06), "measured"), + (1920, 1088, 10, round(338 * 1.10), "measured"), + # Default 1.07 ratio elsewhere, labelled scaled. + (1024, 576, 5, round(158 * 1.07), "scaled"), + (1024, 576, 20, round(222 * 1.07), "scaled"), + (1920, 1088, 5, round(232 * 1.07), "scaled"), ], ) def test_disk_applies_ratio_with_basis( @@ -82,8 +92,8 @@ def test_disk_applies_ratio_with_basis( assert est.basis == basis -def test_unlisted_cell_returns_none() -> None: - """720p/10s is a real grid cell with no measurement: unknown, not interpolated.""" +def test_unlisted_cell_returns_scaled_three_part_estimate() -> None: + """720p/10s is computed by the 3-part formula with load + denoise + decode == seconds.""" est = estimate_fast_wall_time_s( width=1280, height=704, @@ -93,7 +103,121 @@ def test_unlisted_cell_returns_none() -> None: feature="t2v", machine_factor=1.0, ) - assert est is None + assert est is not None + assert est.basis == "scaled" + assert est.load_s + est.denoise_s + est.decode_s == est.seconds + assert est.load_s > 0 and est.denoise_s > 0 and est.decode_s > 0 + + +def test_full_mode_chunked_canvas_returns_none() -> None: + assert ( + estimate_fast_wall_time_s( + width=3840, + height=2176, + frames=compute_num_frames(5, 24), + load_mode="full_models_loading", + offload_mode="NONE", + feature="t2v", + machine_factor=1.0, + ) + is None + ) + + +def test_mac_machine_factor_scales_gpu_terms_without_scaling_fixed_load() -> None: + m5 = estimate_stage_breakdown_s( + width=512, + height=288, + frames=compute_num_frames(4, 24), + load_mode="streaming_models_loading", + offload_mode="DISK", + system="Darwin", + machine_factor=1.0, + stage_2=False, + ) + m3 = estimate_stage_breakdown_s( + width=512, + height=288, + frames=compute_num_frames(4, 24), + load_mode="streaming_models_loading", + offload_mode="DISK", + system="Darwin", + machine_factor=2.0, + stage_2=False, + ) + assert m5 is not None and m3 is not None + assert m3.load_s == m5.load_s == 4 + assert m3.seconds < 2 * m5.seconds + + +def test_tiled_and_windowed_breakdown_scales_denoise_by_tiles_and_windows() -> None: + untiled = estimate_stage_breakdown_s( + width=1920, + height=1088, + frames=97, + load_mode="streaming_models_loading", + offload_mode="DISK", + stage_2=False, + ic_lora=True, + ) + restore_tiled = estimate_stage_breakdown_s( + width=1920, + height=1088, + frames=97, + load_mode="streaming_models_loading", + offload_mode="DISK", + stage_2=False, + ic_lora=True, + tiling=IcLoraTiling(long_side=960, short_side=544), + ) + windowed = estimate_stage_breakdown_s( + width=1920, + height=1088, + frames=241, + load_mode="streaming_models_loading", + offload_mode="DISK", + stage_2=False, + ic_lora=True, + chunk_pixel_frames=97, + carry_frames=25, + tiling=IcLoraTiling(long_side=960, short_side=544), + ) + assert untiled is not None and restore_tiled is not None and windowed is not None + assert restore_tiled.denoise_s > untiled.denoise_s * 3 + assert restore_tiled.decode_s == untiled.decode_s + # Three windows. Each window's denoise time is rounded to whole seconds. + assert abs(windowed.denoise_s - restore_tiled.denoise_s * 3) <= 3 + + +def test_remaining_wall_time_counts_down_through_decode_phase() -> None: + est = WallTimeEstimate( + seconds=200, basis="scaled", t2v_reuse=False, load_s=20, denoise_s=120, decode_s=60 + ) + mid_denoise = remaining_wall_time_s( + est, elapsed_s=80.0, current_step=4, total_steps=8 + ) + decode_start = remaining_wall_time_s( + est, elapsed_s=140.0, current_step=8, total_steps=8, decode_elapsed_s=0.0 + ) + decode_half = remaining_wall_time_s( + est, elapsed_s=170.0, current_step=8, total_steps=8, decode_elapsed_s=30.0 + ) + assert mid_denoise == 120 + assert decode_start == 60 + assert decode_half == 30 + + +def test_remaining_wall_time_reaches_zero_when_overdue() -> None: + est = WallTimeEstimate( + seconds=100, basis="scaled", t2v_reuse=False, load_s=10, denoise_s=60, decode_s=30 + ) + assert remaining_wall_time_s(est, elapsed_s=120.0, current_step=0, total_steps=8) == 0 + assert ( + remaining_wall_time_s( + est, elapsed_s=120.0, current_step=8, total_steps=8, decode_elapsed_s=45.0 + ) + == 0 + ) def test_incoherent_mode_combos_return_none() -> None: @@ -138,18 +262,95 @@ def test_unknown_machine_returns_none() -> None: assert est is None -def test_machine_factor_scales_table() -> None: - """The calibration-probe seam: a 2×-slower machine doubles the table.""" - est = estimate_fast_wall_time_s( +def test_calibrated_factor_uses_stage_law_not_table_cell() -> None: + """Table cells are reference walls at factor 1.0. A calibrated factor is relative to the + stage law, so a 2x-slower machine gets the law's estimate, not 2x the table cell.""" + + def cell(factor: float) -> WallTimeEstimate | None: + return estimate_fast_wall_time_s( + width=1024, + height=576, + frames=compute_num_frames(5, 24), + load_mode="streaming_models_loading", + offload_mode="CPU", + feature="t2v", + machine_factor=factor, + ) + + ref, slow = cell(1.0), cell(2.0) + law = estimate_stage_breakdown_s( width=1024, height=576, frames=compute_num_frames(5, 24), load_mode="streaming_models_loading", offload_mode="CPU", - feature="t2v", machine_factor=2.0, ) - assert est == WallTimeEstimate(seconds=316, basis="measured", t2v_reuse=False) + assert ref is not None and slow is not None and law is not None + assert (ref.seconds, ref.basis) == (158, "measured") + assert (slow.seconds, slow.basis) == (law.seconds, "scaled") + assert (slow.load_s, slow.denoise_s, slow.decode_s) == (law.load_s, law.denoise_s, law.decode_s) + + +def _disk_breakdown( + width: int, height: int, seconds: int, factor: float, *, stage_2: bool = True +) -> WallTimeBreakdown | None: + return estimate_stage_breakdown_s( + width=width, + height=height, + frames=compute_num_frames(seconds, 24), + load_mode="streaming_models_loading", + offload_mode="DISK", + machine_factor=factor, + stage_2=stage_2, + ) + + +def test_cuda_streaming_factor_scales_weight_streaming_only() -> None: + """A RAM-starved DISK machine pays per-step streaming; compute, load, and decode stay.""" + ref_270p = _disk_breakdown(512, 288, 3, 1.0, stage_2=False) + slow_270p = _disk_breakdown(512, 288, 3, 3.6, stage_2=False) + slow_1440p = _disk_breakdown(2560, 1472, 5, 3.6) + assert ref_270p is not None and slow_270p is not None and slow_1440p is not None + assert (slow_270p.load_s, slow_270p.decode_s) == (ref_270p.load_s, ref_270p.decode_s) + # Measured on an RTX 4090 / 32 GiB RAM / DISK offload: 270p 3s took 229-238 s in all, and + # 1440p 5s denoised in 290 s, the same as 540p, because compute hides under streaming. + assert 215 <= slow_270p.seconds <= 245 + assert 280 <= slow_1440p.denoise_s <= 305 + + +def test_full_load_factor_scales_gpu_terms_only() -> None: + def full(factor: float) -> WallTimeBreakdown | None: + return estimate_stage_breakdown_s( + width=1024, + height=576, + frames=compute_num_frames(5, 24), + load_mode="full_models_loading", + offload_mode="NONE", + machine_factor=factor, + ) + + ref, slow = full(1.0), full(2.0) + assert ref is not None and slow is not None + assert slow.load_s == ref.load_s + assert abs(slow.decode_s - 2 * ref.decode_s) <= 1 + assert ref.denoise_s < slow.denoise_s < 2 * ref.denoise_s + + +def test_implied_machine_factor_round_trips_cuda_estimate() -> None: + est = estimate_stage_breakdown_s( + width=1024, + height=576, + frames=compute_num_frames(5, 24), + load_mode="streaming_models_loading", + offload_mode="DISK", + machine_factor=3.0, + ) + assert est is not None + factor = implied_machine_factor( + wall_s=float(est.seconds), width=1024, height=576, frames=compute_num_frames(5, 24) + ) + assert factor is not None and abs(factor - 3.0) < 0.05 @pytest.mark.parametrize("factor", [0.0, -1.0]) @@ -196,3 +397,212 @@ def test_i2v_a2v_reuse_t2v_numbers_flagged(feature: str, reuse: bool) -> None: ) def test_measured_hardware_class(name: str | None, expected: bool) -> None: assert is_measured_hardware_class(name) is expected + + +def test_conv_vae_decodes_at_measured_ratio_on_cuda() -> None: + def run(conv_vae: bool) -> WallTimeBreakdown | None: + return estimate_stage_breakdown_s( + width=2560, + height=1472, + frames=compute_num_frames(5, 24), + load_mode="streaming_models_loading", + offload_mode="DISK", + machine_factor=3.6, + conv_vae=conv_vae, + ) + + diff_vae, conv = run(False), run(True) + assert diff_vae is not None and conv is not None + assert (conv.load_s, conv.denoise_s) == (diff_vae.load_s, diff_vae.denoise_s) + assert abs(conv.decode_s / diff_vae.decode_s - 0.31) < 0.02 + # Measured on an RTX 4090 with ConvVAE: 1440p 5s decoded in 18.7-19.8 s. + assert 15 <= conv.decode_s <= 35 + + +def test_mac_ignores_conv_vae() -> None: + def run(conv_vae: bool) -> WallTimeBreakdown | None: + return estimate_stage_breakdown_s( + width=1024, + height=576, + frames=compute_num_frames(5, 24), + load_mode="streaming_models_loading", + offload_mode="DISK", + system="Darwin", + conv_vae=conv_vae, + ) + + assert run(True) == run(False) + + +def test_conv_vae_swaps_table_cell_decode() -> None: + def cell(conv_vae: bool) -> WallTimeEstimate | None: + return estimate_fast_wall_time_s( + width=1024, + height=576, + frames=compute_num_frames(5, 24), + load_mode="streaming_models_loading", + offload_mode="CPU", + feature="t2v", + machine_factor=1.0, + conv_vae=conv_vae, + ) + + diff_vae, conv = cell(False), cell(True) + assert diff_vae is not None and conv is not None + assert (diff_vae.seconds, diff_vae.basis) == (158, "measured") + assert conv.basis == "scaled" + assert 0 < diff_vae.seconds - conv.seconds < diff_vae.decode_s + + +def test_implied_machine_factor_round_trips_conv_vae_estimate() -> None: + est = estimate_stage_breakdown_s( + width=1280, + height=704, + frames=compute_num_frames(5, 24), + load_mode="streaming_models_loading", + offload_mode="DISK", + machine_factor=3.0, + conv_vae=True, + ) + assert est is not None + factor = implied_machine_factor( + wall_s=float(est.seconds), + width=1280, + height=704, + frames=compute_num_frames(5, 24), + conv_vae=True, + ) + assert factor is not None and abs(factor - 3.0) < 0.05 + + +def test_stage_1_share_weights_mac_and_cuda_streaming_countdown_differently() -> None: + mac = estimate_fast_wall_time_s( + width=1024, + height=576, + frames=compute_num_frames(5, 24), + load_mode="streaming_models_loading", + offload_mode="DISK", + feature="t2v", + machine_factor=1.0, + system="Darwin", + ) + cuda = estimate_fast_wall_time_s( + width=1024, + height=576, + frames=compute_num_frames(5, 24), + load_mode="streaming_models_loading", + offload_mode="DISK", + feature="t2v", + machine_factor=3.6, + system="Windows", + conv_vae=True, + ) + assert mac is not None and cuda is not None + assert mac.stage_1_share is not None and cuda.stage_1_share is not None + assert 0.35 < mac.stage_1_share < 0.55 + assert 0.68 < cuda.stage_1_share < 0.76 + rem_cuda = remaining_wall_time_s( + cuda, + elapsed_s=cuda.load_s + cuda.denoise_s * cuda.stage_1_share, + current_step=8, + total_steps=11, + ) + true_rem = round(cuda.denoise_s * (1.0 - cuda.stage_1_share) + cuda.decode_s) + assert rem_cuda is not None and abs(rem_cuda - true_rem) <= 2 + + +def test_envelope_wall_time_uses_shape_tile_count() -> None: + base = JobShape( + feature="iclora", + model_id="ltx-2.5-22b-distilled", + adapter_id="refine-details", + stage_mode="single_stage", + tiled=True, + chunked=False, + seq=14_976.0, + canvas_px=1920 * 1088, + windows=1, + tiles=1, + ) + one_tile = estimate_envelope_wall_time( + envelope_for(base, "streaming_models_loading", 14.0), machine_factor=1.0 + ) + nine_tiles = estimate_envelope_wall_time( + envelope_for( + JobShape( + feature="iclora", + model_id="ltx-2.5-22b-distilled", + adapter_id="refine-details", + stage_mode="single_stage", + tiled=True, + chunked=False, + seq=14_976.0, + canvas_px=3840 * 2176, + windows=1, + tiles=9, + ), + "streaming_models_loading", + 14.0, + ), + machine_factor=1.0, + ) + assert one_tile is not None and nine_tiles is not None + assert abs(nine_tiles.denoise_s - one_tile.denoise_s * 9) <= 2 + + +def test_implausible_stored_shapes_are_rejected() -> None: + """A tampered row must not size a huge window list.""" + shape = { + "width": 1024, + "height": 576, + "load_mode": "streaming_models_loading", + "offload_mode": "DISK", + } + assert estimate_stage_breakdown_s(**shape, frames=121) is not None # type: ignore[arg-type] + assert estimate_stage_breakdown_s(**shape, frames=100_001) is None # type: ignore[arg-type] + assert implied_machine_factor(wall_s=100.0, width=1024, height=576, frames=100_001) is None + + def envelope(windows: int): # type: ignore[no-untyped-def] + return envelope_for( + JobShape( + feature="fast", + model_id="ltx-2.5-22b-distilled", + adapter_id="", + stage_mode="", + tiled=False, + chunked=False, + seq=9216.0, + canvas_px=1024 * 576, + windows=windows, + ), + "streaming_models_loading", + 10.0, + ) + + assert estimate_envelope_wall_time(envelope(1_000), machine_factor=1.0) is not None + assert estimate_envelope_wall_time(envelope(1_001), machine_factor=1.0) is None + assert ( + implied_envelope_factor( + "Windows", envelope(1_001).bucket, envelope(1_001).point, 100.0 + ) + is None + ) + + +def test_spatial_tile_count_follows_the_upstream_layout_and_the_run_overlap() -> None: + """The count is upstream's ``split_by_size_pinned`` layout, and the run's overlap sets it. + + Documented layouts on 1920x1088: Refine's 1024x576 tiles lay out 2x2, Restore's 960x544 3x2. + A lower overlap needs fewer tiles on a large canvas, down to the layout floor. + """ + refine = IcLoraTiling(long_side=1024, short_side=576) + assert spatial_tile_count(1920, 1088, refine) == 4 + assert spatial_tile_count(1920, 1088, IcLoraTiling(long_side=960, short_side=544)) == 6 + assert spatial_tile_count(1088, 1920, refine) == 4 # portrait follows the canvas + assert spatial_tile_count(1920, 1088, None) == 1 + + def count(overlap: float) -> int: + tiling = IcLoraTiling(long_side=1024, short_side=576, overlap_fraction=overlap) + return spatial_tile_count(3840, 2112, tiling) + + assert [count(o) for o in (0.0, 0.15, 0.25, 0.5)] == [16, 20, 25, 36] diff --git a/backend/tests/test_fal_lane.py b/backend/tests/test_fal_lane.py new file mode 100644 index 000000000..dca5d4e66 --- /dev/null +++ b/backend/tests/test_fal_lane.py @@ -0,0 +1,317 @@ +"""A fal image job runs beside a local job, on its own lane. + +Each test names the bug it catches. +""" + +from __future__ import annotations + +import io +import threading +import time + +import pytest +from PIL import Image + +_CREATE = "/api/generations/text-to-image" +_QUEUE = "/api/generation-queue" + + +def _png_bytes() -> bytes: + buffer = io.BytesIO() + Image.new("RGB", (16, 16), color=(10, 20, 30)).save(buffer, format="PNG") + return buffer.getvalue() + + +def _create(client, provider: str, **params: object) -> dict: + response = client.post(_CREATE, json={"params": {"prompt": "a red fox", "provider": provider, **params}}) + assert response.status_code == 200, response.text + return response.json() + + +def _wait_for(condition, what: str, timeout: float = 5.0) -> None: + deadline = time.monotonic() + timeout + while not condition(): + assert time.monotonic() < deadline, f"timed out waiting for {what}" + time.sleep(0.02) + + +def _status(client, generation_id: str) -> str: + return client.get(f"/api/generations/{generation_id}").json()["status"] + + +def _hold_fal(test_state, fake_services) -> threading.Event: + """Keep every fal request open until the returned event is set.""" + test_state.state.app_settings.fal_api_key = "fal-key" + fake_services.zit_api_client.text_to_image_result = _png_bytes() + fake_services.zit_api_client.queued_release.clear() + return fake_services.zit_api_client.queued_release + + +def _hold_local(fake_services, create_fake_model_files) -> None: + create_fake_model_files(include_zit=True) + pipeline = fake_services.image_generation_pipeline + pipeline.inference_steps = 400 + pipeline.step_delay_s = 0.02 + + +def _start_both(client, test_state, fake_services, create_fake_model_files) -> tuple[dict, dict]: + _hold_fal(test_state, fake_services) + _hold_local(fake_services, create_fake_model_files) + local = _create(client, "local") + assert fake_services.image_generation_pipeline.entered_inference.wait(timeout=5) + fal = _create(client, "fal") + assert fake_services.zit_api_client.queued_entered.wait(timeout=5) + return local, fal + + +def test_a_local_job_and_a_fal_job_run_at_the_same_time( + client, test_state, fake_services, create_fake_model_files +) -> None: + # Bug caught: the fal job waits for the local job (one global queue). + local, fal = _start_both(client, test_state, fake_services, create_fake_model_files) + + active = client.get(_QUEUE).json()["active"] + + assert {entry["generation"]["id"] for entry in active} == {local["id"], fal["id"]} + assert {entry["generation"]["lane"] for entry in active} == {"local", "fal"} + client.post(f"/api/generations/{local['id']}/cancel") + fake_services.zit_api_client.queued_release.set() + + +def test_the_fal_job_reports_its_own_status_and_never_the_local_progress( + client, test_state, fake_services, create_fake_model_files +) -> None: + # Bug caught: the fal job writes the global generation state, so the local job's progress + # bar jumps or the provider job shows the local job's percentage. + local, fal = _start_both(client, test_state, fake_services, create_fake_model_files) + + _wait_for( + lambda: any( + entry["api_status"] == "pending" for entry in client.get(_QUEUE).json()["active"] + ), + "the fal status", + ) + by_id = {entry["generation"]["id"]: entry for entry in client.get(_QUEUE).json()["active"]} + global_progress = test_state.generation.get_generation_progress() + + assert by_id[fal["id"]]["api_status"] == "pending" + assert by_id[local["id"]]["api_status"] is None + assert global_progress.id == local["id"] + assert global_progress.phase != "validating_request" + client.post(f"/api/generations/{local['id']}/cancel") + fake_services.zit_api_client.queued_release.set() + + +def test_cancelling_the_fal_job_leaves_the_local_job_running( + client, test_state, fake_services, create_fake_model_files +) -> None: + # Bug caught: a cancel is routed to the global interrupt and stops the wrong job. + local, fal = _start_both(client, test_state, fake_services, create_fake_model_files) + + assert client.post(f"/api/generations/{fal['id']}/cancel").status_code == 200 + _wait_for(lambda: _status(client, fal["id"]) == "cancelled", "the fal job to cancel") + + assert _status(client, local["id"]) == "running" + client.post(f"/api/generations/{local['id']}/cancel") + + +def test_cancelling_the_local_job_leaves_the_fal_job_running( + client, test_state, fake_services, create_fake_model_files +) -> None: + # Bug caught: the global interrupt flag set for the local job also stops the fal job. + local, fal = _start_both(client, test_state, fake_services, create_fake_model_files) + + assert client.post(f"/api/generations/{local['id']}/cancel").status_code == 200 + _wait_for(lambda: _status(client, local["id"]) == "cancelled", "the local job to cancel") + + assert _status(client, fal["id"]) == "running" + fake_services.zit_api_client.queued_release.set() + _wait_for(lambda: _status(client, fal["id"]) == "succeeded", "the fal job to finish") + + +def test_a_cancelled_fal_job_frees_the_lane_for_the_next_fal_job( + client, test_state, fake_services +) -> None: + # Bug caught: a cancelled provider job keeps the lane until the provider answers. + release = _hold_fal(test_state, fake_services) + first = _create(client, "fal") + assert fake_services.zit_api_client.queued_entered.wait(timeout=5) + second = _create(client, "fal") + + assert _status(client, second["id"]) == "queued" + client.post(f"/api/generations/{first['id']}/cancel") + + # The provider has not answered yet (the request is still held). The lane is free anyway. + _wait_for(lambda: _status(client, first["id"]) == "cancelled", "the first job to cancel") + _wait_for(lambda: _status(client, second["id"]) == "running", "the second job to start") + release.set() + _wait_for(lambda: _status(client, second["id"]) == "succeeded", "the second job to finish") + + +def test_two_fal_jobs_run_in_order_one_at_a_time(client, test_state, fake_services) -> None: + # Bug caught: lane concurrency is not enforced and two fal requests overlap. + release = _hold_fal(test_state, fake_services) + first = _create(client, "fal") + assert fake_services.zit_api_client.queued_entered.wait(timeout=5) + second = _create(client, "fal") + time.sleep(0.2) + + assert len(fake_services.zit_api_client.text_to_image_calls) == 1 + assert _status(client, second["id"]) == "queued" + release.set() + _wait_for(lambda: _status(client, second["id"]) == "succeeded", "the second job") + assert _status(client, first["id"]) == "succeeded" + + +def test_a_fal_job_does_not_block_the_local_sync_generation_slot( + client, test_state, fake_services +) -> None: + # Bug caught: a fal job takes the global GPU slot, so Generate is locked while fal runs. + _hold_fal(test_state, fake_services) + _create(client, "fal") + assert fake_services.zit_api_client.queued_entered.wait(timeout=5) + + # The global slot is free: a local job can reserve it while the fal request is open. + assert test_state.generation.try_reserve_generation_start() is True + test_state.generation.release_generation_start_reservation() + fake_services.zit_api_client.queued_release.set() + + +@pytest.mark.parametrize("parallel_lanes", [False], indirect=True) +def test_with_parallel_lanes_off_a_fal_job_waits_behind_the_local_job( + client, test_state, fake_services, create_fake_model_files +) -> None: + # Bug caught: the kill switch leaves the fal lane on, so runs are not serial. + _hold_fal(test_state, fake_services) + fake_services.zit_api_client.queued_release.set() + _hold_local(fake_services, create_fake_model_files) + local = _create(client, "local") + assert fake_services.image_generation_pipeline.entered_inference.wait(timeout=5) + + fal = _create(client, "fal") + time.sleep(0.2) + + assert fal["lane"] == "local" + assert _status(client, fal["id"]) == "queued" + assert fake_services.zit_api_client.text_to_image_calls == [] + client.post(f"/api/generations/{local['id']}/cancel") + _wait_for(lambda: _status(client, fal["id"]) == "succeeded", "the fal job to run after") + + +@pytest.mark.parametrize("parallel_lanes", [False], indirect=True) +def test_with_parallel_lanes_off_the_local_gemma_still_rewrites_a_fal_prompt( + client, test_state, fake_services, create_fake_model_files +) -> None: + # Bug caught: the kill switch makes the lease fail (the job holds the local slot itself), so + # every fal job pays for fal expansion although Gemma is downloaded and the GPU is idle. + _hold_fal(test_state, fake_services) + fake_services.zit_api_client.queued_release.set() + create_fake_model_files(include_prompt_enhancer=True) + test_state.state.app_settings.explore_auto_enhance_prompts = True + fake_services.prompt_enhancer_pipeline.enhanced_prompt = "a richly detailed red fox" + + fal = _create(client, "fal") + _wait_for(lambda: _status(client, fal["id"]) == "succeeded", "the fal job") + + call = fake_services.zit_api_client.text_to_image_calls[-1] + assert call["prompt"] == "a richly detailed red fox" + assert call["enable_prompt_expansion"] is False + + +@pytest.mark.parametrize("parallel_lanes", [False], indirect=True) +def test_retrying_a_failed_fal_job_with_parallel_lanes_off_runs_it_on_the_local_lane( + client, test_state, fake_services +) -> None: + # Bug caught: the retry keeps the lane "fal", which has no runner now, and the job waits forever. + _hold_fal(test_state, fake_services) + fake_services.zit_api_client.queued_release.set() + store = test_state.queued_generations._db + spec = {"params": {"prompt": "a red fox", "provider": "fal", "width": 512, "height": 512}, "inputs": {}} + job = store.insert_generation("text-to-image", spec, lane="fal") + test_state.generation_queue.stop() + claimed = store.claim_next_queued("fal") + assert claimed is not None + store.mark_failed(job.id, "OUTPUT_UNREADABLE", attempt_count=claimed.attempt_count) + test_state.generation_queue.start() + + assert client.post(f"/api/generations/{job.id}/retry").status_code == 200 + + _wait_for(lambda: _status(client, job.id) == "succeeded", "the retried job") + assert client.get(f"/api/generations/{job.id}").json()["lane"] == "local" + + +def _store(test_state): + return test_state.queued_generations._db + + +def test_the_fal_request_id_is_stored_before_the_first_status_check( + client, test_state, fake_services +) -> None: + # Bug caught: the id is stored late or never, so a stop during the wait leaves a request nobody can cancel. + _hold_fal(test_state, fake_services) + fal = _create(client, "fal") + assert fake_services.zit_api_client.queued_entered.wait(timeout=5) + + body = client.get(f"/api/generations/{fal['id']}").json() + assert body["provider_job_id"] == "fake-fal-1" + fake_services.zit_api_client.queued_release.set() + _wait_for(lambda: _status(client, fal["id"]) == "succeeded", "the fal job to finish") + + +def test_a_fal_request_id_that_cannot_be_stored_fails_the_job_and_cancels_the_request( + client, test_state, fake_services, monkeypatch +) -> None: + # Bug caught: the job runs on at fal with no id on record, so a boot cannot cancel it. + _hold_fal(test_state, fake_services) + monkeypatch.setattr(_store(test_state), "set_provider_job_id", lambda *args: False) + + fal = _create(client, "fal") + + _wait_for(lambda: _status(client, fal["id"]) == "failed", "the fal job to fail") + assert fake_services.zit_api_client.cancelled_request_ids == ["fake-fal-1"] + + +def _two_running_fal_rows(test_state) -> list[str]: + test_state.state.app_settings.fal_api_key = "fal-key" + test_state.generation_queue.stop() + store = _store(test_state) + ids = [] + for request_id in ("req-a", "req-b"): + store.insert_generation("text-to-image", {"params": {"prompt": "x"}, "inputs": {}}, lane="fal") + claimed = store.claim_next_queued("fal") + assert claimed is not None + assert store.set_provider_job_id(claimed.id, claimed.attempt_count, request_id) + ids.append(claimed.id) + return ids + + +def _pending_provider_ids(test_state) -> list[str]: + return sorted(orphan.provider_job_id for orphan in _store(test_state).list_provider_orphans()) + + +def test_a_boot_cancels_every_fal_job_that_was_running_and_forgets_the_ids( + test_state, fake_services +) -> None: + # Bug caught: a job running at fal when the app stopped is failed locally and fal keeps billing it. + _two_running_fal_rows(test_state) + + test_state.queued_generations.recover_on_boot() + + _wait_for(lambda: _pending_provider_ids(test_state) == [], "the boot cancel to finish") + assert sorted(fake_services.zit_api_client.cancel_queued_calls) == ["req-a", "req-b"] + + +def test_a_failing_fal_cancel_at_boot_does_not_block_the_boot_and_keeps_the_ids( + test_state, fake_services +) -> None: + # Bug caught: fal is down at boot, the app fails to start, or the ids are dropped and the jobs run on. + ids = _two_running_fal_rows(test_state) + fake_services.zit_api_client.raise_on_cancel_queued = RuntimeError("fal down") + + test_state.queued_generations.recover_on_boot() + + _wait_for( + lambda: len(fake_services.zit_api_client.cancel_queued_calls) == 2, "both cancels to run" + ) + assert _pending_provider_ids(test_state) == ["req-a", "req-b"] + assert all(_store(test_state).get_generation(i).status == "failed" for i in ids) diff --git a/backend/tests/test_fast_chunked_budget.py b/backend/tests/test_fast_chunked_budget.py index d3affa2ca..f07e841f8 100644 --- a/backend/tests/test_fast_chunked_budget.py +++ b/backend/tests/test_fast_chunked_budget.py @@ -7,15 +7,23 @@ from __future__ import annotations +from dataclasses import replace + +import pytest + from frame_math import compute_num_frames -from runtime_config.fast_chunking import window_count -from runtime_config.measured_cells import MEASURED_HIGH_RES_CELLS +from api_model_specs import get_local_video_generation_model_specs +from runtime_config.budget_admission import Admitted, RiskAllowance +from runtime_config.budget_decision import VideoJobLoad, VideoJobReject +from runtime_config.fast_chunking import is_chunked_canvas, last_window_frames, window_count +from runtime_config.ltx_capabilities import budget_shape, effective_local_caps +from runtime_config.measured_cells import MEASURED_HIGH_RES_CELLS, MEASURED_MAX_DECODE_TOKENS from runtime_config.video_job_budget import ( - VideoJobLoad, - VideoJobReject, advertised_fast_durations, + decide_edit_job, decide_video_job, fast_job_stream_gib, + max_edit_frames_that_load, video_tokens, ) from tests.test_video_job_budget import _windows_measured_filter @@ -26,9 +34,13 @@ def _decide(size: tuple[int, int], frames: int, vram_gib: float): - return decide_video_job( - *size, frames, job_filter=_windows_measured_filter(vram_gib, 64) + admission = decide_video_job( + *size, + frames, + job_filter=_windows_measured_filter(vram_gib, 64), + allowance=RiskAllowance.none(), ) + return admission.load if isinstance(admission, Admitted) else admission.reject def test_clip_that_fits_one_window_is_not_chunked() -> None: @@ -44,13 +56,35 @@ def test_clip_over_one_window_takes_the_longest_window_not_the_shortest() -> Non def test_card_too_small_for_the_long_window_falls_back_to_a_shorter_one() -> None: - # 65 frames is 2 windows either way. 23 GiB rejects the 49-frame windows (24.7 GiB) - # and loads the 41-frame windows (21.9 GiB). - decision = _decide(_4K, 65, 23) + # 81 frames has a full 49-frame second window (24.7 GiB). A 24 GiB card rejects + # the 49-frame windows and loads the 41-frame windows (23.8 GiB). + decision = _decide(_4K, 81, 24) assert isinstance(decision, VideoJobLoad) assert decision.chunk_pixel_frames == 41 +def test_short_second_window_prices_last_window_tokens_and_covers_measured_peaks() -> None: + # G2a (4K 73f: 49f then 41f) peaked at 21.80 GiB and G2b (1440p 145f: 129f then 33f) + # peaked at 21.88 GiB, while G1 (1440p 241f: 129f then 129f) peaked at 25.58 GiB. + # Pricing every 2-window job as two full windows over-asks G2a (24.71) and G2b (26.58) + # past a 24 GiB card; omitting max(base_law(t1), ...) under-asks G2b (14.22) below window 1. + g2a = _decide(_4K, 73, 24) + assert isinstance(g2a, VideoJobLoad) + assert g2a.chunk_pixel_frames == 49 + assert 21.80 <= g2a.stream_gib < 24.0 + + g2b = _decide(_1440P, 145, 24) + assert isinstance(g2b, VideoJobLoad) + assert g2b.chunk_pixel_frames == 129 + assert 21.88 <= g2b.stream_gib < 24.0 + + g1 = _decide(_1440P, 241, 32) + assert isinstance(g1, VideoJobLoad) + assert g1.chunk_pixel_frames == 129 + assert last_window_frames(241, 129) == 129 + assert g1.stream_gib == pytest.approx(26.5832) + + def test_three_windows_pay_a_larger_extra_than_two_windows() -> None: tokens = video_tokens(_4K[1], _4K[0], 49) one = fast_job_stream_gib(tokens, windows=1, darwin=False) @@ -95,16 +129,93 @@ def test_fast_4k_row_loads_at_15_windows_and_refuses_at_16() -> None: def test_fast_1440p_row_is_the_129_frame_window_count_not_the_41_frame_one() -> None: - # 481 frames is 5 windows of 129 (measured); 689 is 6. Opening the row to the 41-frame - # window's 20 would admit 129-frame jobs of 6 to 20 windows that no run covers. - at_row = _decide(_1440P, 481, 64) + # 961 frames is 9 windows of 129 (measured); 1033 is 10. Opening the row to the 41-frame + # window's 20 would admit 129-frame jobs of 10 to 20 windows that no run covers. + assert MEASURED_HIGH_RES_CELLS[("fast", "windows_measured", "1440p")] == 9 + at_row = _decide(_1440P, 961, 64) assert isinstance(at_row, VideoJobLoad) assert at_row.chunk_pixel_frames == 129 - past_row = _decide(_1440P, 689, 64) + past_row = _decide(_1440P, 1033, 64) assert isinstance(past_row, VideoJobReject) assert past_row.reason == "unmeasured_cell" +def test_windows_edit_1440p_and_4k_rows_load_up_to_65_frames_and_mark_73_unmeasured() -> None: + # 1440p Retake and Extend sit inside the 1080p reserved law through 193 frames (29.50 GiB + # vs 29.93 ask), while 4K VAE decode is priced via _EDIT_DECODE_STREAM (21.57 GiB at + # 49f, 26.83 GiB at 65f) and capped at 73,440 decode tokens (65f at 4K) where WDDM paging stays zero. + assert MEASURED_HIGH_RES_CELLS[("edit", "windows_measured", "1440p")] == 1 + assert MEASURED_HIGH_RES_CELLS[("edit", "windows_measured", "2160p")] == 1 + assert MEASURED_MAX_DECODE_TOKENS[("edit", "windows_measured")] == 73_440.0 + job_filter = _windows_measured_filter(32, 64) + edit_1440p = decide_edit_job( + 2560, 1440, 193, job_filter=job_filter, allowance=RiskAllowance.none() + ) + assert isinstance(edit_1440p, Admitted) + edit_4k_65 = decide_edit_job( + *_4K, 65, job_filter=job_filter, allowance=RiskAllowance.none() + ) + assert isinstance(edit_4k_65, Admitted) + assert edit_4k_65.load.stream_gib == pytest.approx(3.15 + 3.222e-4 * 73_440) + assert max_edit_frames_that_load(*_4K, frame_cap=505, job_filter=job_filter) == 65 + edit_4k_73 = decide_edit_job( + *_4K, 73, job_filter=job_filter, allowance=RiskAllowance.none() + ) + assert not isinstance(edit_4k_73, Admitted) + assert edit_4k_73.reject.reason == "unmeasured_cell" + + +def test_windows_4k_edit_frame_cap_stops_at_measured_decode_ceiling() -> None: + # A short 4K retake in Brave mode must not pad optional context past the 65-frame + # (73,440-token) decode ceiling into the 73-frame WDDM paging zone, while an explicit + # >65-frame selection in Brave mode can still reach the VRAM ceiling as an unmeasured bet. + cautious_filter = replace(_windows_measured_filter(32, 64), budget_mode="cautious") + brave_filter = replace(cautious_filter, budget_mode="brave") + + assert max_edit_frames_that_load(*_4K, frame_cap=505, job_filter=cautious_filter) == 65 + assert max_edit_frames_that_load(*_4K, frame_cap=505, job_filter=brave_filter) == 65 + assert ( + max_edit_frames_that_load(*_4K, frame_cap=505, min_frames=73, job_filter=cautious_filter) + == 65 + ) + assert ( + max_edit_frames_that_load(*_4K, frame_cap=505, min_frames=73, job_filter=brave_filter) + == 73 + ) + brave_73 = decide_edit_job(*_4K, 73, job_filter=brave_filter) + assert isinstance(brave_73, Admitted) + assert brave_73.risk is not None and brave_73.risk.tier == "unmeasured" + + +def test_narrow_1440p_canvases_use_chunked_budget_law_instead_of_single_pass_1080p_law() -> None: + # 1440p 1:1 (1472x1472 = 2.17 Mpx), 4:5 (1472x1856 = 2.73 Mpx), and 4:3 (1984x1472 = 2.92 Mpx) + # sit under 3.20 Mpx; gating is_chunked_canvas on pixel area instead of short side drops them + # into the single-pass <=1080p path and refuses 20 s on a 24 GiB card. + caps = effective_local_caps("ltx-2.5-22b-distilled", duration_head_ready=True) + for aspect in ("1:1", "4:5", "4:3"): + width, height = budget_shape(caps, "1440p", aspect, mode="stage2") + assert is_chunked_canvas(width, height), aspect + decision = _decide((width, height), compute_num_frames(20, 24), 24) + assert isinstance(decision, VideoJobLoad), aspect + assert decision.chunk_pixel_frames is not None, aspect + + +@pytest.mark.usefixtures("single_pass_only") +def test_narrower_aspect_ratios_unlock_longer_durations_than_16_9_anchor_on_same_vram() -> None: + # At 1080p/24fps, 10 s at 1:1 (1088x1088, 35,880t -> 15.05 GiB) fits a 16 GiB card while + # 16:9 (1920x1088, 63,240t -> 22.71 GiB) only fits up to 5 s (32,640t -> 14.14 GiB). + specs = get_local_video_generation_model_specs( + duration_head_ready=True, + job_filter=_windows_measured_filter(16, 64), + ) + fast_spec = specs[0].spec + assert fast_spec.aspect_specs is not None + durations_16_9 = fast_spec.aspect_specs["16:9"].supported_resolutions_durations["1080p"].fps_to_durations[24] + durations_1_1 = fast_spec.aspect_specs["1:1"].supported_resolutions_durations["1080p"].fps_to_durations[24] + assert 10 not in durations_16_9 + assert 10 in durations_1_1 + + def test_reject_names_the_ask_of_the_shortest_window() -> None: frames = 241 decision = _decide(_4K, frames, 14) @@ -129,7 +240,7 @@ def test_offered_durations_match_the_create_verdict_at_1440p_and_4k() -> None: decide_video_job( *size, compute_num_frames(seconds, 24), job_filter=job_filter ), - VideoJobLoad, + Admitted, ) ] assert offered == loads diff --git a/backend/tests/test_fast_chunked_cells.py b/backend/tests/test_fast_chunked_cells.py index c8810e125..1fa3e830d 100644 --- a/backend/tests/test_fast_chunked_cells.py +++ b/backend/tests/test_fast_chunked_cells.py @@ -44,17 +44,23 @@ def test_a_single_pass_cell_is_never_listed() -> None: *_rest, chunked = _plain(31.84) listed = {(c.resolution, c.fps, c.duration) for c in chunked} assert ("1080p", 24, 10) not in listed - # Below 1080p only the cells one pass cannot fit on the card (720p at 20 s and 48 or 50 fps) - # run in windows. No resolution is named: the rule is the same one that windows 1080p. - assert not [c for c in chunked if c.resolution == "540p"] - assert {(c.fps, c.duration) for c in chunked if c.resolution == "720p"} == {(48, 20), (50, 20)} - - -def test_a_card_below_the_measured_one_does_not_list_1080p() -> None: + # Below 1080p only the cells one pass cannot take run in windows. No resolution is named: the + # rule is the same one that windows 1080p. A 20 s 540p clip at 24 fps is 35k tokens, inside + # the fit. At 48 fps it is 70k, past it, so Cautious takes it in windows. + assert ("540p", 24, 20) not in listed + assert ("540p", 48, 20) in listed + assert {(c.fps, c.duration) for c in chunked if c.resolution == "720p" and c.duration <= 20} == { + (48, 20), + (50, 20), + } + + +def test_a_card_below_the_measured_one_lists_its_1080p_windows_without_a_card_floor() -> None: kept, *_rest, chunked = _plain(24) assert kept is not None - assert not [c for c in chunked if c.resolution == "1080p"] - assert 20 not in kept["1080p"].fps_to_durations.get(24, []) + cell = next(c for c in chunked if (c.resolution, c.fps, c.duration) == ("1080p", 24, 20)) + assert (cell.windows, cell.window_frames) == (3, 185) + assert 20 in kept["1080p"].fps_to_durations[24] def test_the_a2v_grid_lists_its_own_cells_as_audio() -> None: @@ -70,23 +76,24 @@ def test_the_a2v_grid_lists_its_own_cells_as_audio() -> None: def test_a_refused_mac_1440p_cell_carries_the_window_a_run_would_use() -> None: - # Mac 1440p is an unmeasured cell, so Standard refuses it and Reckless can offer it. The - # refusal knows the windows that run would take, so a picker can say so. + # Mac 1440p past five windows is an unmeasured cell, so Cautious refuses it and Brave can + # offer it. The refusal knows the windows that run would take, so a picker can say so. assert _SPEC.supported_resolutions_durations is not None jf = _job_filter(memory_gb=96, process_mode="full_models_loading", **_mac_profile(pool_gib=48)) _kept, dropped, *_rest = _filter_local_fast_resolution_map( _SPEC.supported_resolutions_durations, _CAPS, job_filter=jf ) - cell = next(c for c in dropped if (c.resolution, c.fps, c.duration) == ("1440p", 24, 10)) + cell = next(c for c in dropped if (c.resolution, c.fps, c.duration) == ("1440p", 48, 20)) assert cell.reason == "unmeasured_cell" - assert (cell.windows, cell.window_frames) == (2, 129) + assert (cell.windows, cell.window_frames) == (9, 129) -def test_a_refusal_that_would_run_in_one_pass_carries_no_window() -> None: +def test_a_busy_card_refusal_carries_no_window() -> None: + """A shortfall that frees up keeps its one-pass refusal, so no window is promised.""" assert _SPEC.supported_resolutions_durations is not None _kept, dropped, *_rest = _filter_local_fast_resolution_map( - _SPEC.supported_resolutions_durations, _CAPS, job_filter=_windows_measured_filter(12, 64) + _SPEC.supported_resolutions_durations, _CAPS, job_filter=_windows_measured_filter(31.84, 64, free_gib=16) ) - single_pass = [c for c in dropped if c.resolution in ("540p", "720p", "1080p")] + single_pass = [c for c in dropped if c.resolution in ("540p", "720p", "1080p") and c.fps == 24 and c.duration <= 10] assert single_pass assert all(c.windows is None and c.window_frames is None for c in single_pass) diff --git a/backend/tests/test_fast_fallback_windows.py b/backend/tests/test_fast_fallback_windows.py index e945f687a..2103dc632 100644 --- a/backend/tests/test_fast_fallback_windows.py +++ b/backend/tests/test_fast_fallback_windows.py @@ -1,36 +1,70 @@ -"""Fast falls back to windows when one pass cannot fit a card a measured run covers.""" +"""Fast runs in windows when one pass cannot fit the machine, at any canvas.""" from __future__ import annotations +from dataclasses import replace from itertools import product import pytest import runtime_config.video_job_budget as budget -from runtime_config.fast_chunking import is_chunked_canvas, job_window_count, window_candidates +from runtime_config.budget_admission import Admission, Admitted, Refused, RiskAllowance +from runtime_config.budget_evidence import Extrapolated, Fitted +from runtime_config.device_calibration import DeviceCalibration, FrontierPoint, envelope_for +from runtime_config.fast_chunking import ( + CARRY_FRAMES, + MIN_WINDOW_FRAMES, + is_chunked_canvas, + job_window_count, + window_candidates, +) from runtime_config.measured_cells import ( MEASURED_WINDOWED_BELOW_1440P_CELLS, is_unmeasured_windowed_below_1440p, - window_fallback_measured, ) -from runtime_config.video_job_budget import VideoJobDecision, VideoJobLoad, VideoJobReject, decide_video_job +from runtime_config.video_job_budget import ( + NOMINAL_MPS_POOL_RATIO, + LocalJobFilter, + VideoJobDecision, + VideoJobLoad, + VideoJobReject, + decide_video_job, + price_video_job, + video_job_reject, +) from tests.test_video_job_budget import _job_filter, _mac_profile, _windows_measured_filter _1080P = (1920, 1088) _1080P_21_9 = (2560, 1088) _3_2 = (1632, 1088) # 1.78 Mpx: between 720p and 1080p, so no pixel band names it _720P = (1280, 704) -_540P = (960, 544) +_540P = (1024, 576) _1440P = (2560, 1472) _RTX_5090_GIB = 31.84 +_MAC_32_GB_POOL_GIB = 32 * NOMINAL_MPS_POOL_RATIO +_BRAVE = RiskAllowance.for_mode("brave") + + +def _admission( + size: tuple[int, int], + seconds: int, + job_filter: LocalJobFilter, + *, + fps: int = 24, + allowance: RiskAllowance | None = None, +) -> Admission: + return decide_video_job(*size, seconds * fps + 1, job_filter=job_filter, allowance=allowance) + + +def _decision(admission: Admission) -> VideoJobDecision: + return admission.load if isinstance(admission, Admitted) else video_job_reject(admission) def _decide( size: tuple[int, int], seconds: int, vram_gib: float, fps: int = 24, free_gib: float | None = None ) -> VideoJobDecision: - return decide_video_job( - *size, seconds * fps + 1, job_filter=_windows_measured_filter(vram_gib, 64, free_gib=free_gib) - ) + jf = _windows_measured_filter(vram_gib, 64, free_gib=free_gib) + return _decision(_admission(size, seconds, jf, fps=fps)) def _single_pass(size: tuple[int, int], seconds: int, vram_gib: float) -> VideoJobDecision: @@ -40,6 +74,10 @@ def _single_pass(size: tuple[int, int], seconds: int, vram_gib: float) -> VideoJ ) +def _mac_filter(pool_gib: float) -> LocalJobFilter: + return _job_filter(memory_gb=pool_gib * 2, process_mode="full_models_loading", **_mac_profile(pool_gib=pool_gib)) + + def test_1080p_20s_runs_in_three_windows_on_the_measured_card() -> None: decision = _decide(_1080P, 20, _RTX_5090_GIB) assert isinstance(decision, VideoJobLoad) @@ -57,12 +95,29 @@ def test_the_rule_names_no_canvas() -> None: assert not is_chunked_canvas(*_3_2) -@pytest.mark.parametrize("vram_gib", [12, 16, 24, 28]) -def test_a_card_below_the_measured_one_keeps_the_single_pass_refusal(vram_gib: float) -> None: - decision = _decide(_1080P, 20, vram_gib) - assert isinstance(decision, VideoJobReject) - assert decision.reason == "stream_over" - assert decision.chunk_pixel_frames is None +@pytest.mark.parametrize("vram_gib", [16, 24, 28]) +def test_a_card_below_the_measured_one_runs_its_windows_without_a_card_floor(vram_gib: float) -> None: + """The row is route-wide: a 16 GiB card's 6 windows of 105 frames are as covered as the 5090's 3.""" + admitted = _admission(_1080P, 20, _windows_measured_filter(vram_gib, 64)) + assert isinstance(admitted, Admitted) + assert admitted.load.chunk_pixel_frames is not None + assert isinstance(admitted.priced.evidence, Fitted) + + +def test_a_card_whose_windows_are_shorter_runs_more_of_them_and_passes_the_row() -> None: + """A 12 GiB card windows 1080p 20 s at 57 frames: 12 windows, past the row's 9.""" + jf = _windows_measured_filter(12, 64) + refused = _admission(_1080P, 20, jf) + assert isinstance(refused, Refused) + assert refused.reject.unmeasured_basis == "windowed_range" + window = refused.reject.chunk_pixel_frames + assert window is not None + assert job_window_count(20 * 24 + 1, window) > MEASURED_WINDOWED_BELOW_1440P_CELLS[("fast", "windows_measured")].max_windows + + admitted = _admission(_1080P, 20, jf, allowance=_BRAVE) + assert isinstance(admitted, Admitted) + assert admitted.load.chunk_pixel_frames == window + assert isinstance(admitted.priced.evidence, Extrapolated) @pytest.mark.parametrize("free_gib", [22.0, 20.0, 16.0]) # one pass of 1080p 10 s asks 22.7 GiB @@ -75,40 +130,163 @@ def test_a_busy_card_keeps_the_single_pass_refusal(free_gib: float) -> None: assert decision.chunk_pixel_frames is None -def test_a_job_past_the_measured_window_count_is_unmeasured() -> None: - # 961 frames (20 s at 48 fps) is 5 windows of 241; the run covered 3. - decision = _decide(_1080P, 20, _RTX_5090_GIB, fps=48) +def test_a_job_inside_the_measured_window_count_is_fitted_not_pinned_to_three_windows() -> None: + """20 s at 48 fps is 5 windows of 241. A row that stayed at the 1080p run's 3 would refuse it.""" + jf = _windows_measured_filter(_RTX_5090_GIB, 64) + admitted = _admission(_1080P, 20, jf, fps=48) + assert isinstance(admitted, Admitted) + assert job_window_count(20 * 48 + 1, admitted.load.chunk_pixel_frames) == 5 + assert isinstance(admitted.priced.evidence, Fitted) + + +def test_a_20_second_540p_48_fps_clip_is_one_pass_only_where_the_mode_takes_the_bet() -> None: + """69.7k tokens is past the 63,240-token fit. Brave runs the one pass with an untested note, + and Cautious windows it at the ceiling (2 windows) instead of refusing.""" + jf = _windows_measured_filter(_RTX_5090_GIB, 64) + brave = _admission(_540P, 20, jf, fps=48, allowance=_BRAVE) + assert isinstance(brave, Admitted) + assert brave.load.chunk_pixel_frames is None + assert isinstance(brave.priced.evidence, Extrapolated) + assert brave.priced.evidence.basis == "pass_tokens" + + cautious = _admission(_540P, 20, jf, fps=48) + assert isinstance(cautious, Admitted) + assert cautious.load.chunk_pixel_frames == window_candidates(*_540P)[0] + assert job_window_count(20 * 48 + 1, cautious.load.chunk_pixel_frames) == 2 + assert isinstance(cautious.priced.evidence, Fitted) + + +def test_a_clean_brave_one_pass_run_opens_that_pass_in_cautious_on_this_card() -> None: + """The device frontier is what proves a pass past the fit: after one clean run, Cautious runs it.""" + jf = _windows_measured_filter(_RTX_5090_GIB, 64) + ran = price_video_job(*_540P, 20 * 48 + 1, job_filter=jf, allowance=_BRAVE) + assert ran.chunk_pixel_frames is None + envelope = envelope_for(ran.shape, ran.decision.mode, ran.stream_gib) + proven = replace( + jf, + calibration=DeviceCalibration( + identity=None, + frontier={envelope.bucket: (FrontierPoint(point=envelope.point, peak_growth_bytes=20 * 1024**3),)}, + ), + ) + + admitted = _admission(_540P, 20, proven, fps=48) + assert isinstance(admitted, Admitted) + assert admitted.load.chunk_pixel_frames is None + assert admitted.priced.covered + + longer = _admission(_540P, 20, proven, fps=50) + assert isinstance(longer, Admitted) + assert longer.load.chunk_pixel_frames == window_candidates(*_540P)[0] + + +def test_a_one_pass_job_inside_the_fit_stays_fitted_and_one_pass() -> None: + """1080p 10 s is 63,240 tokens, the fit's own point: no note, no windows, in any mode.""" + jf = _windows_measured_filter(_RTX_5090_GIB, 64) + admitted = _admission(_1080P, 10, jf) + assert isinstance(admitted, Admitted) + assert admitted.load.chunk_pixel_frames is None + assert isinstance(admitted.priced.evidence, Fitted) + + +def test_the_window_count_does_not_raise_the_ask_past_the_plateau() -> None: + """20 s at 48 fps runs 5 windows against 3 at 24 fps, and asks the same: the window is priced, not the clip.""" + jf = _windows_measured_filter(_RTX_5090_GIB, 64) + three = _decision(_admission(_1080P, 20, jf)) + five = _decision(_admission(_1080P, 20, jf, fps=48)) + assert job_window_count(20 * 24 + 1, three.chunk_pixel_frames) == 3 + assert job_window_count(20 * 48 + 1, five.chunk_pixel_frames) == 5 + assert three.stream_gib == five.stream_gib + assert three.chunk_pixel_frames == five.chunk_pixel_frames + + +def test_a_card_no_window_fits_refuses_with_the_shortest_window_not_the_whole_clip() -> None: + """A Brave downgrade runs this window, so it must be the smallest ask and not one whole-clip pass.""" + decision = _decide(_540P, 20, 6.0) assert isinstance(decision, VideoJobReject) - assert decision.reason == "unmeasured_cell" - assert decision.chunk_pixel_frames == 241 + assert decision.reason == "stream_over" + assert decision.chunk_pixel_frames == MIN_WINDOW_FRAMES + assert decision.stream_gib < _single_pass(_540P, 20, 6.0).stream_gib + + +@pytest.mark.parametrize("pool_gib", [16, 32, 64, 96]) +def test_mac_runs_a_1080p_48_fps_clip_in_windows_past_the_sequence_fence(pool_gib: float) -> None: + """246k tokens are far past the 116k-token MPS fence in one pass, and every window sits under it.""" + jf = _mac_filter(pool_gib) + one_pass = budget._decide_fast_pass( # pyright: ignore[reportPrivateUsage] + *_1080P, 20 * 48 + 1, windows=1, job_filter=jf + ) + assert isinstance(one_pass, VideoJobReject) and one_pass.reason == "mps_sequence_over" + + admitted = _admission(_1080P, 20, jf, fps=48, allowance=_BRAVE) + assert isinstance(admitted, Admitted) + assert admitted.load.chunk_pixel_frames is not None + cautious = _admission(_1080P, 20, jf, fps=48) + windows = job_window_count(20 * 48 + 1, admitted.load.chunk_pixel_frames) + if windows <= MEASURED_WINDOWED_BELOW_1440P_CELLS[("fast", "mac_measured")].max_windows: + assert isinstance(cautious, Admitted) and isinstance(cautious.priced.evidence, Fitted) + else: + assert isinstance(cautious, Refused) and cautious.reject.reason == "unmeasured_cell" -def test_the_measured_cover_is_a_row_not_the_code() -> None: - assert MEASURED_WINDOWED_BELOW_1440P_CELLS[("fast", "windows_measured")] == (3, 30.0) - assert window_fallback_measured("fast", "windows_measured", _RTX_5090_GIB) - assert not window_fallback_measured("fast", "windows_measured", 24.0) - assert not window_fallback_measured("fast", "windows_measured", None) - assert not window_fallback_measured("fast", "mac_measured", 64.0) - assert not window_fallback_measured("edit", "windows_measured", _RTX_5090_GIB) +@pytest.mark.parametrize(("pool_gib", "seconds"), [(16, 10), (32, 20)]) # asks 24.7 and 49 GiB in one pass +def test_mac_windows_a_job_whose_ask_is_over_the_pool(pool_gib: float, seconds: int) -> None: + admission = _admission(_1080P, seconds, _mac_filter(pool_gib), allowance=_BRAVE) + assert isinstance(admission, Admitted) + assert admission.load.chunk_pixel_frames is not None -def test_one_pass_and_high_res_are_never_unmeasured_here() -> None: - assert not is_unmeasured_windowed_below_1440p("fast", "mac_measured", *_1080P, windows=1) - assert is_unmeasured_windowed_below_1440p("fast", "mac_measured", *_1080P, windows=2) - assert not is_unmeasured_windowed_below_1440p("fast", "windows_measured", *_720P, windows=3) - assert is_unmeasured_windowed_below_1440p("fast", "windows_measured", *_720P, windows=4) - # 1440p and 4K have their own rows (is_unmeasured_high_res). - assert is_chunked_canvas(*_1440P) - assert not is_unmeasured_windowed_below_1440p("fast", "windows_measured", *_1440P, windows=9) +def test_mac_parts_smaller_than_the_measured_runs_are_offered_in_cautious() -> None: + """A 32 GB Mac steps 1080p 20 s down to parts shorter than the longest 1080p part, the size + the Mac runs used. A floor at the measured part size stops that Mac at 10 s of 1080p.""" + admitted = _admission(_1080P, 20, _mac_filter(_MAC_32_GB_POOL_GIB)) + assert isinstance(admitted, Admitted) + assert admitted.load.chunk_pixel_frames is not None + assert admitted.load.chunk_pixel_frames < window_candidates(*_1080P)[0] + assert isinstance(admitted.priced.evidence, Fitted) -@pytest.mark.parametrize("pool_gib", [16, 32, 48, 96]) -def test_mac_keeps_every_single_pass_refusal(pool_gib: float) -> None: - """Mac has no row, so no window is tried below 1440p: its refusals stay single-pass.""" - jf = _job_filter(memory_gb=pool_gib * 2, process_mode="full_models_loading", **_mac_profile(pool_gib=pool_gib)) - for size, seconds in product((_540P, _720P, _1080P, _1080P_21_9), (10, 20)): - decision = decide_video_job(*size, seconds * 24 + 1, job_filter=jf) - assert decision.chunk_pixel_frames is None, (size, seconds) + +def test_mac_jobs_past_five_parts_are_still_withheld_in_cautious() -> None: + """The same part on the same Mac: five of them run, and one more is past the longest Mac run.""" + jf = _mac_filter(_MAC_32_GB_POOL_GIB) + window = _decision(_admission(_1080P, 20, jf)).chunk_pixel_frames + assert window is not None + five_frames = window + 4 * (window - CARRY_FRAMES) + six_frames = five_frames + 8 + five = decide_video_job(*_1080P, five_frames, job_filter=jf) + assert isinstance(five, Admitted) + assert five.load.chunk_pixel_frames == window + assert job_window_count(five_frames, window) == 5 + + six = decide_video_job(*_1080P, six_frames, job_filter=jf) + assert isinstance(six, Refused) + assert six.reject.unmeasured_basis == "windowed_range" + assert six.reject.chunk_pixel_frames == window + assert job_window_count(six_frames, window) == 6 + + brave = decide_video_job(*_1080P, six_frames, job_filter=jf, allowance=_BRAVE) + assert isinstance(brave, Admitted) + assert isinstance(brave.priced.evidence, Extrapolated) + + +def test_the_unmeasured_window_cover_follows_the_route_row() -> None: + windows_cover = MEASURED_WINDOWED_BELOW_1440P_CELLS[("fast", "windows_measured")] + assert windows_cover.max_windows == 9 + kwargs = {"window_tokens": 20_000.0} + assert not is_unmeasured_windowed_below_1440p("fast", "windows_measured", *_720P, windows=9, **kwargs) + assert is_unmeasured_windowed_below_1440p("fast", "windows_measured", *_720P, windows=10, **kwargs) + mac_cover = MEASURED_WINDOWED_BELOW_1440P_CELLS[("fast", "mac_measured")] + assert not is_unmeasured_windowed_below_1440p( + "fast", "mac_measured", *_1080P, windows=mac_cover.max_windows, window_tokens=63_240.0 + ) + assert is_unmeasured_windowed_below_1440p( + "fast", "mac_measured", *_1080P, windows=mac_cover.max_windows + 1, window_tokens=63_240.0 + ) + # One pass prices on the fitted rows, and 1440p and 4K have their own rows. + assert not is_unmeasured_windowed_below_1440p("fast", "mac_measured", *_1080P, windows=1, **kwargs) + assert not is_unmeasured_windowed_below_1440p("fast", "windows_measured", *_1440P, windows=9, **kwargs) + assert is_unmeasured_windowed_below_1440p("fast", "legacy", *_1080P, windows=2, **kwargs) def test_no_job_that_loads_or_is_refused_for_another_reason_changes(monkeypatch: pytest.MonkeyPatch) -> None: @@ -121,7 +299,7 @@ def run() -> dict[tuple, VideoJobDecision]: return {c: _decide(c[0], c[1], c[3][0], fps=c[2], free_gib=c[3][1]) for c in cases} after = run() - monkeypatch.setattr(budget, "window_fallback_measured", lambda *_a, **_k: False) + monkeypatch.setattr(budget, "_windows_help", lambda *_a, **_k: False) before = run() changed = [c for c in cases if before[c] != after[c]] @@ -132,9 +310,16 @@ def run() -> dict[tuple, VideoJobDecision]: assert isinstance(was, VideoJobReject), c assert was.reason == "stream_over", c assert was.stream_gib > total, c # no empty card of this size runs it in one pass - assert total >= 30.0, c assert not is_chunked_canvas(*c[0]), c - if isinstance(now, VideoJobLoad): - assert now.chunk_pixel_frames is not None, c - else: - assert now.reason == "unmeasured_cell", c # past the windows the run covered + assert now.chunk_pixel_frames is not None, c + if isinstance(now, VideoJobReject): + assert now.reason in {"unmeasured_cell", "stream_over"}, c + + +def test_a_refused_job_for_ram_keeps_its_refusal_instead_of_windowing() -> None: + """A window does not shorten the pinned-RAM floor, so the RAM refusal stands.""" + jf = _windows_measured_filter(_RTX_5090_GIB, 8) + decision = _decision(_admission(_540P, 20, jf)) + assert isinstance(decision, VideoJobReject) + assert decision.reason == "ram_shortfall" + assert decision.chunk_pixel_frames is None diff --git a/backend/tests/test_feature_flags.py b/backend/tests/test_feature_flags.py index da7a05762..02285e294 100644 --- a/backend/tests/test_feature_flags.py +++ b/backend/tests/test_feature_flags.py @@ -9,7 +9,14 @@ from api_types import FeatureFlags, FeatureFlagsPatch from remote.app import create_remote_app -DEFAULTS = {"customIcLora": False, "advancedIcLoraControls": False, "highResVideoToVideo": False} +DEFAULTS = { + "customIcLora": False, + "advancedIcLoraControls": False, + "highResVideoToVideo": False, + "createWithAi": False, + "showGenerationNegativePrompt": False, + "keyframes": False, +} AUTH = {"Authorization": "Bearer pair-token"} diff --git a/backend/tests/test_generation.py b/backend/tests/test_generation.py index e19f0dc9e..cc4e8a9ad 100644 --- a/backend/tests/test_generation.py +++ b/backend/tests/test_generation.py @@ -19,11 +19,15 @@ GenerateVideoRequest, ) from frame_math import AutoDurationSpec, compute_num_frames +from runtime_config.budget_admission import unmeasured_refusal_message +from runtime_config.budget_evidence import JobShape +from runtime_config.device_calibration import envelope_for from runtime_config.eta import WallTimeEstimate from runtime_config.model_download_specs import delete_cp_path, get_ltx_model_spec, resolve_model_path from services import generation_interrupt from services.generation_interrupt import GenerationCancelledError from services.ltx_api_client.ltx_api_client import LTXAPIClientError +from services.generation_queue.sessions import LocalJobSession from state.app_state_types import GpuSlot, VideoPipelineState from tests.http_error_assertions import assert_http_error from tests.fakes.services import FakeFastVideoPipeline @@ -100,7 +104,7 @@ def _local_cell(fps_to_durations: dict[str, list[int]]) -> dict[str, object]: return {"fps_to_durations": fps_to_durations, "aspect_ratios": list(_LOCAL_CELL_ASPECTS)} -def _fake_running_generation_state(test_state) -> None: +def _fake_gpu_slot(test_state) -> None: pipeline = FakeFastVideoPipeline() test_state.state.gpu_slot = GpuSlot( active_pipeline=VideoPipelineState( @@ -110,6 +114,10 @@ def _fake_running_generation_state(test_state) -> None: loading_mode="full_models_loading", ), ) + + +def _fake_running_generation_state(test_state) -> None: + _fake_gpu_slot(test_state) test_state.generation.start_generation("running") @@ -455,7 +463,7 @@ def test_t2v_auto_duration_fully_dropped_cell_422s_enriched_instead_of_500( status_code=422, code=VIDEO_JOB_TOO_LARGE, message=( - "This job needs 77.0 GB of GPU memory but this card has 8.0 GB. " + "This job needs 11.2 GB of GPU memory but this card has 8.0 GB. " "Lower the resolution, duration, frame rate, or aspect width." ), ) @@ -890,7 +898,7 @@ def test_resolution_mapping_720p(self, client, test_state, fake_services, create assert call["width"] == 1280 assert call["height"] == 704 - def test_local_1440p_is_refused_as_unmeasured_until_reckless( + def test_local_1440p_is_refused_as_unmeasured_until_brave( self, client, test_state, fake_services, create_fake_model_files ): create_fake_model_files() @@ -903,7 +911,7 @@ def test_local_1440p_is_refused_as_unmeasured_until_reckless( assert refused.json()["code"] == VIDEO_JOB_TOO_LARGE assert fake_services.fast_video_pipeline.generate_calls == [] - test_state.state.app_settings.budget_mode = "reckless" + test_state.state.app_settings.budget_mode = "brave" accepted = client.post("/api/generate", json=body) assert accepted.status_code == 200 @@ -2762,10 +2770,7 @@ def test_job_too_large_returns_422(self, client, test_state, create_fake_model_f r, status_code=422, code=VIDEO_JOB_TOO_LARGE, - message=( - "This job needs 20.0 GB of GPU memory but this card has 8.0 GB. " - "Lower the resolution, duration, frame rate, or aspect width." - ), + message=unmeasured_refusal_message("windowed_range"), ) def test_360p_20s_on_8gb_budgets_the_half_canvas( @@ -2806,10 +2811,7 @@ def test_16gb_540p_20s_21_9_returns_422_while_16_9_runs( wide, status_code=422, code=VIDEO_JOB_TOO_LARGE, - message=( - "This job needs 17.6 GB of GPU memory but this card has 16.0 GB. " - "Lower the resolution, duration, frame rate, or aspect width." - ), + message=unmeasured_refusal_message("windowed_range"), ) assert fake_services.fast_video_pipeline.generate_calls == [] @@ -2833,10 +2835,7 @@ def test_16gb_720p_20s_returns_422(self, client, test_state, create_fake_model_f r, status_code=422, code=VIDEO_JOB_TOO_LARGE, - message=( - "This job needs 20.0 GB of GPU memory but this card has 16.0 GB. " - "Lower the resolution, duration, frame rate, or aspect width." - ), + message=unmeasured_refusal_message("windowed_range"), ) def test_job_too_large_does_not_run_local_enhance( @@ -2862,10 +2861,7 @@ def spy(*args, **kwargs): r, status_code=422, code=VIDEO_JOB_TOO_LARGE, - message=( - "This job needs 20.0 GB of GPU memory but this card has 16.0 GB. " - "Lower the resolution, duration, frame rate, or aspect width." - ), + message=unmeasured_refusal_message("windowed_range"), ) assert calls["n"] == 0 @@ -2899,10 +2895,7 @@ def spy(*args, **kwargs): r, status_code=422, code=VIDEO_JOB_TOO_LARGE, - message=( - "This job needs 20.0 GB of GPU memory but this card has 16.0 GB. " - "Lower the resolution, duration, frame rate, or aspect width." - ), + message=unmeasured_refusal_message("windowed_range"), ) assert calls["n"] == 0 @@ -3094,13 +3087,37 @@ def test_response_modes_derive_offload_from_routing(test_state) -> None: test_state.config.checkpoint_drive_type = "nvme" assert handler._load_offload_for_response("streaming_models_loading") == ( "streaming_models_loading", - "DISK", + "CPU", + ) + assert ( + handler._offload_mode( + "streaming_models_loading", cpu_ram_floor_gb=None + ).name + == "DISK" ) assert handler._load_offload_for_response("full_models_loading") == ( "full_models_loading", "NONE", ) + test_state.config.total_ram_bytes = 48 * 1024**3 + assert ( + handler._offload_mode( + "streaming_models_loading", cpu_ram_floor_gb=64 + ).name + == "DISK" + ) + assert handler._load_offload_for_response("streaming_models_loading") == ( + "streaming_models_loading", + "CPU", + ) + + test_state.config.total_ram_bytes = 32 * 1024**3 + assert handler._load_offload_for_response("streaming_models_loading") == ( + "streaming_models_loading", + "DISK", + ) + test_state.config.checkpoint_drive_type = "ssd" assert handler._load_offload_for_response("streaming_models_loading") == ( "streaming_models_loading", @@ -3117,12 +3134,20 @@ def _estimate_config(test_state, gpu_device_name: str | None) -> None: def test_estimate_wall_time_uses_routed_offload_on_measured_class(test_state) -> None: - """540p/5s streamed on a 5090 NVMe box: DISK-routed, measured ratio.""" + """540p/5s streamed on a 5090 NVMe box: CPU at 64 GB, DISK fallback at 32 GB.""" _estimate_config(test_state, "NVIDIA GeForce RTX 5090") est = test_state.video_generation._estimate_wall_time( 1024, 576, compute_num_frames(5, 24), "streaming_models_loading", "t2v" ) - assert est == WallTimeEstimate(seconds=round(158 * 0.87), basis="measured", t2v_reuse=False) + assert est == WallTimeEstimate(seconds=158, basis="measured", t2v_reuse=False) + + test_state.config.total_ram_bytes = 32 * 1024**3 + disk_est = test_state.video_generation._estimate_wall_time( + 1024, 576, compute_num_frames(5, 24), "streaming_models_loading", "t2v" + ) + assert disk_est == WallTimeEstimate( + seconds=round(158 * 1.07), basis="scaled", t2v_reuse=False + ) def test_estimate_wall_time_flags_i2v_reuse(test_state) -> None: @@ -3131,7 +3156,7 @@ def test_estimate_wall_time_flags_i2v_reuse(test_state) -> None: 1024, 576, compute_num_frames(5, 24), "streaming_models_loading", "i2v" ) assert est is not None - assert est.seconds == round(158 * 0.87) + assert est.seconds == 158 assert est.t2v_reuse is True @@ -3145,14 +3170,14 @@ def test_estimate_wall_time_none_off_measured_class(test_state) -> None: ) -def test_estimate_wall_time_none_for_unlisted_cell(test_state) -> None: +def test_estimate_wall_time_scaled_for_unlisted_cell(test_state) -> None: _estimate_config(test_state, "NVIDIA GeForce RTX 5090") - assert ( - test_state.video_generation._estimate_wall_time( - 1280, 704, compute_num_frames(10, 24), "streaming_models_loading", "t2v" - ) - is None + est = test_state.video_generation._estimate_wall_time( + 1280, 704, compute_num_frames(10, 24), "streaming_models_loading", "t2v" ) + assert est is not None + assert est.basis == "scaled" + assert est.load_s + est.denoise_s + est.decode_s == est.seconds class TestGenerateModelSpecs: @@ -3277,6 +3302,7 @@ def test_local_fast_24gb_keeps_1080p_10s(self, client, test_state): assert local_t2v["1080p"]["fps_to_durations"]["24"] == [2, 3, 4, 5, 6, 8, 10] assert local_t2v["720p"]["fps_to_durations"]["24"] == [2, 3, 4, 5, 6, 8, 10, 20] + @pytest.mark.usefixtures("single_pass_only") def test_windows_16gb_48_specs_use_limited_fast_envelope( self, client, test_state, create_fake_model_files ): @@ -3300,6 +3326,7 @@ def test_windows_16gb_48_specs_use_limited_fast_envelope( "1080p": _local_cell({"24": [5, 6], "25": [5, 6]}), } + @pytest.mark.usefixtures("single_pass_only") def test_windows_16gb_48_specs_dropped_cells_name_stream_over( self, client, test_state, create_fake_model_files ): @@ -3334,6 +3361,7 @@ def test_windows_16gb_48_specs_dropped_cells_name_stream_over( assert a2v_cell["over_ram_gb"] is None assert a2v_cell["shortfall_kind"] == "total" + @pytest.mark.usefixtures("single_pass_only") def test_windows_16gb_specs_aspect_rows_name_21_9_where_anchor_kept( self, client, test_state, create_fake_model_files ): @@ -3364,6 +3392,7 @@ def test_windows_16gb_specs_aspect_rows_name_21_9_where_anchor_kept( "need_gb": pytest.approx(17.2, abs=0.05), "have_gb": 16.0, }, + "unmeasured_basis": None, } in aspect_dropped def test_windows_16gb_specs_aspect_rows_never_cover_anchor_or_dropped_cells( @@ -3416,6 +3445,7 @@ def test_windows_31gb_32_specs_dropped_cells_name_ram_shortfall_per_cell( "over_ram_gb": 8, "shortfall_kind": None, "readout": {"kind": "ram", "need_gb": 40.0, "have_gb": 32.0}, + "unmeasured_basis": None, "windows": None, "window_frames": None, } in dropped @@ -3467,6 +3497,7 @@ def test_windows_16gb_32_specs_payload_is_empty_with_ram_reason( assert local_spec["supported_resolutions_durations"] == {} assert local_spec["a2v_supported_resolutions_durations"] == {} + @pytest.mark.usefixtures("single_pass_only") def test_windows_16gb_32_nvme_specs_offer_streamed_cells( self, client, test_state, create_fake_model_files ): @@ -3486,12 +3517,12 @@ def test_windows_16gb_32_nvme_specs_offer_streamed_cells( assert local_t2v["720p"]["fps_to_durations"]["24"] == [2, 3, 4, 5, 6, 8, 10] assert local_t2v["1080p"]["fps_to_durations"]["24"] == [2, 3, 4, 5, 6] - def test_windows_16gb_24_nvme_specs_shortfall_reports_32_floor( + def test_windows_16gb_16_nvme_specs_shortfall_reports_24_floor( self, client, test_state, create_fake_model_files ): - """DISK path still short: the reported floor is the mapped one (32, not 40).""" + """DISK path still short: the reported floor is the NVMe disk one (24, not 40).""" create_fake_model_files() - _configure_windows_fast(test_state, vram_gib=16, total_ram_gib=24) + _configure_windows_fast(test_state, vram_gib=16, total_ram_gib=16) test_state.config.checkpoint_drive_type = "nvme" r = client.get("/api/generate/models-specs") @@ -3499,8 +3530,8 @@ def test_windows_16gb_24_nvme_specs_shortfall_reports_32_floor( assert r.status_code == 200 data = r.json() assert data["local_unavailable_reason"] == "ram_shortfall" - assert data["local_unavailable_required_ram_gb"] == 32 - assert data["local_unavailable_detected_ram_gb"] == 24 + assert data["local_unavailable_required_ram_gb"] == 24 + assert data["local_unavailable_detected_ram_gb"] == 16 assert data["local_models"][0]["spec"]["supported_resolutions_durations"] == {} def test_windows_unknown_ram_specs_payload_has_no_reason( @@ -3520,6 +3551,7 @@ def test_windows_unknown_ram_specs_payload_has_no_reason( local_spec = data["local_models"][0]["spec"] assert local_spec["supported_resolutions_durations"] == {} + @pytest.mark.usefixtures("single_pass_only") def test_windows_16gb_40_specs_payload_has_cells_and_no_reason( self, client, test_state, create_fake_model_files ): @@ -3536,6 +3568,7 @@ def test_windows_16gb_40_specs_payload_has_cells_and_no_reason( assert local_t2v["720p"]["fps_to_durations"]["24"] == [2, 3, 4, 5, 6, 8, 10] assert local_t2v["1080p"]["fps_to_durations"]["24"] == [2, 3, 4, 5, 6] + @pytest.mark.usefixtures("single_pass_only") def test_windows_specs_show_total_cells_despite_depressed_free( self, client, test_state, fake_services, create_fake_model_files ): @@ -3583,6 +3616,7 @@ def test_windows_specs_reason_absent_when_grid_empty_from_total_vram( assert data["local_unavailable_required_ram_gb"] is None assert data["local_unavailable_detected_ram_gb"] is None + @pytest.mark.usefixtures("single_pass_only") def test_windows_12gb_48_specs_use_limited_fast_envelope( self, client, test_state, create_fake_model_files ): @@ -3605,6 +3639,7 @@ def test_windows_12gb_48_specs_use_limited_fast_envelope( "720p": _local_cell({"24": [5, 6, 8], "25": [5, 6, 8]}), } + @pytest.mark.usefixtures("single_pass_only") def test_windows_unknown_vram_bytes_specs_fall_back_to_integer( self, client, test_state, create_fake_model_files ): @@ -3623,6 +3658,7 @@ def test_windows_unknown_vram_bytes_specs_fall_back_to_integer( assert local_t2v["720p"]["fps_to_durations"]["24"] == [2, 3, 4, 5, 6, 8, 10] assert local_t2v["1080p"]["fps_to_durations"]["24"] == [2, 3, 4, 5, 6] + @pytest.mark.usefixtures("single_pass_only") def test_windows_24gb_48_specs_use_complete_fast_envelope( self, client, test_state, create_fake_model_files ): @@ -3652,33 +3688,31 @@ def test_local_fast_unsupported_is_empty(self, client, test_state): assert spec["supported_resolutions_durations"] == {} assert spec["a2v_supported_resolutions_durations"] == {} - def test_local_fast_1080p_20s_refused_with_copy_when_over_budget(self, client): + def test_local_fast_1080p_20s_listed_as_untested_windows_when_one_pass_cannot_fit(self, client): local_spec = client.get("/api/generate/models-specs").json()["local_models"][0]["spec"] local_t2v = local_spec["supported_resolutions_durations"] assert 20 not in local_t2v["1080p"]["fps_to_durations"]["24"] - # Over budget is refused with its measured copy, never silently absent. + # A clip that needs windows on an untested card is refused with its + # windows and shortest-window figure, never silently absent. for audio in (False, True): assert { "resolution": "1080p", "fps": 24, "duration": 20, - "reason": "stream_over", - "message": ( - "This job needs 42.3 GB of GPU memory but this card has 31.0 GB. " - "Lower the resolution, duration, frame rate, or aspect width." - ), + "reason": "unmeasured_cell", + "message": unmeasured_refusal_message("windowed_range"), "audio": audio, "over_gib": None, "over_ram_gb": None, - "shortfall_kind": "total", + "shortfall_kind": None, "readout": { - "kind": "gpu", - "need_gb": pytest.approx(42.3, abs=0.05), - "have_gb": 31.0, + "kind": "untested", + "need_gb": pytest.approx(23.02, abs=0.05), + "have_gb": None, }, - # This profile is not a measured Windows card, so no window is offered instead. - "windows": None, - "window_frames": None, + "unmeasured_basis": "windowed_range", + "windows": 3, + "window_frames": 241, } in local_spec["dropped_cells"] def test_local_auto_duration_requires_duration_head_on_disk(self, client, create_fake_model_files): @@ -3769,7 +3803,7 @@ def test_16gb_cell_over_free_vram_is_too_large( code=VIDEO_JOB_TOO_LARGE, message=( "This job needs 20.0 GB of GPU memory but only 19.0 GB is free " - "right now (of 24.0 GB total). Close other GPU apps and retry." + "right now (of 24.0 GB total). Close other heavy apps (like games, browsers, or video editors) and retry." ), ) @@ -3807,12 +3841,12 @@ def test_generate_derives_pipeline_offload_from_checkpoint_drive( fake_services, create_fake_model_files, ): - """NVMe on Windows CUDA must stream weights from disk, not pin them in RAM.""" + """Windows NVMe falls back to DISK at 32 GB RAM and uses CPU at 48 GB RAM.""" from ltx_pipelines.utils.types import OffloadMode create_fake_model_files() _enable_local_text_encoding(test_state) - _configure_windows_fast(test_state, vram_gib=16, total_ram_gib=48) + _configure_windows_fast(test_state, vram_gib=16, total_ram_gib=32) test_state.config.device = torch.device("cuda") test_state.config.checkpoint_drive_type = "nvme" @@ -3824,6 +3858,43 @@ def test_generate_derives_pipeline_offload_from_checkpoint_drive( assert r.status_code == 200 assert fake_services.fast_video_pipeline.last_offload_mode == OffloadMode.DISK + test_state.state.gpu_slot = None + _configure_windows_fast(test_state, vram_gib=16, total_ram_gib=48) + test_state.config.device = torch.device("cuda") + test_state.config.checkpoint_drive_type = "nvme" + + r = client.post( + "/api/generate", + json={**_T2V_JSON, "resolution": "540p", "duration": 5}, + ) + + assert r.status_code == 200 + assert fake_services.fast_video_pipeline.last_offload_mode == OffloadMode.CPU + + test_state.state.gpu_slot = None + test_state.pipelines.load_ic_lora( + "fake.safetensors", mode="streaming_models_loading" + ) + assert fake_services.ic_lora_pipeline.last_offload_mode == OffloadMode.DISK + + test_state.state.gpu_slot = None + _configure_windows_fast(test_state, vram_gib=16, total_ram_gib=63.45) + test_state.config.device = torch.device("cuda") + test_state.config.checkpoint_drive_type = "nvme" + test_state.pipelines.load_ic_lora( + "fake.safetensors", mode="streaming_models_loading" + ) + assert fake_services.ic_lora_pipeline.last_offload_mode == OffloadMode.CPU + + test_state.state.gpu_slot = None + test_state.pipelines.load_retake_pipeline( + width=1024, height=576, frames=121 + ) + assert ( + fake_services.retake_pipeline.create_calls[-1]["offload_mode"] + == OffloadMode.DISK + ) + def test_streaming_complete_reports_streaming_and_cpu( self, client, @@ -3869,6 +3940,7 @@ def test_full_complete_reports_full_and_none( assert data["load_mode"] == "full_models_loading" assert data["offload_mode"] == "NONE" + @pytest.mark.usefixtures("single_pass_only") def test_16gb_48_oversize_1080p10_is_too_large( self, client, @@ -4072,6 +4144,92 @@ def test_running_reports_estimate_fixed_at_start(self, client, test_state): "t2vReuse": False, } + def test_running_reports_remaining_seconds_from_the_estimate(self, client, test_state): + _fake_gpu_slot(test_state) + test_state.generation.start_generation( + "running", + estimated=WallTimeEstimate( + seconds=200, + basis="scaled", + t2v_reuse=False, + load_s=20, + denoise_s=160, + decode_s=20, + ), + ) + test_state.generation.update_progress("inference", 50, 4, 8) + + data = client.get("/api/generation/progress").json() + + assert 0 < data["remainingSeconds"] < 200 + + def test_running_without_an_estimate_reports_no_remaining_seconds(self, client, test_state): + _fake_running_generation_state(test_state) + test_state.generation.update_progress("inference", 50, 4, 8) + + data = client.get("/api/generation/progress").json() + + assert data.get("remainingSeconds") is None + + def test_decode_clock_starts_on_the_last_step_and_resets_on_an_earlier_one(self, test_state): + _fake_running_generation_state(test_state) + + def decode_started() -> float | None: + running = test_state.state.active_generation.state + return running.decode_started_monotonic + + test_state.generation.update_progress("inference", 40, 3, 8) + assert decode_started() is None + test_state.generation.update_progress("inference", 95, 8, 8) + started = decode_started() + assert started is not None + # The last step again keeps the first stamp. + test_state.generation.update_progress("inference", 95, 8, 8) + assert decode_started() == started + test_state.generation.update_progress("inference", 40, 3, 8) + assert decode_started() is None + + def test_start_from_a_priced_envelope_derives_the_estimate(self, client, test_state): + _configure_5090_windows_fast(test_state) + _fake_gpu_slot(test_state) + ran = envelope_for( + JobShape( + feature="fast", + model_id="ltx-2.5-22b-distilled", + adapter_id="", + stage_mode="", + tiled=False, + chunked=False, + seq=9216.0, + canvas_px=1024 * 576, + windows=1, + ), + "streaming_models_loading", + 14.0, + ) + + test_state.generation.start_generation("running", ran=ran) + + estimate = client.get("/api/generation/progress").json()["estimate"] + assert estimate["basis"] == "scaled" + assert estimate["seconds"] > 0 + + def test_local_job_session_reports_remaining_seconds_only_for_its_own_job(self, test_state): + _fake_gpu_slot(test_state) + test_state.generation.start_generation( + "running", + estimated=WallTimeEstimate( + seconds=200, basis="scaled", t2v_reuse=False, load_s=20, denoise_s=160, decode_s=20 + ), + ) + test_state.generation.update_progress("inference", 50, 4, 8) + + own = LocalJobSession(test_state.generation, "running").progress() + other = LocalJobSession(test_state.generation, "someone-else").progress() + + assert own is not None and own.remaining_seconds is not None + assert other is None + def test_running_reports_no_estimate_by_default(self, client, test_state): _fake_running_generation_state(test_state) @@ -4103,7 +4261,19 @@ def test_measured_cell_returns_table_estimate(self, client, test_state): ) assert r.status_code == 200 assert r.json()["estimate"] == { - "seconds": round(158 * 0.87), + "seconds": 158, + "basis": "measured", + "t2vReuse": False, + } + + test_state.config.total_ram_bytes = 32 * 1024**3 + r_disk = client.post( + "/api/generate/estimate", + json={"resolution": "720p", "duration": 20, "fps": 24, "feature": "t2v"}, + ) + assert r_disk.status_code == 200 + assert r_disk.json()["estimate"] == { + "seconds": round(280 * 1.06), "basis": "measured", "t2vReuse": False, } @@ -4139,10 +4309,10 @@ def test_i2v_and_a2v_flag_reuse(self, client, test_state): assert r.status_code == 200 estimate = r.json()["estimate"] assert estimate is not None - assert estimate["seconds"] == round(158 * 0.87) + assert estimate["seconds"] == 158 assert estimate["t2vReuse"] is True - def test_unlisted_cell_returns_null_estimate(self, client, test_state): + def test_unlisted_cell_returns_scaled_estimate(self, client, test_state): _configure_5090_windows_fast(test_state) r = client.post( @@ -4150,7 +4320,10 @@ def test_unlisted_cell_returns_null_estimate(self, client, test_state): json={"resolution": "720p", "duration": 10, "fps": 24, "feature": "t2v"}, ) assert r.status_code == 200 - assert r.json()["estimate"] is None + estimate = r.json()["estimate"] + assert estimate is not None + assert estimate["basis"] == "scaled" + assert estimate["seconds"] > 0 def test_off_class_hardware_returns_null_estimate(self, client, test_state): _configure_5090_windows_fast(test_state) @@ -4178,6 +4351,7 @@ def test_auto_duration_returns_null_estimate(self, client, test_state): assert r.status_code == 200 assert r.json()["estimate"] is None + @pytest.mark.usefixtures("single_pass_only") def test_oversize_cell_mirrors_generate_422(self, client, test_state): _configure_windows_fast(test_state, vram_gib=16) @@ -4233,10 +4407,7 @@ def test_estimate_21_9_refuses_where_16_9_passes_matching_generate( wide, status_code=422, code=VIDEO_JOB_TOO_LARGE, - message=( - "This job needs 17.6 GB of GPU memory but this card has 16.0 GB. " - "Lower the resolution, duration, frame rate, or aspect width." - ), + message=unmeasured_refusal_message("windowed_range"), ) landscape = client.post( diff --git a/backend/tests/test_generation_lanes.py b/backend/tests/test_generation_lanes.py new file mode 100644 index 000000000..2a8cad790 --- /dev/null +++ b/backend/tests/test_generation_lanes.py @@ -0,0 +1,616 @@ +"""Lane routing in the store and the registry. + +Each test names the bug it catches. +""" + +from __future__ import annotations + +import sqlite3 +from pathlib import Path + +import pytest +from PIL import Image +from pydantic import JsonValue + +from api_types import QueueProgress +from services.displaced_provider_jobs import ( + DISPLACED_PROVIDER_JOBS_FILENAME, + DisplacedProviderJobs, +) +from services.generation_queue.control import QueueLiveState +from services.generation_queue.lanes import LOCAL_LANE_SPEC, LaneRegistry, LaneSpec +from _routes._errors import HTTPError +from services.generation_queue.orphans import cancel_provider_orphans, forget_in +from services.generation_queue.registry import ExecutorRegistry +from services.records import LOCAL_LANE, OutputSpec, ProviderOrphan, UnavailableError +from services.sqlite_store import SqliteStore +from tests.fakes.lanes import TEST_FEATURE, TEST_LANE, TEST_LANE_SPEC + + +def _spec() -> dict[str, JsonValue]: + return {"params": {"prompt": "fox"}, "inputs": {}} + + +class _TestLaneExecutor: + """Only the part of the executor the registry reads.""" + + def lane_for(self, spec) -> str: + del spec + return TEST_LANE + + +class _PlainExecutor: + pass + + +def test_a_runner_never_claims_a_row_of_another_lane(tmp_path: Path) -> None: + # Bug caught: the local runner claims a remote job and runs it on the GPU slot. + store = SqliteStore(tmp_path / "app_data") + remote_job = store.insert_generation(TEST_FEATURE, _spec(), lane=TEST_LANE) + + assert store.claim_next_queued(LOCAL_LANE) is None + claimed = store.claim_next_queued(TEST_LANE) + assert claimed is not None + assert claimed.id == remote_job.id + assert claimed.lane == TEST_LANE + + +def test_has_queued_only_sees_its_own_lane(tmp_path: Path) -> None: + # Bug caught: an idle local runner spins on a queued remote row it can never claim. + store = SqliteStore(tmp_path / "app_data") + store.insert_generation(TEST_FEATURE, _spec(), lane=TEST_LANE) + + assert store.has_queued(TEST_LANE) + assert not store.has_queued(LOCAL_LANE) + + +def test_each_lane_keeps_queue_order_on_its_own(tmp_path: Path) -> None: + # Bug caught: a lane skips its oldest row because another lane holds an older one. + store = SqliteStore(tmp_path / "app_data") + local_first = store.insert_generation("text-to-video", _spec()) + remote_first = store.insert_generation(TEST_FEATURE, _spec(), lane=TEST_LANE) + remote_second = store.insert_generation(TEST_FEATURE, _spec(), lane=TEST_LANE) + + remote_claim = store.claim_next_queued(TEST_LANE) + local_claim = store.claim_next_queued(LOCAL_LANE) + + assert remote_claim is not None and remote_claim.id == remote_first.id + assert local_claim is not None and local_claim.id == local_first.id + next_remote = store.claim_next_queued(TEST_LANE) + assert next_remote is not None and next_remote.id == remote_second.id + + +def test_retry_keeps_the_lane(tmp_path: Path) -> None: + # Bug caught: a retried remote job falls back to the local lane. + store = SqliteStore(tmp_path / "app_data") + job = store.insert_generation(TEST_FEATURE, _spec(), lane=TEST_LANE) + claimed = store.claim_next_queued(TEST_LANE) + assert claimed is not None + store.mark_failed(job.id, "OUTPUT_UNREADABLE", attempt_count=claimed.attempt_count) + + retried = store.retry_generation(job.id) + + assert retried.lane == TEST_LANE + assert store.has_queued(TEST_LANE) + + +def test_unregistered_lane_rows_move_to_local_at_boot(tmp_path: Path) -> None: + # Bug caught: after the parallel lanes are turned off, queued remote rows wait forever. + store = SqliteStore(tmp_path / "app_data") + stranded = store.insert_generation(TEST_FEATURE, _spec(), lane=TEST_LANE) + kept = store.insert_generation("text-to-video", _spec()) + + moved = store.reassign_unknown_lanes([LOCAL_LANE]) + + assert moved == 1 + reloaded = store.get_generation(stranded.id) + assert reloaded is not None and reloaded.lane == LOCAL_LANE + # The moved row keeps its place in the queue order. + claimed = store.claim_next_queued(LOCAL_LANE) + assert claimed is not None and claimed.id == stranded.id + next_claim = store.claim_next_queued(LOCAL_LANE) + assert next_claim is not None and next_claim.id == kept.id + + +def test_boot_reassignment_leaves_finished_rows_alone(tmp_path: Path) -> None: + # Bug caught: a boot with the kill switch rewrites the lane of every old row for good. + store = SqliteStore(tmp_path / "app_data") + job = store.insert_generation(TEST_FEATURE, _spec(), lane=TEST_LANE) + claimed = store.claim_next_queued(TEST_LANE) + assert claimed is not None + store.mark_failed(job.id, "OUTPUT_UNREADABLE", attempt_count=claimed.attempt_count) + + assert store.reassign_unknown_lanes([LOCAL_LANE]) == 0 + reloaded = store.get_generation(job.id) + assert reloaded is not None and reloaded.lane == TEST_LANE + + +def test_retry_can_move_the_job_to_the_lane_that_is_valid_now(tmp_path: Path) -> None: + # Bug caught: a failed remote job retried after a boot with lanes off waits for a lane with no runner. + store = SqliteStore(tmp_path / "app_data") + job = store.insert_generation(TEST_FEATURE, _spec(), lane=TEST_LANE) + claimed = store.claim_next_queued(TEST_LANE) + assert claimed is not None + store.mark_failed(job.id, "OUTPUT_UNREADABLE", attempt_count=claimed.attempt_count) + + retried = store.retry_generation(job.id, lane=LOCAL_LANE) + + assert retried.lane == LOCAL_LANE + assert store.has_queued(LOCAL_LANE) and not store.has_queued(TEST_LANE) + + +def test_registered_lane_rows_stay_put_at_boot(tmp_path: Path) -> None: + # Bug caught: the boot reassignment moves rows of a live lane to local. + store = SqliteStore(tmp_path / "app_data") + job = store.insert_generation(TEST_FEATURE, _spec(), lane=TEST_LANE) + + assert store.reassign_unknown_lanes([LOCAL_LANE, TEST_LANE]) == 0 + reloaded = store.get_generation(job.id) + assert reloaded is not None and reloaded.lane == TEST_LANE + + +def test_executor_without_lane_for_runs_on_local() -> None: + # Bug caught: an executor that does not know about lanes gets no lane at all. + registry = ExecutorRegistry( + {"text-to-video": _PlainExecutor()}, # type: ignore[dict-item] + LaneRegistry([LOCAL_LANE_SPEC, TEST_LANE_SPEC]), + ) + + assert registry.lane_for("text-to-video", _spec()) == LOCAL_LANE + + +def test_lane_of_an_unregistered_provider_resolves_to_local() -> None: + # Bug caught: a job is inserted on a lane that has no runner (kill switch on). + registry = ExecutorRegistry( + {TEST_FEATURE: _TestLaneExecutor()}, # type: ignore[dict-item] + LaneRegistry([LOCAL_LANE_SPEC]), + ) + + assert registry.lane_for(TEST_FEATURE, _spec()) == LOCAL_LANE + + +def test_executor_lane_is_used_when_registered() -> None: + # Bug caught: the executor choice is ignored, so every job stays local. + registry = ExecutorRegistry( + {TEST_FEATURE: _TestLaneExecutor()}, # type: ignore[dict-item] + LaneRegistry([LOCAL_LANE_SPEC, TEST_LANE_SPEC]), + ) + + assert registry.lane_for(TEST_FEATURE, _spec()) == TEST_LANE + + +def test_lane_registry_needs_the_local_lane() -> None: + # Bug caught: a registry without local leaves unknown rows with no fallback. + with pytest.raises(ValueError, match="local lane"): + LaneRegistry([TEST_LANE_SPEC]) + + +def test_lane_needs_at_least_one_worker() -> None: + # Bug caught: a lane with zero workers accepts jobs and never runs them. + with pytest.raises(ValueError, match="concurrency"): + LaneSpec(id="x", concurrency=0, uses_gpu=False, cancellable_while_running=True) + + +class _LiveStateByJob: + def __init__(self, states: dict[str, QueueLiveState]) -> None: + self._states = states + + def wake(self) -> None: + return None + + def interrupt(self, generation_id: str, attempt_count: int) -> None: + del generation_id, attempt_count + + def live_state(self, generation_id: str) -> QueueLiveState | None: + return self._states.get(generation_id) + + +def test_queue_snapshot_lists_every_running_job_with_its_own_live_state( + client, test_state +) -> None: + # Bug caught: the snapshot shows one running job, or shows the local job's progress + # and cancel support on the provider job. + test_state.generation_queue.stop() + store = test_state.queued_generations._db + local_job = store.insert_generation("text-to-video", _spec()) + remote_job = store.insert_generation(TEST_FEATURE, _spec(), lane=TEST_LANE) + assert store.claim_next_queued(LOCAL_LANE) is not None + assert store.claim_next_queued(TEST_LANE) is not None + test_state.queued_generations._queue_control = _LiveStateByJob( + { + local_job.id: QueueLiveState( + progress=QueueProgress( + phase="inference", + progress=40, + currentStep=4, + totalSteps=10, + remainingSeconds=95, + ), + api_status=None, + cancellable=True, + ), + remote_job.id: QueueLiveState( + progress=None, api_status="processing", cancellable=False + ), + } + ) + + body = client.get("/api/generation-queue").json() + + by_id = {entry["generation"]["id"]: entry for entry in body["active"]} + assert set(by_id) == {local_job.id, remote_job.id} + assert by_id[local_job.id]["generation"]["lane"] == LOCAL_LANE + assert by_id[local_job.id]["progress"]["progress"] == 40 + assert by_id[local_job.id]["progress"]["remainingSeconds"] == 95 + assert by_id[local_job.id]["cancellable"] is True + assert by_id[local_job.id]["api_status"] is None + assert by_id[remote_job.id]["generation"]["lane"] == TEST_LANE + assert by_id[remote_job.id]["progress"] is None + assert by_id[remote_job.id]["cancellable"] is False + assert by_id[remote_job.id]["api_status"] == "processing" + + +def test_queued_rows_are_always_cancellable(client, test_state) -> None: + # Bug caught: a queued row inherits "not cancellable" from a running provider job. + test_state.generation_queue.stop() + store = test_state.queued_generations._db + store.insert_generation(TEST_FEATURE, _spec(), lane=TEST_LANE) + + body = client.get("/api/generation-queue").json() + + assert body["active"] == [] + assert body["queued"][0]["cancellable"] is True + assert body["queued"][0]["generation"]["lane"] == TEST_LANE + + +def test_retry_of_a_job_with_an_unknown_feature_still_leaves_an_unregistered_lane(test_state) -> None: + # Bug caught: the lane lookup fails, the stored lane is kept, and no runner serves it. + store = test_state.queued_generations._db + job = store.insert_generation("removed-feature", _spec(), lane=TEST_LANE) + claimed = store.claim_next_queued(TEST_LANE) + assert claimed is not None + store.mark_failed(job.id, "OUTPUT_UNREADABLE", attempt_count=claimed.attempt_count) + + test_state.queued_generations.retry_generation(job.id) + + reloaded = store.get_generation(job.id) + assert reloaded is not None and reloaded.lane == LOCAL_LANE + + +def _claim_remote(store: SqliteStore): + job = store.insert_generation(TEST_FEATURE, _spec(), lane=TEST_LANE) + claimed = store.claim_next_queued(TEST_LANE) + assert claimed is not None and claimed.id == job.id + return claimed + + +def test_provider_job_id_is_stored_for_a_running_job_only(tmp_path: Path) -> None: + # Bug caught: a late provider id lands on a queued or finished row and is later cancelled by mistake. + store = SqliteStore(tmp_path / "app_data") + queued = store.insert_generation("text-to-video", _spec()) + assert store.set_provider_job_id(queued.id, queued.attempt_count, "req-1") is False + + running = _claim_remote(store) + assert store.set_provider_job_id(running.id, running.attempt_count, "req-2") is True + reloaded = store.get_generation(running.id) + assert reloaded is not None and reloaded.provider_job_id == "req-2" + + store.mark_failed(running.id, "OUTPUT_UNREADABLE", attempt_count=running.attempt_count) + assert store.set_provider_job_id(running.id, running.attempt_count, "req-3") is False + + +def test_an_empty_provider_job_id_is_refused(tmp_path: Path) -> None: + # Bug caught: an empty id is stored, the boot orphan list cannot be read, and the app crashes at every start. + store = SqliteStore(tmp_path / "app_data") + running = _claim_remote(store) + + with pytest.raises(ValueError, match="empty"): + store.set_provider_job_id(running.id, running.attempt_count, "") + + assert store.list_provider_orphans() == [] + + +def test_the_orphan_list_skips_an_empty_id_already_in_the_store(tmp_path: Path) -> None: + # Bug caught: a row with an empty id (written by an older build) crashes the boot. + store = SqliteStore(tmp_path / "app_data") + running = _claim_remote(store) + conn = store._connect() + conn.execute("UPDATE generations SET provider_job_id = '' WHERE id = ?", (running.id,)) + conn.commit() + conn.close() + + assert store.list_provider_orphans() == [] + + +def test_a_store_error_while_moving_lanes_reads_as_unavailable(tmp_path: Path, monkeypatch) -> None: + # Bug caught: a locked or full database crashes the boot instead of switching to the unavailable store. + store = SqliteStore(tmp_path / "app_data") + + def broken_connect(): + raise sqlite3.OperationalError("database is locked") + + monkeypatch.setattr(store, "_connect", broken_connect) + + with pytest.raises(UnavailableError): + store.reassign_unknown_lanes([LOCAL_LANE]) + + +def _fail_with_id(store: SqliteStore, provider_id: str): + claimed = _claim_remote(store) + store.set_provider_job_id(claimed.id, claimed.attempt_count, provider_id) + store.mark_failed(claimed.id, "OUTPUT_UNREADABLE", attempt_count=claimed.attempt_count) + return claimed + + +def test_a_retry_shows_the_newest_attempt_only_but_keeps_the_old_id_to_cancel(tmp_path: Path) -> None: + # Bug caught: a retry shows the id of the first attempt, or drops an id that nobody cancelled. + store = SqliteStore(tmp_path / "app_data") + failed = _fail_with_id(store, "req-1") + + retried = store.retry_generation(failed.id) + + assert retried.provider_job_id is None + assert [(o.generation_id, o.lane, o.provider_job_id) for o in store.list_provider_orphans()] == [ + (failed.id, TEST_LANE, "req-1") + ] + + +def test_every_attempt_that_failed_keeps_its_own_id_until_its_cancel_succeeds(tmp_path: Path) -> None: + # Bug caught: a second retry overwrites the id that the first retry saved. + store = SqliteStore(tmp_path / "app_data") + first = _fail_with_id(store, "req-1") + store.retry_generation(first.id) + second = store.claim_next_queued(TEST_LANE) + assert second is not None + store.set_provider_job_id(second.id, second.attempt_count, "req-2") + store.mark_failed(second.id, "OUTPUT_UNREADABLE", attempt_count=second.attempt_count) + store.retry_generation(second.id) + + assert sorted(o.provider_job_id for o in store.list_provider_orphans()) == ["req-1", "req-2"] + + assert store.clear_provider_job_id(first.id, "req-1") is True + assert [o.provider_job_id for o in store.list_provider_orphans()] == ["req-2"] + assert store.clear_provider_job_id(first.id, "req-1") is False + + +def test_an_id_in_the_file_and_on_the_row_is_listed_once(tmp_path: Path) -> None: + # Bug caught: a crash between the file write and the commit of a retry cancels one job twice. + app_data = tmp_path / "app_data" + store = SqliteStore(app_data) + failed = _fail_with_id(store, "req-1") + DisplacedProviderJobs(app_data / DISPLACED_PROVIDER_JOBS_FILENAME).add( + ProviderOrphan(generation_id=failed.id, lane=TEST_LANE, provider_job_id="req-1") + ) + + assert [o.provider_job_id for o in store.list_provider_orphans()] == ["req-1"] + assert store.clear_provider_job_id(failed.id, "req-1") is True + assert store.list_provider_orphans() == [] + + +def test_a_retry_that_cannot_keep_the_old_id_fails_and_leaves_the_job_failed(tmp_path: Path) -> None: + # Bug caught: a retry drops the id of a paid job because the file cannot be written. + app_data = tmp_path / "app_data" + store = SqliteStore(app_data) + failed = _fail_with_id(store, "req-1") + (app_data / DISPLACED_PROVIDER_JOBS_FILENAME).mkdir() + + with pytest.raises(UnavailableError): + store.retry_generation(failed.id) + + row = store.get_generation(failed.id) + assert row is not None + assert (row.status, row.provider_job_id) == ("failed", "req-1") + + +def test_a_retry_of_a_job_with_no_id_adds_no_orphan(tmp_path: Path) -> None: + # Bug caught: a retry of a local or early failure lists an empty or made-up id at boot. + store = SqliteStore(tmp_path / "app_data") + claimed = _claim_remote(store) + store.mark_failed(claimed.id, "OUTPUT_UNREADABLE", attempt_count=claimed.attempt_count) + + store.retry_generation(claimed.id) + + assert store.list_provider_orphans() == [] + assert store.list_displaced_provider_jobs(claimed.id) == [] + + +def test_a_deleted_failed_job_keeps_its_id_for_the_boot_cancel(tmp_path: Path) -> None: + # Bug caught: the user deletes a failed card whose provider cancel failed, and the job runs on. + store = SqliteStore(tmp_path / "app_data") + failed = _fail_with_id(store, "req-1") + + assert store.delete_generation(failed.id) is True + + assert [o.provider_job_id for o in store.list_provider_orphans()] == ["req-1"] + assert store.clear_provider_job_id(failed.id, "req-1") is True + assert store.list_provider_orphans() == [] + + +def test_orphans_are_rows_that_hold_a_provider_job_id_unless_the_job_succeeded( + tmp_path: Path, +) -> None: + # Bug caught: a failed or cancelled job drops out of the list while the provider still runs it. + store = SqliteStore(tmp_path / "app_data") + running = _claim_remote(store) + store.set_provider_job_id(running.id, running.attempt_count, "req-running") + _claim_remote(store) # Running, but the provider never accepted it. + failed = _claim_remote(store) + store.set_provider_job_id(failed.id, failed.attempt_count, "req-failed") + store.mark_failed(failed.id, "OUTPUT_UNREADABLE", attempt_count=failed.attempt_count) + cancelled = _claim_remote(store) + store.set_provider_job_id(cancelled.id, cancelled.attempt_count, "req-cancelled") + store.request_generation_cancellation(cancelled.id) + store.mark_cancelled(cancelled.id, [], attempt_count=cancelled.attempt_count) + done = _claim_remote(store) + store.set_provider_job_id(done.id, done.attempt_count, "req-done") + asset_id, dest = store.allocate_output_path("image", "image/png") + Image.new("RGB", (8, 8)).save(dest) + store.mark_succeeded( + done.id, + [OutputSpec(asset_id=asset_id, dest_path=dest, ordinal=0, mime_type="image/png", name="out.png")], + attempt_count=done.attempt_count, + ) + + orphans = store.list_provider_orphans() + + assert sorted(o.provider_job_id for o in orphans) == ["req-cancelled", "req-failed", "req-running"] + assert {o.lane for o in orphans} == {TEST_LANE} + + +def test_a_late_provider_job_id_of_an_old_attempt_does_not_land_on_the_retry(tmp_path: Path) -> None: + # Bug caught: a provider thread that outlives the stop stamps its id on the running row of a retry. + store = SqliteStore(tmp_path / "app_data") + first = _claim_remote(store) + store.mark_failed(first.id, "OUTPUT_UNREADABLE", attempt_count=first.attempt_count) + store.retry_generation(first.id) + retry = store.claim_next_queued(TEST_LANE) + assert retry is not None and retry.attempt_count != first.attempt_count + + assert store.set_provider_job_id(first.id, first.attempt_count, "late-id") is False + + reloaded = store.get_generation(first.id) + assert reloaded is not None and reloaded.provider_job_id is None + + +def test_clearing_a_provider_job_id_leaves_a_newer_id_alone(tmp_path: Path) -> None: + # Bug caught: a slow cancel of an old provider job wipes the id of the job that replaced it. + store = SqliteStore(tmp_path / "app_data") + claimed = _claim_remote(store) + store.set_provider_job_id(claimed.id, claimed.attempt_count, "req-new") + + assert store.clear_provider_job_id(claimed.id, "req-old") is False + assert store.clear_provider_job_id(claimed.id, "req-new") is True + + reloaded = store.get_generation(claimed.id) + assert reloaded is not None and reloaded.provider_job_id is None + + +def test_boot_recovery_fails_the_running_rows_and_hands_every_orphan_to_its_lane( + test_state, monkeypatch +) -> None: + # Bug caught: a job that was running at the provider is failed locally and nobody cancels it. + handler = test_state.queued_generations + store = handler._db + claimed = _claim_remote(store) + store.set_provider_job_id(claimed.id, claimed.attempt_count, "req-1") + seen: list[list[str]] = [] + monkeypatch.setattr( + "handlers.queued_generation_handler.cancel_provider_orphans_in_background", + lambda orphans, spec_for, on_cancelled: seen.append([o.provider_job_id for o in orphans]), + ) + + handler.recover_on_boot() + + assert seen == [["req-1"]] + reloaded = store.get_generation(claimed.id) + assert reloaded is not None and reloaded.status == "failed" + assert reloaded.provider_job_id == "req-1" + + +def test_a_job_on_a_lane_that_cannot_cancel_is_refused_a_cancel_while_it_runs( + test_state, +) -> None: + # Bug caught: a cancel is accepted for a billed provider job, and the finished output is deleted. + handler = test_state.queued_generations + store = handler._db + claimed = _claim_remote(store) + billed = LaneSpec( + id=TEST_LANE, concurrency=1, uses_gpu=False, cancellable_while_running=False + ) + handler._executor_registry = ExecutorRegistry( + {}, LaneRegistry([LOCAL_LANE_SPEC, billed]) + ) + + with pytest.raises(HTTPError) as refused: + handler.cancel_generation(claimed.id) + + assert refused.value.status_code == 409 + reloaded = store.get_generation(claimed.id) + assert reloaded is not None and reloaded.status == "running" + + +class _Cancels: + def __init__(self, fail_on: str | None = None) -> None: + self.calls: list[str] = [] + self._fail_on = fail_on + + def __call__(self, provider_job_id: str) -> None: + self.calls.append(provider_job_id) + if provider_job_id == self._fail_on: + raise RuntimeError("provider down") + + +def test_each_orphan_is_cancelled_by_its_own_lane_and_one_failure_does_not_stop_the_rest( + tmp_path: Path, +) -> None: + # Bug caught: one failed cancel leaves every later orphan running and billed. + store = SqliteStore(tmp_path / "app_data") + for provider_id in ("req-1", "req-2"): + claimed = _claim_remote(store) + store.set_provider_job_id(claimed.id, claimed.attempt_count, provider_id) + cancels = _Cancels(fail_on="req-1") + lane = LaneSpec( + id=TEST_LANE, + concurrency=1, + uses_gpu=False, + cancellable_while_running=True, + cancel_orphan=cancels, + ) + + done = cancel_provider_orphans( + store.list_provider_orphans(), + LaneRegistry([LOCAL_LANE_SPEC, lane]).spec, + forget_in(store), + ) + + assert cancels.calls == ["req-1", "req-2"] + assert done == 1 + + +def test_a_failed_provider_cancel_keeps_the_id_for_the_next_boot_and_a_good_one_clears_it( + tmp_path: Path, +) -> None: + # Bug caught: a failed provider cancel drops the id, so a billed job outlives every restart. + store = SqliteStore(tmp_path / "app_data") + claimed = _claim_remote(store) + store.set_provider_job_id(claimed.id, claimed.attempt_count, "req-1") + store.fail_running_on_boot() + provider = _Cancels(fail_on="req-1") + lane = LaneSpec( + id=TEST_LANE, concurrency=1, uses_gpu=False, cancellable_while_running=True, + cancel_orphan=provider, + ) + spec_for = LaneRegistry([LOCAL_LANE_SPEC, lane]).spec + + cancel_provider_orphans(store.list_provider_orphans(), spec_for, forget_in(store)) + assert [o.provider_job_id for o in store.list_provider_orphans()] == ["req-1"] + + provider._fail_on = None + cancel_provider_orphans(store.list_provider_orphans(), spec_for, forget_in(store)) + assert store.list_provider_orphans() == [] + + +def test_orphans_of_a_lane_without_a_cancel_are_skipped_and_keep_their_id(tmp_path: Path) -> None: + # Bug caught: a removed provider lane raises at boot, or its job id is dropped before the lane returns. + store = SqliteStore(tmp_path / "app_data") + claimed = _claim_remote(store) + store.set_provider_job_id(claimed.id, claimed.attempt_count, "req-1") + store.fail_running_on_boot() + orphans = store.list_provider_orphans() + forget = forget_in(store) + + assert cancel_provider_orphans(orphans, LaneRegistry([LOCAL_LANE_SPEC, TEST_LANE_SPEC]).spec, forget) == 0 + assert cancel_provider_orphans(orphans, LaneRegistry([LOCAL_LANE_SPEC]).spec, forget) == 0 + assert [o.provider_job_id for o in store.list_provider_orphans()] == ["req-1"] + + +def test_queue_snapshot_shows_the_provider_job_id(client, test_state) -> None: + # Bug caught: the id is stored but never reaches the API, so support cannot find the provider job. + test_state.generation_queue.stop() + store = test_state.queued_generations._db + claimed = _claim_remote(store) + store.set_provider_job_id(claimed.id, claimed.attempt_count, "req-1") + + body = client.get("/api/generation-queue").json() + + assert body["active"][0]["generation"]["provider_job_id"] == "req-1" diff --git a/backend/tests/test_generation_queue.py b/backend/tests/test_generation_queue.py index b80565e95..2ca77c895 100644 --- a/backend/tests/test_generation_queue.py +++ b/backend/tests/test_generation_queue.py @@ -7,7 +7,7 @@ import threading import time import wave -from collections.abc import Callable, Mapping +from collections.abc import Callable, Collection, Mapping from contextlib import AbstractContextManager, nullcontext from dataclasses import dataclass from datetime import datetime, timezone @@ -26,6 +26,8 @@ GenerationErrorCode, ) from frame_math import compute_num_frames +from runtime_config.budget_admission import RiskAllowance +from runtime_config.reject_reasons import PassShape from runtime_config.ic_lora_local_envelope import IC_LORA_SOURCE_TOO_LARGE from runtime_config.video_job_budget import ( LOCAL_GENERATION_RAM_SHORTFALL, @@ -36,6 +38,7 @@ from services.features.video import TextToVideoExecutor from services.features.video.audio_to_video import AudioToVideoExecutor from services.features.video.image_to_video import ImageToVideoExecutor +from services.features.video.keyframes import KeyframesExecutor from services.features.video.text_to_video import ReservedVideoGenerator from services.generation_queue.control import ( SharedGenerationSlot, @@ -44,6 +47,7 @@ from services.generation_queue.registry import ExecutorRegistry from services.generation_queue.runner import QueueRunner from services.patches import diffusion_stage_cache +from services.generation_queue.sessions import JobSession from services.generation_queue.types import ( ExecutionOutcome, GenerationExecutor, @@ -60,7 +64,7 @@ ) from tests.fakes import FakeResponse from tests.fakes.fake_gpu_info import FakeGpuInfo -from tests.fakes.generation import FakeGenerationExecutor +from tests.fakes.generation import FakeGenerationExecutor, FakeJobSession from tests.fakes.services import FakeHTTPClient, FakeTaskRunner @@ -203,6 +207,7 @@ def execute( self, generation: GenerationRecord, outputs: tuple[OutputAllocation, ...], + session: JobSession, ) -> ExecutionOutcome: del generation self.output_path = outputs[0].dest_path @@ -227,13 +232,14 @@ def execute( self, generation: GenerationRecord, outputs: tuple[OutputAllocation, ...], + session: JobSession, ) -> ExecutionOutcome: self.output_path = outputs[0].dest_path self.started.set() try: if not self.release.wait(timeout=3.0): raise RuntimeError("delayed executor was not released") - return FakeGenerationExecutor().execute(generation, outputs) + return FakeGenerationExecutor().execute(generation, outputs, session) finally: self.finished.set() @@ -253,6 +259,7 @@ def execute( self, generation: GenerationRecord, outputs: tuple[OutputAllocation, ...], + session: JobSession, ) -> ExecutionOutcome: del generation self.output_path = outputs[0].dest_path @@ -292,11 +299,11 @@ def __init__(self, app_data_dir: Path) -> None: self.claim_started = threading.Event() self.allow_claim = threading.Event() - def claim_next_queued(self) -> GenerationRecord | None: + def claim_next_queued(self, lane: str = "local") -> GenerationRecord | None: self.claim_started.set() if not self.allow_claim.wait(timeout=2.0): raise RuntimeError("claim was not released") - return super().claim_next_queued() + return super().claim_next_queued(lane) class _BlockAfterClaimDb(SqliteStore): @@ -305,8 +312,8 @@ def __init__(self, app_data_dir: Path) -> None: self.claimed = threading.Event() self.allow_continue = threading.Event() - def claim_next_queued(self) -> GenerationRecord | None: - claimed = super().claim_next_queued() + def claim_next_queued(self, lane: str = "local") -> GenerationRecord | None: + claimed = super().claim_next_queued(lane) if claimed is not None: self.claimed.set() if not self.allow_continue.wait(timeout=2.0): @@ -319,9 +326,13 @@ def __init__(self, app_data_dir: Path) -> None: super().__init__(app_data_dir) self.claimed: GenerationRecord | None = None - def request_generation_cancellation(self, generation_id: str) -> GenerationRecord: + def request_generation_cancellation( + self, generation_id: str, *, uncancellable_lanes: Collection[str] = () + ) -> GenerationRecord: self.claimed = super().claim_next_queued() - return super().request_generation_cancellation(generation_id) + return super().request_generation_cancellation( + generation_id, uncancellable_lanes=uncancellable_lanes + ) class _ExecuteRecorder(_SkipParamValidation): @@ -338,9 +349,10 @@ def execute( self, generation: GenerationRecord, outputs: tuple[OutputAllocation, ...], + session: JobSession, ) -> ExecutionOutcome: self.executed.set() - return FakeGenerationExecutor().execute(generation, outputs) + return FakeGenerationExecutor().execute(generation, outputs, session) class _FailingFinalizationDb(SqliteStore): @@ -397,11 +409,12 @@ def execute( self, generation: GenerationRecord, outputs: tuple[OutputAllocation, ...], + session: JobSession, ) -> ExecutionOutcome: self.execution_ids.append(generation.id) if _prompt(generation) == "first": raise RuntimeError("executor failed") - return FakeGenerationExecutor().execute(generation, outputs) + return FakeGenerationExecutor().execute(generation, outputs, session) class _DirectoryFailureExecutor(_SkipParamValidation): @@ -416,13 +429,14 @@ def execute( self, generation: GenerationRecord, outputs: tuple[OutputAllocation, ...], + session: JobSession, ) -> ExecutionOutcome: path = Path(outputs[0].dest_path) if _prompt(generation) == "first": path.mkdir() self.partial_paths[generation.id] = str(path) raise RuntimeError("executor failed after creating a directory") - return FakeGenerationExecutor().execute(generation, outputs) + return FakeGenerationExecutor().execute(generation, outputs, session) class _DeleteGenerationExecutor(_SkipParamValidation): @@ -438,8 +452,9 @@ def execute( self, generation: GenerationRecord, outputs: tuple[OutputAllocation, ...], + session: JobSession, ) -> ExecutionOutcome: - result = FakeGenerationExecutor().execute(generation, outputs) + result = FakeGenerationExecutor().execute(generation, outputs, session) if _prompt(generation) != "vanish": return result self.output_path = outputs[0].dest_path @@ -477,9 +492,10 @@ def execute( self, generation: GenerationRecord, outputs: tuple[OutputAllocation, ...], + session: JobSession, ) -> ExecutionOutcome: self.cache_resident_at_execute = diffusion_stage_cache._cached_model is not None # noqa: SLF001 - return super().execute(generation, outputs) + return super().execute(generation, outputs, session) class _MetaMovable: @@ -548,6 +564,7 @@ def execute( self, generation: GenerationRecord, outputs: tuple[OutputAllocation, ...], + session: JobSession, ) -> ExecutionOutcome: del generation for output in outputs[: 2 if self._write_optional else 1]: @@ -582,8 +599,8 @@ def test_runner_leaves_out_an_optional_output_the_executor_did_not_write( def test_runner_fails_when_a_required_output_is_missing(tmp_path: Path) -> None: class _WritesNothing(_OptionalOutputExecutor): - def execute(self, generation, outputs) -> ExecutionOutcome: - del generation, outputs + def execute(self, generation, outputs, session) -> ExecutionOutcome: + del generation, outputs, session return ExecutionOutcome() db = SqliteStore(tmp_path / "app_data") @@ -1405,7 +1422,7 @@ class _ReservedVideoCall: output_path: Path | None prompt_wrap: Callable[[str], str] | None = None local_model_id: str | None = None - risk_allowance: bool | None = None + allowance: RiskAllowance | None = None class _RecordingReservedVideoGenerator: @@ -1414,9 +1431,15 @@ def __init__(self, inner: ReservedVideoGenerator) -> None: self.calls: list[_ReservedVideoCall] = [] def validate_local_a2v_request( - self, params: AudioToVideoParams, audio_duration_ms: int + self, + params: AudioToVideoParams, + audio_duration_ms: int, + *, + pass_shape: PassShape, ) -> None: - self._inner.validate_local_a2v_request(params, audio_duration_ms) + self._inner.validate_local_a2v_request( + params, audio_duration_ms, pass_shape=pass_shape + ) @property def models_dir(self) -> Path: @@ -1435,8 +1458,8 @@ def generate_local_reserved( a2v_num_frames: int | None = None, a2v_audio_duration_seconds: float | None = None, local_model_id: str | None = None, - risk_allowance: bool | None = None, - unmeasured_bet: bool = False, + allowance: RiskAllowance | None = None, + pass_shape: PassShape | None = None, ) -> GenerateVideoResponse: self.calls.append( _ReservedVideoCall( @@ -1445,7 +1468,7 @@ def generate_local_reserved( output_path=output_path, prompt_wrap=prompt_wrap, local_model_id=local_model_id, - risk_allowance=risk_allowance, + allowance=allowance, ) ) return self._inner.generate_local_reserved( @@ -1456,8 +1479,8 @@ def generate_local_reserved( a2v_num_frames=a2v_num_frames, a2v_audio_duration_seconds=a2v_audio_duration_seconds, local_model_id=local_model_id, - risk_allowance=risk_allowance, - unmeasured_bet=unmeasured_bet, + allowance=allowance, + pass_shape=pass_shape, ) @@ -1473,9 +1496,13 @@ def __init__( self.models_dir = models_dir if models_dir is not None else Path("/nonexistent-models-dir") def validate_local_a2v_request( - self, params: AudioToVideoParams, audio_duration_ms: int + self, + params: AudioToVideoParams, + audio_duration_ms: int, + *, + pass_shape: PassShape, ) -> None: - del params, audio_duration_ms + del params, audio_duration_ms, pass_shape def generate_local_reserved( self, @@ -1487,10 +1514,10 @@ def generate_local_reserved( a2v_num_frames: int | None = None, a2v_audio_duration_seconds: float | None = None, local_model_id: str | None = None, - risk_allowance: bool | None = None, - unmeasured_bet: bool = False, + allowance: RiskAllowance | None = None, + pass_shape: PassShape | None = None, ) -> GenerateVideoCompleteResponse: - del a2v_num_frames, a2v_audio_duration_seconds, unmeasured_bet + del a2v_num_frames, a2v_audio_duration_seconds, pass_shape self.calls.append( _ReservedVideoCall( request=req, @@ -1498,7 +1525,7 @@ def generate_local_reserved( output_path=output_path, prompt_wrap=prompt_wrap, local_model_id=local_model_id, - risk_allowance=risk_allowance, + allowance=allowance, ) ) if self._error is not None: @@ -1563,7 +1590,7 @@ def test_text_to_video_rejects_unsupported_contract_version(test_state) -> None: with pytest.raises(ValueError, match="contract_version"): executor.plan_outputs(_generation(contract_version=2)) with pytest.raises(ValueError, match="contract_version"): - executor.execute(_generation(contract_version=2), ()) + executor.execute(_generation(contract_version=2), (), FakeJobSession()) @pytest.mark.parametrize("pipeline_id", ["fast", "pro", "pro-2.5", "fast-2.5"]) @@ -1600,7 +1627,7 @@ def test_text_to_video_rejects_capability_invalid_params_before_pipeline( shutdown = threading.Event() with test_state.generation.wait_for_generation_slot(shutdown): with pytest.raises(CapabilityFailedError) as exc_info: - executor.execute(generation, outputs) + executor.execute(generation, outputs, FakeJobSession()) assert exc_info.value.code == "INVALID_VIDEO_GENERATION_SPEC" assert exc_info.value.detail == ( @@ -1637,7 +1664,7 @@ def test_text_to_video_maps_valid_params_to_generation_request( shutdown = threading.Event() with test_state.generation.wait_for_generation_slot(shutdown): - executor.execute(generation, outputs) + executor.execute(generation, outputs, FakeJobSession()) assert dest.exists() assert not dest.is_relative_to(test_state.config.outputs_dir) @@ -1682,7 +1709,7 @@ def test_text_to_video_maps_structural_params_without_local_validation( ) with pytest.raises(CapabilityFailedError) as exc_info: - executor.execute(generation, outputs) + executor.execute(generation, outputs, FakeJobSession()) assert exc_info.value.code == "LTX_MODEL_NOT_INSTALLED" assert recorder.calls == [] @@ -1714,7 +1741,7 @@ def test_recipe_executor_forwards_studio_scaffold_wrap( OutputAllocation(plan=plans[0], asset_id="asset-1", dest_path=str(dest)), ) - executor.execute(generation, outputs) + executor.execute(generation, outputs, FakeJobSession()) assert len(recorder.calls) == 1 wrap = recorder.calls[0].prompt_wrap @@ -1777,7 +1804,7 @@ def test_i2v_recipe_executor_forwards_scaffold_and_start_image( OutputAllocation(plan=plans[0], asset_id="asset-1", dest_path=str(dest)), ) - executor.execute(generation, outputs) + executor.execute(generation, outputs, FakeJobSession()) assert len(recorder.calls) == 1 captured = recorder.calls[0] @@ -1822,7 +1849,7 @@ def test_text_to_video_maps_2_3_offering_without_changing_active_settings( shutdown = threading.Event() with test_state.generation.wait_for_generation_slot(shutdown): - executor.execute(generation, outputs) + executor.execute(generation, outputs, FakeJobSession()) captured = recorder.calls[0] assert captured.request.model == "fast" @@ -1881,7 +1908,7 @@ def test_image_to_video_maps_2_3_offering_without_changing_active_settings( shutdown = threading.Event() with test_state.generation.wait_for_generation_slot(shutdown): - executor.execute(generation, outputs) + executor.execute(generation, outputs, FakeJobSession()) captured = recorder.calls[0] assert captured.request.model == "fast" @@ -1917,7 +1944,7 @@ def test_text_to_video_rejects_undownloaded_offering( shutdown = threading.Event() with test_state.generation.wait_for_generation_slot(shutdown): with pytest.raises(CapabilityFailedError) as exc_info: - executor.execute(generation, outputs) + executor.execute(generation, outputs, FakeJobSession()) assert exc_info.value.code == "LTX_MODEL_NOT_INSTALLED" @@ -1945,7 +1972,7 @@ def test_image_to_video_maps_asset_ids_to_executor_paths( OutputAllocation(plan=plans[0], asset_id="asset-1", dest_path=str(dest)), ) - executor.execute(generation, outputs) + executor.execute(generation, outputs, FakeJobSession()) assert len(recorder.calls) == 1 captured = recorder.calls[0] @@ -1960,6 +1987,51 @@ def test_image_to_video_maps_asset_ids_to_executor_paths( assert end.path not in str(generation.spec) +def test_keyframes_executor_sends_each_still_with_its_frame_and_strength( + test_state, create_fake_model_files, tmp_path: Path +) -> None: + db = SqliteStore(test_state.config.app_data_dir) + late = db.ingest_upload(str(_png(tmp_path / "late.png", size=(16, 32)))) + early = db.ingest_upload(str(_png(tmp_path / "early.png", size=(32, 16)))) + recorder = _stub_reserved(test_state, create_fake_model_files) + executor = KeyframesExecutor(recorder, db) + generation = _generation( + generation_id="keyframes-mapped", + feature="keyframes", + params={ + "prompt": "a fox runs", + "model": "ltx-2.5-fast", + "aspectRatio": "auto", + "resolution": "540p", + "duration": 5, + "fps": 24, + }, + # The list is not in time order. The aspect must follow the earliest frame. + inputs={ + "keyframes": [ + {"assetId": late.id, "frameIndex": 100, "strength": 0.4}, + {"assetId": early.id, "frameIndex": 0, "strength": 0.9}, + ] + }, + ) + plans = executor.plan_outputs(generation) + outputs = ( + OutputAllocation(plan=plans[0], asset_id="asset-1", dest_path=str(tmp_path / "k.mp4")), + ) + + executor.execute(generation, outputs, FakeJobSession()) + + request = recorder.calls[0].request + assert [(k.imagePath, k.frameIndex, k.strength) for k in request.keyframes] == [ + (late.path, 100, 0.4), + (early.path, 0, 0.9), + ] + assert request.imagePath is None + assert request.aspectRatio == "16:9" + assert late.path not in str(generation.spec) + assert early.path not in str(generation.spec) + + @pytest.mark.parametrize( ("requested_ratio", "start_size", "expected_ratio"), [ @@ -1996,7 +2068,7 @@ def test_image_to_video_resolves_auto_aspect_ratio_from_start_frame( dest_path=str(tmp_path / "assets" / f"{case_id}.mp4"), ) - executor.execute(generation, (output,)) + executor.execute(generation, (output,), FakeJobSession()) assert recorder.calls[0].request.aspectRatio == expected_ratio assert generation.spec["params"] == { @@ -2038,7 +2110,7 @@ def no_local_cell(resolution: str, *, is_a2v: bool) -> list[str]: ) with pytest.raises(CapabilityFailedError) as exc_info: - executor.execute(generation, (output,)) + executor.execute(generation, (output,), FakeJobSession()) assert exc_info.value.code == "INVALID_LOCAL_RESOLUTION" assert recorder.calls == [] @@ -2063,7 +2135,7 @@ def test_image_to_video_rejects_non_image_asset( ) with pytest.raises(CapabilityFailedError) as exc_info: - executor.execute(generation, (output,)) + executor.execute(generation, (output,), FakeJobSession()) assert exc_info.value.code == "INPUT_ASSET_NOT_FOUND" assert exc_info.value.detail == "startFrame image is no longer available" @@ -2092,7 +2164,7 @@ def test_image_to_video_execute_rejects_unavailable_start_frame( ) with pytest.raises(CapabilityFailedError) as exc_info: - executor.execute(generation, (output,)) + executor.execute(generation, (output,), FakeJobSession()) assert exc_info.value.code == "INPUT_ASSET_NOT_FOUND" assert exc_info.value.detail == "startFrame image is no longer available" @@ -2122,7 +2194,7 @@ def test_image_to_video_execute_rejects_missing_start_frame_record( ) with pytest.raises(CapabilityFailedError) as exc_info: - executor.execute(generation, (output,)) + executor.execute(generation, (output,), FakeJobSession()) assert exc_info.value.code == "INPUT_ASSET_NOT_FOUND" assert exc_info.value.detail == "startFrame image is no longer available" @@ -2154,7 +2226,7 @@ def test_image_to_video_execute_hides_http_error_filesystem_paths( ) with pytest.raises(CapabilityFailedError) as exc_info: - executor.execute(generation, (output,)) + executor.execute(generation, (output,), FakeJobSession()) assert exc_info.value.code == "INPUT_ASSET_NOT_FOUND" assert exc_info.value.detail == "image input is no longer available" @@ -2185,7 +2257,7 @@ def test_audio_to_video_maps_audio_asset_to_executor_path( OutputAllocation(plan=plans[0], asset_id="asset-1", dest_path=str(dest)), ) - executor.execute(generation, outputs) + executor.execute(generation, outputs, FakeJobSession()) assert len(recorder.calls) == 1 captured = recorder.calls[0] @@ -2226,7 +2298,7 @@ def test_audio_to_video_executes_advertised_1080p( shutdown = threading.Event() with test_state.generation.wait_for_generation_slot(shutdown): - executor.execute(generation, outputs) + executor.execute(generation, outputs, FakeJobSession()) captured = recorder.calls[0] assert captured.request.resolution == "1080p" @@ -2264,7 +2336,7 @@ def test_audio_to_video_hears_a_20s_clip_at_1080p_instead_of_the_kept_10s_prefix shutdown = threading.Event() with test_state.generation.wait_for_generation_slot(shutdown): - executor.execute(generation, outputs) + executor.execute(generation, outputs, FakeJobSession()) call = fake_services.a2v_pipeline.generate_calls[0] assert call["audio_start_time"] == 0.0 @@ -2297,7 +2369,7 @@ def test_audio_to_video_maps_2_3_offering_without_changing_active_settings( shutdown = threading.Event() with test_state.generation.wait_for_generation_slot(shutdown): - executor.execute(generation, outputs) + executor.execute(generation, outputs, FakeJobSession()) captured = recorder.calls[0] assert captured.request.model == "fast" @@ -2331,7 +2403,7 @@ def test_audio_to_video_maps_start_frame_to_image_path( OutputAllocation(plan=plans[0], asset_id="asset-1", dest_path=str(dest)), ) - executor.execute(generation, outputs) + executor.execute(generation, outputs, FakeJobSession()) assert len(recorder.calls) == 1 captured = recorder.calls[0] @@ -2388,7 +2460,7 @@ def test_audio_to_video_resolves_auto_aspect_ratio_from_start_frame( dest_path=str(tmp_path / "assets" / f"{case_id}.mp4"), ) - executor.execute(generation, (output,)) + executor.execute(generation, (output,), FakeJobSession()) assert recorder.calls[0].request.aspectRatio == expected_ratio assert generation.spec["params"]["aspectRatio"] == requested_ratio @@ -2413,7 +2485,7 @@ def test_audio_to_video_auto_aspect_ratio_without_start_frame_uses_16_9( dest_path=str(tmp_path / "assets" / "a2v-auto.mp4"), ) - executor.execute(generation, (output,)) + executor.execute(generation, (output,), FakeJobSession()) assert recorder.calls[0].request.aspectRatio == "16:9" assert generation.spec["params"]["aspectRatio"] == "auto" @@ -2439,7 +2511,7 @@ def test_audio_to_video_rejects_non_audio_asset( ) with pytest.raises(CapabilityFailedError) as exc_info: - executor.execute(generation, (output,)) + executor.execute(generation, (output,), FakeJobSession()) assert exc_info.value.code == "INPUT_ASSET_NOT_FOUND" assert exc_info.value.detail == "audio is no longer available" @@ -2472,7 +2544,7 @@ def test_audio_to_video_rejects_non_image_start_frame( ) with pytest.raises(CapabilityFailedError) as exc_info: - executor.execute(generation, (output,)) + executor.execute(generation, (output,), FakeJobSession()) assert exc_info.value.code == "INPUT_ASSET_NOT_FOUND" assert exc_info.value.detail == "startFrame image is no longer available" @@ -2502,7 +2574,7 @@ def test_audio_to_video_execute_rejects_unavailable_audio( ) with pytest.raises(CapabilityFailedError) as exc_info: - executor.execute(generation, (output,)) + executor.execute(generation, (output,), FakeJobSession()) assert exc_info.value.code == "INPUT_ASSET_NOT_FOUND" assert exc_info.value.detail == "audio is no longer available" @@ -2538,7 +2610,7 @@ def test_audio_to_video_execute_rejects_unavailable_start_frame( ) with pytest.raises(CapabilityFailedError) as exc_info: - executor.execute(generation, (output,)) + executor.execute(generation, (output,), FakeJobSession()) assert exc_info.value.code == "INPUT_ASSET_NOT_FOUND" assert exc_info.value.detail == "startFrame image is no longer available" @@ -2569,7 +2641,7 @@ def test_audio_to_video_execute_rejects_missing_audio_record( ) with pytest.raises(CapabilityFailedError) as exc_info: - executor.execute(generation, (output,)) + executor.execute(generation, (output,), FakeJobSession()) assert exc_info.value.code == "INPUT_ASSET_NOT_FOUND" assert exc_info.value.detail == "audio is no longer available" @@ -2602,7 +2674,7 @@ def test_audio_to_video_execute_hides_http_error_filesystem_paths( ) with pytest.raises(CapabilityFailedError) as exc_info: - executor.execute(generation, (output,)) + executor.execute(generation, (output,), FakeJobSession()) assert exc_info.value.code == "INPUT_ASSET_NOT_FOUND" assert exc_info.value.detail == "input media is no longer available" @@ -2637,7 +2709,7 @@ def test_audio_to_video_converts_cancelled_to_cancelled_error( ) with pytest.raises(GenerationCancelledError): - executor.execute(generation, (output,)) + executor.execute(generation, (output,), FakeJobSession()) def test_audio_to_video_uses_local_a2v_pipeline_not_ltx_api( @@ -2665,7 +2737,7 @@ def test_audio_to_video_uses_local_a2v_pipeline_not_ltx_api( shutdown = threading.Event() with test_state.generation.wait_for_generation_slot(shutdown): - executor.execute(generation, outputs) + executor.execute(generation, outputs, FakeJobSession()) assert len(recorder.calls) == 1 captured = recorder.calls[0] @@ -2718,7 +2790,7 @@ def test_audio_to_video_rejects_retried_job_with_stale_persisted_frames( retried = db.retry_generation(generation.id) with pytest.raises(CapabilityFailedError) as exc_info: - executor.execute(retried, (output,)) + executor.execute(retried, (output,), FakeJobSession()) assert exc_info.value.code == "INVALID_VIDEO_GENERATION_SPEC" assert exc_info.value.detail == ( @@ -2750,11 +2822,11 @@ def test_text_to_video_requires_single_output_allocation( ) match = "text-to-video requires a single 'output' allocation" with pytest.raises(ValueError, match=match): - executor.execute(generation, ()) + executor.execute(generation, (), FakeJobSession()) with pytest.raises(ValueError, match=match): - executor.execute(generation, (output, output)) + executor.execute(generation, (output, output), FakeJobSession()) with pytest.raises(ValueError, match=match): - executor.execute(generation, (preview,)) + executor.execute(generation, (preview,), FakeJobSession()) def test_text_to_video_converts_cancelled_response_to_cancelled_error( @@ -2773,7 +2845,7 @@ def test_text_to_video_converts_cancelled_response_to_cancelled_error( shutdown = threading.Event() with test_state.generation.wait_for_generation_slot(shutdown): with pytest.raises(GenerationCancelledError): - executor.execute(generation, outputs) + executor.execute(generation, outputs, FakeJobSession()) def test_fake_generation_executor_writes_valid_video(tmp_path: Path) -> None: @@ -2787,6 +2859,7 @@ def test_fake_generation_executor_writes_valid_video(tmp_path: Path) -> None: FakeGenerationExecutor().execute( _generation(), (OutputAllocation(plan=plan, asset_id="asset-1", dest_path=str(dest)),), + FakeJobSession(), ) kind, mime_type, metadata = probe_file(dest) assert kind == "video" @@ -2800,7 +2873,7 @@ def test_fake_generation_executor_records_prompts_and_configured_error() -> None seen_prompts=seen, error=RuntimeError("bad input") ) with pytest.raises(RuntimeError, match="bad input"): - executor.execute(_generation(params={"prompt": "first"}), ()) + executor.execute(_generation(params={"prompt": "first"}), (), FakeJobSession()) assert seen == ["first"] @@ -2812,7 +2885,7 @@ def test_fake_generation_executor_block_raises_after_interrupt() -> None: def target() -> None: started.set() try: - executor.execute(_generation(), ()) + executor.execute(_generation(), (), FakeJobSession()) except BaseException as exc: result["error"] = exc @@ -2836,6 +2909,7 @@ def execute( self, generation: GenerationRecord, outputs: tuple[OutputAllocation, ...], + session: JobSession, ) -> ExecutionOutcome: del outputs message = "CUDA out of memory. Tried to allocate 516.00 MiB." diff --git a/backend/tests/test_generation_stats_schema.py b/backend/tests/test_generation_stats_schema.py index a2261e6cb..9cc3d3ca4 100644 --- a/backend/tests/test_generation_stats_schema.py +++ b/backend/tests/test_generation_stats_schema.py @@ -141,7 +141,7 @@ def test_v1_database_upgrades_without_dropping_rows(tmp_path: Path) -> None: apply_migrations(conn, MIGRATIONS_DIR) version = conn.execute("SELECT MAX(version) FROM schema_migrations").fetchone()[0] - assert version == 2 + assert version == 4 assert conn.execute("PRAGMA foreign_key_check").fetchone() is None columns = { row["name"] for row in conn.execute("PRAGMA table_info(generations)").fetchall() diff --git a/backend/tests/test_gpu_job.py b/backend/tests/test_gpu_job.py index afcb93bbe..c1ae2a5ef 100644 --- a/backend/tests/test_gpu_job.py +++ b/backend/tests/test_gpu_job.py @@ -4,6 +4,7 @@ import pytest +from runtime_config.device_calibration import JobEnvelope from services.features.video.edit_executor import run_gpu_job from services.generation_interrupt import GenerationCancelledError @@ -14,10 +15,16 @@ def __init__(self) -> None: self.completed: list[str | None] = [] self.failed: list[str] = [] - def start_generation(self, generation_id: str) -> None: + def start_generation( + self, generation_id: str, *, ran: JobEnvelope | None = None + ) -> None: + del ran self.started.append(generation_id) - def complete_generation(self, result: str | list[str] | None = None) -> None: + def complete_generation( + self, result: str | list[str] | None = None, *, ran: JobEnvelope | None = None + ) -> None: + del ran self.completed.append(result if isinstance(result, str) or result is None else result[0]) def fail_generation(self, error: str) -> None: diff --git a/backend/tests/test_gpu_lease.py b/backend/tests/test_gpu_lease.py new file mode 100644 index 000000000..9c8070c29 --- /dev/null +++ b/backend/tests/test_gpu_lease.py @@ -0,0 +1,163 @@ +"""The GPU lease: a job of another lane borrows the GPU only when it is fully idle. + +Each test names the bug it catches. +""" + +from __future__ import annotations + +import threading +import time + +import pytest + +from services.records import LOCAL_LANE + + +def _lease(test_state, *, local_lane_idle: bool = True): + return test_state.generation.try_lease_idle_gpu(local_lane_idle=lambda: local_lane_idle) + + +def test_the_lease_is_granted_on_an_idle_machine_and_released_after(test_state) -> None: + # Bug caught: the lease never releases and the next local job cannot start. + generation = test_state.generation + + with _lease(test_state) as leased: + assert leased + assert generation.try_reserve_generation_start() is False + + assert generation.try_reserve_generation_start() is True + generation.release_generation_start_reservation() + + +def test_the_lease_fails_while_a_local_job_holds_the_slot(test_state) -> None: + # Bug caught: a fal rewrite loads Gemma while a local job runs. + generation = test_state.generation + assert generation.try_reserve_generation_start(persistent=True) + + with _lease(test_state) as leased: + assert not leased + + # The denied lease must not release the reservation of the job that holds it. + assert generation.try_reserve_generation_start() is False + generation.release_generation_start_reservation() + + +def test_the_idle_check_runs_without_the_state_lock(test_state) -> None: + # Bug caught: the SQLite read of the idle check stalls every handler that needs the lock. + generation = test_state.generation + free_for_others: list[bool] = [] + + def idle_check() -> bool: + def probe() -> None: + acquired = generation.lock.acquire(blocking=False) + free_for_others.append(acquired) + if acquired: + generation.lock.release() + + thread = threading.Thread(target=probe) + thread.start() + thread.join() + return True + + with generation.try_lease_idle_gpu(local_lane_idle=idle_check) as leased: + assert leased + + assert free_for_others == [True] + + +def test_the_lease_fails_while_the_local_lane_has_a_queued_row(test_state) -> None: + # Bug caught: a fal rewrite takes the GPU between two local jobs and evicts the warm model. + store = test_state.queued_generations._db + store.insert_generation("text-to-video", {"params": {"prompt": "fox"}, "inputs": {}}) + + assert test_state.generation_queue.lane_is_idle(LOCAL_LANE) is False + with test_state.generation.try_lease_idle_gpu( + local_lane_idle=lambda: test_state.generation_queue.lane_is_idle(LOCAL_LANE) + ) as leased: + assert not leased + + +def test_the_lease_fails_while_the_queue_yields_to_another_waiter(test_state) -> None: + # Bug caught: the lease starves the assistant, which waits for the GPU through queue_yields. + with test_state.generation.queue_yields(): + with _lease(test_state) as leased: + assert not leased + + +def test_the_lease_fails_when_the_local_lane_reports_busy(test_state) -> None: + # Bug caught: the lease ignores a running local job that has not taken the slot yet. + with _lease(test_state, local_lane_idle=False) as leased: + assert not leased + assert test_state.generation.try_reserve_generation_start() is True + test_state.generation.release_generation_start_reservation() + + +def test_the_lease_does_not_expire_during_a_long_rewrite(test_state, monkeypatch) -> None: + # Bug caught: a timed reservation expires mid-rewrite and a local job starts on the same GPU. + generation = test_state.generation + with _lease(test_state) as leased: + assert leased + assert generation.state.generation_starting_since is None + monkeypatch.setattr(time, "monotonic", lambda: 1e12) + assert generation.try_reserve_generation_start() is False + + +def test_a_denied_lease_never_blocks_the_caller(test_state) -> None: + # Bug caught: the lease waits for the slot and the fal job stalls behind a local job. + generation = test_state.generation + assert generation.try_reserve_generation_start(persistent=True) + finished = threading.Event() + + def lease() -> None: + with _lease(test_state): + pass + finished.set() + + threading.Thread(target=lease, daemon=True).start() + + assert finished.wait(timeout=2) + generation.release_generation_start_reservation() + + +@pytest.mark.parametrize("busy", [False, True]) +def test_a_granted_lease_evicts_the_diffusion_cache_and_a_denied_one_does_not( + test_state, monkeypatch, busy: bool +) -> None: + # Bug caught: a cancelled local video leaves its transformer cached, and Gemma loads next to it. + evictions: list[int] = [] + monkeypatch.setattr( + "handlers.generation_handler.diffusion_stage_cache.evict", lambda: evictions.append(1) + ) + + with _lease(test_state, local_lane_idle=not busy) as leased: + assert leased is (not busy) + + assert len(evictions) == (0 if busy else 1) + + +def test_the_lease_is_released_when_the_body_raises(test_state) -> None: + # Bug caught: a failed rewrite leaves the reservation held and no local job can start. + generation = test_state.generation + + with pytest.raises(RuntimeError, match="rewrite failed"): + with _lease(test_state) as leased: + assert leased + raise RuntimeError("rewrite failed") + + assert generation.try_reserve_generation_start() is True + generation.release_generation_start_reservation() + + +def test_the_lease_is_released_when_the_cache_eviction_fails(test_state, monkeypatch) -> None: + # Bug caught: evict() raises after the reservation was taken and the GPU stays reserved. + def broken_evict() -> None: + raise RuntimeError("evict failed") + + monkeypatch.setattr("handlers.generation_handler.diffusion_stage_cache.evict", broken_evict) + + with pytest.raises(RuntimeError, match="evict failed"): + with _lease(test_state): + pass + + assert test_state.generation.try_reserve_generation_start() is True + test_state.generation.release_generation_start_reservation() diff --git a/backend/tests/test_hf_model_card.py b/backend/tests/test_hf_model_card.py new file mode 100644 index 000000000..b3397e6a8 --- /dev/null +++ b/backend/tests/test_hf_model_card.py @@ -0,0 +1,162 @@ +"""What the custom LoRA form takes from a Hugging Face model card.""" + +from __future__ import annotations + +from api_types import CUSTOM_LORA_TRIGGER_MAX +from services.url_downloader.hf_model_card import parse_model_card + +_CARD = """--- +license: apache-2.0 +instance_prompt: InkW4sh +widget: + - text: a fox in InkW4sh style + - text: a koi pond, InkW4sh + - text: a mountain, InkW4sh + - text: a fourth example that is over the limit +--- + +# Ink Wash + +![preview](preview.png) + +This LoRA gives a [watercolor](https://example.com) ink wash look +with soft edges. + +## Usage +Use it with LTX. +""" + + +def test_the_card_gives_its_trigger_three_examples_and_first_paragraph() -> None: + suggestions = parse_model_card(_CARD) + + assert suggestions.trigger == "InkW4sh" + assert suggestions.examples == ( + "a fox in InkW4sh style", + "a koi pond, InkW4sh", + "a mountain, InkW4sh", + ) + assert suggestions.description == "This LoRA gives a watercolor ink wash look with soft edges." + + +def test_a_card_with_a_broken_yaml_header_gives_a_description_and_no_error() -> None: + for header in ( + "instance_prompt: [unclosed", + "date: 2023-02-30", + "nested: " + "[" * 2000 + "]" * 2000, + ): + suggestions = parse_model_card(f"---\n{header}\n---\n\nA soft look.\n") + assert suggestions.trigger is None + assert suggestions.examples == () + assert suggestions.description == "A soft look." + + +def test_a_trigger_longer_than_the_limit_is_dropped() -> None: + sentence = "a " * CUSTOM_LORA_TRIGGER_MAX + suggestions = parse_model_card(f"---\ninstance_prompt: {sentence}\n---\n") + + assert suggestions.trigger is None + + +def test_a_card_without_instance_prompt_gives_the_first_code_span_of_its_trigger_section() -> None: + card = """--- +library_name: diffusers +--- + +# Felt Cutout + +This LoRA makes a **felt cutout** look. + +## Recommended Trigger Words + +**Main trigger word:** + +- `F3ltCut0u7` + +**Other helpful trigger words:** + +- `felt cutout style` +""" + + suggestions = parse_model_card(card) + + assert suggestions.trigger == "F3ltCut0u7" + assert suggestions.description == "This LoRA makes a felt cutout look." + + +def _card(body: str) -> str: + return f"---\nlibrary_name: diffusers\n---\n\n{body}" + + +def test_trained_words_line_gives_the_first_item_and_drops_an_empty_or_over_long_value() -> None: + first = parse_model_card(_card("# Gollum\n\n**Base model**: LTXV 2.3\n**Trained words**: g0llum, a pale creature\n")) + phrase = parse_model_card(_card("# Pan\n\n**Trained words**: A 360-degree panoramic video\n")) + empty = parse_model_card(_card("# Anime\n\n**Base model**: LTXV 2.3\n**Trained words**: \n")) + too_long = parse_model_card(_card(f"# Face\n\n**Trained words**: {'word ' * 30}\n")) + + assert first.trigger == "g0llum" + assert phrase.trigger == "A 360-degree panoramic video" + assert empty.trigger is None + assert too_long.trigger is None + + +def test_trigger_sentences_give_the_word_without_quotes_or_a_trailing_comma() -> None: + cases = { + 'Trigger Word : "fx dance"': "fx dance", + "**Trigger word:** `crtanim,` (first token of every prompt).": "crtanim", + 'Trigger word "SPROUT"': "SPROUT", + } + + for line, expected in cases.items(): + assert parse_model_card(_card(f"# Title\n\n{line}\n")).trigger == expected, line + + +def test_trigger_heading_reads_a_code_block_or_quoted_item_and_the_first_value_wins() -> None: + block = parse_model_card(_card("## Trigger Word\n\n```text\nsrx_commercial\n```\n\n## Recommended Strength\n")) + quoted = parse_model_card( + _card("## Trigger Word\n\n- 'C6b4rP8nk'\n\n## Other Example triggers\n\n- `cinematic cyberpunk aesthetic`\n") + ) + intro = parse_model_card( + _card("## Recommended Trigger Words\n\nUse one or more of the following:\n\n- `claymation style`\n- `stop motion clay`\n") + ) + + assert block.trigger == "srx_commercial" + assert quoted.trigger == "C6b4rP8nk" + assert intro.trigger == "claymation style" + + +def test_no_trigger_word_and_a_note_under_a_trigger_table_give_no_trigger() -> None: + none = parse_model_card(_card("**No trigger word** — the LoRA is always active when loaded.\n")) + table = parse_model_card( + _card( + "### Trigger words\n\n| Register | Female |\n| --- | --- |\n| Whispering | `(woman, whispering)` |\n\n" + "> **Note:** Male whisper requires the extra word `quietly` to work.\n" + ) + ) + + assert none.trigger is None + assert table.trigger is None + + +def test_example_prompts_and_a_description_without_metadata_or_generated_boilerplate() -> None: + lines = parse_model_card( + _card( + '# Dance\n\nExample prompt : "fx dance figure made of honey"\n\n' + "This LoRA makes a figure dance.\n" + ) + ) + block = parse_model_card( + _card("# Real\n\n## Example prompts\n\n```text\none\ntwo\nthree\nfour\n```\n") + ) + muapi = parse_model_card( + _card("# Style\n\n**Base model**: LTXV 2.3\n**Trained words**: \n\n## Usage (Python)\n\nGet your key from the site.\n") + ) + generated = parse_model_card( + _card("\n\n# LoRA Finetune\n\n## Model description\n\nThis is a lora finetune of model: `Lightricks/LTX-Video`.\n") + ) + + assert lines.examples == ("fx dance figure made of honey",) + assert lines.description == "This LoRA makes a figure dance." + assert block.examples == ("one", "two", "three") + assert muapi.description == "" + assert generated.description == "" diff --git a/backend/tests/test_http.py b/backend/tests/test_http.py index 9bb087664..46aed385a 100644 --- a/backend/tests/test_http.py +++ b/backend/tests/test_http.py @@ -23,7 +23,9 @@ from services.unavailable_store import UnavailableStore from state import build_initial_state, set_state_service_for_tests from state.app_state_types import HfAuthenticated +from runtime_config.budget_admission import unmeasured_refusal_message from tests.conftest import TEST_ADMIN_TOKEN +from tests.fakes.generation import FakeJobSession, LocalLiveQueueControl from tests.http_error_assertions import assert_http_error @@ -38,6 +40,9 @@ def wake(self) -> None: def interrupt(self, generation_id: str, attempt_count: int) -> None: del generation_id, attempt_count + def live_state(self, generation_id: str) -> None: + del generation_id + def _png(path: Path, size: tuple[int, int] = (16, 16)) -> Path: Image.new("RGB", size, color=(1, 2, 3)).save(path) @@ -636,10 +641,7 @@ def test_create_audio_to_video_budgets_static_1080p_when_filter_drops_the_durati response, status_code=422, code="VIDEO_JOB_TOO_LARGE", - message=( - "This job needs 41.7 GB of GPU memory but this card has 31.0 GB. " - "Lower the resolution, duration, frame rate, or aspect width." - ), + message=unmeasured_refusal_message("windowed_range"), ) assert _store(test_state).list_generations("audio-to-video") == [] @@ -1606,10 +1608,10 @@ def test_queue_snapshot_lists_running_then_ranked_queued_work( assert response.status_code == 200, response.text body = response.json() - assert body["active"]["generation"]["id"] == running.id - assert body["active"]["generation"]["status"] == "running" - assert body["active"]["input_assets"][0]["id"] == input_asset.id - assert body["active"]["progress"] is None + assert body["active"][0]["generation"]["id"] == running.id + assert body["active"][0]["generation"]["status"] == "running" + assert body["active"][0]["input_assets"][0]["id"] == input_asset.id + assert body["active"][0]["progress"] is None assert [entry["generation"]["id"] for entry in body["queued"]] == [ third.id, second.id, @@ -1624,6 +1626,9 @@ def test_queue_snapshot_includes_progress_only_for_matching_active_id( ) -> None: with _reserved_generation_start(test_state): store = _store(test_state) + test_state.queued_generations._queue_control = LocalLiveQueueControl( + test_state.generation + ) active = store.insert_generation("text-to-video", _spec("active")) queued = store.insert_generation("text-to-video", _spec("queued")) claimed = store.claim_next_queued() @@ -1637,9 +1642,9 @@ def test_queue_snapshot_includes_progress_only_for_matching_active_id( matched = client.get("/api/generation-queue") assert unmatched.status_code == 200, unmatched.text - assert unmatched.json()["active"]["progress"] is None + assert unmatched.json()["active"][0]["progress"] is None assert matched.status_code == 200, matched.text - progress = matched.json()["active"]["progress"] + progress = matched.json()["active"][0]["progress"] assert progress == { "phase": "", "progress": 0, @@ -1668,8 +1673,8 @@ def test_queue_snapshot_keeps_cancelling_active_and_queued_without_progress( assert cancelled.json()["status"] == "cancelling" assert snapshot.status_code == 200, snapshot.text body = snapshot.json() - assert body["active"]["generation"]["id"] == active.id - assert body["active"]["generation"]["status"] == "cancelling" + assert body["active"][0]["generation"]["id"] == active.id + assert body["active"][0]["generation"]["status"] == "cancelling" assert body["queued"][0]["generation"]["id"] == queued.id assert body["queued"][0]["progress"] is None @@ -1688,7 +1693,7 @@ def test_http_reorder_moves_queued_generation_before_target(client, test_state) persisted = client.get("/api/generation-queue") assert reordered.status_code == 200, reordered.text - assert reordered.json()["active"] is None + assert reordered.json()["active"] == [] assert [entry["generation"]["id"] for entry in reordered.json()["queued"]] == [ first.id, third.id, @@ -1702,6 +1707,9 @@ def test_http_reorder_returns_post_mutation_queue_snapshot( ) -> None: with _reserved_generation_start(test_state): store = _store(test_state) + test_state.queued_generations._queue_control = LocalLiveQueueControl( + test_state.generation + ) input_asset = store.ingest_upload(str(_png(tmp_path / "start.png"))) running = store.insert_generation( "image-to-video", @@ -1731,10 +1739,10 @@ def test_http_reorder_returns_post_mutation_queue_snapshot( assert reordered.status_code == 200, reordered.text body = reordered.json() assert "id" not in body - assert body["active"]["generation"]["id"] == running.id - assert body["active"]["generation"]["status"] == "running" - assert body["active"]["input_assets"][0]["id"] == input_asset.id - assert body["active"]["progress"] == { + assert body["active"][0]["generation"]["id"] == running.id + assert body["active"][0]["generation"]["status"] == "running" + assert body["active"][0]["input_assets"][0]["id"] == input_asset.id + assert body["active"][0]["progress"] == { "phase": "", "progress": 0, "currentStep": None, @@ -2383,6 +2391,7 @@ def test_handler_construction_does_not_fail_running_generations(test_state) -> N preflight_edit_matrix=lambda **kwargs: None, # type: ignore[return-value] preflight_queued_ic_lora_recipe=lambda **kwargs: None, preflight_queued_synthesized_ic_lora=lambda **kwargs: None, + preflight_ic_lora_tile_sizes=lambda **kwargs: None, # type: ignore[return-value] ) loaded = store.get_generation(generation.id) assert loaded is not None @@ -2455,7 +2464,7 @@ def test_i2v_executor_uses_store_rebound_by_app_handler( with pytest.raises( ValueError, match="text-to-video requires a single 'output' allocation" ): - executor.execute(generation, ()) + executor.execute(generation, (), FakeJobSession()) def test_boot_recovery_fallback_rebinds_i2v_asset_resolver( @@ -2479,7 +2488,7 @@ def test_boot_recovery_fallback_rebinds_i2v_asset_resolver( executor = handler.executor_registry.get("image-to-video") with pytest.raises(UnavailableError): - executor.execute(generation, ()) + executor.execute(generation, (), FakeJobSession()) def test_boot_recovery_failure_replaces_handler_and_queue_store( diff --git a/backend/tests/test_http_client_cap.py b/backend/tests/test_http_client_cap.py new file mode 100644 index 000000000..c85d841a9 --- /dev/null +++ b/backend/tests/test_http_client_cap.py @@ -0,0 +1,159 @@ +"""HTTPClientImpl.get with max_bytes, against a real local server. + +A fake cannot show that the cap stops the read, so these tests use a real socket. +""" + +from __future__ import annotations + +from collections.abc import Iterator +from contextlib import contextmanager +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +import threading +import time + +import pytest + +from services.http_client import ( + HttpBodyTooLargeError, + HttpRedirectRefusedError, + HttpTransportError, +) +from services.http_client.http_client_impl import HTTPClientImpl, _redirect_target + +_BODY = b"x" * 1000 + + +class _Handler(BaseHTTPRequestHandler): + def do_GET(self) -> None: # noqa: N802 + port = self.server.server_address[1] + redirects = { + "/redir": "/ok", + "/loop": "/loop", + "/slow-hop-1": "/slow-hop-2", + "/slow-hop-2": "/slow-hop-3", + "/slow-hop-3": "/ok", + "/other-host": f"http://localhost:{port}/echo-auth", + } + if self.path.startswith("/slow-hop"): + # Each hop answers inside a timeout of 1 second. Together they do not. + time.sleep(0.6) + if self.path in redirects: + self.send_response(302) + self.send_header("Location", redirects[self.path]) + self.end_headers() + return + if self.path == "/echo-auth": + echoed = self.headers.get("Authorization", "none").encode() + self.send_response(200) + self.send_header("Content-Length", str(len(echoed))) + self.end_headers() + self.wfile.write(echoed) + return + if self.path == "/slow": + # No Content-Length and a body that arrives in pieces over more than the deadline. + self.send_response(200) + self.end_headers() + for _ in range(6): + self.wfile.write(b"x") + self.wfile.flush() + time.sleep(0.4) + return + self.send_response(404 if self.path == "/missing" else 200) + # /chunked sends no Content-Length, so only the chunk counter can stop it. + if self.path != "/chunked": + self.send_header("Content-Length", str(len(_BODY))) + self.end_headers() + self.wfile.write(_BODY) + + def log_message(self, format: str, *args: object) -> None: # noqa: A002 + del format, args + + +@contextmanager +def _server() -> Iterator[str]: + server = ThreadingHTTPServer(("127.0.0.1", 0), _Handler) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + yield f"http://127.0.0.1:{server.server_address[1]}" + finally: + server.shutdown() + server.server_close() + + +def test_a_body_under_the_cap_is_returned_whole() -> None: + # Bug caught: the capped read drops or truncates a normal image. + with _server() as base: + response = HTTPClientImpl().get(f"{base}/ok", max_bytes=2000) + + assert response.status_code == 200 + assert response.content == _BODY + + +def test_a_declared_length_over_the_cap_is_refused() -> None: + # Bug caught: the cap checks only after the whole body is read. + with _server() as base, pytest.raises(HttpBodyTooLargeError): + HTTPClientImpl().get(f"{base}/ok", max_bytes=999) + + +def test_a_body_with_no_declared_length_is_cut_at_the_cap() -> None: + # Bug caught: a server that hides Content-Length avoids the cap. + with _server() as base, pytest.raises(HttpBodyTooLargeError): + HTTPClientImpl().get(f"{base}/chunked", max_bytes=999) + + +def test_an_error_status_is_returned_with_its_status() -> None: + # Bug caught: the buffered response loses the status, so a 404 reads as an image. + with _server() as base: + response = HTTPClientImpl().get(f"{base}/missing", max_bytes=2000) + + assert response.status_code == 404 + + +def test_a_redirect_is_followed_to_the_body() -> None: + # Bug caught: the hand-made redirect loop returns the 302 instead of the image. + with _server() as base: + response = HTTPClientImpl().get(f"{base}/redir", max_bytes=2000) + + assert response.status_code == 200 + assert response.content == _BODY + + +def test_a_redirect_loop_is_refused() -> None: + # Bug caught: a server that redirects forever holds the download thread (CWE-770). + with _server() as base, pytest.raises(HttpRedirectRefusedError): + HTTPClientImpl().get(f"{base}/loop", max_bytes=2000) + + +def test_the_credential_header_stays_on_the_first_host() -> None: + # Bug caught: a redirect to another host receives the Authorization header (CWE-200). + headers = {"Authorization": "Key "} + with _server() as base: + same_host = HTTPClientImpl().get(f"{base}/echo-auth", headers=headers, max_bytes=2000) + other_host = HTTPClientImpl().get(f"{base}/other-host", headers=headers, max_bytes=2000) + + assert same_host.content == b"Key " + assert other_host.content == b"none" + + +def test_a_redirect_from_https_to_http_is_refused() -> None: + # Bug caught: a fal URL on https sends the download to a plain-http host (CWE-918). + with pytest.raises(HttpRedirectRefusedError): + _redirect_target("https://fal.example/a.png", "http://evil.example/a.png") + assert _redirect_target("https://fal.example/a.png", "/b.png") == "https://fal.example/b.png" + assert _redirect_target("http://fal.example/a.png", "https://fal.example/a.png") + + +def test_a_body_that_arrives_slowly_hits_the_total_deadline() -> None: + # Bug caught: each read is fast, so the per-read timeout never fires and the call never ends. + with _server() as base, pytest.raises(HttpTransportError): + HTTPClientImpl().get(f"{base}/slow", timeout=1, max_bytes=2000) + + +def test_redirect_hops_share_one_deadline() -> None: + # Bug caught: every hop gets the full timeout, so a chain of slow hops runs for a multiple of it. + started = time.monotonic() + with _server() as base, pytest.raises(HttpTransportError): + HTTPClientImpl().get(f"{base}/slow-hop-1", timeout=1, max_bytes=2000) + + assert time.monotonic() - started < 1.5 diff --git a/backend/tests/test_http_error_responses.py b/backend/tests/test_http_error_responses.py index 1669b2898..8388624eb 100644 --- a/backend/tests/test_http_error_responses.py +++ b/backend/tests/test_http_error_responses.py @@ -13,6 +13,7 @@ def test_validation_errors_use_http_error_response(client): payload = response.json() assert payload["code"] == "HTTP_422" assert "Field required" in payload["message"] + assert 'File "' not in payload["message"] def test_unhandled_exceptions_use_http_error_response(test_state, monkeypatch): diff --git a/backend/tests/test_ic_lora_adaptive_budget.py b/backend/tests/test_ic_lora_adaptive_budget.py new file mode 100644 index 000000000..3aa8e81a1 --- /dev/null +++ b/backend/tests/test_ic_lora_adaptive_budget.py @@ -0,0 +1,99 @@ +"""The job budget chooses the window of an adaptive LoRA (Refine Details) before the job starts.""" + +from __future__ import annotations + +import pytest + +from runtime_config.ic_lora_high_res import high_res_tiling +from runtime_config.ic_lora_job_budget import ( + WINDOW_OVER_CAP_MESSAGE, + IcLoraJobLoad, + IcLoraJobReject, + decide_ic_lora_job, + dropped_duration_message_and_code, +) +from runtime_config.ic_lora_stage_mode import IcLoraStageMode +from runtime_config.ic_lora_tiling import IcLoraTiling, with_tiling_overrides +from tests.test_video_job_budget import _windows_measured_filter + +_BASE = IcLoraTiling(long_side=1024, short_side=576, adaptive_window=True) +_270P = (480, 256) +_720P = (1280, 704) +_1080P = (1920, 1088) +_4K = (3840, 2112) + + +def _decide(size: tuple[int, int], frames: int, vram_gib: float, tiling: IcLoraTiling = _BASE): + return decide_ic_lora_job( + *size, + frames, + stage_mode=IcLoraStageMode.SINGLE_STAGE, + job_filter=_windows_measured_filter(vram_gib, 64), + tiling=tiling, + ).priced.decision + + +def _window(decision: object) -> int | None: + assert isinstance(decision, IcLoraJobLoad), decision + return decision.chunk_pixel_frames + + +@pytest.mark.parametrize("size", [_270P, _720P]) +def test_a_low_resolution_clip_runs_in_one_pass_when_the_budget_admits_it(size: tuple[int, int]) -> None: + # The former 73-frame window chunked a 270p clip longer than 73 frames. + assert _window(_decide(size, 241, 24)) is None + + +def test_a_low_resolution_clip_takes_a_window_above_97_when_one_pass_does_not_fit() -> None: + window = _window(_decide(_720P, 241, 14)) + assert window is not None + assert 97 < window < 241 + assert (window - 1) % 8 == 0 + + +def test_1080p_runs_a_short_clip_in_one_pass_and_a_long_one_in_97_frame_windows() -> None: + assert _window(_decide(_1080P, 49, 24)) is None + assert _window(_decide(_1080P, 241, 24)) == 97 + + +def test_4k_never_passes_73_frames_and_the_decode_check_can_go_lower() -> None: + assert _window(_decide(_4K, 137, 48, high_res_tiling(_BASE))) == 73 + assert _window(_decide(_4K, 137, 31.84, high_res_tiling(_BASE))) == 49 + + +def test_a_user_maximum_is_the_longest_window_the_walk_tries() -> None: + capped = with_tiling_overrides(_BASE, overlap_fraction=None, carry_frames=None, max_window_frames=57) + assert capped.max_window_frames == 57 + assert capped.window_frames is None # a fixed window would chunk every clip, so it is not set + assert _window(_decide(_1080P, 241, 24, capped)) == 57 + + +def test_a_maximum_above_the_cap_of_the_resolution_is_refused_not_run_shorter() -> None: + # The run's overrides come after the high-cell plan, as in ``_resolve_settings``. + tiling = with_tiling_overrides( + high_res_tiling(_BASE), overlap_fraction=None, carry_frames=None, max_window_frames=97 + ) + decision = _decide(_4K, 137, 48, tiling) + assert isinstance(decision, IcLoraJobReject) + assert decision.reason == "window_over_cap" + message, _ = dropped_duration_message_and_code(decision, _windows_measured_filter(48, 64)) + assert message == WINDOW_OVER_CAP_MESSAGE + # The same maximum runs at 1080p. + assert _window(_decide(_1080P, 137, 24, tiling)) == 97 + + +def test_an_adaptive_high_cell_stays_adaptive_and_gets_no_fixed_window() -> None: + tiling = high_res_tiling(_BASE) + assert tiling.adaptive_window + assert tiling.window_frames is None + assert tiling.carry_frames == 17 + + +def test_a_maximum_must_be_more_than_twice_the_carry() -> None: + with pytest.raises(ValueError, match="more than twice the carry"): + with_tiling_overrides(_BASE, overlap_fraction=None, carry_frames=33, max_window_frames=57) + + +def test_a_maximum_above_97_is_refused() -> None: + with pytest.raises(ValueError, match="cannot exceed 97"): + with_tiling_overrides(_BASE, overlap_fraction=None, carry_frames=None, max_window_frames=105) diff --git a/backend/tests/test_ic_lora_adaptive_window.py b/backend/tests/test_ic_lora_adaptive_window.py new file mode 100644 index 000000000..e5d90f219 --- /dev/null +++ b/backend/tests/test_ic_lora_adaptive_window.py @@ -0,0 +1,67 @@ +"""Adaptive chunk window of Refine Details: the resolution cap and the candidate list.""" + +from __future__ import annotations + +import pytest + +from runtime_config.ic_lora_adaptive_window import ( + adaptive_window_candidates, + resolution_window_cap, +) +from runtime_config.ic_lora_tiling import ADAPTIVE_MAX_WINDOW_FRAMES, _CONTROLS # pyright: ignore[reportPrivateUsage] + + +@pytest.mark.parametrize( + ("width", "height", "cap"), + [ + (480, 256, None), + (1280, 704, None), + (1920, 1088, 97), + (2560, 1440, 97), + (3840, 2112, 73), + ], +) +def test_resolution_cap(width: int, height: int, cap: int | None) -> None: + assert resolution_window_cap(width, height) == cap + + +def test_the_window_presets_of_the_form_stay_within_the_longest_maximum() -> None: + presets = _CONTROLS["windowFrames"]["presets"] + assert max(presets) == ADAPTIVE_MAX_WINDOW_FRAMES + + +def test_a_short_clip_runs_in_one_pass_only() -> None: + assert adaptive_window_candidates(49, cap=None, user_max=None, carry=25) == [None] + + +def test_an_uncapped_clip_tries_one_pass_then_every_window_below_it() -> None: + candidates = adaptive_window_candidates(241, cap=None, user_max=None, carry=25) + assert candidates[:3] == [None, 233, 225] + assert candidates[-1] == 57 # shortest window for a carry of 25 + assert all(window is None or (window - 1) % 8 == 0 for window in candidates) + + +def test_a_cap_below_the_clip_removes_the_one_pass_candidate() -> None: + candidates = adaptive_window_candidates(241, cap=97, user_max=None, carry=25) + assert candidates[:3] == [97, 89, 81] + assert None not in candidates + + +def test_a_clip_inside_the_cap_still_offers_shorter_windows_after_one_pass() -> None: + assert adaptive_window_candidates(73, cap=97, user_max=None, carry=25) == [None, 65, 57] + + +def test_4k_walk_starts_at_the_cap() -> None: + assert adaptive_window_candidates(137, cap=73, user_max=None, carry=17) == [73, 65, 57, 49, 41] + + +def test_a_user_maximum_below_the_cap_lowers_the_start() -> None: + assert adaptive_window_candidates(241, cap=97, user_max=65, carry=17)[:2] == [65, 57] + + +def test_a_user_maximum_above_the_clip_keeps_one_pass() -> None: + assert adaptive_window_candidates(49, cap=None, user_max=97, carry=17)[0] is None + + +def test_a_cap_under_the_shortest_window_leaves_no_candidate() -> None: + assert adaptive_window_candidates(241, cap=73, user_max=None, carry=41) == [] diff --git a/backend/tests/test_ic_lora_auto_carry.py b/backend/tests/test_ic_lora_auto_carry.py new file mode 100644 index 000000000..e7aa9e323 --- /dev/null +++ b/backend/tests/test_ic_lora_auto_carry.py @@ -0,0 +1,118 @@ +"""Auto carry: the job budget picks the carry with the window, and never a worse run than a fixed carry.""" + +from __future__ import annotations + +import pytest + +from runtime_config.budget_admission import Admitted, PricedJob, RiskAllowance, admit, safety_rank +from runtime_config.ic_lora_auto_carry import picked_carry_tiling +from runtime_config.ic_lora_high_res import high_res_tiling +from runtime_config.ic_lora_job_budget import price_ic_lora_job +from runtime_config.ic_lora_stage_mode import IcLoraStageMode +from runtime_config.ic_lora_tiling import ( + CARRY_PRESETS, + IcLoraTiling, + auto_carry_candidates, + with_tiling_overrides, +) +from tests.test_video_job_budget import _windows_measured_filter + +_BASE = IcLoraTiling(long_side=1024, short_side=576, adaptive_window=True) +_CELLS: dict[str, tuple[tuple[int, int], IcLoraTiling]] = { + "720p": ((1280, 704), _BASE), + "1080p": ((1920, 1088), _BASE), + "1440p": ((2560, 1440), high_res_tiling(_BASE)), + "2160p": ((3840, 2112), high_res_tiling(_BASE)), +} +_VRAM_GIB = (8, 10, 13.25, 16, 24, 48) +_FRAMES = (97, 241) + + +def _price(cell: str, vram_gib: float, frames: int, tiling: IcLoraTiling | None = None) -> PricedJob: + size, cell_tiling = _CELLS[cell] + return price_ic_lora_job( + *size, + frames, + stage_mode=IcLoraStageMode.SINGLE_STAGE, + job_filter=_windows_measured_filter(vram_gib, 64), + ic_lora_id="refine-details", + stills=0, + tiling=cell_tiling if tiling is None else tiling, + ) + + +def _pinned(tiling: IcLoraTiling, carry: int) -> IcLoraTiling: + return tiling.model_copy(update={"carry_frames": carry, "carry_pinned": True}) + + +def test_the_candidates_are_the_presets_up_to_the_carry_of_the_cell() -> None: + assert auto_carry_candidates(25, None) == [25, 17] + assert auto_carry_candidates(17, None) == [17] + assert auto_carry_candidates(33, None) == [33, 25, 17] + + +def test_a_chunk_length_pins_the_candidates_it_can_run_with() -> None: + # A chunk length must be more than twice the carry. + assert auto_carry_candidates(25, 41) == [17] + assert auto_carry_candidates(25, 57) == [25, 17] + + +def test_a_chunk_length_the_default_carry_cannot_run_starts_auto_from_a_shorter_carry() -> None: + tiling = with_tiling_overrides(_BASE, overlap_fraction=None, carry_frames=None, max_window_frames=41) + assert tiling.auto_carry + assert tiling.carry_frames == 17 + + +def test_a_carry_the_run_chose_is_pinned_and_never_searched() -> None: + tiling = with_tiling_overrides(_BASE, overlap_fraction=None, carry_frames=25, max_window_frames=None) + assert tiling.carry_pinned + assert not tiling.auto_carry + assert _price("1080p", 16, 241, tiling).carry_frames is None + + +def test_auto_takes_the_short_carry_when_only_it_runs_clean() -> None: + # At 1080p on 10 GiB the 57-frame shortest window of carry 25 is a bet. Carry 17 lets a 41-frame window run clean. + auto = _price("1080p", 10, 241) + assert auto.carry_frames == 17 + assert safety_rank(auto) == 3 + assert auto.decision.chunk_pixel_frames == 41 + assert safety_rank(_price("1080p", 10, 241, _pinned(_BASE, 25))) < 3 + + +@pytest.mark.parametrize("cell", list(_CELLS)) +@pytest.mark.parametrize("vram_gib", _VRAM_GIB) +@pytest.mark.parametrize("frames", _FRAMES) +def test_auto_is_never_less_safe_than_any_carry_it_may_pick(cell: str, vram_gib: float, frames: int) -> None: + auto = _price(cell, vram_gib, frames) + tiling = _CELLS[cell][1] + fixed = [ + _price(cell, vram_gib, frames, _pinned(tiling, carry)) + for carry in auto_carry_candidates(tiling.carry_frames or 25, None) + ] + assert auto.carry_frames in CARRY_PRESETS + assert safety_rank(auto) >= max(safety_rank(priced) for priced in fixed) + + +@pytest.mark.parametrize("cell", list(_CELLS)) +@pytest.mark.parametrize("vram_gib", _VRAM_GIB) +def test_cautious_never_runs_a_bet_from_auto(cell: str, vram_gib: float) -> None: + admission = admit(_price(cell, vram_gib, 241), RiskAllowance.for_mode("cautious")) + assert not isinstance(admission, Admitted) or admission.risk is None + + +def test_brave_runs_the_unmeasured_cell_as_a_bet_and_cautious_refuses_it() -> None: + priced = _price("2160p", 48, 137) + brave = admit(priced, RiskAllowance.for_mode("brave")) + assert isinstance(brave, Admitted) + assert brave.risk is not None + assert brave.risk.tier == "unmeasured" + assert not isinstance(admit(priced, RiskAllowance.for_mode("cautious")), Admitted) + + +def test_the_run_tiling_takes_the_carry_auto_picked() -> None: + priced = _price("1080p", 10, 241) + run = picked_carry_tiling(_BASE, priced) + assert run is not None + assert run.carry_frames == 17 + assert run.carry_pinned + assert picked_carry_tiling(_BASE, _price("1080p", 16, 241, _pinned(_BASE, 25))) == _BASE diff --git a/backend/tests/test_ic_lora_decode_window.py b/backend/tests/test_ic_lora_decode_window.py index 1e0eb6e9d..4f858d2a2 100644 --- a/backend/tests/test_ic_lora_decode_window.py +++ b/backend/tests/test_ic_lora_decode_window.py @@ -50,9 +50,11 @@ def test_budget_shrinks_as_windows_pile_up_and_saturates() -> None: assert budgets[2] <= 20.9 -def _choose(frames: int, window: int | None, size: tuple[int, int], vram: float = _RTX_5090_GIB): +def _choose( + frames: int, window: int | None, size: tuple[int, int], vram: float = _RTX_5090_GIB, carry: int = 17 +): return choose_decode_window( - frames=frames, window=window, width=size[0], height=size[1], total_vram_gib=vram, carry_frames=17 + frames=frames, window=window, width=size[0], height=size[1], total_vram_gib=vram, carry_frames=carry ) @@ -62,6 +64,14 @@ def test_4k_73_frame_windows_do_not_fit_a_third_window_on_a_5090() -> None: assert choice.window == 49 +def test_4k_cap_under_the_shortest_window_of_a_long_carry_refuses_instead_of_running_it() -> None: + # A carry of 41 needs a window of 89 frames or more. The 4K cap of 73 breaks that, even + # on a card with memory to spare. + assert not _choose(300, 97, _4K, vram=80, carry=41).fits + assert not _choose(300, None, _4K, vram=80, carry=41).fits + assert _choose(300, 97, _4K, vram=80, carry=17).fits + + def test_4k_longer_clips_keep_the_same_window() -> None: assert _choose(241, 73, _4K).window == 49 @@ -96,6 +106,25 @@ def test_1440p_keeps_a_97_frame_window() -> None: assert choice.window == 97 +def test_1440p_budget_leaves_room_for_41f_and_steps_73f_or_97f_down_to_41f_on_16gb() -> None: + """C2/C3 measured 12.8–15.0 GiB decode budget under a 16.0 GiB cap at 1440p; + using the 4K 11.0 GiB reserve would refuse 1440p 41f (need+margin 11.02 > 5.0) + and fail to step 73f/97f down to 41f on 16 GB cards.""" + assert decode_budget_gib(16.0, 5, width=2560, height=1472) == pytest.approx(11.20) + assert decode_budget_gib(15.9, 5, width=2560, height=1472) == pytest.approx(11.10) + for vram in (16.0, 15.9): + water = _choose(137, 41, _1440P, vram=vram) + assert water.fits + assert water.window == 41 + refine = _choose(241, 73, _1440P, vram=vram) + assert refine.fits + assert refine.window == 41 + restore = _choose(137, 97, _1440P, vram=vram) + assert restore.fits + assert restore.window == 41 + + + def test_no_window_fits_a_card_with_too_little_memory() -> None: choice = _choose(137, 73, _4K, vram=24) assert not choice.fits diff --git a/backend/tests/test_ic_lora_generate.py b/backend/tests/test_ic_lora_generate.py index 56009c23f..25611f769 100644 --- a/backend/tests/test_ic_lora_generate.py +++ b/backend/tests/test_ic_lora_generate.py @@ -6,7 +6,6 @@ from PIL import Image from frame_math import compute_num_frames -from runtime_config.ic_lora_job_budget import TWO_STAGE_OVER_MEASURED_MESSAGE from runtime_config.ic_lora_local_envelope import IC_LORA_SOURCE_TOO_LARGE, IC_LORA_V1_ENVELOPE_MESSAGE from runtime_config.video_job_budget import ( LOCAL_GENERATION_UNSUPPORTED, @@ -1013,7 +1012,7 @@ def test_ic_lora_fps_override_budgets_resampled_frames( assert fake_services.ic_lora_pipeline.last_streaming_prefetch_count == 2 -def test_ic_lora_two_stage_over_priced_ceiling_fenced_before_budget( +def test_ic_lora_two_stage_past_priced_ceiling_refuses_with_curve_figures( client: TestClient, tmp_path: Path, create_fake_model_files, @@ -1022,11 +1021,12 @@ def test_ic_lora_two_stage_over_priced_ceiling_fenced_before_budget( test_state, ): """Two-stage past the 14,880-token ceiling (1920x1080 source -> 960x512 - stage-1 x 481 frames = 29,280 tokens): a 20s two-stage job 422s with the - fence message even where the budget would pass it (31 GB legacy).""" + stage-1 x 481 frames = 29,280 tokens) is priced on the curve, not fenced: + Cautious 422s with the figures it compared before the pipeline loads.""" create_fake_model_files() create_fake_ic_lora_files() test_state.config.vram_gb = 31 + test_state.state.app_settings.budget_mode = "cautious" src = tmp_path / "clip.mp4" src.write_bytes(b"\x00" * 100) frames = compute_num_frames(20, 24) @@ -1045,7 +1045,10 @@ def test_ic_lora_two_stage_over_priced_ceiling_fenced_before_budget( fenced, status_code=422, code=VIDEO_JOB_TOO_LARGE, - message=TWO_STAGE_OVER_MEASURED_MESSAGE, + message=( + "This job needs 40.0 GB of GPU memory but this card has 31.0 GB. " + "Lower the resolution, duration, frame rate, or aspect width." + ), ) assert fake_services.ic_lora_pipeline.create_count == 0 single_stage = client.post( diff --git a/backend/tests/test_ic_lora_high_res_budget.py b/backend/tests/test_ic_lora_high_res_budget.py index c0dbe6864..6d1011645 100644 --- a/backend/tests/test_ic_lora_high_res_budget.py +++ b/backend/tests/test_ic_lora_high_res_budget.py @@ -2,25 +2,34 @@ from __future__ import annotations +from runtime_config.budget_admission import Admitted, RiskAllowance +from runtime_config.budget_decision import IcLoraJobLoad, IcLoraJobReject, VideoJobReject from runtime_config.ic_lora_high_res import high_res_tiling -from runtime_config.ic_lora_job_budget import IcLoraJobLoad, IcLoraJobReject, decide_ic_lora_job +from runtime_config.ic_lora_job_budget import decide_ic_lora_job from runtime_config.ic_lora_stage_mode import IcLoraStageMode from runtime_config.ic_lora_tiling import IcLoraTiling from runtime_config.measured_cells import MEASURED_HIGH_RES_CELLS -from runtime_config.video_job_budget import VideoJobReject from tests.test_video_job_budget import _windows_measured_filter _4K = (3840, 2176) +_1440P = (2560, 1472) _FRAMES_10S = 233 +def _verdict(admission): + return admission.load if isinstance(admission, Admitted) else admission.reject + + def _decide_4k(vram_gib: float, tiling: IcLoraTiling): - return decide_ic_lora_job( - *_4K, - _FRAMES_10S, - stage_mode=IcLoraStageMode.SINGLE_STAGE, - job_filter=_windows_measured_filter(vram_gib, 64), - tiling=tiling, + return _verdict( + decide_ic_lora_job( + *_4K, + _FRAMES_10S, + stage_mode=IcLoraStageMode.SINGLE_STAGE, + job_filter=_windows_measured_filter(vram_gib, 64), + tiling=tiling, + allowance=RiskAllowance.none(), + ) ) @@ -50,12 +59,15 @@ def test_4k_ten_second_job_is_refused_on_a_card_below_its_ask() -> None: def _decide_4k_frames(frames: int): - return decide_ic_lora_job( - *_4K, - frames, - stage_mode=IcLoraStageMode.SINGLE_STAGE, - job_filter=_windows_measured_filter(64, 64), - tiling=high_res_tiling(None), + return _verdict( + decide_ic_lora_job( + *_4K, + frames, + stage_mode=IcLoraStageMode.SINGLE_STAGE, + job_filter=_windows_measured_filter(64, 64), + tiling=high_res_tiling(None), + allowance=RiskAllowance.none(), + ) ) @@ -69,17 +81,43 @@ def test_iclora_4k_row_loads_at_10_windows_and_refuses_at_11() -> None: assert past_row.reason == "unmeasured_cell" +def _decide_1440p_frames(frames: int): + return _verdict( + decide_ic_lora_job( + *_1440P, + frames, + stage_mode=IcLoraStageMode.SINGLE_STAGE, + job_filter=_windows_measured_filter(64, 64), + tiling=high_res_tiling(None), + allowance=RiskAllowance.none(), + ) + ) + + +def test_iclora_1440p_row_loads_at_5_windows_and_refuses_at_6() -> None: + # 137 frames is 5 windows of 41 (measured); 161 is 6. The 1440p row must not inherit + # the 4K row's 10 windows or the Fast 1440p row's 9. + assert MEASURED_HIGH_RES_CELLS[("iclora", "windows_measured", "1440p")] == 5 + assert isinstance(_decide_1440p_frames(137), IcLoraJobLoad) + past_row = _decide_1440p_frames(161) + assert isinstance(past_row, VideoJobReject) + assert past_row.reason == "unmeasured_cell" + + _4K_REFINE = (3840, 2112) _REFINE_TILING = high_res_tiling(IcLoraTiling(long_side=1024, short_side=576, window_frames=73)) def _decide_refine_4k(vram_gib: float, frames: int): - return decide_ic_lora_job( - *_4K_REFINE, - frames, - stage_mode=IcLoraStageMode.SINGLE_STAGE, - job_filter=_windows_measured_filter(vram_gib, 64), - tiling=_REFINE_TILING, + return _verdict( + decide_ic_lora_job( + *_4K_REFINE, + frames, + stage_mode=IcLoraStageMode.SINGLE_STAGE, + job_filter=_windows_measured_filter(vram_gib, 64), + tiling=_REFINE_TILING, + allowance=RiskAllowance.none(), + ) ) @@ -108,3 +146,218 @@ def test_refine_4k_keeps_its_catalog_window_on_a_card_with_room() -> None: decision = _decide_refine_4k(48, 137) assert isinstance(decision, IcLoraJobLoad) assert decision.chunk_pixel_frames == 73 + + +def test_1440p_tiled_high_res_loads_on_16gb_cards_for_41f_and_stepped_down_refine() -> None: + """C2 (9.79 GiB @ 16g cap) and C3/N2 (11.67 GiB @ 16g cap) proved 1440p 41f + fits 16 GB cards (ask 11.50 GiB at 2w, 13.36 GiB at 3+w); flat 1.75*Mpx + priced 1440p Water Simulation at 20.32 GiB and refused 16 GB cards.""" + water_2w = _verdict( + decide_ic_lora_job( + *_1440P, + 57, + stage_mode=IcLoraStageMode.SINGLE_STAGE, + job_filter=_windows_measured_filter(15.9, 64, free_gib=15.0), + tiling=high_res_tiling(None), + allowance=RiskAllowance.none(), + ) + ) + assert isinstance(water_2w, IcLoraJobLoad) + assert water_2w.chunk_pixel_frames == 41 + + water_5w = _verdict( + decide_ic_lora_job( + *_1440P, + 137, + stage_mode=IcLoraStageMode.SINGLE_STAGE, + job_filter=_windows_measured_filter(15.9, 64, free_gib=15.0), + tiling=high_res_tiling(None), + allowance=RiskAllowance.none(), + ) + ) + assert isinstance(water_5w, IcLoraJobLoad) + assert water_5w.chunk_pixel_frames == 41 + + # On a 16 GB card, 1440p Refine Details steps 73f down to 41f and fits at 13.36 GiB. + refine_16g = _verdict( + decide_ic_lora_job( + *_1440P, + 113, + stage_mode=IcLoraStageMode.SINGLE_STAGE, + job_filter=_windows_measured_filter(15.9, 64, free_gib=15.0), + ic_lora_id="refine-details", + tiling=_REFINE_TILING, + allowance=RiskAllowance.none(), + ) + ) + assert isinstance(refine_16g, IcLoraJobLoad) + assert refine_16g.chunk_pixel_frames == 41 + + +def test_long_window_tiled_refine_1440p_and_4k_never_under_ask_measured_peaks() -> None: + """T2 (1440p 241f 4w x 73f) peaked at 17.10 GiB and T3 (4K 137f 4w x 49f) + peaked at 25.51 GiB: the old 9.90 + 1.75*Mpx curve under-asked T2 at 16.49 GiB + and T3 at 23.50 GiB.""" + t2_short = _verdict( + decide_ic_lora_job( + *_1440P, + 241, + stage_mode=IcLoraStageMode.SINGLE_STAGE, + job_filter=_windows_measured_filter(24, 64, free_gib=17.10), + ic_lora_id="refine-details", + tiling=_REFINE_TILING, + allowance=RiskAllowance.none(), + ) + ) + assert isinstance(t2_short, VideoJobReject) + assert t2_short.reason == "stream_over" + + t2_fits = _verdict( + decide_ic_lora_job( + *_1440P, + 241, + stage_mode=IcLoraStageMode.SINGLE_STAGE, + job_filter=_windows_measured_filter(24, 64, free_gib=18.80), + ic_lora_id="refine-details", + tiling=_REFINE_TILING, + allowance=RiskAllowance.none(), + ) + ) + assert isinstance(t2_fits, IcLoraJobLoad) + assert t2_fits.chunk_pixel_frames == 73 + + t3_short = _verdict( + decide_ic_lora_job( + *_4K, + 137, + stage_mode=IcLoraStageMode.SINGLE_STAGE, + job_filter=_windows_measured_filter(31.84, 64, free_gib=25.51), + tiling=_REFINE_TILING, + allowance=RiskAllowance.none(), + ) + ) + assert isinstance(t3_short, VideoJobReject) + assert t3_short.reason == "stream_over" + + t3_fits = _verdict( + decide_ic_lora_job( + *_4K, + 137, + stage_mode=IcLoraStageMode.SINGLE_STAGE, + job_filter=_windows_measured_filter(31.84, 64, free_gib=26.30), + tiling=_REFINE_TILING, + allowance=RiskAllowance.none(), + ) + ) + assert isinstance(t3_fits, IcLoraJobLoad) + assert t3_fits.chunk_pixel_frames == 49 + + +def test_4k_square_tiled_prices_on_canvas_window_tokens_and_loads_on_16gb() -> None: + """N1 (2176x2176 x 97f, 4 windows of 41f) peaked at 14.12 GiB: pricing on + canvas-window tokens asks 15.45 GiB, whereas 13.72 + 1.75*Mpx asked 22.00 GiB.""" + n1_short = _verdict( + decide_ic_lora_job( + 2176, + 2176, + 97, + stage_mode=IcLoraStageMode.SINGLE_STAGE, + job_filter=_windows_measured_filter(24.0, 64, free_gib=15.44), + tiling=high_res_tiling(None), + allowance=RiskAllowance.none(), + ) + ) + assert isinstance(n1_short, VideoJobReject) + assert n1_short.reason == "stream_over" + + n1_fits = _verdict( + decide_ic_lora_job( + 2176, + 2176, + 97, + stage_mode=IcLoraStageMode.SINGLE_STAGE, + job_filter=_windows_measured_filter(24.0, 64, free_gib=15.46), + tiling=high_res_tiling(None), + allowance=RiskAllowance.none(), + ) + ) + assert isinstance(n1_fits, IcLoraJobLoad) + assert n1_fits.chunk_pixel_frames == 41 + + +def test_short_second_window_restore_1440p_binds_on_window_1_decode() -> None: + """T4 (Restore 1440p 137f: w1=97f, w2=57f with carry 17) peaked at 15.89 GiB + with +0.00 GiB window-2 growth: max(dec(w1), dec(w2) + c_2w*t1) binds on + w1 (17.84 GiB) rather than charging a full 97f second window (20.95 GiB).""" + restore_high_res = high_res_tiling(IcLoraTiling(long_side=960, short_side=544, window_frames=97)) + t4_short = _verdict( + decide_ic_lora_job( + *_1440P, + 137, + stage_mode=IcLoraStageMode.SINGLE_STAGE, + job_filter=_windows_measured_filter(31.84, 64, free_gib=17.83), + tiling=restore_high_res, + allowance=RiskAllowance.none(), + ) + ) + assert isinstance(t4_short, VideoJobReject) + assert t4_short.reason == "stream_over" + + t4_fits = _verdict( + decide_ic_lora_job( + *_1440P, + 137, + stage_mode=IcLoraStageMode.SINGLE_STAGE, + job_filter=_windows_measured_filter(31.84, 64, free_gib=17.85), + tiling=restore_high_res, + allowance=RiskAllowance.none(), + ) + ) + assert isinstance(t4_fits, IcLoraJobLoad) + assert t4_fits.chunk_pixel_frames == 97 + + +def test_refine_details_1440p_is_measured_through_4_windows_while_4k_stays_unmeasured() -> None: + """T2 measured 1440p refine-details cleanly through 4 windows (241f at 73f + windows), while T3 at 4K paged (0.60 GB shared) and stays unmeasured in Cautious mode.""" + refine_1440p_4w = _verdict( + decide_ic_lora_job( + *_1440P, + 241, + stage_mode=IcLoraStageMode.SINGLE_STAGE, + job_filter=_windows_measured_filter(31.84, 64), + ic_lora_id="refine-details", + tiling=_REFINE_TILING, + allowance=RiskAllowance.none(), + ) + ) + assert isinstance(refine_1440p_4w, IcLoraJobLoad) + + refine_1440p_5w = _verdict( + decide_ic_lora_job( + *_1440P, + 249, + stage_mode=IcLoraStageMode.SINGLE_STAGE, + job_filter=_windows_measured_filter(31.84, 64), + ic_lora_id="refine-details", + tiling=_REFINE_TILING, + allowance=RiskAllowance.none(), + ) + ) + assert isinstance(refine_1440p_5w, VideoJobReject) + assert refine_1440p_5w.reason == "unmeasured_cell" + + refine_4k = _verdict( + decide_ic_lora_job( + *_4K_REFINE, + 137, + stage_mode=IcLoraStageMode.SINGLE_STAGE, + job_filter=_windows_measured_filter(31.84, 64), + ic_lora_id="refine-details", + tiling=_REFINE_TILING, + allowance=RiskAllowance.none(), + ) + ) + assert isinstance(refine_4k, VideoJobReject) + assert refine_4k.reason == "unmeasured_cell" + diff --git a/backend/tests/test_ic_lora_recipe_executor_frames.py b/backend/tests/test_ic_lora_recipe_executor_frames.py index 881f22694..76a864eb2 100644 --- a/backend/tests/test_ic_lora_recipe_executor_frames.py +++ b/backend/tests/test_ic_lora_recipe_executor_frames.py @@ -21,6 +21,7 @@ ) from services.features.video.ic_lora_recipe import IcLoraRecipeExecutor from services.generation_queue.types import OutputAllocation +from tests.fakes.generation import FakeJobSession from services.media_probe import first_audio_codec, video_frame_count from services.records import AssetRecord, CapabilityFailedError, GenerationRecord from tests.lora_catalog_helpers import add_ic_lora @@ -151,7 +152,9 @@ def get_asset(self, asset_id: str) -> AssetRecord | None: plan = executor.plan_outputs(generation)[0] output = tmp_path / "output.mp4" executor.execute( - generation, (OutputAllocation(plan=plan, asset_id="asset", dest_path=str(output)),) + generation, + (OutputAllocation(plan=plan, asset_id="asset", dest_path=str(output)),), + FakeJobSession(), ) return output, model @@ -203,14 +206,14 @@ def test_a_clip_whose_padded_count_is_over_budget_runs_the_snapped_down_count( } -def test_a_stored_over_bet_runs_the_snapped_up_count_after_a_switch_to_standard_mode( +def test_a_stored_over_bet_runs_the_snapped_up_count_after_a_switch_to_cautious_mode( test_state, catalog, tmp_path: Path ) -> None: """The bug is the executor gating on the live mode: a queued job that create admitted fails.""" limit = _first_refused_count(test_state) clip_frames = limit + 3 # both the snapped-down count and the snapped-up count are over source = write_pattern_clip(tmp_path / "source.mp4", frames=clip_frames) - test_state.state.app_settings.budget_mode = "standard" + test_state.state.app_settings.budget_mode = "cautious" output, model = _run( test_state, tmp_path, source, frames=clip_frames, audio=False, risk=_OVER_BET @@ -220,14 +223,14 @@ def test_a_stored_over_bet_runs_the_snapped_up_count_after_a_switch_to_standard_ assert video_frame_count(output) == clip_frames -def test_a_job_stored_without_a_bet_is_refused_after_a_switch_to_reckless_mode( +def test_a_job_stored_without_a_bet_is_refused_after_a_switch_to_brave_mode( test_state, catalog, tmp_path: Path ) -> None: """The bug is the executor gating on the live mode: it runs a job that create refused.""" limit = _first_refused_count(test_state) clip_frames = limit + 3 source = write_pattern_clip(tmp_path / "source.mp4", frames=clip_frames) - test_state.state.app_settings.budget_mode = "reckless" + test_state.state.app_settings.budget_mode = "brave" with pytest.raises(CapabilityFailedError): _run(test_state, tmp_path, source, frames=clip_frames, audio=False) diff --git a/backend/tests/test_ic_lora_recipe_memory.py b/backend/tests/test_ic_lora_recipe_memory.py new file mode 100644 index 000000000..1bfe9773b --- /dev/null +++ b/backend/tests/test_ic_lora_recipe_memory.py @@ -0,0 +1,229 @@ +"""Memory advice for a Home IC-LoRA video recipe, before and after a clip is picked. + +The advice must agree with what create would run, so ``recipe_run_frames`` (the count create and +execute use) is the oracle wherever a frame count matters. +""" + +from __future__ import annotations + +import pytest + +from _routes._errors import HTTPError +from api_types import IcLoraRecipeStoredParams, IcLoraSettings, LoraEntry +from tests.http_error_assertions import assert_http_error +from tests.lora_catalog_helpers import add_ic_lora + +_GIB = 1024**3 +_SINGLE_STAGE = IcLoraSettings(skip_stage_2=True, resolution_factor=1.0, audio_mode="source") +# Its canvas follows the clip size, so a crop changes the ask. +_STAGE_2_LORA = IcLoraSettings(skip_stage_2=False, stage_2_ic_lora=True, resolution_factor=1.0) +_STAND_IN_540P = (960, 540) + + +def _configure_windows(test_state, vram_gib: float) -> None: + test_state.config.system = "Windows" + test_state.config.vram_gb = int(vram_gib) + test_state.config.vram_bytes = int(vram_gib * _GIB) + test_state.config.total_ram_bytes = 64 * _GIB + test_state.config.local_generations_mode = "streaming_models_loading" + + +@pytest.fixture +def recipes(test_state, fake_services, create_fake_model_files): + """Day to Night and the cutout recipe on the catalog, on a 32 GB Windows card.""" + + def install(settings: IcLoraSettings = _SINGLE_STAGE) -> None: + create_fake_model_files() + _configure_windows(test_state, 32) + test_state.state.app_settings.budget_mode = "cautious" + add_ic_lora(fake_services, id="day-to-night", default_settings=settings) + add_ic_lora(fake_services, id="alpha-gen", default_settings=settings) + + return install + + +def _memory( + client, + recipe: str = "day-to-night", + *, + resolution: str = "540p", + cells: list[str] | None = None, + source: tuple[int, int, int] | None = None, +) -> dict: + body: dict[str, object] = { + "model": "ltx-2.5-fast", + "resolution": resolution, + "cells": cells or [resolution], + "audioMode": "generated", + "scale": 1.0, + } + if source is not None: + width, height, frames = source + body["source"] = {"width": width, "height": height, "frames": frames} + response = client.post(f"/api/generations/ic-lora-recipes/{recipe}/memory", json=body) + assert response.status_code == 200, response.text + return response.json() + + +def _run_frames(test_state, clip_frames: int, *, width: int, height: int) -> int | None: + """Frames create runs for Day to Night at 540p, or None when it refuses the clip.""" + stored = IcLoraRecipeStoredParams( + prompt="p", + model="ltx-2.5-fast", + resolution="540p", + audioMode="generated", + fps=24, + loras=[LoraEntry(ref="", scale=1.0, catalogId="day-to-night")], + ) + try: + count, risk = test_state.ic_lora.recipe_run_frames( + ic_lora_id="day-to-night", + source_width=width, + source_height=height, + stored=stored, + clip_frames=clip_frames, + ) + except HTTPError: + return None + return count if risk is None else None + + +def test_a_full_length_clip_that_runs_by_dropping_its_last_frames_reads_as_full( + client, test_state, recipes +) -> None: + recipes() + full_by_dropping = 0 + for quarter_gib in range(40, 129): + _configure_windows(test_state, quarter_gib / 4) + ran = _run_frames(test_state, 240, width=_STAND_IN_540P[0], height=_STAND_IN_540P[1]) + cell = _memory(client)["cells"][0] + assert cell["full"] == (ran is not None), f"{quarter_gib / 4} GiB: create runs {ran}" + full_by_dropping += ran is not None and ran < 240 + assert full_by_dropping, "no card size ran the capped clip by dropping frames" + + +def test_a_cell_never_reports_more_frames_than_the_input_cap(client, recipes) -> None: + recipes() + + response = _memory(client) + + assert response["max_input_frames"] == 240 + assert response["cells"] == [{"resolution": "540p", "max_frames": 240, "full": True}] + + +@pytest.mark.parametrize( + ("settings", "flag", "fits"), + [ + pytest.param(_SINGLE_STAGE, False, False, id="flag-off"), + pytest.param(_SINGLE_STAGE, True, True, id="flag-on"), + pytest.param(_STAGE_2_LORA, True, False, id="stage-2-lora-recipe"), + ], +) +def test_a_high_res_cell_fits_only_when_create_would_run_it( + client, recipes, settings: IcLoraSettings, flag: bool, fits: bool +) -> None: + recipes(settings) + patched = client.request("PATCH", "/api/feature-flags", json={"highResVideoToVideo": flag}) + assert patched.status_code == 200, patched.text + + cells = _memory(client, resolution="1440p", cells=["1440p", "2160p"])["cells"] + + assert [cell["max_frames"] > 0 for cell in cells] == [fits, fits] + + +def test_the_clips_ask_is_priced_at_the_frame_count_create_runs( + client, test_state, recipes +) -> None: + recipes() + _configure_windows(test_state, 16) + width, height = 1920, 1080 + limit = next( + frames + for frames in range(9, 2000, 8) + if _run_frames(test_state, frames, width=width, height=height) is None + ) + + def ask(frames: int) -> float: + selected = _memory(client, source=(width, height, frames))["selected"] + assert selected is not None + return selected["ask_gib"] + + for clip in (limit - 11, limit - 3): + ran = _run_frames(test_state, clip, width=width, height=height) + assert ran is not None + assert ask(clip) == ask(ran), f"a {clip}-frame clip runs {ran} frames" + + +def test_the_cutout_recipe_prices_the_whole_frame_not_the_crop(client, recipes) -> None: + recipes(_STAGE_2_LORA) + # 1920x1200 crops to 3:2 (1800x1200) for a recipe that crops. The cutout keeps every pixel. + wide, cropped = (1920, 1200, 121), (1800, 1200, 121) + + def ask(recipe: str, source: tuple[int, int, int]) -> float: + selected = _memory(client, recipe, source=source)["selected"] + assert selected is not None + return selected["ask_gib"] + + assert ask("day-to-night", wide) == ask("day-to-night", cropped) + assert ask("alpha-gen", wide) > ask("day-to-night", wide) + + +def test_no_number_appears_before_a_clip_is_picked(client, recipes) -> None: + recipes() + + response = _memory(client, cells=["540p", "720p"]) + + assert response["selected"] is None + assert [cell["resolution"] for cell in response["cells"]] == ["540p", "720p"] + + +@pytest.mark.parametrize("recipe", ["no-such-recipe", "ingredients"]) +def test_an_unknown_or_non_video_recipe_is_not_found( + client, recipes, fake_services, recipe: str +) -> None: + recipes() + add_ic_lora(fake_services, id="ingredients", default_settings=_SINGLE_STAGE) + + response = client.post( + f"/api/generations/ic-lora-recipes/{recipe}/memory", + json={"model": "ltx-2.5-fast", "resolution": "540p", "cells": ["540p"]}, + ) + + assert_http_error(response, status_code=404, code="UNKNOWN_IC_LORA") + + +def test_ic_lora_recipe_memory_matches_admit_verdict( + client, test_state, fake_services, recipes +) -> None: + recipes() + patched = client.request("PATCH", "/api/feature-flags", json={"highResVideoToVideo": True}) + assert patched.status_code == 200, patched.text + + # On a 32 GB RAM Windows machine, Day to Night hits ram_shortfall: Cautious + # refuses it (0 frames), while Brave admits the cells whose GPU ask fits. + test_state.config.total_ram_bytes = 32 * _GIB + test_state.state.app_settings.budget_mode = "cautious" + assert _memory(client, cells=["540p"])["cells"] == [ + {"resolution": "540p", "max_frames": 0, "full": False} + ] + test_state.state.app_settings.budget_mode = "brave" + assert _memory(client, cells=["540p"])["cells"] == [ + {"resolution": "540p", "max_frames": 240, "full": True} + ] + + # On Mac, 1440p IC-LoRA is an uncovered Extrapolated load: Cautious refuses + # it at create and in recipe_memory, while Brave admits it. + test_state.config.system = "Darwin" + test_state.config.darwin_unified_memory = True + test_state.config.vram_gb = 64 + test_state.config.vram_bytes = None + test_state.config.available_ram_gb = 64 + test_state.config.total_ram_bytes = 64 * _GIB + fake_services.gpu_info.mps_pool_bytes = 48 * _GIB + test_state.state.app_settings.budget_mode = "cautious" + assert _memory(client, resolution="1440p", cells=["1440p"])["cells"] == [ + {"resolution": "1440p", "max_frames": 0, "full": False} + ] + test_state.state.app_settings.budget_mode = "brave" + assert _memory(client, resolution="1440p", cells=["1440p"])["cells"][0]["max_frames"] > 0 + diff --git a/backend/tests/test_ic_lora_recipe_run_frames.py b/backend/tests/test_ic_lora_recipe_run_frames.py index ce9c3d012..0b6ac359b 100644 --- a/backend/tests/test_ic_lora_recipe_run_frames.py +++ b/backend/tests/test_ic_lora_recipe_run_frames.py @@ -19,6 +19,7 @@ VideoAssetMetadata, VideoMeta, ) +from runtime_config.budget_admission import RiskAllowance from runtime_config.video_job_budget import VIDEO_JOB_TOO_LARGE from services.records import AssetRecord from tests.fakes.services import FakeCapture @@ -30,24 +31,24 @@ @dataclass(frozen=True) class Gate: - """A catalog shape, and the risk tier Reckless mode gives a count the gate refuses.""" + """A catalog shape, and the risk tier Brave mode gives a count the gate refuses.""" settings: IcLoraSettings resolution: str tier: str - flags: dict[str, bool] # the stored allowance that tier leaves on the generation + flags: dict[str, object] # the stored allowance that tier leaves on the generation # A single-stage job is refused for memory. A two-stage job is refused by a fence that moves -# with the frame count, and that Reckless mode runs as an unmeasured bet. +# with the frame count, and that Brave mode runs as an unmeasured bet. _GATES = { "memory": Gate( IcLoraSettings(skip_stage_2=True, resolution_factor=1.0, audio_mode="source"), - "540p", "over", {"risk_allowance": True}, + "540p", "over", {"allowance": RiskAllowance(over=True, unmeasured=False)}, ), "fence": Gate( IcLoraSettings(skip_stage_2=False, resolution_factor=1.0, audio_mode="source"), - "1080p", "unmeasured", {"unmeasured_bet": True}, + "1080p", "unmeasured", {"allowance": RiskAllowance(over=False, unmeasured=True)}, ), } @@ -100,8 +101,8 @@ def first_refused(self, *, width: int = 1920, height: int = 1080, cutout: bool = raise AssertionError("the gate never refused a count") def refused(self, clip_frames: int, mode: str, **kwargs: object) -> None: - """The count is refused: a 422 in standard mode, the gate's risk in reckless mode.""" - if mode == "standard": + """The count is refused: a 422 in cautious mode, the gate's risk in brave mode.""" + if mode == "cautious": with pytest.raises(HTTPError) as exc_info: self.run(clip_frames, **kwargs) assert exc_info.value.code == VIDEO_JOB_TOO_LARGE @@ -119,7 +120,7 @@ def runner(request, test_state, fake_services, create_fake_model_files) -> Runne return Runner(test_state, gate) -@pytest.fixture(params=["standard", "reckless"]) +@pytest.fixture(params=["cautious", "brave"]) def mode(request, test_state) -> str: test_state.state.app_settings.budget_mode = request.param return request.param @@ -139,7 +140,7 @@ def test_a_clip_below_the_floor_runs_the_floor_count(runner: Runner, mode: str) def test_a_snapped_up_count_over_budget_falls_back_to_the_clean_snapped_down_count( runner: Runner, mode: str ) -> None: - """Reckless returns a risk in place of the 422. The fallback must read that risk.""" + """Brave returns a risk in place of the 422. The fallback must read that risk.""" limit = runner.first_refused() assert runner.run(limit - 3) == (limit - 8, None) @@ -159,7 +160,7 @@ def test_when_both_counts_are_over_budget_the_snapped_up_count_is_refused_or_run limit = runner.first_refused() runner.refused(limit + 3, mode) - if mode == "reckless": + if mode == "brave": assert runner.run(limit + 3)[0] == limit + 8 @@ -169,7 +170,7 @@ def test_a_recipe_that_always_pads_never_falls_back_to_snapped_down( limit = runner.first_refused(cutout=True) runner.refused(limit - 3, mode, cutout=True) - if mode == "reckless": + if mode == "brave": assert runner.run(limit - 3, cutout=True)[0] == limit assert runner.run(limit - 11, cutout=True) == (limit - 8, None) @@ -181,11 +182,11 @@ def test_the_stored_allowance_and_not_the_live_mode_gates_the_run( limit = runner.first_refused() flags = runner.gate.flags - test_state.state.app_settings.budget_mode = "reckless" + test_state.state.app_settings.budget_mode = "brave" # Create picked the clean snapped-down count, so nothing is stored. Execute must too. - assert runner.run(limit - 3, risk_allowance=False, unmeasured_bet=False) == (limit - 8, None) + assert runner.run(limit - 3, allowance=RiskAllowance.none()) == (limit - 8, None) - test_state.state.app_settings.budget_mode = "standard" + test_state.state.app_settings.budget_mode = "cautious" # Create ran the over-budget count with a risk, and stored it. Execute must keep it. count, risk = runner.run(limit, **flags) assert count == limit diff --git a/backend/tests/test_ic_lora_recipe_run_frames_mac.py b/backend/tests/test_ic_lora_recipe_run_frames_mac.py index b82603dac..e3aad304c 100644 --- a/backend/tests/test_ic_lora_recipe_run_frames_mac.py +++ b/backend/tests/test_ic_lora_recipe_run_frames_mac.py @@ -1,8 +1,9 @@ -"""Frame count of a queued Home recipe on the Mac layout-to-render cell, priced by the real budget. +"""Frame count of a queued Home recipe when snapped-up is unmeasured and snapped-down is over. -The cell has a priced frame cap. Past it, a two-stage job is an ``unmeasured`` bet, and below it -a short memory pool makes the last priced count ``over``. A clip just above the cap snaps down to -that ``over`` count and up to the first ``unmeasured`` count. +At 4K on a 32 GiB Windows card with a 73-frame window, one unchunked 73-frame pass fits decode +(32.73 GiB ask, ``over``), while an 81-frame clip spans two windows so ``choose_decode_window`` +steps the window down to 65 frames (31.52 GiB ask, ``unmeasured`` for ``refine-details``). A clip +between 73 and 81 frames snaps down to the ``over`` count (73) and up to the ``unmeasured`` count (81). """ from __future__ import annotations @@ -10,32 +11,58 @@ import pytest from _routes._errors import HTTPError -from api_types import IcLoraSettings +from api_types import IcLoraRecipeStoredParams, IcLoraSettings, LoraEntry +from runtime_config.budget_admission import RiskAllowance +from runtime_config.ic_lora_tiling import IcLoraTiling from tests.lora_catalog_helpers import add_ic_lora -from tests.test_ic_lora_recipe_run_frames import _GIB, _ID, Gate, Runner - -# 540p stage 1 at the last priced count needs 17 GB. A 16 GB pool is short of it. -_SHORT_POOL_GIB = 16 +from tests.test_ic_lora_recipe_run_frames import Gate, Runner, _configure_windows + +_REFINE_ID = "refine-details" + + +class _UpscaleRunner(Runner): + def run( + self, clip_frames: int, *, width: int = 1920, height: int = 1080, **kwargs: object + ) -> tuple[int, object]: + return self._state.ic_lora.recipe_run_frames( + ic_lora_id=_REFINE_ID, + source_width=width, + source_height=height, + stored=IcLoraRecipeStoredParams( + prompt="p", + model="ltx-2.5-fast", + resolution=self.gate.resolution, + audioMode="generated", + fps=24, + loras=[LoraEntry(ref="", scale=1.0, catalogId=_REFINE_ID)], + ), + clip_frames=clip_frames, + upscale=True, + **kwargs, + ) @pytest.fixture def mac_runner(test_state, fake_services, create_fake_model_files) -> Runner: create_fake_model_files() - test_state.config.system = "Darwin" - test_state.config.total_ram_bytes = int(48 * _GIB) - test_state.config.local_generations_mode = "streaming_models_loading" - fake_services.gpu_info.mps_pool_bytes = int(_SHORT_POOL_GIB * _GIB) + _configure_windows(test_state, vram_gib=32, total_ram_gib=64) gate = Gate( - IcLoraSettings(skip_stage_2=False, stage_2_ic_lora=True, resolution_factor=1.0), - "540p", "over", {}, + IcLoraSettings( + skip_stage_2=True, + resolution_factor=1.0, + tiling=IcLoraTiling(long_side=1920, short_side=1088, window_frames=73), + ), + "2160p", + "over", + {}, ) - add_ic_lora(fake_services, id=_ID, default_settings=gate.settings) - return Runner(test_state, gate) + add_ic_lora(fake_services, id=_REFINE_ID, default_settings=gate.settings) + return _UpscaleRunner(test_state, gate) def _first_unmeasured_count(runner: Runner, test_state) -> int: - test_state.state.app_settings.budget_mode = "reckless" - for clip in range(9, 2000, 8): + test_state.state.app_settings.budget_mode = "brave" + for clip in range(73, 2000, 8): _, risk = runner.run(clip) if risk is not None and risk.tier == "unmeasured": return clip @@ -43,7 +70,7 @@ def _first_unmeasured_count(runner: Runner, test_state) -> int: @pytest.mark.parametrize("above_cap", [1, 5]) -@pytest.mark.parametrize("live_mode", ["standard", "reckless"]) +@pytest.mark.parametrize("live_mode", ["cautious", "brave"]) def test_an_admitted_unmeasured_job_still_runs_when_its_snapped_down_count_is_refused( mac_runner: Runner, test_state, above_cap: int, live_mode: str ) -> None: @@ -60,7 +87,7 @@ def test_an_admitted_unmeasured_job_still_runs_when_its_snapped_down_count_is_re assert created_risk is not None and created_risk.tier == "unmeasured" test_state.state.app_settings.budget_mode = live_mode - count, risk = mac_runner.run(clip, risk_allowance=False, unmeasured_bet=True) + count, risk = mac_runner.run(clip, allowance=RiskAllowance(over=False, unmeasured=True)) assert count == snapped_up assert risk is not None and risk.tier == "unmeasured" @@ -71,7 +98,7 @@ def test_a_refused_snapped_down_count_does_not_hide_the_snapped_up_refusal( """The bug is the double refusal carrying the message of the count the job did not ask for.""" snapped_up = _first_unmeasured_count(mac_runner, test_state) snapped_down = snapped_up - 8 - test_state.state.app_settings.budget_mode = "standard" + test_state.state.app_settings.budget_mode = "cautious" def refusal(clip_frames: int) -> str: with pytest.raises(HTTPError) as exc_info: diff --git a/backend/tests/test_ic_lora_remote_parity.py b/backend/tests/test_ic_lora_remote_parity.py new file mode 100644 index 000000000..33d56721e --- /dev/null +++ b/backend/tests/test_ic_lora_remote_parity.py @@ -0,0 +1,99 @@ +"""The phone (remote app) gets the same IC-LoRA tiling verdicts and refusals as the desktop app. + +Both apps call one handler. These tests pin that no remote route changes a verdict, a refusal +or a stored choice of the adaptive chunk window. +""" + +from __future__ import annotations + +from pathlib import Path + +from starlette.testclient import TestClient + +from remote.app import create_remote_app +from tests.test_ic_lora_tile_size import ( + _REFINE, + _body, + _configure_windows, + _ingest_sized, + _install, +) + +_AUTH = {"Authorization": "Bearer pair-token"} +_WINDOWS = [97, 73, 57, 41] +_PREFLIGHT = f"/api/generations/ic-lora-recipes/{_REFINE}/preflight" +_CREATE = f"/api/generations/ic-lora-recipes/{_REFINE}" + + +def _preflight_body(video_id: str, resolution: str) -> dict[str, object]: + return { + **_body(video_id, resolution), + "tileSizes": ["standard", "large", "extra-large"], + "maxWindows": _WINDOWS, + "carries": [17, 25, 33], + } + + +def test_remote_preflight_matches_the_desktop_for_a_4k_clip( + client: TestClient, fake_services, test_state, create_fake_model_files, tmp_path: Path +) -> None: + create_fake_model_files(model_id="ltx-2.5-22b-distilled") + _install(fake_services, test_state, _REFINE) + _configure_windows(test_state, vram_gib=48) + video_id = _ingest_sized(client, test_state, tmp_path, width=3840, height=2160, frames=137) + body = _preflight_body(video_id, "2160p") + + desktop = client.post(_PREFLIGHT, json=body) + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as remote: + phone = remote.post(_PREFLIGHT, json=body, headers=_AUTH) + + assert desktop.status_code == phone.status_code == 200, phone.text + assert phone.json() == desktop.json() + cells = {cell["maxWindowFrames"]: cell for cell in phone.json()["maxWindowCells"]} + assert cells[97]["ok"] is False + assert all(cells[window]["ok"] for window in (73, 57, 41)) + + +def test_remote_create_refuses_a_maximum_above_the_cap_like_the_desktop_and_keeps_a_valid_one( + client: TestClient, fake_services, test_state, create_fake_model_files, tmp_path: Path +) -> None: + create_fake_model_files(model_id="ltx-2.5-22b-distilled") + _install(fake_services, test_state, _REFINE) + _configure_windows(test_state, vram_gib=48) + video_id = _ingest_sized(client, test_state, tmp_path, width=3840, height=2160, frames=137) + + desktop = client.post(_CREATE, json=_body(video_id, "2160p", maxWindowFrames=97)) + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as remote: + phone = remote.post(_CREATE, json=_body(video_id, "2160p", maxWindowFrames=97), headers=_AUTH) + kept = remote.post(_CREATE, json=_body(video_id, "2160p", maxWindowFrames=73), headers=_AUTH) + + assert desktop.status_code == phone.status_code == 422 + assert phone.json()["message"] == desktop.json()["message"] + # The phone shows the stored maximum, so Reuse restores the same run. + assert kept.status_code == 200, kept.text + assert kept.json()["spec"]["params"]["maxWindowFrames"] == 73 + + +def test_remote_auto_carry_matches_the_desktop_for_a_chunk_length_the_default_carry_cannot_run( + client: TestClient, fake_services, test_state, create_fake_model_files, tmp_path: Path +) -> None: + create_fake_model_files(model_id="ltx-2.5-22b-distilled") + _install(fake_services, test_state, _REFINE) + _configure_windows(test_state, vram_gib=24) + video_id = _ingest_sized(client, test_state, tmp_path, width=1920, height=1080, frames=137) + body = {**_preflight_body(video_id, "1080p"), "params": {**_body(video_id, "1080p")["params"], "maxWindowFrames": 41}} + + desktop = client.post(_PREFLIGHT, json=body) + desktop_create = client.post(_CREATE, json=_body(video_id, "1080p", maxWindowFrames=41)) + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as remote: + phone = remote.post(_PREFLIGHT, json=body, headers=_AUTH) + phone_create = remote.post(_CREATE, json=_body(video_id, "1080p", maxWindowFrames=41), headers=_AUTH) + + assert desktop.status_code == phone.status_code == 200, phone.text + assert phone.json() == desktop.json() + # Auto carry runs 17, so the 41-frame chunk runs on both apps. Carry 25 would refuse it. + assert phone.json()["defaults"]["carryFrames"] == 17 + assert desktop_create.status_code == phone_create.status_code == 200, phone_create.text diff --git a/backend/tests/test_ic_lora_tile_size.py b/backend/tests/test_ic_lora_tile_size.py new file mode 100644 index 000000000..cac5bfb6b --- /dev/null +++ b/backend/tests/test_ic_lora_tile_size.py @@ -0,0 +1,418 @@ +"""Tile size of Refine Details: the preflight verdicts, the create refusal and the stored choice.""" + +from __future__ import annotations + +from pathlib import Path +from typing import get_args + +import imageio.v2 as imageio +import numpy as np +from starlette.testclient import TestClient + +from api_types import IcLoraSettings, parse_lora_catalog +from handlers.base import resolve_models_dir +from runtime_config.ic_lora_tiling import ( + TILE_SIZES, + IcLoraTileSize, + IcLoraTiling, + with_tiling_overrides, +) +from runtime_config.model_download_specs import resolve_ic_lora_path +from tests.fakes.services import FakeCapture +from tests.lora_catalog_helpers import add_ic_lora, download_spec + +_REFINE = "refine-details" +_DAY_TO_NIGHT = "day-to-night" +_WEIGHTS = "day-to-night.safetensors" +_CATALOG = Path(__file__).resolve().parents[1] / "runtime_config" / "lora_catalog.json" +_GIB = 1024**3 +_SIZES = ["standard", "large", "extra-large"] + + +def test_tile_size_names_match_the_controls_file() -> None: + assert set(get_args(IcLoraTileSize)) == set(TILE_SIZES) + + +def test_tiling_override_error_is_the_validator_text() -> None: + tiling = IcLoraTiling(long_side=1024, short_side=576, window_frames=73, carry_frames=25) + try: + with_tiling_overrides(tiling, overlap_fraction=None, carry_frames=41, max_window_frames=57) + except ValueError as exc: + assert str(exc) == "window_frames must be more than twice carry_frames" + else: + raise AssertionError("expected ValueError") + + +def _mp4(path: Path, *, width: int = 1920, height: int = 1080, frames: int = 49) -> Path: + writer = imageio.get_writer(str(path), fps=24, codec="libx264", macro_block_size=None) + frame = np.zeros((height, width, 3), dtype=np.uint8) + for _ in range(frames): + writer.append_data(frame) + writer.close() + return path + + +def _install(fake_services, test_state, ic_lora_id: str) -> None: + item = next(e for e in parse_lora_catalog(_CATALOG.read_text()).ic_loras if e.id == ic_lora_id) + fake_services.lora_catalog_provider._catalog.ic_loras.append(item) + models_dir = resolve_models_dir(test_state.state, test_state.config) + path = resolve_ic_lora_path(models_dir, item.id, item.download.variants[0].filename) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(b"weights") + + +def _configure_windows(test_state, *, vram_gib: float, budget_mode: str = "brave") -> None: + test_state.config.system = "Windows" + test_state.config.vram_gb = int(vram_gib) + test_state.config.vram_bytes = int(vram_gib * _GIB) + test_state.config.total_ram_bytes = 64 * _GIB + test_state.config.local_generations_mode = "streaming_models_loading" + test_state.state.app_settings.budget_mode = budget_mode + + +def _body(video_id: str, resolution: str, **params: object) -> dict[str, object]: + return { + "params": { + "prompt": "restore fine detail", + "model": "ltx-2.5-fast", + "resolution": resolution, + **params, + }, + "inputs": {"video": {"assetId": video_id}}, + } + + +def _preflight(client: TestClient, recipe_id: str, body: dict[str, object]): + return client.post( + f"/api/generations/ic-lora-recipes/{recipe_id}/preflight", + json={**body, "tileSizes": _SIZES}, + ) + + +def _ingest(client: TestClient, tmp_path: Path, **kwargs) -> str: + return client.post("/api/assets", json={"path": str(_mp4(tmp_path / "clip.mp4", **kwargs))}).json()["id"] + + +def test_each_tile_size_is_refused_as_generate_refuses_it( + client, fake_services, test_state, create_fake_model_files, tmp_path +) -> None: + create_fake_model_files(model_id="ltx-2.5-22b-distilled") + _install(fake_services, test_state, _REFINE) + # A card where 2160p is refused for every size. Cautious refuses what Brave would run as a bet. + _configure_windows(test_state, vram_gib=13.25, budget_mode="cautious") + video_id = _ingest(client, tmp_path) + body = _body(video_id, "2160p") + + cells = {cell["tileSize"]: cell for cell in _preflight(client, _REFINE, body).json()["cells"]} + + assert all(not cell["ok"] for cell in cells.values()) + for size, cell in cells.items(): + params = {} if size == "standard" else {"tilingSize": size} + refused = client.post( + f"/api/generations/ic-lora-recipes/{_REFINE}", json=_body(video_id, "2160p", **params) + ) + assert refused.status_code == 422, size + assert refused.json()["message"] == cell["message"], size + + +def test_a_size_that_fits_has_a_clear_verdict_and_is_stored_with_the_generation( + client, fake_services, test_state, create_fake_model_files, tmp_path +) -> None: + create_fake_model_files(model_id="ltx-2.5-22b-distilled") + _install(fake_services, test_state, _REFINE) + _configure_windows(test_state, vram_gib=24) + video_id = _ingest(client, tmp_path) + body = _body(video_id, "1080p", tilingSize="large") + + cells = _preflight(client, _REFINE, body).json()["cells"] + assert [(cell["ok"], cell["message"]) for cell in cells] == [(True, None)] * 3 + + created = client.post(f"/api/generations/ic-lora-recipes/{_REFINE}", json=body) + assert created.status_code == 200, created.text + assert created.json()["spec"]["params"]["tilingSize"] == "large" + + +def test_a_recipe_without_tiling_controls_refuses_a_tile_size( + client, fake_services, test_state, create_fake_model_files, tmp_path +) -> None: + create_fake_model_files(model_id="ltx-2.5-22b-distilled") + add_ic_lora( + fake_services, + id=_DAY_TO_NIGHT, + download=download_spec(_WEIGHTS), + input={"kind": "video"}, + default_settings=IcLoraSettings(skip_stage_2=True, resolution_factor=1.5, audio_mode="source"), + ) + models_dir = resolve_models_dir(test_state.state, test_state.config) + weights = resolve_ic_lora_path(models_dir, _DAY_TO_NIGHT, _WEIGHTS) + weights.parent.mkdir(parents=True, exist_ok=True) + weights.write_bytes(b"weights") + video_id = _ingest(client, tmp_path) + + refused = client.post( + f"/api/generations/ic-lora-recipes/{_DAY_TO_NIGHT}", + json=_body(video_id, "540p", tilingSize="large", variantId="default"), + ) + + assert refused.status_code == 422, refused.text + + +def test_preflight_accepts_an_empty_prompt_and_create_still_requires_one( + client, fake_services, test_state, create_fake_model_files, tmp_path +) -> None: + create_fake_model_files(model_id="ltx-2.5-22b-distilled") + _install(fake_services, test_state, _REFINE) + _configure_windows(test_state, vram_gib=24) + video_id = _ingest(client, tmp_path) + body = _body(video_id, "1080p", prompt="") + + preflight = _preflight(client, _REFINE, body) + assert preflight.status_code == 200, preflight.text + assert len(preflight.json()["cells"]) == 3 + + created = client.post(f"/api/generations/ic-lora-recipes/{_REFINE}", json=body) + assert created.status_code == 422 + assert created.json()["message"] == "Prompt is required." + + +def test_an_unknown_recipe_at_1440p_is_unknown_not_a_closed_high_cell( + client, test_state, create_fake_model_files, tmp_path +) -> None: + create_fake_model_files(model_id="ltx-2.5-22b-distilled") + _configure_windows(test_state, vram_gib=24) + video_id = _ingest(client, tmp_path) + + refused = client.post( + "/api/generations/ic-lora-recipes/not-a-recipe", + json=_body(video_id, "1440p"), + ) + + assert refused.status_code == 422 + assert refused.json()["code"] == "IC_LORA_UNKNOWN" + + +def test_preflight_of_an_unknown_video_fails_like_the_create_not_with_empty_verdicts( + client, fake_services, test_state, create_fake_model_files +) -> None: + create_fake_model_files(model_id="ltx-2.5-22b-distilled") + _install(fake_services, test_state, _REFINE) + body = _body("missing-asset", "1080p") + + preflight = _preflight(client, _REFINE, body) + created = client.post(f"/api/generations/ic-lora-recipes/{_REFINE}", json=body) + + assert preflight.status_code == created.status_code + assert preflight.status_code >= 400 + assert preflight.json() == created.json() + + +def _window_preflight(client: TestClient, body: dict[str, object], windows: list[int]): + return client.post( + f"/api/generations/ic-lora-recipes/{_REFINE}/preflight", json={**body, "maxWindows": windows} + ) + + +def test_a_window_under_the_shortest_one_is_a_422_not_a_server_error_that_drops_every_verdict( + client, fake_services, test_state, create_fake_model_files, tmp_path +) -> None: + create_fake_model_files(model_id="ltx-2.5-22b-distilled") + _install(fake_services, test_state, _REFINE) + _configure_windows(test_state, vram_gib=24) + video_id = _ingest(client, tmp_path) + + refused = _window_preflight(client, _body(video_id, "1080p"), [73, 33]) + + assert refused.status_code == 422 + + +def test_a_window_is_stored_and_a_window_the_pipeline_refuses_is_refused_at_create( + client, fake_services, test_state, create_fake_model_files, tmp_path +) -> None: + create_fake_model_files(model_id="ltx-2.5-22b-distilled") + _install(fake_services, test_state, _REFINE) + _configure_windows(test_state, vram_gib=24) + video_id = _ingest(client, tmp_path) + url = f"/api/generations/ic-lora-recipes/{_REFINE}" + + created = client.post(url, json=_body(video_id, "1080p", maxWindowFrames=57)) + assert created.status_code == 200, created.text + assert created.json()["spec"]["params"]["maxWindowFrames"] == 57 + + # 105 is above the 97-frame maximum. + refused = client.post(url, json=_body(video_id, "1080p", maxWindowFrames=105)) + assert refused.status_code == 422 + assert refused.json()["code"] == "INVALID_GENERATION_SPEC" + # 41 is not more than twice a carry the user set to 25. + refused = client.post(url, json=_body(video_id, "1080p", maxWindowFrames=41, carryFrames=25)) + assert refused.status_code == 422 + assert refused.json()["code"] == "INVALID_GENERATION_SPEC" + + +def test_each_window_verdict_is_the_refusal_generate_returns_for_that_window( + client, fake_services, test_state, create_fake_model_files, tmp_path +) -> None: + create_fake_model_files(model_id="ltx-2.5-22b-distilled") + _install(fake_services, test_state, _REFINE) + _configure_windows(test_state, vram_gib=24) + video_id = _ingest(client, tmp_path) + windows = [73, 57, 41, 81] + + for params in ({}, {"carryFrames": 17}): + body = _body(video_id, "1080p", **params) + cells = _window_preflight(client, body, windows).json()["maxWindowCells"] + assert [cell["maxWindowFrames"] for cell in cells] == windows + for cell in cells: + created = client.post( + f"/api/generations/ic-lora-recipes/{_REFINE}", + json=_body(video_id, "1080p", maxWindowFrames=cell["maxWindowFrames"], **params), + ) + assert cell["ok"] == (created.status_code == 200), (params, cell) + if not cell["ok"]: + assert cell["message"] == created.json()["message"], (params, cell) + + +def test_tile_size_verdicts_are_judged_with_the_window_the_form_holds( + client, fake_services, test_state, create_fake_model_files, tmp_path +) -> None: + create_fake_model_files(model_id="ltx-2.5-22b-distilled") + _install(fake_services, test_state, _REFINE) + _configure_windows(test_state, vram_gib=24) + video_id = _ingest(client, tmp_path) + + # A window that cannot run makes every tile size fail: the tile preflight kept the window. + cells = _preflight(client, _REFINE, _body(video_id, "1080p", maxWindowFrames=105)).json()["cells"] + + assert [cell["ok"] for cell in cells] == [False] * 3 + + +def _carry_preflight(client: TestClient, body: dict[str, object], carries: list[int]): + return client.post( + f"/api/generations/ic-lora-recipes/{_REFINE}/preflight", + json={**body, "tileSizes": [], "maxWindows": [], "carries": carries}, + ) + + +def test_preflight_returns_carry_verdicts_and_the_defaults_the_run_uses( + client, fake_services, test_state, create_fake_model_files, tmp_path +) -> None: + create_fake_model_files(model_id="ltx-2.5-22b-distilled") + _install(fake_services, test_state, _REFINE) + _configure_windows(test_state, vram_gib=24) + video_id = _ingest(client, tmp_path) + carries = [17, 25, 33] + + local = _carry_preflight(client, _body(video_id, "1080p", maxWindowFrames=57), carries) + assert local.status_code == 200, local.text + payload = local.json() + # The test clip is short, and 1080p fits it in one pass, so Auto is a single pass. + assert payload["defaults"] == { + "carryFrames": 25, + "overlapFraction": 0.25, + "auto": {"kind": "single-pass"}, + } + cells = {cell["carryFrames"]: cell for cell in payload["carryCells"]} + assert [cells[carry]["ok"] for carry in carries] == [True, True, False] + refused = client.post( + f"/api/generations/ic-lora-recipes/{_REFINE}", + json=_body(video_id, "1080p", maxWindowFrames=57, carryFrames=33), + ) + assert cells[33]["message"] == refused.json()["message"] + + high = _carry_preflight(client, _body(video_id, "1440p"), carries) + assert high.status_code == 200, high.text + assert high.json()["defaults"]["carryFrames"] == 17 + + +def test_auto_carry_gives_way_to_a_chunk_length_the_default_carry_cannot_run( + client, fake_services, test_state, create_fake_model_files, tmp_path +) -> None: + create_fake_model_files(model_id="ltx-2.5-22b-distilled") + _install(fake_services, test_state, _REFINE) + _configure_windows(test_state, vram_gib=24) + video_id = _ingest(client, tmp_path) + + # A 41-frame chunk is not more than twice the carry of 25, so Auto carry runs 17. + auto = _carry_preflight(client, _body(video_id, "1080p", maxWindowFrames=41), []) + assert auto.json()["defaults"]["carryFrames"] == 17 + # A carry the user chose stays, and the same chunk length is then refused. + pinned = client.post( + f"/api/generations/ic-lora-recipes/{_REFINE}", + json=_body(video_id, "1080p", maxWindowFrames=41, carryFrames=25), + ) + assert pinned.status_code == 422 + + +def _ingest_sized(client: TestClient, test_state, tmp_path: Path, *, width: int, height: int, frames: int) -> str: + """An asset whose probe reports this size and length. The backend probe is a fake in tests.""" + asset = client.post("/api/assets", json={"path": str(_mp4(tmp_path / "clip.mp4", frames=1))}).json() + test_state.video_processor.register_video( + asset["path"], FakeCapture(frames=["f"] * frames, fps=24, width=width, height=height) + ) + return asset["id"] + + +def test_auto_reports_the_window_a_long_clip_runs_and_a_short_clip_runs_whole( + client, fake_services, test_state, create_fake_model_files, tmp_path +) -> None: + create_fake_model_files(model_id="ltx-2.5-22b-distilled") + _install(fake_services, test_state, _REFINE) + _configure_windows(test_state, vram_gib=24) + long_clip = _ingest_sized(client, test_state, tmp_path, width=1920, height=1080, frames=137) + + defaults = _carry_preflight(client, _body(long_clip, "1080p"), []).json()["defaults"] + + # 1080p stops at 97 frames, so a 137-frame clip is chunked. + assert defaults["auto"]["kind"] == "windowed" + assert defaults["auto"]["frames"] <= 97 + + +def test_a_maximum_above_the_cap_is_a_disabled_cell_with_the_message_create_returns( + client, fake_services, test_state, create_fake_model_files, tmp_path +) -> None: + create_fake_model_files(model_id="ltx-2.5-22b-distilled") + _install(fake_services, test_state, _REFINE) + _configure_windows(test_state, vram_gib=48) + video_id = _ingest_sized(client, test_state, tmp_path, width=3840, height=2160, frames=137) + windows = [97, 73, 57, 41] + + cells = { + cell["maxWindowFrames"]: cell + for cell in _window_preflight(client, _body(video_id, "2160p"), windows).json()["maxWindowCells"] + } + + assert cells[97]["ok"] is False + assert [cells[window]["ok"] for window in (73, 57, 41)] == [True] * 3 + refused = client.post( + f"/api/generations/ic-lora-recipes/{_REFINE}", + json=_body(video_id, "2160p", maxWindowFrames=97), + ) + assert refused.status_code == 422 + assert refused.json()["message"] == cells[97]["message"] + + +def test_generate_runs_the_carry_auto_picked_for_the_chunk_length_the_run_chose( + client, fake_services, test_state, create_fake_model_files, tmp_path +) -> None: + create_fake_model_files(model_id="ltx-2.5-22b-distilled") + _install(fake_services, test_state, _REFINE) + _configure_windows(test_state, vram_gib=24) + video_id = _ingest_sized(client, test_state, tmp_path, width=1280, height=704, frames=241) + path = client.get(f"/api/assets/{video_id}").json()["path"] + + response = client.post( + "/api/ic-lora/generate", + json={ + "ic_lora_id": _REFINE, + "input_path": path, + "prompt": "sharper", + "conditioning_type": "custom", + "max_window_frames": 41, + }, + ) + + # A 41-frame chunk is not more than twice the carry of 25, so Auto carry runs 17 on the pipeline. + assert response.status_code == 200, response.text + pipeline = fake_services.ic_lora_pipeline + assert pipeline.last_tiling is not None + assert pipeline.last_tiling.carry_frames == 17 + assert pipeline.generate_calls[-1]["chunk_pixel_frames"] == 41 diff --git a/backend/tests/test_iclora_preflight.py b/backend/tests/test_iclora_preflight.py index 2ecb312ca..af33c775d 100644 --- a/backend/tests/test_iclora_preflight.py +++ b/backend/tests/test_iclora_preflight.py @@ -18,10 +18,8 @@ PreprocessingStep, ) from frame_math import compute_num_frames -from runtime_config.ic_lora_job_budget import ( - TWO_STAGE_OVER_MEASURED_MESSAGE, - with_budgeted_duration_controls, -) +from runtime_config.budget_admission import unmeasured_refusal_message +from runtime_config.ic_lora_job_budget import with_budgeted_duration_controls from runtime_config.video_job_budget import ( VIDEO_JOB_TOO_LARGE, LocalJobFilter, @@ -104,7 +102,7 @@ def _duration_control(item: IcLoraCatalogItem) -> IcLoraControl: return next(c for c in item.controls if c.id == "duration") -def test_dropped_durations_carry_fence_and_budget_refusals( +def test_dropped_two_stage_duration_past_the_ceiling_carries_curve_figures( test_state, create_fake_model_files ) -> None: create_fake_model_files() @@ -118,9 +116,9 @@ def test_dropped_durations_carry_fence_and_budget_refusals( assert control.options == [5] assert control.dropped_options is not None assert [(d.value, d.reason) for d in control.dropped_options] == [ - (20, "two_stage_over_measured") + (20, "stream_over") ] - assert control.dropped_options[0].message == TWO_STAGE_OVER_MEASURED_MESSAGE + assert control.dropped_options[0].over_gib is not None budgeted = with_budgeted_duration_controls( _duration_item([5, 20], skip_stage_2=True), job_filter=job_filter @@ -310,11 +308,12 @@ def test_preflight_input_errors_match_generate( assert "Input not found" in missing.json()["message"] -def test_preflight_two_stage_long_duration_fences( +def test_preflight_two_stage_past_the_ceiling_is_refused_untested_in_cautious( client: TestClient, tmp_path: Path, create_fake_model_files, test_state ) -> None: create_fake_model_files() _configure_windows(test_state, vram_gib=31, total_ram_gib=64) + test_state.state.app_settings.budget_mode = "cautious" img = _write_png(tmp_path / "in.png", size=(1024, 1024)) resp = client.post( "/api/ic-lora/preflight", @@ -328,8 +327,9 @@ def test_preflight_two_stage_long_duration_fences( assert resp.status_code == 200 (cell,) = resp.json()["cells"] assert cell["ok"] is False - assert cell["message"] == TWO_STAGE_OVER_MEASURED_MESSAGE + assert cell["message"] == unmeasured_refusal_message("two_stage_range") assert cell["code"] == VIDEO_JOB_TOO_LARGE + assert cell["tier"] == "unmeasured" def test_small_source_passes_list_time_dropped_duration( diff --git a/backend/tests/test_image_prompt_plan.py b/backend/tests/test_image_prompt_plan.py new file mode 100644 index 000000000..3f846a5da --- /dev/null +++ b/backend/tests/test_image_prompt_plan.py @@ -0,0 +1,58 @@ +"""Where the rewrite of an image prompt honors a cancel and gives back the GPU lease. + +Each test names the bug it catches. The rewrite matrix is tested through the queue in +test_text_to_image.py. +""" + +from __future__ import annotations + +from contextlib import contextmanager +from typing import Iterator + +import pytest + +from handlers.image_prompt_plan import plan_fal_image_prompt +from services.generation_interrupt import GenerationCancelledError + + +def _cancelled() -> None: + raise GenerationCancelledError() + + +@pytest.mark.parametrize("gemma", [True, False], ids=["gemma", "gemini"]) +def test_a_cancel_before_the_rewrite_stops_it_and_releases_the_lease( + test_state, fake_services, create_fake_model_files, gemma: bool +) -> None: + # Bug caught: a cancel that comes during planning still loads Gemma and holds the GPU lease. + settings = test_state.state.app_settings + settings.explore_auto_enhance_prompts = True + if gemma: + create_fake_model_files(include_prompt_enhancer=True) + else: + settings.prompt_enhancer_provider_preference = "api" + settings.gemini_api_key = "gemini-key" + leased = {"taken": False, "released": False} + + @contextmanager + def lease() -> Iterator[bool]: + leased["taken"] = True + try: + yield True + finally: + leased["released"] = True + + with pytest.raises(GenerationCancelledError): + plan_fal_image_prompt( + test_state.prompt_enhancement, + "a fox", + provenance="typed", + generation_seed=1, + explicit_generation_seed=False, + lease_idle_gpu=lease, + raise_if_cancelled=_cancelled, + ) + + assert fake_services.prompt_enhancer_pipeline.enhance_t2v_calls == [] + assert test_state.http.calls == [] + assert leased["taken"] is gemma + assert leased["released"] is gemma diff --git a/backend/tests/test_ingredients_recipe.py b/backend/tests/test_ingredients_recipe.py index c948a52ac..c440e7ea5 100644 --- a/backend/tests/test_ingredients_recipe.py +++ b/backend/tests/test_ingredients_recipe.py @@ -28,6 +28,7 @@ from services.features.video.reference_sheet import build_reference_sheet, layout_panels from services.generation_interrupt import GenerationCancelledError from services.generation_queue.types import OutputAllocation, OutputPlan +from tests.fakes.generation import FakeJobSession from services.records import AssetRecord, GenerationRecord from tests.fakes import FakeResponse from tests.lora_catalog_helpers import add_ic_lora, download_spec @@ -332,7 +333,7 @@ def test_run_builds_the_sheet_at_the_denoise_size_and_deletes_it( recorder, assets, lambda: test_state.config.default_models_dir, recipe=IC_LORA_RECIPES["ingredients"] ) with pytest.raises(GenerationCancelledError): - executor.execute(generation, outputs) + executor.execute(generation, outputs, FakeJobSession()) assert recorder.sheet_size == budget_pixels(local_caps(resolve_job_local_model_id(test_state.config.default_models_dir, "ltx-2.5-fast")), "540p", "9:16", mode="video") assert recorder.sheet_path is not None and not recorder.sheet_path.exists() @@ -347,7 +348,7 @@ def test_run_makes_the_chosen_duration_at_the_chosen_rate_not_the_catalog_defaul executor = IcLoraSheetRecipeExecutor( test_state.ic_lora, assets, lambda: test_state.config.default_models_dir, recipe=IC_LORA_RECIPES["ingredients"] ) - executor.execute(generation, outputs) + executor.execute(generation, outputs, FakeJobSession()) assert fake_services.ic_lora_pipeline.generate_calls[-1]["num_frames"] == compute_num_frames(12, 25) @@ -485,7 +486,7 @@ def test_enhance_rejects_a_list_of_images_for_an_entry_that_takes_a_video( def _run_sheet_job(test_state, assets: _Assets, generation, outputs) -> None: IcLoraSheetRecipeExecutor( test_state.ic_lora, assets, lambda: test_state.config.default_models_dir, recipe=IC_LORA_RECIPES["ingredients"] - ).execute(generation, outputs) + ).execute(generation, outputs, FakeJobSession()) def test_generate_shows_the_reference_sheet_to_the_automatic_rewrite( @@ -556,7 +557,7 @@ def generate_local_reserved(self, request: object, **kwargs: object) -> object: recorder, assets, lambda: test_state.config.default_models_dir, recipe=IC_LORA_RECIPES["ingredients"] ) with pytest.raises(GenerationCancelledError): - executor.execute(generation, outputs) + executor.execute(generation, outputs, FakeJobSession()) assert recorder.sheet_path == sheet assert seen_pixel == (12, 34, 56) diff --git a/backend/tests/test_job_sessions.py b/backend/tests/test_job_sessions.py new file mode 100644 index 000000000..d1b7083e1 --- /dev/null +++ b/backend/tests/test_job_sessions.py @@ -0,0 +1,160 @@ +"""Job sessions: what an executor sees of cancel, progress and provider status. + +Each test names the bug it catches. +""" + +from __future__ import annotations + +import threading +import time + +from api_types import GenerationProgressResponse +from services import generation_interrupt +from services.generation_queue.lane_sessions import LaneJobSession +from services.generation_queue.sessions import LocalJobSession +from tests.fakes.generation import FakeJobSession + + +class _StickyCancelledOps: + """The generation state still says cancelled from the previous job. No interrupt is set.""" + + def start_api_generation(self, generation_id: str) -> None: + del generation_id + + def get_generation_progress(self) -> GenerationProgressResponse: + return GenerationProgressResponse( + status="cancelled", phase="cancelled", progress=0, currentStep=0, totalSteps=0, cancellable=False + ) + + def update_progress(self, phase: str, progress: int, current_step: int | None = None, total_steps: int | None = None) -> None: + del phase, progress, current_step, total_steps + + def raise_if_cancelled(self) -> None: + generation_interrupt.raise_if_requested() + + def is_generation_cancelled(self) -> bool: + return True + + def cancel_generation(self) -> object: + return None + + def complete_generation(self, result: str | list[str] | None = None) -> None: + del result + + def fail_generation(self, error: str) -> None: + del error + + +def test_local_wait_cancelled_ignores_the_sticky_cancelled_state() -> None: + # Bug caught: a new job reads the previous job's sticky "cancelled" state as its own cancel, + # so a provider call is cancelled at once. + session = LocalJobSession(_StickyCancelledOps(), "gen-1") + started = time.monotonic() + + cancelled = session.wait_cancelled(0.1) + + assert cancelled is False + assert time.monotonic() - started >= 0.09 + + +def test_local_wait_cancelled_wakes_when_the_interrupt_is_requested() -> None: + # Bug caught: a cancel waits for the end of the poll sleep. + session = LocalJobSession(_StickyCancelledOps(), "gen-1") + threading.Timer(0.05, generation_interrupt.request).start() + started = time.monotonic() + + cancelled = session.wait_cancelled(5.0) + + assert cancelled is True + assert time.monotonic() - started < 2.0 + + +def _lane_session( + generation_id: str, recorded: list[tuple[str, int, str]] | None = None +) -> LaneJobSession: + sink = recorded if recorded is not None else [] + + def record(gid: str, attempt: int, pid: str) -> bool: + sink.append((gid, attempt, pid)) + return True + + return LaneJobSession(generation_id, 2, record) + + +def test_a_lane_session_hands_the_provider_job_id_to_the_store_sink() -> None: + # Bug caught: the provider job id never reaches the store, so a job left running at stop cannot be cancelled at boot. + recorded: list[tuple[str, int, str]] = [] + session = _lane_session("gen-remote", recorded) + + stored = session.set_provider_job_id("req-123") + + assert recorded == [("gen-remote", 2, "req-123")] + assert stored is True + + +def test_a_lane_session_survives_a_store_failure_and_reports_it() -> None: + # Bug caught: a store error raises into the executor. The job fails while the provider still runs it. + def broken(generation_id: str, attempt_count: int, provider_job_id: str) -> bool: + raise OSError("disk full") + + session = LaneJobSession("gen-remote", 1, broken) + + assert session.set_provider_job_id("req-123") is False + + +def test_a_lane_session_reports_an_id_the_store_refused() -> None: + # Bug caught: the executor believes the id is stored when the job was no longer running. + session = LaneJobSession("gen-remote", 1, lambda generation_id, attempt_count, provider_job_id: False) + + assert session.set_provider_job_id("req-123") is False + + +def test_the_local_session_keeps_no_provider_job_id_and_lets_the_job_go_on() -> None: + # Bug caught: a fal job on the local lane (the kill switch) fails, as its id has nowhere to go. + session = LocalJobSession(_StickyCancelledOps(), "gen-1") + + assert session.set_provider_job_id("req-123") is True + + +def test_a_lane_session_cancel_does_not_touch_the_process_wide_interrupt() -> None: + # Bug caught: cancelling a remote job sets the global flag and stops the local job. + session = _lane_session("gen-remote") + + session.cancel() + + assert session.wait_cancelled(0) is True + assert generation_interrupt.is_requested() is False + + +def test_a_lane_session_wait_cancelled_wakes_at_once_on_cancel() -> None: + # Bug caught: the provider poll sleeps its whole interval after a cancel and the lane stays busy. + session = _lane_session("gen-remote") + threading.Timer(0.05, session.cancel).start() + started = time.monotonic() + + assert session.wait_cancelled(5.0) is True + assert time.monotonic() - started < 2.0 + + +def test_two_lane_sessions_keep_separate_progress_and_status() -> None: + # Bug caught: lane jobs share one progress slot and show each other's numbers. + first, second = _lane_session("a"), _lane_session("b") + + first.set_progress("inference", 40, None, None) + first.set_api_status("processing") + + assert second.progress() is None + assert second.api_status() is None + progress = first.progress() + assert progress is not None and progress.progress == 40 + assert first.api_status() == "processing" + + +def test_the_fake_session_records_progress_and_still_answers_the_progress_reader() -> None: + # Bug caught: a recording list named `progress` hides the progress() method of the JobSession protocol. + session = FakeJobSession() + + session.set_progress("inference", 40, None, None) + + assert session.progress_updates == [("inference", 40)] + assert session.progress() is None diff --git a/backend/tests/test_keyframes_create.py b/backend/tests/test_keyframes_create.py new file mode 100644 index 000000000..001400bfe --- /dev/null +++ b/backend/tests/test_keyframes_create.py @@ -0,0 +1,148 @@ +"""POST /api/generations/keyframes: the flag gate, what the row stores, and the refusals.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from PIL import Image +from pydantic import JsonValue +from starlette.testclient import TestClient + +from remote.app import create_remote_app +from services.sqlite_store import SqliteStore +from tests.http_error_assertions import assert_http_error + +_AUTH = {"Authorization": "Bearer pair-token"} + + +def _rows(test_state) -> list[object]: + return list(SqliteStore(test_state.config.app_data_dir).list_generations("keyframes")) + + +def _asset(client: TestClient, tmp_path: Path, name: str) -> tuple[str, str]: + path = tmp_path / name + Image.new("RGB", (16, 16), color=(1, 2, 3)).save(path) + created = client.post("/api/assets", json={"path": str(path)}) + assert created.status_code == 200, created.text + return created.json()["id"], str(path) + + +def _body( + keyframes: list[dict[str, JsonValue]], *, duration: int | None = 5 +) -> dict[str, JsonValue]: + return { + "params": { + "prompt": "a fox runs", + "model": "ltx-2.5-fast", + "aspectRatio": "16:9", + "resolution": "540p", + "duration": duration, + "fps": 24, + }, + "inputs": {"keyframes": keyframes}, + } + + +def _enable(client: TestClient) -> None: + flags = client.request("PATCH", "/api/feature-flags", json={"keyframes": True}) + assert flags.status_code == 200, flags.text + + +def test_create_refuses_while_the_flag_is_off_and_queues_nothing( + client, test_state, create_fake_model_files, tmp_path: Path +) -> None: + create_fake_model_files() + asset_id, _ = _asset(client, tmp_path, "a.png") + + refused = client.post( + "/api/generations/keyframes", + json=_body([{"assetId": asset_id, "frameIndex": 0, "strength": 1}]), + ) + + assert_http_error(refused, status_code=422, code="KEYFRAMES_NOT_ENABLED") + assert _rows(test_state) == [] + + +def test_create_stores_asset_ids_and_never_a_file_path( + client, test_state, create_fake_model_files, tmp_path: Path +) -> None: + create_fake_model_files() + _enable(client) + first_id, first_path = _asset(client, tmp_path, "a.png") + last_id, last_path = _asset(client, tmp_path, "b.png") + keyframes: list[dict[str, JsonValue]] = [ + {"assetId": first_id, "frameIndex": 0, "strength": 1}, + {"assetId": last_id, "frameIndex": 120, "strength": 0.5}, + ] + + created = client.post("/api/generations/keyframes", json=_body(keyframes)) + + assert created.status_code == 200, created.text + spec = created.json()["spec"] + assert spec["inputs"] == {"keyframes": keyframes} + stored = json.dumps(spec) + assert first_path not in stored + assert last_path not in stored + assert len(_rows(test_state)) == 1 + + +@pytest.mark.parametrize( + ("case", "frames", "duration"), + [ + ("two stills on one frame", [10, 10], 5), + # 5 s at 24 fps is 121 frames, so the last frame index is 120. + ("a frame past the clip end", [0, 121], 5), + ("no clip length", [0, 10], None), + ("more stills than the limit", list(range(0, 11 * 8, 8)), 8), + ], +) +def test_create_refuses_bad_timelines_and_queues_nothing( + client, + test_state, + create_fake_model_files, + tmp_path: Path, + case: str, + frames: list[int], + duration: int | None, +) -> None: + create_fake_model_files() + _enable(client) + asset_id, _ = _asset(client, tmp_path, "a.png") + keyframes: list[dict[str, JsonValue]] = [ + {"assetId": asset_id, "frameIndex": frame, "strength": 1} for frame in frames + ] + + refused = client.post("/api/generations/keyframes", json=_body(keyframes, duration=duration)) + + assert refused.status_code == 422, case + assert _rows(test_state) == [] + + +def test_remote_create_is_blocked_by_the_flag_and_then_hides_paths( + test_state, create_fake_model_files, tmp_path: Path +) -> None: + create_fake_model_files() + app = create_remote_app(handler=test_state, remote_token="pair-token") + path = tmp_path / "a.png" + Image.new("RGB", (16, 16), color=(1, 2, 3)).save(path) + with TestClient(app) as remote: + uploaded = remote.post( + "/api/assets/upload", + headers=_AUTH, + files={"file": ("a.png", path.read_bytes(), "image/png")}, + ) + asset_id = uploaded.json()["id"] + body = _body([{"assetId": asset_id, "frameIndex": 0, "strength": 1}]) + + refused = remote.post("/api/generations/keyframes", headers=_AUTH, json=body) + remote.request("PATCH", "/api/feature-flags", headers=_AUTH, json={"keyframes": True}) + created = remote.post("/api/generations/keyframes", headers=_AUTH, json=body) + + assert_http_error(refused, status_code=422, code="KEYFRAMES_NOT_ENABLED") + assert created.status_code == 200, created.text + assert created.json()["spec"]["inputs"] == { + "keyframes": [{"assetId": asset_id, "frameIndex": 0, "strength": 1}] + } + assert "path" not in json.dumps(created.json()["spec"]) diff --git a/backend/tests/test_linux_disk_streaming_backend.py b/backend/tests/test_linux_disk_streaming_backend.py deleted file mode 100644 index 45d28c62d..000000000 --- a/backend/tests/test_linux_disk_streaming_backend.py +++ /dev/null @@ -1,260 +0,0 @@ -"""Linux disk streaming uses pread only when mmap would hit ENOMEM. Other platforms are untouched.""" - -from __future__ import annotations - -import logging -import sys -from pathlib import Path - -import pytest -import safetensors -import torch -from ltx_core.block_streaming.disk import DiskTensorReader -from safetensors.torch import save_file - -import services.patches.disk_streaming_pread as darwin_pread -import services.patches.linux_disk_streaming_backend as linux - -GIB = 1024**3 -KIB_PER_GIB = 1024**2 -# A "32 GB" host: the kernel reports ~31 GiB of MemTotal. 31 + 11 GiB swap = 42 GiB < 43 GiB checkpoint. -MEMINFO_32G_HOST = {"MemTotal": 31 * KIB_PER_GIB, "SwapTotal": 11 * KIB_PER_GIB} -CHECKPOINT_46GB = 46_149_345_334 # ltx-2.3-22b-distilled-1.1.safetensors (LTX-Desktop#163) - - -@pytest.fixture(autouse=True) -def _isolate(monkeypatch: pytest.MonkeyPatch): - monkeypatch.delenv(linux.ENV_BACKEND, raising=False) - original_init = DiskTensorReader.__init__ - original_open = safetensors.safe_open - yield - DiskTensorReader.__init__ = original_init # type: ignore[method-assign] - safetensors.safe_open = original_open # type: ignore[assignment] - for module in (linux, darwin_pread): - module._installed = False - module._checked = False - module._original_init = None - - -def _fake_proc( - monkeypatch: pytest.MonkeyPatch, tmp_path: Path, overcommit: str, meminfo_kib: dict[str, int] -) -> None: - overcommit_file = tmp_path / "overcommit_memory" - overcommit_file.write_text(f"{overcommit}\n") - meminfo_file = tmp_path / "meminfo" - meminfo_file.write_text("".join(f"{key}: {kib} kB\n" for key, kib in meminfo_kib.items())) - monkeypatch.setattr(linux, "_PROC_OVERCOMMIT", overcommit_file) - monkeypatch.setattr(linux, "_PROC_MEMINFO", meminfo_file) - - -def _open_with_spy(path: Path) -> list[dict[str, object]]: - seen: list[dict[str, object]] = [] - original_open = safetensors.safe_open - - def _spy(*args: object, **kwargs: object): - seen.append(dict(kwargs)) - return original_open(*args, **kwargs) - - safetensors.safe_open = _spy # type: ignore[assignment] - try: - DiskTensorReader([str(path)]).close() - finally: - safetensors.safe_open = original_open - return seen - - -def _tiny_checkpoint(tmp_path: Path) -> Path: - path = tmp_path / "tiny.safetensors" - save_file({"weight": torch.ones(2, 2)}, str(path)) - return path - - -def _install_on_linux(monkeypatch: pytest.MonkeyPatch, *, refused: bool) -> None: - monkeypatch.setattr(sys, "platform", "linux") - monkeypatch.setattr(linux, "mmap_would_be_refused", lambda _size: refused) - linux.install() - - -# --- kernel refusal rule --- - - -def test_refused_when_heuristic_overcommit_and_file_exceeds_ram_plus_swap( - monkeypatch: pytest.MonkeyPatch, tmp_path: Path -) -> None: - _fake_proc(monkeypatch, tmp_path, "0", MEMINFO_32G_HOST) - assert linux.mmap_would_be_refused(CHECKPOINT_46GB) is True - - -def test_allowed_when_file_fits_in_ram_plus_swap(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: - _fake_proc(monkeypatch, tmp_path, "0", MEMINFO_32G_HOST) - assert linux.mmap_would_be_refused(30 * GIB) is False - - -def test_allowed_when_overcommit_always(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: - _fake_proc(monkeypatch, tmp_path, "1", MEMINFO_32G_HOST) - assert linux.mmap_would_be_refused(CHECKPOINT_46GB) is False - - -def test_refused_when_strict_overcommit_leaves_too_little_commit_headroom( - monkeypatch: pytest.MonkeyPatch, tmp_path: Path -) -> None: - meminfo = {**MEMINFO_32G_HOST, "CommitLimit": 27 * KIB_PER_GIB, "Committed_AS": 5 * KIB_PER_GIB} - _fake_proc(monkeypatch, tmp_path, "2", meminfo) - assert linux.mmap_would_be_refused(23 * GIB) is True - assert linux.mmap_would_be_refused(21 * GIB) is False - - -def test_stays_mmap_when_proc_is_unreadable(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: - monkeypatch.setattr(linux, "_PROC_OVERCOMMIT", tmp_path / "missing") - monkeypatch.setattr(linux, "_PROC_MEMINFO", tmp_path / "missing") - assert linux.mmap_would_be_refused(CHECKPOINT_46GB) is False - - -# --- DiskTensorReader backend selection on Linux --- - - -def test_uses_pread_when_mmap_would_be_refused( - monkeypatch: pytest.MonkeyPatch, tmp_path: Path, caplog: pytest.LogCaptureFixture -) -> None: - path = _tiny_checkpoint(tmp_path) - _install_on_linux(monkeypatch, refused=True) - with caplog.at_level(logging.INFO, logger=linux.logger.name): - seen = _open_with_spy(path) - assert seen == [{"framework": "pt", "device": "cpu", "backend": "pread"}] - assert "mmap would be refused" in caplog.text - - -def test_keeps_mmap_when_it_fits(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: - path = _tiny_checkpoint(tmp_path) - _install_on_linux(monkeypatch, refused=False) - assert _open_with_spy(path) == [{"framework": "pt", "device": "cpu"}] - - -def test_pread_reader_returns_the_tensor(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: - path = _tiny_checkpoint(tmp_path) - _install_on_linux(monkeypatch, refused=True) - reader = DiskTensorReader([str(path)]) - try: - torch.testing.assert_close(reader.get_tensor("weight"), torch.ones(2, 2)) - finally: - reader.close() - - -def test_install_is_idempotent_on_linux(monkeypatch: pytest.MonkeyPatch) -> None: - _install_on_linux(monkeypatch, refused=False) - first = DiskTensorReader.__init__ - linux.install() - assert DiskTensorReader.__init__ is first - - -def test_install_leaves_mmap_when_backend_is_unsupported( - monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture -) -> None: - monkeypatch.setattr(sys, "platform", "linux") - monkeypatch.setattr(linux.inspect, "signature", lambda _fn: type("Sig", (), {"parameters": {}})()) - before = DiskTensorReader.__init__ - linux.install() - assert DiskTensorReader.__init__ is before - with caplog.at_level(logging.WARNING, logger=linux.logger.name): - linux.log_status() - assert "stays on mmap" in caplog.text - - -# --- override flag --- - - -def test_flag_pread_forces_pread_when_mmap_would_work(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: - path = _tiny_checkpoint(tmp_path) - _install_on_linux(monkeypatch, refused=False) - monkeypatch.setenv(linux.ENV_BACKEND, "pread") - assert _open_with_spy(path) == [{"framework": "pt", "device": "cpu", "backend": "pread"}] - - -def test_flag_mmap_forces_mmap_when_kernel_would_refuse(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: - path = _tiny_checkpoint(tmp_path) - _install_on_linux(monkeypatch, refused=True) - monkeypatch.setenv(linux.ENV_BACKEND, "mmap") - assert _open_with_spy(path) == [{"framework": "pt", "device": "cpu"}] - - -@pytest.mark.parametrize("value", ["auto", "", " AUTO "]) -def test_flag_auto_keeps_kernel_driven_choice( - value: str, monkeypatch: pytest.MonkeyPatch, tmp_path: Path -) -> None: - path = _tiny_checkpoint(tmp_path) - _install_on_linux(monkeypatch, refused=True) - monkeypatch.setenv(linux.ENV_BACKEND, value) - assert _open_with_spy(path) == [{"framework": "pt", "device": "cpu", "backend": "pread"}] - - -def test_flag_invalid_value_warns_and_acts_like_auto( - monkeypatch: pytest.MonkeyPatch, tmp_path: Path, caplog: pytest.LogCaptureFixture -) -> None: - path = _tiny_checkpoint(tmp_path) - _install_on_linux(monkeypatch, refused=True) - monkeypatch.setenv(linux.ENV_BACKEND, "preadd") - with caplog.at_level(logging.WARNING, logger=linux.logger.name): - seen = _open_with_spy(path) - assert seen == [{"framework": "pt", "device": "cpu", "backend": "pread"}] - assert "LTX_LINUX_DISK_STREAM_BACKEND" in caplog.text - assert "preadd" in caplog.text - - -def test_log_status_reports_flag_override(monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture) -> None: - _install_on_linux(monkeypatch, refused=False) - monkeypatch.setenv(linux.ENV_BACKEND, "pread") - with caplog.at_level(logging.INFO, logger=linux.logger.name): - linux.log_status() - assert "LTX_LINUX_DISK_STREAM_BACKEND=pread" in caplog.text - - -# --- isolation from macOS and Windows --- - - -@pytest.mark.parametrize("platform", ["darwin", "win32"]) -@pytest.mark.parametrize("flag", [None, "pread", "mmap", "garbage"]) -def test_install_touches_nothing_off_linux( - platform: str, flag: str | None, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture -) -> None: - monkeypatch.setattr(sys, "platform", platform) - if flag is not None: - monkeypatch.setenv(linux.ENV_BACKEND, flag) - init_before = DiskTensorReader.__init__ - open_before = safetensors.safe_open - with caplog.at_level(logging.DEBUG): - linux.install() - linux.log_status() - assert DiskTensorReader.__init__ is init_before - assert safetensors.safe_open is open_before - assert linux._installed is False - assert linux._checked is False - assert caplog.text == "" - - -def test_darwin_pread_patch_is_unchanged_when_both_patches_are_installed( - monkeypatch: pytest.MonkeyPatch, tmp_path: Path -) -> None: - path = _tiny_checkpoint(tmp_path) - monkeypatch.setattr(sys, "platform", "darwin") - monkeypatch.setenv(linux.ENV_BACKEND, "mmap") # Darwin must ignore the Linux flag. - darwin_pread.install() - linux.install() - assert _open_with_spy(path) == [{"framework": "pt", "device": "cpu", "backend": "pread"}] - - -@pytest.mark.parametrize("platform", ["darwin", "win32"]) -def test_linux_module_does_not_import_ml_stack_off_linux(platform: str) -> None: - """A fresh interpreter installing on macOS/Windows imports neither safetensors nor ltx_core.""" - import subprocess - - code = ( - "import sys; " - "import services.patches.linux_disk_streaming_backend as m; " - "sys.platform = %r; m.install(); m.log_status(); " - "bad = [n for n in ('safetensors', 'ltx_core') if n in sys.modules]; " - "sys.exit(1 if bad else 0)" - ) % platform - backend_dir = Path(__file__).resolve().parents[1] - result = subprocess.run([sys.executable, "-c", code], cwd=backend_dir, capture_output=True, text=True) - assert result.returncode == 0, result.stderr - diff --git a/backend/tests/test_local_compat_matrix.py b/backend/tests/test_local_compat_matrix.py index 7f8663c17..7f7cd7f76 100644 --- a/backend/tests/test_local_compat_matrix.py +++ b/backend/tests/test_local_compat_matrix.py @@ -26,7 +26,7 @@ def test_windows_bands_cover_stream_and_ram_gate() -> None: assert "Windows streamed Fast needs **40** GiB total RAM" in md assert "ram_shortfall" in md assert "free VRAM" in md - assert "maps weights from disk and the RAM floor is **32** GiB" in md + assert "reads weights from disk and the RAM floor is **24** GiB" in md def test_darwin_keeps_ceiling_and_ic_lora_footnote() -> None: diff --git a/backend/tests/test_ltx_contract.py b/backend/tests/test_ltx_contract.py index 3e64020ed..39aaa584e 100644 --- a/backend/tests/test_ltx_contract.py +++ b/backend/tests/test_ltx_contract.py @@ -69,30 +69,6 @@ def test_initial_latent_helpers_take_explicit_scale_factors() -> None: assert "video_scale_factors" in _params(helpers.create_initial_audio_latent) -def test_keyframe_swap_targets_exist_in_both_modules() -> None: - """`distilled_keyframe_guiding` rebinds this name in both modules.""" - for module in (helpers, chunk_conditionings): - assert callable(module.combined_image_conditionings) - assert callable(helpers.image_conditionings_by_adding_guiding_latent) - - -def test_chunk_keyframes_resolve_the_swappable_name_from_the_chunks_module() -> None: - """The per-chunk factory looks the name up in its module globals at call time. - - If upstream stops doing that (e.g. binds it as a default argument), swapping the - module attribute silently stops changing multi-keyframe behaviour. - """ - from services.fast_video_pipeline.distilled_keyframe_guiding import distilled_keyframe_guiding - - factory_globals = chunk_conditionings.image_conditionings_for_chunk.__globals__ - assert factory_globals is vars(chunk_conditionings) - - with distilled_keyframe_guiding(): - assert factory_globals["combined_image_conditionings"] is helpers.image_conditionings_by_adding_guiding_latent - - assert factory_globals["combined_image_conditionings"] is not helpers.image_conditionings_by_adding_guiding_latent - - def test_ic_lora_override_point_and_stage_config() -> None: assert _params(ICLoraPipeline._video_conditionings) == ["self", "ctx", "stage_config", "frame_sources"] # type: ignore[attr-defined] assert "apply_ic_lora" in {field.name for field in dataclasses.fields(ICLoraStageConfig)} diff --git a/backend/tests/test_ltx_image_inputs.py b/backend/tests/test_ltx_image_inputs.py new file mode 100644 index 000000000..2a6430015 --- /dev/null +++ b/backend/tests/test_ltx_image_inputs.py @@ -0,0 +1,56 @@ +"""Desktop stills map to ltx-pipelines image bindings.""" + +from __future__ import annotations + +from api_types import ImageConditioningInput +from ltx_pipelines.utils.types import ImageGuide, ImageReplace +from services.ltx_pipeline_common import to_ltx_images + + +def test_first_frame_replaces_and_later_frames_guide() -> None: + images = to_ltx_images( + [ImageConditioningInput("a.png", 0, 0.9), ImageConditioningInput("b.png", 48, 1.0)] + ) + + assert [image.binding for image in images] == [ImageReplace(0), ImageGuide(48)] + assert [image.strength for image in images] == [0.9, 1.0] + + +def test_guide_all_keeps_the_first_frame_as_a_keyframe() -> None: + """Multi-keyframe interpolation regressed to replace-at-0 when frame 0 was not a guide.""" + images = to_ltx_images( + [ImageConditioningInput("a.png", 0, 1.0), ImageConditioningInput("b.png", 48, 1.0)], guide_all=True + ) + + assert [image.binding for image in images] == [ImageGuide(0), ImageGuide(48)] + + +def test_reference_still_at_minus_one_is_a_guide_not_a_replace() -> None: + """A replace binding rejects a negative frame, which broke Layout To Render.""" + (image,) = to_ltx_images([ImageConditioningInput("look.png", -1, 1.0)]) + + assert image.binding == ImageGuide(-1) + + +def test_fast_pipeline_passes_guide_all_to_the_ltx_bindings() -> None: + """Multi-keyframe interpolation fell back to replace-at-0 when ``_run_inference`` ignored the flag.""" + from types import SimpleNamespace + + from services.fast_video_pipeline.ltx_fast_video_pipeline import LTXFastVideoPipeline + + seen: list[object] = [] + + def pipeline(**kwargs: object) -> SimpleNamespace: + seen.append(kwargs["images"]) + return SimpleNamespace(video=iter(()), audio=None, num_frames=9, tiling_config=None) + + runner = LTXFastVideoPipeline.__new__(LTXFastVideoPipeline) + runner.pipeline = pipeline # type: ignore[assignment] + + runner._run_inference( # pyright: ignore[reportPrivateUsage] + prompt="p", seed=1, height=64, width=64, num_frames=9, frame_rate=24.0, + images=[ImageConditioningInput("a.png", 0, 1.0), ImageConditioningInput("b.png", 8, 1.0)], + tiling_config=None, guide_all_images=True, # type: ignore[arg-type] + ) + + assert [image.binding for image in seen[0]] == [ImageGuide(0), ImageGuide(8)] # type: ignore[attr-defined] diff --git a/backend/tests/test_mac_fast_chunked_budget.py b/backend/tests/test_mac_fast_chunked_budget.py index f3ccd90e1..694a1c785 100644 --- a/backend/tests/test_mac_fast_chunked_budget.py +++ b/backend/tests/test_mac_fast_chunked_budget.py @@ -1,16 +1,19 @@ """Mac Fast windowed price at 1440p and 4K (``decide_video_job`` on the Darwin route). Each test names the bug it guards. The Mac law prices the smallest allocator cap that still -passes, so the reference points are capped runs: at 4K a cap of 22.7 GiB failed and 24.0 -passed for two windows, and 28.4 failed and 30.0 passed for seven. +passes, so the reference points are capped runs: at 4K a cap of 22.7 GiB failed and 23.4 +passed for two windows (73f), and 28.4 failed and 29.2 passed for seven (241f). """ from __future__ import annotations import pytest +from runtime_config.budget_admission import Admitted, RiskAllowance +from runtime_config.fast_chunking import window_candidates from runtime_config.measured_cells import MEASURED_HIGH_RES_CELLS from runtime_config.video_job_budget import ( + NOMINAL_MPS_POOL_RATIO, VideoJobLoad, VideoJobReject, _mac_fast_stream_required_gib, @@ -19,10 +22,12 @@ fast_job_stream_gib, video_tokens, ) -from tests.test_video_job_budget import _job_filter, _mac_profile +from tests.test_video_job_budget import _MAC_HOST_GIB, _cap, _job_filter, _mac_profile _4K = (3840, 2176) _1440P = (2560, 1472) +_1440P_9_16 = (1472, 2624) +_1440P_21_9 = (3456, 1472) _4K_WINDOW_TOKENS = video_tokens(_4K[1], _4K[0], 49) _1440P_WINDOW_TOKENS = video_tokens(_1440P[1], _1440P[0], 129) @@ -31,7 +36,10 @@ def _decide(size: tuple[int, int], frames: int, pool_gib: float): job_filter = _job_filter( process_mode="streaming_models_loading", memory_gb=None, **_mac_profile(pool_gib=pool_gib) ) - return decide_video_job(*size, frames, job_filter=job_filter) + admission = decide_video_job( + *size, frames, job_filter=job_filter, allowance=RiskAllowance.none() + ) + return admission.load if isinstance(admission, Admitted) else admission.reject def _mac_ask(tokens: float, windows: int) -> float: @@ -39,23 +47,33 @@ def _mac_ask(tokens: float, windows: int) -> float: def test_mac_plateau_ask_covers_the_capped_4k_edge() -> None: - # A cap of 28.4 GiB failed a 7-window 4K job and 30.0 passed. The fixed 5.7 asked 28.39, - # and the Windows coefficient put on the Mac asks 28.7: both admit a pool that fails. - assert _mac_ask(_4K_WINDOW_TOKENS, 7) >= 30.0 + # A cap of 28.4 GiB failed a 7-window 4K job and 29.2 passed (29.07 peak, capbound=n). + # The fixed 5.7 asked 28.39, and the Windows coefficient put on the Mac asks 28.69: + # both admit a pool that fails or under-asks the 29.2 passing cap. + assert _mac_ask(_4K_WINDOW_TOKENS, 7) >= 29.2 assert _mac_ask(_4K_WINDOW_TOKENS, 7) == _mac_ask(_4K_WINDOW_TOKENS, 3) - assert isinstance(_decide(_4K, 241, 30.2), VideoJobLoad) + assert isinstance(_decide(_4K, 241, _cap(29.3)), VideoJobLoad) def test_mac_two_window_ask_pays_the_second_window_step() -> None: - # A cap of 22.7 GiB failed the 73-frame 4K job (2 windows) and 24.0 passed. A +0 - # two-window price asked 22.69 there, and 24.51 for a 1440p 241-frame job whose second - # window peaked about 3.7 GiB over its first. - assert _mac_ask(_4K_WINDOW_TOKENS, 2) >= 24.0 - assert _mac_ask(_1440P_WINDOW_TOKENS, 2) >= _mac_ask(_1440P_WINDOW_TOKENS, 1) + 3.72 - refused = _decide(_4K, 73, 22.7) + # A cap of 22.7 GiB failed the 73-frame 4K job (2 windows: 49f then 41f) and 24.0 passed. + # Pricing 2 windows from last_window_frames must keep 73f at or above the 24.0 passing cap + # while fitting a 24.96 GiB MPS budget, and keep the full-last-window 1440p 241f job at + # 29.52 GiB (>= 29.25 passing cap). + short_4k = _decide(_4K, 73, _cap(24.96)) + assert isinstance(short_4k, VideoJobLoad) + assert short_4k.chunk_pixel_frames == 49 + assert short_4k.stream_gib - _MAC_HOST_GIB >= 24.0 + refused = _decide(_4K, 73, _cap(22.7)) assert isinstance(refused, VideoJobReject) assert refused.reason == "stream_over" + short_1440p = _decide(_1440P, 145, _cap(24.96)) + assert isinstance(short_1440p, VideoJobLoad) + assert short_1440p.chunk_pixel_frames == 129 + assert short_1440p.stream_gib == pytest.approx(_mac_ask(_1440P_WINDOW_TOKENS, 1) + _MAC_HOST_GIB) + assert _mac_ask(_1440P_WINDOW_TOKENS, 2) >= _mac_ask(_1440P_WINDOW_TOKENS, 1) + 3.72 + def test_mac_windowed_extra_scales_with_window_tokens() -> None: # A fixed Mac extra asks the same for a 41-frame window as for a 129-frame one, and @@ -81,7 +99,7 @@ def test_mac_single_window_ask_is_the_base_law() -> None: def test_windows_and_mac_windowed_coefficients_stay_separate() -> None: # One shared constant or branch would move both routes when either is refit. tokens = _4K_WINDOW_TOKENS - for windows, mac_coefficient, windows_coefficient in ((2, 7.5e-5, 6.5e-5), (3, 1.30e-4, 1.05e-4)): + for windows, mac_coefficient, windows_coefficient in ((2, 8.0e-5, 6.5e-5), (3, 1.15e-4, 1.05e-4)): mac_extra = _mac_ask(tokens, windows) - _mac_fast_stream_required_gib(tokens) assert mac_extra == pytest.approx(mac_coefficient * tokens) windows_extra = fast_job_stream_gib( @@ -103,11 +121,43 @@ def test_mac_fast_4k_row_loads_at_7_windows_and_refuses_at_8() -> None: assert ("iclora", "mac_measured", "2160p") not in MEASURED_HIGH_RES_CELLS -@pytest.mark.parametrize("frames", [121, 241, 481]) -def test_mac_fast_1440p_stays_unmeasured_at_every_window_count(frames: int) -> None: - # 1 window (121 frames), 2 windows (241) and 5 windows (481) of 129 frames were run - # native only; the allocator edge was never capped. A Mac 1440p row, or the 4K row - # keyed on the wrong tier, would open these in Standard mode. - refused = _decide(_1440P, frames, 107.52) - assert isinstance(refused, VideoJobReject) - assert refused.reason == "unmeasured_cell" +def test_mac_fast_1440p_row_loads_at_5_windows_and_refuses_at_6() -> None: + # 481 frames is 5 windows of 129, 601 (12 s at 50 fps) is 6. A row on the wrong + # tier, feature or route, or off by one, moves this boundary. + assert MEASURED_HIGH_RES_CELLS[("fast", "mac_measured", "1440p")] == 5 + at_row = _decide(_1440P, 481, 107.52) + assert isinstance(at_row, VideoJobLoad) + assert at_row.chunk_pixel_frames == 129 + past_row = _decide(_1440P, 601, 107.52) + assert isinstance(past_row, VideoJobReject) + assert past_row.reason == "unmeasured_cell" + + +def test_mac_1440p_asks_cover_their_lowest_passing_caps() -> None: + # Capped 1440p runs (129-frame windows) passed at 24.3 (1w), 29.25 (2w) and 31.7 GiB + # (5w) and failed at 23.3, 28.0 and 30.7. A coefficient drop (1.15e-4 -> 1.10e-4 or + # 8.0e-5 -> 7.0e-5) puts an ask under a measured passing cap. + assert _mac_ask(_1440P_WINDOW_TOKENS, 1) >= 24.3 + assert _mac_ask(_1440P_WINDOW_TOKENS, 2) >= 29.25 + assert _mac_ask(_1440P_WINDOW_TOKENS, 5) >= 31.7 + + +def test_mac_1440p_parts_shorter_than_129_frames_are_offered_in_cautious() -> None: + # Every Mac 1440p run used 129-frame parts. A 32 GB Mac steps 1440p 10 s (241 frames) + # down to shorter parts, and the longest 9:16 and 21:9 parts are shorter than 129 on + # every Mac. A 129-frame floor stops the 32 GB Mac at 8 s of 1440p, 9:16 at 5 s and + # 21:9 at 3 s (one pass) even on a 48 GB Mac. + mac_32_gb = _decide(_1440P, 241, 32 * NOMINAL_MPS_POOL_RATIO) + assert isinstance(mac_32_gb, VideoJobLoad) + assert mac_32_gb.chunk_pixel_frames is not None and mac_32_gb.chunk_pixel_frames < 129 + for size, frames in ((_1440P_9_16, 481), (_1440P_21_9, 241)): + loaded = _decide(size, frames, 48 * NOMINAL_MPS_POOL_RATIO) + assert isinstance(loaded, VideoJobLoad) + assert loaded.chunk_pixel_frames == window_candidates(*size)[0] < 129 + + +def test_mac_1440p_row_stays_off_other_features() -> None: + # Adding the Mac 1440p row under the wrong feature key would open unmeasured IC-LoRA + # or edit cells on Darwin. + assert ("iclora", "mac_measured", "1440p") not in MEASURED_HIGH_RES_CELLS + assert ("edit", "mac_measured", "1440p") not in MEASURED_HIGH_RES_CELLS diff --git a/backend/tests/test_mac_fast_queued.py b/backend/tests/test_mac_fast_queued.py index 4ad80dfed..ab3cc4a5a 100644 --- a/backend/tests/test_mac_fast_queued.py +++ b/backend/tests/test_mac_fast_queued.py @@ -13,10 +13,12 @@ from app_factory import create_app from remote.app import create_remote_app +from runtime_config.budget_admission import unmeasured_refusal_message from runtime_config.video_job_budget import VIDEO_JOB_TOO_LARGE from services.sqlite_store import SqliteStore from tests.conftest import TEST_ADMIN_TOKEN from tests.http_error_assertions import assert_http_error +from tests.test_video_job_budget import _cap _GIB = 1024**3 _REMOTE_AUTH = {"Authorization": "Bearer pair-token"} @@ -84,40 +86,31 @@ def _mac_specs(test_state, fake_services, create_fake_model_files, *, pool_gib: return r.json()["local_models"][0]["spec"] -def test_mac_specs_name_1080p_20s_refusal_with_fence_copy( +def test_mac_specs_list_1080p_20s_as_untested_windows_past_the_fence( test_state, fake_services, create_fake_model_files ) -> None: - """1080p/20s is budget-decided, not statically absent: refused with copy. + """1080p/20s trips the MPS sequence fence in one pass, so it runs in windows. - 124k tokens trip the MPS sequence fence before the pool comparison, so the - verdict is fixed copy at every pool — pool figures would mislead. + A 16 GiB pool (smaller than any supported Mac's, so its windows are short) needs + more windows than any Mac run, so Cautious mode withholds + them, and the dropped cell says so instead of quoting a fence the user cannot act on. """ local_spec = _mac_specs( - test_state, fake_services, create_fake_model_files, pool_gib=32 + test_state, fake_services, create_fake_model_files, pool_gib=16 ) kept_24 = local_spec["supported_resolutions_durations"]["1080p"]["fps_to_durations"]["24"] assert 20 not in kept_24 assert kept_24 == [2, 3, 4, 5, 6, 8, 10] for audio in (False, True): - assert { - "resolution": "1080p", - "fps": 24, - "duration": 20, - "reason": "mps_sequence_over", - "message": ( - "This job is too long for this Mac's GPU to run in one pass. " - "Lower the resolution, duration, frame rate, or aspect width." - ), - "audio": audio, - "over_gib": None, - "over_ram_gb": None, - "shortfall_kind": None, - "readout": None, - # One pass is refused by the fence: no window is offered instead. - "windows": None, - "window_frames": None, - } in local_spec["dropped_cells"] + cell = next( + c for c in local_spec["dropped_cells"] + if c["resolution"] == "1080p" and c["fps"] == 24 and c["duration"] == 20 and c["audio"] is audio + ) + assert cell["reason"] == "unmeasured_cell" + assert cell["message"] == unmeasured_refusal_message("windowed_range") + assert cell["unmeasured_basis"] == "windowed_range" + assert cell["windows"] is not None and cell["windows"] > 1 @pytest.mark.parametrize("surface", ["home", "remote"]) @@ -126,7 +119,7 @@ def test_mac_over_fence_rejects_queued_t2v_before_insert( ) -> None: """Mac create-time preflight 422s the MPS-fenced combo; without it the combo queues and SIGABRTs late.""" create_fake_model_files() - _configure_mac_fast(test_state, fake_services, pool_gib=32) + _configure_mac_fast(test_state, fake_services, pool_gib=16) with _surface_client(test_state, surface) as (client, headers): response = client.post( @@ -139,10 +132,7 @@ def test_mac_over_fence_rejects_queued_t2v_before_insert( response, status_code=422, code=VIDEO_JOB_TOO_LARGE, - message=( - "This job is too long for this Mac's GPU to run in one pass. " - "Lower the resolution, duration, frame rate, or aspect width." - ), + message=unmeasured_refusal_message("windowed_range"), ) assert _store(test_state).list_generations("text-to-video") == [] @@ -152,7 +142,7 @@ def test_mac_over_pool_rejects_queued_a2v_before_insert( ) -> None: """A2V twin: derived frames at a refusing wider shape never reach the queue.""" create_fake_model_files() - _configure_mac_fast(test_state, fake_services, pool_gib=24) + _configure_mac_fast(test_state, fake_services, pool_gib=_cap(14)) app = create_app(handler=test_state, admin_token=TEST_ADMIN_TOKEN) with TestClient(app) as client: @@ -179,10 +169,7 @@ def test_mac_over_pool_rejects_queued_a2v_before_insert( response, status_code=422, code=VIDEO_JOB_TOO_LARGE, - message=( - "This job needs 30.9 GB of GPU memory but this Mac allows 24.0 GB. " - "Lower the resolution, duration, frame rate, or aspect width." - ), + message=unmeasured_refusal_message("windowed_range"), ) assert _store(test_state).list_generations("audio-to-video") == [] diff --git a/backend/tests/test_memory_meter_specs.py b/backend/tests/test_memory_meter_specs.py new file mode 100644 index 000000000..11749cd70 --- /dev/null +++ b/backend/tests/test_memory_meter_specs.py @@ -0,0 +1,119 @@ +"""The specs response carries what the Home memory meter draws: one ask per cell and the capacity.""" + +from __future__ import annotations + +from collections import Counter + +from api_model_specs import build_generate_video_model_specs_response +from frame_math import compute_num_frames +from runtime_config.budget_admission import PricedJob +from runtime_config.budget_decision import VideoJobLoad +from runtime_config.budget_evidence import Extrapolated, JobShape +from runtime_config.ltx_capabilities import budget_size, local_canvas +from runtime_config.memory_meter import estimate_band_gib, meter_confidence +from runtime_config.model_download_specs import get_ltx_model_spec +from runtime_config.video_job_budget import LocalJobFilter, decide_video_job +from tests.test_video_job_budget import _job_filter, _mac_profile, _windows_measured_filter + +_MODEL = "ltx-2.5-22b-distilled" + + +def _spec(job_filter: LocalJobFilter): + return build_generate_video_model_specs_response(_MODEL, job_filter=job_filter).local_models[0].spec + + +def _ask(job_filter: LocalJobFilter, resolution: str, fps: int, duration: int): + asks = _spec(job_filter).cell_asks or [] + return next( + a + for a in asks + if (a.resolution, a.fps, a.duration, a.audio) == (resolution, fps, duration, False) + ) + + +def test_a_legacy_route_1440p_cell_tagged_untested_is_rough_not_solid() -> None: + # The legacy curve tags 1440p unmeasured before it checks the route; its number is still rough. + legacy = _job_filter(memory_gb=24, process_mode="streaming_models_loading") + asks = _spec(legacy).cell_asks or [] + high_res = [a for a in asks if a.resolution in ("1440p", "2160p")] + assert high_res + assert {a.confidence for a in high_res} == {"rough"} + + +def test_an_untested_job_in_parts_is_solid_not_an_estimate() -> None: + # Mac 1440p past 5 windows is an unmeasured cell, but its peak plateaus from window 3. + mac = _job_filter(memory_gb=96, process_mode="full_models_loading", **_mac_profile(pool_gib=48)) + ask = _ask(mac, "1440p", 48, 20) + assert ask.windows == 9 + assert ask.confidence == "solid" + assert ask.band_low_gib is None and ask.band_high_gib is None + + +def test_an_untested_single_pass_is_an_estimate_with_a_band_around_its_ask() -> None: + priced = PricedJob( + feature="fast", + decision=VideoJobLoad(mode="streaming_models_loading", seq=75_480, full_gib=0, stream_gib=28.84), + evidence=Extrapolated(basis="high_res_cell"), + shape=JobShape( + feature="fast", + model_id=_MODEL, + adapter_id="", + stage_mode="", + tiled=False, + chunked=False, + seq=75_480, + canvas_px=1920 * 1088, + windows=1, + ), + ) + for route in ("windows_measured", "mac_measured"): + assert meter_confidence(priced, route=route) == "estimate" + band = estimate_band_gib(28.84, route=route) + assert band is not None + low, high = band + assert low < 28.84 < high + + +def test_an_ask_is_never_rounded_below_the_figure_the_gate_compared() -> None: + win16 = _windows_measured_filter(16, 64) + width, height = budget_size(local_canvas("1080p", mode="video")) + gate = decide_video_job(width, height, compute_num_frames(6, 24), job_filter=win16) + stream_gib = gate.priced.decision.stream_gib + ask = _ask(win16, "1080p", 24, 6) + assert stream_gib <= ask.ask_gib < stream_gib + 0.001 + + +def test_every_static_cell_has_exactly_one_ask_including_withheld_cells() -> None: + # A 16 GB card withholds most long cells; a hover preview still needs their asks. + win16 = _windows_measured_filter(16, 64) + static = get_ltx_model_spec(_MODEL).supported_pipelines[0][1] + expected = Counter( + (resolution, int(fps), duration, audio) + for audio, grid in ( + (False, static.supported_resolutions_durations), + (True, static.a2v_supported_resolutions_durations or {}), + ) + for resolution, cell in grid.items() + for fps, durations in cell.fps_to_durations.items() + for duration in durations + ) + spec = _spec(win16) + assert spec.dropped_cells, "the card must withhold cells for this to test anything" + for asks in (spec.cell_asks or [], (spec.aspect_specs or {})["1:1"].cell_asks): + listed = Counter((a.resolution, int(a.fps), a.duration, a.audio) for a in asks) + assert listed == expected + + +def test_mac_capacity_is_the_mps_pool_not_total_ram() -> None: + mac = _job_filter(memory_gb=96, process_mode="full_models_loading", **_mac_profile(pool_gib=48)) + memory = build_generate_video_model_specs_response(_MODEL, job_filter=mac).memory + assert memory is not None + assert memory.device == "mac" + assert memory.capacity_gib == 48 + + +def test_uncalibrated_non_5090_gpu_omits_cell_estimated_seconds() -> None: + win16 = _windows_measured_filter(16, 64) + ask = _ask(win16, "540p", 24, 5) + assert ask.estimated_seconds is None + diff --git a/backend/tests/test_models.py b/backend/tests/test_models.py index dace822be..4001b68d7 100644 --- a/backend/tests/test_models.py +++ b/backend/tests/test_models.py @@ -1160,6 +1160,7 @@ def test_downloaded_2_5_auto_duration_follows_its_own_duration_head( assert by_model["ltx-2.3-fast"]["spec"]["capabilities"]["auto_duration"] is False assert data["local_models"][0]["spec"]["capabilities"]["auto_duration"] is False + @pytest.mark.usefixtures("single_pass_only") def test_downloaded_2_5_row_uses_measured_profile_when_2_3_active( self, client, test_state, create_fake_model_files ): diff --git a/backend/tests/test_motion_track_executor.py b/backend/tests/test_motion_track_executor.py index c8c7762b4..5360bfe70 100644 --- a/backend/tests/test_motion_track_executor.py +++ b/backend/tests/test_motion_track_executor.py @@ -28,6 +28,7 @@ from services.features.video.motion_path import positions, render_motion_track from services.generation_interrupt import GenerationCancelledError from services.generation_queue.types import OutputAllocation, OutputPlan +from tests.fakes.generation import FakeJobSession from services.records import AssetRecord, CapabilityFailedError, GenerationRecord from tests.lora_catalog_helpers import download_spec @@ -283,7 +284,7 @@ def test_run_sends_the_camera_locked_scene_without_a_rewrite_and_the_clip_at_the executor = IcLoraTrackRecipeExecutor( test_state.ic_lora, assets, lambda: models_dir, recipe=IC_LORA_RECIPES["motion-track"] ) - executor.execute(generation, outputs) + executor.execute(generation, outputs, FakeJobSession()) expected_prompt = CAMERA_LOCK_PROMPT_TEMPLATE.replace("{prompt}", "the frog conducts") assert fake_services.ic_lora_pipeline.generate_calls[-1]["prompt"] == expected_prompt @@ -294,7 +295,7 @@ def test_run_sends_the_camera_locked_scene_without_a_rewrite_and_the_clip_at_the with pytest.raises(GenerationCancelledError): IcLoraTrackRecipeExecutor( recorder, assets, lambda: models_dir, recipe=IC_LORA_RECIPES["motion-track"] - ).execute(generation, outputs) + ).execute(generation, outputs, FakeJobSession()) request = recorder.request assert getattr(request, "prompt") == expected_prompt assert getattr(request, "prompt_provenance") == "typed" @@ -321,7 +322,7 @@ def test_run_deletes_the_control_clip_when_the_run_is_cancelled_or_fails( recorder, assets, lambda: models_dir, recipe=IC_LORA_RECIPES["motion-track"] ) with pytest.raises(RuntimeError if fail else GenerationCancelledError): - executor.execute(generation, outputs) + executor.execute(generation, outputs, FakeJobSession()) assert recorder.clip_path is not None and not recorder.clip_path.exists() @@ -335,7 +336,7 @@ def test_a_stored_high_res_spec_fails_without_the_recipe_slug_in_the_message( _ClipRecorder(), assets, lambda: models_dir, recipe=IC_LORA_RECIPES["motion-track"] ) with pytest.raises(CapabilityFailedError) as raised: - executor.execute(generation, outputs) + executor.execute(generation, outputs, FakeJobSession()) assert "cannot render above 1080p" in str(raised.value) assert "motion-track" not in str(raised.value) diff --git a/backend/tests/test_mps_conv3d_as_conv2d.py b/backend/tests/test_mps_conv3d_as_conv2d.py new file mode 100644 index 000000000..e0395c815 --- /dev/null +++ b/backend/tests/test_mps_conv3d_as_conv2d.py @@ -0,0 +1,116 @@ +"""Per-tap conv2d MPS Conv3d must match stock Conv3d. The numeric tests need an Apple Silicon GPU. + +Credit: tests first written by Sabbagh Fares (@Sabmit) in +https://github.com/Lightricks/LTX-Desktop/pull/189 +""" + +from __future__ import annotations + +import sys + +import pytest +import torch +from torch import nn + +import services.patches.mps_conv3d_as_conv2d as mps_conv3d_as_conv2d + +needs_mps = pytest.mark.skipif(not torch.backends.mps.is_available(), reason="needs MPS") + + +@pytest.fixture(autouse=True) +def _patch_enabled(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(mps_conv3d_as_conv2d, "_enabled", True) + + +def _assert_matches_stock(conv: nn.Conv3d, x: torch.Tensor, atol: float) -> None: + with torch.inference_mode(): + expected = mps_conv3d_as_conv2d._original_forward(conv, x) + actual = mps_conv3d_as_conv2d._forward(conv, x) + assert actual.shape == expected.shape + torch.testing.assert_close(actual.float(), expected.float(), atol=atol, rtol=0) + + +@needs_mps +def test_channel_sliced_channels_last_input_matches_stock_conv3d() -> None: + # MPS conv2d misreads strided input views; the decoder feeds channel slices of its workspace. + torch.manual_seed(0) + channels = 128 + conv = nn.Conv3d(channels, channels, 3, padding=(0, 1, 1)).to("mps", torch.bfloat16) + conv = conv.to(memory_format=torch.channels_last_3d) + workspace = torch.randn(1, 2 * channels, 10, 18, 32, device="mps", dtype=torch.bfloat16) + workspace = workspace.contiguous(memory_format=torch.channels_last_3d) + _assert_matches_stock(conv, workspace[:, :channels, 2:8], atol=0.1) + + +@needs_mps +@pytest.mark.parametrize( + ("stride", "padding"), + [((2, 2, 2), (0, 1, 1)), ((1, 1, 1), (1, 1, 1))], + ids=["strided", "temporally_padded"], +) +def test_strided_or_temporally_padded_conv3d_uses_original_forward( + stride: tuple[int, int, int], padding: tuple[int, int, int] +) -> None: + torch.manual_seed(0) + conv = nn.Conv3d(16, 16, 3, stride=stride, padding=padding).to("mps") + x = torch.randn(1, 16, 8, 12, 12, device="mps") + with torch.inference_mode(): + expected = mps_conv3d_as_conv2d._original_forward(conv, x) + actual = mps_conv3d_as_conv2d._forward(conv, x) + assert torch.equal(actual, expected) + + +@needs_mps +def test_input_shorter_than_temporal_kernel_uses_original_forward() -> None: + conv = nn.Conv3d(16, 16, 3, padding=(0, 1, 1)).to("mps") + x = torch.randn(1, 16, 2, 8, 8, device="mps") + assert not mps_conv3d_as_conv2d._supported(conv, x) + + +@needs_mps +def test_last_partial_chunk_matches_stock_conv3d(monkeypatch: pytest.MonkeyPatch) -> None: + torch.manual_seed(0) + channels, height, width = 32, 8, 8 + frame_bytes = channels * height * width * 4 + # 3 frames per chunk over 8 output frames: chunks of 3, 3, 2. + monkeypatch.setattr(mps_conv3d_as_conv2d, "_CHUNK_BYTES", 3 * frame_bytes) + conv = nn.Conv3d(channels, channels, 3, padding=(0, 1, 1)).to("mps") + x = torch.randn(1, channels, 10, height, width, device="mps") + _assert_matches_stock(conv, x, atol=1e-4) + + +@needs_mps +@pytest.mark.parametrize(("batch", "bias"), [(2, True), (1, False)], ids=["batch_2", "no_bias"]) +def test_batch_above_one_and_missing_bias_match_stock_conv3d(batch: int, bias: bool) -> None: + # Frames are batched into N for conv2d: a wrong batch/frame reshape only shows when batch > 1. + torch.manual_seed(0) + conv = nn.Conv3d(16, 24, 3, padding=(0, 1, 1), bias=bias).to("mps") + x = torch.randn(batch, 16, 6, 10, 10, device="mps") + _assert_matches_stock(conv, x, atol=1e-4) + + +def test_toggle_off_runs_original_forward_and_on_runs_patched_path(monkeypatch: pytest.MonkeyPatch) -> None: + sentinel = torch.full((1,), 7.0) + monkeypatch.setattr(mps_conv3d_as_conv2d, "_installed", True) + monkeypatch.setattr(mps_conv3d_as_conv2d, "_enabled", False) + monkeypatch.setattr(mps_conv3d_as_conv2d, "_supported", lambda conv, x: True) + monkeypatch.setattr(mps_conv3d_as_conv2d, "_conv3d_as_conv2d", lambda conv, x: sentinel) + conv = nn.Conv3d(2, 2, 3, padding=(0, 1, 1)) + x = torch.randn(1, 2, 4, 5, 5) + + mps_conv3d_as_conv2d.set_enabled(False) + assert torch.equal(mps_conv3d_as_conv2d._forward(conv, x), mps_conv3d_as_conv2d._original_forward(conv, x)) + + mps_conv3d_as_conv2d.set_enabled(True) + assert mps_conv3d_as_conv2d._forward(conv, x) is sentinel + + +@pytest.mark.parametrize("platform", ["win32", "linux"]) +def test_install_leaves_conv3d_forward_untouched_off_darwin(platform: str, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(sys, "platform", platform) + monkeypatch.setattr(mps_conv3d_as_conv2d, "_installed", False) + monkeypatch.setattr(mps_conv3d_as_conv2d, "_enabled", False) + before = nn.Conv3d.forward + mps_conv3d_as_conv2d.install() + assert nn.Conv3d.forward is before + assert mps_conv3d_as_conv2d._installed is False diff --git a/backend/tests/test_mps_transfer_sync.py b/backend/tests/test_mps_transfer_sync.py new file mode 100644 index 000000000..3c78441b9 --- /dev/null +++ b/backend/tests/test_mps_transfer_sync.py @@ -0,0 +1,48 @@ +"""MPS weight transfers must wait for queued compute first (see ``mps_transfer_sync``).""" + +from __future__ import annotations + +from contextlib import contextmanager + +import pytest +from ltx_core.loader import streaming_transport + +from services.patches import mps_transfer_sync as patch + + +def _record_calls(monkeypatch: pytest.MonkeyPatch) -> list[str]: + calls: list[str] = [] + + @contextmanager + def fake_transfer(_self, after): + calls.append(f"enter after={after}") + try: + yield "handle" + finally: + calls.append("exit") + + monkeypatch.setattr(patch, "_orig_transfer", fake_transfer) + monkeypatch.setattr(patch.torch.mps, "synchronize", lambda: calls.append("sync")) + return calls + + +def test_patch_replaces_mps_transport_transfer_only() -> None: + assert streaming_transport.MpsTransport.transfer is patch._transfer_after_compute # pyright: ignore[reportPrivateUsage] + assert streaming_transport.CudaTransport.transfer is not patch._transfer_after_compute # pyright: ignore[reportPrivateUsage] + assert streaming_transport.CpuTransport.transfer is not patch._transfer_after_compute # pyright: ignore[reportPrivateUsage] + + +def test_syncs_before_the_upstream_transfer_starts(monkeypatch: pytest.MonkeyPatch) -> None: + calls = _record_calls(monkeypatch) + with patch._transfer_after_compute(object(), "prev") as handle: # pyright: ignore[reportPrivateUsage] + assert handle == "handle" + calls.append("body") + assert calls == ["sync", "enter after=prev", "body", "exit"] + + +def test_body_errors_propagate_and_upstream_exit_runs(monkeypatch: pytest.MonkeyPatch) -> None: + calls = _record_calls(monkeypatch) + with pytest.raises(ValueError, match="boom"): + with patch._transfer_after_compute(object(), None): # pyright: ignore[reportPrivateUsage] + raise ValueError("boom") + assert calls == ["sync", "enter after=None", "exit"] diff --git a/backend/tests/test_nag_cross_attention.py b/backend/tests/test_nag_cross_attention.py new file mode 100644 index 000000000..4287e0e51 --- /dev/null +++ b/backend/tests/test_nag_cross_attention.py @@ -0,0 +1,709 @@ +"""NAG text cross-attention patch: each test names the bug it catches.""" + +from __future__ import annotations + +from dataclasses import dataclass + +import pytest +import torch +from ltx_core.model.transformer.attention import AttentionFunction, AttentionOps, MaskedAttentionFunction +from ltx_core.model.transformer.transformer import BasicAVTransformerBlock, TransformerConfig +from ltx_core.model.transformer.transformer_args import AdaLNTimestepEmbedding +from ltx_core.text_encoders.gemma.embeddings_processor import EmbeddingsProcessorOutput +from ltx_pipelines.ic_lora import ICLoraPipeline +from ltx_pipelines.utils.types import LoadedImageConditioning + +from api_types import ExtendParams, RetakeParams, TextToVideoParams +from runtime_config.nag_limits import NEGATIVE_PROMPT_MAX_LENGTH +from services.fast_video_pipeline.distilled_skip_stage_2 import DistilledPipelineWithSkipStage2 +from services.fast_video_pipeline.nag_config import ( + NagConfig, + NagOffReason, + decide_nag, + nag_config_for_request, +) +from services.fast_video_pipeline.nag_distilled import NagDistilledMixin +from services.features.video.extend import ExtendExecutor +from services.features.video.retake import RetakeExecutor +from services.ic_lora_pipeline.tiled_ic_lora_pipeline import TiledICLoraPipeline +from services.patches.nag_cross_attention import ( + NagState, + active_state, + nag_scope, + normalized_attention_guidance, +) +from state.app_state_types import RetakePipelineState, TextEncodingResult + +_VIDEO_DIM = 32 +_AUDIO_DIM = 16 +_POSITIVE_TOKENS = 5 +_VIDEO_TOKENS = 6 + + +# AUTOMATIC picks the MPS kernel on Apple hosts, which rejects CPU tensors. +_CPU_ATTENTION = AttentionOps( + attention_function=AttentionFunction.PYTORCH.to_callable(), + masked_attention_function=MaskedAttentionFunction.PYTORCH.to_callable(), +) + + +def _block(*, cross_attention_adaln: bool) -> BasicAVTransformerBlock: + torch.manual_seed(0) + block = BasicAVTransformerBlock( + video=TransformerConfig( + dim=_VIDEO_DIM, heads=2, d_head=16, context_dim=_VIDEO_DIM, cross_attention_adaln=cross_attention_adaln + ), + audio=TransformerConfig( + dim=_AUDIO_DIM, heads=2, d_head=8, context_dim=_AUDIO_DIM, cross_attention_adaln=cross_attention_adaln + ), + attention_ops=_CPU_ATTENTION, + ) + with torch.no_grad(): + for parameter in block.parameters(): + parameter.copy_(torch.randn_like(parameter) * 0.2) + return block.eval() + + +def _state() -> NagState: + return NagState(config=NagConfig(negative_prompt="blurry"), positive_length=_POSITIVE_TOKENS) + + +def _text_cross_attention( + block: BasicAVTransformerBlock, + attn: torch.nn.Module, + x: torch.Tensor, + context: torch.Tensor, + *, + cross_attention_adaln: bool, +) -> torch.Tensor: + dim = x.shape[-1] + table = block.scale_shift_table if dim == _VIDEO_DIM else block.audio_scale_shift_table + prompt_table = getattr(block, "prompt_scale_shift_table", None) if cross_attention_adaln else None + modulation = torch.randn(1, 1, table.shape[0] * dim, generator=torch.Generator().manual_seed(1)) + prompt_timestep = torch.randn(1, 1, 2 * dim, generator=torch.Generator().manual_seed(2)) + with torch.no_grad(): + return block._apply_text_cross_attention( # pyright: ignore[reportPrivateUsage] + x, + context, + attn, # pyright: ignore[reportArgumentType] + table, + prompt_table, + AdaLNTimestepEmbedding(modulation=modulation, embedding=modulation), + prompt_timestep if cross_attention_adaln else None, + None, + cross_attention_adaln=cross_attention_adaln, + ) + + +def test_nag_off_leaves_video_text_cross_attention_unchanged() -> None: + block = _block(cross_attention_adaln=False) + x = torch.randn(1, _VIDEO_TOKENS, _VIDEO_DIM) + context = torch.randn(1, _POSITIVE_TOKENS, _VIDEO_DIM) + + out = _text_cross_attention(block, block.attn2, x, context, cross_attention_adaln=False) + + with torch.no_grad(): + assert torch.equal(out, block.attn2(x, context=context, mask=None)) + + +def test_negative_context_gets_the_same_adaln_modulation_as_the_positive_context() -> None: + # With negative == positive, Z_neg == Z_pos and NAG must return the unguided output. + # An unmodulated negative half would differ from the modulated positive half and break this. + block = _block(cross_attention_adaln=True) + x = torch.randn(1, _VIDEO_TOKENS, _VIDEO_DIM) + positive = torch.randn(1, _POSITIVE_TOKENS, _VIDEO_DIM) + unguided = _text_cross_attention(block, block.attn2, x, positive, cross_attention_adaln=True) + + with nag_scope(_state()): + same = _text_cross_attention( + block, block.attn2, x, torch.cat([positive, positive], dim=1), cross_attention_adaln=True + ) + other = _text_cross_attention( + block, + block.attn2, + x, + torch.cat([positive, torch.randn(1, _POSITIVE_TOKENS, _VIDEO_DIM)], dim=1), + cross_attention_adaln=True, + ) + + assert torch.allclose(same, unguided, atol=1e-5) + assert not torch.allclose(other, unguided, atol=1e-3) + + +def test_audio_text_cross_attention_and_self_attention_are_not_guided() -> None: + block = _block(cross_attention_adaln=False) + video_x = torch.randn(1, _VIDEO_TOKENS, _VIDEO_DIM) + video_context = torch.cat([torch.randn(1, _POSITIVE_TOKENS, _VIDEO_DIM)] * 2, dim=1) + audio_x = torch.randn(1, 4, _AUDIO_DIM) + audio_context = torch.randn(1, _POSITIVE_TOKENS + 2, _AUDIO_DIM) + + with nag_scope(_state()): + audio_out = _text_cross_attention(block, block.audio_attn2, audio_x, audio_context, cross_attention_adaln=False) + self_out = _text_cross_attention(block, block.attn1, video_x, video_context, cross_attention_adaln=False) + + with torch.no_grad(): + assert torch.equal(audio_out, block.audio_attn2(audio_x, context=audio_context, mask=None)) + assert torch.equal(self_out, block.attn1(video_x, context=video_context, mask=None)) + + +def test_nag_scope_is_closed_after_a_failed_generation() -> None: + with pytest.raises(RuntimeError, match="boom"): + with nag_scope(_state()): + raise RuntimeError("boom") + + assert active_state() is None + + +@pytest.mark.parametrize("negative_prompt", ["", " \n\t"]) +def test_blank_negative_prompt_does_not_turn_nag_on(negative_prompt: str) -> None: + assert nag_config_for_request(negative_prompt, {}) is None + + +def test_zero_nag_scale_or_env_disabled_turns_nag_off() -> None: + assert nag_config_for_request("blurry", {}, scale=0.0) is None + assert nag_config_for_request("blurry", {}, default_scale=0.0) is None + assert nag_config_for_request("blurry", {"LTX_NAG_ENABLED": "0"}) is None + + +def test_queued_generation_snapshots_nag_scale_so_later_settings_edits_do_not_change_rerenders( + client, test_state, create_fake_model_files +) -> None: + create_fake_model_files() + test_state.state.app_settings.nag_scale = 7.5 + created = client.post( + "/api/generations/text-to-video", + json={ + "params": { + "prompt": "a cat", + "negativePrompt": "subtitles, watermark", + "model": "ltx-2.5-fast", + "aspectRatio": "16:9", + "resolution": "540p", + "duration": 5, + "fps": 24, + } + }, + ) + assert created.status_code == 200, created.text + params = created.json()["spec"]["params"] + assert params["negativePrompt"] == "subtitles, watermark" + assert params["nagScale"] == 7.5 + assert params["nagAlpha"] == 0.25 + assert params["nagTau"] == 2.5 + + # Changing Settings afterwards does not alter the persisted spec. + test_state.state.app_settings.nag_scale = 15.0 + fetched = client.get(f"/api/generations/{created.json()['id']}") + assert fetched.status_code == 200 + assert fetched.json()["spec"]["params"]["nagScale"] == 7.5 + + +def test_normalized_attention_guidance_clips_when_l1_ratio_exceeds_tau() -> None: + z_pos = torch.ones(1, 3, 8) + z_neg = -torch.ones(1, 3, 8) + # Unclipped guidance is 11 * 1 - 10 * (-1) = 21 per element (L1 ratio = 21 > tau = 2.0). + # With alpha=1.0, the output is the clipped guidance vector Z^, whose L1 norm must equal tau * ||z_pos||_1. + out = normalized_attention_guidance(z_pos, z_neg, scale=11.0, alpha=1.0, tau=2.0) + pos_l1 = torch.linalg.vector_norm(z_pos, ord=1, dim=-1) + out_l1 = torch.linalg.vector_norm(out, ord=1, dim=-1) + assert torch.allclose(out_l1, pos_l1 * 2.0, atol=1e-4) + + +@dataclass(frozen=True) +class _FakeRunCtx: + video_context: torch.Tensor + audio_context: torch.Tensor + + +class _FakeEncoder: + def __init__(self) -> None: + self.calls: list[tuple[list[str], dict[str, object]]] = [] + + def __call__(self, prompts: list[str], **kwargs: object) -> list[EmbeddingsProcessorOutput]: + self.calls.append((list(prompts), dict(kwargs))) + return [ + EmbeddingsProcessorOutput( + video_encoding=torch.full((1, 4, 8), float(index + 1)), + audio_encoding=torch.zeros(1, 2, 4), + attention_mask=torch.ones(1, 4), + ) + for index, _ in enumerate(prompts) + ] + + +class _FakeDistilledBase: + def __init__(self) -> None: + self.prompt_encoder = _FakeEncoder() + self.active_during_next: list[NagState | None] = [] + + def _prepare_run(self, **kwargs: object) -> _FakeRunCtx: + (ctx_p,) = self.prompt_encoder([str(kwargs["prompt"])], enhance_first_prompt=True) + assert ctx_p.audio_encoding is not None + return _FakeRunCtx(video_context=ctx_p.video_encoding, audio_context=ctx_p.audio_encoding) + + def stream_chunks(self, **kwargs: object): + ctx = self._prepare_run(**kwargs) + + def _gen(): + for chunk_idx in range(3): + self.active_during_next.append(active_state()) + yield (chunk_idx, ctx.video_context.shape[1]) + + return _gen(), 9, "tiling" + + +class _FakeNagPipeline(NagDistilledMixin, _FakeDistilledBase): + pass + + +def test_prepare_run_appends_negative_embedding_and_sets_positive_length() -> None: + pipe = _FakeNagPipeline() + original_encoder = pipe.prompt_encoder + nag = NagConfig(negative_prompt="watermark", scale=9.0) + + with pipe._nag_request(nag): # pyright: ignore[reportPrivateUsage] + ctx = pipe._prepare_run(prompt="a fox") # pyright: ignore[reportPrivateUsage] + + assert pipe.prompt_encoder is original_encoder + assert original_encoder.calls == [(["a fox", "watermark"], {"enhance_first_prompt": True})] + assert ctx.video_context.shape == (1, 8, 8) + assert torch.all(ctx.video_context[:, :4] == 1.0) + assert torch.all(ctx.video_context[:, 4:] == 2.0) + assert pipe._nag_state is not None # pyright: ignore[reportPrivateUsage] + assert pipe._nag_state.positive_length == 4 # pyright: ignore[reportPrivateUsage] + + +def test_scoped_chunks_activates_nag_only_inside_next_and_not_between_chunks() -> None: + pipe = _FakeNagPipeline() + nag = NagConfig(negative_prompt="flicker", scale=11.0) + + chunks, num_frames, _ = pipe.stream_chunks(prompt="a fox", nag=nag) + assert num_frames == 9 + assert active_state() is None + + seen_between_chunks: list[NagState | None] = [] + yielded = [] + for item in chunks: + seen_between_chunks.append(active_state()) + yielded.append(item) + + assert active_state() is None + assert yielded == [(0, 8), (1, 8), (2, 8)] + assert seen_between_chunks == [None, None, None] + assert len(pipe.active_during_next) == 3 + assert all(state is not None and state.positive_length == 4 for state in pipe.active_during_next) + + +def test_skip_stage_2_activates_nag_denoise_scope_during_stage_1(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr( + "services.fast_video_pipeline.distilled_skip_stage_2.image_conditionings", + lambda **_kwargs: [], + ) + monkeypatch.setattr( + "services.fast_video_pipeline.distilled_skip_stage_2.create_initial_av_latents", + lambda *, pixel_shape, **_kwargs: ( + torch.zeros(1, 4, pixel_shape.frames, pixel_shape.height, pixel_shape.width), + torch.zeros(1, 8, pixel_shape.frames, 16), + ), + ) + + pipe = DistilledPipelineWithSkipStage2.__new__(DistilledPipelineWithSkipStage2) + pipe.device = torch.device("cpu") + pipe.dtype = torch.bfloat16 + pipe.use_ancestral_sampler = False + pipe.duration_predictor = None + + class _Conditioner: + def load_conditionings(self, images, color_space=None): # noqa: ARG002 + return [ + LoadedImageConditioning(still=img.path, strength=img.strength, binding=img.binding) + for img in images + ] + + def __call__(self, build): + return build(object()) + + class _LatentState: + def __init__(self, latent: torch.Tensor) -> None: + self.latent = latent + + class _Decoder: + checkpoint_path = "unused" + diffvae_optimization = None + + def __call__(self, _latent, _tiling, _generator, dtype=None): # noqa: ARG002 + # Decode runs after stage 1 exits, so NAG scope must already be closed here. + assert active_state() is None + return torch.zeros(1, 3, 9, 288, 512) + + active_in_stage: list[NagState | None] = [] + + def stage(**kwargs): + active_in_stage.append(active_state()) + video = kwargs["modalities"].video + return _LatentState(video.latent), _LatentState(video.latent.clone()) + + stage.video_scale_factors = object() # type: ignore[attr-defined] + pipe.image_conditioner = _Conditioner() # type: ignore[assignment] + pipe.prompt_encoder = _FakeEncoder() + pipe.stage = stage # type: ignore[assignment] + pipe.video_decoder = _Decoder() # type: ignore[assignment] + pipe.audio_decoder = lambda _latent: None # type: ignore[assignment] + + nag = NagConfig(negative_prompt="subtitles", scale=11.0) + pipe( + prompt="a clip", + seed=1, + height=576, + width=1024, + frame_rate=24, + images=[], + num_frames=9, + tiling_config=None, + skip_stage_2=True, + nag=nag, + ) + + assert active_state() is None + assert len(active_in_stage) == 1 + assert active_in_stage[0] is not None + assert active_in_stage[0].config == nag + assert active_in_stage[0].positive_length == 4 + + +def test_handler_drops_nag_when_text_encoding_is_not_local_or_compile_is_enabled( + client, test_state, fake_services, create_fake_model_files +) -> None: + create_fake_model_files() + # 1. API text encoding active (API key set, use_local_text_encoder=False): NAG is skipped. + test_state.state.app_settings.ltx_api_key = "test-api-key" + test_state.state.app_settings.use_local_text_encoder = False + fake_services.text_encoder.encode_responses.append( + TextEncodingResult(video_context=torch.zeros(1, 4, 8), audio_context=None) + ) + + resp_api = client.post( + "/api/generate", + json={ + "prompt": "a fox", + "negativePrompt": "blurry", + "model": "fast", + "resolution": "540p", + "duration": 5, + "fps": 24, + "aspectRatio": "16:9", + }, + ) + assert resp_api.status_code == 200, resp_api.text + assert fake_services.fast_video_pipeline.generate_calls[-1]["nag"] is None + + # 2. Local text encoding active, but use_torch_compile=True: NAG is skipped. + test_state.state.app_settings.use_local_text_encoder = True + test_state.state.app_settings.use_torch_compile = True + + resp_compile = client.post( + "/api/generate", + json={ + "prompt": "a fox", + "negativePrompt": "blurry", + "model": "fast", + "resolution": "540p", + "duration": 5, + "fps": 24, + "aspectRatio": "16:9", + }, + ) + assert resp_compile.status_code == 200, resp_compile.text + assert fake_services.fast_video_pipeline.generate_calls[-1]["nag"] is None + + queued_compile = client.post( + "/api/generations/text-to-video", + json={ + "params": { + "prompt": "a fox", + "negativePrompt": "blurry", + "model": "ltx-2.5-fast", + "aspectRatio": "16:9", + "resolution": "540p", + "duration": 5, + "fps": 24, + } + }, + ) + assert queued_compile.status_code == 200, queued_compile.text + assert "nagScale" not in queued_compile.json()["spec"]["params"] + + +def test_edit_executor_resolve_nag_returns_none_when_default_scale_is_zero_and_spec_omits_nag_scale( + test_state, create_fake_model_files +) -> None: + create_fake_model_files() + test_state.state.app_settings.nag_scale = 0.0 + retake_executor = RetakeExecutor( + test_state.pipelines, + test_state.assets, # type: ignore[arg-type] + test_state.text, + lambda: test_state.video_generation.models_dir, + test_state.config.default_negative_prompt, + test_state.generation, + test_state.prompt_enhancement, + default_nag_scale=lambda: test_state.settings.get_settings_snapshot().nag_scale, + ) + extend_executor = ExtendExecutor( + test_state.pipelines, + test_state.assets, # type: ignore[arg-type] + test_state.text, + lambda: test_state.video_generation.models_dir, + test_state.config.default_negative_prompt, + test_state.generation, + test_state.prompt_enhancement, + default_nag_scale=lambda: test_state.settings.get_settings_snapshot().nag_scale, + ) + + pipeline_state = RetakePipelineState( + pipeline=object(), # type: ignore[arg-type] + distilled=True, + quantized=False, + ltx_model_id="ltx-2.5-22b-distilled", + loading_mode="full_models_loading", + gemma_root="/fake/gemma", + ) + retake_params = RetakeParams( + model="ltx-2.5-fast", + prompt="replace with a cat", + negativePrompt="blurry, flicker", + startTime=0.0, + duration=2.0, + ) + extend_params = ExtendParams( + model="ltx-2.5-fast", + prompt="continue the walk", + negativePrompt="blurry, flicker", + duration=2.0, + ) + + assert retake_executor.resolve_nag(retake_params, pipeline_state) is None + assert extend_executor.resolve_nag(extend_params, pipeline_state) is None + + test_state.state.app_settings.nag_scale = 8.5 + resolved_retake = retake_executor.resolve_nag(retake_params, pipeline_state) + resolved_extend = extend_executor.resolve_nag(extend_params, pipeline_state) + assert resolved_retake is not None and resolved_retake.scale == 8.5 + assert resolved_extend is not None and resolved_extend.scale == 8.5 + + +def test_dump_fast_params_allows_nag_on_edit_and_a2v_when_torch_compile_is_enabled( + test_state, create_fake_model_files +) -> None: + create_fake_model_files() + test_state.state.app_settings.nag_scale = 9.0 + test_state.state.app_settings.use_torch_compile = True + + fast_dumped = test_state.queued_generations._dump_fast_params( # pyright: ignore[reportPrivateUsage] + TextToVideoParams( + prompt="a fox", + negativePrompt="blurry", + model="ltx-2.5-fast", + aspectRatio="16:9", + resolution="540p", + duration=5, + fps=24, + ) + ) + assert "nagScale" not in fast_dumped + + edit_dumped = test_state.queued_generations._dump_fast_params( # pyright: ignore[reportPrivateUsage] + RetakeParams( + model="ltx-2.5-fast", + prompt="replace with a cat", + negativePrompt="blurry", + startTime=0.0, + duration=2.0, + ), + uses_torch_compile=False, + ) + assert edit_dumped["nagScale"] == 9.0 + + +def test_tiled_ic_lora_pipeline_activates_nag_scope_inside_stream_chunks( + monkeypatch: pytest.MonkeyPatch, +) -> None: + pipe = TiledICLoraPipeline.__new__(TiledICLoraPipeline) + encoder = _FakeEncoder() + pipe.prompt_encoder = encoder # type: ignore[assignment] + active_during_next: list[NagState | None] = [] + + def fake_parent_stream_chunks(self: object, **kwargs: object): + ctx = self._prepare_run(**kwargs) # type: ignore[attr-defined] + + def _gen(): + for chunk_idx in range(3): + active_during_next.append(active_state()) + yield (chunk_idx, ctx.video_context.shape[1]) + + return _gen(), 9, "tiling" + + monkeypatch.setattr(ICLoraPipeline, "_prepare_run", _FakeDistilledBase._prepare_run) + monkeypatch.setattr(ICLoraPipeline, "stream_chunks", fake_parent_stream_chunks) + nag = NagConfig(negative_prompt="watermark", scale=11.0) + + chunks, num_frames, _ = pipe.stream_chunks(prompt="a fox", nag=nag) + assert num_frames == 9 + assert active_state() is None + yielded = list(chunks) + assert active_state() is None + assert yielded == [(0, 8), (1, 8), (2, 8)] + assert len(active_during_next) == 3 + assert all( + state is not None and state.config == nag and state.positive_length == 4 + for state in active_during_next + ) + + +def test_decide_nag_returns_config_or_off_reason_across_inputs() -> None: + assert decide_nag("", {}).reason == NagOffReason.NO_NEGATIVE + assert decide_nag("blurry", {"LTX_NAG_ENABLED": "0"}).reason == NagOffReason.DISABLED_BY_ENV + assert decide_nag("blurry", {}, scale=0.0).reason == NagOffReason.STRENGTH_ZERO + assert decide_nag("blurry", {}, default_scale=0.0).reason == NagOffReason.STRENGTH_ZERO + assert ( + decide_nag("blurry", {}, local_encoding=False).reason + == NagOffReason.API_ENCODING + ) + assert ( + decide_nag("blurry", {}, compiled=True).reason + == NagOffReason.TORCH_COMPILE + ) + active = decide_nag("blurry", {}, scale=7.5) + assert active.reason is None + assert active.config == NagConfig(negative_prompt="blurry", scale=7.5) + assert active.enhancer_negative == "blurry" + + +def test_queued_generation_preserves_explicit_zero_nag_scale_so_execution_does_not_fall_back_to_default( + client, test_state, create_fake_model_files +) -> None: + create_fake_model_files() + test_state.state.app_settings.nag_scale = 11.0 + created = client.post( + "/api/generations/text-to-video", + json={ + "params": { + "prompt": "a cat", + "negativePrompt": "blurry", + "nagScale": 0, + "model": "ltx-2.5-fast", + "aspectRatio": "16:9", + "resolution": "540p", + "duration": 5, + "fps": 24, + } + }, + ) + assert created.status_code == 200, created.text + params = created.json()["spec"]["params"] + assert params["nagScale"] == 0.0 + assert "nagAlpha" not in params + assert "nagTau" not in params + + +def test_negative_prompt_exceeding_max_length_is_rejected_with_422(client) -> None: + too_long = "x" * (NEGATIVE_PROMPT_MAX_LENGTH + 1) + resp = client.post( + "/api/generations/text-to-video", + json={ + "params": { + "prompt": "a cat", + "negativePrompt": too_long, + "model": "ltx-2.5-fast", + "aspectRatio": "16:9", + "resolution": "540p", + "duration": 5, + "fps": 24, + } + }, + ) + assert resp.status_code == 422 + + +def test_generate_forwards_negative_prompt_to_enhancer_and_nag( + client, test_state, fake_services, create_fake_model_files +) -> None: + create_fake_model_files(include_prompt_enhancer=True) + test_state.state.app_settings.use_local_text_encoder = True + fake_services.prompt_enhancer_pipeline.enhanced_prompt = "a vivid fox running" + + resp = client.post( + "/api/generate", + json={ + "prompt": "a fox", + "negativePrompt": "blurry", + "model": "fast", + "resolution": "540p", + "duration": 5, + "fps": 24, + "aspectRatio": "16:9", + }, + ) + assert resp.status_code == 200, resp.text + assert fake_services.prompt_enhancer_pipeline.enhance_t2v_calls[-1]["negative_prompt"] == "blurry" + nag = fake_services.fast_video_pipeline.generate_calls[-1]["nag"] + assert nag is not None + assert nag.negative_prompt == "blurry" + + +def test_generation_does_not_steer_prompt_enhancer_with_negative_prompt_when_nag_is_disabled( + client, test_state, fake_services, create_fake_model_files +) -> None: + create_fake_model_files(include_prompt_enhancer=True) + test_state.state.app_settings.use_local_text_encoder = True + test_state.state.app_settings.nag_scale = 0.0 + fake_services.prompt_enhancer_pipeline.enhanced_prompt = "a vivid fox running" + + resp = client.post( + "/api/generate", + json={ + "prompt": "a fox", + "negativePrompt": "blurry, watermark", + "model": "fast", + "resolution": "540p", + "duration": 5, + "fps": 24, + "aspectRatio": "16:9", + }, + ) + assert resp.status_code == 200, resp.text + assert fake_services.prompt_enhancer_pipeline.enhance_t2v_calls[-1]["negative_prompt"] == "" + assert fake_services.fast_video_pipeline.generate_calls[-1]["nag"] is None + + +def test_edit_executor_does_not_pass_negative_prompt_to_enhancer_when_local_encoding_is_unavailable( + test_state, create_fake_model_files +) -> None: + create_fake_model_files() + test_state.state.app_settings.ltx_api_key = "test-api-key" + test_state.state.app_settings.use_local_text_encoder = False + retake_executor = RetakeExecutor( + test_state.pipelines, + test_state.assets, # type: ignore[arg-type] + test_state.text, + lambda: test_state.video_generation.models_dir, + test_state.config.default_negative_prompt, + test_state.generation, + test_state.prompt_enhancement, + default_nag_scale=lambda: test_state.settings.get_settings_snapshot().nag_scale, + ) + params = RetakeParams( + model="ltx-2.5-fast", + prompt="replace with a cat", + negativePrompt="blurry, flicker", + startTime=0.0, + duration=2.0, + ) + decision = retake_executor.decide_nag( + params, + local_encoding=test_state.text.should_use_local_encoding("ltx-2.5-22b-distilled"), + ) + assert decision.reason == NagOffReason.API_ENCODING + assert decision.enhancer_negative == "" + + diff --git a/backend/tests/test_nag_strength_e2e.py b/backend/tests/test_nag_strength_e2e.py new file mode 100644 index 000000000..a1c8e9900 --- /dev/null +++ b/backend/tests/test_nag_strength_e2e.py @@ -0,0 +1,172 @@ +"""Per-run NAG strength, end to end: create body -> stored row -> the NAG config the model gets. + +The frontend setting "Per-run strength controls" sends `nagScale`, `nagAlpha` and `nagTau` in the create +body. These tests run the real queue and the real text-to-video executor against the fake +pipeline, and read the `nag` argument that the pipeline `generate` call received. Each test +names the bug it catches. +""" + +from __future__ import annotations + +import time +from pathlib import Path + +import pytest +from pydantic import JsonValue +from starlette.testclient import TestClient + +from app_factory import create_app +from services.fast_video_pipeline.nag_config import NagConfig +from services.sqlite_store import SqliteStore +from state import build_initial_state, set_state_service_for_tests +from state.app_state_types import HfAuthenticated +from tests.conftest import TEST_ADMIN_TOKEN +from tests.test_http import _a2v_params, _bundle, _wav # pyright: ignore[reportPrivateUsage] + +_BASE_PARAMS: dict[str, JsonValue] = { + "prompt": "a fox runs", + "negativePrompt": "clouds", + "model": "ltx-2.5-fast", + "aspectRatio": "16:9", + "resolution": "540p", + "duration": 5, + "fps": 24, +} + + +def _run_text_to_video( + test_state, + fake_services, + default_app_settings, + create_fake_model_files, + *, + settings_scale: float, + **strength: float, +) -> tuple[dict[str, JsonValue], NagConfig | None]: + """Create one text-to-video run, wait for the pipeline call, return its stored params and the model's NAG.""" + create_fake_model_files() + # The default test_state swaps in fake executors. Build one without them, so the real + # text-to-video executor runs and calls the (fake) pipeline. + handler = build_initial_state( + test_state.config, + default_app_settings, + service_bundle=_bundle(fake_services, SqliteStore(test_state.config.app_data_dir)), + ) + handler.state.hf_auth_state = HfAuthenticated(access_token="fake-hf-token", expires_at=1e18) + handler.state.app_settings.use_local_text_encoder = True + handler.state.app_settings.nag_scale = settings_scale + set_state_service_for_tests(handler) + + with TestClient(create_app(handler=handler, admin_token=TEST_ADMIN_TOKEN)) as client: + created = client.post( + "/api/generations/text-to-video", json={"params": {**_BASE_PARAMS, **strength}} + ) + assert created.status_code == 200, created.text + generation_id = created.json()["id"] + # The fake pipeline writes no real video, so the run can fail after the call. The call + # is what matters here: it holds the NAG config the model received. + deadline = time.monotonic() + 10.0 + while not fake_services.fast_video_pipeline.generate_calls: + assert time.monotonic() < deadline, "the pipeline was never called" + time.sleep(0.01) + stored = client.get(f"/api/generations/{generation_id}").json()["spec"]["params"] + + (call,) = fake_services.fast_video_pipeline.generate_calls + return stored, call["nag"] + + +@pytest.mark.parametrize( + ("strength", "expected"), + [ + # Default preset sends nothing: Settings scale and the backend alpha and tau. + ({}, NagConfig("clouds", scale=7.5, alpha=0.25, tau=2.5)), + # Strong sends only alpha. Bug: it also replaced the Settings scale. + ({"nagAlpha": 0.5}, NagConfig("clouds", scale=7.5, alpha=0.5, tau=2.5)), + # Max. + ( + {"nagScale": 20.0, "nagAlpha": 0.5, "nagTau": 5.0}, + NagConfig("clouds", scale=20.0, alpha=0.5, tau=5.0), + ), + # Custom, with alpha at its lowest. + ( + {"nagScale": 3.5, "nagAlpha": 0.0, "nagTau": 1.0}, + NagConfig("clouds", scale=3.5, alpha=0.0, tau=1.0), + ), + ], +) +def test_text_to_video_run_gets_the_strength_the_form_sent( + test_state, fake_services, default_app_settings, create_fake_model_files, strength, expected +) -> None: + stored, nag = _run_text_to_video( + test_state, + fake_services, + default_app_settings, + create_fake_model_files, + settings_scale=7.5, + **strength, + ) + + assert nag == expected + # The row holds what the model got, which is what the result line shows. + assert (stored["nagScale"], stored["nagAlpha"], stored["nagTau"]) == ( + expected.scale, + expected.alpha, + expected.tau, + ) + + +def test_explicit_scale_turns_nag_on_even_when_settings_strength_is_zero( + test_state, fake_services, default_app_settings, create_fake_model_files +) -> None: + """Why the form must not send a strength while Settings has NAG off. + + The request scale wins over Settings, so a stale Max would force NAG on. + """ + _, nag = _run_text_to_video( + test_state, + fake_services, + default_app_settings, + create_fake_model_files, + settings_scale=0.0, + nagScale=20.0, + nagAlpha=0.5, + nagTau=5.0, + ) + + assert nag == NagConfig("clouds", scale=20.0, alpha=0.5, tau=5.0) + + +def test_audio_to_video_run_gets_the_strength_the_form_sent( + test_state, fake_services, default_app_settings, create_fake_model_files, tmp_path: Path +) -> None: + """Audio to video decides NAG in its own handler path. Bug: it ignored the request knobs.""" + create_fake_model_files() + handler = build_initial_state( + test_state.config, + default_app_settings, + service_bundle=_bundle(fake_services, SqliteStore(test_state.config.app_data_dir)), + ) + handler.state.hf_auth_state = HfAuthenticated(access_token="fake-hf-token", expires_at=1e18) + handler.state.app_settings.use_local_text_encoder = True + handler.state.app_settings.nag_scale = 7.5 + set_state_service_for_tests(handler) + + with TestClient(create_app(handler=handler, admin_token=TEST_ADMIN_TOKEN)) as client: + audio = client.post("/api/assets", json={"path": str(_wav(tmp_path / "line.wav"))}).json() + created = client.post( + "/api/generations/audio-to-video", + json={ + "params": _a2v_params( + negativePrompt="clouds", nagScale=20.0, nagAlpha=0.5, nagTau=5.0 + ), + "inputs": {"audio": {"assetId": audio["id"]}}, + }, + ) + assert created.status_code == 200, created.text + deadline = time.monotonic() + 10.0 + while not fake_services.a2v_pipeline.generate_calls: + assert time.monotonic() < deadline, "the pipeline was never called" + time.sleep(0.01) + + (call,) = fake_services.a2v_pipeline.generate_calls + assert call["nag"] == NagConfig("clouds", scale=20.0, alpha=0.5, tau=5.0) diff --git a/backend/tests/test_nag_strength_setting.py b/backend/tests/test_nag_strength_setting.py new file mode 100644 index 000000000..6e555cf86 --- /dev/null +++ b/backend/tests/test_nag_strength_setting.py @@ -0,0 +1,51 @@ +"""The `showNagStrengthControls` setting: Desktop saves it, the phone reads it from the status.""" + +from __future__ import annotations + +import json + +from starlette.testclient import TestClient + +from remote.app import create_remote_app + +AUTH = {"Authorization": "Bearer pair-token"} + + +def test_setting_is_off_by_default_on_desktop_and_phone(client, test_state) -> None: + """Bug: the row showing for everyone after an upgrade.""" + assert client.get("/api/settings").json()["showNagStrengthControls"] is False + assert client.get("/api/prompt-enhancer").json()["showNagStrengthControls"] is False + + with TestClient(create_remote_app(handler=test_state, remote_token="pair-token")) as phone: + status = phone.get("/api/prompt-enhancer", headers=AUTH) + assert status.json()["showNagStrengthControls"] is False + + +def test_turning_the_setting_on_is_saved_and_reaches_the_phone(client, test_state) -> None: + saved = client.post("/api/settings", json={"showNagStrengthControls": True}) + assert saved.status_code == 200, saved.text + + assert client.get("/api/settings").json()["showNagStrengthControls"] is True + assert client.get("/api/prompt-enhancer").json()["showNagStrengthControls"] is True + # Saved to disk, so it survives a restart. + on_disk = json.loads(test_state.config.settings_file.read_text(encoding="utf-8")) + assert on_disk["show_nag_strength_controls"] is True + + with TestClient(create_remote_app(handler=test_state, remote_token="pair-token")) as phone: + status = phone.get("/api/prompt-enhancer", headers=AUTH) + assert status.json()["showNagStrengthControls"] is True + + client.post("/api/settings", json={"showNagStrengthControls": False}) + with TestClient(create_remote_app(handler=test_state, remote_token="pair-token")) as phone: + status = phone.get("/api/prompt-enhancer", headers=AUTH) + assert status.json()["showNagStrengthControls"] is False + + +def test_phone_cannot_change_the_setting(test_state) -> None: + """The phone only reads the status. A settings write from it must not exist.""" + with TestClient(create_remote_app(handler=test_state, remote_token="pair-token")) as phone: + response = phone.post( + "/api/settings", headers=AUTH, json={"showNagStrengthControls": True} + ) + assert response.status_code in (404, 405) + assert test_state.state.app_settings.show_nag_strength_controls is False diff --git a/backend/tests/test_offload_mode.py b/backend/tests/test_offload_mode.py index 22e81110b..d487ec870 100644 --- a/backend/tests/test_offload_mode.py +++ b/backend/tests/test_offload_mode.py @@ -56,13 +56,54 @@ def test_linux_cuda_streaming_with_unknown_ram_is_disk() -> None: def test_windows_cuda_streaming_routes_disk_on_nvme() -> None: - for ram_bytes in (64 * _GIB, 32 * _GIB, None): + for ram_bytes in (32 * _GIB, None): assert ( offload_mode_for_prefetch_count( 2, torch.device("cuda"), drive_type="nvme", system="Windows", ram_bytes=ram_bytes ) is OffloadMode.DISK ) + for ram_bytes in (40 * _GIB, 64 * _GIB): + assert ( + offload_mode_for_prefetch_count( + 2, torch.device("cuda"), drive_type="nvme", system="Windows", ram_bytes=ram_bytes + ) + is OffloadMode.CPU + ) + # A nominal 64 GB Windows box reports ~63.45 GiB usable; ceiling GiB keeps it on CPU at the 64 GB floor. + assert ( + offload_mode_for_prefetch_count( + 2, + torch.device("cuda"), + drive_type="nvme", + system="Windows", + ram_bytes=int(63.45 * _GIB), + cpu_ram_floor_gb=64, + ) + is OffloadMode.CPU + ) + assert ( + offload_mode_for_prefetch_count( + 2, + torch.device("cuda"), + drive_type="nvme", + system="Windows", + ram_bytes=48 * _GIB, + cpu_ram_floor_gb=64, + ) + is OffloadMode.DISK + ) + assert ( + offload_mode_for_prefetch_count( + 2, + torch.device("cuda"), + drive_type="nvme", + system="Windows", + ram_bytes=64 * _GIB, + cpu_ram_floor_gb=None, + ) + is OffloadMode.DISK + ) def test_windows_cuda_streaming_stays_cpu_without_nvme() -> None: diff --git a/backend/tests/test_pass_shape.py b/backend/tests/test_pass_shape.py new file mode 100644 index 000000000..42d804216 --- /dev/null +++ b/backend/tests/test_pass_shape.py @@ -0,0 +1,381 @@ +"""One pass or parts: the per-job shape, the "Never split into parts" switch, and the Brave alternative.""" + +from __future__ import annotations + +import threading +import wave +from collections.abc import Iterator +from contextlib import contextmanager +from pathlib import Path + +import pytest +from pydantic import JsonValue +from starlette.testclient import TestClient + +from app_factory import create_app +from frame_math import compute_num_frames +from remote.app import create_remote_app +from runtime_config.fast_chunking import job_window_count +from runtime_config.video_job_budget import ( + MPS_SEQUENCE_OVER_MESSAGE, + ONE_PASS_UNAVAILABLE, + ONE_PASS_UNAVAILABLE_MESSAGE, + VIDEO_JOB_TOO_LARGE, +) +from services.features.video import TextToVideoExecutor +from services.generation_queue.types import OutputAllocation +from services.sqlite_store import SqliteStore +from tests.conftest import TEST_ADMIN_TOKEN +from tests.fakes.generation import FakeJobSession +from tests.http_error_assertions import assert_http_error + +_GIB = 1024**3 +_RTX_5090_GIB = 31.84 + + +def _configure_windows(test_state, create_fake_model_files, *, vram_gib: float, mode: str) -> None: + create_fake_model_files() + test_state.config.system = "Windows" + test_state.config.vram_gb = int(vram_gib) + test_state.config.vram_bytes = int(vram_gib * _GIB) + test_state.config.total_ram_bytes = 64 * _GIB + test_state.config.local_generations_mode = "streaming_models_loading" + test_state.state.app_settings.use_local_text_encoder = True + test_state.state.app_settings.budget_mode = mode + + +def _configure_mac(test_state, fake_services, create_fake_model_files, *, pool_gib: float, mode: str) -> None: + create_fake_model_files() + test_state.config.system = "Darwin" + test_state.config.total_ram_bytes = 48 * _GIB + test_state.config.local_generations_mode = "streaming_models_loading" + fake_services.gpu_info.mps_pool_bytes = int(pool_gib * _GIB) + test_state.state.app_settings.budget_mode = mode + + +def _t2v( + resolution: str, duration: int | None, *, fps: int = 24, pass_shape: str | None = None +) -> dict[str, JsonValue]: + params: dict[str, JsonValue] = { + "prompt": "fox", + "model": "ltx-2.5-fast", + "aspectRatio": "16:9", + "resolution": resolution, + "duration": duration, + "fps": fps, + } + if pass_shape is not None: + params["passShape"] = pass_shape + return {"params": params} + + +@contextmanager +def _home(test_state) -> Iterator[TestClient]: + with TestClient(create_app(handler=test_state, admin_token=TEST_ADMIN_TOKEN)) as client: + yield client + + +def _create(test_state, body: dict[str, JsonValue]): + with _home(test_state) as client: + return client.post("/api/generations/text-to-video", json=body) + + +def _a2v_create( + test_state, tmp_path: Path, resolution: str, *, seconds: float, pass_shape: str +): + wav_path = tmp_path / "line.wav" + with wave.open(str(wav_path), "wb") as wav_file: + wav_file.setnchannels(1) + wav_file.setsampwidth(2) + wav_file.setframerate(8000) + wav_file.writeframes(b"\x00\x00" * int(seconds * 8000)) + with _home(test_state) as client: + audio = client.post("/api/assets", json={"path": str(wav_path)}).json() + return client.post( + "/api/generations/audio-to-video", + json={ + "params": { + "prompt": "the character speaks", + "resolution": resolution, + "model": "ltx-2.5-fast", + "fps": 24, + "passShape": pass_shape, + }, + "inputs": {"audio": {"assetId": audio["id"]}}, + }, + ) + + +def _stored_spec(test_state, generation_id: str) -> dict[str, object]: + record = SqliteStore(test_state.config.app_data_dir).get_generation(generation_id) + assert record is not None + return dict(record.spec) + + +def _run(test_state, fake_services, tmp_path: Path, generation_id: str) -> int | None: + """Execute the queued job and return the window the pipeline got (None is one pass).""" + record = SqliteStore(test_state.config.app_data_dir).get_generation(generation_id) + assert record is not None + executor = TextToVideoExecutor(test_state.video_generation) + plans = executor.plan_outputs(record) + outputs = ( + OutputAllocation(plan=plans[0], asset_id=f"{generation_id}-out", dest_path=str(tmp_path / f"{generation_id}.mp4")), + ) + with test_state.generation.wait_for_generation_slot(threading.Event()): + executor.execute(record, outputs, FakeJobSession()) + window = fake_services.fast_video_pipeline.generate_calls[-1]["chunk_pixel_frames"] + assert window is None or isinstance(window, int) + return window + + +def _fast_spec(test_state) -> dict: + with _home(test_state) as client: + response = client.get("/api/generate/models-specs") + assert response.status_code == 200, response.text + return next(item["spec"] for item in response.json()["local_models"] if item["pipeline"] == "fast") + + +def _cell(cells: list[dict], resolution: str, duration: int, fps: int = 24) -> dict | None: + return next( + ( + c + for c in cells + if (c["resolution"], c["duration"], c["fps"], c["audio"]) == (resolution, duration, fps, False) + ), + None, + ) + + +def _kept(spec: dict, resolution: str, fps: int = 24) -> list[int]: + cell = spec["supported_resolutions_durations"].get(resolution) + return [] if cell is None else cell["fps_to_durations"].get(str(fps), []) + + +def test_a_forced_one_pass_over_the_card_runs_as_an_over_bet_in_brave( + test_state, fake_services, create_fake_model_files, tmp_path: Path +) -> None: + # A 16 GB card runs 1080p 10 s in parts at 16 GB; one pass asks 22.7. + _configure_windows(test_state, create_fake_model_files, vram_gib=16, mode="brave") + response = _create(test_state, _t2v("1080p", 10, pass_shape="one_pass")) + assert response.status_code == 200, response.text + assert response.json()["risk"]["tier"] == "over" + assert _run(test_state, fake_services, tmp_path, response.json()["id"]) is None + + +def test_a_forced_one_pass_over_the_card_is_refused_in_cautious( + test_state, create_fake_model_files +) -> None: + _configure_windows(test_state, create_fake_model_files, vram_gib=16, mode="cautious") + assert _create(test_state, _t2v("1080p", 10)).status_code == 200 + response = _create(test_state, _t2v("1080p", 10, pass_shape="one_pass")) + assert_http_error( + response, + status_code=422, + code=VIDEO_JOB_TOO_LARGE, + message=( + "This job needs 22.7 GB of GPU memory but this card has 16.0 GB. " + "Lower the resolution, duration, frame rate, or aspect width." + ), + ) + assert len(test_state.queued_generations.list_generations("text-to-video")) == 1 + + +@pytest.mark.parametrize("mode", ["brave", "cautious"]) +def test_a_forced_one_pass_past_the_mac_fence_is_refused_in_every_mode( + test_state, fake_services, create_fake_model_files, mode: str +) -> None: + # 1080p 20 s is past the MPS sequence fence in one pass; in parts it runs on this pool. + _configure_mac(test_state, fake_services, create_fake_model_files, pool_gib=32, mode=mode) + assert _create(test_state, _t2v("1080p", 20)).status_code == 200 + response = _create(test_state, _t2v("1080p", 20, pass_shape="one_pass")) + assert_http_error( + response, status_code=422, code=VIDEO_JOB_TOO_LARGE, message=MPS_SEQUENCE_OVER_MESSAGE + ) + + +def test_a_forced_one_pass_at_1440p_longer_than_one_part_is_refused( + test_state, create_fake_model_files +) -> None: + _configure_windows(test_state, create_fake_model_files, vram_gib=_RTX_5090_GIB, mode="brave") + response = _create(test_state, _t2v("1440p", 10, pass_shape="one_pass")) + assert_http_error( + response, status_code=422, code=ONE_PASS_UNAVAILABLE, message=ONE_PASS_UNAVAILABLE_MESSAGE + ) + assert _create(test_state, _t2v("1440p", 2, pass_shape="one_pass")).status_code == 200 + + +def test_forced_parts_run_even_where_brave_would_run_one_pass( + test_state, fake_services, create_fake_model_files, tmp_path: Path +) -> None: + # 540p 20 s at 48 fps is past the fitted tokens in one pass: Brave's own pick is one pass. + _configure_windows(test_state, create_fake_model_files, vram_gib=_RTX_5090_GIB, mode="brave") + auto = _create(test_state, _t2v("540p", 20, fps=48)) + parts = _create(test_state, _t2v("540p", 20, fps=48, pass_shape="parts")) + assert auto.status_code == 200 and parts.status_code == 200, (auto.text, parts.text) + assert _run(test_state, fake_services, tmp_path, auto.json()["id"]) is None + assert _run(test_state, fake_services, tmp_path, parts.json()["id"]) is not None + + +def test_the_stored_shape_and_not_the_live_setting_decides_the_run( + test_state, fake_services, create_fake_model_files, tmp_path: Path +) -> None: + _configure_windows(test_state, create_fake_model_files, vram_gib=16, mode="brave") + test_state.state.app_settings.never_split_into_parts = True + never_split = _create(test_state, _t2v("1080p", 10)) + test_state.state.app_settings.never_split_into_parts = False + automatic = _create(test_state, _t2v("1080p", 10)) + assert never_split.status_code == 200 and automatic.status_code == 200 + test_state.state.app_settings.never_split_into_parts = True + assert _run(test_state, fake_services, tmp_path, automatic.json()["id"]) is not None + test_state.state.app_settings.never_split_into_parts = False + assert _run(test_state, fake_services, tmp_path, never_split.json()["id"]) is None + # An automatic length is sized for the stored shape too: in Cautious one pass + # stops at 6 s, and the live parts range (20 s) would be refused in one pass. + test_state.state.app_settings.budget_mode = "cautious" + test_state.state.app_settings.never_split_into_parts = True + auto_length = _create(test_state, _t2v("1080p", None)) + assert auto_length.status_code == 200, auto_length.text + test_state.state.app_settings.never_split_into_parts = False + assert _run(test_state, fake_services, tmp_path, auto_length.json()["id"]) is None + assert fake_services.fast_video_pipeline.generate_calls[-1]["num_frames"].max_seconds == 6 + + +def test_never_split_withholds_cells_that_only_fit_in_parts_in_cautious( + test_state, create_fake_model_files +) -> None: + _configure_windows(test_state, create_fake_model_files, vram_gib=16, mode="cautious") + assert 10 in _kept(_fast_spec(test_state), "1080p") + test_state.state.app_settings.never_split_into_parts = True + spec = _fast_spec(test_state) + assert 10 not in _kept(spec, "1080p") + dropped = _cell(spec["dropped_cells"], "1080p", 10) + assert dropped is not None and dropped["reason"] == "stream_over" + + +def test_never_split_offers_cells_that_only_fit_in_parts_as_over_in_brave( + test_state, create_fake_model_files +) -> None: + _configure_windows(test_state, create_fake_model_files, vram_gib=16, mode="brave") + test_state.state.app_settings.never_split_into_parts = True + spec = _fast_spec(test_state) + assert 10 in _kept(spec, "1080p") + warned = _cell(spec["warned_cells"], "1080p", 10) + assert warned is not None and warned["tier"] == "over" + ask = _cell(spec["cell_asks"], "1080p", 10) + assert ask is not None and ask["windows"] == 1 + + +@pytest.mark.parametrize("mode", ["brave", "cautious"]) +def test_never_split_withholds_1440p_cells_longer_than_one_part( + test_state, create_fake_model_files, mode: str +) -> None: + _configure_windows(test_state, create_fake_model_files, vram_gib=_RTX_5090_GIB, mode=mode) + test_state.state.app_settings.never_split_into_parts = True + spec = _fast_spec(test_state) + assert 2 in _kept(spec, "1440p") and 10 not in _kept(spec, "1440p") + dropped = _cell(spec["dropped_cells"], "1440p", 10) + assert dropped is not None + assert (dropped["reason"], dropped["message"]) == ("one_pass_unavailable", ONE_PASS_UNAVAILABLE_MESSAGE) + + +def test_an_explicit_parts_request_wins_over_the_switch( + test_state, fake_services, create_fake_model_files, tmp_path: Path +) -> None: + _configure_windows(test_state, create_fake_model_files, vram_gib=16, mode="brave") + test_state.state.app_settings.never_split_into_parts = True + response = _create(test_state, _t2v("1080p", 10, pass_shape="parts")) + assert response.status_code == 200, response.text + assert response.json()["risk"] is None + assert _run(test_state, fake_services, tmp_path, response.json()["id"]) is not None + # An automatic length is not cut to the one-pass maximum. + auto_length = _create(test_state, _t2v("1080p", None, pass_shape="parts")) + assert auto_length.status_code == 200, auto_length.text + assert _run(test_state, fake_services, tmp_path, auto_length.json()["id"]) is not None + assert fake_services.fast_video_pipeline.generate_calls[-1]["num_frames"].max_seconds == 20 + # Every 4K audio-to-video length is longer than one part, so the switch alone + # drops the whole row. + _configure_windows(test_state, create_fake_model_files, vram_gib=_RTX_5090_GIB, mode="brave") + a2v = _a2v_create(test_state, tmp_path, "2160p", seconds=5.0, pass_shape="parts") + assert a2v.status_code == 200, a2v.text + assert _stored_spec(test_state, a2v.json()["id"])["_passShape"] == "parts" + + +def test_the_alternative_ask_is_sent_only_in_brave_where_the_toggle_shows( + test_state, fake_services, create_fake_model_files +) -> None: + # On a 16 GB card 1080p 10 s runs in parts (one pass is over), and 2 s fits in one pass. + _configure_windows(test_state, create_fake_model_files, vram_gib=16, mode="brave") + asks = _fast_spec(test_state)["cell_asks"] + parts = _cell(asks, "1080p", 10) + one_pass = _cell(asks, "1080p", 2) + assert parts is not None and parts["alternative"]["windows"] == 1 + assert one_pass is not None and "alternative" not in one_pass + test_state.state.app_settings.budget_mode = "cautious" + assert all("alternative" not in ask for ask in _fast_spec(test_state)["cell_asks"]) + # On a 5090, 540p 20 s at 48 fps runs one pass past the fitted tokens, so parts are + # the alternative, until the switch makes one pass the only shape. + _configure_windows(test_state, create_fake_model_files, vram_gib=_RTX_5090_GIB, mode="brave") + asks = _fast_spec(test_state)["cell_asks"] + past_fitted = _cell(asks, "540p", 20, fps=48) + assert past_fitted is not None and past_fitted["alternative"]["windows"] > 1 + # 1440p 10 s runs in parts; one pass there is never offered. + high_res = _cell(asks, "1440p", 10) + assert high_res is not None and high_res["windows"] > 1 and "alternative" not in high_res + test_state.state.app_settings.never_split_into_parts = True + assert all("alternative" not in ask for ask in _fast_spec(test_state)["cell_asks"]) + test_state.state.app_settings.never_split_into_parts = False + # 1080p 20 s on a Mac runs in parts; one pass is past the sequence fence. + _configure_mac(test_state, fake_services, create_fake_model_files, pool_gib=32, mode="brave") + fenced = _cell(_fast_spec(test_state)["cell_asks"], "1080p", 20) + assert fenced is not None and fenced["windows"] > 1 and "alternative" not in fenced + + +@pytest.mark.parametrize( + ("vram_gib", "resolution", "duration", "fps", "shape"), + [ + (16, "1080p", 10, 24, "one_pass"), # parts by default, one pass over the card + (_RTX_5090_GIB, "540p", 20, 48, "parts"), # one pass past the fitted tokens by default + ], +) +def test_the_alternative_ask_is_what_create_runs_for_that_shape( + test_state, + fake_services, + create_fake_model_files, + tmp_path: Path, + vram_gib: float, + resolution: str, + duration: int, + fps: int, + shape: str, +) -> None: + _configure_windows(test_state, create_fake_model_files, vram_gib=vram_gib, mode="brave") + ask = _cell(_fast_spec(test_state)["cell_asks"], resolution, duration, fps) + assert ask is not None + alternative = ask["alternative"] + response = _create(test_state, _t2v(resolution, duration, fps=fps, pass_shape=shape)) + assert response.status_code == 200, response.text + if shape == "one_pass": + assert response.json()["risk"]["readout"]["need_gb"] == pytest.approx(alternative["ask_gib"], abs=0.1) + else: + # A clean parts job carries no readout; Cautious's own pick for this cell is + # parts, and its ask is the one Cautious create runs. + assert response.json()["risk"] is None + test_state.state.app_settings.budget_mode = "cautious" + cautious = _cell(_fast_spec(test_state)["cell_asks"], resolution, duration, fps) + assert cautious is not None + assert (cautious["windows"], cautious["ask_gib"]) == (alternative["windows"], alternative["ask_gib"]) + window = _run(test_state, fake_services, tmp_path, response.json()["id"]) + assert job_window_count(compute_num_frames(duration, fps), window) == alternative["windows"] + + +def test_remote_create_keeps_the_pass_shape(test_state, create_fake_model_files) -> None: + _configure_windows(test_state, create_fake_model_files, vram_gib=16, mode="brave") + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as client: + response = client.post( + "/api/generations/text-to-video", + headers={"Authorization": "Bearer pair-token"}, + json=_t2v("1080p", 10, pass_shape="one_pass"), + ) + assert response.status_code == 200, response.text + assert _stored_spec(test_state, response.json()["id"])["_passShape"] == "one_pass" diff --git a/backend/tests/test_patch_import_smoke.py b/backend/tests/test_patch_import_smoke.py index 627cf7ce8..586205376 100644 --- a/backend/tests/test_patch_import_smoke.py +++ b/backend/tests/test_patch_import_smoke.py @@ -1,4 +1,4 @@ -"""Import every Desktop ltx-2 patch plus distilled_keyframe_guiding. +"""Import every Desktop ltx-2 patch. Catches import-time AssertionError (the 1.3.0 recommended_tiling_config class of boot failure) without starting the FastAPI server. @@ -12,9 +12,8 @@ PATCHES_DIR = Path(__file__).resolve().parents[1] / "services" / "patches" -def test_every_patch_module_and_keyframe_guiding_import() -> None: +def test_every_patch_module_imports() -> None: modules = sorted(p.stem for p in PATCHES_DIR.glob("*.py") if p.stem != "__init__") assert modules, "expected services/patches/*.py modules" for name in modules: importlib.import_module(f"services.patches.{name}") - importlib.import_module("services.fast_video_pipeline.distilled_keyframe_guiding") diff --git a/backend/tests/test_perf_runner_queued.py b/backend/tests/test_perf_runner_queued.py index 7b8a1bb04..0c838b089 100644 --- a/backend/tests/test_perf_runner_queued.py +++ b/backend/tests/test_perf_runner_queued.py @@ -50,9 +50,12 @@ def get(self, path: str) -> Any: if path == queued.QUEUE_PATH: running = [i for i, s in self.status.items() if s in {"queued", "running"}] if not running: - return {"active": None} + return {"active": []} self.status[running[0]] = "running" - return {"active": {"generation": {"id": running[0]}, "progress": {"phase": self.phase}}} + # Another lane's job runs too. The driver must pick its own entry, not the first. + other = {"generation": {"id": "other-lane-job"}, "progress": {"phase": "validating_request"}} + mine = {"generation": {"id": running[0]}, "progress": {"phase": self.phase}} + return {"active": [other, mine]} generation_id = path.rsplit("/", 1)[1] self.polls[generation_id] = self.polls.get(generation_id, 0) + 1 if self.status[generation_id] in {"queued", "running"} and self.polls[generation_id] >= self.polls_until_done: diff --git a/backend/tests/test_pinned_pool_fix.py b/backend/tests/test_pinned_pool_fix.py index 29c801d76..29743da6f 100644 --- a/backend/tests/test_pinned_pool_fix.py +++ b/backend/tests/test_pinned_pool_fix.py @@ -1,13 +1,15 @@ -"""Streaming pinned-host alloc must not surface as a CUDA VRAM OOM.""" +"""Pinned host buffers must degrade to pageable memory, not crash or surface as a CUDA VRAM OOM.""" from __future__ import annotations import pytest import torch -from ltx_core.block_streaming import utils as bs_utils +from ltx_core.loader import buffers, registry, state_loader, streaming_builder import services.patches.pinned_pool_fix as patch +_PINNED_REQUEST_BYTES = 4 << 20 + @pytest.fixture(autouse=True) def _reset_windows_log_flag() -> None: @@ -16,99 +18,76 @@ def _reset_windows_log_flag() -> None: patch._windows_pageable_logged = False -def test_patch_rebinds_alloc_buffer() -> None: - assert bs_utils.alloc_buffer is patch._patched_alloc_buffer - - -def test_require_attr_fails_loudly_when_symbol_missing() -> None: - with pytest.raises(RuntimeError, match="definitely_missing_symbol not found"): - patch._require_attr("definitely_missing_symbol") +def test_every_importer_of_host_bytes_is_rebound() -> None: + """A module that kept the upstream reference would still crash on Windows.""" + assert buffers.host_bytes is patch._patched_host_bytes + for module in (registry, state_loader, streaming_builder): + assert module.host_bytes is patch._patched_host_bytes -def test_unpinned_allocation_unchanged() -> None: - buf = patch._patched_alloc_buffer(64, torch.device("cpu"), pin_memory=False) +def test_unpinned_request_is_upstream_behavior() -> None: + buf = patch._patched_host_bytes(64) assert buf.shape == (64,) assert buf.dtype == torch.uint8 assert not buf.is_pinned() -def test_windows_pin_request_uses_pageable_memory(monkeypatch: pytest.MonkeyPatch) -> None: +def test_windows_pin_request_uses_pageable_memory_without_touching_upstream(monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr(patch.sys, "platform", "win32") - monkeypatch.setattr(torch.cuda, "is_available", lambda: True) - def register_must_not_run(_nbytes: int) -> torch.Tensor | None: - raise AssertionError("cudaHostRegister path must be skipped on Windows") + def upstream_must_not_run(_nbytes: int, *, pin: bool = False) -> torch.Tensor: + raise AssertionError("upstream pins through mmap.MAP_ANONYMOUS, which Windows lacks") - monkeypatch.setattr(patch, "_alloc_pinned_exact_cleared", register_must_not_run) + monkeypatch.setattr(patch, "_orig_host_bytes", upstream_must_not_run) - buf = patch._patched_alloc_buffer(1024, torch.device("cpu"), pin_memory=True) - assert buf.numel() == 1024 + buf = patch._patched_host_bytes(_PINNED_REQUEST_BYTES, pin=True) + + assert buf.numel() == _PINNED_REQUEST_BYTES assert buf.dtype == torch.uint8 assert not buf.is_pinned() -def test_windows_allocate_layout_views_stays_pageable(monkeypatch: pytest.MonkeyPatch) -> None: - monkeypatch.setattr(patch.sys, "platform", "win32") - monkeypatch.setattr(torch.cuda, "is_available", lambda: True) - views = bs_utils.allocate_layout_views({"k": (torch.Size([4, 4]), torch.bfloat16)}, pin_memory=True) - assert not views["k"].is_pinned() - assert views["k"].shape == torch.Size([4, 4]) - - -def test_linux_clears_sticky_error_after_register_failure(monkeypatch: pytest.MonkeyPatch) -> None: +def test_linux_registration_failure_clears_sticky_error_and_falls_back_to_pageable( + monkeypatch: pytest.MonkeyPatch, +) -> None: monkeypatch.setattr(patch.sys, "platform", "linux") - monkeypatch.setattr(torch.cuda, "is_available", lambda: True) - monkeypatch.setattr(patch, "_orig_alloc_pinned_exact", lambda _nbytes: None) cleared: list[bool] = [] monkeypatch.setattr(patch, "_clear_cuda_sticky_error", lambda: cleared.append(True)) - real_empty = torch.empty + def failing_register(nbytes: int, *, pin: bool = False) -> torch.Tensor: + raise RuntimeError(f"could not page-lock {nbytes} host bytes") - def empty_unpinned(*args: object, pin_memory: bool = False, **kwargs: object) -> torch.Tensor: - return real_empty(*args, pin_memory=False, **kwargs) # type: ignore[arg-type] + monkeypatch.setattr(patch, "_orig_host_bytes", failing_register) - monkeypatch.setattr(torch, "empty", empty_unpinned) + buf = patch._patched_host_bytes(_PINNED_REQUEST_BYTES, pin=True) - buf = patch._patched_alloc_buffer(32, torch.device("cpu"), pin_memory=True) - assert buf.numel() == 32 + assert buf.numel() == _PINNED_REQUEST_BYTES + assert not buf.is_pinned() assert cleared == [True] -def test_linux_pin_oom_falls_back_to_pageable(monkeypatch: pytest.MonkeyPatch) -> None: +def test_linux_pinned_pool_cuda_oom_falls_back_to_pageable(monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr(patch.sys, "platform", "linux") - monkeypatch.setattr(torch.cuda, "is_available", lambda: True) - monkeypatch.setattr(patch, "_alloc_pinned_exact_cleared", lambda _nbytes: None) - cleared: list[bool] = [] - monkeypatch.setattr(patch, "_clear_cuda_sticky_error", lambda: cleared.append(True)) + monkeypatch.setattr(patch, "_clear_cuda_sticky_error", lambda: None) - real_empty = torch.empty + def oom_pin(_nbytes: int, *, pin: bool = False) -> torch.Tensor: + raise RuntimeError("CUDA error: out of memory") - def empty_maybe_pin(*args: object, pin_memory: bool = False, **kwargs: object) -> torch.Tensor: - if pin_memory: - raise RuntimeError("CUDA error: out of memory") - return real_empty(*args, pin_memory=False, **kwargs) # type: ignore[arg-type] + monkeypatch.setattr(patch, "_orig_host_bytes", oom_pin) - monkeypatch.setattr(torch, "empty", empty_maybe_pin) + buf = patch._patched_host_bytes(128, pin=True) - buf = patch._patched_alloc_buffer(128, torch.device("cpu"), pin_memory=True) assert buf.numel() == 128 assert not buf.is_pinned() - assert cleared == [True] -def test_linux_pin_non_oom_is_not_swallowed(monkeypatch: pytest.MonkeyPatch) -> None: +def test_linux_unrelated_runtime_error_is_not_swallowed(monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr(patch.sys, "platform", "linux") - monkeypatch.setattr(torch.cuda, "is_available", lambda: True) - monkeypatch.setattr(patch, "_alloc_pinned_exact_cleared", lambda _nbytes: None) - - real_empty = torch.empty - def empty_maybe_pin(*args: object, pin_memory: bool = False, **kwargs: object) -> torch.Tensor: - if pin_memory: - raise RuntimeError("CUDA error: invalid argument") - return real_empty(*args, pin_memory=False, **kwargs) # type: ignore[arg-type] + def invalid_argument(_nbytes: int, *, pin: bool = False) -> torch.Tensor: + raise RuntimeError("CUDA error: invalid argument") - monkeypatch.setattr(torch, "empty", empty_maybe_pin) + monkeypatch.setattr(patch, "_orig_host_bytes", invalid_argument) with pytest.raises(RuntimeError, match="invalid argument"): - patch._patched_alloc_buffer(8, torch.device("cpu"), pin_memory=True) + patch._patched_host_bytes(8, pin=True) diff --git a/backend/tests/test_pipeline_load_guarantees.py b/backend/tests/test_pipeline_load_guarantees.py index 0f0534f10..10d6e9e3c 100644 --- a/backend/tests/test_pipeline_load_guarantees.py +++ b/backend/tests/test_pipeline_load_guarantees.py @@ -62,7 +62,7 @@ def _swap_cases(test_state, lora_path: str, depth_path: str) -> dict[str, _Loade ), "retake": _LoaderCase( fake_class=FakeRetakePipeline, - first=lambda: test_state.pipelines.load_retake_pipeline(distilled=True), + first=lambda: test_state.pipelines.load_retake_pipeline(distilled=True)[0], swap=lambda: test_state.pipelines.load_retake_pipeline(distilled=False), ), "ic-lora": _LoaderCase( @@ -156,3 +156,24 @@ def _spy(*args: Any, **kwargs: Any) -> Any: monkeypatch.setattr(fake_class, "create", _spy) load() assert observed.get("held") is True + + +def test_image_load_releases_a_resident_video_pipeline_before_create( + test_state, create_fake_model_files, monkeypatch +) -> None: + """A queued image job often follows a video job: both models must not be resident at once.""" + create_fake_model_files(include_zit=True) + video = test_state.pipelines.load_gpu_pipeline("fast") + old = weakref.ref(video) + del video + original_create = FakeImageGenerationPipeline.create + observed: dict[str, bool] = {} + + def _spy(*args: Any, **kwargs: Any) -> Any: + gc.collect() + observed["video_alive"] = old() is not None + return original_create(*args, **kwargs) + + monkeypatch.setattr(FakeImageGenerationPipeline, "create", _spy) + test_state.pipelines.load_image_generation_pipeline_to_gpu() + assert observed.get("video_alive") is False diff --git a/backend/tests/test_prompt_enhancement.py b/backend/tests/test_prompt_enhancement.py index 2cdad1fbd..ef46ffa19 100644 --- a/backend/tests/test_prompt_enhancement.py +++ b/backend/tests/test_prompt_enhancement.py @@ -3,9 +3,12 @@ from __future__ import annotations import base64 +from contextlib import nullcontext import logging from io import BytesIO +from pathlib import Path +import ltx_pipelines.utils.gpu_model as ltx_gpu_model from PIL import Image from api_types import ( InstructionSection, @@ -17,6 +20,8 @@ from services import generation_interrupt from services.gemini_text_client import DEFAULT_GEMINI_MODEL from services.prompt_enhancement import build_audio_visual_caption_system_prompt +from services.prompt_enhancer_pipeline import ltx_prompt_enhancer_pipeline as ltx_mod +from services.prompt_enhancer_pipeline.ltx_prompt_enhancer_pipeline import LtxPromptEnhancerPipeline from tests.fakes import FakeResponse from tests.http_error_assertions import assert_http_error from tests.lora_catalog_helpers import add_ic_lora, add_lora @@ -180,6 +185,82 @@ def test_keyframe_strength_is_forwarded_to_enhance_i2v( (str(opening), 0, 0.7) ] + def test_keyframe_asset_ids_reach_enhance_i2v_as_paths_in_time_order( + self, client, fake_services, create_fake_model_files, make_test_image, tmp_path + ): + # Explore sends asset ids. A route that skipped them would enhance from text alone. + create_fake_model_files(model_id=_LOCAL_ENHANCER_MODEL_ID) + paths = [tmp_path / "late.png", tmp_path / "early.png"] + for path in paths: + path.write_bytes(make_test_image().getvalue()) + late, early = ( + client.post("/api/assets", json={"path": str(path)}).json()["id"] for path in paths + ) + + r = client.post( + "/api/enhance-prompt", + json={ + "prompt": "", + "duration": 5, + "fps": 24, + "keyframeAssets": [ + {"assetId": late, "frameIndex": 80, "strength": 0.5}, + {"assetId": early, "frameIndex": 0}, + ], + }, + ) + + assert r.status_code == 200, r.text + call = fake_services.prompt_enhancer_pipeline.enhance_i2v_calls[0] + # The asset store copies each file, so the paths are the stored copies. + sent = call["keyframes"] + assert [(frame, strength) for _, frame, strength in sent] == [(0, 1.0), (80, 0.5)] + assert len({path for path, _, _ in sent}) == 2 + assert all(Path(path).is_file() for path, _, _ in sent) + assert call["duration"] == 5 + assert call["fps"] == 24 + + def test_a_typed_prompt_and_the_keyframes_reach_one_rewrite_together( + self, client, fake_services, create_fake_model_files, make_test_image, tmp_path + ): + # The rewrite must use the typed text as its instruction, beside the stills. + # Dropping either one would turn it into a text-only or a stills-only rewrite. + create_fake_model_files(model_id=_LOCAL_ENHANCER_MODEL_ID) + paths = [tmp_path / "a.png", tmp_path / "b.png"] + for path in paths: + path.write_bytes(make_test_image().getvalue()) + ids = [client.post("/api/assets", json={"path": str(path)}).json()["id"] for path in paths] + + r = client.post( + "/api/enhance-prompt", + json={ + "prompt": "slow dolly in", + "duration": 5, + "fps": 24, + "keyframeAssets": [ + {"assetId": ids[0], "frameIndex": 0}, + {"assetId": ids[1], "frameIndex": 96}, + ], + }, + ) + + assert r.status_code == 200, r.text + calls = fake_services.prompt_enhancer_pipeline.enhance_i2v_calls + assert len(calls) == 1 + assert calls[0]["prompt"] == "slow dolly in" + assert [frame[1] for frame in calls[0]["keyframes"]] == [0, 96] + + def test_keyframes_and_keyframe_assets_cannot_both_be_sent(self, client): + r = client.post( + "/api/enhance-prompt", + json={ + "prompt": "a cat", + "keyframes": [{"imagePath": "/tmp/a.png", "frameIndex": 0}], + "keyframeAssets": [{"assetId": "asset-1", "frameIndex": 1}], + }, + ) + assert r.status_code == 422 + def test_keyframes_cannot_mix_with_first_frame( self, client, create_fake_model_files, make_test_image, tmp_path ): @@ -1031,6 +1112,97 @@ def test_local_provider_still_requires_gemma_even_with_gemini_key_set(self, clie r = client.post("/api/enhance-prompt", json={"prompt": "x"}) assert_http_error(r, status_code=409, code="LOCAL_TEXT_ENCODER_NOT_AVAILABLE") + def test_enhance_passes_negative_prompt_as_exclusion_constraint_on_positive_rewrite( + self, client, test_state + ): + test_state.state.app_settings.gemini_api_key = "key" + test_state.http.queue("post", _gemini_ok("a sharp fox in the snow")) + + r = client.post( + "/api/enhance-prompt", + json={"prompt": "a fox", "negativePrompt": "blurry, watermark", "provider": "api"}, + ) + assert r.status_code == 200 + assert r.json() == {"enhancedPrompt": "a sharp fox in the snow"} + payload = test_state.http.calls[-1].json_payload + assert ( + "Excluded elements (do not include or mention in the prompt): blurry, watermark" + in payload["contents"][0]["parts"][0]["text"] + ) + assert "Do NOT include, mention, describe, or imply" in payload["systemInstruction"]["parts"][0]["text"] + + # Empty negativePrompt omits the exclusion constraint. + test_state.http.queue("post", _gemini_ok("a plain fox caption")) + r_empty = client.post( + "/api/enhance-prompt", + json={"prompt": "a fox", "negativePrompt": "", "provider": "api"}, + ) + assert r_empty.status_code == 200 + assert r_empty.json() == {"enhancedPrompt": "a plain fox caption"} + empty_payload = test_state.http.calls[-1].json_payload + assert "Excluded elements" not in empty_payload["contents"][0]["parts"][0]["text"] + assert "Do NOT include, mention, describe, or imply" not in empty_payload["systemInstruction"]["parts"][0]["text"] + + def test_template_fill_ic_lora_enhance_passes_negative_prompt_exclusion_to_enhancer( + self, client, test_state, fake_services, create_fake_model_files + ): + create_fake_model_files(model_id=_LOCAL_ENHANCER_MODEL_ID) + test_state.state.app_settings.use_local_text_encoder = True + add_ic_lora( + fake_services, + id="deblur", + name="Deblur", + prompt_template=PromptTemplateSpec( + template="Reference shows {reference}. DEBLUR {result}.", + placeholders={ + "reference": PromptTemplatePlaceholder(), + "result": PromptTemplatePlaceholder(), + }, + ), + ) + fake_services.prompt_enhancer_pipeline.enhanced_prompt = ( + '{"reference": "a blurry butterfly", "result": "a sharp butterfly"}' + ) + + r = client.post( + "/api/enhance-prompt", + json={ + "prompt": "sharpen the butterfly", + "negativePrompt": "haloing, ringing", + "icLoraId": "deblur", + }, + ) + assert r.status_code == 200 + assert r.json()["enhancedPrompt"] == "Reference shows a blurry butterfly. DEBLUR a sharp butterfly." + call = fake_services.prompt_enhancer_pipeline.enhance_t2v_calls[-1] + assert call["negative_prompt"] == "haloing, ringing" + + def test_ltx_prompt_enhancer_pipeline_includes_negative_prompt_exclusion_in_system_and_user_messages( + self, monkeypatch + ): + captured_messages: list[list[dict[str, object]]] = [] + + monkeypatch.setattr(ltx_gpu_model, "gpu_model", lambda enc: nullcontext(enc)) + monkeypatch.setattr(LtxPromptEnhancerPipeline, "_build_text_encoder", lambda self: object()) + monkeypatch.setattr(ltx_mod, "_default_system_prompt", lambda _enc, *, t2v: "default system") + + def fake_generate(_enc, messages, *, image, seed, max_new_tokens_floor=None): + del image, seed, max_new_tokens_floor + captured_messages.append(messages) + return "a sharp fox in the snow" + + monkeypatch.setattr(ltx_mod, "_generate", fake_generate) + + pipe = LtxPromptEnhancerPipeline(gemma_root="/fake/gemma", device="cpu") + out = pipe.enhance_t2v("a fox", None, 42, negative_prompt="blurry, watermark") + assert out == "a sharp fox in the snow" + assert len(captured_messages) == 1 + sys_msg, user_msg = captured_messages[0] + assert "Do NOT include, mention, describe, or imply" in str(sys_msg["content"]) + assert "Excluded elements (do not include or mention in the prompt): blurry, watermark" in str( + user_msg["content"] + ) + class TestImageMediaType: def test_generation_uses_image_generation_system_prompt( diff --git a/backend/tests/test_queue_dispatcher.py b/backend/tests/test_queue_dispatcher.py new file mode 100644 index 000000000..102e4f7ce --- /dev/null +++ b/backend/tests/test_queue_dispatcher.py @@ -0,0 +1,425 @@ +"""The dispatcher runs one runner per lane. Lanes run side by side. + +Each test names the bug it catches. Jobs fail on purpose after the checks: only the +timing and the claim order matter here, not the output. +""" + +from __future__ import annotations + +import threading +import time +from collections.abc import Mapping +from contextlib import AbstractContextManager, nullcontext +from pathlib import Path + +from pydantic import JsonValue + +from services.displaced_provider_jobs import ( + DISPLACED_PROVIDER_JOBS_FILENAME, + DisplacedProviderJobs, +) +from services.generation_interrupt import GenerationCancelledError +from services.generation_queue.dispatcher import QueueDispatcher +from services.generation_queue.lane_sessions import LaneJobSession +from services.generation_queue.lane_slots import CountingLaneSlot +from services.generation_queue.lanes import LOCAL_LANE_SPEC, LaneSpec +from services.generation_queue.registry import ExecutorRegistry +from services.generation_queue.runner import QueueRunner +from services.generation_queue.types import ExecutionOutcome, OutputAllocation, OutputPlan +from services.records import LOCAL_LANE, GenerationRecord, ProviderOrphan +from services.sqlite_store import SqliteStore +from tests.fakes.lanes import TEST_FEATURE, TEST_LANE, TEST_LANE_SPEC + +_PLAN = OutputPlan(slot="output", media_kind="video", mime_type="video/mp4", name="output.mp4") + + +def _spec() -> dict[str, JsonValue]: + return {"params": {"prompt": "fox"}, "inputs": {}} + + +class _OpenSlot: + def wait_for_generation_slot(self, shutdown: threading.Event) -> AbstractContextManager[None]: + del shutdown + return nullcontext() + + def cancel_generation(self) -> object: + return None + + +class _ProbeExecutor: + """Records overlap and claim order, then fails the job.""" + + def __init__(self, lane: str, *, hold_seconds: float = 0.0, barrier: threading.Barrier | None = None) -> None: + self._lane = lane + self._hold_seconds = hold_seconds + self._barrier = barrier + self._lock = threading.Lock() + self.running = 0 + self.max_running = 0 + self.runs: list[str] = [] + self.release = threading.Event() + self.release.set() + + def validate_params(self, spec: Mapping[str, object], *, contract_version: int) -> None: + del spec, contract_version + + def lane_for(self, spec: Mapping[str, object]) -> str: + del spec + return self._lane + + def plan_outputs(self, generation: GenerationRecord) -> tuple[OutputPlan, ...]: + del generation + return (_PLAN,) + + def execute(self, generation: GenerationRecord, outputs: tuple[OutputAllocation, ...], session) -> ExecutionOutcome: + del outputs, session + with self._lock: + self.running += 1 + self.max_running = max(self.max_running, self.running) + self.runs.append(generation.id) + try: + if self._barrier is not None: + self._barrier.wait() + time.sleep(self._hold_seconds) + self.release.wait(timeout=10) + finally: + with self._lock: + self.running -= 1 + raise RuntimeError("probe done") + + +def _runner(store: SqliteStore, executors: dict[str, _ProbeExecutor], lane: LaneSpec, **kwargs) -> QueueRunner: + local = lane.id == LOCAL_LANE + return QueueRunner( + db=store, + generation=_OpenSlot() if local else CountingLaneSlot(lane.concurrency), + executors=ExecutorRegistry(executors), # type: ignore[arg-type] + lane=lane, + session_factory=None if local else (lambda job: LaneJobSession(job.id, job.attempt_count, store.set_provider_job_id)), + idle_wait_seconds=kwargs.pop("idle_wait_seconds", 0.05), + **kwargs, + ) + + +def _wait(predicate, timeout: float = 5.0) -> bool: + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + if predicate(): + return True + time.sleep(0.01) + return predicate() + + +def _failed(store: SqliteStore, *ids: str) -> bool: + return all(store.get_generation(generation_id).status == "failed" for generation_id in ids) + + +def test_a_local_job_and_a_remote_job_are_in_flight_together(tmp_path: Path) -> None: + # Bug caught: lanes share one worker, so the second job starts only after the first ends. + store = SqliteStore(tmp_path / "app_data") + barrier = threading.Barrier(2, timeout=3) + executors = { + "text-to-video": _ProbeExecutor(LOCAL_LANE, barrier=barrier), + TEST_FEATURE: _ProbeExecutor(TEST_LANE, barrier=barrier), + } + local = store.insert_generation("text-to-video", _spec()) + remote = store.insert_generation(TEST_FEATURE, _spec(), lane=TEST_LANE) + dispatcher = QueueDispatcher( + [_runner(store, executors, LOCAL_LANE_SPEC), _runner(store, executors, TEST_LANE_SPEC)] + ) + + dispatcher.start() + try: + assert _wait(lambda: _failed(store, local.id, remote.id)) + # Both jobs end failed on purpose. A barrier that timed out means they never overlapped. + assert not barrier.broken + finally: + dispatcher.stop() + + +def test_a_lane_runs_one_job_at_a_time_at_concurrency_one(tmp_path: Path) -> None: + # Bug caught: a remote lane with concurrency 1 runs two provider requests at once. + store = SqliteStore(tmp_path / "app_data") + probe = _ProbeExecutor(TEST_LANE, hold_seconds=0.05) + ids = [store.insert_generation(TEST_FEATURE, _spec(), lane=TEST_LANE).id for _ in range(3)] + dispatcher = QueueDispatcher( + [_runner(store, {TEST_FEATURE: probe, "text-to-video": _ProbeExecutor(LOCAL_LANE)}, LOCAL_LANE_SPEC), + _runner(store, {TEST_FEATURE: probe}, TEST_LANE_SPEC)] + ) + + dispatcher.start() + try: + assert _wait(lambda: _failed(store, *ids)) + finally: + dispatcher.stop() + + assert probe.max_running == 1 + assert probe.runs == ids + + +def test_two_workers_of_one_lane_never_run_the_same_row(tmp_path: Path) -> None: + # Bug caught: two workers claim one row and the provider request is sent twice. + store = SqliteStore(tmp_path / "app_data") + # The barrier lets a job finish only when three run together, so max_running is exact. + probe = _ProbeExecutor(TEST_LANE, barrier=threading.Barrier(3, timeout=10)) + wide_lane = LaneSpec(id=TEST_LANE, concurrency=3, uses_gpu=False, cancellable_while_running=True) + ids = [store.insert_generation(TEST_FEATURE, _spec(), lane=TEST_LANE).id for _ in range(12)] + dispatcher = QueueDispatcher( + [_runner(store, {"text-to-video": _ProbeExecutor(LOCAL_LANE)}, LOCAL_LANE_SPEC), + _runner(store, {TEST_FEATURE: probe}, wide_lane)] + ) + + dispatcher.start() + try: + assert _wait(lambda: _failed(store, *ids)) + finally: + dispatcher.stop() + + assert sorted(probe.runs) == sorted(ids) + assert len(set(probe.runs)) == len(ids) + assert probe.max_running == 3 + + +def test_wake_reaches_the_runner_of_the_lane_that_got_the_row(tmp_path: Path) -> None: + # Bug caught: a new remote row waits for the idle poll because only the local runner is woken. + store = SqliteStore(tmp_path / "app_data") + probe = _ProbeExecutor(TEST_LANE) + dispatcher = QueueDispatcher( + [_runner(store, {"text-to-video": _ProbeExecutor(LOCAL_LANE)}, LOCAL_LANE_SPEC, idle_wait_seconds=30), + _runner(store, {TEST_FEATURE: probe}, TEST_LANE_SPEC, idle_wait_seconds=30)] + ) + dispatcher.start() + try: + time.sleep(0.2) # Both runners are now idle and wait on their wake event. + job = store.insert_generation(TEST_FEATURE, _spec(), lane=TEST_LANE) + dispatcher.wake() + + assert _wait(lambda: _failed(store, job.id), timeout=3) + finally: + dispatcher.stop() + + +def test_stop_waits_for_all_lanes_against_one_deadline(tmp_path: Path) -> None: + # Bug caught: stop joins the lanes one after the other, so shutdown takes N times the limit. + store = SqliteStore(tmp_path / "app_data") + local_probe = _ProbeExecutor(LOCAL_LANE) + remote_probe = _ProbeExecutor(TEST_LANE) + for probe in (local_probe, remote_probe): + probe.release.clear() # The job ignores a stop and ends only when released. + store.insert_generation("text-to-video", _spec()) + store.insert_generation(TEST_FEATURE, _spec(), lane=TEST_LANE) + slow_remote = LaneSpec(id=TEST_LANE, concurrency=1, uses_gpu=False, cancellable_while_running=True) + dispatcher = QueueDispatcher( + [_runner(store, {"text-to-video": local_probe}, LOCAL_LANE_SPEC), + _runner(store, {TEST_FEATURE: remote_probe}, slow_remote)], + stop_join_timeout_seconds=1.0, + ) + dispatcher.start() + assert _wait(lambda: local_probe.running == 1 and remote_probe.running == 1) + + started = time.monotonic() + dispatcher.stop() + elapsed = time.monotonic() - started + + local_probe.release.set() + remote_probe.release.set() + assert elapsed < 1.0 * 1.8 + + +class _ProviderWaitExecutor(_ProbeExecutor): + """A provider job: it waits on its session like the remote client does.""" + + def execute(self, generation: GenerationRecord, outputs: tuple[OutputAllocation, ...], session) -> ExecutionOutcome: + del outputs + with self._lock: + self.running += 1 + self.runs.append(generation.id) + try: + while not session.wait_cancelled(0.01): + pass + raise GenerationCancelledError() + finally: + with self._lock: + self.running -= 1 + + +def test_stop_cancels_a_provider_job_so_its_request_is_freed(tmp_path: Path) -> None: + # Bug caught: the app quits with a remote request open. The job never sees a cancel and the provider keeps billing it. + store = SqliteStore(tmp_path / "app_data") + probe = _ProviderWaitExecutor(TEST_LANE) + store.insert_generation(TEST_FEATURE, _spec(), lane=TEST_LANE) + dispatcher = QueueDispatcher( + [_runner(store, {"text-to-video": _ProbeExecutor(LOCAL_LANE)}, LOCAL_LANE_SPEC), + _runner(store, {TEST_FEATURE: probe}, TEST_LANE_SPEC)], + ) + dispatcher.start() + assert _wait(lambda: probe.running == 1) + + dispatcher.stop() + + # The job saw the cancel and returned. Boot recovery fails the row it left running. + assert probe.running == 0 + + +class _SubmitThenEndExecutor(_ProbeExecutor): + """A provider job: the provider accepts it, then the job ends the given way.""" + + def __init__(self, lane: str, end: str) -> None: + super().__init__(lane) + self.end = end + self.submitted = threading.Event() + + def execute(self, generation: GenerationRecord, outputs: tuple[OutputAllocation, ...], session) -> ExecutionOutcome: + del outputs + assert session.set_provider_job_id("req-77") is True + self.submitted.set() + if self.end == "fail": + raise RuntimeError("lost the provider") + while not session.wait_cancelled(0.01): + pass + raise GenerationCancelledError() + + +def _lane_with_cancel(cancels: list[str]) -> LaneSpec: + return LaneSpec( + id=TEST_LANE, + concurrency=1, + uses_gpu=False, + cancellable_while_running=True, + cancel_orphan=cancels.append, + ) + + +def test_a_user_cancel_asks_the_provider_to_drop_the_job_and_clears_its_id(tmp_path: Path) -> None: + # Bug caught: the row becomes cancelled, the executor stops waiting, and the provider keeps the job. + store = SqliteStore(tmp_path / "app_data") + executor = _SubmitThenEndExecutor(TEST_LANE, "cancel") + cancels: list[str] = [] + job = store.insert_generation(TEST_FEATURE, _spec(), lane=TEST_LANE) + runner = _runner(store, {TEST_FEATURE: executor}, _lane_with_cancel(cancels)) + runner.start() + try: + assert executor.submitted.wait(5.0) + cancelling = store.request_generation_cancellation(job.id) + runner.interrupt(cancelling.id, cancelling.attempt_count) + + assert _wait(lambda: cancels == ["req-77"]) + assert _wait(lambda: (g := store.get_generation(job.id)) is not None and g.provider_job_id is None) + finally: + runner.stop() + final = store.get_generation(job.id) + assert final is not None and final.status == "cancelled" + + +def test_a_job_that_fails_after_the_provider_accepted_it_is_cancelled_at_the_provider(tmp_path: Path) -> None: + # Bug caught: an executor error ends the row as failed while the provider still runs and bills the job. + store = SqliteStore(tmp_path / "app_data") + executor = _SubmitThenEndExecutor(TEST_LANE, "fail") + cancels: list[str] = [] + job = store.insert_generation(TEST_FEATURE, _spec(), lane=TEST_LANE) + runner = _runner(store, {TEST_FEATURE: executor}, _lane_with_cancel(cancels)) + runner.start() + try: + assert _wait(lambda: cancels == ["req-77"]) + finally: + runner.stop() + final = store.get_generation(job.id) + assert final is not None and final.status == "failed" + + +def _failed_with_id(store: SqliteStore, provider_id: str) -> GenerationRecord: + store.insert_generation(TEST_FEATURE, _spec(), lane=TEST_LANE) + claimed = store.claim_next_queued(TEST_LANE) + assert claimed is not None + store.set_provider_job_id(claimed.id, claimed.attempt_count, provider_id) + store.mark_failed(claimed.id, "OUTPUT_UNREADABLE", attempt_count=claimed.attempt_count) + return claimed + + +def test_a_retry_before_the_runner_reads_the_id_does_not_lose_the_provider_job(tmp_path: Path) -> None: + # Bug caught: the user retries between the failure and the provider cancel, and the old id is gone. + store = SqliteStore(tmp_path / "app_data") + cancels: list[str] = [] + runner = _runner(store, {}, _lane_with_cancel(cancels)) + failed = _failed_with_id(store, "req-1") + store.retry_generation(failed.id) + + runner._release_provider_job(failed) + + assert _wait(lambda: cancels == ["req-1"]) + assert _wait(lambda: store.list_provider_orphans() == []) + + +def test_a_failed_cancel_of_a_replaced_attempt_keeps_its_id_for_the_next_boot(tmp_path: Path) -> None: + # Bug caught: a provider that is down makes the retry drop the id for good. + store = SqliteStore(tmp_path / "app_data") + calls: list[str] = [] + + def provider_down(provider_job_id: str) -> None: + calls.append(provider_job_id) + raise RuntimeError("provider down") + + lane = LaneSpec( + id=TEST_LANE, concurrency=1, uses_gpu=False, cancellable_while_running=True, + cancel_orphan=provider_down, + ) + runner = _runner(store, {}, lane) + failed = _failed_with_id(store, "req-1") + store.retry_generation(failed.id) + + runner._release_provider_job(failed) + + assert _wait(lambda: calls == ["req-1"]) + assert [o.provider_job_id for o in store.list_provider_orphans()] == ["req-1"] + + +def test_a_replaced_attempt_of_another_lane_is_left_to_the_boot(tmp_path: Path) -> None: + # Bug caught: a lane cancels a job of another lane with the wrong provider call. + store = SqliteStore(tmp_path / "app_data") + cancels: list[str] = [] + runner = _runner(store, {}, _lane_with_cancel(cancels)) + failed = _failed_with_id(store, "req-1") + store.retry_generation(failed.id, lane=LOCAL_LANE) + displaced = DisplacedProviderJobs( + tmp_path / "app_data" / DISPLACED_PROVIDER_JOBS_FILENAME + ) + displaced.remove(failed.id, "req-1") + displaced.add( + ProviderOrphan(generation_id=failed.id, lane="other-provider", provider_job_id="req-1") + ) + + runner._release_provider_job(failed) + + assert cancels == [] + assert [o.provider_job_id for o in store.list_provider_orphans()] == ["req-1"] + + +def test_a_job_claimed_while_the_lane_stops_is_cancelled(tmp_path: Path) -> None: + # Bug caught: a job that registers after request_stop took its snapshot runs past the stop. + store = SqliteStore(tmp_path / "app_data") + store.insert_generation(TEST_FEATURE, _spec(), lane=TEST_LANE) + sessions: list[LaneJobSession] = [] + holder: dict[str, QueueRunner] = {} + + def factory(job: GenerationRecord) -> LaneJobSession: + # The stop lands between the claim and the registration of the job. + holder["runner"].request_stop() + session = LaneJobSession(job.id, job.attempt_count, store.set_provider_job_id) + sessions.append(session) + return session + + runner = QueueRunner( + db=store, + generation=CountingLaneSlot(1), + executors=ExecutorRegistry({TEST_FEATURE: _ProviderWaitExecutor(TEST_LANE)}), # type: ignore[arg-type] + lane=TEST_LANE_SPEC, + session_factory=factory, + idle_wait_seconds=0.05, + ) + holder["runner"] = runner + runner.start() + try: + assert _wait(lambda: len(sessions) == 1) + assert _wait(lambda: sessions[0].wait_cancelled(0)) + finally: + runner.stop() diff --git a/backend/tests/test_refine_details_flag.py b/backend/tests/test_refine_details_flag.py deleted file mode 100644 index 395f0f8f0..000000000 --- a/backend/tests/test_refine_details_flag.py +++ /dev/null @@ -1,156 +0,0 @@ -"""Refine Details needs the highResVideoToVideo flag: every path refuses or hides it while the flag is off.""" - -from __future__ import annotations - -from pathlib import Path - -import imageio.v2 as imageio -import numpy as np -from starlette.testclient import TestClient - -from api_types import IcLoraCatalogItem, parse_lora_catalog -from handlers.base import resolve_models_dir -from runtime_config.model_download_specs import resolve_ic_lora_path -from tests.http_error_assertions import assert_http_error - -_REFINE = "refine-details" -_ALPHA = "alpha-gen" -_CATALOG = Path(__file__).resolve().parents[1] / "runtime_config" / "lora_catalog.json" - - -def _mp4(path: Path) -> Path: - writer = imageio.get_writer(str(path), fps=8, codec="libx264", macro_block_size=None) - frame = np.zeros((16, 16, 3), dtype=np.uint8) - for _ in range(8): - writer.append_data(frame) - writer.close() - return path - - -def _set_flag(client: TestClient, enabled: bool) -> None: - response = client.request("PATCH", "/api/feature-flags", json={"highResVideoToVideo": enabled}) - assert response.status_code == 200, response.text - - -def _install(fake_services, test_state, ic_lora_id: str, *, weights: bool = True) -> IcLoraCatalogItem: - """Add the shipped catalog entry to the fake catalog and write its weights.""" - item = next( - entry - for entry in parse_lora_catalog(_CATALOG.read_text()).ic_loras - if entry.id == ic_lora_id - ) - fake_services.lora_catalog_provider._catalog.ic_loras.append(item) - if weights: - models_dir = resolve_models_dir(test_state.state, test_state.config) - path = resolve_ic_lora_path(models_dir, item.id, item.download.variants[0].filename) - path.parent.mkdir(parents=True, exist_ok=True) - path.write_bytes(b"weights") - return item - - -def _create_recipe(client: TestClient, recipe_id: str, video_id: str, resolution: str = "720p"): - return client.post( - f"/api/generations/ic-lora-recipes/{recipe_id}", - json={ - "params": {"prompt": "restore fine detail", "model": "ltx-2.5-fast", "resolution": resolution}, - "inputs": {"video": {"assetId": video_id}}, - }, - ) - - -def _listed_ids(client: TestClient) -> list[str]: - response = client.get("/api/ic-loras") - assert response.status_code == 200, response.text - return [row["ic_lora"]["id"] for row in response.json()["ic_loras"]] - - -def test_catalog_list_hides_refine_details_until_the_flag_is_on( - client: TestClient, fake_services, test_state, create_fake_model_files -) -> None: - create_fake_model_files(model_id="ltx-2.5-22b-distilled") - _install(fake_services, test_state, _REFINE, weights=False) - - assert _REFINE not in _listed_ids(client) - - _set_flag(client, True) - assert _REFINE in _listed_ids(client) - - -def test_download_of_refine_details_is_unknown_until_the_flag_is_on( - client: TestClient, fake_services, test_state, create_fake_model_files -) -> None: - create_fake_model_files(model_id="ltx-2.5-22b-distilled") - _install(fake_services, test_state, _REFINE, weights=False) - - refused = client.post("/api/ic-loras/download", json={"ic_lora_id": _REFINE}) - assert refused.status_code == 404 - - _set_flag(client, True) - accepted = client.post("/api/ic-loras/download", json={"ic_lora_id": _REFINE}) - assert accepted.status_code == 200, accepted.text - - -def test_generate_and_preflight_refuse_refine_details_until_the_flag_is_on( - client: TestClient, fake_services, test_state, create_fake_model_files, tmp_path: Path -) -> None: - create_fake_model_files(model_id="ltx-2.5-22b-distilled") - _install(fake_services, test_state, _REFINE) - clip = _mp4(tmp_path / "clip.mp4") - generate = { - "ic_lora_id": _REFINE, - "input_path": str(clip), - "prompt": "", - "conditioning_type": "custom", - } - preflight = {"ic_lora_id": _REFINE, "input_path": str(clip), "durations": [1.0]} - - for path, body in (("/api/ic-lora/generate", generate), ("/api/ic-lora/preflight", preflight)): - assert_http_error( - client.post(path, json=body), - status_code=422, - code="HIGH_RES_NOT_ENABLED", - message="HIGH_RES_NOT_ENABLED", - ) - - _set_flag(client, True) - allowed = client.post("/api/ic-lora/preflight", json=preflight) - assert allowed.status_code == 200, allowed.text - - -def test_home_create_refuses_refine_details_until_the_flag_is_on( - client: TestClient, fake_services, test_state, create_fake_model_files, tmp_path: Path -) -> None: - create_fake_model_files(model_id="ltx-2.5-22b-distilled") - _install(fake_services, test_state, _REFINE) - video = client.post("/api/assets", json={"path": str(_mp4(tmp_path / "clip.mp4"))}).json() - - assert_http_error( - _create_recipe(client, _REFINE, video["id"]), - status_code=422, - code="HIGH_RES_NOT_ENABLED", - message="HIGH_RES_NOT_ENABLED", - ) - - _set_flag(client, True) - accepted = _create_recipe(client, _REFINE, video["id"]) - assert accepted.status_code == 200, accepted.text - assert accepted.json()["spec"]["params"]["loras"][0]["catalogId"] == _REFINE - - -def test_recent_features_skip_refine_details_before_the_limit_while_the_flag_is_off( - client: TestClient, fake_services, test_state, create_fake_model_files, tmp_path: Path -) -> None: - create_fake_model_files(model_id="ltx-2.5-22b-distilled") - _install(fake_services, test_state, _ALPHA) - _install(fake_services, test_state, _REFINE) - video = client.post("/api/assets", json={"path": str(_mp4(tmp_path / "clip.mp4"))}).json() - assert _create_recipe(client, _ALPHA, video["id"], "540p").status_code == 200 - _set_flag(client, True) - assert _create_recipe(client, _REFINE, video["id"]).status_code == 200 - - shown = client.get("/api/generations/recent-features", params={"limit": 1}) - assert shown.json() == [_REFINE] - - _set_flag(client, False) - hidden = client.get("/api/generations/recent-features", params={"limit": 1}) - assert hidden.json() == [_ALPHA] diff --git a/backend/tests/test_remote_generations.py b/backend/tests/test_remote_generations.py index 9153a9b01..4e9fe59f0 100644 --- a/backend/tests/test_remote_generations.py +++ b/backend/tests/test_remote_generations.py @@ -22,6 +22,10 @@ _APPROVED_PARAM_KEYS = frozenset( { "prompt", + "negativePrompt", + "nagScale", + "nagAlpha", + "nagTau", "model", "resolution", "duration", @@ -33,6 +37,10 @@ "mode", "startTime", "seed", + "passShape", + "width", + "height", + "provider", } ) _SECRET_PATHS = ( @@ -190,10 +198,12 @@ def test_recent_features_match_on_desktop_and_remote(test_state) -> None: older = store.insert_generation("text-to-video", _spec("older")) newer = store.insert_generation("extend", _spec("newer")) hidden = store.insert_generation("desktop-only-feature", _spec("hidden")) + # Bug caught: a newer image job takes a Recently used slot, but has no Home screen to reopen. + image = store.insert_generation("text-to-image", _spec("image")) conn = sqlite3.connect(test_state.config.app_data_dir / "store.sqlite3") conn.executemany( "UPDATE generations SET created_at = ? WHERE id = ?", - [(1, older.id), (2, newer.id), (3, hidden.id)], + [(1, older.id), (2, newer.id), (3, hidden.id), (4, image.id)], ) conn.commit() conn.close() @@ -214,6 +224,40 @@ def test_recent_features_match_on_desktop_and_remote(test_state) -> None: assert remote_recent.json() == desktop_recent.json() +def test_remote_creates_text_to_image_and_projects_only_form_fields(test_state) -> None: + test_state.state.app_settings.fal_api_key = "fal-key" + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as client: + created = client.post( + "/api/generations/text-to-image", + headers=AUTH, + json={ + "params": { + "prompt": "a fox", + "width": 1000, + "height": 768, + "provider": "fal", + } + }, + ) + fetched = client.get(f"/api/generations/{created.json()['id']}", headers=AUTH) + + assert created.status_code == 200, created.text + body = created.json() + assert body["feature"] == "text-to-image" + assert body["spec"]["params"] == { + "prompt": "a fox", + "promptProvenance": "typed", + "width": 992, + "height": 768, + "provider": "fal", + } + assert "inputs" not in body["spec"] + _assert_no_path_keys(body) + assert fetched.status_code == 200 + assert fetched.json()["feature"] == "text-to-image" + + def test_remote_creates_lora_recipe_and_strips_ref( test_state, monkeypatch, create_fake_model_files ) -> None: @@ -428,10 +472,15 @@ def test_remote_generation_openapi_is_queued_only(test_state) -> None: "/api/generation-seed": ["get", "post"], "/api/generations": ["get"], "/api/generations/audio-to-video": ["post"], + "/api/generations/custom-lora": ["post"], + "/api/generations/text-to-image": ["post"], "/api/generations/edit/preflight": ["post"], "/api/generations/extend": ["post"], "/api/generations/ic-lora-recipes/{recipe_id}": ["post"], + "/api/generations/ic-lora-recipes/{recipe_id}/memory": ["post"], + "/api/generations/ic-lora-recipes/{recipe_id}/preflight": ["post"], "/api/generations/image-to-video": ["post"], + "/api/generations/keyframes": ["post"], "/api/generations/recipes/{recipe_id}": ["post"], "/api/generations/recent-features": ["get"], "/api/generations/retake": ["post"], @@ -490,7 +539,7 @@ def test_remote_queue_snapshot_excludes_desktop_file_paths( assert snapshot.status_code == 200, snapshot.text body = snapshot.json() - assert body["active"] is None + assert body["active"] == [] assert body["done"] == [] assert body["failed"] == [] assert body["unseen_ids"] == [] @@ -502,6 +551,24 @@ def test_remote_queue_snapshot_excludes_desktop_file_paths( _assert_no_secret_paths(body) +def test_remote_snapshot_hides_a_running_job_of_a_feature_the_remote_may_not_see( + test_state, +) -> None: + # Bug caught: the new "active" list skips the feature filter and leaks a desktop-only job. + store = _store(test_state) + hidden = store.insert_generation("desktop-only-feature", _spec("hidden")) + claimed = store.claim_next_queued("local") + assert claimed is not None and claimed.id == hidden.id + app = create_remote_app(handler=test_state, remote_token="pair-token") + + with TestClient(app) as client: + snapshot = client.get("/api/generation-queue", headers=AUTH) + + assert snapshot.status_code == 200, snapshot.text + assert snapshot.json()["active"] == [] + assert hidden.id not in snapshot.text + + def test_remote_reorder_returns_path_free_queue_snapshot( test_state, tmp_path: Path ) -> None: @@ -528,7 +595,7 @@ def test_remote_reorder_returns_path_free_queue_snapshot( assert reordered.status_code == 200, reordered.text body = reordered.json() assert "id" not in body - assert body["active"] is None + assert body["active"] == [] assert [entry["generation"]["id"] for entry in body["queued"]] == [ second.id, first.id, @@ -602,7 +669,10 @@ def _assert_remote_asset_payload(payload: object) -> dict[str, object]: return payload -def test_remote_create_t2v_keeps_form_fields_and_drops_lora_refs(test_state) -> None: +def test_remote_create_t2v_keeps_form_fields_and_drops_lora_refs( + test_state, create_fake_model_files +) -> None: + create_fake_model_files() app = create_remote_app(handler=test_state, remote_token="pair-token") with TestClient(app) as client: created = client.post( @@ -641,6 +711,10 @@ def test_remote_create_t2v_keeps_form_fields_and_drops_lora_refs(test_state) -> params = body["spec"]["params"] assert params == { "prompt": "a fox on a beach", + "negativePrompt": "blurry", + "nagScale": 11.0, + "nagAlpha": 0.25, + "nagTau": 2.5, "model": "ltx-2.5-fast", "aspectRatio": "16:9", "resolution": "720p", @@ -648,6 +722,7 @@ def test_remote_create_t2v_keeps_form_fields_and_drops_lora_refs(test_state) -> "fps": 24, "scale": 0.5, "promptProvenance": "typed", + "passShape": "auto", } assert set(params) <= _APPROVED_PARAM_KEYS assert "inputs" not in body["spec"] @@ -757,6 +832,7 @@ def test_remote_create_i2v_keeps_asset_ids_for_form_restore( "duration": 8, "fps": 50, "promptProvenance": "typed", + "passShape": "auto", } assert body["spec"]["inputs"] == { "startFrame": {"assetId": start["id"]}, @@ -1039,6 +1115,42 @@ def test_remote_projects_an_integer_seed_and_drops_other_values(test_state) -> N _assert_no_secret_paths(junk_body) +def test_remote_keeps_the_advanced_tiling_choices_so_reuse_restores_the_run(test_state) -> None: + tiling: dict[str, JsonValue] = { + "tilingOverlap": 0.25, + "carryFrames": 41, + "tilingSize": "large", + "maxWindowFrames": 97, + } + store = _store(test_state) + saved = store.insert_generation( + "refine-details", {"params": {"prompt": "fox", **tiling}, "inputs": {}} + ) + damaged = store.insert_generation( + "refine-details", + { + "params": { + "prompt": "fox", + "tilingOverlap": 9, + "carryFrames": 3, + "tilingSize": "/Users/me/secret", + "maxWindowFrames": 5, + }, + "inputs": {}, + }, + ) + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as client: + saved_body = client.get(f"/api/generations/{saved.id}", headers=AUTH).json() + damaged_body = client.get(f"/api/generations/{damaged.id}", headers=AUTH) + + assert {key: saved_body["spec"]["params"][key] for key in tiling} == tiling + # A stored value out of range is dropped, never a 500 that hides the whole generation. + assert damaged_body.status_code == 200 + assert not tiling.keys() & damaged_body.json()["spec"]["params"].keys() + _assert_no_secret_paths(damaged_body.json()) + + def test_remote_get_strips_nested_path_like_spec_values( test_state, tmp_path: Path ) -> None: diff --git a/backend/tests/test_remote_prompt_enhancement.py b/backend/tests/test_remote_prompt_enhancement.py index 06b52c096..348a3b28d 100644 --- a/backend/tests/test_remote_prompt_enhancement.py +++ b/backend/tests/test_remote_prompt_enhancement.py @@ -172,6 +172,51 @@ def test_remote_enhance_resolves_image_asset_id( assert r.json()["enhancedPrompt"] == "a still, enhanced" +def test_remote_enhance_reads_keyframe_asset_ids_with_a_blank_prompt( + test_state, tmp_path: Path +) -> None: + test_state.state.app_settings.gemini_api_key = "gemini-key" + test_state.http.queue("post", _gemini_ok("a hall, enhanced")) + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as client: + uploaded = client.post( + "/api/assets/upload", + headers=AUTH, + files={"file": ("frame.png", _png_bytes(tmp_path), "image/png")}, + ) + assert uploaded.status_code == 200 + r = client.post( + "/api/enhance-prompt", + headers=AUTH, + json={ + "prompt": "", + "provider": "api", + "duration": 5, + "fps": 24, + "keyframeAssets": [{"assetId": uploaded.json()["id"], "frameIndex": 0}], + }, + ) + assert r.status_code == 200, r.text + assert r.json()["enhancedPrompt"] == "a hall, enhanced" + + +def test_remote_enhance_accepts_the_empty_custom_lora_list_every_home_form_sends( + test_state, +) -> None: + # The Home Enhance request always carries customLoraIds. A body model that forbids it + # fails Enhance on the phone for every feature. + test_state.state.app_settings.gemini_api_key = "gemini-key" + test_state.http.queue("post", _gemini_ok("enhanced")) + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as client: + r = client.post( + "/api/enhance-prompt", + headers=AUTH, + json={"prompt": "a cat", "provider": "api", "customLoraIds": []}, + ) + assert r.status_code == 200, r.text + + def test_full_settings_stay_off_remote(test_state) -> None: app = create_remote_app(handler=test_state, remote_token="pair-token") with TestClient(app) as client: @@ -327,3 +372,32 @@ def test_remote_enhance_rejects_a_bad_selection_mix_with_422_not_500( assert r.status_code == 422 assert "validation error" not in r.text + + +def test_remote_enhance_accepts_media_type_image_with_the_image_system_prompt(test_state) -> None: + test_state.state.app_settings.gemini_api_key = "gemini-key" + test_state.http.queue("post", _gemini_ok("a shiny red sedan")) + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as client: + r = client.post( + "/api/enhance-prompt", + headers=AUTH, + json={"prompt": "a red car", "provider": "api", "mediaType": "image"}, + ) + + assert r.status_code == 200 + assert r.json()["enhancedPrompt"] == "a shiny red sedan" + instruction = test_state.http.calls[-1].json_payload["systemInstruction"]["parts"][0]["text"] + assert "Z-Image-Turbo" in instruction + + +def test_remote_image_enhance_refuses_an_input_image_so_edit_stays_unreachable(test_state) -> None: + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as client: + r = client.post( + "/api/enhance-prompt", + headers=AUTH, + json={"prompt": "a red car", "mediaType": "image", "imageAssetId": "asset-1"}, + ) + + assert r.status_code == 422 diff --git a/backend/tests/test_retake_extend_generation.py b/backend/tests/test_retake_extend_generation.py index 26e2d9743..a15abb39e 100644 --- a/backend/tests/test_retake_extend_generation.py +++ b/backend/tests/test_retake_extend_generation.py @@ -13,6 +13,7 @@ import pytest from api_types import ExtendParams, LTXLocalModelId, RetakeParams +from runtime_config.budget_admission import RiskAllowance from runtime_config.ltx_runtime_paths import resolve_ltx_runtime_paths from runtime_config.model_download_specs import get_existing_cp_path, get_ltx_model_spec from runtime_config.video_job_budget import ( @@ -331,7 +332,7 @@ def _prepare_extend(test_state, video_path: str, duration: float): 42, test_state.config.outputs_dir / "out.mp4", str(test_state.config.outputs_dir / "windowed.mp4"), - allow_risk=False, + allowance=RiskAllowance.none(), ) @@ -396,7 +397,7 @@ def test_queued_home_edit_loads_the_text_encoder_of_its_own_model( 1, tmp_path / "out.mp4", str(tmp_path / "out.window.mp4"), - allow_risk=False, + allowance=RiskAllowance.none(), ) assert fake_services.retake_pipeline.create_calls[-1]["gemma_root"] == expected_gemma_root diff --git a/backend/tests/test_retake_stitch.py b/backend/tests/test_retake_stitch.py index bb0e8039a..8050bbe15 100644 --- a/backend/tests/test_retake_stitch.py +++ b/backend/tests/test_retake_stitch.py @@ -5,6 +5,7 @@ import subprocess from pathlib import Path +import av import imageio_ffmpeg import numpy as np import pytest @@ -20,7 +21,7 @@ STITCH_TIMEOUT_CAP_SECONDS, timeout_for_source_duration, ) -from services.retake_pipeline.rgb_stitch import iter_span +from services.retake_pipeline.rgb_stitch import iter_span, write_rgb_video from services.retake_pipeline.window import ( MAX_FADE_FRAMES, denoised_frame_span, @@ -406,3 +407,24 @@ def test_late_rgb_span_matches_when_timestamps_do_not_start_at_zero(tmp_path: Pa full = list(iter_span(str(shifted), 0, 180, 16, 16)) late = list(iter_span(str(shifted), 100, 108, 16, 16)) assert np.array_equal(late, full[100:108]) + + +def test_write_rgb_video_closes_the_frame_source_when_the_encode_fails(tmp_path: Path): + # An odd width makes libx264 refuse to open. The frame generator must still be closed, or + # on Windows it keeps its source file open and blocks the caller's cleanup (WinError 32). + closed: list[bool] = [] + + def frames(): + try: + yield np.zeros((360, 635, 3), dtype=np.uint8) + finally: + closed.append(True) + + try: + write_rgb_video(tmp_path / "out.mp4", frames(), fps=24.0, width=635, height=360) + except av.error.FFmpegError: + # Checked while the exception is still being handled, which is when the caller's cleanup + # runs (the traceback still references the generator, so GC cannot close it for us). + assert closed == [True] + else: + pytest.fail("an odd width should not encode") diff --git a/backend/tests/test_runtime_policy_decision.py b/backend/tests/test_runtime_policy_decision.py index 78cce53f3..c94f72c08 100644 --- a/backend/tests/test_runtime_policy_decision.py +++ b/backend/tests/test_runtime_policy_decision.py @@ -282,9 +282,29 @@ def test_linux_unknown_ram_fails_closed_to_disk_streaming() -> None: def test_windows_routes_disk_on_nvme_only() -> None: - """NVMe sustains the ~70 GB mapped reads; SATA (~130 s) does not earn the switch.""" - assert should_disk_stream_cuda_weights("Windows", 64, drive_type="nvme") is True + """Windows NVMe falls back to disk below the CPU floor (or for Edit); SATA stays on CPU.""" assert should_disk_stream_cuda_weights("Windows", 32, drive_type="nvme") is True + assert should_disk_stream_cuda_weights("Windows", 40, drive_type="nvme") is False + assert should_disk_stream_cuda_weights("Windows", 64, drive_type="nvme") is False + assert ( + should_disk_stream_cuda_weights( + "Windows", 48, drive_type="nvme", cpu_ram_floor_gb=64 + ) + is True + ) + assert ( + should_disk_stream_cuda_weights( + "Windows", 64, drive_type="nvme", cpu_ram_floor_gb=64 + ) + is False + ) + assert ( + should_disk_stream_cuda_weights( + "Windows", 64, drive_type="nvme", cpu_ram_floor_gb=None + ) + is True + ) + assert should_disk_stream_cuda_weights("Windows", None, drive_type="nvme") is True assert should_disk_stream_cuda_weights("Windows", 64, drive_type="ssd") is False assert should_disk_stream_cuda_weights("Windows", 64, drive_type="hdd") is False assert should_disk_stream_cuda_weights("Windows", 64, drive_type=None) is False diff --git a/backend/tests/test_safetensors_loader_fix.py b/backend/tests/test_safetensors_loader_fix.py deleted file mode 100644 index a1871cb34..000000000 --- a/backend/tests/test_safetensors_loader_fix.py +++ /dev/null @@ -1,34 +0,0 @@ -"""Patched SafetensorsStateDictLoader.load must match safetensors.torch.load_file.""" - -from __future__ import annotations - -from pathlib import Path - -import torch -from ltx_core.loader.sft_loader import SafetensorsStateDictLoader -from safetensors.torch import load_file, save_file - -import services.patches.safetensors_loader_fix as patch - - -def test_patch_rebinds_loader() -> None: - assert SafetensorsStateDictLoader.load is patch._patched_load - - -def test_patched_load_matches_safetensors_load_file(tmp_path: Path) -> None: - path = tmp_path / "tiny.safetensors" - expected = { - "weight": torch.randn(8, 4, dtype=torch.float32), - "bias": torch.ones(4, dtype=torch.bfloat16), - } - save_file(expected, str(path)) - - loaded = patch._patched_load(SafetensorsStateDictLoader(), str(path), sd_ops=None) # type: ignore[arg-type] - reference = load_file(str(path)) - - assert set(loaded.sd) == set(reference) == set(expected) - for key, tensor in expected.items(): - torch.testing.assert_close(loaded.sd[key], tensor, rtol=0, atol=0) - torch.testing.assert_close(loaded.sd[key], reference[key], rtol=0, atol=0) - assert loaded.sd[key].dtype == tensor.dtype - assert loaded.sd[key].shape == tensor.shape diff --git a/backend/tests/test_safetensors_metadata_fix.py b/backend/tests/test_safetensors_metadata_fix.py deleted file mode 100644 index b89c9f7d7..000000000 --- a/backend/tests/test_safetensors_metadata_fix.py +++ /dev/null @@ -1,97 +0,0 @@ -"""FP8 scale / key scans must not use safetensors.safe_open (Windows commit charge). - -safetensors.safe_open maps the whole file with torch.UntypedStorage.from_file(shared=False), -which reserves copy-on-write commit equal to the file size. On a 46 GB distilled-1.1 -checkpoint that raises OSError 1455 before generation starts (Lightricks/LTX-Desktop#158). -""" - -from __future__ import annotations - -from pathlib import Path - -import pytest -import torch -from ltx_core.block_streaming import builder as streaming_builder -from ltx_core.model.transformer.model_configurator import LTXV_MODEL_COMFY_RENAMING_MAP -from ltx_core.quantization import fp8_cast -from safetensors.torch import save_file - -import services.patches.safetensors_metadata_fix as patch - -_PAGING_FILE_ERROR = OSError("The paging file is too small for this operation to complete. (os error 1455)") -_WEIGHT_KEY = "model.diffusion_model.transformer_blocks.0.attn1.to_q.weight" -_SCALE_KEY = f"{_WEIGHT_KEY}_scale" -_NON_BLOCK_KEY = "model.diffusion_model.proj_in.weight" - - -def _boom(*_args: object, **_kwargs: object) -> object: - raise _PAGING_FILE_ERROR - - -def _write_checkpoint(path: Path) -> Path: - save_file( - { - _WEIGHT_KEY: torch.zeros(2, 2, dtype=torch.float8_e4m3fn), - _SCALE_KEY: torch.tensor(0.5, dtype=torch.float32), - _NON_BLOCK_KEY: torch.zeros(2, 2, dtype=torch.bfloat16), - }, - str(path), - ) - return path - - -def test_read_scales_survives_safe_open_paging_file_error(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: - ckpt = _write_checkpoint(tmp_path / "model.safetensors") - monkeypatch.setattr(fp8_cast.safetensors, "safe_open", _boom) - - scales = fp8_cast._read_scales(ckpt) - - assert set(scales) == {"transformer_blocks.0.attn1.to_q.weight"} - torch.testing.assert_close(scales["transformer_blocks.0.attn1.to_q.weight"], torch.tensor(0.5)) - - -def test_build_fp8_policy_survives_safe_open_paging_file_error(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: - ckpt = _write_checkpoint(tmp_path / "model.safetensors") - monkeypatch.setattr(fp8_cast.safetensors, "safe_open", _boom) - - policy = fp8_cast.build_policy(ckpt) - - # Scale was registered: dropping the sibling key succeeds instead of raising. - assert policy.sd_ops is not None - assert policy.sd_ops.apply_to_key_value( - "transformer_blocks.0.attn1.to_q.weight_scale", - torch.tensor(0.5, dtype=torch.float32), - ) == [] - - -def test_read_scales_rejects_scale_key_without_diffusion_prefix( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - path = tmp_path / "bad.safetensors" - save_file({"other.weight_scale": torch.tensor(1.0, dtype=torch.float32)}, str(path)) - monkeypatch.setattr(fp8_cast.safetensors, "safe_open", _boom) - - with pytest.raises(ValueError, match="does not start with the expected raw prefix"): - fp8_cast._read_scales(path) - - -def test_scan_checkpoint_keys_survives_safe_open_paging_file_error( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - ckpt = _write_checkpoint(tmp_path / "model.safetensors") - monkeypatch.setattr(streaming_builder.safetensors, "safe_open", _boom) - - block_key_map, non_block_keys = streaming_builder._scan_checkpoint_keys( - [str(ckpt)], LTXV_MODEL_COMFY_RENAMING_MAP, "transformer_blocks" - ) - - assert set(block_key_map[0]) == { - (_WEIGHT_KEY, "attn1.to_q.weight"), - (_SCALE_KEY, "attn1.to_q.weight_scale"), - } - assert non_block_keys == [(_NON_BLOCK_KEY, "proj_in.weight")] - - -def test_patch_rebinds_read_scales_and_scan_checkpoint_keys() -> None: - assert fp8_cast._read_scales is patch._patched_read_scales - assert streaming_builder._scan_checkpoint_keys is patch._patched_scan_checkpoint_keys diff --git a/backend/tests/test_settings.py b/backend/tests/test_settings.py index 5172f892c..62d3e78fc 100644 --- a/backend/tests/test_settings.py +++ b/backend/tests/test_settings.py @@ -297,6 +297,14 @@ def test_use_conv_vae_round_trip(self, client, test_state): assert test_state.state.app_settings.use_conv_vae is False assert client.get("/api/settings").json()["useConvVae"] is False + def test_mps_conv3d_toggle_defaults_off_and_round_trips_in_camel_case(self, client, test_state): + assert client.get("/api/settings").json()["mpsConv3DAsConv2DEnabled"] is False + + r = client.post("/api/settings", json={"mpsConv3DAsConv2DEnabled": True}) + assert r.status_code == 200 + assert test_state.state.app_settings.mps_conv3d_as_conv2d_enabled is True + assert client.get("/api/settings").json()["mpsConv3DAsConv2DEnabled"] is True + def test_use_conv_vae_change_unloads_gpu_pipeline( self, client, test_state, fake_services, create_fake_model_files ): @@ -1074,3 +1082,17 @@ def test_errors_are_not_cached(self, client, test_state): DEFAULT_GEMINI_MODEL, ] assert len(test_state.http.calls) == 2 + + +@pytest.mark.parametrize("legacy_mode", ["standard", "reckless"]) +def test_settings_patch_folds_legacy_budget_mode_to_brave( + client, test_state, legacy_mode: str +) -> None: + test_state.state.app_settings.budget_mode = "cautious" + + response = client.post("/api/settings", json={"budgetMode": legacy_mode}) + + assert response.status_code == 200, response.text + assert test_state.state.app_settings.budget_mode == "brave" + assert client.get("/api/settings").json()["budgetMode"] == "brave" + diff --git a/backend/tests/test_state_actions.py b/backend/tests/test_state_actions.py index 842cfc6c3..2ebde7e7f 100644 --- a/backend/tests/test_state_actions.py +++ b/backend/tests/test_state_actions.py @@ -8,14 +8,15 @@ import pytest from _routes._errors import HTTPError +from services.patches import mps_conv3d_as_conv2d from runtime_config.ic_lora_stage_mode import IcLoraStageMode from runtime_config.video_job_budget import ( HardwareProfile, LocalJobFilter, MemoryBudget, - VideoJobLoad, decide_edit_job, ) +from runtime_config.budget_decision import VideoJobLoad from frame_math import compute_num_frames from handlers.generation_handler import GenerationSlotWaitAborted, _RESERVATION_TIMEOUT_S from services import generation_interrupt @@ -38,6 +39,28 @@ def test_start_generation_requires_gpu(test_state): test_state.generation.start_generation("gen-1") +def test_start_generation_pushes_mps_toggle_into_patch(test_state, create_fake_model_files, monkeypatch): + monkeypatch.setattr(mps_conv3d_as_conv2d, "_enabled", False) + create_fake_model_files() + test_state.pipelines.load_gpu_pipeline("fast") + test_state.settings.update_settings(UpdateSettingsRequest(mpsConv3DAsConv2DEnabled=True, useConvVae=True)) + + test_state.generation.start_generation("gen-1") + + assert mps_conv3d_as_conv2d._enabled is True + + +def test_start_generation_keeps_mps_patch_off_without_fast_decode(test_state, create_fake_model_files, monkeypatch): + monkeypatch.setattr(mps_conv3d_as_conv2d, "_enabled", True) + create_fake_model_files() + test_state.pipelines.load_gpu_pipeline("fast") + test_state.settings.update_settings(UpdateSettingsRequest(mpsConv3DAsConv2DEnabled=True, useConvVae=False)) + + test_state.generation.start_generation("gen-1") + + assert mps_conv3d_as_conv2d._enabled is False + + def test_generation_mutex_prevents_second_start(test_state, create_fake_model_files): create_fake_model_files() test_state.pipelines.load_gpu_pipeline("fast") @@ -326,7 +349,7 @@ def test_retake_pipeline_eviction(test_state, create_fake_model_files): create_fake_model_files() test_state.pipelines.load_gpu_pipeline("fast") - retake_state = test_state.pipelines.load_retake_pipeline(distilled=True) + retake_state, _ = test_state.pipelines.load_retake_pipeline(distilled=True) assert isinstance(test_state.state.gpu_slot, GpuSlot) assert isinstance(test_state.state.gpu_slot.active_pipeline, RetakePipelineState) assert test_state.state.gpu_slot.active_pipeline is retake_state @@ -349,7 +372,7 @@ def test_retake_pipeline_uses_text_encoder_of_the_requested_model( resolve_model_path(test_state.config.default_models_dir, spec_23.text_encoder_cp) ) - state = test_state.pipelines.load_retake_pipeline( + state, _ = test_state.pipelines.load_retake_pipeline( distilled=True, ltx_model_id="ltx-2.3-22b-distilled-1.1" ) @@ -365,7 +388,7 @@ def test_retake_1080p_streams_without_flipping_process_mode( assert test_state.config.local_generations_mode == "full_models_loading" frames = compute_num_frames(10, 24) - state = test_state.pipelines.load_retake_pipeline( + state, _ = test_state.pipelines.load_retake_pipeline( distilled=True, width=1920, height=1088, frames=frames ) @@ -400,9 +423,9 @@ def test_long_1080p_edit_window_is_capped_to_what_31gb_loads( ), ), ) - assert isinstance(decision, VideoJobLoad) + assert isinstance(decision.priced.decision, VideoJobLoad) - state = test_state.pipelines.load_retake_pipeline( + state, _ = test_state.pipelines.load_retake_pipeline( distilled=True, width=1920, height=1088, frames=cap ) assert state.loading_mode == "streaming_models_loading" @@ -489,7 +512,7 @@ def test_retake_540p_5s_stays_full(test_state, fake_services, create_fake_model_ create_fake_model_files() frames = compute_num_frames(5, 24) - state = test_state.pipelines.load_retake_pipeline( + state, _ = test_state.pipelines.load_retake_pipeline( distilled=True, width=1024, height=576, frames=frames ) @@ -501,10 +524,10 @@ def test_retake_full_pipeline_is_not_reused_for_a_stream_job( test_state, fake_services, create_fake_model_files ): create_fake_model_files() - small = test_state.pipelines.load_retake_pipeline( + small, _ = test_state.pipelines.load_retake_pipeline( distilled=True, width=1024, height=576, frames=compute_num_frames(5, 24) ) - large = test_state.pipelines.load_retake_pipeline( + large, _ = test_state.pipelines.load_retake_pipeline( distilled=True, width=1920, height=1088, frames=compute_num_frames(10, 24) ) diff --git a/backend/tests/test_store.py b/backend/tests/test_store.py index 722f2b871..3c14c4442 100644 --- a/backend/tests/test_store.py +++ b/backend/tests/test_store.py @@ -60,9 +60,10 @@ def test_fresh_db_applies_initial_schema(tmp_path: Path) -> None: "generations", "assets", "paired_devices", + "device_calibration_frontier", } version = conn.execute("SELECT MAX(version) FROM schema_migrations").fetchone()[0] - assert version == 2 + assert version == 4 asset_columns = { row["name"] for row in conn.execute("PRAGMA table_info(assets)").fetchall() } @@ -115,7 +116,7 @@ def test_second_open_is_noop(tmp_path: Path) -> None: apply_migrations(conn, MIGRATIONS_DIR) apply_migrations(conn, MIGRATIONS_DIR) count = conn.execute("SELECT COUNT(*) FROM schema_migrations").fetchone()[0] - assert count == 2 + assert count == 4 conn.close() @@ -129,7 +130,7 @@ def test_rerun_after_ddl_without_ledger_row_does_not_brick(tmp_path: Path) -> No conn.commit() apply_migrations(conn, MIGRATIONS_DIR) version = conn.execute("SELECT MAX(version) FROM schema_migrations").fetchone()[0] - assert version == 2 + assert version == 4 tables = { row[0] for row in conn.execute( diff --git a/backend/tests/test_store_assets_dir.py b/backend/tests/test_store_assets_dir.py new file mode 100644 index 000000000..e55815cb0 --- /dev/null +++ b/backend/tests/test_store_assets_dir.py @@ -0,0 +1,275 @@ +from __future__ import annotations + +import json +import sqlite3 +from pathlib import Path + +import pytest +from PIL import Image + +from app_handler import AppHandler, open_store +from remote.controller import RemoteExposureController +from services.features.video.reference_sheet import ensure_reference_sheet +from services.records import UnavailableError +from services.unavailable_store import UnavailableStore +from services.sqlite_store import ASSETS_MARKER_FILENAME, SqliteStore +from services.thumbnails import resolve_stored_thumbnail +from tests.test_store import _spec, _succeed_png + + +def _png(path: Path) -> Path: + Image.new("RGB", (64, 48), color=(10, 20, 30)).save(path) + return path + + +def _custom_dir(tmp_path: Path, *, marker: bool = True) -> Path: + assets_dir = tmp_path / "custom" + assets_dir.mkdir() + if marker: + (assets_dir / ASSETS_MARKER_FILENAME).write_text("") + return assets_dir + + +def _stored_thumbnail(app_data: Path, asset_id: str) -> str | None: + conn = sqlite3.connect(app_data / "store.sqlite3") + try: + row = conn.execute( + "SELECT thumbnail_path FROM assets WHERE id = ?", (asset_id,) + ).fetchone() + finally: + conn.close() + return None if row is None or row[0] is None else str(row[0]) + + +def test_custom_assets_dir_receives_ingested_files(tmp_path: Path) -> None: + app_data = tmp_path / "app_data" + assets_dir = _custom_dir(tmp_path) + store = SqliteStore(app_data, assets_dir=assets_dir) + + record = store.ingest_upload(str(_png(tmp_path / "cat.png"))) + + assert Path(record.path).parent == assets_dir + assert Path(record.path).is_file() + assert not (app_data / "assets" / Path(record.path).name).exists() + + +def test_missing_custom_assets_dir_is_unavailable_and_not_created( + tmp_path: Path, +) -> None: + missing = tmp_path / "unplugged" / "assets" + + with pytest.raises(UnavailableError): + SqliteStore(tmp_path / "app_data", assets_dir=missing) + + assert not missing.exists() + assert not missing.parent.exists() + + +def test_custom_assets_dir_without_marker_is_unavailable(tmp_path: Path) -> None: + with pytest.raises(UnavailableError): + SqliteStore(tmp_path / "app_data", assets_dir=_custom_dir(tmp_path, marker=False)) + + +def test_open_store_degrades_when_the_custom_assets_dir_is_missing( + tmp_path: Path, +) -> None: + store = open_store(tmp_path / "app_data", tmp_path / "unplugged") + + assert isinstance(store, UnavailableStore) + assert not (tmp_path / "unplugged").exists() + + +def test_open_store_uses_the_custom_assets_dir(tmp_path: Path) -> None: + assets_dir = _custom_dir(tmp_path) + store = open_store(tmp_path / "app_data", assets_dir) + + assert isinstance(store, SqliteStore) + record = store.ingest_upload(str(_png(tmp_path / "cat.png"))) + assert Path(record.path).parent == assets_dir + + +def test_remote_controller_starts_when_the_custom_assets_dir_is_missing( + test_state: AppHandler, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + # The store degrades to UnavailableStore. The remote controller must not crash the server. + monkeypatch.setattr(test_state.config, "assets_dir", tmp_path / "unplugged") + + RemoteExposureController(test_state) + + +def test_missing_assets_dir_at_runtime_does_not_tombstone_rows(tmp_path: Path) -> None: + assets_dir = _custom_dir(tmp_path) + store = SqliteStore(tmp_path / "app_data", assets_dir=assets_dir) + record = _succeed_png(store) + + moved = tmp_path / "custom-away" + assets_dir.rename(moved) + with pytest.raises(UnavailableError): + store.list_assets() + with pytest.raises(UnavailableError): + store.delete_asset(record.id) + assert store.get_asset(record.id) is None + + moved.rename(assets_dir) + page = store.list_assets() + assert [item.asset.id for item in page.items] == [record.id] + + +def test_default_assets_dir_still_tombstones_a_missing_file(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + record = _succeed_png(store) + Path(record.path).unlink() + + assert store.list_assets().items == () + assert store.get_asset(record.id) is None + Path(record.path).write_bytes(b"") + assert store.get_asset(record.id) is None + + +def test_generated_output_thumbnail_is_a_name_and_matches_a_later_read( + tmp_path: Path, +) -> None: + app_data = tmp_path / "app_data" + store = SqliteStore(app_data, assets_dir=_custom_dir(tmp_path)) + record = _succeed_png(store) + + assert record.thumbnail_path is not None + assert _stored_thumbnail(app_data, record.id) == f"{record.id}-thumb.jpg" + loaded = store.get_asset(record.id) + assert loaded is not None + assert loaded.thumbnail_path == record.thumbnail_path + assert Path(record.thumbnail_path).parent == tmp_path / "custom" + + +def test_thumbnail_column_holds_the_file_name_only(tmp_path: Path) -> None: + app_data = tmp_path / "app_data" + store = SqliteStore(app_data) + record = store.ingest_upload(str(_png(tmp_path / "cat.png"))) + + assert _stored_thumbnail(app_data, record.id) == f"{record.id}-thumb.jpg" + + +def test_ingest_result_and_later_read_return_the_same_thumbnail_path( + tmp_path: Path, +) -> None: + store = SqliteStore(tmp_path / "app_data", assets_dir=_custom_dir(tmp_path)) + record = store.ingest_upload(str(_png(tmp_path / "cat.png"))) + + loaded = store.get_asset(record.id) + assert loaded is not None + assert record.thumbnail_path is not None + assert loaded.thumbnail_path == record.thumbnail_path + assert Path(record.thumbnail_path).parent == tmp_path / "custom" + assert Path(record.thumbnail_path).is_file() + + +def test_old_row_with_absolute_thumbnail_path_resolves_in_current_folder( + tmp_path: Path, +) -> None: + app_data = tmp_path / "app_data" + store = SqliteStore(app_data) + record = store.ingest_upload(str(_png(tmp_path / "cat.png"))) + old_absolute = tmp_path / "old-folder" / f"{record.id}-thumb.jpg" + conn = sqlite3.connect(app_data / "store.sqlite3") + try: + conn.execute( + "UPDATE assets SET thumbnail_path = ? WHERE id = ?", + (str(old_absolute), record.id), + ) + conn.commit() + finally: + conn.close() + + loaded = store.get_asset(record.id) + + assert loaded is not None + assert loaded.thumbnail_path == str(app_data / "assets" / f"{record.id}-thumb.jpg") + assert Path(loaded.thumbnail_path).is_file() + + +def test_delete_removes_the_thumbnail_file(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data", assets_dir=_custom_dir(tmp_path)) + record = store.ingest_upload(str(_png(tmp_path / "cat.png"))) + assert record.thumbnail_path is not None + + assert store.delete_asset(record.id) is True + + assert not Path(record.path).exists() + assert not Path(record.thumbnail_path).exists() + + +def test_thumbnail_helpers_keep_only_a_safe_file_name(tmp_path: Path) -> None: + assert resolve_stored_thumbnail(tmp_path, None) is None + assert resolve_stored_thumbnail(tmp_path, "x-thumb.jpg") == tmp_path / "x-thumb.jpg" + assert resolve_stored_thumbnail(tmp_path, "../../etc/x.jpg") == tmp_path / "x.jpg" + assert resolve_stored_thumbnail(tmp_path, "..") is None + assert resolve_stored_thumbnail(tmp_path, "") is None + + +def test_marker_name_matches_the_shared_contract() -> None: + contract = Path(__file__).resolve().parents[2] / "shared" / "assets-marker.json" + assert json.loads(contract.read_text())["filename"] == ASSETS_MARKER_FILENAME + + +def test_default_folder_is_recreated_for_a_new_output(tmp_path: Path) -> None: + app_data = tmp_path / "app_data" + store = SqliteStore(app_data) + (app_data / "assets").rmdir() + + _, dest = store.allocate_output_path("image", "image/png") + + assert Path(dest).parent.is_dir() + + +def test_custom_folder_is_not_recreated_for_a_new_output(tmp_path: Path) -> None: + custom = _custom_dir(tmp_path) + store = SqliteStore(tmp_path / "app_data", assets_dir=custom) + (custom / ASSETS_MARKER_FILENAME).unlink() + custom.rmdir() + + with pytest.raises(UnavailableError): + store.allocate_output_path("image", "image/png") + + assert not custom.exists() + + +def test_missing_custom_folder_does_not_fail_queued_jobs(tmp_path: Path) -> None: + custom = _custom_dir(tmp_path) + store = SqliteStore(tmp_path / "app_data", assets_dir=custom) + uploaded = store.ingest_upload(str(_png(tmp_path / "start.png"))) + job = store.insert_generation( + "image-to-video", _spec(inputs={"startFrame": {"assetId": uploaded.id}}) + ) + (custom / ASSETS_MARKER_FILENAME).unlink() # the drive is gone + + assert store.claim_next_queued() is None + + (custom / ASSETS_MARKER_FILENAME).write_text("") + claimed = store.claim_next_queued() + assert claimed is not None and claimed.id == job.id + + +def test_ingest_into_a_missing_custom_folder_is_unavailable(tmp_path: Path) -> None: + custom = _custom_dir(tmp_path) + store = SqliteStore(tmp_path / "app_data", assets_dir=custom) + (custom / ASSETS_MARKER_FILENAME).unlink() + + with pytest.raises(UnavailableError): + store.ingest_upload(str(_png(tmp_path / "cat.png"))) + + +def test_in_flight_folder_follows_the_custom_assets_folder(tmp_path: Path) -> None: + from runtime_config.assets_layout import in_flight_folder + + custom = tmp_path / "custom" + assert in_flight_folder(tmp_path / "app_data", custom) == custom / ".in-flight" + assert in_flight_folder(tmp_path / "app_data") == tmp_path / "app_data" / "assets" / ".in-flight" + + +def test_reference_sheet_does_not_create_a_gone_assets_dir(tmp_path: Path) -> None: + gone = tmp_path / "unplugged" + + with pytest.raises(FileNotFoundError): + ensure_reference_sheet([], 64, 64, in_flight_dir=gone / ".in-flight") + + assert not gone.exists() diff --git a/backend/tests/test_text_to_image.py b/backend/tests/test_text_to_image.py new file mode 100644 index 000000000..d330ebb48 --- /dev/null +++ b/backend/tests/test_text_to_image.py @@ -0,0 +1,413 @@ +"""Queued text-to-image: provider resolution at create, execution, prompt rewrite, cancel.""" + +from __future__ import annotations + +import io +import time +from pathlib import Path + +import pytest +from PIL import Image + +from services.zit_api_client.zit_api_client import ZitImageBlockedError +from services.zit_api_client.zit_api_client_impl import ZitAPIClientImpl +from tests.fakes import FakeResponse +from tests.fakes.services import FakeHTTPClient +from tests.http_error_assertions import assert_http_error + +_CREATE = "/api/generations/text-to-image" + + +def _png_bytes() -> bytes: + buffer = io.BytesIO() + Image.new("RGB", (16, 16), color=(10, 20, 30)).save(buffer, format="PNG") + return buffer.getvalue() + + +def _create(client, **params: object): + return client.post(_CREATE, json={"params": {"prompt": "a red fox", **params}}) + + +def _await_status(client, generation_id: str, *statuses: str) -> dict: + deadline = time.monotonic() + 5 + while True: + body = client.get(f"/api/generations/{generation_id}").json() + if body["status"] in statuses: + return body + assert time.monotonic() < deadline, body["status"] + time.sleep(0.02) + + +def _use_fal(test_state, fake_services) -> None: + test_state.state.app_settings.fal_api_key = "fal-key" + fake_services.zit_api_client.text_to_image_result = _png_bytes() + + +def _enable_enhancer(test_state, create_fake_model_files, fake_services) -> None: + create_fake_model_files(include_prompt_enhancer=True) + test_state.state.app_settings.explore_auto_enhance_prompts = True + fake_services.prompt_enhancer_pipeline.enhanced_prompt = "a richly detailed red fox" + + +def _fal_prompt(fake_services) -> str: + return fake_services.zit_api_client.text_to_image_calls[-1]["prompt"] + + +def _fal_expansion(fake_services) -> bool: + return fake_services.zit_api_client.text_to_image_calls[-1]["enable_prompt_expansion"] + + +def _use_gemini(test_state, reply: str | None) -> None: + settings = test_state.state.app_settings + settings.prompt_enhancer_provider_preference = "api" + settings.gemini_api_key = "gemini-key" + if reply is not None: + test_state.http.queue( + "post", + FakeResponse( + status_code=200, + json_payload={"candidates": [{"content": {"parts": [{"text": reply}]}}]}, + ), + ) + + +def test_fal_without_a_key_is_refused_and_nothing_is_queued(client) -> None: + response = _create(client, provider="fal") + + assert_http_error( + response, + status_code=422, + code="FAL_API_KEY_NOT_CONFIGURED", + message="Add a fal API key.", + ) + queue = client.get("/api/generation-queue").json() + assert queue["queued"] == [] and queue["active"] == [] + + +def test_retry_keeps_the_stored_provider_after_the_setting_flips( + client, test_state, fake_services +) -> None: + _use_fal(test_state, fake_services) + test_state.state.app_settings.user_prefers_fal_api_image_generations = True + fake_services.zit_api_client.raise_on_text_to_image = RuntimeError("provider down") + + created = _create(client).json() + assert created["spec"]["params"]["provider"] == "fal" + _await_status(client, created["id"], "failed") + + test_state.state.app_settings.user_prefers_fal_api_image_generations = False + fake_services.zit_api_client.raise_on_text_to_image = None + assert client.post(f"/api/generations/{created['id']}/retry").status_code == 200 + done = _await_status(client, created["id"], "succeeded", "failed") + + assert done["status"] == "succeeded" + assert len(fake_services.zit_api_client.text_to_image_calls) == 2 + assert fake_services.image_generation_pipeline.generate_calls == [] + + +def test_local_is_refused_when_the_machine_forces_api_generations( + client, test_state +) -> None: + test_state.config.local_generations_mode = "unsupported" + + response = _create(client, provider="local") + + assert_http_error( + response, + status_code=422, + code="LOCAL_GENERATION_UNSUPPORTED", + message="This machine cannot run local generation.", + ) + + +def test_local_without_the_image_model_is_refused_as_not_downloaded(client) -> None: + response = _create(client, provider="local") + + assert_http_error( + response, + status_code=409, + code="IMAGE_MODEL_NOT_DOWNLOADED", + message="Download the Z-Image Turbo model.", + ) + + +@pytest.mark.parametrize( + "body", + [ + {"params": {"prompt": "a fox", "imagePath": "/tmp/source.png"}}, + {"params": {"prompt": "a fox"}, "inputs": {"image": {"assetId": "a1"}}}, + ], + ids=["imagePath-in-params", "image-in-inputs"], +) +def test_create_refuses_any_image_input_so_edit_is_never_reachable(client, body) -> None: + assert client.post(_CREATE, json=body).status_code == 422 + + +def test_fal_job_saves_one_png_as_an_image_asset(client, test_state, fake_services) -> None: + _use_fal(test_state, fake_services) + + created = _create(client, provider="fal", width=768, height=512).json() + done = _await_status(client, created["id"], "succeeded", "failed") + + assert done["status"] == "succeeded" + assert len(done["outputs"]) == 1 + asset = done["outputs"][0] + assert asset["media_kind"] == "image" + assert (asset["metadata"]["metadata"]["width"], asset["metadata"]["metadata"]["height"]) == (16, 16) + assert Path(asset["path"]).read_bytes() == _png_bytes() + call = fake_services.zit_api_client.text_to_image_calls[0] + assert (call["width"], call["height"], call["prompt"]) == (768, 512, "a red fox") + + +def test_a_blocked_fal_result_fails_with_a_clear_code_and_saves_no_asset( + client, test_state, fake_services +) -> None: + _use_fal(test_state, fake_services) + fake_services.zit_api_client.raise_on_text_to_image = ZitImageBlockedError("blocked") + + created = _create(client, provider="fal").json() + done = _await_status(client, created["id"], "failed") + + assert done["error_code"] == "IMAGE_BLOCKED_BY_SAFETY_CHECKER" + assert done["outputs"] == [] + + +def test_fal_client_still_returns_the_placeholder_when_a_caller_does_not_reject_blocked() -> None: + # GenSpace's sync path never rejected a blocked result. Only the queued job does. + http = FakeHTTPClient() + http.queue( + "post", + FakeResponse( + status_code=200, + json_payload={"images": [{"url": "https://fal.test/black.png"}], "has_nsfw_concepts": [True]}, + ), + ) + http.queue("get", FakeResponse(status_code=200, content=b"black-pixels")) + + image = ZitAPIClientImpl(http).generate_text_to_image( + api_key="k", prompt="p", width=512, height=512, seed=1, num_inference_steps=4 + ) + + assert image == b"black-pixels" + + +def test_auto_enhance_rewrites_the_prompt( + client, test_state, fake_services, create_fake_model_files +) -> None: + _use_fal(test_state, fake_services) + _enable_enhancer(test_state, create_fake_model_files, fake_services) + + created = _create(client, provider="fal", prompt="a fox").json() + _await_status(client, created["id"], "succeeded") + + assert fake_services.prompt_enhancer_pipeline.enhance_t2v_calls[0]["prompt"] == "a fox" + assert _fal_prompt(fake_services) == "a richly detailed red fox" + assert _fal_expansion(fake_services) is False + + +@pytest.mark.parametrize( + ("auto_enhance", "provenance"), + [(False, "typed"), (True, "enhanced")], + ids=["auto-enhance-off", "already-enhanced-by-hand"], +) +def test_prompt_is_sent_as_typed_when_no_rewrite_is_wanted( + client, test_state, fake_services, create_fake_model_files, auto_enhance, provenance +) -> None: + _use_fal(test_state, fake_services) + _enable_enhancer(test_state, create_fake_model_files, fake_services) + test_state.state.app_settings.explore_auto_enhance_prompts = auto_enhance + + created = _create(client, provider="fal", promptProvenance=provenance).json() + _await_status(client, created["id"], "succeeded") + + assert fake_services.prompt_enhancer_pipeline.enhance_t2v_calls == [] + assert _fal_prompt(fake_services) == "a red fox" + assert _fal_expansion(fake_services) is False + + +def test_api_only_machine_never_rewrites_on_local_gemma( + client, test_state, fake_services, create_fake_model_files +) -> None: + """status() reports local enhancement as unsupported there, so the job must not load Gemma.""" + test_state.config.local_generations_mode = "unsupported" + _use_fal(test_state, fake_services) + _enable_enhancer(test_state, create_fake_model_files, fake_services) + + created = _create(client, provider="fal").json() + _await_status(client, created["id"], "succeeded") + + assert fake_services.prompt_enhancer_pipeline.enhance_t2v_calls == [] + assert _fal_prompt(fake_services) == "a red fox" + assert _fal_expansion(fake_services) is True + + +def test_a_failed_local_rewrite_falls_back_to_fal_expansion( + client, test_state, fake_services, create_fake_model_files +) -> None: + # Bug caught: a crashed Gemma rewrite sends a bare prompt, so auto-enhance silently does nothing. + _use_fal(test_state, fake_services) + _enable_enhancer(test_state, create_fake_model_files, fake_services) + fake_services.prompt_enhancer_pipeline.raise_on_enhance = RuntimeError("gemma crashed") + + created = _create(client, provider="fal").json() + done = _await_status(client, created["id"], "succeeded", "failed") + + assert done["status"] == "succeeded" + assert _fal_prompt(fake_services) == "a red fox" + assert _fal_expansion(fake_services) is True + + +def test_gemma_rewrites_when_the_gpu_is_idle_and_fal_does_not_expand( + client, test_state, fake_services, create_fake_model_files +) -> None: + # Bug caught: fal expansion is paid for although the GPU could rewrite for free. + _use_fal(test_state, fake_services) + _enable_enhancer(test_state, create_fake_model_files, fake_services) + + created = _create(client, provider="fal").json() + _await_status(client, created["id"], "succeeded") + + assert len(fake_services.prompt_enhancer_pipeline.enhance_t2v_calls) == 1 + assert _fal_prompt(fake_services) == "a richly detailed red fox" + assert _fal_expansion(fake_services) is False + + +def test_fal_expands_when_the_gpu_is_busy_and_gemma_stays_unloaded( + client, test_state, fake_services, create_fake_model_files +) -> None: + # Bug caught: the fal job loads Gemma while a local job owns the GPU. + _use_fal(test_state, fake_services) + _enable_enhancer(test_state, create_fake_model_files, fake_services) + + with test_state.generation.queue_yields(): + created = _create(client, provider="fal").json() + _await_status(client, created["id"], "succeeded") + + assert fake_services.prompt_enhancer_pipeline.enhance_t2v_calls == [] + assert _fal_prompt(fake_services) == "a red fox" + assert _fal_expansion(fake_services) is True + + +def test_gemini_rewrites_when_gemma_is_missing_and_fal_does_not_expand( + client, test_state, fake_services +) -> None: + # Bug caught: a user without Gemma but with Gemini pays for fal expansion. + _use_fal(test_state, fake_services) + test_state.state.app_settings.explore_auto_enhance_prompts = True + _use_gemini(test_state, "a fox, rewritten by gemini") + + created = _create(client, provider="fal").json() + _await_status(client, created["id"], "succeeded") + + assert _fal_prompt(fake_services) == "a fox, rewritten by gemini" + assert _fal_expansion(fake_services) is False + + +def test_a_failed_gemini_rewrite_falls_back_to_fal_expansion(client, test_state, fake_services) -> None: + # Bug caught: a Gemini error fails the whole job instead of falling back. + _use_fal(test_state, fake_services) + test_state.state.app_settings.explore_auto_enhance_prompts = True + _use_gemini(test_state, None) + test_state.http.queue("post", FakeResponse(status_code=500, text="boom")) + + created = _create(client, provider="fal").json() + done = _await_status(client, created["id"], "succeeded", "failed") + + assert done["status"] == "succeeded" + assert _fal_prompt(fake_services) == "a red fox" + assert _fal_expansion(fake_services) is True + + +def test_fal_expands_when_no_enhancer_is_available(client, test_state, fake_services) -> None: + # Bug caught: auto-enhance on with no enhancer sends the bare prompt without expansion. + _use_fal(test_state, fake_services) + test_state.state.app_settings.explore_auto_enhance_prompts = True + + created = _create(client, provider="fal").json() + _await_status(client, created["id"], "succeeded") + + assert _fal_prompt(fake_services) == "a red fox" + assert _fal_expansion(fake_services) is True + + +def test_the_prompt_fal_expanded_replaces_the_typed_prompt_on_the_finished_row( + client, test_state, fake_services +) -> None: + # Bug caught: the user never sees the prompt fal actually used. + _use_fal(test_state, fake_services) + test_state.state.app_settings.explore_auto_enhance_prompts = True + fake_services.zit_api_client.queued_provider_prompt = "a red fox, expanded by fal" + + created = _create(client, provider="fal").json() + done = _await_status(client, created["id"], "succeeded") + + assert done["spec"]["params"]["prompt"] == "a red fox, expanded by fal" + + +def test_cancelling_a_running_local_image_job_ends_cancelled_with_no_asset( + client, test_state, fake_services, create_fake_model_files +) -> None: + create_fake_model_files(include_zit=True) + pipeline = fake_services.image_generation_pipeline + pipeline.inference_steps = 200 + pipeline.step_delay_s = 0.02 + + created = _create(client, provider="local").json() + assert pipeline.entered_inference.wait(timeout=5) + assert client.post(f"/api/generations/{created['id']}/cancel").status_code == 200 + done = _await_status(client, created["id"], "cancelled") + + assert done["outputs"] == [] + assert not list(test_state.config.outputs_dir.glob("*.png")) + + +def test_sides_are_stored_rounded_down_to_the_16_grid(client, test_state, fake_services) -> None: + _use_fal(test_state, fake_services) + + created = _create(client, provider="fal", width=1000, height=777).json() + _await_status(client, created["id"], "succeeded") + + assert (created["spec"]["params"]["width"], created["spec"]["params"]["height"]) == (992, 768) + call = fake_services.zit_api_client.text_to_image_calls[0] + assert (call["width"], call["height"]) == (992, 768) + + +@pytest.mark.parametrize(("width", "height"), [(255, 512), (512, 2049)]) +def test_sides_outside_the_limits_are_refused(client, width, height) -> None: + assert _create(client, provider="local", width=width, height=height).status_code == 422 + + +@pytest.mark.parametrize( + ("setup", "provider", "blocker"), + [ + ("no-fal-key", "fal", "FAL_API_KEY_NOT_CONFIGURED"), + ("unsupported-hardware", "local", "LOCAL_GENERATION_UNSUPPORTED"), + ("model-missing", "local", "IMAGE_MODEL_NOT_DOWNLOADED"), + ], +) +def test_status_reports_the_same_blocker_create_refuses_with( + client, test_state, setup, provider, blocker +) -> None: + if setup == "unsupported-hardware": + test_state.config.local_generations_mode = "unsupported" + + status = client.get("/api/image-generation/status").json() + created = _create(client, provider=provider) + + assert status["falBlocker" if provider == "fal" else "localBlocker"] == blocker + assert created.json()["code"] == blocker + + +def test_status_defaults_to_fal_when_the_machine_cannot_run_locally( + client, test_state +) -> None: + test_state.config.local_generations_mode = "unsupported" + test_state.state.app_settings.fal_api_key = "fal-key" + + status = client.get("/api/image-generation/status").json() + + assert status == { + "defaultProvider": "fal", + "localBlocker": "LOCAL_GENERATION_UNSUPPORTED", + "falBlocker": None, + } diff --git a/backend/tests/test_tiled_ic_lora_pipeline.py b/backend/tests/test_tiled_ic_lora_pipeline.py index c6a0f9b4c..2a18c79ff 100644 --- a/backend/tests/test_tiled_ic_lora_pipeline.py +++ b/backend/tests/test_tiled_ic_lora_pipeline.py @@ -9,7 +9,8 @@ import torch from ltx_core.model.video_vae import TileSizeConfig from ltx_pipelines.ic_lora import ICLoraPipeline -from ltx_pipelines.utils.types import ImageConditioningInput +from ltx_pipelines.utils.media_io import PlaybackSegment +from ltx_pipelines.utils.types import ImageConditioningInput, LoadedImageConditioning from services.ic_lora_pipeline.ic_lora_inference import InferenceResult, encode_result from services.ic_lora_pipeline.tiled_ic_lora_pipeline import ( @@ -64,7 +65,6 @@ def fake_reference(chunk, **kwargs): # noqa: ARG001 return ["reference"] def fake_images(chunk, **kwargs): # noqa: ARG001 - captured["image_color_space"] = kwargs.get("color_space") return ["image"] monkeypatch.setattr( @@ -101,7 +101,6 @@ def fake_images(chunk, **kwargs): # noqa: ARG001 assert captured["temporal"] == 2 assert captured["strength"] == 0.7 assert captured["color_space"] is color_space - assert captured["image_color_space"] is color_space # Audio-only chunks carry no video, so nothing is encoded. assert make(SimpleNamespace(video=None, layout=SimpleNamespace(pixel_frames=0))) == [] @@ -125,7 +124,12 @@ def fake_parent(self, ctx, stage_config, frame_sources): # noqa: ARG001 assert seen["stage_config"] is stage_config -def _still_ctx(*images: ImageConditioningInput) -> SimpleNamespace: +def _loaded(path: str, frame_idx: int) -> LoadedImageConditioning: + binding = ImageConditioningInput.at(path, frame_idx, 1.0).binding + return LoadedImageConditioning(still=path, strength=1.0, binding=binding) # type: ignore[arg-type] + + +def _still_ctx(*images: LoadedImageConditioning) -> SimpleNamespace: return SimpleNamespace( images=list(images), num_frames=121, @@ -164,10 +168,10 @@ def fake_stills(**kwargs): "ltx_pipelines.chunks.conditionings.reference_video_conditionings_for_chunk", fake_reference ) monkeypatch.setattr( - "services.ic_lora_pipeline.tiled_ic_lora_pipeline.combined_image_conditionings", fake_stills + "services.ic_lora_pipeline.tiled_ic_lora_pipeline.image_conditionings", fake_stills ) - first_frame = ImageConditioningInput("first.png", 0, 1.0) - still = ImageConditioningInput("look.png", -1, 1.0) + first_frame = _loaded("first.png", 0) + still = _loaded("look.png", -1) chunk = SimpleNamespace( video=torch.zeros(1, 4, 2, 16, 24), layout=SimpleNamespace(pixel_frames=9), @@ -184,14 +188,14 @@ def fake_stills(**kwargs): def test_still_at_another_negative_index_is_rejected() -> None: - ctx = _still_ctx(ImageConditioningInput("look.png", -2, 1.0)) + ctx = _still_ctx(_loaded("look.png", -2)) with pytest.raises(ValueError, match="frame_idx -1"): _still_pipeline()._video_conditionings(ctx, SimpleNamespace(apply_ic_lora=True), {}) def test_still_with_a_reference_downscale_is_rejected() -> None: - ctx = _still_ctx(ImageConditioningInput("look.png", -1, 1.0)) + ctx = _still_ctx(_loaded("look.png", -1)) with pytest.raises(ValueError, match="reference_downscale_factor 1"): _still_pipeline(downscale=2)._video_conditionings(ctx, SimpleNamespace(apply_ic_lora=True), {}) @@ -199,7 +203,7 @@ def test_still_with_a_reference_downscale_is_rejected() -> None: def test_stage_without_ic_lora_rejects_a_negative_frame_still() -> None: """The upstream closure refuses a negative index, so a still never reaches a plain stage.""" - ctx = _still_ctx(ImageConditioningInput("look.png", -1, 1.0)) + ctx = _still_ctx(_loaded("look.png", -1)) with pytest.raises(ValueError, match="outside the planned stitched range"): _still_pipeline()._video_conditionings(ctx, SimpleNamespace(apply_ic_lora=False), {}) @@ -215,14 +219,15 @@ def windows(): finally: state["closed"] = True - def failing_encode(*, video, **kwargs): # noqa: ARG001 - next(iter(video)) + def failing_encode(segments, **kwargs): # noqa: ARG001 + next(iter(segments)) raise RuntimeError("encoder died") - monkeypatch.setattr("ltx_pipelines.utils.media_io.encode_video", failing_encode) + monkeypatch.setattr("ltx_pipelines.utils.media_io.encode_media_segments", failing_encode) video = windows() + segments = (PlaybackSegment(video=chunk, audio=None) for chunk in video) result = InferenceResult( - video=video, audio=None, num_frames=18, tiling_config=None, streams=(video,) + segments=segments, num_frames=18, tiling_config=None, streams=(segments, video) ) with pytest.raises(RuntimeError, match="encoder died"): diff --git a/backend/tests/test_ui_preferences.py b/backend/tests/test_ui_preferences.py new file mode 100644 index 000000000..7ad5e741c --- /dev/null +++ b/backend/tests/test_ui_preferences.py @@ -0,0 +1,20 @@ +"""GET /api/ui-preferences: the setting that shows the Advanced section reaches the phone.""" + +from __future__ import annotations + +from starlette.testclient import TestClient + +from remote.app import create_remote_app + +_AUTH = {"Authorization": "Bearer pair-token"} + + +def test_remote_reads_the_advanced_controls_setting_the_desktop_saved(client: TestClient, test_state) -> None: + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as remote: + assert remote.get("/api/ui-preferences").status_code == 401 + assert remote.get("/api/ui-preferences", headers=_AUTH).json() == {"advancedControls": False} + + assert client.post("/api/settings", json={"advancedControls": True}).status_code == 200 + + assert remote.get("/api/ui-preferences", headers=_AUTH).json() == {"advancedControls": True} diff --git a/backend/tests/test_url_downloader.py b/backend/tests/test_url_downloader.py new file mode 100644 index 000000000..2bbfa526a --- /dev/null +++ b/backend/tests/test_url_downloader.py @@ -0,0 +1,147 @@ +"""The real URL downloader, run against a fake HTTP transport. + +The fake transport replaces the network only. Redirect handling, header building, the size cap +and the truncation check are the real code in ``UrlDownloaderImpl``. +""" + +from __future__ import annotations + +import io +from collections.abc import Mapping +from pathlib import Path +from typing import Any + +import pytest +import requests +from requests.adapters import BaseAdapter + +from runtime_config.custom_lora_urls import HuggingFaceRepo +from services.url_downloader import UrlDownloadError +from services.url_downloader.public_address_adapter import public_addresses +from services.url_downloader.url_downloader_impl import _MAX_CARD_BYTES, UrlDownloaderImpl, public_only_session + +_HF_FILE = "https://huggingface.co/acme/dolly/resolve/main/dolly.safetensors" +_CDN_FILE = "https://cdn.example.com/signed/dolly.safetensors" +_MAX_BYTES = 1024 + + +class _FakeTransport(BaseAdapter): + """Answers each URL with a canned response and keeps every request it was sent.""" + + def __init__(self, routes: Mapping[str, tuple[int, Mapping[str, str], bytes]]) -> None: + super().__init__() + self._routes = routes + self.sent: list[requests.PreparedRequest] = [] + + def send(self, request: requests.PreparedRequest, *args: Any, **kwargs: Any) -> requests.Response: + del args, kwargs + self.sent.append(request) + status, headers, body = self._routes[str(request.url)] + response = requests.Response() + response.status_code = status + response.headers.update(headers) + response.url = str(request.url) + response.request = request + response.raw = io.BytesIO(body) + return response + + def close(self) -> None: + return None + + +def _downloader(routes: Mapping[str, tuple[int, Mapping[str, str], bytes]]) -> tuple[UrlDownloaderImpl, _FakeTransport]: + transport = _FakeTransport(routes) + + def session() -> requests.Session: + made = requests.Session() + made.mount("https://", transport) + return made + + return UrlDownloaderImpl(session), transport + + +def _download(downloader: UrlDownloaderImpl, url: str, dest: Path, *, hf_token: str | None = "hf-secret") -> None: + downloader.download(url, dest, hf_token=hf_token, max_bytes=_MAX_BYTES) + + +def test_hugging_face_token_is_not_sent_to_the_redirect_target(tmp_path: Path) -> None: + downloader, transport = _downloader( + { + _HF_FILE: (302, {"Location": _CDN_FILE}, b""), + _CDN_FILE: (200, {"Content-Length": "4"}, b"data"), + } + ) + + _download(downloader, _HF_FILE, tmp_path / "out.bin") + + first, second = transport.sent + assert first.headers["Authorization"] == "Bearer hf-secret" + assert "Authorization" not in second.headers + assert (tmp_path / "out.bin").read_bytes() == b"data" + + +def test_a_redirect_to_a_private_host_is_refused_before_a_request_is_sent(tmp_path: Path) -> None: + downloader, transport = _downloader({_HF_FILE: (302, {"Location": "https://10.0.0.5/x.safetensors"}, b"")}) + + with pytest.raises(UrlDownloadError, match="private network"): + _download(downloader, _HF_FILE, tmp_path / "out.bin") + + assert [str(request.url) for request in transport.sent] == [_HF_FILE] + + +def test_a_download_over_the_size_cap_is_refused_with_and_without_a_length_header(tmp_path: Path) -> None: + announced, _ = _downloader({_CDN_FILE: (200, {"Content-Length": str(_MAX_BYTES + 1)}, b"x")}) + unannounced, _ = _downloader({_CDN_FILE: (200, {}, b"x" * (_MAX_BYTES + 1))}) + + for downloader in (announced, unannounced): + with pytest.raises(UrlDownloadError, match="too large"): + _download(downloader, _CDN_FILE, tmp_path / "out.bin") + + +def test_a_download_shorter_than_its_length_header_fails_as_interrupted(tmp_path: Path) -> None: + downloader, _ = _downloader({_CDN_FILE: (200, {"Content-Length": "100"}, b"x" * 10)}) + + with pytest.raises(UrlDownloadError, match="interrupted"): + _download(downloader, _CDN_FILE, tmp_path / "out.bin") + + +def test_a_moved_hugging_face_repo_tells_the_user_to_copy_the_new_link() -> None: + api_url = "https://huggingface.co/api/models/acme/old-name/revision/main" + downloader, _ = _downloader({api_url: (301, {"Location": "https://huggingface.co/api/models/acme/new-name"}, b"")}) + + with pytest.raises(UrlDownloadError, match="Copy the new link"): + downloader.list_hugging_face_files(HuggingFaceRepo("acme/old-name"), hf_token=None) + + +@pytest.mark.parametrize("host", ["localhost", "127.0.0.1"]) +def test_the_connect_time_check_refuses_a_loopback_address(host: str) -> None: + with pytest.raises(UrlDownloadError, match="private network"): + public_addresses(host, 443) + + +def test_the_default_session_ignores_a_system_proxy_that_would_hide_the_address( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setenv("HTTPS_PROXY", "http://proxy.example.com:3128") + url = "https://cdn.example.com/lora.safetensors" + + assert requests.Session().merge_environment_settings(url, {}, None, None, None)["proxies"] + assert public_only_session().merge_environment_settings(url, {}, None, None, None)["proxies"] == {} + + +def test_the_default_session_refuses_a_private_address_before_it_connects() -> None: + # Without the address check this request would try to connect to this computer instead. + with public_only_session() as session, pytest.raises(UrlDownloadError, match="private network"): + session.get("https://localhost/lora.safetensors", timeout=2) + + +_CARD_URL = "https://huggingface.co/acme/dolly/raw/main/README.md" + + +def test_a_missing_readme_gives_an_empty_card_and_an_oversize_one_is_cut_at_the_cap() -> None: + repo = HuggingFaceRepo(repo_id="acme/dolly") + missing, _ = _downloader({_CARD_URL: (404, {}, b"")}) + huge, _ = _downloader({_CARD_URL: (200, {}, b"a" * (_MAX_CARD_BYTES * 2))}) + + assert missing.fetch_hugging_face_card(repo, hf_token=None) == "" + assert len(huge.fetch_hugging_face_card(repo, hf_token=None)) == _MAX_CARD_BYTES diff --git a/backend/tests/test_video_job_budget.py b/backend/tests/test_video_job_budget.py index 9b5f04b2d..04421171a 100644 --- a/backend/tests/test_video_job_budget.py +++ b/backend/tests/test_video_job_budget.py @@ -2,6 +2,9 @@ from __future__ import annotations +from dataclasses import replace +from typing import Any + from api_types import ( REFERENCE_STILL_FRAME_IDX, DownloadSpec, @@ -18,9 +21,8 @@ from pytest import approx from runtime_config.ic_lora_chunking import IC_LORA_CHUNK_PIXEL_FRAMES from runtime_config.ic_lora_job_budget import ( - MAC_TWO_STAGE_UNMEASURED_MESSAGE, REFINE_DECODE_FLOOR_MESSAGE, - TWO_STAGE_OVER_MEASURED_MESSAGE, + IcLoraDurationOutcome, IcLoraJobLoad, IcLoraJobReject, catalog_output_fps, @@ -32,6 +34,22 @@ two_stage_exceeds_priced, with_budgeted_duration_controls, ) +from runtime_config.budget_admission import ( + Admission, + Admitted, + Refused, + budget_readout_for_reject, + compared_available_gib, + is_tight_fit, + load_headroom_gib, + reject_over_gib, + reject_over_ram_gb, + reject_risk_tier, + reject_shortfall_kind, + risk_for_reject, + unmeasured_refusal_message, +) +from runtime_config.budget_decision import IcLoraJobDecision, VideoJobDecision from runtime_config.ic_lora_local_envelope import effective_denoise_stage1, ic_lora_output_canvas from runtime_config.ltx_capabilities import local_caps, pixels_for from runtime_config.model_download_specs import get_ltx_model_spec @@ -46,25 +64,22 @@ HardwareProfile, LocalJobFilter, MemoryBudget, + FastDurationOutcome, VideoJobLoad, VideoJobReject, advertised_fast_durations, + _decide_fast_pass, # pyright: ignore[reportPrivateUsage] + _mac_edit_stream_required_gib, # pyright: ignore[reportPrivateUsage] budget_route, - compared_available_gib, decide_edit_job, decide_video_job, estimated_giB, fits, - load_headroom_gib, - load_risk_tier, + mac_disk_stream_host_gib, max_edit_frames_that_load, memory_gb_for_job, + price_alternative_pass, reject_message_and_code, - reject_over_gib, - reject_over_ram_gb, - reject_risk_tier, - reject_shortfall_kind, - risk_for_reject, video_tokens, ) from services.retake_pipeline.window import ( @@ -74,7 +89,43 @@ ) _GIB = 1024**3 + + +def _priced_video_job(*args: Any, **kwargs: Any) -> VideoJobDecision: + """The mode-blind verdict: these tests pin pricing, not admission.""" + return decide_video_job(*args, **kwargs).priced.decision + + +def _priced_edit_job(*args: Any, **kwargs: Any) -> VideoJobDecision: + return decide_edit_job(*args, **kwargs).priced.decision + + +def _priced_ic_lora_job(*args: Any, **kwargs: Any) -> IcLoraJobDecision: + return decide_ic_lora_job(*args, **kwargs).priced.decision + + +def _refused_reasons(outcome: FastDurationOutcome | IcLoraDurationOutcome) -> dict[int, str]: + return {seconds: refused.reject.reason for seconds, refused in outcome.refused.items()} + + +def _untested_basis(admission: Admission) -> str | None: + """The basis of an untested refusal with priced figures, else None.""" + if not isinstance(admission, Refused) or admission.reject.reason != "unmeasured_cell": + return None + reject = admission.reject + assert isinstance(reject, VideoJobReject) + assert reject.stream_gib > 0 + return reject.unmeasured_basis _FAST_2_5_MODEL_ID = "ltx-2.5-22b-distilled" +_MAC_HOST_GIB = mac_disk_stream_host_gib(_FAST_2_5_MODEL_ID) + + +def _cap(cap_gib: float) -> float: + """The MPS pool that admits what a measured allocator cap admitted. + + Caps bound MPS memory only; the loader's host buffers ride on top of them. + """ + return cap_gib + _MAC_HOST_GIB _WINDOWS_2_3_MODEL_ID = "ltx-2.3-22b-distilled-1.1" @@ -109,7 +160,7 @@ def test_fits_31gb_5s_540p_full_and_20s_not_full() -> None: def test_decide_31gb_5s_540p_full() -> None: w, h = _source_dim_stage1(1024, 576) - decision = decide_ic_lora_job( + decision = _priced_ic_lora_job( w, h, compute_num_frames(5, 24), stage_mode=IcLoraStageMode.SINGLE_STAGE, job_filter=_job_filter(memory_gb=31, process_mode="full_models_loading"), @@ -121,7 +172,7 @@ def test_decide_31gb_5s_540p_full() -> None: def test_decide_31gb_8s_and_10s_540p_stream() -> None: w, h = _source_dim_stage1(1024, 576) for seconds in (8, 10): - decision = decide_ic_lora_job( + decision = _priced_ic_lora_job( w, h, compute_num_frames(seconds, 24), stage_mode=IcLoraStageMode.SINGLE_STAGE, job_filter=_job_filter(memory_gb=31, process_mode="full_models_loading"), @@ -133,12 +184,12 @@ def test_decide_31gb_8s_and_10s_540p_stream() -> None: def test_decide_chunked_1080p_prices_one_window() -> None: w, h = _source_dim_stage1(1920, 1080) frames = compute_num_frames(8, 24) - chunked = decide_ic_lora_job( + chunked = _priced_ic_lora_job( w, h, frames, job_filter=_job_filter(memory_gb=31, process_mode="full_models_loading"), stage_mode=IcLoraStageMode.SINGLE_STAGE ) assert isinstance(chunked, IcLoraJobLoad) assert chunked.mode == "streaming_models_loading" - window = decide_ic_lora_job( + window = _priced_ic_lora_job( w, h, 97, job_filter=_job_filter(memory_gb=31, process_mode="full_models_loading"), stage_mode=IcLoraStageMode.SINGLE_STAGE ) assert isinstance(window, IcLoraJobLoad) @@ -146,7 +197,7 @@ def test_decide_chunked_1080p_prices_one_window() -> None: def test_decide_stage_2_ic_lora_1080p_chunks_and_fits() -> None: - decision = decide_ic_lora_job( + decision = _priced_ic_lora_job( 960, 544, compute_num_frames(9, 24), @@ -160,7 +211,7 @@ def test_decide_stage_2_ic_lora_1080p_chunks_and_fits() -> None: def test_decide_1080p_single_stage_5s_on_22gb_chunks_and_loads_instead_of_rejecting() -> None: # Whole clip: 2 x 16 x 2025 = 64800 tokens, stream estimate 23.5 GiB, over 22. # One 97-frame window: 2 x 13 x 2025 = 52650 tokens, stream estimate 19.7 GiB. - decision = decide_ic_lora_job( + decision = _priced_ic_lora_job( 1920, 1080, compute_num_frames(5, 24), job_filter=_job_filter(memory_gb=22, process_mode="full_models_loading"), stage_mode=IcLoraStageMode.SINGLE_STAGE, ) @@ -173,7 +224,7 @@ def test_decide_1080p_single_stage_5s_on_22gb_chunks_and_loads_instead_of_reject def test_decide_off_grid_123_frames_chunks_like_121_frames() -> None: # Both counts are 16 latent frames, so both need the same window on a 22 GB card. def window(frames: int) -> int | None: - decision = decide_ic_lora_job( + decision = _priced_ic_lora_job( 1920, 1088, frames, job_filter=_job_filter(memory_gb=22, process_mode="full_models_loading"), stage_mode=IcLoraStageMode.SINGLE_STAGE, ) @@ -197,7 +248,7 @@ def test_decide_a_longer_clip_is_never_accepted_after_a_shorter_clip_is_rejected for width, height, mode, memory_gb in cases: accepted = [ isinstance( - decide_ic_lora_job( + _priced_ic_lora_job( width, height, compute_num_frames(seconds, 24), job_filter=_job_filter(memory_gb=memory_gb, process_mode="full_models_loading"), stage_mode=mode, @@ -217,10 +268,10 @@ def test_decide_does_not_chunk_two_stage_or_small_jobs() -> None: (960, 512, IcLoraStageMode.STAGE_1_LORA), (1024, 576, IcLoraStageMode.SINGLE_STAGE), ): - priced = decide_ic_lora_job( + priced = _priced_ic_lora_job( width, height, frames, job_filter=_job_filter(memory_gb=31, process_mode="full_models_loading"), stage_mode=mode ) - window = decide_ic_lora_job( + window = _priced_ic_lora_job( width, height, 97, job_filter=_job_filter(memory_gb=31, process_mode="full_models_loading"), stage_mode=mode ) assert priced.seq > window.seq @@ -228,7 +279,7 @@ def test_decide_does_not_chunk_two_stage_or_small_jobs() -> None: def test_decide_31gb_20s_540p_streams() -> None: w, h = _source_dim_stage1(1024, 576) - decision = decide_ic_lora_job( + decision = _priced_ic_lora_job( w, h, compute_num_frames(20, 24), stage_mode=IcLoraStageMode.SINGLE_STAGE, job_filter=_job_filter(memory_gb=31, process_mode="full_models_loading"), @@ -239,7 +290,7 @@ def test_decide_31gb_20s_540p_streams() -> None: def test_decide_31gb_5s_2160p_spatial_reject() -> None: w, h = _source_dim_stage1(3840, 2160) - decision = decide_ic_lora_job( + decision = _priced_ic_lora_job( w, h, compute_num_frames(5, 24), stage_mode=IcLoraStageMode.SINGLE_STAGE, job_filter=_job_filter(memory_gb=31, process_mode="full_models_loading"), @@ -251,7 +302,7 @@ def test_decide_31gb_5s_2160p_spatial_reject() -> None: def test_decide_31gb_5s_2160p_two_stage_stage_1_lora_is_a_spatial_reject() -> None: # A 3840x2160 source gives a 3840x2048 canvas, so stage 1 is 1920x1024. That is inside # the 1920x1088 cell, but stage 2 runs at 3840x2048 and is over it. - decision = decide_ic_lora_job( + decision = _priced_ic_lora_job( 1920, 1024, compute_num_frames(5, 24), job_filter=_job_filter(memory_gb=32, process_mode="full_models_loading"), stage_mode=IcLoraStageMode.STAGE_1_LORA, ) @@ -262,7 +313,7 @@ def test_decide_31gb_5s_2160p_two_stage_stage_1_lora_is_a_spatial_reject() -> No def test_stage_1_lora_prices_the_stage_2_canvas_when_it_is_heavier_than_stage_1() -> None: # Stage 1 960x544, 121 frames: 16 latent frames of 17x30 cells, times 2 for the # reference = 16320 tokens. Stage 2 at 1920x1088 has no reference: 16 x 34 x 60 = 32640. - decision = decide_ic_lora_job( + decision = _priced_ic_lora_job( 960, 544, 121, job_filter=_job_filter(memory_gb=32, process_mode="full_models_loading"), stage_mode=IcLoraStageMode.STAGE_1_LORA, ) @@ -275,7 +326,7 @@ def test_a_reference_still_adds_one_latent_frame_of_tokens_to_the_stage_2_lora_p # 121 frames are 16 latent frames, doubled for the reference: 2 x 16 x 880 = 28160. # One still adds one latent frame of the canvas: 880. def price(stills: int) -> float: - decision = decide_ic_lora_job( + decision = _priced_ic_lora_job( 640, 352, 121, job_filter=_job_filter(memory_gb=32, process_mode="full_models_loading"), stage_mode=IcLoraStageMode.STAGE_2_LORA, stills=stills, ) @@ -288,7 +339,7 @@ def price(stills: int) -> float: def test_decide_ic_lora_unsupported_beats_spatial() -> None: w, h = _source_dim_stage1(1280, 720) - decision = decide_ic_lora_job( + decision = _priced_ic_lora_job( w, h, compute_num_frames(5, 24), stage_mode=IcLoraStageMode.SINGLE_STAGE, job_filter=_job_filter(memory_gb=31, process_mode="unsupported"), @@ -299,7 +350,7 @@ def test_decide_ic_lora_unsupported_beats_spatial() -> None: def test_decide_ic_lora_unsupported_process_rejects() -> None: w, h = _source_dim_stage1(1024, 576) - decision = decide_ic_lora_job( + decision = _priced_ic_lora_job( w, h, compute_num_frames(5, 24), stage_mode=IcLoraStageMode.SINGLE_STAGE, job_filter=_job_filter(memory_gb=31, process_mode="unsupported"), @@ -310,14 +361,14 @@ def test_decide_ic_lora_unsupported_process_rejects() -> None: def test_decide_24gb_stream_process_never_full() -> None: w, h = _source_dim_stage1(1024, 576) - five = decide_ic_lora_job( + five = _priced_ic_lora_job( w, h, compute_num_frames(5, 24), stage_mode=IcLoraStageMode.SINGLE_STAGE, job_filter=_job_filter(memory_gb=24, process_mode="streaming_models_loading"), ) - twenty = decide_ic_lora_job( + twenty = _priced_ic_lora_job( w, h, compute_num_frames(20, 24), @@ -333,14 +384,14 @@ def test_decide_24gb_stream_process_never_full() -> None: def test_windows_tall_20s_never_asks_below_the_line_over_i1() -> None: """Portrait 576x960 @ 20s (65,880 seq): the line asks 25.93 over I1's native 24.81.""" frames = compute_num_frames(20, 24) - short = decide_ic_lora_job( + short = _priced_ic_lora_job( 576, 960, frames, stage_mode=IcLoraStageMode.SINGLE_STAGE, job_filter=_windows_measured_filter(31, 64, free_gib=25.93), ) assert isinstance(short, VideoJobReject) assert short.reason == "stream_over" - fits = decide_ic_lora_job( + fits = _priced_ic_lora_job( 576, 960, frames, stage_mode=IcLoraStageMode.SINGLE_STAGE, job_filter=_windows_measured_filter(31, 64, free_gib=25.94), @@ -352,14 +403,14 @@ def test_windows_tall_20s_never_asks_below_the_line_over_i1() -> None: def test_windows_tall_10s_never_asks_below_the_line_over_i2() -> None: """Portrait 576x960 @ 10s (33,480 seq): the line asks 16.38 over I2's native 15.36.""" frames = compute_num_frames(10, 24) - short = decide_ic_lora_job( + short = _priced_ic_lora_job( 576, 960, frames, stage_mode=IcLoraStageMode.SINGLE_STAGE, job_filter=_windows_measured_filter(31, 64, free_gib=16.37), ) assert isinstance(short, VideoJobReject) assert short.reason == "stream_over" - fits = decide_ic_lora_job( + fits = _priced_ic_lora_job( 576, 960, frames, stage_mode=IcLoraStageMode.SINGLE_STAGE, job_filter=_windows_measured_filter(31, 64, free_gib=16.38), @@ -373,7 +424,7 @@ def test_two_stage_job_is_not_priced_on_the_single_stage_line() -> None: free must refuse the two-stage job.""" frames = compute_num_frames(10, 24) assert frames == 241 - refused = decide_ic_lora_job( + refused = _priced_ic_lora_job( 960, 512, frames, stage_mode=IcLoraStageMode.STAGE_1_LORA, job_filter=_windows_measured_filter(31, 64, free_gib=11.0), @@ -386,7 +437,7 @@ def test_single_stage_job_is_not_priced_on_the_two_stage_line() -> None: """960x512 x 241: single-stage asks 15.28 (2x stage-1 tokens) and must load at 15.29 free — on the two-stage count (4x) it would ask 24.06 and refuse.""" frames = compute_num_frames(10, 24) - loads = decide_ic_lora_job( + loads = _priced_ic_lora_job( 960, 512, frames, stage_mode=IcLoraStageMode.SINGLE_STAGE, job_filter=_windows_measured_filter(31, 64, free_gib=15.29), @@ -399,14 +450,14 @@ def test_stage_1_lora_is_priced_on_four_times_its_stage_1_tokens() -> None: """960x512 x 241: stage 2 runs at 1920x1024 without the reference, 59,520 seq, asking 24.06. On the single-stage count (2x) it would ask 15.28 and admit.""" frames = compute_num_frames(10, 24) - short = decide_ic_lora_job( + short = _priced_ic_lora_job( 960, 512, frames, stage_mode=IcLoraStageMode.STAGE_1_LORA, job_filter=_windows_measured_filter(31, 64, free_gib=24.05), ) assert isinstance(short, VideoJobReject) assert short.reason == "stream_over" - fits = decide_ic_lora_job( + fits = _priced_ic_lora_job( 960, 512, frames, stage_mode=IcLoraStageMode.STAGE_1_LORA, job_filter=_windows_measured_filter(31, 64, free_gib=24.06), @@ -428,7 +479,7 @@ def test_catalog_preview_prices_two_stage_when_default_settings_say_two_stage() (5, "stream_over"), (8, "stream_over"), (10, "stream_over"), - (20, "two_stage_over_measured"), + (20, "stream_over"), ] single_stage = with_budgeted_duration_controls( _catalog_item_two_stage().model_copy( @@ -447,14 +498,14 @@ def test_catalog_preview_prices_two_stage_when_default_settings_say_two_stage() def test_two_stage_t1_cell_never_asks_below_its_native_peak() -> None: """Two-stage 960x512 @ 5s (30,720 seq): the line asks 15.56 over T1's native 13.65.""" frames = compute_num_frames(5, 24) - short = decide_ic_lora_job( + short = _priced_ic_lora_job( 960, 512, frames, stage_mode=IcLoraStageMode.STAGE_1_LORA, job_filter=_windows_measured_filter(31, 64, free_gib=15.56), ) assert isinstance(short, VideoJobReject) assert short.reason == "stream_over" - fits = decide_ic_lora_job( + fits = _priced_ic_lora_job( 960, 512, frames, stage_mode=IcLoraStageMode.STAGE_1_LORA, job_filter=_windows_measured_filter(31, 64, free_gib=15.57), @@ -468,10 +519,10 @@ def test_two_stage_ask_exceeds_single_stage_ask_by_the_measured_stage_2_delta() stage-2 increment — a too-flat stage-2 slope would collapse them.""" frames = compute_num_frames(5, 24) job_filter = _windows_measured_filter(31, 64, free_gib=31.0) - two = decide_ic_lora_job( + two = _priced_ic_lora_job( 960, 512, frames, stage_mode=IcLoraStageMode.STAGE_1_LORA, job_filter=job_filter ) - one = decide_ic_lora_job( + one = _priced_ic_lora_job( 960, 512, frames, stage_mode=IcLoraStageMode.SINGLE_STAGE, job_filter=job_filter ) assert isinstance(two, IcLoraJobLoad) @@ -483,14 +534,14 @@ def test_two_stage_floor_binds_below_the_crossover() -> None: """640x320 @ 1s (3,200 seq): the unclamped line asks 7.44 — the 8.00 floor must bind, not the bare line.""" frames = compute_num_frames(1, 24) - short = decide_ic_lora_job( + short = _priced_ic_lora_job( 640, 320, frames, stage_mode=IcLoraStageMode.STAGE_1_LORA, job_filter=_windows_measured_filter(31, 64, free_gib=7.99), ) assert isinstance(short, VideoJobReject) assert short.reason == "stream_over" - fits = decide_ic_lora_job( + fits = _priced_ic_lora_job( 640, 320, frames, stage_mode=IcLoraStageMode.STAGE_1_LORA, job_filter=_windows_measured_filter(31, 64, free_gib=8.0), @@ -517,7 +568,7 @@ def test_two_stage_at_the_priced_ceiling_is_offered_not_fenced() -> None: assert outcome.kept == [10] -def test_two_stage_one_token_past_the_priced_ceiling_is_fenced() -> None: +def test_two_stage_one_token_past_the_priced_ceiling_is_untested() -> None: """512x647 x 361 frames is exactly 14,881 tokens — one past the ceiling.""" assert compute_num_frames(15, 24) == 361 assert video_tokens(647, 512, 361) == 14881 @@ -533,7 +584,7 @@ def test_two_stage_one_token_past_the_priced_ceiling_is_fenced() -> None: job_filter=_windows_measured_filter(31, 64, free_gib=31.0), ) assert outcome.kept == [] - assert outcome.rejected == {15: "two_stage_over_measured"} + assert _untested_basis(outcome.refused[15]) == "two_stage_range" def test_two_stage_fence_is_token_based_not_duration_based() -> None: @@ -560,20 +611,20 @@ def test_two_stage_fence_is_token_based_not_duration_based() -> None: stage_mode=IcLoraStageMode.STAGE_1_LORA, job_filter=_windows_measured_filter(31, 64, free_gib=20.89), ) - assert short.rejected == {20: "stream_over"} + assert _refused_reasons(short) == {20: "stream_over"} def test_two_stage_t3_cell_never_asks_below_its_native_peak() -> None: """640x320 @ 5s (12,800 seq) reserved 10.23 natively; the line asks 10.28.""" frames = compute_num_frames(5, 24) - short = decide_ic_lora_job( + short = _priced_ic_lora_job( 640, 320, frames, stage_mode=IcLoraStageMode.STAGE_1_LORA, job_filter=_windows_measured_filter(31, 64, free_gib=10.27), ) assert isinstance(short, VideoJobReject) assert short.reason == "stream_over" - fits = decide_ic_lora_job( + fits = _priced_ic_lora_job( 640, 320, frames, stage_mode=IcLoraStageMode.STAGE_1_LORA, job_filter=_windows_measured_filter(31, 64, free_gib=10.28), @@ -586,7 +637,7 @@ def test_two_stage_idle_10gb_refuses_3200t_cell() -> None: """Same 3,200-token cell asks 10.28 — must refuse on an idle 10 GB card (free 9.9).""" frames = compute_num_frames(5, 24) - decision = decide_ic_lora_job( + decision = _priced_ic_lora_job( 640, 320, frames, stage_mode=IcLoraStageMode.STAGE_1_LORA, job_filter=_windows_measured_filter(10, 64, free_gib=9.9), @@ -598,7 +649,7 @@ def test_two_stage_idle_10gb_refuses_3200t_cell() -> None: def test_two_stage_12gb_still_streams_3200t_cell() -> None: """The refit must not strand 12 GB cards: 10.28 still fits idle 12 GB free.""" frames = compute_num_frames(5, 24) - decision = decide_ic_lora_job( + decision = _priced_ic_lora_job( 640, 320, frames, stage_mode=IcLoraStageMode.STAGE_1_LORA, job_filter=_windows_measured_filter(12, 64, free_gib=11.9), @@ -622,22 +673,23 @@ def test_over_cap_two_stage_refuses_spatial_not_with_the_fence_advice() -> None: job_filter=_windows_measured_filter(31, 64, free_gib=31.0), ) assert outcome.kept == [] - assert outcome.rejected == {20: "spatial"} + assert _refused_reasons(outcome) == {20: "spatial"} def test_two_stage_refusal_message_does_not_claim_a_five_second_rule() -> None: """User-visible wire copy: the refusal must not cite the retired 5s rule.""" message, code = dropped_duration_message_and_code( - IcLoraJobReject( - reason="two_stage_over_measured", + VideoJobReject( + reason="unmeasured_cell", seq=0.0, full_gib=0.0, stream_gib=99.9, + unmeasured_basis="two_stage_range", ), _windows_measured_filter(31, 64, free_gib=12.0), ) assert code == VIDEO_JOB_TOO_LARGE - assert message == TWO_STAGE_OVER_MEASURED_MESSAGE + assert message == unmeasured_refusal_message("two_stage_range") assert "5 second" not in message @@ -645,11 +697,11 @@ def test_spatial_cap_corner_is_the_1080p_output() -> None: """1920x1088 output prices (either way round); one grid step wider refuses.""" job_filter = _windows_measured_filter(31, 64, free_gib=31.0) for width, height in ((1920, 1088), (1088, 1920)): - prices = decide_ic_lora_job( + prices = _priced_ic_lora_job( width, height, 97, stage_mode=IcLoraStageMode.SINGLE_STAGE, job_filter=job_filter ) assert isinstance(prices, IcLoraJobLoad), (width, height) - refuses = decide_ic_lora_job( + refuses = _priced_ic_lora_job( 1952, 1088, 97, stage_mode=IcLoraStageMode.SINGLE_STAGE, job_filter=job_filter ) assert isinstance(refuses, IcLoraJobReject) @@ -674,13 +726,13 @@ def test_mac_growth_ask_covers_the_t3_pass_bottom() -> None: (15.46, 15.96] where the 1.3 intercept asked 15.33 — the refit line asks 15.97, so the measured 15.46 fail must refuse.""" frames = compute_num_frames(10, 24) - short = decide_ic_lora_job( - 576, 960, frames, stage_mode=IcLoraStageMode.SINGLE_STAGE, job_filter=_mac_iclora_filter(15.46) + short = _priced_ic_lora_job( + 576, 960, frames, stage_mode=IcLoraStageMode.SINGLE_STAGE, job_filter=_mac_iclora_filter(_cap(15.46)) ) assert isinstance(short, VideoJobReject) assert short.reason == "stream_over" - fits = decide_ic_lora_job( - 576, 960, frames, stage_mode=IcLoraStageMode.SINGLE_STAGE, job_filter=_mac_iclora_filter(15.97) + fits = _priced_ic_lora_job( + 576, 960, frames, stage_mode=IcLoraStageMode.SINGLE_STAGE, job_filter=_mac_iclora_filter(_cap(15.97)) ) assert isinstance(fits, IcLoraJobLoad) assert fits.mode == "streaming_models_loading" @@ -691,13 +743,13 @@ def test_mac_growth_ask_covers_the_p20v_pass_bottom() -> None: where the T4 line asked 24.85 — the refit asks 25.86, so a 25.85 pool must refuse (a carried 5.486e-4 slope would admit it).""" frames = compute_num_frames(20, 24) - short = decide_ic_lora_job( - 576, 960, frames, stage_mode=IcLoraStageMode.SINGLE_STAGE, job_filter=_mac_iclora_filter(25.85) + short = _priced_ic_lora_job( + 576, 960, frames, stage_mode=IcLoraStageMode.SINGLE_STAGE, job_filter=_mac_iclora_filter(_cap(25.85)) ) assert isinstance(short, VideoJobReject) assert short.reason == "stream_over" - fits = decide_ic_lora_job( - 576, 960, frames, stage_mode=IcLoraStageMode.SINGLE_STAGE, job_filter=_mac_iclora_filter(25.87) + fits = _priced_ic_lora_job( + 576, 960, frames, stage_mode=IcLoraStageMode.SINGLE_STAGE, job_filter=_mac_iclora_filter(_cap(25.87)) ) assert isinstance(fits, IcLoraJobLoad) assert fits.mode == "streaming_models_loading" @@ -708,18 +760,18 @@ def test_mac_ingredients_adder_covers_the_xm1_pass_top() -> None: video line asks 15.97 — pricing the adapter on the line admits a measured-fail pool, so 16.46 must refuse and 16.47 load.""" frames = compute_num_frames(10, 24) - short = decide_ic_lora_job( + short = _priced_ic_lora_job( 576, 960, frames, stage_mode=IcLoraStageMode.SINGLE_STAGE, - job_filter=_mac_iclora_filter(16.46), + job_filter=_mac_iclora_filter(_cap(16.46)), ic_lora_id="ingredients", ) assert isinstance(short, VideoJobReject) assert short.reason == "stream_over" - fits = decide_ic_lora_job( + fits = _priced_ic_lora_job( 576, 960, frames, stage_mode=IcLoraStageMode.SINGLE_STAGE, - job_filter=_mac_iclora_filter(16.47), + job_filter=_mac_iclora_filter(_cap(16.47)), ic_lora_id="ingredients", ) assert isinstance(fits, IcLoraJobLoad) @@ -731,18 +783,18 @@ def test_mac_ingredients_adder_covers_the_p20i_pass_top() -> None: the fitted 25.86 exactly as XM1 — the adder is token-flat, so 26.35 must refuse and 26.36 load (a token-scaled term misses one end).""" frames = compute_num_frames(20, 24) - short = decide_ic_lora_job( + short = _priced_ic_lora_job( 576, 960, frames, stage_mode=IcLoraStageMode.SINGLE_STAGE, - job_filter=_mac_iclora_filter(26.35), + job_filter=_mac_iclora_filter(_cap(26.35)), ic_lora_id="ingredients", ) assert isinstance(short, VideoJobReject) assert short.reason == "stream_over" - fits = decide_ic_lora_job( + fits = _priced_ic_lora_job( 576, 960, frames, stage_mode=IcLoraStageMode.SINGLE_STAGE, - job_filter=_mac_iclora_filter(26.36), + job_filter=_mac_iclora_filter(_cap(26.36)), ic_lora_id="ingredients", ) assert isinstance(fits, IcLoraJobLoad) @@ -755,10 +807,10 @@ def test_mac_image_adder_ignores_non_ingredients_ids() -> None: or size-keyed adder refuses these runnable cells at a 15.97 pool.""" frames = compute_num_frames(10, 24) for ic_lora_id in ("day-to-night", "greenscreen-avatar", None): - decision = decide_ic_lora_job( + decision = _priced_ic_lora_job( 576, 960, frames, stage_mode=IcLoraStageMode.SINGLE_STAGE, - job_filter=_mac_iclora_filter(15.97), + job_filter=_mac_iclora_filter(_cap(15.97)), ic_lora_id=ic_lora_id, ) assert isinstance(decision, IcLoraJobLoad) @@ -796,32 +848,32 @@ def test_mac_ingredients_list_time_matches_generate_in_the_adder_gap() -> None: line only, so it offered 20s that generate (with the +0.50 adder) 422s — the offer must equal the verdict on both sides of the 26.36 edge.""" frames = compute_num_frames(20, 24) - generate_short = decide_ic_lora_job( + generate_short = _priced_ic_lora_job( 576, 960, frames, stage_mode=IcLoraStageMode.SINGLE_STAGE, - job_filter=_mac_iclora_filter(26.0), + job_filter=_mac_iclora_filter(_cap(26.0)), ic_lora_id="ingredients", ) assert isinstance(generate_short, VideoJobReject) listed_short = with_budgeted_duration_controls( _mac_ingredients_list_item(), - job_filter=_mac_iclora_filter(26.0, memory_gb=48), + job_filter=_mac_iclora_filter(_cap(26.0), memory_gb=48), ) short_control = next(c for c in listed_short.controls if c.id == "duration") assert short_control.options == [5, 6, 8, 10] assert short_control.dropped_options is not None assert [(d.value, d.reason) for d in short_control.dropped_options] == [(20, "stream_over")] - generate_fits = decide_ic_lora_job( + generate_fits = _priced_ic_lora_job( 576, 960, frames, stage_mode=IcLoraStageMode.SINGLE_STAGE, - job_filter=_mac_iclora_filter(26.36), + job_filter=_mac_iclora_filter(_cap(26.36)), ic_lora_id="ingredients", ) assert isinstance(generate_fits, IcLoraJobLoad) listed_fits = with_budgeted_duration_controls( _mac_ingredients_list_item(), - job_filter=_mac_iclora_filter(26.36, memory_gb=48), + job_filter=_mac_iclora_filter(_cap(26.36), memory_gb=48), ) fits_control = next(c for c in listed_fits.controls if c.id == "duration") assert fits_control.options == [5, 6, 8, 10, 20] @@ -832,33 +884,33 @@ def test_mac_floor_still_binds_below_the_growth_crossover() -> None: """At 2,304 tokens the refit line asks 7.16 — the 9.84 floor must still govern small cells, not become dead code under the new intercept.""" frames = compute_num_frames(5, 24) - short = decide_ic_lora_job( - 576, 256, frames, stage_mode=IcLoraStageMode.SINGLE_STAGE, job_filter=_mac_iclora_filter(9.83) + short = _priced_ic_lora_job( + 576, 256, frames, stage_mode=IcLoraStageMode.SINGLE_STAGE, job_filter=_mac_iclora_filter(_cap(9.83)) ) assert isinstance(short, VideoJobReject) assert short.reason == "stream_over" - fits = decide_ic_lora_job( - 576, 256, frames, stage_mode=IcLoraStageMode.SINGLE_STAGE, job_filter=_mac_iclora_filter(9.85) + fits = _priced_ic_lora_job( + 576, 256, frames, stage_mode=IcLoraStageMode.SINGLE_STAGE, job_filter=_mac_iclora_filter(_cap(9.85)) ) assert isinstance(fits, IcLoraJobLoad) assert fits.mode == "streaming_models_loading" -def test_mac_two_stage_refuses_unmeasured_on_a_huge_pool() -> None: - """Two-stage shapes past the priced cell refuse with their own reason at any - pool: both layouts at 960x512 here, past the 928x512 canvas fence.""" +def test_mac_two_stage_outside_cell_is_priced_on_the_curve_not_fenced() -> None: + """Two-stage shapes past the measured Mac cell are untested at any pool, but + priced on the two-stage curve: both layouts at 960x512 here, past the + 928x512 cell. A fence returning before the curve refuses with no figures.""" frames = compute_num_frames(5, 24) for mode in (IcLoraStageMode.STAGE_1_LORA, IcLoraStageMode.STAGE_2_LORA): - decision = decide_ic_lora_job( + admission = decide_ic_lora_job( 960, 512, frames, stage_mode=mode, job_filter=_mac_iclora_filter(100) ) - assert isinstance(decision, IcLoraJobReject), mode - assert decision.reason == "mac_two_stage_unmeasured" + assert _untested_basis(admission) == "mac_two_stage_cell", mode -def test_mac_two_stage_composes_under_the_token_ceiling_fence() -> None: - """Mac two-stage past the priced token range keeps the token-ceiling - reason: the platform-blind fence runs first, the Mac fence below it.""" +def test_mac_two_stage_past_the_token_range_names_the_range_not_the_mac_cell() -> None: + """Mac two-stage past the priced token range is tagged with the + platform-blind range first, the Mac cell below it.""" outcome = decide_ic_lora_durations( [5, 10], stage1_width=960, @@ -868,55 +920,31 @@ def test_mac_two_stage_composes_under_the_token_ceiling_fence() -> None: job_filter=_mac_iclora_filter(100), ) assert outcome.kept == [] - assert outcome.rejected == { - 5: "mac_two_stage_unmeasured", - 10: "two_stage_over_measured", - } - assert set(outcome.rejects) == {5, 10} + assert _untested_basis(outcome.refused[5]) == "mac_two_stage_cell" + assert _untested_basis(outcome.refused[10]) == "two_stage_range" -def test_mac_two_stage_refusal_carries_fixed_copy_without_figures() -> None: - """The Mac two-stage drop messages fixed copy (nothing was compared) under VIDEO_JOB_TOO_LARGE.""" - message, code = dropped_duration_message_and_code( - IcLoraJobReject( - reason="mac_two_stage_unmeasured", - seq=0.0, - full_gib=0.0, - stream_gib=99.9, - ), - _mac_iclora_filter(100), - ) - assert (message, code) == (MAC_TWO_STAGE_UNMEASURED_MESSAGE, VIDEO_JOB_TOO_LARGE) - - -def test_mac_layout_to_render_540p_5s_loads_on_16gb_pool() -> None: +def test_mac_layout_to_render_540p_5s_edges() -> None: """PhaseMN-A1-shaped L2R (540p 5s: 448x256 x 121, 1 still) edges (11.5, 12.0] - — refusing it as unmeasured bricks 540p two-stage on 16 GB Macs it fits. + — refusing it as unmeasured bricks 540p two-stage where it fits. The 12.00 refusal must be stream_over: the fence would hide a chord regression.""" frames = compute_num_frames(5, 24) - short = decide_ic_lora_job( + short = _priced_ic_lora_job( 448, 256, frames, stage_mode=IcLoraStageMode.STAGE_2_LORA, - job_filter=_mac_iclora_filter(12.00), + job_filter=_mac_iclora_filter(_cap(12.00)), stills=1, ) assert isinstance(short, VideoJobReject) assert short.reason == "stream_over" - fits = decide_ic_lora_job( + fits = _priced_ic_lora_job( 448, 256, frames, stage_mode=IcLoraStageMode.STAGE_2_LORA, - job_filter=_mac_iclora_filter(12.01), + job_filter=_mac_iclora_filter(_cap(12.01)), stills=1, ) assert isinstance(fits, IcLoraJobLoad) assert fits.mode == "streaming_models_loading" - sixteen = decide_ic_lora_job( - 448, 256, frames, - stage_mode=IcLoraStageMode.STAGE_2_LORA, - job_filter=_mac_iclora_filter(12.50), - stills=1, - ) - assert isinstance(sixteen, IcLoraJobLoad) def test_mac_layout_to_render_540p_10s_edges() -> None: @@ -924,18 +952,18 @@ def test_mac_layout_to_render_540p_10s_edges() -> None: the higher chord — a single-chord price under-asks it by 0.25 onto a pool the 720p chord refuses.""" frames = compute_num_frames(10, 24) - short = decide_ic_lora_job( + short = _priced_ic_lora_job( 448, 256, frames, stage_mode=IcLoraStageMode.STAGE_2_LORA, - job_filter=_mac_iclora_filter(14.75), + job_filter=_mac_iclora_filter(_cap(14.75)), stills=1, ) assert isinstance(short, VideoJobReject) assert short.reason == "stream_over" - fits = decide_ic_lora_job( + fits = _priced_ic_lora_job( 448, 256, frames, stage_mode=IcLoraStageMode.STAGE_2_LORA, - job_filter=_mac_iclora_filter(14.76), + job_filter=_mac_iclora_filter(_cap(14.76)), stills=1, ) assert isinstance(fits, IcLoraJobLoad) @@ -946,26 +974,26 @@ def test_mac_layout_to_render_720p_5s_edges() -> None: """PhaseL2R-P5-shaped L2R (720p 5s: 640x352 x 121, 1 still) asks 15.00 unchunked and retries chunked at 97f (13.67) when the pool sits between 13.67 and 15.00.""" frames = compute_num_frames(5, 24) - short = decide_ic_lora_job( + short = _priced_ic_lora_job( 640, 352, frames, stage_mode=IcLoraStageMode.STAGE_2_LORA, - job_filter=_mac_iclora_filter(13.67), + job_filter=_mac_iclora_filter(_cap(13.67)), stills=1, ) assert isinstance(short, VideoJobReject) assert short.reason == "stream_over" - chunked = decide_ic_lora_job( + chunked = _priced_ic_lora_job( 640, 352, frames, stage_mode=IcLoraStageMode.STAGE_2_LORA, - job_filter=_mac_iclora_filter(14.99), + job_filter=_mac_iclora_filter(_cap(14.99)), stills=1, ) assert isinstance(chunked, IcLoraJobLoad) assert chunked.chunk_pixel_frames == IC_LORA_CHUNK_PIXEL_FRAMES - fits = decide_ic_lora_job( + fits = _priced_ic_lora_job( 640, 352, frames, stage_mode=IcLoraStageMode.STAGE_2_LORA, - job_filter=_mac_iclora_filter(15.00), + job_filter=_mac_iclora_filter(_cap(15.00)), stills=1, ) assert isinstance(fits, IcLoraJobLoad) @@ -978,26 +1006,26 @@ def test_mac_layout_to_render_720p_10s_retries_chunked_on_24gb_pool() -> None: and retries chunked at 97f (13.67) on a 24 GB Mac (~18.7 GiB pool) — suppressing the chunked retry rejects a job that fits in 97f windows.""" frames = compute_num_frames(10, 24) - short = decide_ic_lora_job( + short = _priced_ic_lora_job( 640, 352, frames, stage_mode=IcLoraStageMode.STAGE_2_LORA, - job_filter=_mac_iclora_filter(13.67), + job_filter=_mac_iclora_filter(_cap(13.67)), stills=1, ) assert isinstance(short, VideoJobReject) assert short.reason == "stream_over" - chunked = decide_ic_lora_job( + chunked = _priced_ic_lora_job( 640, 352, frames, stage_mode=IcLoraStageMode.STAGE_2_LORA, - job_filter=_mac_iclora_filter(22.99), + job_filter=_mac_iclora_filter(_cap(22.99)), stills=1, ) assert isinstance(chunked, IcLoraJobLoad) assert chunked.chunk_pixel_frames == IC_LORA_CHUNK_PIXEL_FRAMES - fits = decide_ic_lora_job( + fits = _priced_ic_lora_job( 640, 352, frames, stage_mode=IcLoraStageMode.STAGE_2_LORA, - job_filter=_mac_iclora_filter(23.00), + job_filter=_mac_iclora_filter(_cap(23.00)), stills=1, ) assert isinstance(fits, IcLoraJobLoad) @@ -1009,26 +1037,26 @@ def test_mac_layout_to_render_1080p_5s_edges() -> None: """PhaseL2R-H-shaped L2R (1080p 5s: 928x512 x 121, 1 still) asks 24.76 unchunked and 21.39 when retried chunked at 97f — refusing it strands 32 GB Macs to API.""" frames = compute_num_frames(5, 24) - short = decide_ic_lora_job( + short = _priced_ic_lora_job( 928, 512, frames, stage_mode=IcLoraStageMode.STAGE_2_LORA, - job_filter=_mac_iclora_filter(21.38), + job_filter=_mac_iclora_filter(_cap(21.38)), stills=1, ) assert isinstance(short, VideoJobReject) assert short.reason == "stream_over" - chunked = decide_ic_lora_job( + chunked = _priced_ic_lora_job( 928, 512, frames, stage_mode=IcLoraStageMode.STAGE_2_LORA, - job_filter=_mac_iclora_filter(24.75), + job_filter=_mac_iclora_filter(_cap(24.75)), stills=1, ) assert isinstance(chunked, IcLoraJobLoad) assert chunked.chunk_pixel_frames == IC_LORA_CHUNK_PIXEL_FRAMES - fits = decide_ic_lora_job( + fits = _priced_ic_lora_job( 928, 512, frames, stage_mode=IcLoraStageMode.STAGE_2_LORA, - job_filter=_mac_iclora_filter(24.76), + job_filter=_mac_iclora_filter(_cap(24.76)), stills=1, ) assert isinstance(fits, IcLoraJobLoad) @@ -1042,17 +1070,17 @@ def test_mac_opt_in_two_stage_540p_10s_edges() -> None: measured cell to API. The 11.83 refusal must be stream_over: the fence would hide a chord regression.""" frames = compute_num_frames(10, 24) - short = decide_ic_lora_job( + short = _priced_ic_lora_job( 448, 256, frames, stage_mode=IcLoraStageMode.STAGE_1_LORA, - job_filter=_mac_iclora_filter(11.83), + job_filter=_mac_iclora_filter(_cap(11.83)), ) assert isinstance(short, VideoJobReject) assert short.reason == "stream_over" - fits = decide_ic_lora_job( + fits = _priced_ic_lora_job( 448, 256, frames, stage_mode=IcLoraStageMode.STAGE_1_LORA, - job_filter=_mac_iclora_filter(11.84), + job_filter=_mac_iclora_filter(_cap(11.84)), ) assert isinstance(fits, IcLoraJobLoad) assert fits.mode == "streaming_models_loading" @@ -1064,17 +1092,17 @@ def test_mac_opt_in_two_stage_540p_5s_loads() -> None: refuses it as unmeasured; the 10.58 refusal must be stream_over so a chord regression cannot hide behind the fence.""" frames = compute_num_frames(5, 24) - short = decide_ic_lora_job( + short = _priced_ic_lora_job( 448, 256, frames, stage_mode=IcLoraStageMode.STAGE_1_LORA, - job_filter=_mac_iclora_filter(10.58), + job_filter=_mac_iclora_filter(_cap(10.58)), ) assert isinstance(short, VideoJobReject) assert short.reason == "stream_over" - fits = decide_ic_lora_job( + fits = _priced_ic_lora_job( 448, 256, frames, stage_mode=IcLoraStageMode.STAGE_1_LORA, - job_filter=_mac_iclora_filter(10.59), + job_filter=_mac_iclora_filter(_cap(10.59)), ) assert isinstance(fits, IcLoraJobLoad) assert fits.mode == "streaming_models_loading" @@ -1086,62 +1114,60 @@ def test_mac_opt_in_two_stage_refuses_past_the_cell() -> None: layout too, not just Layout to Render. An opening that drops the gate for the opt-in layout prices this shape on chords that never saw it.""" assert compute_num_frames(15, 24) == 361 - decision = decide_ic_lora_job( + admission = decide_ic_lora_job( 448, 256, 361, stage_mode=IcLoraStageMode.STAGE_1_LORA, job_filter=_mac_iclora_filter(100), ) - assert isinstance(decision, IcLoraJobReject) - assert decision.reason == "mac_two_stage_unmeasured" + assert _untested_basis(admission) == "mac_two_stage_cell" def test_mac_two_stage_refuses_540p_15s_past_the_duration_fence() -> None: """540p L2R at 15s (361 frames, 5,152 tokens) slides under the widened token fence at 448x256 — the 241-frame duration fence must carry it.""" assert compute_num_frames(15, 24) == 361 - decision = decide_ic_lora_job( + admission = decide_ic_lora_job( 448, 256, 361, stage_mode=IcLoraStageMode.STAGE_2_LORA, job_filter=_mac_iclora_filter(100), stills=1, ) - assert isinstance(decision, IcLoraJobReject) - assert decision.reason == "mac_two_stage_unmeasured" + assert _untested_basis(admission) == "mac_two_stage_cell" def test_mac_two_stage_loads_chunked_1080p_10s_and_720p_20s() -> None: """Chunked Mac L2R (K/K4: 640x352 x 481f, 7w of 97f; H10c: 928x512 x 241f, 3w of 97f) prices flat on the per-window chord — refusing window != None - rejects measured chunked two-stage shapes with mac_two_stage_unmeasured.""" - k_short = decide_ic_lora_job( + tags measured chunked two-stage shapes untested.""" + k_short = _priced_ic_lora_job( 640, 352, compute_num_frames(20, 24), stage_mode=IcLoraStageMode.STAGE_2_LORA, - job_filter=_mac_iclora_filter(13.67), + job_filter=_mac_iclora_filter(_cap(13.67)), stills=1, ) assert isinstance(k_short, VideoJobReject) assert k_short.reason == "stream_over" - k_fits = decide_ic_lora_job( + k_fits = _priced_ic_lora_job( 640, 352, compute_num_frames(20, 24), stage_mode=IcLoraStageMode.STAGE_2_LORA, - job_filter=_mac_iclora_filter(13.68), + job_filter=_mac_iclora_filter(_cap(13.68)), stills=1, ) assert isinstance(k_fits, IcLoraJobLoad) assert k_fits.chunk_pixel_frames == IC_LORA_CHUNK_PIXEL_FRAMES - h10c_short = decide_ic_lora_job( + h10c_short = _priced_ic_lora_job( 928, 512, compute_num_frames(10, 24), stage_mode=IcLoraStageMode.STAGE_2_LORA, - job_filter=_mac_iclora_filter(21.38), + job_filter=_mac_iclora_filter(_cap(21.38)), stills=1, ) assert isinstance(h10c_short, VideoJobReject) assert h10c_short.reason == "stream_over" - h10c_fits = decide_ic_lora_job( + h10c_fits = _priced_ic_lora_job( 928, 512, compute_num_frames(10, 24), stage_mode=IcLoraStageMode.STAGE_2_LORA, - job_filter=_mac_iclora_filter(21.39), + job_filter=_mac_iclora_filter(_cap(21.39)), stills=1, ) assert isinstance(h10c_fits, IcLoraJobLoad) @@ -1157,7 +1183,7 @@ def test_two_stage_fence_ignores_single_stage() -> None: def test_decide_ic_lora_job_windows_full_pick_legacy() -> None: """Full-vs-stream stays legacy: 5s full-loads on 31 GB Windows.""" w, h = _source_dim_stage1(1024, 576) - decision = decide_ic_lora_job( + decision = _priced_ic_lora_job( w, h, compute_num_frames(5, 24), @@ -1173,7 +1199,7 @@ def test_decide_ic_lora_job_windows_full_pick_legacy() -> None: def test_decide_ic_lora_job_windows_spatial_still_first() -> None: """A 4K source is over the 1080p cap: spatial on Windows, before the measured gate.""" w, h = _source_dim_stage1(3840, 2160) - decision = decide_ic_lora_job( + decision = _priced_ic_lora_job( w, h, compute_num_frames(5, 24), @@ -1193,7 +1219,7 @@ def test_windows_prices_one_window_restore_at_tile_plus_decode() -> None: """Restore 1080p x 97 asks 11.71 (tile 10.41 + 1.30 canvas decode): canvas pricing strands 16 GB cards to API for a measured cell, while bare tile pricing under-asks the decode peak by 1.3 into an OOM.""" - short = decide_ic_lora_job( + short = _priced_ic_lora_job( 1920, 1088, 97, stage_mode=IcLoraStageMode.SINGLE_STAGE, job_filter=_windows_measured_filter(16, 64, free_gib=11.71), @@ -1201,7 +1227,7 @@ def test_windows_prices_one_window_restore_at_tile_plus_decode() -> None: ) assert isinstance(short, VideoJobReject) assert short.reason == "stream_over" - fits = decide_ic_lora_job( + fits = _priced_ic_lora_job( 1920, 1088, 97, stage_mode=IcLoraStageMode.SINGLE_STAGE, job_filter=_windows_measured_filter(16, 64, free_gib=11.72), @@ -1217,14 +1243,14 @@ def test_windows_streams_one_window_tiled_on_full_mode_cards() -> None: """The legacy full curve on a tile seq would full-load 32 GB cards, where resident (~23) plus tile working set exceeds the headroom — tiled stays streamed. The small untiled control proves full would otherwise fire.""" - control = decide_ic_lora_job( + control = _priced_ic_lora_job( 576, 256, 121, stage_mode=IcLoraStageMode.SINGLE_STAGE, job_filter=_windows_measured_filter(31, 64, free_gib=31.0, process_mode="full_models_loading"), ) assert isinstance(control, IcLoraJobLoad) assert control.mode == "full_models_loading" - decision = decide_ic_lora_job( + decision = _priced_ic_lora_job( 1920, 1088, 97, stage_mode=IcLoraStageMode.SINGLE_STAGE, job_filter=_windows_measured_filter(31, 64, free_gib=31.0, process_mode="full_models_loading"), @@ -1237,7 +1263,7 @@ def test_windows_streams_one_window_tiled_on_full_mode_cards() -> None: def test_windows_prices_one_window_refine_at_tile_plus_decode() -> None: """Refine 1080p x 97 asks 12.22 (tile 10.92 + 1.30): the bigger tile prices its own pass, and bare tile pricing under-asks its 11.71 decode peak.""" - short = decide_ic_lora_job( + short = _priced_ic_lora_job( 1920, 1088, 97, stage_mode=IcLoraStageMode.SINGLE_STAGE, job_filter=_windows_measured_filter(16, 64, free_gib=12.21), @@ -1245,7 +1271,7 @@ def test_windows_prices_one_window_refine_at_tile_plus_decode() -> None: ) assert isinstance(short, VideoJobReject) assert short.reason == "stream_over" - fits = decide_ic_lora_job( + fits = _priced_ic_lora_job( 1920, 1088, 97, stage_mode=IcLoraStageMode.SINGLE_STAGE, job_filter=_windows_measured_filter(16, 64, free_gib=12.22), @@ -1259,7 +1285,7 @@ def test_windows_single_tile_small_canvas_skips_decode_term() -> None: """Restore 540p x 97 (one tile = canvas) asks 10.18 with no decode term: its 7.96 peak stays denoise-bound under the ask, and a flat term would strand 12 GB cards for it.""" - short = decide_ic_lora_job( + short = _priced_ic_lora_job( 960, 512, 97, stage_mode=IcLoraStageMode.SINGLE_STAGE, job_filter=_windows_measured_filter(12, 64, free_gib=10.18), @@ -1267,7 +1293,7 @@ def test_windows_single_tile_small_canvas_skips_decode_term() -> None: ) assert isinstance(short, VideoJobReject) assert short.reason == "stream_over" - fits = decide_ic_lora_job( + fits = _priced_ic_lora_job( 960, 512, 97, stage_mode=IcLoraStageMode.SINGLE_STAGE, job_filter=_windows_measured_filter(12, 64, free_gib=10.19), @@ -1280,7 +1306,7 @@ def test_windows_single_tile_small_canvas_skips_decode_term() -> None: def test_windows_refine_still_at_fence_falls_back_to_canvas() -> None: """A look still pushes Refine's 97f tile pass (14,976 + 576) over the tile-seq fence: uncounted stills would under-price the pass, so it prices the canvas.""" - decision = decide_ic_lora_job( + decision = _priced_ic_lora_job( 1920, 1088, 97, stage_mode=IcLoraStageMode.SINGLE_STAGE, job_filter=_windows_measured_filter(16, 64, free_gib=15.9), @@ -1294,7 +1320,7 @@ def test_windows_refine_still_at_fence_falls_back_to_canvas() -> None: def test_legacy_route_keeps_main_s_tile_price() -> None: """Linux prices the 960x544 tile (2 x 6,630 = 13,260 seq), as on main.""" - decision = decide_ic_lora_job( + decision = _priced_ic_lora_job( 1920, 1088, 97, stage_mode=IcLoraStageMode.SINGLE_STAGE, job_filter=_job_filter(memory_gb=32, process_mode="streaming_models_loading"), @@ -1305,34 +1331,109 @@ def test_legacy_route_keeps_main_s_tile_price() -> None: def test_canvas_pricing_keeps_restore_s_fixed_window() -> None: - """Restore 1080p x 241 on Windows: priced as one canvas window, and the pipeline - still gets Restore's 97-frame window.""" - decision = decide_ic_lora_job( + """Restore 1080p x 241 on Windows: priced on the unified canvas-window decode + curve (15.00 GiB over R3/R6's 14.50–14.58 GiB and C1's 12.11 GiB @ 16g cap) + instead of the 22.15 GiB untiled canvas ask that stranded 16 GB cards.""" + short = _priced_ic_lora_job( 1920, 1088, 241, stage_mode=IcLoraStageMode.SINGLE_STAGE, - job_filter=_windows_measured_filter(31, 64, free_gib=31.0), + job_filter=_windows_measured_filter(16, 64, free_gib=14.99), tiling=_RESTORE_TILING, ) - assert isinstance(decision, IcLoraJobLoad) - assert decision.chunk_pixel_frames == 97 - assert decision.seq == 53_040 + assert isinstance(short, VideoJobReject) + assert short.reason == "stream_over" + fits = _priced_ic_lora_job( + 1920, 1088, 241, + stage_mode=IcLoraStageMode.SINGLE_STAGE, + job_filter=_windows_measured_filter(16, 64, free_gib=15.00), + tiling=_RESTORE_TILING, + ) + assert isinstance(fits, IcLoraJobLoad) + assert fits.chunk_pixel_frames == 97 + assert fits.seq == 13_260 + + +def test_windows_prices_chunked_1080p_refine_on_canvas_window_decode_curve() -> None: + """T1 (Refine 1080p x 241 in 5 windows of 73f) peaked at 12.74 GiB: falling + back to untiled canvas pricing (18.54 GiB) when window is not None refuses + 16 GB cards a job that saturates at 12.74 GiB.""" + refine_chunked_tiling = IcLoraTiling(long_side=1024, short_side=576, window_frames=73) + short = _priced_ic_lora_job( + 1920, 1088, 241, + stage_mode=IcLoraStageMode.SINGLE_STAGE, + job_filter=_windows_measured_filter(16, 64, free_gib=12.73), + tiling=refine_chunked_tiling, + ) + assert isinstance(short, VideoJobReject) + assert short.reason == "stream_over" + fits = _priced_ic_lora_job( + 1920, 1088, 241, + stage_mode=IcLoraStageMode.SINGLE_STAGE, + job_filter=_windows_measured_filter(16, 64, free_gib=12.74), + tiling=refine_chunked_tiling, + ) + assert isinstance(fits, IcLoraJobLoad) + assert fits.chunk_pixel_frames == 73 + assert fits.seq == 11_520 + + +def test_windows_prices_half_res_ref_adapters_at_1_25x_video_tokens() -> None: + """Video Guide and Motion Track use reference_downscale_factor=2 (-ref0.5), + appending 0.25x video tokens (1.25x total): pricing them at 2.0x over-asks + VG1 (1080p 121f, 12.80 GiB measured) at 25.76 GiB and VG3 (1080p 241f 3w, + 13.30 GiB measured) at 22.15 GiB, stranding 16 GB and 24 GB cards.""" + for adapter_id in ("video-guide", "motion-track"): + vg1_short = _priced_ic_lora_job( + 1920, 1088, 121, + stage_mode=IcLoraStageMode.SINGLE_STAGE, + job_filter=_windows_measured_filter(16, 64, free_gib=13.35), + ic_lora_id=adapter_id, + ) + assert isinstance(vg1_short, VideoJobReject) + assert vg1_short.reason == "stream_over" + vg1_fits = _priced_ic_lora_job( + 1920, 1088, 121, + stage_mode=IcLoraStageMode.SINGLE_STAGE, + job_filter=_windows_measured_filter(16, 64, free_gib=13.37), + ic_lora_id=adapter_id, + ) + assert isinstance(vg1_fits, IcLoraJobLoad) + assert vg1_fits.seq == 40_800 + + vg3_short = _priced_ic_lora_job( + 1920, 1088, 241, + stage_mode=IcLoraStageMode.SINGLE_STAGE, + job_filter=_windows_measured_filter(16, 64, free_gib=14.60), + ic_lora_id="video-guide", + ) + assert isinstance(vg3_short, VideoJobReject) + assert vg3_short.reason == "stream_over" + vg3_fits = _priced_ic_lora_job( + 1920, 1088, 241, + stage_mode=IcLoraStageMode.SINGLE_STAGE, + job_filter=_windows_measured_filter(16, 64, free_gib=14.62), + ic_lora_id="video-guide", + ) + assert isinstance(vg3_fits, IcLoraJobLoad) + assert vg3_fits.chunk_pixel_frames == 97 + assert vg3_fits.seq == 33_150 def test_mac_prices_restore_shaped_tiled_job_at_its_tile() -> None: """Restore 1080p x 97 tiled passes at 9.84 — pricing it at the 22 GB canvas - refuses 24 GB and 16 GB Macs a job the tile fits.""" - short = decide_ic_lora_job( + refuses 24 GB Macs a job the tile fits.""" + short = _priced_ic_lora_job( 1920, 1088, 97, stage_mode=IcLoraStageMode.SINGLE_STAGE, - job_filter=_mac_iclora_filter(9.83), + job_filter=_mac_iclora_filter(_cap(9.83)), tiling=_RESTORE_TILING, ) assert isinstance(short, VideoJobReject) assert short.reason == "stream_over" - fits = decide_ic_lora_job( + fits = _priced_ic_lora_job( 1920, 1088, 97, stage_mode=IcLoraStageMode.SINGLE_STAGE, - job_filter=_mac_iclora_filter(9.85), + job_filter=_mac_iclora_filter(_cap(9.85)), tiling=_RESTORE_TILING, ) assert isinstance(fits, IcLoraJobLoad) @@ -1343,20 +1444,20 @@ def test_mac_prices_restore_shaped_tiled_job_at_its_tile() -> None: def test_mac_prices_chunked_restore_at_flat_s20() -> None: """Restore 1080p x 241 chunked asks the flat 18.7 S20 pass: canvas-window - pricing (21.94) refuses 24 GB pools a measured cell, while the 9.84 tile + pricing (21.94) refuses pools the measured pass fits, while the 9.84 tile price fails the same clip outright.""" - short = decide_ic_lora_job( + short = _priced_ic_lora_job( 1920, 1088, 241, stage_mode=IcLoraStageMode.SINGLE_STAGE, - job_filter=_mac_iclora_filter(18.69), + job_filter=_mac_iclora_filter(_cap(18.69)), tiling=_RESTORE_TILING, ) assert isinstance(short, VideoJobReject) assert short.reason == "stream_over" - fits = decide_ic_lora_job( + fits = _priced_ic_lora_job( 1920, 1088, 241, stage_mode=IcLoraStageMode.SINGLE_STAGE, - job_filter=_mac_iclora_filter(18.71), + job_filter=_mac_iclora_filter(_cap(18.71)), tiling=_RESTORE_TILING, ) assert isinstance(fits, IcLoraJobLoad) @@ -1368,10 +1469,10 @@ def test_mac_prices_chunked_restore_at_flat_s20() -> None: def test_mac_chunked_restore_20s_prices_flat() -> None: """Restore 1080p x 481 (the measured 7-window max) asks the flat 18.7 — the fence must reach the measured edge, not stop at 10 s.""" - decision = decide_ic_lora_job( + decision = _priced_ic_lora_job( 1920, 1088, 481, stage_mode=IcLoraStageMode.SINGLE_STAGE, - job_filter=_mac_iclora_filter(18.71), + job_filter=_mac_iclora_filter(_cap(18.71)), tiling=_RESTORE_TILING, ) assert isinstance(decision, IcLoraJobLoad) @@ -1381,7 +1482,7 @@ def test_mac_chunked_restore_20s_prices_flat() -> None: def test_mac_chunked_restore_past_20s_falls_back_to_canvas_window() -> None: """Restore 1080p x 505 runs past the measured 7 windows: flat pricing it extrapolates growth nobody measured, so it prices the canvas window.""" - decision = decide_ic_lora_job( + decision = _priced_ic_lora_job( 1920, 1088, 505, stage_mode=IcLoraStageMode.SINGLE_STAGE, job_filter=_mac_iclora_filter(18.70), @@ -1395,10 +1496,10 @@ def test_mac_chunked_restore_past_20s_falls_back_to_canvas_window() -> None: def test_mac_small_canvas_chunked_restore_keeps_window_price() -> None: """Restore 720p x 241 chunked asks its canvas window (12.73), not the flat 18.7: the flat price misapplied refuses fittable mid pools.""" - decision = decide_ic_lora_job( + decision = _priced_ic_lora_job( 1280, 704, 241, stage_mode=IcLoraStageMode.SINGLE_STAGE, - job_filter=_mac_iclora_filter(15.0), + job_filter=_mac_iclora_filter(_cap(15.0)), tiling=_RESTORE_TILING, ) assert isinstance(decision, IcLoraJobLoad) @@ -1409,7 +1510,7 @@ def test_mac_small_canvas_chunked_restore_keeps_window_price() -> None: def test_mac_chunked_restore_still_at_fence_falls_back_to_canvas() -> None: """A look still pushes the 97f tile pass (13,260 + 510) over the flat fence: an uncounted still prices 18.7 where the true need exceeds it.""" - decision = decide_ic_lora_job( + decision = _priced_ic_lora_job( 1920, 1088, 241, stage_mode=IcLoraStageMode.SINGLE_STAGE, job_filter=_mac_iclora_filter(18.70), @@ -1424,7 +1525,7 @@ def test_mac_chunked_restore_still_at_fence_falls_back_to_canvas() -> None: def test_mac_tiled_price_stays_canvas_for_bigger_tile() -> None: """Refine's 1024x576 tile (7,488 tokens at 97f) was never measured — only Restore's 960x544 tile prices the tile.""" - decision = decide_ic_lora_job( + decision = _priced_ic_lora_job( 1920, 1088, 97, stage_mode=IcLoraStageMode.SINGLE_STAGE, job_filter=_mac_iclora_filter(12.5), @@ -1438,7 +1539,7 @@ def test_mac_tiled_price_stays_canvas_for_bigger_tile() -> None: def test_refine_decode_floor_refuses_long_1080p_on_huge_vram() -> None: """Refine 1080p x 241 unchunked refuses with its own reason on 48 GB free: canvas figures would admit it straight into the pipeline's DiffVAE 400.""" - decision = decide_ic_lora_job( + decision = _priced_ic_lora_job( 1920, 1088, 241, stage_mode=IcLoraStageMode.SINGLE_STAGE, job_filter=_windows_measured_filter(48, 128, free_gib=47.0), @@ -1451,7 +1552,7 @@ def test_refine_decode_floor_refuses_long_1080p_on_huge_vram() -> None: def test_refine_decode_floor_bites_on_mac_too() -> None: """The DiffVAE floor is a pipeline limit, not a CUDA curve — a CUDA-only fence lets huge-pool Macs into the same 400.""" - decision = decide_ic_lora_job( + decision = _priced_ic_lora_job( 1920, 1088, 241, stage_mode=IcLoraStageMode.SINGLE_STAGE, job_filter=_mac_iclora_filter(100), @@ -1465,7 +1566,7 @@ def test_windows_prices_long_720p_refine_at_canvas_plus_decode() -> None: """Refine 720p x 241 unchunked asks 23.90 (canvas 22.60 + 1.30): under 720p the decode fits usable, but bare canvas pricing would admit 24 GB-edge pools its decode volume exceeds.""" - short = decide_ic_lora_job( + short = _priced_ic_lora_job( 1280, 704, 241, stage_mode=IcLoraStageMode.SINGLE_STAGE, job_filter=_windows_measured_filter(31, 64, free_gib=22.70), @@ -1473,7 +1574,7 @@ def test_windows_prices_long_720p_refine_at_canvas_plus_decode() -> None: ) assert isinstance(short, VideoJobReject) assert short.reason == "stream_over" - fits = decide_ic_lora_job( + fits = _priced_ic_lora_job( 1280, 704, 241, stage_mode=IcLoraStageMode.SINGLE_STAGE, job_filter=_windows_measured_filter(31, 64, free_gib=23.90), @@ -1503,7 +1604,7 @@ def test_windows_layout_to_render_prices_the_look_still() -> None: job_filter = _windows_measured_filter(31, 64, free_gib=31.0) def priced(stills: int) -> IcLoraJobLoad: - decision = decide_ic_lora_job( + decision = _priced_ic_lora_job( 960, 544, 121, stage_mode=IcLoraStageMode.STAGE_2_LORA, job_filter=job_filter, @@ -1520,7 +1621,7 @@ def priced(stills: int) -> IcLoraJobLoad: def test_windows_prices_a_chunked_job_as_one_window() -> None: """1080p x 241 single-stage runs in 97-frame windows asking 22.15 — it fits a 24 GB card; the whole clip would ask 43.81.""" - decision = decide_ic_lora_job( + decision = _priced_ic_lora_job( 1920, 1088, 241, stage_mode=IcLoraStageMode.SINGLE_STAGE, job_filter=_windows_measured_filter(24, 64, free_gib=23.9), @@ -1532,7 +1633,7 @@ def test_windows_prices_a_chunked_job_as_one_window() -> None: def test_windows_chunked_reject_keeps_the_priced_window() -> None: # The bug is a downgrade running the whole clip: the reject dropped the # 97-frame window, and None means one unchunked pass. - decision = decide_ic_lora_job( + decision = _priced_ic_lora_job( 1920, 1088, 241, stage_mode=IcLoraStageMode.SINGLE_STAGE, job_filter=_windows_measured_filter(16, 64, free_gib=15.0), @@ -1557,7 +1658,7 @@ def tier(available: float) -> str | None: vram_bytes=int(available * _GIB), free_vram_bytes=int(available * _GIB), ) - return load_risk_tier(load, job_filter, feature="fast") + return "tight" if is_tight_fit(load, job_filter) else None assert tier(ask + 0.5) is None assert tier(ask + 0.49) == "tight" @@ -1566,7 +1667,7 @@ def tier(available: float) -> str | None: def test_two_stage_fence_counts_one_window_for_chunked_layout_to_render() -> None: """Layout to Render 1080p x 241: 15,810 stage-1 tokens over the clip, past the fence, but it runs in 6,630-token windows.""" - decision = decide_ic_lora_job( + decision = _priced_ic_lora_job( 960, 544, 241, stage_mode=IcLoraStageMode.STAGE_2_LORA, job_filter=_windows_measured_filter(31, 64, free_gib=31.0), @@ -1580,57 +1681,57 @@ def test_decide_ic_lora_job_windows_ram_gate() -> None: """L5 floors: 64 CPU / 48 DISK (L5-48 holds); unknown fails closed (Fast mirror).""" w, h = _source_dim_stage1(1024, 576) frames = compute_num_frames(5, 24) - short_cpu = decide_ic_lora_job( + short_cpu = _priced_ic_lora_job( w, h, frames, stage_mode=IcLoraStageMode.SINGLE_STAGE, job_filter=_windows_measured_filter(31, 62, free_gib=12.0) ) assert isinstance(short_cpu, VideoJobReject) assert short_cpu.reason == "ram_shortfall" - ok_cpu_63 = decide_ic_lora_job( + ok_cpu_63 = _priced_ic_lora_job( w, h, frames, stage_mode=IcLoraStageMode.SINGLE_STAGE, job_filter=_windows_measured_filter(31, 63, free_gib=12.0) ) assert isinstance(ok_cpu_63, IcLoraJobLoad) - ok_cpu = decide_ic_lora_job( + ok_cpu = _priced_ic_lora_job( w, h, frames, stage_mode=IcLoraStageMode.SINGLE_STAGE, job_filter=_windows_measured_filter(31, 64, free_gib=12.0) ) assert isinstance(ok_cpu, IcLoraJobLoad) - short_disk = decide_ic_lora_job( + short_disk = _priced_ic_lora_job( w, h, frames, stage_mode=IcLoraStageMode.SINGLE_STAGE, job_filter=_windows_measured_filter( - 31, 46, free_gib=12.0, drive_type="nvme" + 31, 30, free_gib=12.0, drive_type="nvme" ), ) assert isinstance(short_disk, VideoJobReject) assert short_disk.reason == "ram_shortfall" - ok_disk_47 = decide_ic_lora_job( + ok_disk_31 = _priced_ic_lora_job( w, h, frames, stage_mode=IcLoraStageMode.SINGLE_STAGE, job_filter=_windows_measured_filter( - 31, 47, free_gib=12.0, drive_type="nvme" + 31, 31, free_gib=12.0, drive_type="nvme" ), ) - assert isinstance(ok_disk_47, IcLoraJobLoad) - ok_disk = decide_ic_lora_job( + assert isinstance(ok_disk_31, IcLoraJobLoad) + ok_disk = _priced_ic_lora_job( w, h, frames, stage_mode=IcLoraStageMode.SINGLE_STAGE, job_filter=_windows_measured_filter( - 31, 48, free_gib=12.0, drive_type="nvme" + 31, 32, free_gib=12.0, drive_type="nvme" ), ) assert isinstance(ok_disk, IcLoraJobLoad) - unknown_ram = decide_ic_lora_job( + unknown_ram = _priced_ic_lora_job( w, h, frames, stage_mode=IcLoraStageMode.SINGLE_STAGE, job_filter=_windows_measured_filter(31, None, free_gib=12.0) @@ -1641,7 +1742,7 @@ def test_decide_ic_lora_job_windows_ram_gate() -> None: def test_windows_iclora_tall_20s_refuses_paging_cell_on_24gb() -> None: """Allocated ask 18.81 admits at free 24, but native reserved is 24.81; must refuse.""" - decision = decide_ic_lora_job( + decision = _priced_ic_lora_job( 576, 960, compute_num_frames(20, 24), stage_mode=IcLoraStageMode.SINGLE_STAGE, job_filter=_windows_measured_filter(24, 64, free_gib=24.0), @@ -1652,7 +1753,7 @@ def test_windows_iclora_tall_20s_refuses_paging_cell_on_24gb() -> None: def test_windows_iclora_wide_20s_refuses_on_10gb() -> None: """Floor ask 8.00 admits at free 9.99, but native reserved is 10.97; must refuse.""" - decision = decide_ic_lora_job( + decision = _priced_ic_lora_job( 576, 256, compute_num_frames(20, 24), stage_mode=IcLoraStageMode.SINGLE_STAGE, job_filter=_windows_measured_filter(9.99, 64, free_gib=9.99), @@ -1663,7 +1764,7 @@ def test_windows_iclora_wide_20s_refuses_on_10gb() -> None: def test_windows_iclora_small_cell_loads_on_10gb() -> None: """Reserved ask 8.53 must still load at free 9.95 (guards over-correction stranding idle 10GB).""" - decision = decide_ic_lora_job( + decision = _priced_ic_lora_job( 576, 256, compute_num_frames(10, 24), stage_mode=IcLoraStageMode.SINGLE_STAGE, job_filter=_windows_measured_filter(9.99, 64, free_gib=9.95), @@ -1674,7 +1775,7 @@ def test_windows_iclora_small_cell_loads_on_10gb() -> None: def test_windows_iclora_two_stage_d4_refuses_paging_band() -> None: """Allocated ask 18.01 admits at free 22, but native reserved is 22.61; must refuse.""" - decision = decide_ic_lora_job( + decision = _priced_ic_lora_job( 960, 512, compute_num_frames(10, 24), stage_mode=IcLoraStageMode.STAGE_1_LORA, job_filter=_windows_measured_filter(24, 64, free_gib=22.0), @@ -1732,7 +1833,7 @@ def test_full_estimate_is_above_stream() -> None: def _video_job(width: int, height: int, seconds: int, fps: int = 24, **kwargs): - return decide_video_job( + return _priced_video_job( width, height, compute_num_frames(seconds, fps), @@ -1740,6 +1841,17 @@ def _video_job(width: int, height: int, seconds: int, fps: int = 24, **kwargs): ) +def _one_pass_priced(width: int, height: int, frames: int, *, job_filter: LocalJobFilter) -> VideoJobDecision: + """The one-pass verdict: what the Fast law says before the picker tries windows.""" + return _decide_fast_pass(width, height, frames, windows=1, job_filter=job_filter) # pyright: ignore[reportPrivateUsage] + + +def _one_pass_job(width: int, height: int, seconds: int, fps: int = 24, **kwargs): + return _one_pass_priced( + width, height, compute_num_frames(seconds, fps), job_filter=_job_filter(**kwargs) + ) + + def test_decide_video_job_31gb_540p_5s_full() -> None: decision = _video_job(1024, 576, 5, memory_gb=31, process_mode="full_models_loading") assert isinstance(decision, VideoJobLoad) @@ -1752,11 +1864,6 @@ def test_decide_video_job_32gb_720p_20s_streams() -> None: assert decision.mode == "streaming_models_loading" -def test_decide_video_job_16gb_720p_20s_rejects() -> None: - decision = _video_job(1280, 704, 20, memory_gb=16, process_mode="streaming_models_loading") - assert isinstance(decision, VideoJobReject) - - def test_decide_video_job_15gb_540p_5s_still_streams() -> None: decision = _video_job(1024, 576, 5, memory_gb=15, process_mode="streaming_models_loading") assert isinstance(decision, VideoJobLoad) @@ -1765,7 +1872,7 @@ def test_decide_video_job_15gb_540p_5s_still_streams() -> None: def test_decide_edit_job_31gb_720p_extend_streams() -> None: """5090 extend 1280×704×337 estimated 27.2 GiB and reserved the whole card.""" - decision = decide_edit_job( + decision = _priced_edit_job( 1280, 704, 337, @@ -1773,7 +1880,7 @@ def test_decide_edit_job_31gb_720p_extend_streams() -> None: ) assert isinstance(decision, VideoJobLoad) assert decision.mode == "streaming_models_loading" - reported_as_32 = decide_edit_job( + reported_as_32 = _priced_edit_job( 1280, 704, 337, job_filter=_job_filter(memory_gb=32, process_mode="full_models_loading"), ) @@ -1807,7 +1914,7 @@ def _windows_measured_filter( def test_decide_edit_job_windows_540p_floor_is_8_75() -> None: """Floor edge (8.5, 8.75]: fails below 8.75 free, streams at 8.75 (RAM ok).""" - short = decide_edit_job( + short = _priced_edit_job( 1024, 576, 121, @@ -1815,7 +1922,7 @@ def test_decide_edit_job_windows_540p_floor_is_8_75() -> None: ) assert isinstance(short, VideoJobReject) assert short.reason == "stream_over" - fits = decide_edit_job( + fits = _priced_edit_job( 1024, 576, 121, job_filter=_windows_measured_filter(31, 64, free_gib=8.75) ) assert isinstance(fits, VideoJobLoad) @@ -1824,7 +1931,7 @@ def test_decide_edit_job_windows_540p_floor_is_8_75() -> None: def test_decide_edit_job_windows_720p_follows_formula() -> None: """337 denoise frames need 15.48 (curve binds, not the 9.0 floor).""" - short = decide_edit_job( + short = _priced_edit_job( 1280, 704, 337, @@ -1832,7 +1939,7 @@ def test_decide_edit_job_windows_720p_follows_formula() -> None: ) assert isinstance(short, VideoJobReject) assert short.reason == "stream_over" - fits = decide_edit_job( + fits = _priced_edit_job( 1280, 704, 337, job_filter=_windows_measured_filter(31, 64, free_gib=15.5) ) assert isinstance(fits, VideoJobLoad) @@ -1841,7 +1948,7 @@ def test_decide_edit_job_windows_720p_follows_formula() -> None: def test_decide_edit_job_windows_1080p_417f_refuses_paging_window() -> None: """417f admitted at allocated ask 30.18 paged (reserved 34.70); reserved ask 34.95 refuses at free 30.3.""" - decision = decide_edit_job( + decision = _priced_edit_job( 1920, 1088, 417, @@ -1853,7 +1960,7 @@ def test_decide_edit_job_windows_1080p_417f_refuses_paging_window() -> None: def test_decide_edit_job_windows_1080p_337f_loads_step0_clean_window() -> None: """337f ran clean on base (reserved 28.86); reserved ask 29.30 still loads at free 30.3.""" - decision = decide_edit_job( + decision = _priced_edit_job( 1920, 1088, 337, @@ -1865,7 +1972,7 @@ def test_decide_edit_job_windows_1080p_337f_loads_step0_clean_window() -> None: def test_decide_edit_job_windows_full_pick_unchanged() -> None: """Full-vs-stream stays legacy: short 720p full-loads on 31 GB Windows.""" - decision = decide_edit_job( + decision = _priced_edit_job( 1280, 704, compute_num_frames(5, 24), @@ -1880,7 +1987,7 @@ def test_decide_edit_job_windows_full_pick_unchanged() -> None: def test_decide_edit_job_windows_ram_gate() -> None: """E3 floors: 64 CPU / 32 DISK (holds by Fast precedent); unknown fails closed.""" base = dict(vram_gib=31) - short_cpu = decide_edit_job( + short_cpu = _priced_edit_job( 1024, 576, 121, @@ -1890,7 +1997,7 @@ def test_decide_edit_job_windows_ram_gate() -> None: ) assert isinstance(short_cpu, VideoJobReject) assert short_cpu.reason == "ram_shortfall" - short_cpu_62 = decide_edit_job( + short_cpu_62 = _priced_edit_job( 1024, 576, 121, @@ -1900,7 +2007,7 @@ def test_decide_edit_job_windows_ram_gate() -> None: ) assert isinstance(short_cpu_62, VideoJobReject) assert short_cpu_62.reason == "ram_shortfall" - ok_cpu_63 = decide_edit_job( + ok_cpu_63 = _priced_edit_job( 1024, 576, 121, @@ -1909,7 +2016,7 @@ def test_decide_edit_job_windows_ram_gate() -> None: ), ) assert isinstance(ok_cpu_63, VideoJobLoad) - ok_cpu_64 = decide_edit_job( + ok_cpu_64 = _priced_edit_job( 1024, 576, 121, @@ -1918,7 +2025,7 @@ def test_decide_edit_job_windows_ram_gate() -> None: ), ) assert isinstance(ok_cpu_64, VideoJobLoad) - ok_disk = decide_edit_job( + ok_disk = _priced_edit_job( 1024, 576, 121, @@ -1930,7 +2037,7 @@ def test_decide_edit_job_windows_ram_gate() -> None: ), ) assert isinstance(ok_disk, VideoJobLoad) - short_sata = decide_edit_job( + short_sata = _priced_edit_job( 1024, 576, 121, @@ -1943,7 +2050,7 @@ def test_decide_edit_job_windows_ram_gate() -> None: ) assert isinstance(short_sata, VideoJobReject) assert short_sata.reason == "ram_shortfall" - unknown_ram = decide_edit_job( + unknown_ram = _priced_edit_job( 1024, 576, 121, @@ -1957,7 +2064,7 @@ def test_decide_edit_job_windows_ram_gate() -> None: def test_ram_gate_admits_63_45gib_box_on_64gib_floor() -> None: """A real 64 GB box reports ~63.45; exact-compare must not refuse it.""" - decision = decide_edit_job( + decision = _priced_edit_job( 1024, 576, 121, @@ -1966,20 +2073,20 @@ def test_ram_gate_admits_63_45gib_box_on_64gib_floor() -> None: assert isinstance(decision, VideoJobLoad) -def test_ram_gate_admits_31_5gib_on_32gib_disk_floor() -> None: - """A 32 GB NVMe box reports under nominal; streamed edit must load.""" - decision = decide_edit_job( +def test_ram_gate_admits_23_5gib_on_24gib_disk_floor() -> None: + """A 24 GB NVMe box reports under nominal; streamed edit must load.""" + decision = _priced_edit_job( 1024, 576, 121, - job_filter=_windows_measured_filter(31, 31.5, free_gib=12.0, drive_type="nvme"), + job_filter=_windows_measured_filter(31, 23.5, free_gib=12.0, drive_type="nvme"), ) assert isinstance(decision, VideoJobLoad) def test_ram_gate_still_refuses_below_floor_minus_headroom() -> None: """Headroom must not swallow genuine shortfalls: 62 on a 64 floor refuses.""" - decision = decide_edit_job( + decision = _priced_edit_job( 1024, 576, 121, @@ -2019,9 +2126,9 @@ def test_max_edit_frames_shrinks_1080p_on_31gb_and_keeps_720p() -> None: job_filter = _job_filter(memory_gb=31, process_mode="full_models_loading") cap = max_edit_frames_that_load(1920, 1088, frame_cap=505, job_filter=job_filter) assert cap < 505 - assert isinstance(decide_edit_job(1920, 1088, 505, job_filter=job_filter), VideoJobReject) - assert isinstance(decide_edit_job(1920, 1088, cap, job_filter=job_filter), VideoJobLoad) - assert isinstance(decide_edit_job(1920, 1088, cap + 1, job_filter=job_filter), VideoJobReject) + assert isinstance(_priced_edit_job(1920, 1088, 505, job_filter=job_filter), VideoJobReject) + assert isinstance(_priced_edit_job(1920, 1088, cap, job_filter=job_filter), VideoJobLoad) + assert isinstance(_priced_edit_job(1920, 1088, cap + 1, job_filter=job_filter), VideoJobReject) assert ( max_edit_frames_that_load(1280, 736, frame_cap=505, job_filter=job_filter) == 505 ) @@ -2034,7 +2141,7 @@ def test_max_edit_frames_shrinks_1080p_on_31gb_and_keeps_720p() -> None: max_input_frames=cap, ) assert isinstance( - decide_edit_job( + _priced_edit_job( 1920, 1088, window.context_frames + extend_frames, job_filter=job_filter ), VideoJobLoad, @@ -2048,13 +2155,13 @@ def test_max_edit_frames_shrinks_1080p_on_31gb_and_keeps_720p() -> None: ) assert retake.encode_frames <= cap assert isinstance( - decide_edit_job(1920, 1088, retake.encode_frames, job_filter=job_filter), + _priced_edit_job(1920, 1088, retake.encode_frames, job_filter=job_filter), VideoJobLoad, ) def test_decide_edit_job_31gb_short_720p_stays_full() -> None: - decision = decide_edit_job( + decision = _priced_edit_job( 1280, 704, compute_num_frames(5, 24), @@ -2077,20 +2184,20 @@ def _windows_5090_edit_filter() -> LocalJobFilter: def test_decide_edit_job_refuses_369f_on_5090_free_short() -> None: """The total-fitting 369f window asks 31.6 against 30.1 free: refuse, don't page.""" - decision = decide_edit_job(1920, 1088, 369, job_filter=_windows_5090_edit_filter()) + decision = _priced_edit_job(1920, 1088, 369, job_filter=_windows_5090_edit_filter()) assert isinstance(decision, VideoJobReject) assert decision.reason == "stream_over" def test_decide_edit_job_loads_345f_on_5090_free_short() -> None: """The shrunken 345f window asks 29.9 against 30.1 free: load, don't refuse.""" - decision = decide_edit_job(1920, 1088, 345, job_filter=_windows_5090_edit_filter()) + decision = _priced_edit_job(1920, 1088, 345, job_filter=_windows_5090_edit_filter()) assert isinstance(decision, VideoJobLoad) assert decision.mode == "streaming_models_loading" def test_fast_budget_still_full_loads_the_720p_extend_clip() -> None: - decision = decide_video_job( + decision = _priced_video_job( 1280, 704, 337, job_filter=_job_filter(memory_gb=31, process_mode="full_models_loading"), ) @@ -2157,13 +2264,13 @@ def test_legacy_darwin_no_model_never_rejects() -> None: def test_decide_video_job_stream_over_rejects() -> None: - decision = _video_job(1280, 704, 20, memory_gb=8, process_mode="full_models_loading") + decision = _one_pass_job(1280, 704, 20, memory_gb=8, process_mode="full_models_loading") assert isinstance(decision, VideoJobReject) assert decision.reason == "stream_over" def test_decide_video_job_16gb_1080p_10s_rejects() -> None: - decision = _video_job(1920, 1088, 10, memory_gb=16, process_mode="streaming_models_loading") + decision = _one_pass_job(1920, 1088, 10, memory_gb=16, process_mode="streaming_models_loading") assert isinstance(decision, VideoJobReject) @@ -2253,7 +2360,7 @@ def test_reject_free_short_says_close_apps_not_lower() -> None: assert code == VIDEO_JOB_TOO_LARGE assert message == ( "This job needs 15.8 GB of GPU memory but only 15.0 GB is free " - "right now (of 16.0 GB total). Close other GPU apps and retry." + "right now (of 16.0 GB total). Close other heavy apps (like games, browsers, or video editors) and retry." ) @@ -2389,6 +2496,7 @@ def test_reject_caller_action_overrides_default_advice() -> None: ) +@pytest.mark.usefixtures("single_pass_only") def test_decide_fast_durations_reports_per_cell_reject_reasons() -> None: from runtime_config.video_job_budget import decide_fast_durations @@ -2402,7 +2510,7 @@ def test_decide_fast_durations_reports_per_cell_reject_reasons() -> None: ), ) assert over_vram.kept == [5] - assert over_vram.rejected == {10: "stream_over"} + assert _refused_reasons(over_vram) == {10: "stream_over"} short_ram = decide_fast_durations( 1024, @@ -2416,7 +2524,7 @@ def test_decide_fast_durations_reports_per_cell_reject_reasons() -> None: ), ) assert short_ram.kept == [] - assert short_ram.rejected == {5: "ram_shortfall"} + assert _refused_reasons(short_ram) == {5: "ram_shortfall"} def _mac_profile( @@ -2461,17 +2569,17 @@ def test_mac_fast_stream_required_matches_measured_brackets( def test_mac_25_pool_edges_gate_f1_cell() -> None: - load = _video_job( + load = _one_pass_job( 1280, 704, 10, process_mode="streaming_models_loading", - **_mac_profile(pool_gib=12.70), + **_mac_profile(pool_gib=_cap(12.70)), ) assert isinstance(load, VideoJobLoad) assert load.mode == "streaming_models_loading" - reject = _video_job( + reject = _one_pass_job( 1280, 704, 10, process_mode="streaming_models_loading", - **_mac_profile(pool_gib=12.30), + **_mac_profile(pool_gib=_cap(12.30)), ) assert isinstance(reject, VideoJobReject) assert reject.reason == "stream_over" @@ -2481,13 +2589,13 @@ def test_mac_25_540p5s_floor_edges() -> None: load = _video_job( 1024, 576, 5, process_mode="streaming_models_loading", - **_mac_profile(pool_gib=9.75), + **_mac_profile(pool_gib=_cap(9.75)), ) assert isinstance(load, VideoJobLoad) reject = _video_job( 1024, 576, 5, process_mode="streaming_models_loading", - **_mac_profile(pool_gib=9.40), + **_mac_profile(pool_gib=_cap(9.40)), ) assert isinstance(reject, VideoJobReject) assert reject.reason == "stream_over" @@ -2497,23 +2605,23 @@ def test_mac_25_1080p10s_top_cell_edges() -> None: # Ask 24.74 sits 0.03 above the 24.71 pass edge (the +0.03 intercept lift # covers the 720p/10s fence cell): safe-direction over-refusal, never an # inversion — the 24.31 fail top stays refused. - load = _video_job( + load = _one_pass_job( 1920, 1088, 10, process_mode="streaming_models_loading", - **_mac_profile(pool_gib=24.74), + **_mac_profile(pool_gib=_cap(24.74)), ) assert isinstance(load, VideoJobLoad) - reject = _video_job( + reject = _one_pass_job( 1920, 1088, 10, process_mode="streaming_models_loading", - **_mac_profile(pool_gib=24.71), + **_mac_profile(pool_gib=_cap(24.71)), ) assert isinstance(reject, VideoJobReject) assert reject.reason == "stream_over" - fail_top = _video_job( + fail_top = _one_pass_job( 1920, 1088, 10, process_mode="streaming_models_loading", - **_mac_profile(pool_gib=24.31), + **_mac_profile(pool_gib=_cap(24.31)), ) assert isinstance(fail_top, VideoJobReject) assert fail_top.reason == "stream_over" @@ -2559,15 +2667,34 @@ def test_mac_23_routes_through_pool_gate_instead_of_never_reject() -> None: assert loaded.mode == "streaming_models_loading" -def test_mac_fast_unknown_model_id_fails_closed() -> None: - """A future model id must never silently take the legacy never-reject branch.""" - profile = HardwareProfile( - system="Darwin", - model_id="ltx-9.9-future", # type: ignore[arg-type] +def test_mac_fast_unknown_model_id_is_unmeasured() -> None: + """A future model id prices as unmeasured instead of crashing or silently passing.""" + job_filter = _job_filter( process_mode="streaming_models_loading", + **_mac_profile(pool_gib=32, model_id="ltx-9.9-future"), # type: ignore[arg-type] + ) + cautious = decide_video_job( + 1024, + 576, + compute_num_frames(5, 24), + job_filter=job_filter, ) - with pytest.raises(AssertionError): - profile.is_mac_fast + assert _untested_basis(cautious) == "unmeasured_model" + + brave = decide_video_job( + 1024, + 576, + compute_num_frames(5, 24), + job_filter=LocalJobFilter( + profile=job_filter.profile, + budget=job_filter.budget, + budget_mode="brave", + ), + ) + assert isinstance(brave, Admitted) + assert brave.risk is not None + assert brave.risk.tier == "unmeasured" + assert brave.risk.unmeasured_basis == "unmeasured_model" def test_mac_25_unknown_pool_fails_closed() -> None: @@ -2582,14 +2709,14 @@ def test_mac_25_unknown_pool_fails_closed() -> None: def test_windows_25_ignores_pool_bytes() -> None: """Pool neither gates nor rescues the Windows VRAM profile.""" - loads = _video_job( + loads = _one_pass_job( 1024, 576, 5, process_mode="streaming_models_loading", mps_pool_bytes=None, **_windows_profile(vram_gib=16), ) assert isinstance(loads, VideoJobLoad) - rejects = _video_job( + rejects = _one_pass_job( 1280, 704, 20, process_mode="streaming_models_loading", mps_pool_bytes=int(100 * _GIB), @@ -2610,10 +2737,60 @@ def test_mac_25_unsupported_mode_precedence() -> None: def test_mac_25_pool_gates_darwin_grid() -> None: - """A 14 GiB pool keeps short 540p but drops 540p/20s and all 1080p.""" - kwargs = dict(process_mode="streaming_models_loading", **_mac_profile(pool_gib=14.0)) - assert _fast_durations(1024, 576, (5, 6, 8, 10, 20), **kwargs) == [5, 6, 8, 10] - assert _fast_durations(1920, 1088, (5, 10), **kwargs) == [] + """A 14 GiB MPS budget runs 1080p only in short windows, and 20 s needs more than five of them.""" + kwargs = dict(process_mode="streaming_models_loading", **_mac_profile(pool_gib=_cap(14.0))) + assert _fast_durations(1024, 576, (5, 6, 8, 10, 20), **kwargs) == [5, 6, 8, 10, 20] + assert _fast_durations(1920, 1088, (5, 10, 20), **kwargs) == [5, 10] + + +def test_mac_edit_ask_also_carries_the_loader_buffers() -> None: + """A pool that fits a 540p/5s retake's MPS ask alone must still refuse it.""" + mps_ask = _mac_edit_stream_required_gib(video_tokens(576, 1024, 121)) + + def edit(pool_gib: float) -> VideoJobDecision: + return _priced_edit_job( + 1024, 576, 121, + job_filter=_job_filter( + process_mode="streaming_models_loading", **_mac_profile(pool_gib=pool_gib) + ), + ) + + short = edit(mps_ask + 0.01) + assert isinstance(short, VideoJobReject) + assert short.reason == "stream_over" + assert isinstance(edit(mps_ask + _MAC_HOST_GIB + 0.01), VideoJobLoad) + + +def test_mac_over_figure_is_positive_when_only_the_loader_buffers_miss() -> None: + """11 GiB fits 540p/5s's 9.75 MPS floor but not floor + buffers: the refusal must + print the charged shortfall, not need-under-have.""" + job_filter = _job_filter(process_mode="streaming_models_loading", **_mac_profile(pool_gib=11.0)) + decision = _one_pass_priced(1024, 576, compute_num_frames(5, 24), job_filter=job_filter) + assert isinstance(decision, VideoJobReject) + assert decision.reason == "stream_over" + assert reject_over_gib(decision, job_filter) == approx(9.75 + _MAC_HOST_GIB - 11.0) + readout = budget_readout_for_reject(decision, job_filter) + assert readout is not None + assert readout.need_gb > readout.have_gb + + +def test_mac_future_model_prices_the_largest_known_block() -> None: + """A model id past the spec table pays the loader buffers instead of riding free.""" + + def ask(model_id: str) -> float: + decision = _priced_video_job( + 1024, 576, compute_num_frames(5, 24), + job_filter=_job_filter( + process_mode="streaming_models_loading", + **_mac_profile(pool_gib=107.52, model_id=model_id), + ), + ) + return decision.stream_gib + + largest = mac_disk_stream_host_gib(_WINDOWS_2_3_MODEL_ID) + assert largest > _MAC_HOST_GIB + assert ask("ltx-9.9-future") == approx(9.75 + largest) + assert ask(_FAST_2_5_MODEL_ID) == approx(9.75 + _MAC_HOST_GIB) def _windows_profile( @@ -2675,6 +2852,7 @@ def test_windows_25_unlisted_resolution_gets_finite_requirement() -> None: assert isinstance(decision, VideoJobLoad) +@pytest.mark.usefixtures("single_pass_only") def test_windows_25_16gib_grid_drops_720p20() -> None: """720p/20s needs 20.03 reserved (measured 19.53); 16 GB keeps the rest.""" profile = _windows_profile(vram_gib=16) @@ -2690,6 +2868,7 @@ def test_windows_25_16gib_grid_drops_720p20() -> None: ) == [5] +@pytest.mark.usefixtures("single_pass_only") def test_windows_25_12gib_grid_serves_limited_cells() -> None: profile = _windows_profile(vram_gib=12) @@ -2748,7 +2927,7 @@ def test_windows_25_supported_mode_empty_grid_when_free_below_smallest_cell() -> ): outcome = decide_fast_durations(width, height, 24, durations, job_filter=job_filter) assert outcome.kept == [] - assert set(outcome.rejected.values()) == {"stream_over"} + assert set(_refused_reasons(outcome).values()) == {"stream_over"} def test_linux_12gib_keeps_generic_curve_subset() -> None: @@ -2789,6 +2968,7 @@ def test_windows_23_streaming_ram_floor_matches_25() -> None: assert isinstance(fits, VideoJobLoad) +@pytest.mark.usefixtures("single_pass_only") def test_windows_23_12gib_matches_25_measured_grid() -> None: # The bug is Windows 2.3 staying on the rough curve and keeping a 720p/10s # cell that 2.5 refuses at 12 GB. @@ -2805,6 +2985,7 @@ def test_windows_23_12gib_matches_25_measured_grid() -> None: ) == [] +@pytest.mark.usefixtures("single_pass_only") def test_windows_25_23gib_unlocks_1080p10_and_22gib_does_not() -> None: full = _windows_profile(vram_gib=23) assert _fast_durations( @@ -2820,6 +3001,7 @@ def test_windows_25_23gib_unlocks_1080p10_and_22gib_does_not() -> None: ) == [5] +@pytest.mark.usefixtures("single_pass_only") def test_windows_25_vram_boundaries_are_strict_per_cell() -> None: import math @@ -2861,6 +3043,7 @@ def test_windows_25_vram_boundaries_are_strict_per_cell() -> None: ) == [5] +@pytest.mark.usefixtures("single_pass_only") def test_windows_25_unknown_vram_bytes_falls_back_to_integer_gb() -> None: """Bytes-probe glitch with a viable integer figure: evaluate, don't empty. @@ -2888,7 +3071,7 @@ def test_windows_25_unknown_vram_bytes_and_gb_fails_closed() -> None: def test_windows_25_oversize_cell_is_stream_over_not_unsupported() -> None: - decision = _video_job( + decision = _one_pass_job( 1920, 1088, 10, @@ -2928,12 +3111,12 @@ def test_windows_25_static_cells_load_or_refuse_with_copy_on_32gib() -> None: **profile, ), ) - assert set(outcome.kept) | set(outcome.rejected) == set(durations) - for duration, reason in outcome.rejected.items(): + assert set(outcome.kept) | set(_refused_reasons(outcome)) == set(durations) + for duration, reason in _refused_reasons(outcome).items(): # Measured profiles always compare a figure: the refusal must # carry it for picker copy, never vanish silently. assert reason != "unsupported" - assert duration in outcome.rejects + assert duration in outcome.refused assert reason != "unmeasured_cell" # every static 1440p and 4K cell has a run refused.add((resolution, aspect, duration)) @@ -3001,15 +3184,15 @@ def test_windows_25_cpu_path_ram_floor_stays_40(drive_type: str) -> None: assert below_floor.reason == "ram_shortfall" -def test_windows_25_disk_path_ram_floor_is_32() -> None: - """NVMe maps from disk (~5 GB committed), so the floor drops to 32, strict below 31.""" +def test_windows_25_disk_path_ram_floor_is_24() -> None: + """NVMe streams from disk (~5–6 GB working set), so the floor drops to 24, strict below 23.""" at_floor = _video_job( 1024, 576, 5, memory_gb=16, process_mode="streaming_models_loading", - **_windows_profile(vram_gib=16, total_ram_gib=32, drive_type="nvme"), + **_windows_profile(vram_gib=16, total_ram_gib=24, drive_type="nvme"), ) assert isinstance(at_floor, VideoJobLoad) @@ -3019,7 +3202,7 @@ def test_windows_25_disk_path_ram_floor_is_32() -> None: 5, memory_gb=16, process_mode="streaming_models_loading", - **_windows_profile(vram_gib=16, total_ram_gib=31.5, drive_type="nvme"), + **_windows_profile(vram_gib=16, total_ram_gib=23.5, drive_type="nvme"), ) assert isinstance(within_headroom, VideoJobLoad) @@ -3029,7 +3212,7 @@ def test_windows_25_disk_path_ram_floor_is_32() -> None: 5, memory_gb=16, process_mode="streaming_models_loading", - **_windows_profile(vram_gib=16, total_ram_gib=31 - 1 / _GIB, drive_type="nvme"), + **_windows_profile(vram_gib=16, total_ram_gib=23 - 1 / _GIB, drive_type="nvme"), ) assert isinstance(below_floor, VideoJobReject) assert below_floor.reason == "ram_shortfall" @@ -3062,7 +3245,7 @@ def test_windows_25_disk_and_cpu_paths_disagree_at_36gib_ram() -> None: def test_linux_streaming_ignores_ram_and_drive() -> None: """No RAM gate off the Windows Fast profile: a VRAM-over cell is stream_over, never shortfall.""" - decision = _video_job( + decision = _one_pass_job( 1280, 704, 20, @@ -3095,6 +3278,7 @@ def test_windows_streaming_ram_threshold_matches_linux_cpu_offload_floor() -> No assert WINDOWS_FAST_STREAMING_RAM_BYTES == CUDA_CPU_OFFLOAD_RAM_FLOOR_GB * _GIB +@pytest.mark.usefixtures("single_pass_only") def test_windows_25_free_vram_restricts_advertised_cells() -> None: profile = _windows_profile(vram_gib=16) busy = dict(profile, free_vram_bytes=int(11.0 * _GIB)) @@ -3128,7 +3312,7 @@ def test_windows_25_unknown_free_vram_falls_back_to_total() -> None: def test_windows_25_cell_over_free_vram_is_stream_over() -> None: - decision = _video_job( + decision = _one_pass_job( 1280, 704, 20, @@ -3143,7 +3327,7 @@ def test_windows_25_cell_over_free_vram_is_stream_over() -> None: def test_windows_fast_540p20_refuses_paging_cell_on_12gb() -> None: """Allocated ask 10.86 admits at free 11.5, but native reserved is 14.64; must refuse.""" - decision = _video_job( + decision = _one_pass_job( 1024, 576, 20, @@ -3158,7 +3342,7 @@ def test_windows_fast_540p20_refuses_paging_cell_on_12gb() -> None: def test_windows_fast_1080p5_refuses_paging_cell_on_12gb() -> None: """Allocated ask 10.20 admits at free 11.5, but native reserved is 13.61; must refuse.""" - decision = _video_job( + decision = _one_pass_job( 1920, 1088, 5, @@ -3202,7 +3386,7 @@ def test_windows_fast_floor_keeps_idle_10gb_for_540p5() -> None: def test_windows_25_free_vram_cannot_expand_beyond_total() -> None: - decision = _video_job( + decision = _one_pass_job( 1920, 1088, 10, @@ -3324,6 +3508,7 @@ def test_windows_25_budget_accepts_non_24fps_frame_counts() -> None: assert isinstance(decision, VideoJobLoad) +@pytest.mark.usefixtures("single_pass_only") def test_windows_25_portrait_matches_landscape_at_boundary() -> None: """9:16 is the same latent geometry (identical tokens, identical requirement).""" import math @@ -3386,6 +3571,7 @@ def test_linux_and_darwin_keep_existing_envelopes() -> None: assert darwin == [] +@pytest.mark.usefixtures("single_pass_only") def test_windows_23_keeps_existing_generic_curve() -> None: kept = _fast_durations( 1280, @@ -3492,10 +3678,9 @@ def test_list_time_layout_to_render_prices_the_look_still() -> None: ] -def test_with_budgeted_duration_two_stage_drops_unmeasured_durations() -> None: - """Two-stage is priced through the 14,880-token ceiling (D4): at the 1080p - preview only the 20s cell (29,280 tokens) drops, so the list never offers - what generate fences.""" +def test_with_budgeted_duration_two_stage_prices_past_the_ceiling_on_the_curve() -> None: + """Two-stage is measured through the 14,880-token ceiling (D4): at the 1080p + preview only the 20s cell (29,280 tokens) drops, with the curve's figures.""" out = with_budgeted_duration_controls( _catalog_item_two_stage(), job_filter=_windows_measured_filter(31, 64, free_gib=31.0), @@ -3504,7 +3689,7 @@ def test_with_budgeted_duration_two_stage_drops_unmeasured_durations() -> None: assert duration.options == [5, 8, 10] assert duration.dropped_options is not None assert [(d.value, d.reason) for d in duration.dropped_options] == [ - (20, "two_stage_over_measured") + (20, "stream_over") ] @@ -3532,10 +3717,11 @@ def test_with_budgeted_duration_drops_carry_tier_and_over_gib() -> None: over = next(d for d in duration.dropped_options if d.reason == "stream_over") assert over.tier == "over" assert over.over_gib is not None and over.over_gib > 0 - measured = [d for d in duration.dropped_options if d.reason == "two_stage_over_measured"] - for drop in measured: + untested = [d for d in duration.dropped_options if d.reason == "unmeasured_cell"] + for drop in untested: assert drop.tier == "unmeasured" assert drop.over_gib is None + assert drop.unmeasured_basis is not None def test_catalog_output_fps_coerces_junk_to_default() -> None: @@ -3552,19 +3738,13 @@ def test_tight_band_marks_headroom_under_max_floor_and_ratio() -> None: job_filter = _windows_measured_filter(14.5, 48) decision = VideoJobLoad(mode="streaming_models_loading", seq=1000.0, full_gib=20.0, stream_gib=14.14) assert load_headroom_gib(decision, job_filter) == approx(0.36) - assert load_risk_tier(decision, job_filter, feature="fast") == "tight" + assert is_tight_fit(decision, job_filter) def test_headroom_past_the_band_is_fit_not_tight() -> None: job_filter = _windows_measured_filter(16.0, 48) decision = VideoJobLoad(mode="streaming_models_loading", seq=1000.0, full_gib=20.0, stream_gib=14.14) - assert load_risk_tier(decision, job_filter, feature="fast") is None - - -def test_legacy_route_load_is_unmeasured_not_fit() -> None: - job_filter = _job_filter(memory_gb=31, process_mode="streaming_models_loading") - decision = VideoJobLoad(mode="streaming_models_loading", seq=1000.0, full_gib=20.0, stream_gib=10.0) - assert load_risk_tier(decision, job_filter, feature="fast") == "unmeasured" + assert not is_tight_fit(decision, job_filter) def test_unknown_figures_stay_silent_not_tight() -> None: @@ -3605,7 +3785,7 @@ def test_unsupported_has_no_risk_tier() -> None: def test_mps_fence_has_no_risk_tier() -> None: - # The bug is reckless tiering the MPS sequence fence (an uncatchable + # The bug is Brave tiering the MPS sequence fence (an uncatchable # SIGABRT, not a bet) as over-budget and allowing a fenced job. job_filter = _windows_measured_filter(31, 48) decision = VideoJobReject( @@ -3625,7 +3805,7 @@ def test_mac_fast_over_mps_fence_refuses_with_fixed_copy() -> None: job_filter = _job_filter( process_mode="streaming_models_loading", **_mac_profile(pool_gib=107.52) ) - decision = decide_video_job( + decision = _one_pass_priced( 1920, 1088, compute_num_frames(20, 50), job_filter=job_filter ) assert isinstance(decision, VideoJobReject) @@ -3637,7 +3817,7 @@ def test_mac_fast_over_mps_fence_refuses_with_fixed_copy() -> None: def test_mac_fast_at_mps_fence_boundary_loads() -> None: """Off-by-one guard: exactly 116,000 tokens loads, one frame past it refuses.""" assert video_tokens(1280, 1600, 457) == 116_000 - load = decide_video_job( + load = _one_pass_priced( 1600, 1280, 457, @@ -3646,7 +3826,7 @@ def test_mac_fast_at_mps_fence_boundary_loads() -> None: ), ) assert isinstance(load, VideoJobLoad) - refuse = decide_video_job( + refuse = _one_pass_priced( 1600, 1280, 458, @@ -3660,7 +3840,7 @@ def test_mac_fast_at_mps_fence_boundary_loads() -> None: def test_mac_fence_binds_before_pool_shortfall() -> None: """A job past both the fence and the pool reports the fence — pool GB figures would mislead.""" - decision = _video_job( + decision = _one_pass_job( 1920, 1088, 20, 50, process_mode="streaming_models_loading", **_mac_profile(pool_gib=24.0), @@ -3699,3 +3879,59 @@ def test_iclora_dropped_message_for_mps_fence_is_fixed_copy() -> None: ) message, code = dropped_duration_message_and_code(decision, job_filter) assert (message, code) == (MPS_SEQUENCE_OVER_MESSAGE, VIDEO_JOB_TOO_LARGE) + + +def test_total_only_uses_startup_usable_vram_when_lower_than_total() -> None: + """Picker/queue total_only must gate against startup usable VRAM so an OS/display reserve is not offered and then refused at execute.""" + budget = MemoryBudget( + total_vram_bytes=24 * _GIB, + usable_vram_bytes=int(22.4 * _GIB), + free_vram_bytes=int(18.0 * _GIB), + total_ram_bytes=64 * _GIB, + memory_gb=24.0, + mps_pool_bytes=None, + total_only=True, + ) + assert budget.total_vram_gib == pytest.approx(24.0) + assert budget.usable_vram_gib == pytest.approx(22.4) + assert budget.available_vram_gib == pytest.approx(22.4) + profile = HardwareProfile( + system="Windows", + model_id="ltx-2.5-22b-distilled", + process_mode="streaming_models_loading", + ) + cautious_filter = LocalJobFilter(profile=profile, budget=budget, budget_mode="cautious") + # 1080p / 10 s at 25 fps (249 frames) asks ~23.28 GiB in one pass (> 22.4 usable), + # so auto splits it into 2 parts (~22.14 GiB) and admits it in Cautious mode. + admitted = decide_video_job(1920, 1088, 249, job_filter=cautious_filter) + assert isinstance(admitted, Admitted) + assert admitted.priced.shape.windows == 2 + # In Brave mode, the 1-pass alternative is offered with an "over" bet. + brave_filter = replace(cautious_filter, budget_mode="brave") + alt = price_alternative_pass(1920, 1088, 249, job_filter=brave_filter, auto=admitted.priced) + assert alt is not None and alt.shape.windows == 1 + assert alt.over_risk is not None and alt.over_risk.tier == "over" + # Forcing one_pass in Cautious refuses with the card-ceiling message (not "free right now"). + one_pass_filter = replace(cautious_filter, pass_shape="one_pass") + refused = decide_video_job(1920, 1088, 249, job_filter=one_pass_filter) + assert isinstance(refused, Refused) + assert isinstance(refused.reject, VideoJobReject) + assert reject_shortfall_kind(refused.reject, one_pass_filter) == "total" + readout = budget_readout_for_reject(refused.reject, one_pass_filter) + assert readout is not None and readout.kind == "gpu" + assert readout.have_gb == pytest.approx(22.4) + msg, code = reject_message_and_code(refused.reject, one_pass_filter) + assert code == VIDEO_JOB_TOO_LARGE + assert "this card has 22.4 GB" in msg + assert "free right now" not in msg + # At execute time (total_only=False) on an idle card (free == usable == 22.4 GiB), + # a 23.3 GiB reject is still classified as "total", not "free" / "gpu_busy". + exec_filter = replace( + one_pass_filter, + budget=replace(budget, total_only=False, free_vram_bytes=int(22.4 * _GIB)), + ) + assert reject_shortfall_kind(refused.reject, exec_filter) == "total" + exec_readout = budget_readout_for_reject(refused.reject, exec_filter) + assert exec_readout is not None and exec_readout.kind == "gpu" + + diff --git a/backend/tests/test_video_resolution.py b/backend/tests/test_video_resolution.py index d0ac2f48f..7d85e53e2 100644 --- a/backend/tests/test_video_resolution.py +++ b/backend/tests/test_video_resolution.py @@ -117,3 +117,17 @@ def test_correct_frame_count_trims_down_to_8k_plus_1(): def test_correct_frame_count_rejects_too_short(): with pytest.raises(HTTPError): correct_frame_count(8) + + +def test_home_edit_size_snaps_odd_edges_to_even(): + # The frontend sends 635x360 for a 360p retake of a 960x544 clip (360 * 960/544 = 635.3). + # libx264 with yuv420p cannot encode an odd edge, so the picture size comes back even. + assert resolve_home_edit_size(635, 360, 960, 544) == (636, 360) + assert resolve_home_edit_size(361, 203, 960, 544) == (362, 204) + + +def test_home_edit_size_keeps_even_edges_and_the_source_bound(): + assert resolve_home_edit_size(640, 360, 960, 544) == (640, 360) + assert resolve_home_edit_size(None, None, 960, 544) == (960, 544) + # Never larger than the (even) source. + assert resolve_home_edit_size(1920, 1088, 960, 544) == (960, 544) diff --git a/backend/tests/test_windows_fast_queued.py b/backend/tests/test_windows_fast_queued.py index 364bd268c..9b9efb325 100644 --- a/backend/tests/test_windows_fast_queued.py +++ b/backend/tests/test_windows_fast_queued.py @@ -345,6 +345,7 @@ def test_windows_low_ram_rejects_queued_fast_before_insert( ("i2v", "1080p", 10, 18.0), ], ) +@pytest.mark.usefixtures("single_pass_only") def test_windows_over_envelope_rejects_queued_fast_before_insert( test_state, create_fake_model_files, @@ -446,6 +447,7 @@ def test_linux_queued_t2v_still_enqueues_stream_over_cell( test_state.config.vram_bytes = 16 * _GIB test_state.config.total_ram_bytes = 32 * _GIB test_state.config.local_generations_mode = "streaming_models_loading" + test_state.state.app_settings.budget_mode = "brave" with _surface_client(test_state, "home") as (client, headers): response = client.post( @@ -456,10 +458,12 @@ def test_linux_queued_t2v_still_enqueues_stream_over_cell( assert response.status_code == 200, response.text assert response.json()["status"] == "queued" + assert response.json()["risk"] is not None assert len(_store(test_state).list_generations("text-to-video")) == 1 @pytest.mark.parametrize("surface", ["home", "remote"]) +@pytest.mark.usefixtures("single_pass_only") def test_windows_queued_21_9_refuses_before_insert_where_16_9_enqueues( test_state, create_fake_model_files, surface: str ) -> None: @@ -535,7 +539,7 @@ def test_windows_queued_auto_fully_dropped_cell_names_figures_not_unsupported( status_code=422, code=VIDEO_JOB_TOO_LARGE, message=( - "This job needs 77.0 GB of GPU memory but this card has 8.0 GB. " + "This job needs 11.2 GB of GPU memory but this card has 8.0 GB. " "Lower the resolution, duration, frame rate, or aspect width." ), ) @@ -543,6 +547,7 @@ def test_windows_queued_auto_fully_dropped_cell_names_figures_not_unsupported( @pytest.mark.parametrize("surface", ["home", "remote"]) +@pytest.mark.usefixtures("single_pass_only") def test_windows_queued_i2v_auto_resolves_start_frame_before_insert( test_state, create_fake_model_files, tmp_path: Path, surface: str ) -> None: @@ -583,6 +588,7 @@ def test_windows_queued_i2v_auto_resolves_start_frame_before_insert( @pytest.mark.parametrize("surface", ["home", "remote"]) +@pytest.mark.usefixtures("single_pass_only") def test_windows_queued_recipe_21_9_refuses_before_insert_where_16_9_enqueues( test_state, create_fake_model_files, surface: str, monkeypatch ) -> None: @@ -621,6 +627,7 @@ def test_windows_queued_recipe_21_9_refuses_before_insert_where_16_9_enqueues( @pytest.mark.parametrize("surface", ["home", "remote"]) +@pytest.mark.usefixtures("single_pass_only") def test_windows_queued_recipe_i2v_auto_resolves_start_frame_before_insert( test_state, create_fake_model_files, tmp_path: Path, surface: str, monkeypatch ) -> None: @@ -667,6 +674,7 @@ def test_windows_queued_recipe_i2v_auto_resolves_start_frame_before_insert( @pytest.mark.parametrize("surface", ["home", "remote"]) +@pytest.mark.usefixtures("single_pass_only") def test_windows_queued_a2v_21_9_refuses_before_insert_where_16_9_enqueues( test_state, create_fake_model_files, tmp_path: Path, surface: str ) -> None: @@ -707,6 +715,7 @@ def test_windows_queued_a2v_21_9_refuses_before_insert_where_16_9_enqueues( @pytest.mark.parametrize("surface", ["home", "remote"]) +@pytest.mark.usefixtures("single_pass_only") def test_windows_queued_a2v_auto_resolves_start_frame_before_insert( test_state, create_fake_model_files, tmp_path: Path, surface: str ) -> None: diff --git a/backend/tests/test_zit_queue_client.py b/backend/tests/test_zit_queue_client.py new file mode 100644 index 000000000..676ab2c8f --- /dev/null +++ b/backend/tests/test_zit_queue_client.py @@ -0,0 +1,388 @@ +"""The fal queue client: submit, poll, fetch, cancel. + +Each test names the bug it catches. +""" + +from __future__ import annotations + +import pytest + +from api_types import ApiActivityStatus +from services.generation_interrupt import GenerationCancelledError +from services.http_client.http_client import HttpTransportError +from services.zit_api_client.zit_api_client import ZitImageBlockedError +from services.zit_api_client import zit_api_client_impl +from services.zit_api_client.zit_api_client_impl import ZitAPIClientImpl +from tests.fakes import FakeResponse +from tests.fakes.services import FakeHTTPClient + +_STATUS_URL = "https://queue.fal.run/fal-ai/z-image/requests/r1/status" +_RESULT_URL = "https://queue.fal.run/fal-ai/z-image/requests/r1" +_CANCEL_URL = "https://queue.fal.run/fal-ai/z-image/requests/r1/cancel" +_IMAGE_URL = "https://fal.test/out.png" +_SUBMITTED = { + "request_id": "r1", + "status_url": _STATUS_URL, + "response_url": _RESULT_URL, + "cancel_url": _CANCEL_URL, +} + + +def _status(value: str, **extra: object) -> FakeResponse: + return FakeResponse(status_code=200, json_payload={"status": value, **extra}) + + +def _result(**extra: object) -> FakeResponse: + payload = {"images": [{"url": _IMAGE_URL}], "has_nsfw_concepts": [False], **extra} + return FakeResponse(status_code=200, json_payload=payload) + + +def _client(http: FakeHTTPClient, *, timeout: float = 30.0) -> ZitAPIClientImpl: + return ZitAPIClientImpl(http, queue_poll_interval_seconds=0.0, queue_timeout_seconds=timeout) + + +def _submit( + client: ZitAPIClientImpl, + *, + expansion: bool = False, + on_status=None, + on_submitted=None, + wait_cancelled=None, +): + return client.generate_text_to_image_queued( + api_key="k", + prompt="a fox", + width=512, + height=512, + seed=1, + num_inference_steps=8, + enable_prompt_expansion=expansion, + on_status=on_status or (lambda _status: None), + on_submitted=on_submitted or (lambda _request_id: True), + wait_cancelled=wait_cancelled or (lambda _seconds: False), + ) + + +def _queue_happy_path(http: FakeHTTPClient, *polls: FakeResponse, result: FakeResponse | None = None) -> None: + http.queue("post", FakeResponse(status_code=200, json_payload=_SUBMITTED)) + http.queue("get", *polls, result or _result(), FakeResponse(content=b"png-bytes")) + + +def test_the_urls_fal_returns_are_used_not_built_ones() -> None: + # Bug caught: the client rebuilds the status and result URLs and misses a sub-path endpoint. + http = FakeHTTPClient() + _queue_happy_path(http, _status("COMPLETED")) + + image = _submit(_client(http)) + + assert image.image_bytes == b"png-bytes" + assert [(call.method, call.url) for call in http.calls] == [ + ("post", "https://queue.fal.run/fal-ai/z-image/turbo"), + ("get", _STATUS_URL), + ("get", _RESULT_URL), + ("get", _IMAGE_URL), + ] + + +@pytest.mark.parametrize("expansion", [False, True]) +def test_the_expansion_flag_reaches_the_request(expansion: bool) -> None: + # Bug caught: enable_prompt_expansion is dropped, so fal bills or skips an expansion by accident. + http = FakeHTTPClient() + _queue_happy_path(http, _status("COMPLETED")) + + _submit(_client(http), expansion=expansion) + + payload = http.calls[0].json_payload + assert payload is not None and payload["enable_prompt_expansion"] is expansion + + +def test_fal_statuses_map_to_the_api_activity_statuses() -> None: + # Bug caught: the panel shows the wrong provider phase, or none. + http = FakeHTTPClient() + _queue_happy_path(http, _status("IN_QUEUE"), _status("IN_PROGRESS"), _status("COMPLETED")) + seen: list[ApiActivityStatus] = [] + + _submit(_client(http), on_status=seen.append) + + assert seen == ["pending", "processing"] + + +def test_the_prompt_fal_used_is_returned() -> None: + # Bug caught: an expanded prompt is lost, so the finished row shows only the typed prompt. + http = FakeHTTPClient() + _queue_happy_path(http, _status("COMPLETED"), result=_result(prompt="a fox, expanded")) + + assert _submit(_client(http), expansion=True).prompt == "a fox, expanded" + + +def test_an_error_on_a_completed_request_fails_and_cancels() -> None: + # Bug caught: COMPLETED with an error is read as a success and the result fetch fails oddly. + http = FakeHTTPClient() + http.queue("post", FakeResponse(status_code=200, json_payload=_SUBMITTED)) + http.queue("get", _status("COMPLETED", error="model crashed")) + http.queue("put", FakeResponse(status_code=400, text="ALREADY_COMPLETED")) + + with pytest.raises(RuntimeError, match="model crashed"): + _submit(_client(http)) + + assert http.calls[-1].method == "put" and http.calls[-1].url == _CANCEL_URL + + +def test_a_request_that_never_completes_times_out_and_is_cancelled() -> None: + # Bug caught: a stuck provider request holds the fal lane forever and keeps billing. + http = FakeHTTPClient() + http.queue("post", FakeResponse(status_code=200, json_payload=_SUBMITTED)) + http.queue("get", _status("IN_QUEUE")) + http.queue("put", FakeResponse(status_code=202)) + + with pytest.raises(RuntimeError, match="timed out"): + _submit(_client(http, timeout=0.0)) + + assert http.calls[-1].method == "put" and http.calls[-1].url == _CANCEL_URL + + +@pytest.mark.parametrize( + "cancel_response", + [FakeResponse(status_code=202), FakeResponse(status_code=400, text="ALREADY_COMPLETED")], + ids=["accepted", "already-completed"], +) +def test_cancel_stops_the_poll_and_asks_fal_to_drop_the_request(cancel_response: FakeResponse) -> None: + # Bug caught: a cancelled job keeps polling, or a 400 on cancel replaces the cancel error. + http = FakeHTTPClient() + http.queue("post", FakeResponse(status_code=200, json_payload=_SUBMITTED)) + http.queue("get", _status("IN_PROGRESS")) + http.queue("put", cancel_response) + + answers = iter([False, True]) + + with pytest.raises(GenerationCancelledError): + _submit(_client(http), wait_cancelled=lambda _seconds: next(answers)) + + assert [call.method for call in http.calls] == ["post", "get", "put"] + assert http.calls[-1].url == _CANCEL_URL + + +def test_a_failed_cancel_request_does_not_hide_the_cancel() -> None: + # Bug caught: a transport error on the cancel call turns a cancel into a failure. + http = FakeHTTPClient() + http.queue("post", FakeResponse(status_code=200, json_payload=_SUBMITTED)) + http.queue("get", _status("IN_QUEUE")) + http.queue("put", HttpTransportError("down")) + answers = iter([False, True]) + + with pytest.raises(GenerationCancelledError): + _submit(_client(http), wait_cancelled=lambda _seconds: next(answers)) + + +def test_one_dropped_status_check_is_not_an_error() -> None: + # Bug caught: a single network blip fails a job that fal still runs. + http = FakeHTTPClient() + http.queue("post", FakeResponse(status_code=200, json_payload=_SUBMITTED)) + http.queue("get", HttpTransportError("blip"), _status("COMPLETED"), _result(), FakeResponse(content=b"png")) + + assert _submit(_client(http)).image_bytes == b"png" + + +def test_three_dropped_status_checks_in_a_row_fail_the_job() -> None: + # Bug caught: the client polls a dead connection forever. + http = FakeHTTPClient() + http.queue("post", FakeResponse(status_code=200, json_payload=_SUBMITTED)) + http.queue("get", *[HttpTransportError("down")] * 3) + http.queue("put", FakeResponse(status_code=202)) + + with pytest.raises(RuntimeError, match="status check failed"): + _submit(_client(http)) + + +@pytest.mark.parametrize( + "result", + [ + FakeResponse(json_payload={"images": [], "has_nsfw_concepts": []}), + FakeResponse(json_payload={"images": [{"url": _IMAGE_URL}], "has_nsfw_concepts": [True]}), + ], + ids=["no-images", "nsfw-flag-on-black-image"], +) +def test_a_blocked_result_raises_instead_of_returning_the_placeholder(result: FakeResponse) -> None: + # Bug caught: a black placeholder from the safety checker is saved as the user's image. + http = FakeHTTPClient() + http.queue("post", FakeResponse(status_code=200, json_payload=_SUBMITTED)) + http.queue("get", _status("COMPLETED"), result) + + with pytest.raises(ZitImageBlockedError): + _submit(_client(http)) + + # The request finished. There is nothing to cancel at the provider. + assert [call.method for call in http.calls] == ["post", "get", "get"] + + +@pytest.mark.parametrize("key", ["status_url", "response_url", "cancel_url"]) +def test_a_response_url_on_another_host_is_refused_so_the_key_is_never_sent_there(key: str) -> None: + # Bug caught: the client sends the fal API key to whatever host the submit response names. + http = FakeHTTPClient() + http.queue( + "post", + FakeResponse(status_code=200, json_payload={**_SUBMITTED, key: "https://evil.example/steal"}), + ) + + with pytest.raises(RuntimeError, match="unexpected host"): + _submit(_client(http)) + + assert [call.method for call in http.calls] == ["post"] + + +def test_a_status_page_that_is_not_json_is_retried_like_any_transient_failure() -> None: + # Bug caught: a proxy page with status 200 raises ValueError and ends a job fal still runs. + http = FakeHTTPClient() + http.queue("post", FakeResponse(status_code=200, json_payload=_SUBMITTED)) + http.queue( + "get", + FakeResponse(status_code=200, json_raises=True), + _status("COMPLETED"), + _result(), + FakeResponse(content=b"png-bytes"), + ) + + assert _submit(_client(http)).image_bytes == b"png-bytes" + + +@pytest.mark.parametrize( + ("answers", "expected_methods"), + [ + ([True], ["post", "put"]), + ([False, True], ["post", "get", "put"]), + ([False, False, True], ["post", "get", "get", "put"]), + ], + ids=["cancel-before-status", "cancel-before-result", "cancel-before-download"], +) +def test_a_cancel_that_lands_during_a_request_stops_before_the_next_one( + answers: list[bool], expected_methods: list[str] +) -> None: + # Bug caught: a cancel during a request still runs the next status, result or download request. + http = FakeHTTPClient() + _queue_happy_path(http, _status("COMPLETED")) + http.queue("put", FakeResponse(status_code=400, text="ALREADY_COMPLETED")) + remaining = iter(answers) + + with pytest.raises(GenerationCancelledError): + _submit(_client(http), wait_cancelled=lambda _seconds: next(remaining)) + + assert [call.method for call in http.calls] == expected_methods + assert _IMAGE_URL not in [call.url for call in http.calls] + + +def test_the_request_id_is_reported_before_the_first_status_check() -> None: + # Bug caught: the id is stored late, so a crash during the first poll leaves a request fal still runs. + http = FakeHTTPClient() + _queue_happy_path(http, _status("COMPLETED")) + seen_calls: list[int] = [] + + _submit( + _client(http), + on_submitted=lambda request_id: seen_calls.append(len(http.calls)) or request_id == "r1", + ) + + assert seen_calls == [1] # Only the submit had run. + + +def test_a_request_id_that_is_not_stored_cancels_the_request_at_once() -> None: + # Bug caught: a boot cannot cancel a request it has no id for, so fal keeps running and billing it. + http = FakeHTTPClient() + http.queue("post", FakeResponse(status_code=200, json_payload=_SUBMITTED)) + http.queue("put", FakeResponse(status_code=202)) + + with pytest.raises(RuntimeError, match="not stored"): + _submit(_client(http), on_submitted=lambda _request_id: False) + + assert [(call.method, call.url) for call in http.calls] == [ + ("post", "https://queue.fal.run/fal-ai/z-image/turbo"), + ("put", _CANCEL_URL), + ] + + +@pytest.mark.parametrize("request_id", [None, "", "../x", "a/b", "a b"]) +def test_a_submit_response_without_a_usable_request_id_fails_before_any_poll(request_id: object) -> None: + # Bug caught: a bad id reaches the store and later becomes part of a cancel URL. + http = FakeHTTPClient() + http.queue("post", FakeResponse(status_code=200, json_payload={**_SUBMITTED, "request_id": request_id})) + + with pytest.raises(RuntimeError, match="request_id"): + _submit(_client(http)) + + assert [call.method for call in http.calls] == ["post"] + + +@pytest.mark.parametrize("status", [200, 202, 400, 404]) +def test_a_boot_cancel_uses_the_url_fal_returns_and_accepts_every_done_status(status: int) -> None: + # Bug caught: the derived cancel URL drifts from the one fal returns, so a boot cancel hits nothing. + http = FakeHTTPClient() + http.queue("put", FakeResponse(status_code=status)) + + _client(http).cancel_queued(api_key="k", request_id="r1") + + assert [(call.method, call.url) for call in http.calls] == [("put", _CANCEL_URL)] + assert http.calls[0].headers is not None and http.calls[0].headers["Authorization"] == "Key k" + + +@pytest.mark.parametrize("status", [401, 429, 500, 503]) +def test_a_boot_cancel_that_fails_raises_so_the_id_is_kept(status: int) -> None: + # Bug caught: a failed cancel is read as done, the id is cleared and the request runs on. + http = FakeHTTPClient() + http.queue("put", FakeResponse(status_code=status)) + + with pytest.raises(RuntimeError, match=str(status)): + _client(http).cancel_queued(api_key="k", request_id="r1") + + +def test_a_boot_cancel_refuses_an_id_that_is_not_a_request_id() -> None: + # Bug caught: an id with a path in it sends the key to another fal path. + http = FakeHTTPClient() + + with pytest.raises(ValueError): + _client(http).cancel_queued(api_key="k", request_id="../../x") + + assert http.calls == [] + + +def _queue_result_then_image(http: FakeHTTPClient, image_url: str, image: FakeResponse) -> None: + http.queue("post", FakeResponse(status_code=200, json_payload=_SUBMITTED)) + http.queue( + "get", + _status("COMPLETED"), + FakeResponse(status_code=200, json_payload={"images": [{"url": image_url}]}), + image, + ) + + +def test_an_image_url_that_is_not_https_is_not_fetched() -> None: + # Bug caught: a plain-http or file-like URL in the fal result is fetched (CWE-918). + http = FakeHTTPClient() + _queue_result_then_image(http, "http://fal.test/out.png", FakeResponse(content=b"png-bytes")) + + with pytest.raises(RuntimeError, match="not https"): + _submit(_client(http)) + + assert "http://fal.test/out.png" not in [call.url for call in http.calls] + + +def test_an_image_larger_than_the_cap_fails_the_job(monkeypatch: pytest.MonkeyPatch) -> None: + # Bug caught: a huge body from fal is read whole into memory (CWE-770). + monkeypatch.setattr(zit_api_client_impl, "_MAX_IMAGE_DOWNLOAD_BYTES", 8) + http = FakeHTTPClient() + _queue_result_then_image(http, _IMAGE_URL, FakeResponse(content=b"123456789")) + + with pytest.raises(RuntimeError, match="too large"): + _submit(_client(http)) + + +def test_a_failed_download_shows_the_status_and_not_the_body() -> None: + # Bug caught: the provider body lands in the job error that the user and the logs show (CWE-209). + http = FakeHTTPClient() + _queue_result_then_image( + http, _IMAGE_URL, FakeResponse(status_code=500, text="internal detail: token abc") + ) + + with pytest.raises(RuntimeError) as raised: + _submit(_client(http)) + + assert "500" in str(raised.value) + assert "internal detail" not in str(raised.value) diff --git a/backend/uv.lock b/backend/uv.lock index cc6e206a1..3b7738507 100644 --- a/backend/uv.lock +++ b/backend/uv.lock @@ -18,12 +18,12 @@ supported-markers = [ [[manifest.dependency-metadata]] name = "ltx-core" -version = "1.4.1" -requires-dist = ["torch~=2.7", "torchaudio", "torchvision", "einops", "numpy", "colour-science", "av", "transformers>=5.8.0,<5.15", "safetensors", "accelerate", "scipy>=1.14", "mps-sdpa>=0.2.0 ; platform_machine == 'arm64' and sys_platform == 'darwin'"] +version = "1.6.0" +requires-dist = ["torch~=2.7", "torchaudio", "torchvision", "einops", "numpy", "colour-science", "transformers>=5.8.0,<5.15", "safetensors", "accelerate", "scipy>=1.14", "mps-sdpa>=0.2.0 ; platform_machine == 'arm64' and sys_platform == 'darwin'"] [[manifest.dependency-metadata]] name = "ltx-pipelines" -version = "1.4.1" +version = "1.6.0" requires-dist = ["ltx-core", "av", "tqdm", "pillow", "openimageio", "cloudpickle>=3.1"] [[package]] @@ -1150,11 +1150,10 @@ wheels = [ [[package]] name = "ltx-core" -version = "1.4.1" -source = { git = "https://github.com/Lightricks/LTX-2.git?subdirectory=packages%2Fltx-core&tag=v1.4.1#2d6e71c88be37b55a2dd698c2dff447edfbe5898" } +version = "1.6.0" +source = { git = "https://github.com/Lightricks/LTX-2.git?subdirectory=packages%2Fltx-core&tag=v1.6.0#c1b4675863c07c59c92e502446cccdaedbe5889c" } dependencies = [ { name = "accelerate", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "av", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, { name = "colour-science", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, { name = "einops", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, { name = "mps-sdpa", marker = "platform_machine == 'arm64' and sys_platform == 'darwin'" }, @@ -1200,6 +1199,7 @@ dependencies = [ { name = "pydantic-ai-slim", extra = ["google", "openai"], marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, { name = "pynvml", marker = "(python_full_version == '3.13.*' and sys_platform == 'win32') or (sys_platform != 'darwin' and sys_platform != 'win32')" }, { name = "python-multipart", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, + { name = "pyyaml", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, { name = "sageattention", version = "1.0.6", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform != 'darwin' and sys_platform != 'win32'" }, { name = "sageattention", version = "2.2.0+cu128torch2.10.0andhigher.post5", source = { url = "https://github.com/woct0rdho/SageAttention/releases/download/v2.2.0-windows.post5/sageattention-2.2.0+cu128torch2.10.0andhigher.post5-cp310-abi3-win_amd64.whl" }, marker = "python_full_version == '3.13.*' and sys_platform == 'win32'" }, { name = "sentencepiece", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, @@ -1243,8 +1243,8 @@ requires-dist = [ { name = "huggingface-hub", specifier = ">=0.23.0" }, { name = "imageio", specifier = ">=2.37.2" }, { name = "imageio-ffmpeg", specifier = ">=0.6.0" }, - { name = "ltx-core", git = "https://github.com/Lightricks/LTX-2.git?subdirectory=packages%2Fltx-core&tag=v1.4.1" }, - { name = "ltx-pipelines", git = "https://github.com/Lightricks/LTX-2.git?subdirectory=packages%2Fltx-pipelines&tag=v1.4.1" }, + { name = "ltx-core", git = "https://github.com/Lightricks/LTX-2.git?subdirectory=packages%2Fltx-core&tag=v1.6.0" }, + { name = "ltx-pipelines", git = "https://github.com/Lightricks/LTX-2.git?subdirectory=packages%2Fltx-pipelines&tag=v1.6.0" }, { name = "matplotlib", specifier = ">=3.8" }, { name = "natten", marker = "sys_platform == 'win32'", url = "https://storage.googleapis.com/ltx-desktop-artifacts/wheels/natten-0.21.6+torch2100cu128-cp313-cp313-win_amd64.whl" }, { name = "ninja", marker = "sys_platform == 'darwin'", specifier = ">=1.11" }, @@ -1260,6 +1260,7 @@ requires-dist = [ { name = "pytest", marker = "extra == 'test'", specifier = ">=8.0" }, { name = "pytest-split", marker = "extra == 'test'", specifier = ">=0.11.0" }, { name = "python-multipart", specifier = ">=0.0.32" }, + { name = "pyyaml", specifier = ">=6.0" }, { name = "requests", marker = "extra == 'test'", specifier = ">=2.34.2" }, { name = "sageattention", marker = "sys_platform != 'darwin' and sys_platform != 'win32'", specifier = ">=1.0.0" }, { name = "sageattention", marker = "sys_platform == 'win32'", url = "https://github.com/woct0rdho/SageAttention/releases/download/v2.2.0-windows.post5/sageattention-2.2.0+cu128torch2.10.0andhigher.post5-cp310-abi3-win_amd64.whl" }, @@ -1281,8 +1282,8 @@ provides-extras = ["test", "dev"] [[package]] name = "ltx-pipelines" -version = "1.4.1" -source = { git = "https://github.com/Lightricks/LTX-2.git?subdirectory=packages%2Fltx-pipelines&tag=v1.4.1#2d6e71c88be37b55a2dd698c2dff447edfbe5898" } +version = "1.6.0" +source = { git = "https://github.com/Lightricks/LTX-2.git?subdirectory=packages%2Fltx-pipelines&tag=v1.6.0#c1b4675863c07c59c92e502446cccdaedbe5889c" } dependencies = [ { name = "av", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, { name = "cloudpickle", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md index 77b8416bd..a7cb9a1ee 100644 --- a/docs/DEVELOPMENT.md +++ b/docs/DEVELOPMENT.md @@ -45,6 +45,7 @@ Pull requests must pass `pnpm typecheck`, `pnpm backend:test`, and the frontend - [`CONTRIBUTING.md`](CONTRIBUTING.md): how to contribute - [`backend/architecture.md`](../backend/architecture.md): backend architecture - [`remote-lan.md`](remote-lan.md): LAN Remote architecture -- [`local-compat-matrix.md`](local-compat-matrix.md): tool and hardware compatibility +- [`hardware-compatibility.md`](hardware-compatibility.md): what each GPU and Mac runs (canonical user-facing page) +- [`local-compat-matrix.md`](local-compat-matrix.md): tool and hardware compatibility (generated; never hand-edit) - [`INSTALLER.md`](INSTALLER.md): building installers - [`TELEMETRY.md`](TELEMETRY.md): telemetry and privacy diff --git a/docs/desktop-eta-calibration-report.md b/docs/desktop-eta-calibration-report.md new file mode 100644 index 000000000..bb4c18df7 --- /dev/null +++ b/docs/desktop-eta-calibration-report.md @@ -0,0 +1,123 @@ +# Desktop ETA calibration — Apple M5 Max + +Measured against `feat/desktop-eta` before `b9ef038`, then used to refit the Darwin coefficients in that commit. 23 local Fast generations, ConvVAE on, cautious budget, LTX 2.5 Fast, streaming from disk. Apple M5 Max, 40-core GPU, 128 GB unified memory. Prompts were sent as already-enhanced so Gemma rewrite time is not in the wall clock. + +`spec` is `estimated_seconds` from `GET /api/generate/models-specs` before the job. `est` is `POST /api/generate/estimate`. `start` is the first queue `remainingSeconds`. `wall` is `(finished_at - started_at) / 1000`. Stage splits are from the backend log: load ends at `Running denoising loop`, denoise ends at `Freed resident transformer`, decode is `Building video decoder` to `Video saved to`. + +## Runs + +| Run | Job | Wall s | Spec s | Est s | Start s | Factor after | +| --- | --- | ---: | ---: | ---: | ---: | ---: | +| 1 | T2V 270p 3s 16:9 | 33.3 | 58 | 58 | 58 | 0.25 | +| 2 | T2V 270p 3s 16:9 | 33.5 | 37 | 37 | 37 | 0.25 | +| 3 | T2V 360p 4s 16:9 | 60.6 | 45 | 45 | 45 | 0.52 | +| 4 | T2V 540p 5s 16:9 | 164.2 | 112 | 108 | 108 | 0.86 | +| 5 | T2V 270p 2s 16:9 | 32.7 | 47 | 47 | 47 | 0.25 | +| 6 | T2V 270p 5s 16:9 | 65.4 | 42 | 42 | 41 | 0.25 | +| 7 | T2V 360p 3s 16:9 | 59.5 | 41 | 41 | 41 | 0.25 | +| 8 | T2V 360p 6s 16:9 | 115.0 | 52 | 52 | 52 | 0.53 | +| 9 | T2V 540p 3s 16:9 | 114.3 | 82 | 82 | 82 | 0.53 | +| 10 | T2V 540p 8s 16:9 | 332.2 | 166 | 166 | 166 | 1.20 | +| 11 | T2V 540p 10s 16:9 | 407.9 | 418 | 418 | 418 | 1.17 | +| 12 | T2V 720p 5s 16:9 | 297.6 | 317 | 317 | 317 | 1.13 | +| 13 | T2V 720p 10s 16:9 | 655.9 | 640 | 572 | 572 | 1.16 | +| 14 | T2V 1080p 5s 16:9 | 773.0 | 816 | 841 | 841 | 1.09 | +| 15 | T2V 540p 5s 9:16 | 195.8 | 198 | 198 | 198 | 0.25 | +| 16 | T2V 540p 5s 1:1 | 106.6 | 55 | 55 | 54 | 0.25 | +| 17 | T2V 540p 5s 21:9 | 256.1 | 85 | 85 | 85 | 0.33 | +| 18a | T2V 360p 4s 4:3 | 59.4 | 44 | 44 | 44 | 0.25 | +| 18b | T2V 360p 4s 3:2 | 66.7 | 42 | 42 | 42 | 0.25 | +| 19 | T2V 540p 5s 48fps | 400.4 | 114 | 114 | 113 | 0.54 | +| 20 | T2V 1440p 5s 16:9 | 1596.8 | 853 | 853 | 852 | 1.03 | +| 21 | I2V 540p 5s 16:9 | 193.0 | 188 | 181 | 181 | 0.25 | +| 22 | A2V 540p (129 frames) | 207.1 | — | — | 74 | 0.25 | +| 23 | cozy-felt 540p 4s | 174.8 | — | — | 64 | 0.25 | +| 24 | Ingredients | not run | | | | | + +Run 24 returned `IC_LORA_HF_AUTH_REQUIRED`. The weights are on disk. Create still requires Hugging Face sign-in. + +A2V and cozy-felt have no separate pre-gen ETA in this log. The fast-grid lookup is the wrong surface for those routes. The start countdown above is what the queue actually showed. A2V audio produced 129 frames, not the 121 of a 5-second 24 fps text clip. + +1440p / 5s is one window. The first chunk candidate is 129 frames and the clip is 121, so the multi-window check did not apply. No cell was over the cautious budget. + +## Calibration did not converge + +The cold table, before any run, versus the wall times those cells later measured: + +| Cell | Cold spec s | Wall s | Error | +| --- | ---: | ---: | ---: | +| 270p 3s | 58 | 33.3 | +74% | +| 360p 4s | 88 | 60.6 | +45% | +| 540p 5s | 184 | 164.2 | +12% | + +Mean absolute error of those three cold specs: **44%**. + +After run 1 the factor clamped to the floor, 0.25. Specs became 37 / 45 / 72. Mean absolute error against the same three walls: **31%**. The 270p repeat got closer (37 vs 33.5, +10%). The other two got worse, because a single short clip cannot identify the machine when most of the prediction is a fixed 18 second load. + +Run 2 was the same 270p cell and did not move the frontier. The factor stayed 0.25. Run 3 then missed by 26% (45 vs 60.6). Run 4, after the factor had risen to 0.52, missed 540p by 32% (112 vs 164). + +Through phase B the live factor swung between the 0.25 floor and about 1.2. Mean absolute error of the pre-gen spec against wall for runs 5–21: **31%**. Long 16:9 cells taken while the factor sat near 1 were close (540p/10s +2%, 720p/5s +7%, 720p/10s −2%, 1080p/5s +6%). The same shapes taken after the factor had fallen back to 0.25 were not (540p/5s at 48 fps −72%, 1440p/5s −47% at factor 0.54). + +## Pre-gen spec versus the countdown at start + +`spec` and `start` matched within 5 seconds on every 270p and 360p run, and on most 540p runs. They did not on: + +| Run | Spec s | Start s | Gap | +| --- | ---: | ---: | ---: | +| 13 720p 10s | 640 | 572 | 68 s | +| 14 1080p 5s | 816 | 841 | 25 s | +| 21 I2V 540p 5s | 188 | 181 | 7 s | + +On those three the countdown followed `POST /api/generate/estimate`, not the models-specs cell. The button and the queue were different clocks. + +## Stages, old law at factor 1.0 + +Every run spent 3.5–5.0 seconds from job start to the denoising loop. The old law predicted 18 seconds of load on all of them. That single constant is why short clips looked impossibly fast and the factor pinned at 0.25. + +Denoise at factor 1.0 was within about 15% on 540p and above, and high on the shortest 270p and 360p clips (31 s predicted vs 21 s measured for 270p/3s). + +Decode was the other systematic miss. One rate for both passes under-predicted 540p–720p decode (540p/10s 137 s predicted vs 194 s measured, 720p/10s 226 vs 288) and, with the old quadratic, over-predicted 1440p (608 vs 567). 1080p decode was closer (281 vs 313). + +Log splits match the wall clock within a second on every run except 18a, where the decode marker latched onto the wrong `Video saved to` line. Use the wall time for that row, not the decode split. + +## Live countdown + +On run 1 the mid-denoise projection was better than the cold spec: `|58 − 33.3| = 25 s` at the start, `|14.9 + 17 − 33.3| = 1.5 s` at step 4/8. + +That did not hold once the factor was wrong, and it did not hold on long jobs even when the factor was near 1. The mid projection ran ahead of reality: + +| Run | Start error s | Mid projection error s | Decode countdown s | Actual decode s | +| --- | ---: | ---: | ---: | ---: | +| 1 270p 3s | +25 | −1.5 | 9 | 9.3 | +| 11 540p 10s | +10 | −110 | 163 | 195 | +| 12 720p 5s | +19 | −73 | 121 | 135 | +| 14 1080p 5s | +43 | −165 | 333 | 314 | +| 20 1440p 5s | −744 | −862 | 323 | 568 | + +1080p was the one long job whose decode countdown matched the remaining decode. Everywhere else the countdown at step N/N was short, because the decode term it was counting down was short. Samples show it decreasing. They do not show it reaching zero and sticking while the decoder was still running. The value was simply too small. + +## Aspect, frame rate, other routes + +540p / 5s walls: 16:9 164 s, 9:16 196 s, 1:1 107 s, 21:9 256 s. 9:16 has the same latent count as 16:9 and was 19% slower, so an ETA that equates them is wrong on this machine. 1:1 was faster and 21:9 was slower, in the right direction. The live specs for 1:1 (55 s) and 21:9 (85 s) were not, because the factor was on the floor. + +48 fps / 5s is 241 frames, the same count as 24 fps / 10s. Walls were 400 s and 408 s. Frame-count scaling holds. The live spec of 114 s did not. It was the floor factor, not the frame model. + +I2V 540p/5s took 193 s against the text-to-video 164 s. The spec of 188 s, taken while the factor was near 1, was close. A2V (129 frames) took 207 s and the queue opened at 74 s. Cozy-felt 540p/4s took 175 s and the queue opened at 64 s. Both countdowns were the floor-factor fast estimate, and both were far under the wall. + +## Refit + +`b9ef038` changes only the Darwin branch of `_stage_time_parts`, evaluated at factor 1.0 on this M5 Max: + +| Term | Before | After | +| --- | ---: | ---: | +| Fixed load | 18 s | 4 s | +| Fixed denoise per step | 1.5 s | 0.6 s | +| Denoise per token per step | 0.0016 | 0.0018 | +| Denoise quadratic | 3.6e-8 | 3.6e-8 | +| Decode per token, 1-stage | 0.0065 | 0.0065 | +| Decode per token, 2-stage | 0.0065 | 0.0095 | +| Decode quadratic | 6.5e-8 | 2.5e-8 | + +Mean absolute error of the new law against the 23 measured walls, at factor 1.0, is **7%**. A2V at 129 frames is within 1%. I2V is within 1%. Cozy-felt is 10% low (158 s vs 175 s). The cells still outside 15% are the ones the old load constant had distorted the least cleanly: 270p/3s and 360p/4s about +17%, and the first 540p/5s +18%. 720p, 1080p, and 1440p are within 5%. + +This is ConvVAE only. DiffVAE was not measured, and both paths share these coefficients. diff --git a/docs/generation-queue-lanes.md b/docs/generation-queue-lanes.md new file mode 100644 index 000000000..29f6e2409 --- /dev/null +++ b/docs/generation-queue-lanes.md @@ -0,0 +1,100 @@ +# Generation queue lanes + +The queue runs jobs in **lanes**. A lane is a pool of capacity for one resource or one provider. It is never tied to a feature. + +- Jobs in one lane run in queue order, up to the concurrency of the lane. +- Jobs in different lanes do not wait for each other. +- The lane of a job is set once, when the job is queued. It is stored in `generations.lane`. + +| Lane | Concurrency | Uses the GPU | What runs there | +| --- | --- | --- | --- | +| `local` | 1 | yes | Every local job. Every job whose lane is not registered. | +| `fal` | 1 | no | Text-to-image jobs with `provider: "fal"`. | + +## Rules + +- Every executor must run correctly on the `local` lane. A lane that is not registered falls back to `local`. At boot, `reassign_unknown_lanes` moves the rows of an unregistered lane to `local`. +- The kill switch `LTX_PARALLEL_QUEUE_LANES=0` registers only the `local` lane. All jobs then run one at a time. +- The `local` lane keeps the global `GenerationHandler` slot. Sync routes (GenSpace, Edit) block only this lane. +- An executor reports progress, cancel and provider status through its `JobSession`. It must not read or write the global generation state. Only the `local` lane maps the session onto that state. +- Live facts of a running job (progress, `api_status`, `cancellable`) are never stored. The queue reads them from the running session (`QueueControl.live_state`). +- `QueueSnapshot.active` is a list. It has one entry for each running job. + +## The provider job id + +A job on a provider lane runs at a third party. That party has its own id for the job. + +- The executor calls `JobSession.set_provider_job_id` right after the provider accepts the job. +- The queue stores the id in `generations.provider_job_id`. Only a running attempt takes it. The store checks the attempt, so a late write of an old attempt never lands on a retry. +- A job that failed or was cancelled keeps its id until a provider cancel succeeds (see Provider cancel). A succeeded job keeps it as a record. +- A retry takes the id off the row, so the row shows the newest attempt only. The old id moves to the file `displaced_provider_jobs.json` in the app data folder, and stays there until a provider cancel of it succeeds. The store writes the file before it commits the retry. A crash in between leaves the id in both places, and the readers list it once. If the file cannot be written, the retry fails and the job stays failed with its id. The file is deleted when no id is left. A file that cannot be parsed is moved to `displaced_provider_jobs.json.corrupt`. +- `set_provider_job_id` never raises for a store failure. It returns `False` when the id was not stored (a store error, or the attempt is no longer running). Boot cannot cancel such a job, so the executor must cancel it at the provider. +- An empty id is refused (`ValueError` in the store). It would make the boot orphan list unreadable. +- The id is in the API (`Generation.provider_job_id`), in the Remote API, and in the logs. +- A local job has no provider job id. It stays null. + +## Provider cancel + +`LaneSpec.cancel_orphan(provider_job_id)` asks the provider to drop a job. It must be safe to repeat, and it must treat "already finished" as success. It must bound its own network time. + +- `JobSession.cancel` only signals the executor. It returns at once and does no network I/O, because the queue calls it while it holds the lane lock. +- After the executor returns for an attempt that failed or was cancelled, the runner calls `cancel_orphan` on its own thread. A slow provider never holds a worker. +- When the call succeeds, the id is cleared. When it fails, or the app stops first, the id stays on the row. +- `cancellable_while_running=False` is enforced. A cancel of a running job on such a lane gets `409 INVALID_GENERATION_STATUS`, and the job keeps running. The queue panel hides its Cancel button. The result card still shows one, and the click gets the 409. + +A retry never loses an id that was not cancelled yet. The runner of the old attempt cancels it, and a boot cancels it when the call failed or the app stopped first. A deleted row keeps its id in the same way. + +## Boot recovery + +At boot, a job that was running is marked failed (`fail_running_on_boot`). The provider can still run it and bill it. + +1. `QueuedGenerationHandler.recover_on_boot` fails the running jobs and moves the queued rows of unregistered lanes to `local`. +2. It reads every row that still holds a provider job id (`list_provider_orphans`): running, cancelling, failed and cancelled rows, deleted rows too. It also reads the old ids that a retry replaced (`displaced_provider_jobs.json`). +3. For each orphan, it calls `LaneSpec.cancel_orphan(provider_job_id)` of the lane, then clears the id. The calls run on a daemon thread, so a slow provider does not delay the boot. + +A failed call is logged and does not stop the others. The id stays, so the next boot tries again. A lane that has no `cancel_orphan`, or is not registered, is skipped with a warning. Its rows keep the id, and the cancel happens at the first boot where the lane is back. + +## Logs + +Each log line names the lane and the generation id. + +- `Generation () started on lane , attempt ` +- `Generation left lane after s` +- `Generation accepted by its provider as job ` +- `Cancelling provider job of generation (lane )` +- `Provider job of generation cannot be cancelled: lane has no cancel. The id stays on the row.` + +## The fal lane + +- The executor (`QueuedImageHandler`) calls `set_provider_job_id` with the fal request id right after fal accepts the request and before the first status check. If the id is not stored, it cancels the request at fal at once and the job fails. +- `FAL_LANE_SPEC.cancel_orphan` is `QueuedImageHandler.cancel_fal_request`. It sends `PUT` to the cancel URL of the request with the saved fal API key. `202`, `400 ALREADY_COMPLETED` and `404` count as done. Any other status raises, so the id stays for the next boot. +- fal builds its request URLs from the app id (`fal-ai/z-image`), not from the sub-path (`/turbo`). `ZitAPIClientImpl.cancel_queued` derives the URL from `FAL_QUEUE_APP`. A test compares it with the URL in a submit response fixture. +- The boot cancel needs the fal API key. When the key is removed, the cancel fails and the id stays. +- Under the kill switch a fal job runs on the local lane. That lane records no id and has no boot cancel. + +## Add a lane + +1. Add a `LaneSpec` in `services/generation_queue/lanes.py` and register it in `AppHandler`. +2. Add `lane_for(spec)` to the executor. It must be a pure function of the stored spec. +3. In `AppHandler._lane_runner`, give the lane a slot and a session factory. A lane that does not hold the GPU uses `CountingLaneSlot` and `LaneJobSession`. +4. Set `cancellable_while_running` to `False` only if a running job cannot be stopped. +5. Set `stop_grace_seconds` for a lane whose jobs the app cannot wait for at stop. The queue cancels the running sessions of such a lane. +6. Set `cancel_orphan` so that the boot can drop a job that the provider still runs. +7. Call `session.set_provider_job_id` in the executor, right after the provider accepts the job. + +## Borrow the GPU from another lane + +A job in another lane that needs the GPU for a short step (for example a Gemma prompt rewrite) must use `GenerationHandler.try_lease_idle_gpu`. The lease never waits. It succeeds only when no local job runs, no local row waits and nobody else waits for the GPU. A granted lease evicts the diffusion stage cache first, so the borrowed step does not load next to a cached transformer. When the lease fails, the job must use a provider-side fallback. A job that already holds the GPU slot (a fal job on the local lane under the kill switch) does not lease: `JobSession.holds_gpu_slot` is true. + +## Prompt rewrite of a fal image job + +The rewrite runs only when Explore auto-enhance is on and the prompt is not already enhanced. The code is `backend/handlers/image_prompt_plan.py`. + +| Gemma downloaded | GPU | Gemini set up | Result | +| --- | --- | --- | --- | +| yes | idle | any | Local Gemma rewrite. `enable_prompt_expansion` is false. | +| yes | busy | any | fal expands (`enable_prompt_expansion` true). | +| no | n/a | yes | Gemini rewrite. `enable_prompt_expansion` is false. | +| no | n/a | no | fal expands. | + +A failed rewrite (not a cancel) also falls back to fal expansion. fal bills the expansion. diff --git a/docs/hardware-compatibility.md b/docs/hardware-compatibility.md new file mode 100644 index 000000000..8a21a90bb --- /dev/null +++ b/docs/hardware-compatibility.md @@ -0,0 +1,958 @@ +# Will it run on my machine? + +A plain-language guide to what LTX Desktop can generate on your hardware: +**text/image/audio generation**, **Retake & Extend** (video editing), and +**IC-LoRA** (video recipes and Ingredients). The tables are what the app +itself offers in Cautious mode: they are worked out from the same memory +budget the app checks when you press Generate, and that budget is fitted to +real runs on one RTX 5090 PC and one Mac (an M5 Max). The app refuses jobs it +cannot run rather than failing halfway. On other cards and Macs, and for clips +made in parts, the memory a job needs is calculated from those runs, not run on +that card (see [Brave mode](#brave-mode) for what to do beyond them). + +The numbers behind these tables live in the app's code. If what the app does +and what this page says disagree, the app is right and this page is out of +date — please report it. + +This guide covers local generation on **Windows PCs with an NVIDIA GPU** and on +**Apple Silicon Macs**. It has one part per OS, each covering generation, +editing, and IC-LoRA. + +**On Windows with an NVIDIA GPU?** Read +[On Windows](#on-windows-nvidia-gpu). **On a Mac?** Skip to +[On a Mac](#on-a-mac-apple-silicon). + +## Three ways a video can be generated + +A video is a 3D box of "tokens": width × height × time. Every 32 × 32 pixel +patch of a frame is one token, and every 8 frames add one more layer in time. +More resolution, a longer clip, or a higher frame rate makes the box bigger, +and a bigger box needs more memory. When the box doesn't fit, the app has two +independent levers: + +1. **How the model is loaded** — all of it on the GPU, or streamed in parts + (the **Full** and **Stream** marks in the tables below). +2. **How the box is sliced** — along time (**chunking**) or across the frame + (**tiling**), so only a smaller piece sits in memory at once. + +### Way 1: Single-pass (Full or Stream) + +In a normal single-pass run, the model looks at the whole box at every step. + +```text +SINGLE-PASS (normal generation) +Every token attends to every other token across the whole video at once. + + +---------------------------------------+ + / /| + / TIME / | Height + / (all frames) / | + +---------------------------------------+ + + | | / + | 100% of video in memory | / Width + | |/ + +---------------------------------------+ + + - Memory: Highest (holds the whole video at once) + - Speed: Fastest (no repeated frames, no overlapping pieces) + - Quality: The reference (the first and last frame see each other directly) +``` + +There are two loading variants: + +- **Full:** all model weights stay on the GPU next to the video. Fastest, most + memory. +- **Stream:** weights are loaded layer by layer during each step. About + 10–25% slower. **The output pixels are identical to Full** — it only changes + how the model is moved, not what is generated. + +### Way 2: Temporal chunking (slicing time into overlapping windows) + +Instead of one giant pass, the app generates the clip in shorter windows, one +after another (for example 129, 97, 73, 49 or 41 frames at a time). If each +window were generated on its own there would be a hard cut between them, so +each window starts from the tail of the one before it — the **carry** +(typically 17 frames for text/image/audio generation, 25 for IC-LoRA). + +```text +TEMPORAL CHUNKING (e.g. 97-frame windows with a 25-frame carry) + +Timeline (frames): 1 73 97 169 193 241 + |-------------------|=====|------------------|=====|---------| +Window 1 (97f): [====== Gen 1 ======|carry] + : : +Window 2 (97f): [carry|====== Gen 2 =====|carry] + : : +Window 3 (73f): [carry|== Gen 3 ] + + [====] = overlap ("carry"): already generated in the previous + window and fed into the next one so motion matches. +``` + +What it costs and buys: + +- **Memory drops.** Peak memory follows the window length (97 frames instead + of 241), plus a small overhead for stitching the windows together. Smaller + windows need less memory but mean more of them; for text/image/audio + generation the app starts from the longest window and steps down + (129 → 97 → 73 → 49 → 41 frames) until one fits. +- **Time goes up.** Every carry region is generated twice: with a 41-frame + window and a 17-frame carry each window adds only 24 new frames, so a + 20-second (481-frame) clip takes 20 windows. Each window also repeats its own + upscale-and-decode cycle. +- **Plain text/image-to-video can drift.** Window 5 only sees the tail of + window 4 and has forgotten window 1, so lighting, background, or a subject's + look can slowly change over many windows, like a game of telephone. +- **With IC-LoRA it is nearly lossless** (see below): the guide video anchors + every window. + +### Way 3: Spatial tiling (slicing the frame into overlapping tiles) + +At very large frame sizes even one window has too many pixels. Tiling cuts +each frame into overlapping rectangles and runs the model on one tile at a +time, inside every denoising step. Neighbouring tiles overlap so their edges +blend without visible seams. + +```text +SPATIAL TILING (inside one 4K frame) + + +-------------------+-------+-------------------+ + | | | | + | Tile 1 |overlap| Tile 2 | + | | : | | + +-------------------+-------+-------------------+ + | overlap | + | overlap | + +-------------------+-------+-------------------+ + | | : | | + | Tile 3 |overlap| Tile 4 | + | | | | + +-------------------+-------+-------------------+ + + At EVERY denoising step: + 1. Run the model on Tile 1 + 2. Run the model on Tile 2 + 3. Run the model on Tile 3 + 4. Run the model on Tile 4 + 5. Blend the overlapping edges together + --> Go to the next denoising step +``` + +- **Memory drops during denoising**, because only one tile is in memory at a + time. The final decode of the whole frame still needs room for the full + canvas, so the saving is not total. +- **Time goes way up.** A 4K frame in 1920×1088 tiles takes up to 9 tiles per + step (about 50 seconds per step on an RTX 5090); finer 1024×576 tiles need + 36 per step, roughly four times longer. +- **It needs a guide.** The top-left tile can't see the bottom-right one except + slowly through the overlap, so for plain text-to-video each tile could invent + its own scene. With **IC-LoRA** the source video already fixes the layout of + the whole frame, so tiling works well. That is why tiling is only used for + IC-LoRA. + +### Side by side + +```text ++--------------------+------------------+------------------+----------------------------+ +| Strategy | Peak memory | Generation time | Output vs. single-pass | ++--------------------+------------------+------------------+----------------------------+ +| 1. Full | Highest | Fastest (1.0x) | Identical (the reference) | +| 2. Stream | Medium (1 pass) | ~1.1x - 1.25x | Identical pixels | +| 3. Chunked (large | Low | ~1.2x - 1.5x | Slight drift over a long | +| windows) | | | video | +| 4. Chunked (small | Very low | ~2.0x - 3.5x | More drift (many windows) | +| windows) | | | | +| 5. Tiled (+chunk) | Lowest per step | ~3x - 15x slower | Needs a guide (IC-LoRA) | ++--------------------+------------------+------------------+----------------------------+ +``` + +The dividing line: **Full → Stream** is a transparent loading choice (same +algorithm, same video). **Single-pass → chunking or tiling** changes the +algorithm itself — a different video, and more time. + +### Does chunking drift with IC-LoRA? + +Much less than in plain text/image-to-video, because every window gets +three anchors: + +```text +IC-LORA CHUNKING: THREE ANCHORS PER WINDOW + +Window 1 (frames 1..97) Window 2 (frames 73..169) ++-------------------------------+ +--------------------------------+ +| 1. Guide slice (frames 1..97) | | 1. Guide slice (frames 73..169)| <-- locks motion & layout +| 2. Carry overlap (25 frames) | --> | 2. Carry overlap (frames 73..97)| <-- smooths the seam +| 3. Reference still (+1 frame) | --> | 3. Reference still (+1 frame) | <-- locks the overall look ++-------------------------------+ +--------------------------------+ +``` + +- **Geometry and motion don't drift.** Each window receives its own slice of + your source video, so camera motion, subject position and pose stay locked + to it for the whole clip. +- **Look and colour depend on the recipe.** + - _Restoration recipes_ (Restore, Refine Details, Upscale): the source already + holds the true colours and lighting, so there is virtually no drift. + Restore deliberately works in 97-frame windows on longer clips, because + running it unchunked past that length loses detail. + - _Style and look-transfer recipes_ (Day to Night, Layout to Render, Canny, + Depth, Pose): the model has to invent colours or textures, so the first + frame (or your look image) is attached to every window as a reference still + to keep them consistent. + - _Outpainting_: the centre is locked by the source, but the invented borders + rely on the overlap between windows, so subtle texture drift can still + show in the margins of very long clips. + +So chunking is a genuine quality-and-speed trade-off for text/image-to-video, +and nearly free in quality for IC-LoRA — you only pay the time for the overlap. + +### Which way the app picks + +The app uses the cheapest way that fits your machine: **Full**, then +**Stream**, then **chunking** with the longest window that fits. Tiling is used +only for IC-LoRA (Restore, Refine Details, and the 1440p/4K cells). In +[Brave mode](#brave-mode) the app still steps down through the windows +first; Brave only comes into play when even the smallest window doesn't +fit. + +Where each way shows up below: + +- **Text/image/audio generation up to 1080p:** single-pass (Full or Stream) + whenever your machine can hold the clip in one go. When it cannot — a long + clip, a high frame rate, or a smaller card or Mac — the app chunks it + instead of refusing, at any resolution. +- **Text/image/audio generation at 1440p and 4K:** chunked, always streamed. +- **IC-LoRA:** single-pass for small jobs, chunked past a size limit; Restore + and Refine Details are tiled, and the 1440p/4K cells are tiled and chunked. +- **Retake and Extend:** single-pass only — they never chunk or tile, which is + why long or large edits shorten or refuse instead. + +## On Windows (NVIDIA GPU) + +### Windows in 30 seconds + +- **Text/image/audio generation runs on 10 GB cards and up.** When a clip + is too big for one pass, the app makes it in overlapping parts instead of + refusing it: a 12 GB card runs 720p at 20 seconds and 1080p at 10 + seconds in parts, and a 16 GB card runs 1080p at 20 seconds in parts. Those + numbers are at 24 fps — higher frame rates trim the top (see below). 8 GB + cards sit below the 9 GB floor — the app routes them to the API + automatically. +- **1440p and 4K text/image/audio generation runs in overlapping time + windows and needs a bigger card.** 1440p: up to 10 seconds on 16 GB, 20 on + 24 GB and 32 GB. 4K: up to 10 seconds on 24 GB and 32 GB cards (on 24 GB + at 24/25 fps; fewer seconds at 48/50 fps). Both are slow — on an RTX 5090 a + 3-second 4K clip takes about 7 minutes and a 10-second one about 26. Jobs + beyond the lengths we have run need [Brave mode](#brave-mode). +- **Higher frame rates cost more memory.** 25 fps matches 24 fps almost + everywhere; 48/50 fps render twice the frames, so the longest clips need + more parts or a bigger card — 1080p at 20 seconds and 48/50 fps needs 24 GB. +- **Ultrawide costs more memory.** Every local clip offers 21:9 through 9:16 + (except 4K, which has no 21:9); the tables show 16:9. Narrower shapes fit wherever 16:9 fits, but 21:9 + ultrawide needs ~30% more and can refuse where 16:9 runs. +- **Video editing (Retake & Extend) needs a 12 GB graphics card or better + for most jobs.** 10 GB cards stream the smallest cells; 8 GB cards cannot + run it at all. +- **Bigger picture + longer clip = more parts, and a slower run.** Up to 1080p + the app picks one pass when it fits and parts when it doesn't, so a smaller + card trades time, not options. 1080p at 20 seconds runs in 3 parts on 24 GB + and 32 GB cards and in 6 on a 16 GB card. +- **IC-LoRA recipes take a source clip of up to 10 seconds.** At 540p and + 720p a 16 GB card runs the whole 10 seconds; at 1080p most recipes need + 24 GB for the whole clip (Restore and Refine Details run it on 16 GB). + Smaller cards get shorter clips (see below). +- **System RAM matters too.** 64 GB runs everything at full speed. On a fast + NVMe drive, 32 GB runs every tool (including IC-LoRA) and 24 GB runs + generation and editing (see below). +- **Disk space is an install question, not a per-job one.** The model pack + needs ~72 GB free to download (see the README); generating itself only + needs room for the output video, so the app never refuses a job over disk. +- **"Streamed" is not an error.** It means the app fits a bigger job by loading + the model in parts. It runs a bit slower; that's normal. + +### How to read the Windows tables + +**Columns — your graphics card, by its memory (VRAM).** Find the column closest +to your card without going over it. Examples: RTX 3080 (10 GB), RTX 4070 +(12 GB), RTX 4080 (16 GB), RTX 4090 (24 GB), RTX 5090 (32 GB). 8 GB cards +(RTX 4060 Ti) sit below the 9 GB local-generation floor, so every table starts +at 10 GB. + +**Rows — the job you want.** Resolution × length, at 24 fps in 16:9 — the +anchor the generation tables are quoted at. Lengths between two rows fall +between them; the app computes your exact clip when you press Generate. The +frame-rate and aspect-ratio notes under each generation table say how the +other picker values differ. + +**Cells — what the app will do:** + +| Mark | Meaning | +| ---------- | ------------------------------------------------------------------------ | +| **Full** | Runs with the whole model on the GPU. Fastest. | +| **Stream** | Runs by streaming the model's weights layer by layer. A bit slower. Normal for big jobs. | +| **Parts (n)** | Runs in _n_ overlapping time windows (see [Way 2](#way-2-temporal-chunking-slicing-time-into-overlapping-windows)), always streamed. Slower; plain text-to-video can drift a little across parts. | +| **—** | Not offered. The app tells you why instead of failing halfway. | + +In the app, a **—** cell shows as a greyed-out option with the reason +attached — the picker tells you before Generate, not after. Frame-rate and +duration pickers are linked: picking 50 fps can grey out long durations that +24 fps offers, each with its reason. Video-editing and IC-LoRA options depend +on your source clip, so the same picker can offer more (or less) once you pick +one. Editing and IC-LoRA follow your source media — they have no frame-rate or +aspect-ratio pickers, so only the generation tables carry those notes. + +**Two things that move you one column left in real life:** + +1. **Free vs total memory.** The picker and the queue judge your card by its total + memory, so you see everything it can run. Whether there's room right now is + checked when the job starts: Generate checks at the click, and a queued job + checks when its turn comes. Between queued jobs the app first clears what the + previous job left behind. A browser with 50 tabs can still eat 1–2 GB — if a + job that "should" fit is refused when it starts, close other apps and try again. +2. **System RAM (below).** Streamed jobs also need enough PC memory; the RAM + table applies on top of every "Stream" and "Parts" cell. + +### Retake & Extend (video editing) + +Retake re-generates part of your clip; Extend grows it longer. Both are budgeted +the same way: what counts is the **total footage the AI processes at once**. + +The table shows the **longest window of footage** each card processes at once, +at 24 fps, rounded down to the half second. A clip that needs more is shortened to that window instead of being +refused. + +| Picture | 10 GB | 12 GB | 16 GB | 24 GB | 32 GB | +| ------- | ------ | ----- | ----- | ----- | ----- | +| 540p | 11.5 s | 16 s | 20 s | 20 s | 20 s | +| 720p | 6.5 s | 9 s | 14.5 s | 20 s | 20 s | +| 1080p | 2.5 s | 3.5 s | 6 s | 10.5 s | 15.5 s | + +20 s is the longest window the editor ever takes. Every cell streams, except on +32 GB cards, which run 540p windows up to 20 s, 720p up to about 10 s and 1080p +up to about 5 s with the whole model on the GPU (**Full**). + +**Three things that surprise people:** + +- **Extend counts your existing footage too.** A "10 second" extension on top of + 10 seconds of context is budgeted as ~15 seconds of processing. Extensions + also always keep at least ~5 seconds of your clip as context, so the longest + single extension is about 16 seconds (less at 1080p on smaller cards). +- **Long clips shorten automatically.** You don't get an error — you get + the longest window your card can run (the table above). +- **8 GB cards sit out video editing entirely.** The smallest edit needs about + 8.8 GB, and 8 GB cards report under the 9 GB floor. This is a hard floor, + not a setting we can lower. 10 GB cards stream short windows (the first + column above) — the app trims to your exact window. + +**Above 1080p.** Retake and Extend normally cap the picture at 1080p. With the +experimental **High-resolution video to video** option on, sources up to 4K are +kept (and a 1440p tier appears for a 4K source). At **1440p**, Cautious mode +runs the longest window that fits your card (about **8.5 seconds** of processed +footage on 32 GB, **5.5 seconds** on 24 GB, **3 seconds** on 16 GB, **1.5 +seconds** on 12 GB — longer clips shorten automatically, just like at 1080p). +At **4K**, edits never run in windows and Cautious mode runs short windows that +fit your card and the 65-frame video-decode ceiling (about **2.5 seconds** on +32 GB, **2 seconds** on 24 GB, **1 second** on 16 GB, **0.5 seconds** on +12 GB); longer 4K edit selections need [Brave mode](#brave-mode). + +### IC-LoRA (video recipes and Ingredients) + +Most IC-LoRA tools are **video recipes** (Day to Night, Deblur, Restore, +Refine Details, Layout to Render and the rest): they take your source clip, +up to **10 seconds**, and keep its motion and framing. What counts is the +output size and how much of the clip runs. The table shows the longest +source clip each card runs at 24 fps in Cautious mode; a longer clip is +refused with the reason (Brave mode offers to try it). + +| Recipe and output | 10 GB | 12 GB | 16 GB | 24 GB | 32 GB | +| ------------------------- | ------ | ----- | ------ | ----- | ----- | +| Most recipes, 540p | 3 s | 5 s | 8.5 s | 10 s | 10 s | +| Most recipes, 720p | 1.5 s | 3 s | 10 s | 10 s | 10 s | +| Most recipes, 1080p | — | 1 s | 2 s | 10 s | 10 s | +| Layout to Render, 540p | 3.5 s | 6 s | 10 s | 10 s | 10 s | +| Restore, 1080p | 2 s | 4 s | 10 s | 10 s | 10 s | +| Refine Details, 1080p | 1.5 s | 5 s | 10 s | 10 s | 10 s | + +Layout to Render matches the other recipes at 720p and 1080p. Restore and +Refine Details run in tiles, and their longer clips run in windows whose +decode is priced on its own, so at 1080p they fit cards the other recipes +don't; at 540p and 720p they run the whole 10 seconds on every card except +Restore on 10 GB cards (2 s). + +**Ingredients (from images).** Ingredients builds a clip from your images and +has its own duration picker (5 to 20 seconds). What matters is the images' +shape: + +- **Wide image** (landscape, e.g. 1024×576 or any 16:9 image) +- **Tall phone photo** (portrait, e.g. 768×1280) + +| Job (image shape × length) | 10 GB | 12 GB | 16 GB | 24 GB | 32 GB | +| ---------------------------- | ------- | ------- | ------ | ------ | ------ | +| Wide image, up to 20 s | —⁴ | Stream¹ | Stream | Stream | Full | +| Tall phone photo, up to 5 s | — | Stream¹ | Stream | Stream | Full | +| Tall phone photo, up to 10 s | — | — | —² | Stream | Stream | +| Tall phone photo, 20 s | — | — | — | —³ | Stream | + +¹ Asks ~11.7 GB — tight on a 12 GB card; close other apps first. +² Asks ~16.4 GB — just over a 16 GB card, so it is refused (8 s fits). +³ Asks ~25.9 GB. Needs 32 GB; 24 GB cards are refused, not streamed. +⁴ 10 GB cards run wide images up to 10 s. + +**How your image's size enters the budget (Ingredients).** When you upload a photo, the app +reads its pixel dimensions, derives a working grid from them, and checks each +duration against that grid — new upload, new verdicts. Generate checks once +more against the preprocessed clip, so preprocessing can't sneak an +over-the-fence job past the upload check. + +On the default path (every catalog recipe as shipped: stage-1-only), the +working grid comes from a fixed 768-pixel-wide bucket — only your photo's +_shape_ sets its height. A 48 MP phone photo and a small web image of the +same shape budget identically, which is why the table covers just two shapes +(wide / tall). Absolute size matters only under Advanced settings: **Source +dimensions** sizes the grid to your photo's own pixels (anything past 1080p +refuses on any card, and 1080p itself asks ~22 GB — so downscale first), while +**two-stage** sizes it to about half your photo's pixels (a 1080p photo fits, +~4K refuses, and the limit is length × photo size together). + +One fence applies on every path, any machine: the output must fit inside +1920×1088, turned either way (the experimental 1440p/4K cells below are the +only exception). On the default path that only bites photos +taller than about 3.3:1, and because it is the _shape_ that refuses, +downscaling the file won't help; crop to a less extreme shape instead. + +**IC-LoRA at 1440p and 4K (experimental).** Every catalog recipe can render at +1440p or 4K, but only when the **High-resolution video to video** option in the +app's developer panel is on (it ships off). The recipe runs in a single stage, +in tiles of up to 1920×1088 (four tiles per 1440p frame, nine per 4K frame), in +short windows of 41 frames that overlap by 17 — each window adds 24 new frames +(see [Three ways a video can be generated](#three-ways-a-video-can-be-generated)). +The cells never upscale: your source must be at least as large as the cell +(about 2144 px on its short side for 4K, 1424 px for 1440p). + +- **What Cautious mode allows at 1440p:** most recipes up to **5 windows** — 137 + frames, about 5 seconds at 24 or 25 fps — on 16 GB cards and up (a 5-second + clip asks ~13.4 GB). Restore and Refine Details run the whole 10-second clip + on 24 GB and 32 GB cards; on a 16 GB card Restore stops at 5 seconds and + Refine Details at 2 seconds. The 16 GB and 24 GB figures are calculated from + our RTX 5090 runs, not run on those cards. +- **What Cautious mode allows at 4K:** 32 GB cards only. Most recipes and + Restore run the whole 10-second clip (a 5-second clip asks ~23.3 GB for most + recipes). Refine Details at 4K has not run cleanly, so Cautious refuses it. +- **Needs Brave mode:** most recipes at 1440p past 5 windows, Refine Details at + 4K, and 1440p clips longer than your card fits. 4K on a card under 32 GB is + refused in both modes: the decoder cannot finish a 4K frame there. +- **Time and quality:** on an RTX 5090 a 1440p window takes about 13 minutes + (about 66 minutes for a 5-window clip), and a 4K step takes about 50 seconds + (~8 minutes per window, over an hour for a 10-second clip). The output has + 1440p or 4K pixels but about 1080p detail (one stage, no refinement pass), and + a recipe that changes the whole scene (Day to Night, for example) can differ a + little from tile to tile — check results by eye. + +### Text, image & audio generation (T2V/I2V/A2V) + +Generate a video from a prompt, a start image, or an audio track. One table +serves all three — the app budgets them identically, and the source image +costs a flat, tiny amount. Shorter clips inside a row may run Full where the +row says Stream, or in one pass where it says Parts; the row shows its longest +length. Every 1440p and 4K cell streams. The table is the 24 fps picture in +16:9 in Cautious mode; the notes below it cover the other frame rates and +shapes. + +| Job (resolution × length) | 10 GB | 12 GB | 16 GB | 24 GB | 32 GB | +| ------------------------- | ------- | --------- | --------- | ---------- | --------- | +| 270p/360p up to 5 s¹ | Stream² | Stream | Stream | Stream | Full | +| 540p up to 5 s | Stream² | Stream | Stream | Stream | Full | +| 540p up to 10 s | Stream² | Stream | Stream | Stream | Full | +| 540p up to 20 s | — | Parts (2) | Stream | Stream | Stream | +| 720p up to 5 s | Stream² | Stream | Stream | Stream | Full | +| 720p up to 10 s | — | Parts (2) | Stream | Stream | Full | +| 720p up to 20 s | — | Parts (4) | Parts (2) | Stream | Stream | +| 1080p up to 5 s | — | Parts (2) | Stream | Stream | Stream | +| 1080p up to 10 s | — | Parts (6) | Parts (3) | Stream | Stream | +| 1080p up to 20 s | — | —⁴ | Parts (6) | Parts (3) | Parts (3) | +| 1440p up to 10 s | — | — | Parts (7)³ | Parts (3)³ | Parts (2) | +| 1440p up to 20 s | — | — | —⁴ | Parts (6)³ | Parts (5) | +| 4K up to 10 s | — | — | — | Parts (10)³ | Parts (7) | + +¹ The app budgets 270p like 540p and 360p like 720p. Shorter clips can fit +where the row's longest does not: a 10 GB card runs 1080p at 2 s, and a 12 GB +card runs 1440p at 2 s (in 2 parts). +² Exactly at the limit on 10 GB cards — close other apps first. A card that +reports less than its full 10 GB runs none of these. (8 GB cards report under +the 9 GB floor and are routed to the API.) +³ Calculated, not run on that card: we ran 1440p and 4K on an RTX 5090 (32 GB), +so the 32 GB column was run. The memory need on 16 GB and 24 GB cards is +calculated from those runs (the smaller windows those cards use were only tried +on the 32 GB card, forced to stream). Close other apps first and expect long +runs. +⁴ More parts than we have run (12 on a 12 GB card at 1080p, 15 on a 16 GB card +at 1440p): Cautious mode refuses it, and [Brave mode](#brave-mode) runs it with +a warning. + +**The headline for 10 GB cards:** text/image generation is fully available up +to 720p/5 s and 540p/10 s — video editing is what wants 12 GB, not this. + +**1440p and 4K.** These run in overlapping time windows (see +[Three ways a video can be generated](#three-ways-a-video-can-be-generated)), +always streamed. The app tries the longest window that fits your card: +129 frames on 32 GB at 1440p (and through 8 s on 24 GB), shorter ones on +smaller cards or longer 24 GB clips (97 frames from 10 s at 1440p on 24 GB; +49 frames at 3 s at 4K on 24 GB, stepping down to 41 frames from 4 s), which +means more windows and a slower run. Plain text-to-video +can drift a little between windows. The pickers offer 1440p up to 20 s and 4K +up to 10 s (no 21:9 at 4K; audio-to-video starts at 5 s). + +- **What Cautious mode allows.** The app only offers jobs of up to **9 + windows at 1440p** and up to **15 windows at 4K** — the longest runs we have + run on an RTX 5090. (We also ran 1440p as 20 short 41-frame windows, but the + app counts windows, not their length, so it stops at 9.) That is what the + rows above show: 16 GB cards reach 10 s at 1440p (7 windows of 49 frames, 8 + at 25 fps; 4 s runs in 2 windows of 73 frames), + and 24 GB and 32 GB cards reach 20 s (2 windows of 129 frames at 6 and 8 s + and 3–6 windows of 97 frames at 10–20 s on 24 GB; 5 + windows of 129 frames on 32 GB); 4K clips of 10 s need 24 GB (2 windows of + 49 frames at 3 s, 4–10 windows of 41 frames at 4–10 s) or 32 GB (7 windows + of 49 frames). Longer clips, or cards below + the rows (4K on 16 GB, 1440p past 2 s on 12 GB), are refused in Cautious mode and need + [Brave mode](#brave-mode). +- **Frame rate.** 25 fps matches 24 fps. At 48/50 fps the clip has twice the + frames, so more windows: 1440p tops out at 6 s on 16 GB, 10 s on 24 GB and + 20 s on 32 GB; 4K at 6 s on 24 GB, and 10 s on 32 GB. +- **Image-to-video and audio-to-video** are priced the same as text-to-video + and offered on the same rows (we ran both at 1440p and 4K on the RTX 5090). +- **Time.** On an RTX 5090 a 3-second 4K clip takes about 7 minutes and a + 10-second one about 26, and the app shows a long-run warning for 4K. + Smaller cards use shorter windows and take longer still. + +A clip that fits your card in one pass but is longer than the longest single +pass we ran (past 10 seconds at 1080p and 24 fps, or 540p at 20 seconds and 48/50 fps) runs in two or more +windows in Cautious mode, and in one pass with a warning in Brave mode. After one +clean Brave run on your card, Cautious mode runs that clip in one pass too. + +In Brave mode, below 1440p, a clip that can run either way shows a **Make it** +choice: **One pass** or **In parts**. The app picks one, and the meter shows +the memory each needs. One pass has no joins between parts but needs more +memory; parts fit a smaller card. **Never split into parts** (Settings → +Hardware budget) makes every clip in one pass: some lengths are then not +offered, a 1440p or 4K clip longer than one window is refused, and in Brave +mode some clips ask more memory than the card has. + +How much of this the app runs without asking depends on the runs behind it. +Up to 9 windows is a tested case on Windows, on any card, and just runs. Past +that, a clip has not been tried at that length: Cautious mode refuses it with a +message saying so, and Brave mode (the default) runs it with a warning that it +may take long, fail or stall. After one clean run on your card, Cautious mode +accepts that clip length there too. If a +card cannot fit even the smallest window (41 frames), the app refuses with the +memory it would need. + +**Frame rate (24/25/48/50 fps).** 25 fps matches the table almost +everywhere — the one exception is 540p at 10 seconds, which needs 12 GB at +25 fps (10 GB at 24 fps, exactly at the limit). 48 and 50 fps render twice +the frames, so clips need more parts and the top lengths step down: 10 GB +cards keep 540p up to 5 s (4 s at 50 fps) and 720p up to 3 s; 12 GB cards keep +540p and 720p up to 20 s and 1080p up to 6 s; 1080p at 10 s needs 16 GB and +1080p at 20 s needs 24 GB. On 32 GB cards, 48/50 fps also runs Stream where +the table says Full (540p/10 s, 720p/10 s). The picker lists each frame rate's +durations separately and greys out the ones that don't fit, with the reason +attached. + +**Aspect ratio.** Every cell offers 21:9, 16:9, 3:2, 4:3, 1:1, 4:5, and 9:16. +Narrower and square shapes cost the same or less than 16:9, so they fit +wherever the table says the job runs. 21:9 ultrawide is ~30% wider, so it takes +more parts and can refuse where 16:9 runs: 10 GB cards stop at 540p 6 s and +720p 4 s, 12 GB cards at 1080p 8 s, 16 GB cards at 1440p 3 s, and 24 GB cards +at 4K 2 s. The picker greys out a refusing 21:9 shape with its numbers +attached, and queuing one is refused before anything is saved. The model was +trained on 16:9 and 9:16; the picker marks the other ratios with a quality +warning. + +### System memory (RAM) + +Every "Stream" and "Parts" cell above _also_ needs enough PC memory. (Full loads keep +everything on the graphics card and skip this check.) The app picks the path +automatically from your drive type and memory size: + +| Job | Standard path (any drive, or NVMe with enough RAM) | Lower-RAM NVMe path (NVMe SSD) | +| ---------------- | -------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | +| Text/image/audio | 40 GB minimum | 24 GB minimum (streams from the SSD below 40 GB, ~15–25% slower) | +| Retake & Extend | 64 GB minimum (non-NVMe drives) | 24 GB minimum (NVMe always streams from the SSD; full speed at 64 GB, ~15% slower at 24–32 GB) | +| IC-LoRA | 64 GB minimum | 32 GB minimum (streams from the SSD below 64 GB, ~1.3–1.5× slower) | + +In practice: **64 GB of RAM runs everything at full speed. On an NVMe +drive, 32 GB runs every tool** (including IC-LoRA, streaming weights from the +SSD), and **24 GB runs generation and editing**. Under 24 GB, streamed jobs are +not offered. + +The app enforces these floors. + +### What still needs Brave mode (Windows) + +Cautious mode refuses these; [Brave mode](#brave-mode) runs them with a +warning: + +- Clips that run in more than 9 windows at 1080p and below (for example 1080p + at 20 s on a 12 GB card), until a clean run on your card. +- 1440p text/image/audio clips past 9 windows (for example 20 s on a 16 GB + card, or 20 s at 48/50 fps on a 24 GB card) and 4K clips past 15 windows, + and either on a card below the rows above (4K on 16 GB, 1440p past 2 s on + 12 GB). +- IC-LoRA at 1440p past 5 windows (about 5 seconds; Restore and Refine Details + run longer on 24 GB and up) or past what your card fits, and Refine Details + at 4K (these also need the experimental **High-resolution video to video** + option). 4K IC-LoRA on a card under 32 GB is refused in both modes. +- Retake and Extend at 4K past the 65-frame decode ceiling (~2.5 s at 24 fps) + or past what your card fits (also needs the experimental + **High-resolution video to video** option). + +## On a Mac (Apple Silicon) + +### Mac in 30 seconds + +- **Check your macOS version** (Apple menu → About This Mac): local generation + needs **macOS 26 or later**. The app itself runs on macOS 14 and later. On + macOS 14 and 15 local generation is unavailable, and the app shows the + **Coming soon to your device** notice. +- **Find your memory size** (Apple menu → About This Mac): **24 GB runs most + jobs up to 1080p; 48 GB and up runs it all.** Macs with 16 GB or less, and + Intel Macs, run local generation via the API instead — the app routes you + automatically. +- **1440p runs on every Mac, 4K needs 32 GB, and both take hours.** In + Cautious mode 1440p runs up to 6 seconds at 24 fps on a 24 GB Mac, 10 seconds + on 32 and 36 GB Macs, and 20 seconds on 48 GB Macs and up. 4K runs up to 2 + seconds on a 32 GB Mac, 3 seconds on a 36 GB Mac and 10 seconds on 48 GB and + up. +- **Higher frame rates cost more memory.** 25 fps matches 24 fps almost + everywhere; 48/50 fps render twice the frames, so the longest clips step + down — 1080p stops at 8 seconds on a 24 GB Mac and 10 seconds on 32–36 GB + Macs, and 1440p at 3 to 6 seconds below 48 GB. +- **Ultrawide costs more memory.** Every cell offers 21:9 through 9:16; the + tables show 16:9. Narrower shapes fit wherever 16:9 fits, but 21:9 + ultrawide costs ~30% more and can refuse where 16:9 runs. +- **Ingredients from tall phone photos is the priciest Mac IC-LoRA job.** A + 20-second clip needs a 48 GB Mac (it asks ~29.4 GB against a typical ~25.0 GB + allowance on 32 GB Macs and ~28.1 GB on 36 GB Macs); wide images run + everywhere. +- **Closing other apps won't unlock new cells.** The check is against a fixed + cap for your model, not free memory — though closing apps can still speed + runs up. +- **Disk space is an install question, not a per-job one.** The model pack + needs ~72 GB free to download (see the README); generating itself only + needs room for the output video, so the app never refuses a job over disk. + +### How to read the Mac tables + +**Columns — your Mac's total memory.** Apple menu → About This Mac. Find +the band closest to your Mac: 24 GB, 32 GB, 36 GB, or 48 GB and up. The tables are +the typical picture — the app checks your exact machine when you press +Generate, and its verdict is final. + +**Below 24 GB** (8/16 GB Macs) and **Intel Macs**: local generation is not +offered; the app routes you to the API instead. This is a deliberate floor: we +have not run local generation on Macs under 24 GB, so the app uses the API there. + +**Rows — the job you want.** Resolution × length, at 24 fps in 16:9 — the +anchor the generation tables are quoted at. Lengths between two rows fall +between them; the app computes your exact clip when you press Generate. The +frame-rate and aspect-ratio notes under the generation table say how the +other picker values differ. + +**Cells — what the app will do:** + +| Mark | Meaning | +| -------- | -------------------------------------------------------------------------------- | +| **Runs** | Offered on your Mac in one pass. Always streamed; no Full/Stream split. | +| **Parts (n)** | Runs in _n_ overlapping time windows. Slower; plain text-to-video can drift a little across parts. | +| **—** | Not offered. The app tells you why instead of failing halfway. | + +In the app, a **—** cell shows as a greyed-out option with the reason +attached — the picker tells you before Generate, not after. Frame-rate and +duration pickers are linked: picking 50 fps can grey out long durations that +24 fps offers, each with its reason. Video-editing and IC-LoRA options depend +on your source clip, so the same picker can offer more (or less) once you pick +one. Editing and IC-LoRA follow your source media — they have no frame-rate or +aspect-ratio pickers, so only the generation table carries those notes. + +**Closing other apps won't unlock new cells.** Macs share one pool of memory +between everything, so the check is against a fixed cap for your model, not +free memory — though closing apps can still speed runs up. Every job's ask +includes about 3 GB for the buffers the model loader keeps while it streams +the weights. + +### Text, image & audio generation (Mac) + +Text-to-video, image-to-video, and audio-to-video are all budgeted the same +way on Mac: what counts is **resolution × length**. Editing and IC-LoRA have +their own costs, covered separately below. The table is the 24 fps picture in +16:9 in Cautious mode; the notes below it cover the other frame rates and +shapes. + +| Job (resolution × length) | 24 GB Mac | 32 GB Mac | 36 GB Mac | 48 GB Mac and up | +| ------------------------- | --------- | --------- | --------- | ---------------- | +| 540p up to 20 s | Runs | Runs | Runs | Runs | +| 720p up to 10 s | Runs | Runs | Runs | Runs | +| 720p up to 20 s | Parts (2) | Runs | Runs | Runs | +| 1080p up to 5 s | Runs | Runs | Runs | Runs | +| 1080p up to 10 s | Parts (3) | Parts (2) | Runs | Runs | +| 1080p up to 20 s | —¹ | Parts (4) | Parts (3) | Parts (3) | +| 1440p up to 5 s | Parts (4) | Parts (2) | Runs | Runs | +| 1440p up to 10 s | —² | Parts (4) | Parts (4) | Parts (2) | +| 1440p up to 20 s | —¹ | —¹ | —¹ | Parts (5)³ | +| 4K up to 3 s | — | —⁴ | Parts (2)⁴ | Parts (2) | +| 4K up to 10 s | — | — | — | Parts (7)⁵ | + +¹ More than 5 parts, past the Mac runs: Cautious mode refuses it, and +[Brave mode](#brave-mode) runs it with a warning. +² A 24 GB Mac stops at 6 s (4 parts of 49 frames). +³ We ran 1440p on one M5 Max, up to **5 windows** of 129 frames (20 s at 24 or +25 fps, 10 s at 48 or 50 fps). The app asks ~34.7 GB for it; 24–36 GB Macs and +clips longer than the five-window run are calculated, not run. Like 4K, 20 +seconds at 1440p takes hours (about 2 hours on the test Mac). +⁴ A 2-second 4K clip in two short parts asks ~23.0 GB and fits a 32 GB Mac's +~25.0 GB allowance; a 3-second clip asks ~27.5 GB, which needs a 36 GB Mac. +⁵ Runs in overlapping windows of 49 frames, up to **7 windows** — the longest +run we completed (a 10-second clip at 24 fps is exactly 7). It asks ~32.3 GB, +so it needs a 48 GB Mac or larger. 4K takes hours: our test Mac needed close +to three hours for a 10-second clip, and about 25 minutes more for every extra +window. All Mac 4K runs were on that one M5 Max; what smaller Macs need is +calculated from them, not run on those Macs. + +Smaller Macs use shorter parts than the 129-frame (1440p) and 49-frame (4K) +windows we ran on the Mac. Those shorter parts are calculated from the Mac runs +and from the Windows runs, which show a part's extra memory scaling with its +size; they have not been run on a Mac. + +**Frame rate (24/25/48/50 fps).** 25 fps matches the table except 4K on 48 GB +Macs (8 s instead of 10 s). 48 and 50 fps render twice the frames, so long +clips need more parts, and the 5-part limit sets the top: 540p and 720p run +through 20 s on every Mac; 1080p runs through 8 s on a 24 GB Mac, 10 s on 32 +and 36 GB Macs and 20 s on 48 GB and up. At 1440p, 48/50 fps fits 3 s on a 24 +GB Mac, 6 s on 32 and 36 GB Macs and 10 s on 48 GB and up. At 4K the 7-window +limit sets the top: a 48 GB Mac or larger gets up to 5 s at 48 fps and 4 s at +50 fps, and smaller Macs no 4K clip at 48/50 fps. The picker lists each frame +rate's durations separately. + +**Aspect ratio.** Every cell offers 21:9, 16:9, 3:2, 4:3, 1:1, 4:5, and 9:16. +Narrower and square shapes fit wherever 16:9 fits. 21:9 ultrawide costs ~30% +more and can refuse where 16:9 runs: at 1440p it stops at 2 s on a 24 GB Mac, +8 s on a 32 GB Mac and 10 s on 36 GB and up, and at 1080p at 10 s on a 24 GB +Mac. The app re-checks your exact Mac at Generate and names its numbers. The +model was trained on 16:9 and 9:16; the picker marks the other ratios with a +quality warning. + +### IC-LoRA on Mac + +Video recipes take your source clip, up to **10 seconds**, as on Windows. The +table shows the longest source clip each Mac runs at 24 fps in Cautious mode. + +| Recipe and output | 24 GB Mac | 32 GB Mac and up | +| ------------------------- | --------- | ---------------- | +| Most recipes, 540p | 9 s | 10 s | +| Most recipes, 720p | 10 s | 10 s | +| Most recipes, 1080p | 2 s | 10 s | +| Layout to Render, 1080p | 2 s | 10 s | +| Restore, 1080p | 4 s | 10 s | +| Refine Details, 1080p | 3 s | 10 s | + +Layout to Render runs longer clips in overlapping 97-frame windows, which keeps +its memory flat. Restore runs one 97-frame window (4 s) on a 24 GB Mac; longer +1080p Restore clips run in windows that need a 32 GB Mac. + +**Ingredients (from images)** on Mac: + +| Job (image shape × length) | 24 GB Mac | 32 GB Mac | 36 GB Mac | 48 GB Mac and up | +| ---------------------------- | --------- | --------- | --------- | ---------------- | +| Wide image, up to 20 s | Runs | Runs | Runs | Runs | +| Tall phone photo, up to 10 s | —¹ | Runs | Runs | Runs | +| Tall phone photo, 20 s | — | —² | —² | Runs | + +¹ Asks ~19.5 GB against a typical ~18.7 GB allowance on 24 GB Macs, so it is +refused; 8 s fits. +² Asks ~29.4 GB against a typical ~25.0 GB allowance on 32 GB Macs and ~28.1 GB +on 36 GB Macs, so it needs a 48 GB Mac. + +**Two-stage** (upscaled output) is offered on Macs at small sizes: 540p and +720p up to about 10 s, 1080p up to about 5 s in a single pass. 5-second clips +at 540p and 720p fit a 24 GB Mac; 720p at 10 s and 1080p at 5 s in one pass +need a 36 GB Mac. Bigger canvases refuse here rather than guessing. + +**Above 1080p.** The experimental 1440p and 4K IC-LoRA cells (the +**High-resolution video to video** option in the developer panel) are not +offered in Cautious mode on any Mac: none has been run on one, so every such job +needs [Brave mode](#brave-mode). + +One fence applies on every path, any machine: the working grid must fit +inside 1024×576. On the default path that only bites photos taller than +about 1.9:1 — past phone portrait — and because it is the _shape_ that +refuses, downscaling the file won't help; crop to a less extreme shape +instead. + +### Editing on Mac + +Retake and Extend cost the same on Mac: what counts is **resolution × window +length**. Extend counts your existing footage too — a "10 second" extension on +top of 10 seconds of context is budgeted as ~15 seconds of processing, and +extensions always keep at least ~5 seconds of your clip as context. A clip that +needs more than the table is shortened to the longest window your Mac runs +instead of being refused. Windows are at 24 fps, rounded down to the half second. + +| Picture | 24 GB Mac | 32 GB Mac | 36 GB Mac | 48 GB Mac and up | +| ------- | --------- | --------- | --------- | ---------------- | +| 540p | 20 s | 20 s | 20 s | 20 s | +| 720p | 11.5 s | 20 s | 20 s | 20 s | +| 1080p | 4.5 s | 8.5 s | 10.5 s | 16 s | + +**Above 1080p.** Retake and Extend cap the picture at 1080p. With the +experimental **High-resolution video to video** option on, larger sources are +kept, but we have not run edits that large on any Mac and edits never run +in windows, so every such job needs [Brave mode](#brave-mode). + +### What still needs Brave mode (Mac) + +Cautious mode refuses these; [Brave mode](#brave-mode) runs them with a +warning: + +- Any text/image/audio clip below 1440p that has to run in more than 5 parts + (for example 1080p 20 s on a 24 GB Mac). +- 1440p text/image/audio generation past 5 parts: past 6 s on a 24 GB Mac, 20 s + on 32 and 36 GB Macs, and 20 s at 48/50 fps on 48 GB Macs and up. +- 4K text/image/audio generation past 7 windows, and 4K longer than your Mac + fits (past 2 s on 32 GB, past 3 s on 36 GB, any 4K on 24 GB). These are over + the memory allowance, so the warning says the job may fail. +- IC-LoRA at 1440p and 4K (these also need the experimental + **High-resolution video to video** option). +- Retake and Extend above 1080p. +- Two-stage IC-LoRA beyond the lengths listed in the IC-LoRA section (for + example 540p past 10 s). + +## Worked examples + +### On Windows + +**"I have an RTX 4070 (12 GB) and 32 GB of RAM. What can I do?"** +Generation: up to 720p at 20 seconds and 1080p at 10 seconds, in parts. +Editing: 540p up to ~16 seconds, 720p up to ~9 seconds, or 1080p up to ~3.5 seconds — on an NVMe +drive these run about 1.5× slower than full speed (normal, not broken). +IC-LoRA needs 48 GB of RAM on the fast-drive path (64 on Standard) — with +that, recipes run 540p clips up to 5 seconds and 720p up to 3 seconds, and +Ingredients runs wide images up to 20 seconds. + +**"Can I extend my 1080p clip by 10 seconds on a 4090 (24 GB)?"** +Not in one go — one 1080p extension tops out around 5–6 seconds on 24 GB +(the app names the maximum); split it into two extensions. + +**"I want a 20-second video of my character from a phone selfie (tall photo)."** +With Ingredients, on 32 GB: yes. On 24 GB or less: no — it needs ~25.9 GB. +Use a wide photo (20 s runs on 12 GB) or a shorter clip instead (10 s runs on +24 GB, 8 s on 16 GB). + +**"Why is local generation missing on my 8 GB card?"** +Because 8 GB cards report under the 9 GB floor, so the app routes you to the +API for everything. On a 10 GB card, text/image generation fits, and IC-LoRA +recipes fit short clips (about 3 seconds at 540p; close other apps first) — but streamed jobs also need +32–64 GB of system RAM depending on the path, which 10 GB-card machines +don't always have. Video editing wants a 12 GB card. + +**"I have a 5090 (32 GB) with 96 GB of RAM. Any limits?"** +Almost none up to 1080p. The longest 1080p edits (~15.5 s windows) and every +IC-LoRA job up to 1080p run. At higher resolutions it runs 1440p up to 20 s (including at +48 and 50 fps) and 4K up to 10 s (slowly — about 26 minutes for a 10-second 4K +clip), plus 1440p edits (up to ~8.5 s windows) and short 4K edits (up to ~2.5 s +windows), 1440p IC-LoRA up to about 5 +seconds (the whole 10 seconds for Restore and Refine Details), and 4K IC-LoRA +up to about 10 seconds with the experimental option on. +Longer 1440p/4K IC-LoRA clips and longer 4K edits need Brave mode. Big jobs still show +"Stream" — that's the app being careful with your VRAM, not a problem. + +**"Can my 4090 (24 GB) make a 10-second 4K video?"** +Yes at 24 or 25 fps: it runs in ten 41-frame windows, so expect a long run, and +the memory need on a 24 GB card is calculated from our 5090 runs, not run on +that card. At 48/50 fps it tops out at 6 seconds. 1440p is available up to 20 +seconds at 24/25 fps (and 10 seconds at 48/50 fps); a 20-second 1440p clip at +48/50 fps needs Brave mode. + +**"Why is 20 seconds missing at 50 fps?"** +Because 50 fps renders twice the frames of 24 fps, so a clip needs more +memory or more parts. On a 16 GB card 1080p stops at 10 seconds at 50 fps (20 +at 24 fps), and on a 10 GB card 540p stops at 4 seconds. Pick 24 fps or a +shorter clip — the picker shows each frame rate's own durations. + +### On a Mac + +**"I have a MacBook Pro with 48 GB. What can I do?"** +Everything in the Mac tables above, including 1080p at 10 seconds, 1440p up to +20 seconds, and 4K up to 10 seconds (the last two take hours). If your Mac has +24 GB, the only things off the menu in Cautious mode are 1080p past 10 +seconds, 1440p past 6 seconds, and 4K — shorter or lower-resolution versions of +the same idea still run, some of them in parts. + +**"Can I make a 4K video on my 32 GB Mac?"** +Up to a 2-second clip at 24 or 25 fps (two short parts at ~23.0 GB against a +typical ~25.0 GB allowance). A 3-second clip asks ~27.5 GB, which needs a +36 GB Mac. Anything longer asks more than a 32 GB Mac's memory allowance, so +Cautious mode refuses it. Brave mode will try it anyway, with a warning that it may fail or +stall. + +## Why did the app say no? + +Every refusal names its reason, with the numbers: what the job needs vs what +the machine has (e.g. "needs 15.8 GB of GPU memory but this card has 12.0 GB"; +on a Mac it names your Mac's allowance instead). On Windows, when memory is +merely busy rather than too small, the message says to close other apps and +retry instead — on a Mac, closing apps never unlocks new cells. The common +ones: + +| Message means… | Try this | +| ------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------- | +| Not enough GPU memory | Shorter clip, lower resolution or frame rate, or a narrower shape than 21:9. On Windows, closing other GPU apps can also free enough to retry. | +| Not enough system RAM (Windows only) | Close heavy programs; on desktops, more RAM is the real fix. | +| Source image too large (IC-LoRA) | Downscale the photo — or crop it, if it is extremely tall — and retry. | +| Extension too long | The message names the maximum — split it into two extensions. | +| Untested on this machine | Lower the resolution, or turn off Cautious mode ([Brave mode](#brave-mode)) to try it anyway (shows the extrapolated memory estimate). | + +### Brave mode + +**Brave mode** is the default. Besides the jobs measured to fit, it lets you +try the rest: jobs that are over your machine's budget, and jobs nobody has +measured on your kind of hardware yet (the unmeasured 1440p and 4K cells +above, and anything past the window counts listed there). The memory meter +shows the risk, and the app asks before running such a job (Settings → +Hardware budget → "Ask before risky generates" turns the question off). The +job may fail, run out of memory, or stall the app. **Cautious mode** +(Settings → Hardware budget) runs only the jobs measured to fit, and refuses +the rest. + +Brave mode does not lift hard limits. Jobs the app cannot run at all still +refuse: no local pipeline on the machine, a Mac clip too long for the GPU to +process in one pass, a photo over the spatial limit, or Refine Details on a long +high-resolution clip its decoder cannot fit. For text/image/audio clips that +run in windows, the app still tries every window length first; Brave only +applies when even the smallest window does not fit. + +If you believe a refusal is wrong — a job the tables above say should run — +that _is_ a bug we'd like to hear about. Note your machine and memory +(graphics card, RAM, and drive type on Windows; Mac model and memory on a +Mac), and the exact job (resolution, length, frame rate, shape); the last section below says where the numbers come from. + +## Where these numbers come from + +The app's memory budget comes from running real jobs on a Windows RTX 5090 PC +and an Apple Silicon Mac: finding the exact memory limit of each job (by +deliberately giving it too little), running the same PC with less system RAM to +find the RAM floors, and re-running the longest clips to confirm the top end +really doesn't fit. Between the jobs we ran, the app interpolates, and the +tables on this page are read off that budget. + +1440p and 4K are the exception. We ran those on an RTX 5090 (Fast 1440p and 4K, +image and audio to video at 1440p and 4K, Retake and Extend at 1440p and 4K, IC-LoRA at +1440p and 4K) and on one Apple Silicon Mac (Fast 1440p and 4K, with the memory +allowance capped to find each edge). The app offers only up to the number of +windows those runs covered. We did not run other card sizes (16 and 24 GB Windows cards, 24–48 GB Macs); their memory need is calculated from the runs above, which is +why those rows are footnoted as calculated. Anything beyond the runs is a +Brave-mode bet. + +For the frame-minded: durations land on a frame grid of 8n + 1 frames, so 5 s at +24 fps is 121 frames — and 50 fps renders about twice the frames of 24 fps, +which is why its cells sit lower. + +If what the app does and what these tables say disagree, the tables are out of +date — please report it. The Mac figures on this page include the ~3 GB the +model loader holds while it streams the weights. diff --git a/docs/local-compat-matrix.md b/docs/local-compat-matrix.md index 03a18f9f6..a402c5561 100644 --- a/docs/local-compat-matrix.md +++ b/docs/local-compat-matrix.md @@ -8,8 +8,8 @@ subset of these durations, and wider shapes can refuse a kept top cell Retake/Extend rows are viability + RAM floor (`Yes*` — VRAM depends on your source length): no canonical input exists for a representative cell, but the floor is input-free. Bands carry no drive class, so -Windows bands take the CPU path (64 GB floor; NVMe maps from disk at -32 GB instead). +Windows bands take the CPU path (64 GB floor; NVMe streams from disk at +24 GB instead). Regenerate: `cd backend && uv run python -m runtime_config.local_compat_matrix`. | Tool | CUDA unsupported | CUDA stream | CUDA full | Windows stream | Windows RAM-gated | Darwin unsupported | macOS below 26 | Darwin stream | Intel Mac / no GPU | @@ -28,7 +28,8 @@ Floors: Windows **9** (fp8 cards; **15** without fp8) / Linux **15** GiB total V Windows streamed Fast needs **40** GiB total RAM; Darwin **32** GiB total RAM and macOS **26** or later (macOS 14 and 15 run the app but not local generation); Fast cells gate on the MPS pool -(9.75 GiB floor); ~72 GB disk for the 2.5 Fast core pack +(9.75 GiB floor, plus 3.01 GiB +of loader host buffers); ~72 GB disk for the 2.5 Fast core pack (kitchen-sink installs with 2.3, image models, and processors are larger). CUDA stream (16 GB) still runs T2V/I2V/A2V; @@ -36,22 +37,21 @@ the Fast picker disables 720p/20s and 1080p at 8s and up (greyed out with the re because `decide_video_job` would reject them. CUDA full (31 GB) keeps those cells (they stream) except 1080p/20s, whose stream ask exceeds `CUDA_FULL_VRAM_GB`. Darwin stream gates each Fast cell against the sampled MPS -pool (M2/F1 model, 9.75 GiB floor); the 48 GB example keeps the full grid except 1080p/20s +pool (M2/F1 model, 9.75 GiB floor); the 48 GB example keeps the full grid (1080p/20s in windows) (nominal 0.78 pool ratio — min of 2 F0 probes, SKU-dependent). -Windows stream (16 GB VRAM, 40 GB RAM) runs -the limited grid (540p through 20s, 720p through 10s, 1080p through 6s); 24 GB VRAM runs the -full grid including 1080p/10s, and 12 GB VRAM runs 540p through 10s plus 720p -through 8s (no 1080p — the 5s cell needs 14.14 reserved). Below 40 GB RAM, streamed Fast cells are not +Windows stream (16 GB VRAM, 40 GB RAM) runs every Fast cell +through 1080p/20s, in time windows where one pass does not fit (1080p/10s runs in 3); what each card size runs is in +`docs/hardware-compatibility.md`. Below 40 GB RAM, streamed Fast cells are not offered (`ram_shortfall`). Streamed edit cells gate on E3-measured floors (64 GB CPU, -32 GB NVMe DISK); streamed IC-LoRA on L5-measured floors (64 GB CPU, -48 GB DISK, L5-48 holds both temps). The live picker lists every total-fitting cell; +24 GB NVMe DISK); streamed IC-LoRA on L5-measured floors (64 GB CPU, +32 GB DISK, L5-32 holds both temps). The live picker lists every total-fitting cell; GenSpace refuses cells over free VRAM at click, and queued jobs re-check at execute. -On NVMe drives, streamed Fast maps weights from disk and the RAM floor is **32** GiB instead. +On NVMe drives below 40 GB, streamed Fast reads weights from disk and the RAM floor is **24** GiB instead. 1440p and 4K Fast cells run long clips in overlapping time windows, and the job budget prices one window. -1440p and 4K are offered for Fast, A2V and the Home recipes; Retake, Extend and IC-LoRA need `highResVideoToVideo`. Both are provisional, and -the Mac window extra is a copy of the Windows one. The cells above are the 24 fps / 16:9 anchor and do not list these two rows. +1440p and 4K are offered for Fast, A2V and the Home recipes; Retake, Extend and IC-LoRA need `highResVideoToVideo` (Refine Details does not). Both are provisional; +Windows and Mac each fit their own window extra. The cells above are the 24 fps / 16:9 anchor and do not list these two rows. Footnote: Darwin IC-LoRA gates each duration against the sampled MPS pool (I1/I2 model, 9.84 GiB floor, growth line diff --git a/docs/ltx-2-1-5-0-upgrade.md b/docs/ltx-2-1-5-0-upgrade.md new file mode 100644 index 000000000..955812acd --- /dev/null +++ b/docs/ltx-2-1-5-0-upgrade.md @@ -0,0 +1,112 @@ +# LTX-2 1.5.0 upgrade: analysis and decisions + +This document records the move from `ltx-core` and `ltx-pipelines` v1.4.1 to v1.5.0 +(release notes: ). Version 1.5.0 includes 1.4.2. +The manual test plan is in `docs/ltx-2-1-5-0-manual-test-plan.md`. + +## What changed in Desktop + +| Area | Change | +| --- | --- | +| Pins | `backend/pyproject.toml` pins `ltx-core==1.5.0`, `ltx-pipelines==1.5.0`, tag `v1.5.0`, and the two `dependency-metadata` versions. | +| Lock | `backend/uv.lock` has the new version and commit `e98f6d927d83c92ef2be6aec76c8440b19306e39`. No dependency changed. | +| Image inputs | One helper, `to_ltx_images` in `services/ltx_pipeline_common.py`, converts Desktop stills to upstream inputs. Fast, A2V and IC-LoRA use it. | +| Fast pipeline | `guide_all_images` now selects `ImageConditioningInput.guide` for every still. The helper swap in `distilled_keyframe_guiding.py` is deleted. | +| Skip stage 2 | `_call_stage_1_only` calls `load_conditionings` and `image_conditionings`. | +| A2V | `_prepare` calls `load_conditionings`. Both stages and every window encode the loaded stills. `resolve_image_conditionings` and `encode_stage_image_conditionings` are deleted. | +| Tiled IC-LoRA | Stills at frame -1 use `image_conditionings`. The chunk call has no `color_space`. | +| Patches | All kept. Version comments updated. The `diffusion_stage_cache` test fake follows the new `DiffusionStage` surface. | + +## Upstream API map + +| 1.4.1 | 1.5.0 | +| --- | --- | +| `ImageConditioningInput(path, frame_idx, strength)` | `ImageConditioningInput.at / .replace / .guide(path, frame_idx, strength, crf=None)` | +| `ImageConditioner.resolve_crf` | `ImageConditioner.load_conditionings(images, color_space)` | +| `combined_image_conditionings(...)` | `image_conditionings(loaded_images, height, width, video_encoder, dtype, device)` | +| `image_conditionings_by_adding_guiding_latent` | `ImageGuide` binding | +| `image_conditionings_for_chunk(..., color_space)` | `image_conditionings_for_chunk(chunk, images, video_encoder)` | +| `images[0][0]` | `images[0].path`, read before loading | + +Binding rules that Desktop relies on: + +- `.at(frame 0)` replaces frame 0. A later frame guides. This equals the old `combined_image_conditionings`. +- `ImageReplace` accepts only frame 0 or `1 + 8k`. It is re-checked when a chunk maps the index. +- `ImageGuide` has no range check. The IC-LoRA reference still at frame -1 must be a guide. +- `to_ltx_images` leaves `crf` unset. The checkpoint default applies, as `resolve_crf` did. +- `api_types.ImageConditioningInput` (the Desktop tuple) is unchanged. Conversion happens at the pipeline boundary only. + +## Patch decisions + +| Patch or fork | Decision | Reason | +| --- | --- | --- | +| `diffusion_stage_cache` | Keep | `DiffusionStage._transformer_ctx` still takes `**kwargs`. Only DFR and multi-GPU call `resident()`. Desktop never does. | +| `diffusion_interrupt` | Keep | `DiffusionStage.__call__` is unchanged. Samplers still use `tqdm` over a sized range. | +| `diffvae_decode_vram` | Keep | The 80-frame x 608 px clamp comes from a 1.4.1 hang. 1.5.0 changed the decoder, so an ablation is needed first (see "Follow-ups"). | +| `safetensors_*`, `disk_streaming_pread`, `linux_disk_streaming_backend`, `pinned_pool_fix`, `mps_sdpa_torch` | Keep | Target symbols and contracts are unchanged. | +| `natten_libnatten_gate` | Keep | `natten_available()` still reads the module flag the patch clears. | +| `distilled_keyframe_guiding` | Delete | `ImageGuide` replaces it. | +| `TiledICLoraPipeline._video_conditionings` | Keep, adapted | Re-diffed against upstream. Only `color_space` and the still helper changed. | +| `DistilledPipelineWithSkipStage2` | Keep, adapted | Re-diffed against `_prepare_run`. Same call order, `load_conditionings` replaces `resolve_crf`. | +| `DistilledA2VPipeline`, `LTXRetakePipeline` | Keep | `DiffusionStage` calls are unchanged. Retake uses `TemporalRegionMask`, which is unchanged. | + +## Edge cases checked + +1. **Replace at an invalid frame.** `ImageReplace` rejects frames that are not `0` or `1 + 8k`. `.at` makes frame 0 a replace only. No Desktop path passes another replace frame. +2. **Reference still at -1.** `.at(-1)` gives `ImageGuide(-1)`. The tiled pipeline still rejects any other negative index. Upstream `assert_image_frames_in_clip` still rejects a negative frame on a stage without the IC-LoRA. The existing guard in `LTXICLoraPipeline.generate` stays. +3. **Multi-keyframe frame 0.** Old code forced "guide everything". `guide_all=True` keeps that. First and last frame image-to-video keeps replace at 0. +4. **Missing or broken image.** `load_conditionings` raises `ValueError` before any model build. The handler checks the file first (`validate_image_file`, HTTP 400), so users keep the same message. +5. **EXR stills.** Desktop has no EXR flow. `load_conditionings(images)` is called without `color_space`. +6. **Window runs.** `LoadedImageConditioning.map_frame_index` keeps the decoded still. A2V window runs reuse one decode. +7. **Skip stage 2 with auto duration.** `enhance_prompt_image` is read from `images[0].path` before loading. +8. **Torch Compile.** Timestep tables are now compact tensors. The compile path needs a live check (manual plan, section D). +9. **Same seed, new output.** Output is not bit-identical. Add this to the release notes. + +## Flags and options evaluated for a Settings toggle + +| Upstream option | Used by Desktop pipelines | Decision | +| --- | --- | --- | +| `--spatial-upscalings 2` (DFR) | No. DFR is a separate pipeline. Desktop uses distilled pipelines. | No toggle. A toggle would have no effect. | +| `with_rowwise_fp8_gemm` | Upstream applies it only in the DFR epilogue. | No toggle yet. See below. | +| `--refine-audio` | Only `TI2VidTwoStagesPipeline`. Desktop does not use it. | No toggle. | +| Marking (VideoSeal, AudioSeal) | Opt-in extras. | No toggle. Needs a product decision. Keep off. | +| `alpha_gen` | A one-stage IC-LoRA pipeline, not a flag. Desktop already ships an `alpha-gen` recipe on the generic IC-LoRA pipeline. | No change. | +| `--chunked`, `--compile`, `--offload` | Already mapped to Desktop behaviour or settings. | Existing "Performance (CUDA)" group stays as is. | + +Why no rowwise FP8 toggle in this PR: + +- It changes the numbers of every transformer pass. It is lossy (3 mantissa bits for activations). +- It needs five pipelines (fast, IC-LoRA, A2V, retake, extend) to rebuild their quantization policy. None of that can run in CI. +- This PR must stay at zero regressions. A GPU-only, unmeasured, lossy option does not fit. +- The grouping already exists. `CudaPerformanceSection` ("Performance (CUDA)") holds Torch Compile and Diffusion stage cache. A new toggle belongs there. + +Proposed experiment after the upgrade ships: + +1. Add `use_rowwise_fp8_gemm` to `AppSettings` (default off). Hide it unless `supports_fp8_gemm(device)`. +2. In each pipeline constructor, wrap the fp8 policy with `with_rowwise_fp8_gemm` when the setting is on. +3. Measure speed and compare outputs on an RTX 4090 and 5090 with `performance_runner` before any default change. + +## Packaging + +- `uv.lock` changes, so the Python deps hash changes. Windows and Linux users download a new Python environment on first start. +- Build and upload the archive for the new hash before the release (`electron/python-setup.ts`, `scripts/prepare-python.*`). +- `uv lock` fails in the current CI image with a resolver error on Python 3.14 markers. This also happens on `main`. The lock was edited by hand (only the two ltx entries). `uv lock --check` passes. +- Developers run `uv sync` in `backend/` after they pull. + +## Open PRs + +No open PR conflicts with the 1.5.0 change as text. Each PR got a comment with the steps to follow after the merge. + +| PR | Effect | +| --- | --- | +| #464 | `pyproject.toml` and `uv.lock` merge cleanly. Run `uv lock --check` after the merge. | +| #463, #441, #446 | Budget constants and docs say "measured on 1.4.1". Re-check them against 1.5.0. #441 and #446 also conflict with `main` already. | +| #454 | `generate_still` calls `_run_inference(images=[])`. It still works. `_run_inference` has a new keyword `guide_all_images` with a default. | +| #457, #448 | New stills or recipes must go through `to_ltx_images`. They must not build upstream inputs by hand. | + +## Follow-ups (not in this PR) + +- Ablation of the `diffvae_decode_vram` clamp on a 32 GB card. +- Re-measure hardware budgets on 1.5.0. Refit only on an unsafe miss (`docs/hardware-budgets.md`). +- Rowwise FP8 experiment (above). +- Optional: compare the upstream `alpha_gen` pipeline with the `alpha-gen` recipe. diff --git a/docs/nag-negative-prompt-phase0-findings.md b/docs/nag-negative-prompt-phase0-findings.md new file mode 100644 index 000000000..5bf933acf --- /dev/null +++ b/docs/nag-negative-prompt-phase0-findings.md @@ -0,0 +1,163 @@ +# NAG negative prompt: Phase 0 findings + +Base: branch `cursor/ltx2-1-5-0-upgrade-f80d` (PR #465, LTX-2 v1.5.0). +Source read: `Lightricks/LTX-2` tag `v1.5.0` (`ltx-core`, `ltx-pipelines`). +Plan: `nag-negative-prompt-poc-plan.md` (Bar Galili). + +Status: read-only exploration. No product code changed. + +## 1. Generation path (fast pipeline) + +1. `handlers/video_generation_handler.py` calls `pipeline_state.pipeline.generate(...)` (line ~850). +2. `LTXFastVideoPipeline.generate` (`services/fast_video_pipeline/ltx_fast_video_pipeline.py`) calls `_run_inference`. +3. `_run_inference` calls `DistilledPipelineWithSkipStage2` (Desktop subclass in `distilled_skip_stage_2.py`) as `__call__` or `stream_chunks`. +4. The parent class is `ltx_pipelines.distilled.DistilledPipeline`. Desktop wraps and subclasses it. Desktop does not vendor it. +5. `DistilledPipeline._prepare_run` encodes the prompt with `self.prompt_encoder([prompt], ...)`. It returns `ctx_p.video_encoding` and `ctx_p.audio_encoding`. +6. `stream_chunks` passes both encodings into `generate_uniform_chunks(context=VideoAudio(...))`. `denoise_chunks` then runs stage 1 and stage 2 through `DiffusionStage`. +7. `ltx_pipelines/utils/helpers.py` (line ~540) builds `Modality(context=..., context_mask=None)`. +8. `TransformerArgsPreprocessor` (`ltx_core/model/transformer/transformer_args.py`) puts `context` into `TransformerArgs`. +9. `BasicAVTransformerBlock.forward` reads `video.context` and `audio.context`. + +Result: long-form windows and both stages share one `context` per chunk. A negative context has the same lifetime. + +## 2. Text cross-attention modules (v1.5.0) + +All paths are under `ltx_core/model/transformer/`. + +| Modality | Module | Q | K/V | Call site | +|---|---|---|---|---| +| Video | `BasicAVTransformerBlock.attn2` | video `vx` | text `video.context` | `transformer.py` ~240 | +| Audio | `BasicAVTransformerBlock.audio_attn2` | audio `ax` | text `audio.context` | `transformer.py` ~270 | + +Do not patch these modules: + +- `attn1` and `audio_attn1` (self-attention). +- `audio_to_video_attn` and `video_to_audio_attn` (audio and video cross-attention). + +Both text cross-attention calls go through `BasicAVTransformerBlock._apply_text_cross_attention`. It has two branches: + +- `cross_attention_adaln` is false: `attn(x_normed, context=context, mask=context_mask)`. +- `cross_attention_adaln` is true: `apply_cross_attention_adaln(...)`. + +## 3. Finding that changes the plan: AdaLN on K/V + +With `cross_attention_adaln`, the context is modulated before attention: + +``` +encoder_hidden_states = context * (1 + scale_kv) + shift_kv +``` + +`shift_kv` and `scale_kv` come from `prompt_scale_shift_table`. They also come from `prompt_timestep` when `use_prompt_adaln_single` is true. + +- The negative context must use the same modulation as the positive context. If it does not, `Z_neg` is wrong. +- The query side (`attn_input`) and the output gate (`q_gate`) are shared. `q_gate` multiplies the final output. +- Open question: apply NAG before or after `q_gate`? NAG on the raw attention output (before `q_gate`) matches the plan formula. Check against KJNodes. + +The `attn(...)` call also runs `to_out` (and optional per-head gating) inside `Attention.forward`. The plan formula works on the output after `V`. Decide whether NAG works before or after `to_out`: + +- Before `to_out`: matches the paper. It needs a patch inside `Attention.forward`, because `out` is local there. +- After `to_out`: `to_out` is linear, so extrapolation is equivalent. The L1 norm and the clip are not equivalent. +- Per-head gating (`to_gate_logits`) depends only on `x`. It applies to both branches equally. + +Open question for the PoC: use the pre-`to_out` tensor. Confirm with KJNodes. + +## 4. Attention kernel and hooks + +- `Attention.forward` calls `self.attention_function(q, k, v, heads)` when `mask is None`. It calls `self.masked_attention_function(...)` otherwise. +- The kernels are `PytorchAttention` (SDPA), `FlashAttention3`, `FlashAttention4`, `MPSSdpaAttention`. They come from `AttentionOps`. +- There is no processor or hook mechanism. Plan a forward patch. +- The text context mask is always `None` in `ltx-pipelines` (`context_mask=None`). The plan item "handle the negative attention mask" reduces to: pass `mask=None` for both branches. Gemma padding is handled inside the embeddings processor. +- Both contexts have the same sequence length, because the embeddings processor pads to a fixed length. Verify this once on a real run. + +## 5. Text encoding + +- `PromptEncoder.__call__(prompts: list[str], ...)` returns one `EmbeddingsProcessorOutput` per prompt. Gemma is loaded once, then freed. +- `ltx_retake_pipeline.py` already encodes `[prompt, negative_prompt]` in non-distilled mode. Use the same pattern: `prompts_to_encode = [prompt, negative]`. +- The prompt enhancer is controlled by `enhance_first_prompt`. It applies to the first prompt only. The negative prompt stays out of it by position. +- Desktop also pre-warms text encoding through `self._text.prepare_text_encoding(...)` in the handlers. Check that this path can include the negative prompt. + +## 6. Optimizations that interact with NAG + +| Feature | Where | Effect | +|---|---|---| +| FP8 cast policy | `build_fp8_cast_policy`, `device_supports_fp8` | Extra `to_k`, `to_v` projections on the negative context run through the same weights. No new weights. | +| `torch.compile` | `compile_transformer` uses `CompilationConfig()`; `ltx_core/.../compiling.py` | `mark_dynamic` covers `args.context_mask` dim 2 only. A new tensor or a changed context length can cause a recompile. Pad the negative context to the positive length. | +| CUDA graph capture | `CompilationConfig` capture is off in Desktop | No change now. A future capture would need a fixed NAG shape. | +| Streaming or offload | `OffloadMode`, `streaming_prefetch_count` | No weights added. The extra memory is small (one K/V pair per layer, transient). | +| Transformer cache patch | `services/patches/diffusion_stage_cache.py` | Caches the built transformer. A forward patch applied to the class (not the instance) survives the cache. | +| Step caching | None found | n/a | + +## 7. Chosen injection point + +Patch `BasicAVTransformerBlock._apply_text_cross_attention` (and, for the AdaLN branch, the `apply_cross_attention_adaln` path) in a new `services/patches/nag_cross_attention.py`. Follow the style of the other files in `services/patches/`. + +- The negative context travels in a context variable that the patch reads. The pipeline wrapper sets it around one generation. +- This avoids editing `TransformerArgs`, `Modality` and `ModalitySpec`, which are upstream types. +- A strict no-op: when the context variable is unset, call the original method. The output stays bit-identical. +- Add the patch to the `services.patches` re-verify list (see `.cursor/rules/ltx2-patch-reverify.mdc`). + +Alternative (rejected for the PoC): add `negative_context` to `Modality`. It is cleaner but touches many upstream call sites and breaks on every upgrade. + +## 8. Data flow + +``` +negativePrompt (request) + -> handler passes it to pipeline.generate(negative_prompt, nag_*) + -> DistilledPipelineWithSkipStage2._prepare_run: prompt_encoder([prompt, negative]) + -> ctx_p (as today) + ctx_n + -> set NAG context var (v_neg, a_neg, scale, alpha, tau) + -> denoise_chunks stage 1 (and stage 2, per experiment) + -> patched text cross-attention reads the context var + -> clear the context var in a finally block +``` + +Notes: + +- `ctx_n` is encoded once per job. It is reused across steps, both stages and all long-form windows. +- The skip-stage-2 path (`distilled_skip_stage_2.py`) has its own `_prepare_run` copy and must be changed too. +- The A2V pipeline (`ltx_a2v_pipeline.py`) already takes a `negative_prompt`. Check what it does with it in distilled mode before reusing the name. + +## 9. Affected callers + +Wire the new parameters for each caller, or state "not supported yet": + +- `handlers/video_generation_handler.py`: fast text-to-video, image-to-video, keyframes (line ~850). +- Long-form windows: `windowed_run.py` and `stream_chunks` (same context var). +- `distilled_skip_stage_2.py`: the skip-stage-2 variant. +- `handlers/retake_handler.py`, `services/features/video/retake.py`, `extend.py`, `edit_executor.py`: they pass `default_negative_prompt`. Keep NAG off for them in the PoC. +- `handlers/ic_lora_handler.py`: IC-LoRA (`ic_lora_pipeline`, tiled variant). Out of scope for the PoC. +- A2V (`a2v_pipeline`): out of scope for the PoC. +- Remote API: `remote/dto.py` has no negative prompt field. Phase 3. +- Seed Hunt drafts and rerenders: Phase 3 (persist NAG parameters). + +Existing wiring to know: + +- `api_types.py` already has `negativePrompt: str = ""` on the video request (line ~831). The fast pipeline ignores it today. +- `video_generation_handler.py` falls back to `default_negative_prompt` only on the A2V path (line ~968). +- `ltx2_server.py` defines `DEFAULT_NEGATIVE_PROMPT` (line ~318). + +## 10. Open questions (answered) + +1. Extrapolation convention: KJNodes `LTX2_NAG` uses `s * Z_pos - (s - 1) * Z_neg`. Desktop uses the same, so the KJNodes defaults (`scale=11`, `alpha=0.25`, `tau=2.5`) apply as they are. In the plan's formula this is `s_plan = scale - 1`. +2. Guided tensor: the attention output after `V`, before the per-head gate and `to_out`. KJNodes does the same (`ltxv_crossattn_forward_nag`). The gate and `to_out` stay shared. +3. Clip: KJNodes clips when the L1 ratio is above `tau` and maps a NaN ratio to 10. Desktop copies both. +4. KJNodes gives the NAG context no mask. Desktop gives the negative half no mask either. +5. `negativePrompt` contract: the field already exists. With the flag off, it stays ignored on the fast path. With the flag on, a non-empty value turns NAG on. +6. `DEFAULT_NEGATIVE_PROMPT` is not used for NAG. It was written for CFG models. A hidden default list is a Phase 3 decision. +7. Stage 1 only or both stages: Phase 1 guides every denoise call (both stages). The sweep belongs to Phase 2. + +New finding (API text encoding): `LTXTextEncoder` patches `PromptEncoder.__call__` in API mode. It returns zeros for every prompt after the first. NAG with a zero negative is wrong. The handler skips NAG when the text encoding is not local, and logs a warning. + +## 11. Implementation status (Phases 1-3) + +Done on branch `nag-negative-prompt-poc`: + +- `services/fast_video_pipeline/nag_config.py`: `NagConfig`, `nag_config_for_request` (enabled when `negativePrompt` is non-empty and `scale > 0`, unless `LTX_NAG_ENABLED=0`), optional `LTX_NAG_SCALE`, `LTX_NAG_ALPHA`, `LTX_NAG_TAU`. +- `services/patches/nag_cross_attention.py`: the `attn2` patch and `nag_scope`. +- `services/fast_video_pipeline/nag_distilled.py`: encodes the negative prompt in the same Gemma pass, appends it to the video context, and scopes NAG to the denoise calls. +- `DistilledPipelineWithSkipStage2`, `LTXFastVideoPipeline.generate`, the protocol, the fake and `video_generation_handler.py` pass `nag` through. +- `state/app_settings.py`, `AppSettingsContext.tsx`, `SettingsModal.tsx`: `nag_scale` (`nagScale`, default `11.0`) setting in **General > Generation**. +- `api_types.py`, `queued_generation_handler.py`, `remote/dto.py`: `nagScale`, `nagAlpha`, `nagTau` persisted on queued generations and projected to Remote so retries and rerenders reproduce. +- `textToVideo.ts`, `imageToVideo.ts`, `loraRecipe.ts`: `Negative prompt` textarea exposed on Home and Remote forms. +- Tests: `backend/tests/test_nag_cross_attention.py`, `backend/tests/test_remote_generations.py`, `textToVideo.test.ts`, `imageToVideo.test.ts`. + diff --git a/docs/remote-lan.md b/docs/remote-lan.md index 18cf27eb6..dd8fa2bfc 100644 --- a/docs/remote-lan.md +++ b/docs/remote-lan.md @@ -69,7 +69,15 @@ The Remote server exposes only the Explore surface: available, plus `defaultProvider` (Gemini if a Desktop key is stored, otherwise local Gemma when downloaded). Does not return API keys or filesystem paths. -- `POST /api/enhance-prompt` — rewrite the prompt. Image frames and the source +- `POST /api/generations/text-to-image` — queued Z-Image Turbo image, on the same + queue and `/api/generations` list, get, retry, cancel, and delete as video. + Body `provider` is `local` or `fal`; omit it to follow the Desktop setting. The + phone can spend the Desktop's stored fal key and local GPU. It never reads or + changes the key. +- `GET /api/image-generation/status` — which image providers can run now and + why not (`localBlocker`, `falBlocker` codes only), plus `defaultProvider`. +- `POST /api/enhance-prompt` — rewrite the prompt. `mediaType: "image"` rewrites a + text-to-image prompt and takes no image asset ids. Image frames and the source video (`videoAssetId`, with `icLoraId` for an IC-LoRA) are asset ids, never paths. A video can stand in for the prompt. A Retake also sends `replacedWindow` (`start`, `end` in seconds), so the stills come from around the part it replaces. Body `provider` is `local` or `api`; omit it to use @@ -98,7 +106,7 @@ These stay off `:41955`: - Desktop path ingest (`POST /api/assets`). - Model downloads and Hugging Face auth (except the LoRA recipe preflight already on this port). -- Image generation (Gen Space only). +- Gen Space image generation and editing (`POST /api/generate-image`). The assistant's tools run inside the shared `AppHandler`, not through these routes. Jobs started from a phone chat report `analytics_client="remote"`. diff --git a/docs/setup-and-settings.md b/docs/setup-and-settings.md index 8a5e5f4f5..c728dec80 100644 --- a/docs/setup-and-settings.md +++ b/docs/setup-and-settings.md @@ -2,35 +2,7 @@ ## Platform requirements -These values match the [LTX Desktop page](https://ltx.io/ltx-desktop). All platforms need **100 GB+ free disk space**, up to **160 GB+** with additional LoRAs and IC-LoRAs. - -### Windows (local generation) - -- Windows 10/11 (64-bit) -- NVIDIA GPU with CUDA, **24 GB+ VRAM** (32 GB recommended) -- 32 GB RAM - -### Linux (local generation) - -- Ubuntu 22.04+ or similar distro (x64 or arm64) -- NVIDIA GPU with CUDA and the NVIDIA driver installed (PyTorch bundles the CUDA runtime), **24 GB+ VRAM** (32 GB recommended) -- 32 GB RAM - -### macOS (local generation) - -- macOS 26+ (Tahoe) for local generation. The app itself needs macOS 14 or later. On macOS 14 and 15 the app shows the **Coming soon to your device** notice. -- Apple Silicon (M1 or later) with **48 GB+**: full local generation -- Apple Silicon with 32 GB: limited (540p and 5 s only) -- Apple Silicon with less than 24 GB, or an Intel Mac: Gen Space API only. Intel Macs have no MPS backend. - -### Lower-spec machines - -The app offers local generation on lower-spec machines, but we do not recommend them. The app uses these floors (see `backend/runtime_config/runtime_policy.py` and `docs/local-compat-matrix.md`): - -- CUDA: **9 GiB VRAM** on Windows with an fp8-capable GPU, **15 GiB** otherwise (Linux, non-fp8 Windows; integer GiB from `total_memory // 1024**3`) -- macOS: **32 GiB total RAM** (machine SKU, not free RAM at launch) and **macOS 26 or later** - -Below a floor, local generation is unavailable and the app shows the **Coming soon to your device** notice. An LTX API key is not required. +Recommended specs, disk space and the hardware floors are in the README's [System requirements](../README.md#system-requirements). What each GPU and Mac size can run, the RAM each job needs, and Brave and Cautious modes are in [`hardware-compatibility.md`](hardware-compatibility.md). ## First run & data locations @@ -62,7 +34,7 @@ Open **Settings** from the bottom of the sidebar. | Tab | What it controls | | --- | --- | -| **General** | Appearance (theme: system, light, or dark); auto-enhance for local and API generation; fast decode (faster video decode with slightly lower fidelity); text encoding (LTX API or local encoder); NVIDIA performance options (Torch Compile and diffusion stage cache, experimental); anonymous analytics | +| **General** | Appearance (theme: system, light, or dark); auto-enhance for local and API generation; fast decode (faster video decode with slightly lower fidelity); text encoding (LTX API or local encoder); NVIDIA performance options (Torch Compile and diffusion stage cache, experimental); Apple Silicon performance options (faster Fast decode, experimental, Mac only); anonymous analytics | | **Models** | Download and manage checkpoints, LoRAs, and encoder models. See [Managing models](models-and-loras.md#managing-models). Hidden in API-only mode | | **Legacy** | Options for Gen Space and the Video Editor: project assets folder, default base model, preference for cloud video and image generation, and seed lock | | **API Keys** | Optional LTX, fal, and Gemini keys. The app checks a key before it saves it, and you can remove a saved key | diff --git a/docs/skills/measuring-hardware-cells.md b/docs/skills/measuring-hardware-cells.md new file mode 100644 index 000000000..3ca055be9 --- /dev/null +++ b/docs/skills/measuring-hardware-cells.md @@ -0,0 +1,611 @@ +--- +name: measuring-hardware-cells +description: >- + Use when measuring local hardware capability cells on a GPU or Apple Silicon + Mac, benchmarking peak VRAM or unified memory and step times across + resolutions or durations, finding the true OOM or paging cliff in Cautious or + Brave mode, diagnosing silent WDDM shared-memory paging or macOS swap + thrashing, or contributing empirical hardware measurements and budget law + improvements. +--- + +# Measuring Hardware Capability Cells Locally + +## Overview + +LTX Desktop decides what a local machine can generate, edit, or run with IC-LoRA using continuous token-based memory laws and measured-cell registries in `backend/runtime_config/`. This skill guides contributors and maintainers through pricing a hardware capability cell in code, instrumenting real runs on Windows/Linux (CUDA) or Apple Silicon (MPS), avoiding platform-specific allocator traps, binary-searching the true hardware cliff, and reporting reproducible results to improve the budget planner and compatibility docs. + +### Related Documentation + +| Document | Role | +| --- | --- | +| `docs/hardware-compatibility.md` | User-facing guide showing what each GPU and Mac tier runs in Cautious mode, priced directly from `backend/runtime_config/` | +| `docs/local-compat-matrix.md` | Generated tool × hardware-band matrix (`cd backend && uv run python -m runtime_config.local_compat_matrix`; never hand-edit) | +| `backend/performance_runner/README.md` | Headless backend performance harness (`pnpm perf:dev`), GPU/RAM samplers, and live regression scenarios | + +> **Note for maintainers:** If your checkout includes the maintainer skill `maintaining-hardware-budgets` (`docs/skills/maintaining-hardware-budgets.md`), also follow its change-to-doc table when updating budget laws, floors, or measured-cell registries. + +--- + +## 1. Anatomy of a Hardware Cell + +A **hardware cell** is a specific combination of workflow, model, canvas geometry, frame count, execution strategy, and budget mode. Every axis below affects either the predicted memory ask or the admission verdict: + +1. **Workflow / Feature (`BudgetFeature` in `runtime_config/measured_cells.py`)**: + - **Fast (`fast`)**: Distilled text-to-video (T2V), image-to-video (I2V), and audio-to-video (A2V) (`decide_video_job`). All three modalities share one token law; single-pass and windowed runs price the heaviest stage-2 pass. + - **Video Edit (`edit`)**: **Retake** (regenerate a segment inside a source clip) and **Extend** (generate new frames anchored to source context frames) (`decide_edit_job`). Retake and Extend share one single-pass token law (`tokens = (W / 32) * (H / 32) * latents`) plus a single-tile DiffVAE decode law on Windows. Edits **never** chunk or tile during denoising (`windows = 1`); instead, `max_edit_frames_that_load` binary-searches the longest frame window (up to `MAX_INPUT_FRAMES`) that fits the machine. + - **IC-LoRA (`iclora`)**: Catalog video-to-video recipes (such as Day to Night, Water Simulation, Restore, Refine Details, Video Guide) and image-to-video **Ingredients** (`decide_ic_lora_job`, plus recipe frame caps via `IcLoraHandler.recipe_run_frames` and `POST /api/generations/ic-lora-recipes/{recipe_id}/memory`). Distinguishes `IcLoraStageMode` (`SINGLE_STAGE` vs `TWO_STAGE`), reference still count (`stills`), and full-res vs half-res reference adapters (`_HALF_RES_REF_IC_LORAS`). +2. **Model Version (`LTXLocalModelId`)**: + - Resolved via `get_latest_ltx_model_id()` (or `ALL_LTX_LOCAL_MODEL_IDS` in `runtime_config/model_download_specs.py`). Any model ID not in `MEASURED_LOCAL_MODEL_IDS` is tagged `Extrapolated(basis="unmeasured_model")`. +3. **Resolution & Aspect Ratio (Real Canvas vs Priced Canvas)**: + - Resolution labels in code and API requests are `"540p"`, `"720p"`, `"1080p"`, `"1440p"`, and `"2160p"` (**always use `"2160p"`, never `"4K"`, when calling budget or capability helpers**). + - Aspect ratios: `"16:9"`, `"9:16"`, `"1:1"`, `"21:9"`, `"3:2"`, `"4:3"`, `"4:5"` (`"21:9"` is not offered at `"2160p"`). + - **Real canvas**: `pixels_for(local_caps(model_id), resolution, aspect)` returns the actual `width x height` (snapped to the 64-px two-stage grid) that the pipeline executes. + - **Priced canvas**: `budget_pixels(local_caps(model_id), resolution, aspect, mode="video")` returns the canvas the budget prices. Ratios narrower than `16:9` (`1:1`, `4:3`, `4:5`, `3:2`) are floored at the `16:9` anchor canvas so the duration picker stays consistent across shapes; wider or larger canvases (`21:9` everywhere, `9:16` at `1440p`) are priced at their own dimensions. + - **Edit canvas**: Video edits letterbox the source onto a 32-px grid without upscaling (a native `2560x1440` source runs at `2560x1440`, whereas Fast `1440p` `16:9` runs at `2560x1472`). +4. **Duration, Frame Rate (`fps`), and the `8k + 1` Frame Grid**: + - Pixel frames must sit on the causal VAE grid `8k + 1`: `frames = compute_num_frames(duration_s, fps)` (`frame_math.py`), producing `latents = (frames - 1) // 8 + 1` temporal latent frames. + - Transformer sequence tokens for one pass of `F` pixel frames on canvas `W x H`: + $$\text{seq} = \text{video\_tokens}(H, W, F) = \left(\frac{F - 1}{8} + 1\right) \times \frac{W}{32} \times \frac{H}{32}$$ + - `48` and `50` fps double `frames` (and `seq`) compared to `24` and `25` fps at the same duration. +5. **Execution Geometry (Load Mode, Temporal Chunking, Spatial/Decode Tiling)**: + - **Load mode (`LoadMode`)**: `full_models_loading` (weights stay resident in VRAM) vs `streaming_models_loading` (weights stream layer-by-layer during each step via `OffloadMode.DISK` or `OffloadMode.CPU`; identical output pixels). Macs always use `streaming_models_loading` (`OffloadMode.DISK`). + - **Single-pass vs Chunked Parts (`fast_chunking.py`, `ic_lora_chunking.py`)**: + - Canvases at or above `CHUNKED_CANVAS_MIN_SHORT_SIDE` (`1440p` and `2160p`) longer than one window always run in overlapping temporal windows (`parts`). Canvases below `1440p` run in a single pass when it fits, and automatically step down into overlapping windows when a single pass exceeds the device ceiling (`_windows_help`). + - `window_candidates(W, H)` lists valid `8k + 1` window lengths from longest (capped by `MAX_WINDOW_TOKENS`) down to `MIN_WINDOW_FRAMES`. Consecutive windows overlap by `CARRY_FRAMES` (Fast) or `ic_lora_carry_frames(tiling)` (IC-LoRA). + - Window count is `windows = job_window_count(frames, chunk_pixel_frames, carry_frames)`, and the final window runs `last_window_frames(frames, chunk_pixel_frames, carry_frames)` frames. + - In multi-window runs, peak memory rises from Window 1 (`w1`) to Window 2 (`w2`, which carries overlap state from Window 1) and plateaus from Window 3 (`PEAK_PLATEAU_WINDOWS`) onward (`w3..wN`). + - **Spatial & Decode Tiling (`ic_lora_tiling.py`, `ic_lora_high_res.py`, `ic_lora_decode_window.py`)**: + - Tiled IC-LoRAs (Restore, Refine Details, and any recipe at `1440p`/`2160p` with `highResVideoToVideo` enabled) run denoising one spatial tile at a time (`transformer_pass_size`), then run DiffVAE decode over the full canvas (using `choose_decode_window` and `diffvae_decode_vram` to tile decode). +6. **Budget Mode (`cautious` vs `brave`) and Pass Shape (`auto`, `one_pass`, `parts`)**: + - **Cautious (`"cautious"`)**: Admits only cells that fit the memory budget AND have measured coverage (`Fitted`, or covered by the device's local `DeviceCalibration` frontier). Refuses `stream_over`, `ram_shortfall`, and `unmeasured_cell`. + - **Brave (`"brave"`)**: Allows `stream_over`, `ram_shortfall`, and `unmeasured_cell` as confirmable `GenerationRisk` bets (`tier="over"` or `tier="unmeasured"`). Brave never bypasses hard walls (`unsupported`, `mps_sequence_over`, `one_pass_unavailable`, `spatial`, `refine_decode_floor`). + +--- + +## 2. Pre-Flight & Machine Hygiene + +Before running any measurement cell, standardize the host environment so runs are reproducible and free of background noise: + +1. **Record the hardware & software baseline**: + - Capture OS/kernel build, GPU model or Apple Silicon chip, GPU driver version, exact total and idle-free VRAM bytes (`torch.cuda.mem_get_info(0)`) or macOS total RAM + Metal pool (`torch.mps.recommended_max_memory()`), total and available system RAM, storage bus type for the checkpoint directory (`nvme`, `ssd`, `hdd`), Python, `torch`, `ltx-core`, and `ltx-pipelines` versions, active `model_id`, and attention backend (`SageAttention` on CUDA; `picked=mpsgraph_zc active=True` on Apple Silicon). +2. **Close background GPU and memory consumers**: + - On CUDA, execution-time admission gates on `min(total_vram, free_vram)`. Browsers, Electron apps, video editors, or secondary monitors occupying 1–3 GiB of VRAM will both trigger premature `stream_over` refusals (or edit-window shrinking) and cause early WDDM paging. Prefer running against the headless backend (`pnpm perf:dev`). + - On Linux laptops with hybrid GPUs, verify whether the desktop display server is hosted on the iGPU or the NVIDIA dGPU (`nvidia-smi` `Display Active`). +3. **Prevent system sleep and power throttling**: + - Keep laptops plugged into AC power with high/normal performance mode enabled (Low Power Mode off). + - **macOS**: Run `caffeinate -dimsu -t ` in a separate terminal and verify with `pmset -g assertions | grep -i prevent`. + - **Windows**: Prevent sleep via PowerShell `SetThreadExecutionState(0x80000003)` for the duration of the sweep. + - **Linux**: Wrap long sweeps in `systemd-inhibit --what=idle:sleep`. +4. **Distinguish Cold-Start vs Warm Steady-State runs**: + - **Cold run (required for peak memory / edge measurements)**: Launch a fresh backend process per cell so cached allocator blocks or fragmentation from a previous cell cannot skew Window 1 peaks. When benchmarking loader I/O (`load_s`), also empty the OS standby/page cache before starting (`RAMMap64.exe -accepteula -Et` on Windows; `sudo purge` on macOS). + - **Warm run (for steady-state throughput & retention soak)**: Run subsequent jobs in the same backend process to measure warm step time (`s/step`), stage-cache speedups, or multi-job memory retention (running a cell 5–10 times back-to-back in `soak_test.py` to confirm inter-job VRAM and RSS return to a flat floor). + - **Deterministic payload controls**: Fix `seed: 42`, use a constant prompt with prompt rewrite bypassed (`promptProvenance: "enhanced"`), and keep `Torch Compile` off unless specifically testing compilation. + +--- + +## 3. How to Price a Cell Before Running + +Never guess or hardcode expected GiB numbers—laws and constants move when refit. Always query `runtime_config` directly from `backend/` to inspect what the planner predicts for your live machine or any target hardware tier: + +```bash +cd backend && UV_FROZEN=1 uv run python - <<'EOF' +import importlib.metadata +import json +import platform +from pathlib import Path + +import torch + +from frame_math import compute_num_frames +from runtime_config.accelerator import accelerator_supports_fp8 +from runtime_config.budget_admission import Admitted +from runtime_config.device_calibration import CALIBRATION_EPOCH +from runtime_config.fast_chunking import CARRY_FRAMES, job_window_count, last_window_frames +from runtime_config.ic_lora_chunking import ic_lora_carry_frames +from runtime_config.ic_lora_high_res import high_res_tiling +from runtime_config.ic_lora_job_budget import ( + HOME_IC_LORA_PREVIEW_SETTINGS, + catalog_preview_stage1, + decide_ic_lora_job, +) +from runtime_config.ic_lora_stage_mode import IcLoraStageMode +from runtime_config.ic_lora_tiling import IcLoraTiling +from runtime_config.local_runtime import resolve_local_runtime +from runtime_config.ltx_capabilities import budget_pixels, local_caps, pixels_for +from runtime_config.macos_version import detect_macos_major +from runtime_config.model_download_specs import get_latest_ltx_model_id +from runtime_config.reject_reasons import BudgetMode, PassShape +from runtime_config.runtime_policy import decide_local_generation_mode +from runtime_config.video_job_budget import ( + NOMINAL_MPS_POOL_RATIO, + HardwareProfile, + LocalJobFilter, + MemoryBudget, + decide_edit_job, + decide_video_job, + mac_disk_stream_host_gib, + max_edit_frames_that_load, + memory_gb_for_job, + video_tokens, +) +from services.gpu_info.gpu_info_impl import GpuInfoImpl +from services.retake_pipeline.window import MAX_INPUT_FRAMES +from services.storage_info.storage_info import DriveType +from services.storage_info.storage_info_impl import StorageInfoImpl + +GIB = 1024**3 +MODEL = get_latest_ltx_model_id() +CAPS = local_caps(MODEL) + + +def live_filter( + *, + mode: BudgetMode = "cautious", + pass_shape: PassShape = "auto", + total_only: bool = False, + checkpoint_dir: Path | str = Path.home(), +) -> tuple[LocalJobFilter, dict[str, object]]: + """Build a LocalJobFilter from the current machine's live GPU/MPS/RAM probes.""" + gpu = GpuInfoImpl() + storage = StorageInfoImpl(checkpoint_dir) + sys_raw = platform.system() + system = sys_raw if sys_raw in ("Windows", "Darwin") else "Linux" + rt = resolve_local_runtime( + gpu, + system=system, + fp8_capable=accelerator_supports_fp8(), + storage_info=storage, + macos_major=detect_macos_major(), + ) + free_vram = gpu.get_free_cuda_vram_bytes() + mps_pool = gpu.get_mps_pool_bytes() + jf = LocalJobFilter( + profile=HardwareProfile( + system=system, # type: ignore[arg-type] + model_id=MODEL, + process_mode=rt.mode, + drive_type=rt.checkpoint_drive_type, + fp8_capable=rt.fp8_capable, + ), + budget=MemoryBudget( + total_vram_bytes=rt.vram_bytes, + free_vram_bytes=free_vram, + total_ram_bytes=rt.total_ram_bytes, + memory_gb=memory_gb_for_job( + vram_gb=rt.vram_gb, + available_ram_gb=rt.available_ram_gb, + darwin=rt.darwin, + ), + mps_pool_bytes=mps_pool, + total_only=total_only, + ), + budget_mode=mode, + pass_shape=pass_shape, + ) + meta = { + "system": system, + "os_release": platform.release(), + "gpu_model": rt.gpu_device_name, + "process_mode": rt.mode, + "vram_total_gib": round(rt.vram_bytes / GIB, 2) if rt.vram_bytes else None, + "vram_free_gib": round(free_vram / GIB, 2) if free_vram else None, + "mps_pool_gib": round(mps_pool / GIB, 2) if mps_pool else None, + "mac_loader_host_gib": round(mac_disk_stream_host_gib(MODEL), 2) if rt.darwin else None, + "ram_total_gib": round(rt.total_ram_bytes / GIB, 2) if rt.total_ram_bytes else None, + "drive_type": rt.checkpoint_drive_type, + "fp8_capable": rt.fp8_capable, + "torch": torch.__version__, + "ltx_core": importlib.metadata.version("ltx-core"), + "ltx_pipelines": importlib.metadata.version("ltx-pipelines"), + "model_id": MODEL, + "calibration_epoch": CALIBRATION_EPOCH, + } + return jf, meta + + +def band_filter( + system: str, + gib: float, + *, + ram_gb: int = 64, + free_gib: float | None = None, + mode: BudgetMode = "cautious", + pass_shape: PassShape = "auto", + drive_type: DriveType | None = "nvme", +) -> LocalJobFilter: + """Build a LocalJobFilter for any simulated GPU (gib=VRAM) or Mac (gib=unified RAM).""" + darwin = system == "Darwin" + vram_int = None if darwin else int(gib) + ram_int = int(gib) if darwin else ram_gb + process_mode = decide_local_generation_mode( + system, + not darwin, + vram_int, + mps_available=darwin, + ram_gb=ram_int, + macos_major=26 if darwin else None, + ) + total_vram_bytes = None if darwin else int(gib * GIB) + free_vram_bytes = ( + None + if darwin + else (int(free_gib * GIB) if free_gib is not None else total_vram_bytes) + ) + return LocalJobFilter( + profile=HardwareProfile( + system=system, # type: ignore[arg-type] + model_id=MODEL, + process_mode=process_mode, + drive_type=None if darwin else drive_type, + ), + budget=MemoryBudget( + total_vram_bytes=total_vram_bytes, + free_vram_bytes=free_vram_bytes, + total_ram_bytes=ram_int * GIB, + memory_gb=memory_gb_for_job( + vram_gb=vram_int, available_ram_gb=ram_int, darwin=darwin + ), + mps_pool_bytes=int(ram_int * GIB * NOMINAL_MPS_POOL_RATIO) if darwin else None, + total_only=(free_gib is None), + ), + budget_mode=mode, + pass_shape=pass_shape, + ) + + +def price_fast( + jf: LocalJobFilter, res: str, aspect: str, duration_s: int, fps: int = 24 +) -> dict[str, object]: + w_priced, h_priced = budget_pixels(CAPS, res, aspect, mode="video") + w_real, h_real = pixels_for(CAPS, res, aspect) + frames = compute_num_frames(duration_s, fps) + adm = decide_video_job(w_priced, h_priced, frames, job_filter=jf) + chunk_f = adm.priced.chunk_pixel_frames + windows = job_window_count(frames, chunk_f, CARRY_FRAMES) + last_f = last_window_frames(frames, chunk_f, CARRY_FRAMES) if chunk_f else frames + return { + "cell": f"fast {res} {aspect} {duration_s}s@{fps}fps ({frames}f)", + "mode": jf.budget_mode, + "canvas_real": f"{w_real}x{h_real}", + "canvas_priced": f"{w_priced}x{h_priced}", + "admitted": isinstance(adm, Admitted), + "verdict": adm.load.mode if isinstance(adm, Admitted) else adm.reject.reason, + "stream_gib": round(adm.priced.stream_gib, 2), + "full_gib": round(adm.priced.full_gib, 2), + "windows": windows, + "window_frames": chunk_f or frames, + "last_window_frames": last_f, + "seq_priced": int(adm.priced.seq), + "tokens_real": int(video_tokens(h_real, w_real, chunk_f or frames)), + "evidence": type(adm.priced.evidence).__name__, + "risk": ( + f"{adm.risk.tier}:{adm.risk.unmeasured_basis or adm.risk.shortfall_kind}" + if isinstance(adm, Admitted) and adm.risk + else ("none" if isinstance(adm, Admitted) else (adm.bet.tier if adm.bet else "hard_wall")) + ), + } + + +def price_edit( + jf: LocalJobFilter, width: int, height: int, frames: int | None = None +) -> dict[str, object]: + target_f = ( + frames + if frames is not None + else max_edit_frames_that_load(width, height, frame_cap=MAX_INPUT_FRAMES, job_filter=jf) + ) + adm = decide_edit_job(width, height, target_f, job_filter=jf) + return { + "cell": f"edit {width}x{height} ({target_f}f)", + "mode": jf.budget_mode, + "admitted": isinstance(adm, Admitted), + "max_frames": target_f if isinstance(adm, Admitted) else 0, + "max_seconds_24fps": round((target_f - 1) / 24, 2) if isinstance(adm, Admitted) else 0.0, + "verdict": adm.load.mode if isinstance(adm, Admitted) else adm.reject.reason, + "stream_gib": round(adm.priced.stream_gib, 2), + "seq": int(adm.priced.seq), + "evidence": type(adm.priced.evidence).__name__, + } + + +def price_iclora( + jf: LocalJobFilter, + stage1_w: int, + stage1_h: int, + duration_s: int, + *, + fps: int = 24, + ic_lora_id: str = "day-to-night", + stage_mode: IcLoraStageMode = IcLoraStageMode.SINGLE_STAGE, + tiling: IcLoraTiling | None = None, + stills: int = 0, +) -> dict[str, object]: + frames = compute_num_frames(duration_s, fps) + adm = decide_ic_lora_job( + stage1_w, + stage1_h, + frames, + stage_mode=stage_mode, + job_filter=jf, + ic_lora_id=ic_lora_id, + stills=stills, + tiling=tiling, + ) + chunk_f = adm.priced.chunk_pixel_frames + carry_f = ic_lora_carry_frames(tiling) + windows = job_window_count(frames, chunk_f, carry_f) + return { + "cell": f"iclora:{ic_lora_id} {stage1_w}x{stage1_h} {duration_s}s@{fps}fps ({frames}f)", + "mode": jf.budget_mode, + "admitted": isinstance(adm, Admitted), + "verdict": adm.load.mode if isinstance(adm, Admitted) else adm.reject.reason, + "stream_gib": round(adm.priced.stream_gib, 2), + "windows": windows, + "window_frames": chunk_f or frames, + "tiled": tiling is not None, + "seq": int(adm.priced.seq), + "evidence": type(adm.priced.evidence).__name__, + } + + +_, host_meta = live_filter() +print("Host profile:", json.dumps(host_meta, indent=2)) + +for mode in ("cautious", "brave"): + win16 = band_filter("Windows", 16, mode=mode) + print(price_fast(win16, "1440p", "16:9", 10, 24)) + print(price_edit(win16, 1920, 1088)) + print( + price_iclora( + win16, + 2560, + 1472, + 5, + ic_lora_id="water-simulation", + tiling=high_res_tiling(None), + ) + ) +EOF +``` + +- **Ingredients preview**: Pass `stage1_w, stage1_h = catalog_preview_stage1(HOME_IC_LORA_PREVIEW_SETTINGS)`, `stage_mode=HOME_IC_LORA_PREVIEW_SETTINGS.stage_mode`, and `ic_lora_id="ingredients"` (omitting `ic_lora_id` on macOS skips the Ingredients adapter term). +- **Home IC-LoRA video recipes**: To inspect the exact frame count a recipe runs after input-cap and budget trimming, query `POST /api/generations/ic-lora-recipes/{recipe_id}/memory` or call `IcLoraHandler.recipe_run_frames` (see `backend/tests/test_ic_lora_recipe_memory.py`). + +--- + +## 4. How to Run and Instrument a Cell + +### Running via the Local Backend + +1. **Launch the backend**: + - **Headless (preferred for measurements)**: Run `pnpm perf:dev` from the repo root. It starts the Python backend without Electron/Chromium GPU contention and opens the performance dashboard (`backend/performance_runner/README.md`). + - **Manual Apple Silicon launch**: Always prepend `backend/.venv/bin` to `PATH` so `ninja` is available to build the zero-copy `mpsgraph_zc` attention extension: + ```bash + cd backend + PATH="$PWD/.venv/bin:$PATH" LTX_APP_DATA_DIR=/tmp/ltx-meas LTX_PORT=41954 .venv/bin/python ltx2_server.py + ``` +2. **Select the right route and flags**: + - Enable `highResVideoToVideo: true` in settings when testing `1440p` or `2160p` Video Edit (Retake/Extend) or IC-LoRA cells. + - Submit `1440p` and `2160p` IC-LoRA recipes through the **queued Home recipe route** (`POST /api/generations/ic-lora-recipes/{recipe_id}`), which wires `high_res_settings` (`1440p`/`2160p` canvas and high-res spatial/temporal tiling). + - Switch to **Brave mode** (`budget_mode: "brave"`) when probing cells just above the Cautious boundary (`stream_over` or `unmeasured_cell`). +3. **Account for Device Calibration (`runtime_config/device_calibration.py`)**: + - At the end of every local generation, `CalibrationHandler.record_if_clean` runs `clean_run_verdict(identity, baseline, end)`: + - **CUDA**: `"clean"` when reserved VRAM growth stayed within `baseline.free_vram_bytes - PAGING_MARGIN_BYTES` and `min_free_vram_bytes >= MIN_FREE_FLOOR_BYTES`; otherwise logs `"vram_growth"` or `"free_floor"`. + - **Darwin**: `"clean"` when swap growth stayed within `SWAP_GROWTH_TOLERANCE_BYTES`; otherwise logs `"swap_growth"`. + - A `"clean"` run writes a `FrontierPoint(seq, canvas_px, windows)` into `store.sqlite3` (`device_calibration_frontier` table) under `CALIBRATION_EPOCH` and logs: + `[calibration] clean: seq= canvas= windows= (widened|already covered)` + - **Calibration side effect during sweeps**: Once a Brave run is recorded as `clean`, any subsequent cell in the same `CalibrationBucket` with `(seq, canvas_px, windows)` all `<=` that point is marked `covered=True` and **admitted in Cautious mode without an `unmeasured_cell` refusal**. Record your Cautious pre-flight verdicts *before* executing Brave runs, or isolate runs with a scratch `LTX_APP_DATA_DIR`. + +### Per-Phase Telemetry to Record + +Inspect the backend session log (`/logs/`) and hardware samplers for four phases on every run: + +| Phase | Log Markers & Probes | What to Record & Verify | +| --- | --- | --- | +| **0. Gate & Geometry Attestation** | `[video] job budget`, `[video-edit] job budget`, `[ic-lora] job budget`
`[hires-video] x in window(s) of frames (carry )`
`[ic-lora] stage-1 ...` / `chunked: ...` / `tiled: ...` | Verify `seq`, `stream=GiB`, `window=f`, real canvas `WxH`, and `OffloadMode.DISK` vs `CPU`. **Void the run** if the logged geometry does not match the target cell. | +| **1. Model Load & Text/Source Encode** | Job start → first denoise heartbeat | `load_s` (elapsed load + text/reference encode time) and `pre_window_peak_gib` (peak memory before Window 1 denoise starts, covering the text encoder, reference VAE encode, and any control preprocessors). | +| **2. Transformer Denoise Windows** | `[heartbeat] ... allocated=GiB reserved=GiB peak=

GiB free=/GiB alloc_retries=` (CUDA)
`[heartbeat] ... torch=GiB driver=GiB max=GiB \| sdpa: ...` (MPS)
`[hires-video] ... peak VRAM allocated
GiB, reserved GiB` | Per-window peak series `per_window_peaks_gib = [w1, w2, ..., wN]`, whole-run `allocated` and `reserved` (or `driver`) peaks, and steady-state step time **`s/step`** (seconds per denoising step in stage 1 and stage 2). | +| **3. DiffVAE Decode & Export** | `DiffVAE CUDA tiling after evict: measured= GiB budget= GiB xx t/h/w tiles=//`
`DiffVAE MPS tiling clamp xx t/h/w tiles=//` | `decode_s` (time from last denoise step to job completion), `post_window_peak_gib` (decode/stitch/export peak), verbatim decode tiling line, and `oom_phase` (`encode`, `denoise-w`, `decode`, `stitch`, `export`) if the run failed. | + +--- + +## 5. Platform-Specific Measurement Traps + +### Windows & Linux (CUDA) + +1. **`cuda_max_allocated` vs `cuda_max_reserved` — Never cap reserved-law runs**: + - `cuda_max_allocated` tracks active tensor bytes and predicts hard `CUDA out of memory` crashes. + - `cuda_max_reserved` tracks the PyTorch caching allocator's physical segment footprint and predicts **WDDM paging** on Windows. + - **Trap**: Do **not** set `torch.cuda.set_per_process_memory_fraction` or `PYTORCH_CUDA_ALLOC_CONF=max_split_size_mb:...` when measuring Windows reserved memory laws. A virtual cap forces PyTorch to flush cached segments whenever reservations approach the cap, making `cuda_max_reserved` artificially hug the cap while `cuda_max_allocated` stays constant—destroying the native reserved signal. + - **Rule**: Run **native (uncapped)** when measuring reserved laws. Use `torch.cuda.set_per_process_memory_fraction` on a large GPU *only* when testing whether `cuda_max_allocated` and post-evict DiffVAE decode tiling (`resolve_cuda_decode_tiling_retry`) survive inside a simulated smaller card's hard ceiling. + - In `full_models_loading` mode, `cuda_max_allocated` can sit flat across small and medium token counts (dominated by resident weights) while `cuda_max_reserved` climbs with tokens. Always record both metrics. +2. **Silent WDDM Shared-Memory Paging (`s/step` blow-up without OOM)**: + - On Windows (WDDM), when a job's working set exceeds physical free VRAM, the OS driver silently spills GPU pages into **Shared GPU Memory** (system RAM over PCIe) instead of raising `CUDA out of memory`. + - **Symptoms**: The job does not crash—it finishes very slowly or appears to stall while per-step denoise time (`s/step`) blows up **3x–10x+** and `alloc_retries` in `[heartbeat]` climbs as `cudaMalloc` thrashes the cache. + - **Rule**: Sample Windows **Shared GPU Memory** (Task Manager / `typeperf`) alongside `s/step` and `[heartbeat]` `free` / `alloc_retries`. If Shared GPU usage rises > 0.5 GB above idle baseline, `s/step` inflates 3x–10x, or calibration logs `vram_growth` / `free_floor`, record the outcome as **`paging-slowdown`** (a failed capacity point), **never** as `pass`. +3. **NVMe Disk-Streaming vs CPU Offload & Host RAM**: + - On Windows, `windows_checkpoint_streams_from_disk` routes NVMe volumes to `OffloadMode.DISK` and non-NVMe volumes to `OffloadMode.CPU` (each gated by its own system RAM floor in `video_job_budget.py`). + - Confirm from the backend log which offload mode ran, and monitor process `PeakWorkingSet64` and commit charge. If `OffloadMode.DISK` throughput is unexpectedly slow on Windows NVMe, check whether Windows Defender real-time protection is scanning the checkpoint directory on positional reads (`LTX_LOADER_READ_WORKERS`). + +### Apple Silicon Mac (MPS / Unified Memory) + +1. **Unified Memory Pool Ceiling & Loader Host Buffers (`mac_disk_stream_host_gib`)**: + - Macs gate local jobs against the Metal allocator ceiling `torch.mps.recommended_max_memory()` (`get_mps_pool_bytes()`, roughly `NOMINAL_MPS_POOL_RATIO` of total unified RAM). + - Alongside MPS tensors, the disk-streaming weight loader allocates ordinary host-memory read buffers and staging buckets **outside** the MPS allocator (`mac_disk_stream_host_gib(model_id)`). Because CPU and GPU share unified memory, `decide_mac_job` adds `mac_disk_stream_host_gib(model_id)` on top of the MPS allocator curve so `stream_gib` reflects total unified-memory demand. +2. **Native Driver Cache vs Capped Edge Brackets (`(F, P]`)**: + - **Trap**: Never compare an uncapped (native) Mac `driver_allocated_memory()` peak directly to `stream_gib`. On an uncapped pool, the Metal driver retains several GiB of lazy buffer cache above the true minimum working set. + - **Rule**: Use a native uncapped run only to observe the relative per-window step shape `[w1, w2, ..., wN]`. To measure the true Mac memory requirement of a cell (an **edge law**), bracket the MPS allocator in a fresh backend process per cap using: + ```python + pool_gib = torch.mps.recommended_max_memory() / (1024**3) + torch.mps.set_per_process_memory_fraction(cap_gib / pool_gib) + ``` + - Find the lowest passing cap `P` (completes with valid, non-flat frames) and the highest failing cap `F` just below `P` (HTTP 500 / Metal `Tried to allocate` OOM), establishing the allocator bracket `(F, P]`. When comparing an allocator cap `cap_gib` to `decide_mac_job`'s `stream_gib`, add `mac_disk_stream_host_gib(model_id)` to the allocator edge. +3. **macOS Swap / Compressor Thrashing & Attention Leak Tripwire**: + - When unified memory is over-committed, macOS compresses pages (`cmprs` in `top` / `vm_stat`) and swaps to SSD (`sysctl -n vm.swapusage`) instead of raising a Metal OOM, causing `s/step` to balloon. Monitor `sysctl -n vm.swapusage` and `memory_pressure`; if swap grows past `SWAP_GROWTH_TOLERANCE_BYTES` or thrashing occurs, abort and record **`paging-slowdown`** (`fail-swap`), not `pass`. + - Verify the first `[heartbeat]` line prints `picked=mpsgraph_zc active=True`. If `driver` climbs ~2 GiB every 15 s while `torch` stays flat, the fallback attention path is leaking because `ninja` was not on `PATH`—abort and fix `PATH` before measuring. + +--- + +## 6. Designing a Cell Sweep (Binary-Searching the Cliff) + +Do not brute-force every `(resolution × aspect × fps × duration)` combination. Use the budget predictor and invariant transfers to locate the true boundary in a few anchor runs: + +```dot +digraph sweep_cliff { + "Price target grid in Cautious & Brave" [shape=box]; + "Run Anchor A (highest Cautious-admitted cell)" [shape=box]; + "Anchor A clean pass?" [shape=diamond]; + "Binary-search DOWN (frames / window) to find highest clean pass" [shape=box]; + "Run Anchor B (lowest Cautious-refused cell) in Brave mode" [shape=box]; + "Anchor B clean pass?" [shape=diamond]; + "Jump to ceiling Nw cell (records [w1..wN] in one run); binary-search only if ceiling fails" [shape=box]; + "Cliff bracketed: (Anchor A, Anchor B]" [shape=box]; + + "Price target grid in Cautious & Brave" -> "Run Anchor A (highest Cautious-admitted cell)"; + "Run Anchor A (highest Cautious-admitted cell)" -> "Anchor A clean pass?"; + "Anchor A clean pass?" -> "Binary-search DOWN (frames / window) to find highest clean pass" [label="no (OOM / paging)"]; + "Anchor A clean pass?" -> "Run Anchor B (lowest Cautious-refused cell) in Brave mode" [label="yes"]; + "Run Anchor B (lowest Cautious-refused cell) in Brave mode" -> "Anchor B clean pass?"; + "Anchor B clean pass?" -> "Cliff bracketed: (Anchor A, Anchor B]" [label="no (OOM / paging)"]; + "Anchor B clean pass?" -> "Jump to ceiling Nw cell (records [w1..wN] in one run); binary-search only if ceiling fails" [label="yes"]; +} +``` + +1. **Pick Anchor A and Anchor B from the pricing script**: + - **Anchor A**: Highest duration / frame count at the target resolution admitted in `cautious` mode. + - **Anchor B**: Lowest duration / frame count refused in `cautious` mode (`stream_over` or `unmeasured_cell`) that `brave` mode admits. +2. **Exploit multi-window series capture**: + - Never run separate `1w`, `2w`, `3w`, `4w`, and `5w` jobs at the same window size. A single `Nw` run logs `[w1, w2, ..., wN]`, giving the 1-window base (`w1`), the 2-window step (`w2`), and the `>=3`-window plateau (`w3..wN`) in one execution. +3. **Exploit modality and aspect-ratio invariance**: + - **Modality**: Measure the full token curve on Fast T2V, then run at most one high-window spot-check on I2V and A2V to confirm zero conditioning surcharge. For Video Edit, test one same-token Retake vs Extend pair. + - **Aspect ratio**: Measure `16:9` as the anchor. Spot-check at most one **Class A** orientation twin (`9:16` at `1080p` or `2160p`, identical tokens to `16:9`), one **Class B** own-window portrait (`9:16` at `1440p`), one **Class C** smaller square (`1:1`), and one **Class D** ultrawide (`21:9`). `3:2`, `4:3`, and `4:5` ride the `1:1` Class C result. + +--- + +## 7. Reporting & Contributing Results + +### Reproducible Measurement Report Template + +Include only text tables and JSONL records in issues or pull requests—never commit `.mp4` outputs, source clips, PNG frames, or raw multi-megabyte log files. + +#### Hardware & Runtime Profile (`runtime.json` / PR header) + +| Field | Value | +| --- | --- | +| **OS & Build** | e.g., Windows 11 (`10.0.26100`), macOS (`26.x`), Linux kernel (`6.x`) | +| **GPU / Apple Silicon Chip** | e.g., NVIDIA GeForce RTX 4080 / Apple M4 Max | +| **VRAM (Total / Idle Free) or MPS Pool** | ` GiB` / ` GiB` (or MPS pool ` GiB` + loader host ` GiB`) | +| **System RAM & Drive Type** | ` GiB` / `` | +| **Driver / PyTorch / LTX Versions** | Driver ``, `torch `, `ltx-core `, `ltx-pipelines ` | +| **Model ID & Offload Mode** | ``, `OffloadMode.`, Attention `` | + +#### Cell Sweep Summary Table + +| Cell ID | Workflow & Mode | Res / Aspect (`WxH` real) | Duration / Frames (`fps`) | Pass Shape (`windows x win_f`, carry, last) | Predicted Ask (`stream_gib`) | Measured Peak (`reserved` / `alloc` or `driver` + cap bracket) | Per-Window Peaks `[w1..wN]` | Pre / Post Decode (`GiB`) | Step Time (`s/step`) | Shared GPU or Swap Delta | Calibration Verdict | Outcome (`oom_phase`) | +| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | +| `` | `fast-t2v` (`brave`) | `1440p` `16:9` (``) | `10s` / `f` (`24`) | `w x f` (`c`, `last f`) | ` GiB` | ` / GiB` | `[, ..., ]` | `

 / ` | ` /  s` | ` GB` | `clean` | `pass` (`-`) |
+
+Valid `Outcome` values:
+- `pass`: Completed with valid visual frames, no WDDM paging (`shared_delta <= 0.5 GB`) or macOS swap growth, steady `s/step`, and `clean` calibration verdict.
+- `paging-slowdown`: Completed or killed after WDDM shared-memory spill (`> 0.5 GB`) or macOS swap thrashing caused a 3x–10x+ `s/step` blow-up (`vram_growth`, `free_floor`, or `swap_growth`).
+- `oom`: Failed with CUDA or Metal `Tried to allocate` / `out of memory` (`oom_phase` = `encode`, `denoise-w`, `decode`, `stitch`, or `export`).
+- `refusal`: Refused pre-run by the budget gate (record HTTP 422 code and `reject.reason`).
+
+#### Per-Run JSONL Schema (`records.jsonl`)
+
+Populate the geometry and predicted fields from the Section 3 pricing script and the measured fields from the backend log and hardware samplers:
+
+```json
+{
+  "id": "fast-1440p-16x9-10s-24fps",
+  "feature": "fast",
+  "modality": "t2v",
+  "model_id": "",
+  "budget_mode": "brave",
+  "resolution_label": "1440p",
+  "aspect_ratio": "16:9",
+  "canvas_real": "",
+  "canvas_priced": "",
+  "duration_s": 10,
+  "fps": 24,
+  "frames": 241,
+  "windows": 2,
+  "window_frames": 129,
+  "last_window_frames": 129,
+  "carry_frames": 17,
+  "tiled": false,
+  "seq_priced": 62560,
+  "tokens_real": 62560,
+  "predicted_stream_gib": 0.0,
+  "cap_gib": null,
+  "measured_reserved_peak_gib": 0.0,
+  "measured_alloc_peak_gib": 0.0,
+  "mps_driver_peak_gib": null,
+  "per_window_peaks_gib": [],
+  "pre_window_peak_gib": 0.0,
+  "post_window_peak_gib": 0.0,
+  "step_time_s_stage1": 0.0,
+  "step_time_s_stage2": 0.0,
+  "load_s": 0.0,
+  "decode_s": 0.0,
+  "wall_s": 0.0,
+  "shared_gpu_delta_gb": 0.0,
+  "swap_delta_gib": 0.0,
+  "calibration_verdict": "clean",
+  "outcome": "pass",
+  "oom_phase": null,
+  "job_budget_log": "[video] job budget ...",
+  "decode_plan_log": "DiffVAE CUDA tiling after evict: ..."
+}
+```
+
+### Formula Universality & Parameterizing a New Setup
+
+Across CUDA and Apple Silicon MPS, the budget planner uses a **universal functional form**. Resolution (`540p`–`2160p`), aspect ratio (`16:9`, `9:16`, `1:1`, `21:9`), frame rate (`24`–`50` fps), modality (T2V, I2V, A2V; Retake vs Extend), and IC-LoRA stage layout (`SINGLE_STAGE`, `STAGE_1_LORA`, `STAGE_2_LORA`) all collapse onto a single scalar—the heaviest-pass token count $t$ (`video_tokens` or `_heaviest_pass_tokens`):
+
+1. **Single-pass floored-linear law (`_StreamModel`)**:
+   $$\text{base}(t) = \max\bigl(\text{floor\_gib},\; \text{intercept\_gib} + \text{gib\_per\_token} \cdot t\bigr)$$
+2. **Multi-window temporal chunking (`fast_job_stream_gib`)** across $W$ windows (Window 1 tokens $t_1$, last window tokens $t_2$):
+   $$\text{windowed}(t_1, t_2, W) = \begin{cases} \text{base}(t_1) & W = 1 \\ \max\bigl(\text{base}(t_1),\; \text{base}(t_2) + c_{2\text{w}} \cdot t_1\bigr) & W = 2 \\ \text{base}(t_1) + c_{\text{plat}} \cdot t_1 & W \ge \text{PEAK\_PLATEAU\_WINDOWS} \end{cases}$$
+3. **Phase envelope & unified-memory host charge**:
+   $$\text{stream\_gib} = \max\bigl(\text{law}_{\text{denoise}}(t_{\text{pass}}),\; \text{law}_{\text{decode}}(t_{\text{decode}})\bigr) + H_{\text{host}}$$
+
+Because the functional shape is invariant, adapting the planner to another hardware/software configuration (for example, Linux CUDA, pre-Ada `bf16` where `fp8_capable=False`, a new PyTorch/CUDA/Metal allocator release, or a new model checkpoint) only requires substituting the setup's parameter vector:
+
+| Parameter | Code Symbol (`video_job_budget.py` / `ic_lora_job_budget.py`) | Physical Meaning | Minimum Runs to Fit / Verify |
+| --- | --- | --- | --- |
+| `floor_gib` | `_StreamModel.floor_gib`, `_IC_LORA_FLOOR_GIB`, `_MAC_IC_LORA_FLOOR_GIB` | Encode-region / resident-weight floor where small-$t$ jobs are dominated by text or source VAE encoding rather than denoise tokens | 1–2 small-token cells (`540p` short duration) |
+| `intercept_gib` | `_StreamModel.intercept_gib`, `_IC_LORA_RESERVED_INTERCEPT_GIB` | Base resident working set + fixed allocator cache during streamed denoising | 3–4 single-pass cells spanning low to high $t$ (fitted jointly with `gib_per_token`) |
+| `gib_per_token` | `_StreamModel.gib_per_token`, `_IC_LORA_RESERVED_GIB_PER_SEQ_TOKEN` | Per-token activation working set + per-token transient allocation slope | Same 3–4 single-pass cells (plus upper-bound rounding so every clean point is covered) |
+| $c_{2\text{w}}$, $c_{\text{plat}}$ | `WINDOWED_TWO_WINDOW_GIB_PER_TOKEN`, `WINDOWED_PLATEAU_GIB_PER_TOKEN` (and `_MAC_WINDOWED_*`) | Carry/allocator state retained in Window 2 ($c_{2\text{w}}$) and at the Window $\ge 3$ plateau ($c_{\text{plat}}$) per Window-1 token | 1 multi-window cell (`4w` or `5w`, capturing `[w1, w2, w3, w4]` in one run) + 1 short-last-window `2w` cell |
+| $H_{\text{host}}$ / RAM floor | `mac_disk_stream_host_gib(model_id)` / `WINDOWS_*_STREAMING_RAM_GB` | Host memory held outside the GPU/MPS allocator by the weight loader (`disk_stream_unit_bytes` on unified memory; pinned/buffered host RAM on CUDA) | Derived from `LTXLocalModelSpec.disk_stream_unit_bytes` on macOS; host working-set / swap check on CUDA |
+
+**When simple variable replacement suffices vs. when a structural term is needed:**
+- **Different VRAM or unified-memory size within a measured family** (e.g., 12 GB / 16 GB / 24 GB vs 32 GB CUDA, or 24 GB / 36 GB / 48 GB vs 128 GB Apple Silicon): **Zero formula constants change**—the demand curve $\text{stream\_gib}(t)$ is capacity-independent, and `MemoryBudget` probes the card's actual supply at runtime.
+- **New software stack, precision, or OS route** (e.g., Linux CUDA, `fp8_capable=False` `bf16`, or a PyTorch/allocator bump): **Replace the parameter vector above** using 4–6 anchor cells.
+- **Structural boundaries where a single linear line is not enough**:
+  - *Untiled high-res decode crossover*: When DiffVAE decodes a large spatial canvas (`2160p`) untiled in time (`frames <= DECODE_MAX_UNTILED_WINDOW`), decode peak can exceed denoise peak, requiring a separate `_StreamModel` decode line inside the `max(denoise, decode)` envelope (such as `_EDIT_DECODE_STREAM` or `_windows_tiled_canvas_decode_gib`).
+  - *Multi-chord resolution kinks*: On macOS two-stage IC-LoRA (`_mac_iclora_two_stage_required_gib`), stage-1 vs stage-2 residency shifts slope between `540p` and `720p`, modeled as the maximum of two linear chords.
+  - *Non-memory kernel fences*: Hardware indexing limits (such as `_MPS_TRANSFORMER_TOKEN_FENCE` on Metal's 32-bit matrix-multiply index) are hard per-forward token ceilings independent of memory pool size.
+
+### Proposing Code & Documentation Updates from Measurements
+
+1. **Opening newly measured cells (`backend/runtime_config/measured_cells.py`)**:
+   - When an `unmeasured_cell` (such as a high-res window count, a decode token ceiling, or an IC-LoRA composition) passes cleanly (`outcome="pass"`, plateau flat across windows, decode clean) within `predicted_stream_gib`, propose updating `MEASURED_HIGH_RES_CELLS`, `MEASURED_WINDOWED_BELOW_1440P_CELLS`, `MEASURED_MAX_DECODE_TOKENS`, or `MEASURED_IC_LORA_COMPOSITION_CELLS`.
+2. **Refitting a budget law or decode window (`backend/runtime_config/`)**:
+   - **Under-ask (`measured > predicted_stream_gib`, or `paging-slowdown` / `oom` on an admitted cell)**: Check `oom_phase` and `pre_window_peak_gib` vs `post_window_peak_gib`.
+     - If the peak or failure is in `denoise-w`, refit the floor, intercept, per-token slope, or windowed extra (`windows == 2` vs `windows >= PEAK_PLATEAU_WINDOWS`) in `video_job_budget.py` or `ic_lora_job_budget.py` so the curve forms an upper bound over every clean measured point.
+     - If the peak or failure is in `decode`, update the decode reserve or window step-down table in `ic_lora_decode_window.py` or `MEASURED_MAX_DECODE_TOKENS` rather than inflating the transformer token slope.
+   - **Over-ask (`measured << predicted_stream_gib` across a bracketed sweep)**: Tighten the law only when backed by native reserved points across the token range (on CUDA) or `(F, P]` capped edge brackets (on macOS).
+   - **Calibration epoch**: Whenever a budget law refit or an `ltx-core` / `ltx-pipelines` upgrade moves peak memory, increment `CALIBRATION_EPOCH` in `backend/runtime_config/device_calibration.py`.
+3. **Syncing public docs and tests in the same change**:
+   - Re-price any affected hardware tier columns in `docs/hardware-compatibility.md` using the pricing script in Section 3 (never hand-calculate; round edit windows down to the half second).
+   - Regenerate `docs/local-compat-matrix.md` from code (never edit it by hand):
+     ```bash
+     cd backend && uv run python -m runtime_config.local_compat_matrix
+     ```
+   - Run the budget and matrix verification tests:
+     ```bash
+     pnpm backend:test -- tests/test_local_compat_matrix.py tests/test_video_job_budget.py tests/test_ic_lora_job_budget.py tests/test_device_calibration.py
+     ```
diff --git a/docs/telemetry-schema.md b/docs/telemetry-schema.md
index 92a07ce5d..3ab5f9121 100644
--- a/docs/telemetry-schema.md
+++ b/docs/telemetry-schema.md
@@ -69,8 +69,12 @@ Carries only what is known at finish; never repeats the start payload
 | `error_code`               | string?                                              | Fixed label, never a message/path. `CUDA_OOM` is a policy-miss signal (admitted but didn't fit), distinct from other failures                                        |
 | `load_mode`                | `full_models_loading` \| `streaming_models_loading`? | Whole model resident vs streamed                                                                                                                                     |
 | `offload_mode`             | `NONE` \| `CPU` \| `DISK`?                           | Resident vs pinned-host vs mapped-from-checkpoint streaming                                                                                                          |
+| `prompt_rewrite`           | `local` \| `gemini` \| `fal_expansion`?              | Who rewrote the prompt of a fal image run: local Gemma, Gemini, or fal's own expansion. Absent when no rewrite ran                                                  |
 
 
+Jobs on a lane that does not use the GPU (fal) carry no hardware keys, because the
+local GPU does not run them.
+
 Modes ride success rows only: cancelled/failed ends carry null (the summary
 never escapes the raise), as do edit rows (the retake pipeline does not
 surface its decisions).
diff --git a/docs/tools-and-options.md b/docs/tools-and-options.md
index bf501499c..3b3276384 100644
--- a/docs/tools-and-options.md
+++ b/docs/tools-and-options.md
@@ -22,7 +22,7 @@ Every tool in LTX Desktop, with the settings each one offers. For prompt rewriti
 
 ## Generation options
 
-The forms share one set of video settings. The app lists only the options that your downloaded models and your hardware can run. Longer clips and higher resolutions are hidden on machines that cannot run them (see [`local-compat-matrix.md`](local-compat-matrix.md)).
+The forms share one set of video settings. The app lists only the options that your downloaded models and your hardware can run. Longer clips and higher resolutions are greyed out, with the reason, on machines that cannot run them (see [`hardware-compatibility.md`](hardware-compatibility.md)).
 
 ### Text to Video, Image to Video, and LoRA tools
 
diff --git a/electron-builder.yml b/electron-builder.yml
index 788feda67..859793697 100644
--- a/electron-builder.yml
+++ b/electron-builder.yml
@@ -48,7 +48,8 @@ extraResources:
       - "!models/**"
       - "!tests/**"
   # The backend reads these files at import time (services/features/ic_lora_recipes.py,
-  # services/features/video/motion_path.py, runtime_config/ic_lora_local_envelope.py).
+  # services/features/video/motion_path.py, runtime_config/ic_lora_local_envelope.py,
+  # runtime_config/ic_lora_tiling.py).
   # Name each file. Do not use a glob.
   - from: shared
     to: shared
@@ -56,6 +57,7 @@ extraResources:
       - ic-lora-input-cap.json
       - motion-path.json
       - ic-lora-stage-2-upscale.json
+      - ic-lora-tiling-controls.json
   - from: python-deps-hash.txt
     to: python-deps-hash.txt
 
diff --git a/electron/app-state.ts b/electron/app-state.ts
index 34ca5bb7e..f53a4e431 100644
--- a/electron/app-state.ts
+++ b/electron/app-state.ts
@@ -1,11 +1,14 @@
 import { app } from 'electron'
 import fs from 'fs'
 import path from 'path'
+import { getAppDataDir } from './app-paths'
 
 export interface AppState {
   analyticsEnabled?: boolean
   installationId?: string
   projectAssetsPath?: string
+  /** Custom folder of the asset store. Unset means `/assets`. */
+  assetsDir?: string
   skippedUpdateVersion?: string
   autoCheckUpdates?: boolean
   setupComplete?: boolean
@@ -31,7 +34,12 @@ export function readAppState(): AppState {
 }
 
 export function writeAppState(state: AppState): void {
-  fs.writeFileSync(getAppStatePath(), JSON.stringify(state, null, 2))
+  // Write a temp file and rename it. A crash must not leave a half file: an unreadable state
+  // reads as empty, and that would drop the saved assets folder.
+  const statePath = getAppStatePath()
+  const tempPath = `${statePath}.tmp`
+  fs.writeFileSync(tempPath, JSON.stringify(state, null, 2))
+  fs.renameSync(tempPath, statePath)
 }
 
 let cachedProjectAssetsPath: string | null = null
@@ -56,6 +64,33 @@ export function setProjectAssetsPath(p: string): void {
   writeAppState(state)
 }
 
+export function getDefaultAssetsDir(): string {
+  return path.join(getAppDataDir(), 'assets')
+}
+
+let cachedAssetsDir: string | null = null
+
+/** Folder of the asset store. A custom folder holds the `.ltx-assets` marker. */
+export function getAssetsDir(): string {
+  if (cachedAssetsDir) return cachedAssetsDir
+  const saved = readAppState().assetsDir
+  cachedAssetsDir = saved ? path.resolve(saved) : getDefaultAssetsDir()
+  return cachedAssetsDir
+}
+
+export function isCustomAssetsDir(): boolean {
+  return getAssetsDir() !== getDefaultAssetsDir()
+}
+
+/** `undefined` returns to the default folder. */
+export function setAssetsDir(dir: string | undefined): void {
+  const state = readAppState()
+  if (dir && path.resolve(dir) !== getDefaultAssetsDir()) state.assetsDir = path.resolve(dir)
+  else delete state.assetsDir
+  writeAppState(state)
+  cachedAssetsDir = null
+}
+
 export function getSkippedUpdateVersion(): string | undefined {
   return readAppState().skippedUpdateVersion
 }
diff --git a/electron/assets-move-guards.ts b/electron/assets-move-guards.ts
new file mode 100644
index 000000000..90ece8f7c
--- /dev/null
+++ b/electron/assets-move-guards.ts
@@ -0,0 +1,35 @@
+import { isFfmpegRunning } from './export/ffmpeg-utils'
+import { getAuthToken, getBackendUrl, isGenerationActive } from './python-backend'
+
+/** Folders the user must not pick: the move would damage the system. */
+export function systemFolders(): string[] {
+  if (process.platform === 'win32') {
+    return [process.env.SystemRoot, process.env.ProgramFiles, process.env['ProgramFiles(x86)'], process.env.ProgramData]
+      .filter((dir): dir is string => Boolean(dir))
+  }
+  if (process.platform === 'darwin') return ['/System', '/usr', '/bin', '/sbin', '/etc', '/private/etc', '/Library']
+  return ['/usr', '/bin', '/sbin', '/etc', '/lib', '/boot', '/proc', '/sys', '/dev']
+}
+
+/**
+ * Why the app server cannot restart now, or `null`. The backend queue is the source of truth.
+ * A queued generation also needs the backend, and an ffmpeg job reads the asset files.
+ */
+export async function busyReason(): Promise {
+  if (isGenerationActive()) return 'A generation is running.'
+  if (isFfmpegRunning()) return 'An export is running.'
+  const url = getBackendUrl()
+  if (!url) return null
+  try {
+    const response = await fetch(`${url}/api/generation-queue`, {
+      headers: { Authorization: `Bearer ${getAuthToken() ?? ''}` },
+      signal: AbortSignal.timeout(3000),
+    })
+    if (!response.ok) return 'The app cannot check for running generations.'
+    const snapshot = (await response.json()) as { active?: unknown[]; queued?: unknown[] }
+    const count = (snapshot.active?.length ?? 0) + (snapshot.queued?.length ?? 0)
+    return count > 0 ? 'A generation is running or queued.' : null
+  } catch {
+    return 'The app cannot check for running generations.'
+  }
+}
diff --git a/electron/assets-move-run.test.ts b/electron/assets-move-run.test.ts
new file mode 100644
index 000000000..2a7baef4c
--- /dev/null
+++ b/electron/assets-move-run.test.ts
@@ -0,0 +1,167 @@
+import assert from 'node:assert/strict'
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+import { afterEach, beforeEach, describe, it } from 'node:test'
+import { runMove, type MoveDeps, type MoveRequest, type MoveStatePatch } from './assets-move-run.ts'
+import { ASSETS_MARKER_FILENAME, preflightMove } from './assets-relocation.ts'
+
+const A = '11111111-1111-4111-8111-111111111111'
+const B = '22222222-2222-4222-8222-222222222222'
+
+let root: string
+let from: string
+let to: string
+
+beforeEach(() => {
+  root = fs.mkdtempSync(path.join(os.tmpdir(), 'ltx-move-'))
+  from = path.join(root, 'old')
+  to = path.join(root, 'new')
+  fs.mkdirSync(from)
+  fs.mkdirSync(to)
+  fs.writeFileSync(path.join(from, `${A}.png`), 'hello')
+  fs.writeFileSync(path.join(from, `${A}-thumb.jpg`), 'th')
+  fs.writeFileSync(path.join(from, 'notes.txt'), 'mine')
+})
+
+afterEach(() => {
+  fs.rmSync(root, { recursive: true, force: true })
+})
+
+const replan = () =>
+  preflightMove({ from, to, protectedDirs: [], blockedRoots: [], appFolders: [], freeBytes: async () => 1_000_000 })
+
+async function request(overrides: Partial = {}): Promise {
+  const first = await replan()
+  assert.equal(first.ok, true)
+  if (!first.ok) throw new Error(first.reason)
+  return { plan: first.plan, toCustom: true, previousDir: undefined, replan, ...overrides }
+}
+
+function fakes(overrides: Partial = {}) {
+  const calls: string[] = []
+  const phases: MoveStatePatch[] = []
+  const deps: MoveDeps = {
+    stopBackend: async () => void calls.push('stop'),
+    startBackend: async () => void calls.push('start'),
+    saveAssetsDir: (dir) => void calls.push(`save:${dir ?? 'default'}`),
+    emit: (patch) => void phases.push(patch),
+    isCancelled: () => false,
+    logError: () => {},
+    ...overrides,
+  }
+  return { deps, calls, phases }
+}
+
+const list = (dir: string) => fs.readdirSync(dir).sort()
+
+describe('runMove', () => {
+  it('copies, saves the folder, restarts, and deletes only the asset files in the old folder', async () => {
+    const { deps, calls, phases } = fakes()
+
+    const result = await runMove(await request(), deps)
+
+    assert.equal(result, 'moved')
+    assert.deepEqual(calls, ['stop', 'save:' + to, 'start'])
+    assert.deepEqual(list(to), [ASSETS_MARKER_FILENAME, `${A}-thumb.jpg`, `${A}.png`].sort())
+    assert.deepEqual(list(from), ['notes.txt'])
+    assert.equal(phases[phases.length - 1].result?.ok, true)
+  })
+
+  it('copies a file that was added after the confirmation', async () => {
+    const { deps } = fakes()
+    const req = await request()
+    fs.writeFileSync(path.join(from, `${B}.png`), 'late')
+
+    await runMove(req, deps)
+
+    assert.equal(fs.readFileSync(path.join(to, `${B}.png`), 'utf8'), 'late')
+    assert.deepEqual(list(from), ['notes.txt'])
+  })
+
+  it('goes back to the old folder when the backend does not start on the new one', async () => {
+    let starts = 0
+    const { deps, calls, phases } = fakes({
+      startBackend: async () => {
+        calls.push('start')
+        if (++starts === 1) throw new Error('boom')
+      },
+    })
+
+    const result = await runMove(await request({ previousDir: from }), deps)
+
+    assert.equal(result, 'failed')
+    assert.deepEqual(calls, ['stop', 'save:' + to, 'start', `save:${from}`, 'start'])
+    assert.deepEqual(list(to), [])
+    assert.deepEqual(list(from), [`${A}-thumb.jpg`, `${A}.png`, 'notes.txt'].sort())
+    assert.equal(phases[phases.length - 1].result?.ok, false)
+  })
+
+  it('removes the copies and keeps the old folder when the user cancels', async () => {
+    const { deps, calls, phases } = fakes({ isCancelled: () => true })
+
+    const result = await runMove(await request(), deps)
+
+    assert.equal(result, 'cancelled')
+    assert.deepEqual(calls, ['stop', 'start'])
+    assert.deepEqual(list(to), [])
+    assert.deepEqual(list(from), [`${A}-thumb.jpg`, `${A}.png`, 'notes.txt'].sort())
+    assert.equal(phases[phases.length - 1].result?.ok, false)
+  })
+
+  it('honors a cancel that comes in while the last file is copied', async () => {
+    let cancel = false
+    const { deps, calls } = fakes({
+      isCancelled: () => cancel,
+      emit: (patch) => {
+        if (patch.phase === 'copying' && patch.filesDone === 2) cancel = true
+      },
+    })
+
+    const result = await runMove(await request(), deps)
+
+    assert.equal(result, 'cancelled')
+    assert.deepEqual(calls, ['stop', 'start'])
+    assert.deepEqual(list(to), [])
+    assert.deepEqual(list(from), [`${A}-thumb.jpg`, `${A}.png`, 'notes.txt'].sort())
+  })
+
+  it('restarts and changes nothing when the new plan is rejected', async () => {
+    const { deps, calls } = fakes()
+    const req = await request({
+      replan: async () => ({ ok: false, reason: 'The current assets folder was not found.' }),
+    })
+
+    const result = await runMove(req, deps)
+
+    assert.equal(result, 'failed')
+    assert.deepEqual(calls, ['stop', 'start'])
+    assert.deepEqual(list(to), [])
+    assert.deepEqual(list(from), [`${A}-thumb.jpg`, `${A}.png`, 'notes.txt'].sort())
+  })
+
+  it('does not start a second backend when the first one does not stop', async () => {
+    const { deps, calls, phases } = fakes({
+      stopBackend: async () => {
+        calls.push('stop')
+        throw new Error('timeout')
+      },
+    })
+
+    const result = await runMove(await request(), deps)
+
+    assert.equal(result, 'failed')
+    assert.deepEqual(calls, ['stop'])
+    assert.match(phases[phases.length - 1].result?.message ?? '', /did not stop/)
+  })
+
+  it('moves back to the default folder without a marker', async () => {
+    const { deps, calls } = fakes()
+
+    const result = await runMove(await request({ toCustom: false, previousDir: from }), deps)
+
+    assert.equal(result, 'moved')
+    assert.deepEqual(calls, ['stop', 'save:default', 'start'])
+    assert.equal(fs.existsSync(path.join(to, ASSETS_MARKER_FILENAME)), false)
+  })
+})
diff --git a/electron/assets-move-run.ts b/electron/assets-move-run.ts
new file mode 100644
index 000000000..c708b99e5
--- /dev/null
+++ b/electron/assets-move-run.ts
@@ -0,0 +1,135 @@
+import type { AssetsMoveState } from '../shared/electron-api-schema.ts'
+import {
+  copyFiles,
+  deleteMovedFiles,
+  releaseFolder,
+  removeCreated,
+  removeMarker,
+  writeMarker,
+  type MovePlan,
+  type PreflightResult,
+} from './assets-relocation.ts'
+
+export type MoveStatePatch = Partial & Pick
+
+/** What the move needs from the app. Tests give fakes, the app gives the real backend and settings. */
+export type MoveDeps = {
+  /** Stops the backend and holds its start. It throws when the backend does not stop. */
+  stopBackend: () => Promise
+  /** Releases the hold and starts the backend with the saved folder. */
+  startBackend: () => Promise
+  saveAssetsDir: (dir: string | undefined) => void
+  emit: (patch: MoveStatePatch) => void
+  isCancelled: () => boolean
+  logError: (message: string) => void
+}
+
+export type MoveRequest = {
+  plan: MovePlan
+  toCustom: boolean
+  /** The custom folder in use now. `undefined` when the default folder is in use. */
+  previousDir: string | undefined
+  /** Plans the move again. It runs after the backend stopped. */
+  replan: () => Promise
+}
+
+export type MoveOutcome = 'moved' | 'cancelled' | 'failed'
+
+const PROGRESS_INTERVAL_MS = 150
+
+function errorText(error: unknown): string {
+  return error instanceof Error ? error.message : String(error)
+}
+
+/** Runs the move. The setting changes only after a verified copy. Every failure ends on the old folder. */
+export async function runMove(
+  { plan: confirmed, toCustom, previousDir, replan }: MoveRequest,
+  deps: MoveDeps,
+): Promise {
+  const done = (ok: boolean, message: string) =>
+    deps.emit({ phase: 'done', canCancel: false, result: { ok, message } })
+  const restartNote = (message: string, failure: string | null) =>
+    failure ? `${message} The server could not restart: ${failure}` : message
+  const restart = async (): Promise => {
+    try {
+      await deps.startBackend()
+      return null
+    } catch (error) {
+      return errorText(error)
+    }
+  }
+
+  deps.emit({ phase: 'stopping', filesTotal: confirmed.files.length, bytesTotal: confirmed.totalBytes })
+  try {
+    await deps.stopBackend()
+  } catch (error) {
+    // The old backend may still run. Do not start a second one on the same database.
+    done(false, `The app server did not stop (${errorText(error)}). Restart the app. Your assets are still in the old folder.`)
+    return 'failed'
+  }
+
+  let created: string[] = []
+  let markerCreated = false
+  let plan = confirmed
+  try {
+    // The user read the confirmation some time ago. A file may have been added since then.
+    // Plan again now that the backend is stopped, so no file stays behind in the old folder.
+    const fresh = await replan()
+    if (!fresh.ok) {
+      done(false, restartNote(`${fresh.reason} Your assets are still in the old folder.`, await restart()))
+      return 'failed'
+    }
+    plan = fresh.plan
+
+    deps.emit({ phase: 'copying', filesTotal: plan.files.length, bytesTotal: plan.totalBytes })
+    let lastEmit = 0
+    const copy = await copyFiles(plan, {
+      isCancelled: deps.isCancelled,
+      onProgress: ({ filesDone, bytesDone }) => {
+        const now = Date.now()
+        if (now - lastEmit < PROGRESS_INTERVAL_MS && filesDone < plan.files.length) return
+        lastEmit = now
+        deps.emit({ phase: 'copying', filesDone, bytesDone })
+      },
+    })
+    created = copy.created
+
+    // The commit boundary. A cancel is honored up to here, also when it came in while the
+    // last file was copied or while no file needed a copy. There is no await between this
+    // check and the change of `canCancel`, so a later cancel is ignored and cannot be lost.
+    if (copy.status === 'cancelled' || deps.isCancelled()) {
+      await removeCreated(created)
+      created = []
+      deps.emit({ phase: 'restarting', canCancel: false })
+      const failure = await restart()
+      done(false, restartNote('The move was cancelled. Your assets are still in the old folder.', failure))
+      return failure === null ? 'cancelled' : 'failed'
+    }
+    deps.emit({ phase: 'restarting', canCancel: false })
+
+    if (toCustom) markerCreated = await writeMarker(plan.to)
+    deps.saveAssetsDir(toCustom ? plan.to : undefined)
+    const failure = await restart()
+    if (failure !== null) throw new Error(`The server did not start with the new folder (${failure}).`)
+  } catch (error) {
+    deps.logError(`Assets move failed: ${errorText(error)}`)
+    await removeCreated(created)
+    if (markerCreated) await removeMarker(plan.to)
+    deps.saveAssetsDir(previousDir)
+    const revert = await restart()
+    const reason = errorText(error).replace(/\.$/, '')
+    done(false, restartNote(`The move failed: ${reason}. Your assets are still in the old folder.`, revert))
+    return 'failed'
+  }
+
+  deps.emit({ phase: 'cleaning', canCancel: false })
+  const undeleted = await deleteMovedFiles(plan)
+  if (undeleted.length === 0 && previousDir) await releaseFolder(plan.from)
+  done(
+    true,
+    undeleted.length === 0
+      ? 'Your assets are in the new folder.'
+      : `Your assets are in the new folder. The app could not delete ${undeleted.length} old files in ${plan.from}. You can delete them by hand.`,
+  )
+  return 'moved'
+}
diff --git a/electron/assets-move.ts b/electron/assets-move.ts
new file mode 100644
index 000000000..1b154ef28
--- /dev/null
+++ b/electron/assets-move.ts
@@ -0,0 +1,143 @@
+import os from 'os'
+import type { AssetsMoveState } from '../shared/electron-api-schema'
+import { formatBytes } from '../shared/format-bytes'
+import { getAppDataDir } from './app-paths'
+import { getAssetsDir, getDefaultAssetsDir, isCustomAssetsDir, setAssetsDir } from './app-state'
+import { runMove, type MoveDeps, type MoveStatePatch } from './assets-move-run'
+import { busyReason, systemFolders } from './assets-move-guards'
+import { checkCustomAssetsDir, preflightMove, type MovePlan } from './assets-relocation'
+import { getCurrentDir } from './config'
+import { freeDiskBytes } from './free-disk-space'
+import { logger } from './logger'
+import { pickFolder, showMessage } from './native-dialogs'
+import {
+  holdBackendStart,
+  isBackendAdopted,
+  startPythonBackend,
+  stopPythonBackendAndWait,
+} from './python-backend'
+import { getMainWindow } from './window'
+
+export type ChangeResult = { success: true; path: string } | { success: false; error: string }
+
+const CANCELLED: ChangeResult = { success: false, error: 'cancelled' }
+
+let state: AssetsMoveState | null = null
+let cancelRequested = false
+let releaseBackendHold = () => {}
+// Set at once, before the first dialog opens, so two calls cannot start two moves.
+let changing = false
+
+/** The move state while a move runs. `null` when idle. A finished move is not kept. */
+export function getAssetsMoveState(): AssetsMoveState | null {
+  return state && state.phase !== 'done' ? state : null
+}
+
+export function cancelAssetsMove(): void {
+  if (state?.canCancel) cancelRequested = true
+}
+
+function emit(patch: MoveStatePatch): void {
+  state = { filesDone: 0, filesTotal: 0, bytesDone: 0, bytesTotal: 0, canCancel: true, ...state, ...patch }
+  getMainWindow()?.webContents.send('assets-move-progress', state)
+}
+
+/** The real backend and settings. `runMove` takes these, so tests can give fakes. */
+const moveDeps: MoveDeps = {
+  stopBackend: async () => {
+    releaseBackendHold = holdBackendStart()
+    await stopPythonBackendAndWait()
+  },
+  startBackend: async () => {
+    // Release the hold first: a start that waits (for example after a renderer reload) joins this one.
+    releaseBackendHold()
+    await startPythonBackend({ askUser: false })
+  },
+  saveAssetsDir: setAssetsDir,
+  emit,
+  isCancelled: () => cancelRequested,
+  logError: (message) => logger.error(message),
+}
+
+async function reject(message: string): Promise {
+  await showMessage({ type: 'info', message: 'The assets folder was not changed.', detail: message, buttons: ['OK'], noLink: true })
+  return { success: false, error: message }
+}
+
+async function confirmMove(plan: MovePlan): Promise {
+  const count = plan.files.length
+  const detail =
+    `From: ${plan.from}\nTo: ${plan.to}\n\n` +
+    (count === 0
+      ? 'There are no assets to move.'
+      : `${count} files (${formatBytes(plan.totalBytes)}) will be copied, checked, and then deleted from the old folder. ` +
+        `${formatBytes(plan.freeBytes)} is free in the new folder.`) +
+    '\n\nThe app server restarts. Do not close the app while the move runs.'
+  const response = await showMessage({
+    type: 'question',
+    message: 'Move your assets to this folder?',
+    detail,
+    buttons: ['Move assets', 'Cancel'],
+    defaultId: 1,
+    cancelId: 1,
+    noLink: true,
+  })
+  return response === 0
+}
+
+/** `'pick'` asks the user for a folder. `'default'` goes back to the default folder. */
+export async function changeAssetsDir(target: 'pick' | 'default'): Promise {
+  if (changing) return reject('An assets move is already running.')
+  changing = true
+  try {
+    return await changeAssetsDirLocked(target)
+  } catch (error) {
+    // The renderer gets a fixed text. The detail stays in the log.
+    logger.error(`Assets folder change failed: ${error}`)
+    return reject('Something went wrong. See the logs for details.')
+  } finally {
+    releaseBackendHold()
+    cancelRequested = false
+    changing = false
+  }
+}
+
+async function changeAssetsDirLocked(target: 'pick' | 'default'): Promise {
+  const toCustom = target === 'pick'
+  if (!toCustom && !isCustomAssetsDir()) return reject('The app already uses the default folder.')
+  if (isBackendAdopted()) return reject('The app server was started outside this app, so the app cannot restart it.')
+
+  const busy = await busyReason()
+  if (busy) return reject(`${busy} Wait until it finishes, then try again.`)
+
+  const to = toCustom ? await pickFolder('Choose the assets folder', { canCreate: true }) : getDefaultAssetsDir()
+  if (!to) return CANCELLED
+
+  const from = getAssetsDir()
+  const previousDir = isCustomAssetsDir() ? from : undefined
+  // The default folder is inside the app data folder, so only a picked folder is checked against it.
+  const blockedRoots = toCustom ? systemFolders() : []
+  const appFolders = toCustom ? [getAppDataDir(), getCurrentDir()] : []
+  const replan = async () => {
+    if (previousDir) {
+      // A drive that was unplugged must not look like an empty library.
+      const source = await checkCustomAssetsDir(previousDir)
+      if (!source.ok) return { ok: false as const, reason: `The current assets folder is not available. ${source.reason}` }
+    }
+    return preflightMove({ from, to, protectedDirs: [os.homedir(), getAppDataDir(), getCurrentDir()], blockedRoots, appFolders, freeBytes: freeDiskBytes })
+  }
+  const preflight = await replan()
+  if (!preflight.ok) return reject(preflight.reason)
+  if (!(await confirmMove(preflight.plan))) return CANCELLED
+
+  // The check above may be old after the user read the dialog.
+  const busyAfterConfirm = await busyReason()
+  if (busyAfterConfirm) return reject(`${busyAfterConfirm} Wait until it finishes, then try again.`)
+
+  cancelRequested = false
+  state = null
+  emit({ phase: 'checking' })
+  const result = await runMove({ plan: preflight.plan, toCustom, previousDir, replan }, moveDeps)
+  if (result === 'moved') return { success: true, path: getAssetsDir() }
+  return result === 'cancelled' ? CANCELLED : { success: false, error: state?.result?.message ?? 'The move failed.' }
+}
diff --git a/electron/assets-relocation.test.ts b/electron/assets-relocation.test.ts
new file mode 100644
index 000000000..828bf9ffb
--- /dev/null
+++ b/electron/assets-relocation.test.ts
@@ -0,0 +1,305 @@
+import assert from 'node:assert/strict'
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+import { afterEach, beforeEach, describe, it } from 'node:test'
+import {
+  ASSETS_MARKER_FILENAME,
+  checkCustomAssetsDir,
+  copyFiles,
+  deleteMovedFiles,
+  preflightMove,
+  releaseFolder,
+  writeMarker,
+  type PreflightOptions,
+} from './assets-relocation.ts'
+
+const A = '11111111-1111-4111-8111-111111111111'
+const B = '22222222-2222-4222-8222-222222222222'
+
+let root: string
+let from: string
+let to: string
+
+beforeEach(() => {
+  root = fs.mkdtempSync(path.join(os.tmpdir(), 'ltx-assets-'))
+  from = path.join(root, 'old')
+  to = path.join(root, 'new')
+  fs.mkdirSync(from)
+  fs.mkdirSync(to)
+})
+
+afterEach(() => {
+  fs.rmSync(root, { recursive: true, force: true })
+})
+
+function write(dir: string, name: string, content: string): void {
+  fs.writeFileSync(path.join(dir, name), content)
+}
+
+function options(overrides: Partial = {}): PreflightOptions {
+  return {
+    from,
+    to,
+    protectedDirs: [],
+    blockedRoots: [],
+    appFolders: [],
+    freeBytes: async () => 1_000_000,
+    ...overrides,
+  }
+}
+
+async function plan(overrides: Partial = {}) {
+  const result = await preflightMove(options(overrides))
+  assert.equal(result.ok, true, result.ok ? '' : result.reason)
+  if (!result.ok) throw new Error(result.reason)
+  return result.plan
+}
+
+async function reason(overrides: Partial = {}): Promise {
+  const result = await preflightMove(options(overrides))
+  assert.equal(result.ok, false)
+  return result.ok ? '' : result.reason
+}
+
+describe('preflightMove', () => {
+  it('lists the files, skips the in-flight folder and the marker, and counts the bytes', async () => {
+    write(from, `${A}.png`, '12345')
+    write(from, `${A}-thumb.jpg`, '12')
+    write(from, ASSETS_MARKER_FILENAME, '')
+    fs.mkdirSync(path.join(from, '.in-flight'))
+    write(path.join(from, '.in-flight'), 'x.mp4', 'busy')
+
+    const result = await plan()
+
+    assert.deepEqual(result.files.map((f) => f.name).sort(), [`${A}-thumb.jpg`, `${A}.png`])
+    assert.equal(result.totalBytes, 7)
+  })
+
+  it('leaves foreign files, partial copies and the marker out of the list', async () => {
+    write(from, `${A}.png`, '1')
+    write(from, `${B}.png.ltx-partial`, '2')
+    write(from, 'notes.txt', 'mine')
+    write(from, 'photo.png', 'mine')
+    write(from, ASSETS_MARKER_FILENAME, '')
+
+    const result = await plan()
+
+    assert.deepEqual(result.files.map((f) => f.name), [`${A}.png`])
+  })
+
+  it('rejects a missing old folder: it is not an empty library', async () => {
+    fs.rmSync(from, { recursive: true })
+    assert.match(await reason(), /was not found/)
+  })
+
+  it('moves the content of an asset file that is a link and deletes only the link', async (t) => {
+    write(root, 'real.png', 'real')
+    try {
+      fs.symlinkSync(path.join(root, 'real.png'), path.join(from, `${A}.png`))
+    } catch {
+      t.skip('symbolic links are not allowed here')
+      return
+    }
+    const result = await plan()
+    assert.deepEqual(result.files, [{ name: `${A}.png`, size: 4 }])
+
+    await copyFiles(result, { onProgress: () => {}, isCancelled: () => false })
+    await deleteMovedFiles(result)
+
+    assert.equal(fs.readFileSync(path.join(to, `${A}.png`), 'utf8'), 'real')
+    assert.equal(fs.existsSync(path.join(from, `${A}.png`)), false)
+    assert.equal(fs.readFileSync(path.join(root, 'real.png'), 'utf8'), 'real')
+  })
+
+  it('rejects the same folder', async () => {
+    assert.match(await reason({ to: from }), /uses now/)
+  })
+
+  it('rejects a folder inside the old folder and a parent of the old folder', async () => {
+    const inside = path.join(from, 'inner')
+    fs.mkdirSync(inside)
+    assert.match(await reason({ to: inside }), /must not contain/)
+    assert.match(await reason({ to: root }), /must not contain/)
+  })
+
+  it('rejects a drive root, a network path, a protected folder and a system folder', async () => {
+    assert.match(await reason({ to: path.parse(root).root }), /drive root/)
+    assert.match(await reason({ to: '\\\\server\\share\\assets' }), /Network/)
+    const data = path.join(root, 'data')
+    fs.mkdirSync(path.join(data, 'sub'), { recursive: true })
+    assert.match(await reason({ to: data, protectedDirs: [path.join(data, 'sub')] }), /app or personal/)
+    const system = path.join(root, 'system')
+    fs.mkdirSync(path.join(system, 'inner'), { recursive: true })
+    assert.match(await reason({ to: path.join(system, 'inner'), blockedRoots: [system] }), /system folder/)
+  })
+
+  it('names the app folders when the target is inside one', async () => {
+    const appData = path.join(root, 'app-data')
+    fs.mkdirSync(path.join(appData, 'models'), { recursive: true })
+    assert.match(await reason({ to: path.join(appData, 'models'), appFolders: [appData] }), /inside the app folders/)
+  })
+
+  it('rejects a new folder inside the old folder when the path goes through a link', async (t) => {
+    const link = path.join(root, 'link')
+    try {
+      fs.symlinkSync(root, link)
+    } catch {
+      t.skip('symbolic links are not allowed here')
+      return
+    }
+    // The folder does not exist yet, so the check must resolve the link through its parent.
+    assert.match(await reason({ to: path.join(link, 'old', 'inner') }), /must not contain/)
+    assert.match(
+      await reason({ to: path.join(link, 'data', 'new'), appFolders: [path.join(root, 'data')] }),
+      /inside the app folders/,
+    )
+  })
+
+  it('rejects a move that does not fit and shows the sizes', async () => {
+    write(from, `${A}.png`, 'x'.repeat(4096))
+    assert.match(await reason({ freeBytes: async () => 1024 }), /Not enough space: 4.0 KB needed, 1.0 KB free/)
+  })
+
+  it('allows a foreign folder and leaves its files alone', async () => {
+    write(to, 'notes.txt', 'mine')
+    write(from, `${A}.png`, '1')
+    await plan()
+    assert.equal(fs.readFileSync(path.join(to, 'notes.txt'), 'utf8'), 'mine')
+  })
+
+})
+
+describe('copyFiles', () => {
+  it('copies files with the same content and reports progress', async () => {
+    write(from, `${A}.png`, 'hello')
+    write(from, `${B}.jpg`, 'world!')
+    const result = await plan()
+    const seen: number[] = []
+
+    const copied = await copyFiles(result, {
+      onProgress: (p) => seen.push(p.bytesDone),
+      isCancelled: () => false,
+    })
+
+    assert.equal(copied.status, 'done')
+    assert.equal(fs.readFileSync(path.join(to, `${A}.png`), 'utf8'), 'hello')
+    assert.equal(fs.readFileSync(path.join(to, `${B}.jpg`), 'utf8'), 'world!')
+    assert.equal(seen[seen.length - 1], 11)
+    assert.deepEqual(fs.readdirSync(to).sort(), [`${A}.png`, `${B}.jpg`])
+  })
+
+  it('replaces a file with the same name in the target', async () => {
+    write(from, `${A}.png`, 'hello')
+    write(to, `${A}.png`, 'old')
+    const result = await plan()
+
+    await copyFiles(result, { onProgress: () => {}, isCancelled: () => false })
+
+    assert.equal(fs.readFileSync(path.join(to, `${A}.png`), 'utf8'), 'hello')
+  })
+
+  it('removes everything it created when it is cancelled', async () => {
+    write(from, `${A}.png`, 'hello')
+    write(from, `${B}.png`, 'world')
+    const result = await plan()
+    let cancel = false
+
+    const copied = await copyFiles(result, {
+      onProgress: (p) => {
+        if (p.filesDone === 1) cancel = true
+      },
+      isCancelled: () => cancel,
+    })
+
+    assert.equal(copied.status, 'cancelled')
+    assert.deepEqual(fs.readdirSync(to), [])
+    assert.deepEqual(fs.readdirSync(from).sort(), [`${A}.png`, `${B}.png`])
+  })
+
+  it('keeps a file that was in the target before when a later file is cancelled', async () => {
+    write(from, `${A}.png`, 'hello')
+    write(from, `${B}.png`, 'world')
+    write(to, `${A}.png`, 'old')
+    const result = await plan()
+    let cancel = false
+
+    const copied = await copyFiles(result, {
+      onProgress: (p) => {
+        if (p.filesDone === 1) cancel = true
+      },
+      isCancelled: () => cancel,
+    })
+
+    assert.equal(copied.status, 'cancelled')
+    assert.deepEqual(fs.readdirSync(to), [`${A}.png`])
+  })
+
+  it('removes the partial copy and throws when the source cannot be read', async () => {
+    write(from, `${A}.png`, 'hello')
+    const result = await plan()
+    fs.rmSync(path.join(from, `${A}.png`))
+
+    await assert.rejects(() => copyFiles(result, { onProgress: () => {}, isCancelled: () => false }))
+    assert.deepEqual(fs.readdirSync(to), [])
+  })
+})
+
+describe('deleteMovedFiles', () => {
+  it('deletes the old asset files and keeps everything else', async () => {
+    write(from, `${A}.png`, 'hello')
+    write(from, 'notes.txt', 'mine')
+    fs.mkdirSync(path.join(from, '.in-flight'))
+    const result = await plan()
+
+    const failed = await deleteMovedFiles(result)
+
+    assert.deepEqual(failed, [])
+    assert.deepEqual(fs.readdirSync(from).sort(), ['.in-flight', 'notes.txt'])
+  })
+})
+
+describe('marker', () => {
+  it('writeMarker tells whether it created the marker, and releaseFolder removes it', async () => {
+    assert.equal(await writeMarker(to), true)
+    assert.equal(await writeMarker(to), false)
+    fs.mkdirSync(path.join(to, '.in-flight'))
+    await releaseFolder(to)
+    assert.deepEqual(fs.readdirSync(to), [])
+  })
+
+  it('releaseFolder keeps an in-flight folder that is not empty', async () => {
+    fs.mkdirSync(path.join(to, '.in-flight'))
+    write(path.join(to, '.in-flight'), 'x.mp4', 'busy')
+    await releaseFolder(to)
+    assert.deepEqual(fs.readdirSync(to), ['.in-flight'])
+  })
+})
+
+describe('marker contract', () => {
+  it('matches shared/assets-marker.json', () => {
+    const contract = JSON.parse(
+      fs.readFileSync(new URL('../shared/assets-marker.json', import.meta.url), 'utf8'),
+    ) as { filename: string }
+    assert.equal(ASSETS_MARKER_FILENAME, contract.filename)
+  })
+})
+
+describe('checkCustomAssetsDir', () => {
+  it('fails when the folder is missing', async () => {
+    const check = await checkCustomAssetsDir(path.join(root, 'gone'))
+    assert.equal(check.ok, false)
+  })
+
+  it('fails for a network path without touching it', async () => {
+    const check = await checkCustomAssetsDir('\\\\server\\share\\assets')
+    assert.equal(check.ok, false)
+  })
+
+  it('fails when the marker is missing, and passes once it is written', async () => {
+    const before = await checkCustomAssetsDir(to)
+    assert.equal(before.ok, false)
+    await writeMarker(to)
+    assert.deepEqual(await checkCustomAssetsDir(to), { ok: true })
+  })
+})
diff --git a/electron/assets-relocation.ts b/electron/assets-relocation.ts
new file mode 100644
index 000000000..2f98355ed
--- /dev/null
+++ b/electron/assets-relocation.ts
@@ -0,0 +1,323 @@
+import fs from 'fs'
+import fsp from 'fs/promises'
+import path from 'path'
+import { formatBytes } from '../shared/format-bytes.ts'
+import { isRemoteFilePath } from '../shared/remote-file-path.ts'
+
+/** Same name as ASSETS_MARKER_FILENAME in backend/services/sqlite_store.py. */
+export const ASSETS_MARKER_FILENAME = '.ltx-assets'
+// Only files are moved. The backend's `.in-flight` folder stays: the backend clears it at boot.
+const PARTIAL_SUFFIX = '.ltx-partial'
+const COPY_CHUNK_BYTES = 4 * 1024 * 1024
+// Same name as IN_FLIGHT_DIRNAME in backend/runtime_config/assets_layout.py.
+const IN_FLIGHT_DIRNAME = '.in-flight'
+
+export type SourceFile = { name: string; size: number }
+
+export type MovePlan = {
+  from: string
+  to: string
+  /** Every asset file in the old folder (see ASSET_FILE_NAME). They are all deleted after the move. */
+  files: SourceFile[]
+  totalBytes: number
+  freeBytes: number
+}
+
+export type PreflightResult = { ok: true; plan: MovePlan } | { ok: false; reason: string }
+
+export type PreflightOptions = {
+  from: string
+  to: string
+  /** The target equals or contains one of these folders: reject. */
+  protectedDirs: string[]
+  /** The target is inside one of these system folders: reject. */
+  blockedRoots: string[]
+  /** The target is inside one of these app folders (app data, install): reject. */
+  appFolders: string[]
+  freeBytes: (dir: string) => Promise
+}
+
+export type MoveProgress = { filesDone: number; bytesDone: number }
+
+export type CopyHooks = {
+  onProgress: (progress: MoveProgress) => void
+  isCancelled: () => boolean
+}
+
+export type CopyResult = { status: 'done' | 'cancelled'; created: string[] }
+
+/**
+ * The real path. A folder that does not exist yet is resolved through its nearest existing parent,
+ * so a new folder behind a link compares the same way as an existing one.
+ */
+function realpathOrResolve(p: string): string {
+  const missing: string[] = []
+  let current = path.resolve(p)
+  for (;;) {
+    try {
+      return path.join(fs.realpathSync.native(current), ...missing.reverse())
+    } catch {
+      const parent = path.dirname(current)
+      if (parent === current) return path.resolve(p)
+      missing.push(path.basename(current))
+      current = parent
+    }
+  }
+}
+
+function comparable(p: string): string {
+  const resolved = realpathOrResolve(p)
+  return process.platform === 'win32' ? resolved.toLowerCase() : resolved
+}
+
+/** True when `child` is `parent` or is inside it. */
+function isInside(child: string, parent: string): boolean {
+  const relative = path.relative(comparable(parent), comparable(child))
+  return (
+    relative === '' ||
+    (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative))
+  )
+}
+
+// The store names its files `` and `-thumb.jpg` (see _derived_path and
+// ThumbnailWriter in the backend). Only those files are moved or deleted. A custom folder can
+// hold the user's own files, and the app must never touch them.
+const ASSET_FILE_NAME = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}(-thumb)?\.[a-z0-9]+$/i
+
+async function listSourceFiles(dir: string): Promise {
+  const files: SourceFile[] = []
+  for (const name of await fsp.readdir(dir)) {
+    if (!ASSET_FILE_NAME.test(name)) continue
+    // stat follows a link, as the backend does. The copy holds the content, and the delete removes only the link.
+    const stat = await fsp.stat(path.join(dir, name)).catch(() => null)
+    if (stat?.isFile()) files.push({ name, size: stat.size })
+  }
+  return files
+}
+
+function rejectTarget(options: PreflightOptions): string | null {
+  const { from, to } = options
+  if (isRemoteFilePath(to)) return 'Network folders are not supported. Choose a folder on a local drive.'
+  if (path.parse(path.resolve(to)).root === path.resolve(to)) return 'Choose a folder, not a drive root.'
+  if (comparable(from) === comparable(to)) return 'This is the folder that the app uses now.'
+  if (isInside(to, from) || isInside(from, to)) {
+    return 'The new folder and the current folder must not contain each other.'
+  }
+  if (options.protectedDirs.some((dir) => isInside(dir, to))) {
+    return 'This folder holds app or personal data. Choose another folder.'
+  }
+  if (options.blockedRoots.some((dir) => isInside(to, dir))) {
+    return 'This is a system folder. Choose another folder.'
+  }
+  if (options.appFolders.some((dir) => isInside(to, dir))) {
+    return 'This folder is inside the app folders. Choose another folder.'
+  }
+  return null
+}
+
+async function probeWritable(dir: string): Promise {
+  const probe = path.join(dir, `.ltx-probe-${process.pid}-${Date.now()}`)
+  try {
+    await fsp.writeFile(probe, '')
+    await fsp.unlink(probe)
+    return true
+  } catch {
+    return false
+  }
+}
+
+/** Checks the move and changes nothing, except that a missing target folder is created. */
+export async function preflightMove(options: PreflightOptions): Promise {
+  const { from, to } = options
+  const rejected = rejectTarget(options)
+  if (rejected) return { ok: false, reason: rejected }
+
+  try {
+    await fsp.mkdir(to, { recursive: true })
+    if (!(await fsp.stat(to)).isDirectory()) return { ok: false, reason: 'The path is not a folder.' }
+  } catch {
+    return { ok: false, reason: 'The folder cannot be created or read.' }
+  }
+  if (!(await probeWritable(to))) {
+    return { ok: false, reason: 'The app has no write access to this folder.' }
+  }
+
+  let files: SourceFile[]
+  try {
+    files = await listSourceFiles(from)
+  } catch (err) {
+    if ((err as NodeJS.ErrnoException).code === 'ENOENT') {
+      return { ok: false, reason: 'The current assets folder was not found. Connect it first.' }
+    }
+    throw err
+  }
+  const totalBytes = files.reduce((sum, file) => sum + file.size, 0)
+  const freeBytes = await options.freeBytes(to)
+  if (totalBytes > freeBytes) {
+    return {
+      ok: false,
+      reason: `Not enough space: ${formatBytes(totalBytes)} needed, ${formatBytes(freeBytes)} free.`,
+    }
+  }
+
+  return {
+    ok: true,
+    plan: {
+      from,
+      to,
+      files,
+      totalBytes,
+      freeBytes,
+    },
+  }
+}
+
+class CancelledError extends Error {}
+
+async function copyOne(
+  source: string,
+  partial: string,
+  onBytes: (bytes: number) => void,
+  isCancelled: () => boolean,
+): Promise {
+  await new Promise((resolve, reject) => {
+    const input = fs.createReadStream(source, { highWaterMark: COPY_CHUNK_BYTES })
+    const output = fs.createWriteStream(partial)
+    // Reject only after the output handle is closed. On Windows an open handle blocks the
+    // removal of the partial file.
+    const fail = (err: Error) => {
+      input.destroy()
+      if (output.closed) reject(err)
+      else {
+        output.once('close', () => reject(err))
+        output.destroy()
+      }
+    }
+    input.on('data', (chunk) => {
+      onBytes(chunk.length)
+      if (isCancelled()) input.destroy(new CancelledError())
+    })
+    input.on('error', fail)
+    output.on('error', fail)
+    // 'close', not 'finish': on Windows the file cannot be renamed before the handle is closed.
+    output.on('close', resolve)
+    input.pipe(output)
+  })
+}
+
+async function removeQuietly(file: string): Promise {
+  await fsp.rm(file, { force: true }).catch(() => undefined)
+}
+
+/**
+ * Copies every file. A file with the same name in the target is replaced. Each file goes to a partial name first,
+ * its size is checked, and then it gets its final name. A cancel or an error removes
+ * everything this call created.
+ */
+export async function copyFiles(plan: MovePlan, hooks: CopyHooks): Promise {
+  const created: string[] = []
+  let filesDone = 0
+  let bytesDone = 0
+  const cleanup = async () => {
+    for (const file of created) await removeQuietly(file)
+  }
+  try {
+    for (const file of plan.files) {
+      if (hooks.isCancelled()) throw new CancelledError()
+      const target = path.join(plan.to, file.name)
+      const partial = target + PARTIAL_SUFFIX
+      created.push(partial)
+      await copyOne(
+        path.join(plan.from, file.name),
+        partial,
+        (bytes) => {
+          bytesDone += bytes
+          hooks.onProgress({ filesDone, bytesDone })
+        },
+        hooks.isCancelled,
+      )
+      if ((await fsp.stat(partial)).size !== file.size) {
+        throw new Error(`The copy of ${file.name} has the wrong size.`)
+      }
+      // The old file is deleted later. Flush the copy to disk first, so a power loss cannot
+      // leave a truncated copy next to a deleted original.
+      const handle = await fsp.open(partial, 'r+')
+      try {
+        await handle.sync()
+      } finally {
+        await handle.close()
+      }
+      // A file that was in the target before stays when a later step fails: it is not ours to delete.
+      const existed = await fsp.access(target).then(() => true, () => false)
+      await fsp.rename(partial, target)
+      if (existed) created.pop()
+      else created[created.length - 1] = target
+      filesDone += 1
+      hooks.onProgress({ filesDone, bytesDone })
+    }
+    return { status: 'done', created }
+  } catch (err) {
+    await cleanup()
+    if (err instanceof CancelledError || hooks.isCancelled()) return { status: 'cancelled', created: [] }
+    throw err
+  }
+}
+
+/** The marker tells the backend that this folder is the library, not an empty mount point. Returns false when it was there already. */
+export async function writeMarker(dir: string): Promise {
+  try {
+    await fsp.writeFile(path.join(dir, ASSETS_MARKER_FILENAME), '', { flag: 'wx' })
+    return true
+  } catch (err) {
+    if ((err as NodeJS.ErrnoException).code === 'EEXIST') return false
+    throw err
+  }
+}
+
+export async function removeMarker(dir: string): Promise {
+  await fsp.rm(path.join(dir, ASSETS_MARKER_FILENAME), { force: true }).catch(() => undefined)
+}
+
+/** Removes the marker, and the in-flight folder if it is empty, from a folder the app left. */
+export async function releaseFolder(dir: string): Promise {
+  await removeMarker(dir)
+  await fsp.rmdir(path.join(dir, IN_FLIGHT_DIRNAME)).catch(() => undefined)
+}
+
+/** Removes files that a failed or reverted move created in the new folder. */
+export async function removeCreated(created: string[]): Promise {
+  for (const file of created) await removeQuietly(file)
+}
+
+/** Deletes the moved files from the old folder. Returns the files that could not be deleted. */
+export async function deleteMovedFiles(plan: MovePlan): Promise {
+  const failed: string[] = []
+  for (const file of plan.files) {
+    const full = path.join(plan.from, file.name)
+    try {
+      await fsp.rm(full, { force: true })
+    } catch {
+      failed.push(full)
+    }
+  }
+  return failed
+}
+
+export type AssetsDirCheck = { ok: true } | { ok: false; reason: string }
+
+/** Startup check for a saved custom folder: it must exist, be writable and hold the marker. */
+export async function checkCustomAssetsDir(dir: string): Promise {
+  // A network path would make Windows send credentials to the remote host.
+  if (isRemoteFilePath(dir)) return { ok: false, reason: 'Network folders are not supported.' }
+  try {
+    if (!(await fsp.stat(dir)).isDirectory()) return { ok: false, reason: 'The path is not a folder.' }
+  } catch {
+    return { ok: false, reason: 'The folder was not found.' }
+  }
+  const hasMarker = await fsp.access(path.join(dir, ASSETS_MARKER_FILENAME)).then(() => true, () => false)
+  if (!hasMarker) {
+    return { ok: false, reason: `The folder has no ${ASSETS_MARKER_FILENAME} file. It may be an empty mount point.` }
+  }
+  if (!(await probeWritable(dir))) return { ok: false, reason: 'The app has no write access to the folder.' }
+  return { ok: true }
+}
diff --git a/electron/assets-startup.ts b/electron/assets-startup.ts
new file mode 100644
index 000000000..553b17198
--- /dev/null
+++ b/electron/assets-startup.ts
@@ -0,0 +1,91 @@
+import { app } from 'electron'
+import { getAssetsDir, getDefaultAssetsDir, isCustomAssetsDir, setAssetsDir } from './app-state'
+import { checkCustomAssetsDir } from './assets-relocation'
+import { logger } from './logger'
+import { pickFolder, showMessage } from './native-dialogs'
+
+const RETRY = 0
+const CHOOSE = 1
+const USE_DEFAULT = 2
+const QUIT = 3
+
+async function askWhatToDo(dir: string, reason: string): Promise {
+  return showMessage({
+    type: 'warning',
+    title: 'Assets folder not available',
+    message: 'The assets folder is not available.',
+    detail:
+      `${dir}\n\n${reason}\n\n` +
+      'Your assets are not deleted. Connect the drive or restore the folder, then choose Retry. ' +
+      'Choose "Choose folder" if you moved the folder. ' +
+      'Choose "Use default folder" to start with the default folder. Your assets in the old folder stay there.',
+    buttons: ['Retry', 'Choose folder…', 'Use default folder', 'Quit'],
+    defaultId: RETRY,
+    cancelId: QUIT,
+    noLink: true,
+  })
+}
+
+async function confirmUseDefault(): Promise {
+  const response = await showMessage({
+    type: 'warning',
+    message: 'Use the default folder?',
+    detail:
+      'Your assets in the other folder will not show in the app, and the app marks them as deleted. ' +
+      'The files stay in the other folder, but the app cannot show them again. ' +
+      'Choose "Back" if you can still connect or find the folder.',
+    buttons: ['Use default folder', 'Back'],
+    defaultId: 1,
+    cancelId: 1,
+    noLink: true,
+  })
+  return response === 0
+}
+
+/** A relink does not copy anything: the chosen folder must already hold the library. */
+async function chooseMovedFolder(): Promise {
+  const picked = await pickFolder('Choose the assets folder')
+  if (!picked) return
+  const check = await checkCustomAssetsDir(picked)
+  if (!check.ok) {
+    await showMessage({
+      type: 'warning',
+      message: `This folder cannot be used. ${check.reason}`,
+      buttons: ['OK'],
+      noLink: true,
+    })
+    return
+  }
+  setAssetsDir(picked)
+}
+
+/**
+ * Runs before every backend start. A saved custom folder that is missing or has no marker
+ * must never fall back to the default folder without the user's choice: the backend would
+ * start with an empty library. The only caller runs inside `startPromise`, so two checks never overlap.
+ */
+export async function ensureAssetsDirReady({ askUser = true }: { askUser?: boolean } = {}): Promise {
+  // The default folder needs no check: the backend creates it.
+  while (isCustomAssetsDir()) {
+    const dir = getAssetsDir()
+    const check = await checkCustomAssetsDir(dir)
+    if (check.ok) return
+    logger.warn(`Assets folder unavailable: ${dir} (${check.reason})`)
+    if (!askUser) throw new Error(`The assets folder is not available. ${check.reason}`)
+
+    const choice = await askWhatToDo(dir, check.reason)
+    if (choice === QUIT) {
+      app.quit()
+      throw new Error('The assets folder is not available.')
+    }
+    if (choice === USE_DEFAULT) {
+      // The default folder exists, so the backend marks every asset that is not in it as deleted.
+      if (!(await confirmUseDefault())) continue
+      setAssetsDir(undefined)
+      logger.info(`Assets folder reset to default ${getDefaultAssetsDir()}`)
+      return
+    }
+    if (choice === CHOOSE) await chooseMovedFolder()
+    // RETRY, or a folder that failed the check: the loop checks again.
+  }
+}
diff --git a/electron/config.ts b/electron/config.ts
index f636f7b7a..2f4e2eed0 100644
--- a/electron/config.ts
+++ b/electron/config.ts
@@ -1,7 +1,7 @@
 import { app } from 'electron'
 import path from 'path'
 import os from 'os'
-import { getProjectAssetsPath } from './app-state'
+import { getAssetsDir, getProjectAssetsPath } from './app-state'
 
 export const isDev = !app.isPackaged
 
@@ -25,6 +25,6 @@ export function getAllowedRoots(): string[] {
   if (!isDev && process.resourcesPath) {
     roots.push(process.resourcesPath)
   }
-  roots.push(getProjectAssetsPath())
+  roots.push(getProjectAssetsPath(), getAssetsDir())
   return roots
 }
diff --git a/electron/explore-seed.test.ts b/electron/explore-seed.test.ts
index 4fceede3e..292b442ea 100644
--- a/electron/explore-seed.test.ts
+++ b/electron/explore-seed.test.ts
@@ -107,6 +107,11 @@ const SEED_CASES: readonly {
     suffix: /motion-track-input\.jpg$/,
     header: { offset: 0, bytes: JPEG_HEADER },
   },
+  ...(["summer", "autumn", "winter", "spring"] as const).map((season) => ({
+    kind: `keyframes-${season}-image` as const,
+    suffix: new RegExp(`keyframes-${season}\\.jpg$`),
+    header: { offset: 0, bytes: JPEG_HEADER },
+  })),
 ];
 
 describe("packaged seed IPC", () => {
@@ -175,4 +180,16 @@ describe("packaged seed path resolution", () => {
     assert.match(yaml, /from:\s+resources\/explore-assets/);
     assert.match(yaml, /to:\s+explore-assets/);
   });
+
+  it("packages the shared JSON files the backend reads at import", () => {
+    const yaml = fs.readFileSync(path.join(repoRoot, "electron-builder.yml"), "utf8");
+    for (const name of [
+      "ic-lora-input-cap.json",
+      "motion-path.json",
+      "ic-lora-stage-2-upscale.json",
+      "ic-lora-tiling-controls.json",
+    ]) {
+      assert.equal(yaml.includes(`- ${name}`), true, name);
+    }
+  });
 });
diff --git a/electron/explore-seed.ts b/electron/explore-seed.ts
index 841e68aaa..0c934a87c 100644
--- a/electron/explore-seed.ts
+++ b/electron/explore-seed.ts
@@ -10,6 +10,9 @@ import {
   IC_LORA_SEED_DIR,
   icLoraSeedFilename,
   INGREDIENTS_SHEET_SEED_FILENAME,
+  KEYFRAMES_SEED_FILES,
+  KEYFRAMES_SEED_KINDS,
+  type KeyframesSeedKind,
   LAYOUT_TO_RENDER_IMAGE_SEED_FILENAME,
   MOTION_TRACK_IMAGE_SEED,
   VIDEO_GUIDE_IMAGE_SEED,
@@ -30,6 +33,19 @@ function icLoraSeedSpec(recipeId: string, title: string) {
   };
 }
 
+function keyframesSeedSpecs() {
+  return Object.fromEntries(
+    KEYFRAMES_SEED_KINDS.map((kind) => [
+      kind,
+      {
+        dir: EXPLORE_IMAGE_TO_VIDEO_SEED_DIR,
+        filename: KEYFRAMES_SEED_FILES[kind],
+        missing: "A Keyframes example image is missing",
+      },
+    ]),
+  ) as Record;
+}
+
 const PACKAGED_SEEDS: Record<
   PackagedSeedKind,
   { dir: string; filename: string; missing: string }
@@ -90,6 +106,7 @@ const PACKAGED_SEEDS: Record<
     filename: VIDEO_GUIDE_IMAGE_SEED.filename,
     missing: "Video Guide start frame is missing",
   },
+  ...keyframesSeedSpecs(),
 };
 
 export function packagedSeedSpec(kind: PackagedSeedKind) {
diff --git a/electron/export/ffmpeg-utils.ts b/electron/export/ffmpeg-utils.ts
index 4c5d4dd61..ca51565bf 100644
--- a/electron/export/ffmpeg-utils.ts
+++ b/electron/export/ffmpeg-utils.ts
@@ -174,6 +174,11 @@ export function getVideoDimensions(videoPath: string): { width: number; height:
   return { width, height }
 }
 
+/** True while an ffmpeg job reads or writes files. */
+export function isFfmpegRunning(): boolean {
+  return activeExportProcess !== null
+}
+
 export function stopExportProcess(): void {
   if (activeExportProcess) {
     logger.info( 'Stopping active export process...')
diff --git a/electron/ipc/assets-handlers.ts b/electron/ipc/assets-handlers.ts
new file mode 100644
index 000000000..90f82527f
--- /dev/null
+++ b/electron/ipc/assets-handlers.ts
@@ -0,0 +1,11 @@
+import { getAssetsDir } from '../app-state'
+import { cancelAssetsMove, changeAssetsDir, getAssetsMoveState } from '../assets-move'
+import { handle } from './typed-handle'
+
+export function registerAssetsHandlers(): void {
+  handle('getAssetsDir', () => getAssetsDir())
+  handle('changeAssetsDir', () => changeAssetsDir('pick'))
+  handle('resetAssetsDir', () => changeAssetsDir('default'))
+  handle('cancelAssetsMove', () => cancelAssetsMove())
+  handle('getAssetsMoveState', () => getAssetsMoveState())
+}
diff --git a/electron/ipc/file-handlers.ts b/electron/ipc/file-handlers.ts
index 5eae37fbe..c664cb2a2 100644
--- a/electron/ipc/file-handlers.ts
+++ b/electron/ipc/file-handlers.ts
@@ -458,6 +458,16 @@ export function registerFileHandlers(): void {
     return seedPaths
   })
 
+  // Size only. The path must already be an allowed root or a file the user just picked.
+  handle('getLocalFileSize', ({ filePath }) => {
+    const normalizedPath = validatePath(filePath, getAllowedRoots())
+    const stat = fs.statSync(normalizedPath)
+    if (!stat.isFile()) {
+      throw new Error('Path is not a file')
+    }
+    return stat.size
+  })
+
   handle('showOpenFileDialog', async ({ title, filters, properties }) => {
     const mainWindow = getMainWindow()
     if (!mainWindow) return null
diff --git a/electron/main.ts b/electron/main.ts
index b0c1a43d4..2e9396259 100644
--- a/electron/main.ts
+++ b/electron/main.ts
@@ -9,6 +9,7 @@ import { registerDeepLinkProtocolClient } from './deep-link-protocol'
 import { registerExportHandlers } from './export/export-handler'
 import { stopExportProcess } from './export/ffmpeg-utils'
 import { registerAppHandlers } from './ipc/app-handlers'
+import { registerAssetsHandlers } from './ipc/assets-handlers'
 import { registerFileHandlers } from './ipc/file-handlers'
 import { registerMediaHandlers } from './ipc/media-handlers'
 import { registerLogHandlers } from './ipc/log-handlers'
@@ -130,6 +131,7 @@ if (!gotLock) {
     onSetupCompleted: () => sendLaunched('setup-completed'),
   })
   registerFileHandlers()
+  registerAssetsHandlers()
   registerMediaHandlers()
   registerLogHandlers()
   registerExportHandlers()
diff --git a/electron/native-dialogs.ts b/electron/native-dialogs.ts
new file mode 100644
index 000000000..08c146732
--- /dev/null
+++ b/electron/native-dialogs.ts
@@ -0,0 +1,21 @@
+import { dialog } from 'electron'
+import path from 'path'
+import { getMainWindow } from './window'
+
+/** Native message box. It is modal to the main window when one exists. Returns the button index. */
+export async function showMessage(options: Electron.MessageBoxOptions): Promise {
+  const win = getMainWindow()
+  const result = win ? await dialog.showMessageBox(win, options) : await dialog.showMessageBox(options)
+  return result.response
+}
+
+/** Native folder picker. Returns the resolved path, or `null` when the user cancels. */
+export async function pickFolder(title: string, { canCreate = false } = {}): Promise {
+  const win = getMainWindow()
+  const options: Electron.OpenDialogOptions = {
+    title,
+    properties: canCreate ? ['openDirectory', 'createDirectory'] : ['openDirectory'],
+  }
+  const result = win ? await dialog.showOpenDialog(win, options) : await dialog.showOpenDialog(options)
+  return result.canceled || !result.filePaths[0] ? null : path.resolve(result.filePaths[0])
+}
diff --git a/electron/preload.ts b/electron/preload.ts
index e9dbaae86..97456dd1a 100644
--- a/electron/preload.ts
+++ b/electron/preload.ts
@@ -1,5 +1,6 @@
 import {
   electronAPISchemas,
+  type AssetsMoveState,
   type BackendHealthStatus,
   type UpdateStatePayload,
 } from '../shared/electron-api-schema'
@@ -36,6 +37,12 @@ api.onUpdateEvent = (cb: (data: UpdateStatePayload) => void) => {
   return () => ipcRenderer.removeListener('update-event', listener)
 }
 
+api.onAssetsMoveProgress = (cb: (data: AssetsMoveState) => void) => {
+  const listener = (_: unknown, data: AssetsMoveState) => cb(data)
+  ipcRenderer.on('assets-move-progress', listener)
+  return () => ipcRenderer.removeListener('assets-move-progress', listener)
+}
+
 api.onDeepLink = (cb: (data: DeepLinkIntent) => void) => {
   const listener = (_: unknown, data: DeepLinkIntent) => cb(data)
   ipcRenderer.on('deep-link', listener)
diff --git a/electron/python-backend.ts b/electron/python-backend.ts
index f4048635a..78d5dd683 100644
--- a/electron/python-backend.ts
+++ b/electron/python-backend.ts
@@ -5,6 +5,8 @@ import path from 'path'
 import { sendAnalyticsEvent } from './analytics'
 import { startAnalyticsSink, type AnalyticsSink } from './analytics-sink'
 import { getAppDataDir } from './app-paths'
+import { getAssetsDir, isCustomAssetsDir } from './app-state'
+import { ensureAssetsDirReady } from './assets-startup'
 import { getCurrentDir, isDev } from './config'
 import { clearHeartbeatFile, decideThresholdTick, readHeartbeatState } from './liveness-grace'
 import { logger, writeLog } from './logger'
@@ -327,7 +329,28 @@ export function getPythonPath(): string {
   return 'python'
 }
 
-export async function startPythonBackend(): Promise {
+// While an assets move runs, the backend must stay stopped. A renderer reload calls
+// `startPythonBackend`, and that start would use the old folder while files are copied.
+let startHold: Promise | null = null
+
+/** Makes `startPythonBackend` wait until the returned function is called. */
+export function holdBackendStart(): () => void {
+  let release = () => {}
+  startHold = new Promise((resolve) => {
+    release = () => {
+      startHold = null
+      resolve()
+    }
+  })
+  return release
+}
+
+/**
+ * `askUser: false` is for the assets move. A folder that cannot be used then fails the start, so the
+ * move can roll back by itself. The recovery dialog could change the setting behind the move.
+ */
+export async function startPythonBackend({ askUser = true }: { askUser?: boolean } = {}): Promise {
+  while (startHold) await startHold
   if (startPromise) {
     return startPromise
   }
@@ -349,13 +372,17 @@ export async function startPythonBackend(): Promise {
   isIntentionalShutdown = false
   const epoch = startEpoch
 
-  const openSink: Promise = analyticsSink
-    ? Promise.resolve(analyticsSink)
-    : startAnalyticsSink(sendAnalyticsEvent).catch((error: unknown) => {
-        const message = error instanceof Error ? error.message : String(error)
-        logger.warn(`Analytics sink failed to start; continuing without it: ${message}`)
-        return null
-      })
+  // The check may show a native dialog, so it runs inside the start promise: a second
+  // caller waits on `startPromise` and does not spawn a second backend.
+  const openSink: Promise = ensureAssetsDirReady({ askUser }).then(() =>
+    analyticsSink
+      ? analyticsSink
+      : startAnalyticsSink(sendAnalyticsEvent).catch((error: unknown) => {
+          const message = error instanceof Error ? error.message : String(error)
+          logger.warn(`Analytics sink failed to start; continuing without it: ${message}`)
+          return null
+        }),
+  )
 
   startPromise = openSink.then((sink) => new Promise((resolve, reject) => {
     if (epoch !== startEpoch) {
@@ -418,6 +445,8 @@ export async function startPythonBackend(): Promise {
         LTX_ADMIN_TOKEN: adminToken,
         LTX_LOG_FILE: getCurrentLogFilename(),
         LTX_APP_DATA_DIR: getAppDataDir(),
+        // Always set: an empty value stops a LTX_ASSETS_DIR from the parent environment.
+        LTX_ASSETS_DIR: isCustomAssetsDir() ? getAssetsDir() : '',
         LTX_DEV_MODE: isDev ? '1' : '0',
         LTX_ANALYTICS_SINK_URL: sink?.url ?? '',
         LTX_ANALYTICS_TOKEN: sink?.token ?? '',
@@ -608,6 +637,33 @@ export async function startPythonBackend(): Promise {
   }
 }
 
+/** True when the backend was started outside this app (dev). This app cannot restart it. */
+export function isBackendAdopted(): boolean {
+  return backendOwnership === 'adopted'
+}
+
+/**
+ * Stops the backend and waits until the process exits. A new start must not overlap the old
+ * exit. It throws when the process is still alive after the timeout.
+ */
+export async function stopPythonBackendAndWait(timeoutMs = 15000): Promise {
+  const proc = pythonProcess
+  // A start that is still running ends with "stopped during startup". Wait for that end, so
+  // the next start does not join the old attempt.
+  const pendingStart = startPromise
+  stopPythonBackend()
+  if (proc && proc.exitCode === null && proc.signalCode === null) {
+    await new Promise((resolve, reject) => {
+      const timer = setTimeout(() => reject(new Error('timeout')), timeoutMs)
+      proc.once('exit', () => {
+        clearTimeout(timer)
+        resolve()
+      })
+    })
+  }
+  await pendingStart?.catch(() => undefined)
+}
+
 export function stopPythonBackend(): void {
   startEpoch += 1
 
diff --git a/frontend/assets/home/keyframes/discover-poster.webp b/frontend/assets/home/keyframes/discover-poster.webp
new file mode 100644
index 000000000..af59410a8
Binary files /dev/null and b/frontend/assets/home/keyframes/discover-poster.webp differ
diff --git a/frontend/assets/home/keyframes/discover-preview.mp4 b/frontend/assets/home/keyframes/discover-preview.mp4
new file mode 100644
index 000000000..c2342f048
Binary files /dev/null and b/frontend/assets/home/keyframes/discover-preview.mp4 differ
diff --git a/frontend/assets/home/refine-details/discover-poster.webp b/frontend/assets/home/refine-details/discover-poster.webp
new file mode 100644
index 000000000..de1e13495
Binary files /dev/null and b/frontend/assets/home/refine-details/discover-poster.webp differ
diff --git a/frontend/assets/home/refine-details/discover-preview.mp4 b/frontend/assets/home/refine-details/discover-preview.mp4
new file mode 100644
index 000000000..caab8b7c0
Binary files /dev/null and b/frontend/assets/home/refine-details/discover-preview.mp4 differ
diff --git a/frontend/components/AppShell.tsx b/frontend/components/AppShell.tsx
index f99fb95fc..1c73fa24d 100644
--- a/frontend/components/AppShell.tsx
+++ b/frontend/components/AppShell.tsx
@@ -20,6 +20,7 @@ import {
   type SettingsLegacyScrollAnchor,
   type SettingsTabId,
 } from '../lib/settings-navigation'
+import { AssetsMoveOverlay } from './settings/AssetsMoveOverlay'
 import { SettingsScreen } from './SettingsModal'
 import { UpdateAvailableModal } from './UpdateAvailableModal'
 import { LtxioToastHost } from '../ltx-io/components/shared/Toast/LtxioToastHost'
@@ -387,6 +388,7 @@ export function AppShell() {
       
 
       {restartingOverlay}
+      
       
     
     
diff --git a/frontend/components/SettingsModal.tsx b/frontend/components/SettingsModal.tsx
index e36d8695b..f5df33947 100644
--- a/frontend/components/SettingsModal.tsx
+++ b/frontend/components/SettingsModal.tsx
@@ -20,6 +20,7 @@ import {
 } from "../contexts/AppSettingsContext";
 import type { AppUpdate } from "../hooks/use-app-update";
 import { ApiClient, type ApiSuccessOf } from "../lib/api-client";
+import { useDeleteConfirmationPreference } from "../lib/delete-confirmation-preference";
 import { LtxApiKeyInput } from "./LtxApiKeyInput";
 import { ApiKeySettingsBlock } from "./settings/ApiKeySettingsBlock";
 import { AboutSettingsSection } from "./settings/AboutSettingsSection";
@@ -27,6 +28,7 @@ import { AssistantSettingsSection } from "./settings/AssistantSettingsSection";
 import { CudaPerformanceSection } from "./settings/CudaPerformanceSection";
 import { EnhanceSettingsSection } from "./settings/EnhanceSettingsSection";
 import { LegacyTextEncodingSection } from "./settings/LegacyTextEncodingSection";
+import { AssetsFolderSection } from "./settings/AssetsFolderSection";
 import { LegacySettingsSection } from "./settings/LegacySettingsSection";
 import { ModelsSettingsSection } from "./settings/ModelsSettingsSection";
 import pageLayoutStyles from "./settings/SettingsPageLayout.module.scss";
@@ -41,10 +43,13 @@ import {
   SettingsCallout,
   SettingsHint,
   SettingsKeyStatus,
+  SettingsNumberInput,
   SettingsSelect,
   SettingsStack,
   SettingsSubsection,
 } from "./settings/SettingsContent";
+// eslint-disable-next-line no-restricted-imports
+import { MAX_NAG_SCALE } from "@/ltx-io/screens/Feature/definitions/negativePrompt";
 import { isSettingsTabAvailable } from "../lib/settings-navigation";
 import type {
   SettingsInitialReason,
@@ -235,6 +240,31 @@ export function SettingsScreen({
   const [resolvedGeminiModel, setResolvedGeminiModel] = useState(DEFAULT_GEMINI_MODEL);
   const geminiModelSaveSeq = useRef(0);
   const [analyticsEnabled, setAnalyticsEnabled] = useState(false);
+  const { skipDeleteConfirmation, setSkipDeleteConfirmation } =
+    useDeleteConfirmationPreference();
+  const [nagScaleDraft, setNagScaleDraft] = useState(() => String(settings.nagScale));
+
+  useEffect(() => {
+    setNagScaleDraft(String(settings.nagScale));
+  }, [settings.nagScale]);
+
+  const commitNagScaleDraft = () => {
+    const trimmed = nagScaleDraft.trim();
+    if (!trimmed) {
+      setNagScaleDraft(String(settings.nagScale));
+      return;
+    }
+    const parsed = Number(trimmed);
+    if (!Number.isFinite(parsed)) {
+      setNagScaleDraft(String(settings.nagScale));
+      return;
+    }
+    const clamped = Math.max(0, Math.min(MAX_NAG_SCALE, parsed));
+    setNagScaleDraft(String(clamped));
+    if (clamped !== settings.nagScale) {
+      updateSettings({ nagScale: clamped });
+    }
+  };
 
   // Sync active tab with initialTab when the screen becomes active or the prop changes.
   useEffect(() => {
@@ -434,6 +464,18 @@ export function SettingsScreen({
                 
               
 
+              
+
+              
+                 setSkipDeleteConfirmation(!skipDeleteConfirmation)}
+                />
+              
+
               
+                  {window.electronAPI.platform === "darwin" && settings.useConvVae ? (
+                    
+                        updateSettings({
+                          mpsConv3DAsConv2DEnabled: !settings.mpsConv3DAsConv2DEnabled,
+                        })
+                      }
+                    />
+                  ) : null}
+                  
+
+ +

+ Strength of negative prompt guidance for local Fast generations (0 turns NAG off; default 11). +

+
+ { + setNagScaleDraft(event.currentTarget.value); + }} + onBlur={commitNagScaleDraft} + onKeyDown={(event) => { + if (event.key === "Enter") { + event.currentTarget.blur(); + } + }} + /> +
+ + updateSettings({ + showNagStrengthControls: !settings.showNagStrengthControls, + }) + } + />
@@ -497,6 +592,18 @@ export function SettingsScreen({ /> + + + updateSettings({ advancedControls: !settings.advancedControls }) + } + /> + + + {showPill ? : null} + {showPill ? ( + Cautious mode is on. Jobs that need too much memory or are untested are blocked. + ) : null} + {settingsSyncError ? {settingsSyncError} : null} + {showPill ? ( + + ) : null} + {settingsSyncError ? ( + + ) : null} + + ); +} diff --git a/frontend/components/home/DesktopHomeLayout.tsx b/frontend/components/home/DesktopHomeLayout.tsx index 83b6efd7f..26586a5aa 100644 --- a/frontend/components/home/DesktopHomeLayout.tsx +++ b/frontend/components/home/DesktopHomeLayout.tsx @@ -6,6 +6,8 @@ import { Outlet, useLocation, useNavigate } from "react-router"; import { useTheme } from "@/ds/styles/themes/useTheme"; // eslint-disable-next-line no-restricted-imports +import { DesktopAssistantPanel } from "@/ltx-io/components/Assistant/DesktopAssistantPanel"; +// eslint-disable-next-line no-restricted-imports import { GenerationQueuePanel } from "@/ltx-io/components/GenerationQueue/GenerationQueuePanel"; // eslint-disable-next-line no-restricted-imports import { useQuickSearch } from "@/ltx-io/components/QuickSearch/QuickSearchContext"; @@ -32,8 +34,6 @@ import { } from "../../lib/open-ltx-api-key-settings"; import { LocalGenerationUnsupportedNotice } from "../LocalGenerationUnsupportedNotice"; -// eslint-disable-next-line no-restricted-imports -import { DesktopAssistantPanel } from "@/ltx-io/components/Assistant/DesktopAssistantPanel"; import styles from "./DesktopHomeLayout.module.scss"; import { DesktopHomeSidebar } from "./DesktopHomeSidebar"; import { DesktopHomeSupportFab } from "./DesktopHomeSupportFab"; @@ -41,6 +41,7 @@ import { DesktopHomeSupportFab } from "./DesktopHomeSupportFab"; import { DesktopLtxioQuickSearch } from "./DesktopLtxioQuickSearch"; import { HistoryNavButtons } from "./HistoryNavButtons"; import { PageHeader } from "./PageHeader"; +import { CautiousModePill } from "./CautiousModePill"; import { useHistoryShortcuts } from "./useHistoryNav"; function DesktopHomeLayoutBody({ @@ -62,6 +63,7 @@ function DesktopHomeLayoutBody({ selectAssistant, assistantSelectionPending, budgetModeSaving, + neverSplitSaving, } = useAppSettings(); const { pathname } = useLocation(); useHistoryShortcuts(); @@ -73,6 +75,12 @@ function DesktopHomeLayoutBody({ const isAssetsPage = shellEntry?.id === "assets"; const isAssistantPage = shellEntry?.id === "assistant"; const assistantAvailable = !isSettingsPage && shellEntry?.id !== "projects"; + const nagUnavailableReason = + settings.nagScale <= 0 + ? "Negative prompt guidance (NAG) is turned off in Settings (strength is 0)." + : settings.hasLtxApiKey && !settings.useLocalTextEncoder + ? "Negative prompt guidance (NAG) requires the local text encoder and is skipped while LTX API text encoding is active." + : null; const exploreRuntime = useMemo( () => ({ ...createDesktopExploreRuntime(modelsVersion, { @@ -88,6 +96,8 @@ function DesktopHomeLayoutBody({ ); }, usesLtxApiTextEncoding: !settings.useLocalTextEncoder, + nagUnavailableReason, + showNagStrengthControls: settings.showNagStrengthControls, openLtxApiKeySettings: () => { window.dispatchEvent( new CustomEvent("open-settings", { @@ -104,6 +114,13 @@ function DesktopHomeLayoutBody({ }, budgetMode: settings.budgetMode, budgetModeSaving, + advancedControls: settings.advancedControls, + neverSplitIntoParts: settings.neverSplitIntoParts, + neverSplitSaving, + budgetRiskConfirm: { + skip: settings.skipBudgetRiskConfirm, + setSkip: (skip) => updateSettings({ skipBudgetRiskConfirm: skip }), + }, }), askAssistant: (id: string) => { setAssistantAttachment({ id }); @@ -133,8 +150,14 @@ function DesktopHomeLayoutBody({ modelsVersion, settings.budgetMode, budgetModeSaving, + settings.advancedControls, + settings.neverSplitIntoParts, + neverSplitSaving, + settings.skipBudgetRiskConfirm, settings.exploreAutoEnhancePrompts, settings.useLocalTextEncoder, + nagUnavailableReason, + settings.showNagStrengthControls, settings.assistantProvider, settings.assistantLocalModel, settings.geminiModel, @@ -192,6 +215,7 @@ function DesktopHomeLayoutBody({ } /> ) : null}
, }} /> )} @@ -221,7 +246,16 @@ function DesktopHomeLayoutBody({ fullPage={isAssistantPage} headerLeading={} attachmentRequest={assistantAttachment} - headerActions={queueControl} + headerActions={ + isAssistantPage ? ( + <> + + {queueControl} + + ) : ( + queueControl + ) + } onExpand={() => navigate(paths.assistant)} onDock={() => { setAssistantOpen(true); diff --git a/frontend/components/home/DesktopHomeSidebar.tsx b/frontend/components/home/DesktopHomeSidebar.tsx index bd8f68c56..b45d89c28 100644 --- a/frontend/components/home/DesktopHomeSidebar.tsx +++ b/frontend/components/home/DesktopHomeSidebar.tsx @@ -1,13 +1,15 @@ import { useNavigate } from "react-router"; -import { useAppChromeControls } from "../AppShell"; + +// eslint-disable-next-line no-restricted-imports +import { useAddCustomLoraModal } from "@/ltx-io/screens/Feature/CustomLoraFeatureScreen"; + import { useAppSettings } from "../../contexts/AppSettingsContext"; import { useProjects } from "../../contexts/ProjectContext"; import { openProject } from "../../lib/project-navigation"; +import { useAppChromeControls } from "../AppShell"; + import { HomeSidebar } from "./HomeSidebar"; -import { - planHomeSidebarItems, - type HomeSidebarActions, -} from "./home-sidebar-items"; +import { type HomeSidebarActions, planHomeSidebarItems } from "./home-sidebar-items"; export function DesktopHomeSidebar({ portalContainer, @@ -17,6 +19,7 @@ export function DesktopHomeSidebar({ openQuickSearch?: () => void; }) { const navigate = useNavigate(); + const openAddCustomLora = useAddCustomLoraModal(); const { openSettings, isSettingsModalOpen } = useAppChromeControls(); const { activateProject, clearActiveProject, setCurrentTab } = useProjects(); const { localViable } = useAppSettings(); @@ -24,6 +27,7 @@ export function DesktopHomeSidebar({ const actions: HomeSidebarActions = { host: "desktop", openQuickSearch, + openAddCustomLora, goTo: (path, { clearActiveProject: shouldClear }) => { if (shouldClear) clearActiveProject(); navigate(path); @@ -34,11 +38,5 @@ export function DesktopHomeSidebar({ openProject(projectId, { activateProject, setCurrentTab, navigate }); }, }; - return ( - - ); + return ; } diff --git a/frontend/components/home/HomeGallery.module.scss b/frontend/components/home/HomeGallery.module.scss index e46b4e58e..64e684845 100644 --- a/frontend/components/home/HomeGallery.module.scss +++ b/frontend/components/home/HomeGallery.module.scss @@ -120,6 +120,19 @@ } } +.blankCover { + display: flex; + align-items: center; + justify-content: center; + background: var(--semantic-bg-secondary); + color: var(--semantic-fg-secondary); +} + +.blankCoverIcon { + width: var(--scale-32); + height: var(--scale-32); +} + .copy { display: flex; flex: 1 1 auto; diff --git a/frontend/components/home/HomeGallery.tsx b/frontend/components/home/HomeGallery.tsx index d3f84c240..1d61900d8 100644 --- a/frontend/components/home/HomeGallery.tsx +++ b/frontend/components/home/HomeGallery.tsx @@ -1,42 +1,87 @@ -import { useCallback, useRef, useState } from 'react' -import { Text } from '@/ds/Text/Text' +import { useCallback, useRef, useState } from "react"; + +import { Text } from "@/ds/Text/Text"; +import CustomLoraIcon from "@/ds/assets/Icons/CustomLora.svg?react"; +import { customLoraPosterUrl } from "@/lib/custom-lora-covers"; + import { + type HomeFeatureDefinition, getHomeFeature, offeredHomeFeatureSections, - type HomeFeatureDefinition, -} from '../../lib/home-features.ts' -import { useHighResVideoToVideoEnabled } from '../../ltx-io/hooks/useHighResVideoToVideoEnabled.ts' -import { HOME_LORA_GALLERY_SECTIONS } from '../../lib/home-lora-gallery.ts' -import { HOME_FEATURE_MEDIA, type HomeFeatureMedia } from './home-media' +} from "../../lib/home-features.ts"; +import { HOME_LORA_GALLERY_SECTIONS } from "../../lib/home-lora-gallery.ts"; +import { CUSTOM_LORA_LABEL } from "../../ltx-io/components/QuickSearch/quickSearchModel.ts"; +import { useCustomLoras } from "../../ltx-io/hooks/useCustomLoras.ts"; +import { useHomeFeatureFlags } from "../../ltx-io/hooks/useHomeFeatureFlags.ts"; +import { customLoraRunPath } from "../../paths.ts"; + +import styles from "./HomeGallery.module.scss"; +import { + type GalleryHomeFeatureId, + HOME_FEATURE_MEDIA, + type HomeFeatureMedia, +} from "./home-media"; import { browserFeaturePreviewCanPlayType, canAttachFeaturePreviewSrc, silenceFeaturePreview, -} from './homeFeaturePreviewMedia' -import { usePrefersReducedMotion } from './usePrefersReducedMotion' -import styles from './HomeGallery.module.scss' +} from "./homeFeaturePreviewMedia"; +import { usePrefersReducedMotion } from "./usePrefersReducedMotion"; type HomeGalleryProps = { - onOpen: (path: string) => void + onOpen: (path: string) => void; +}; + +/** One tile of a gallery section: a Home feature, or a LoRA the user saved. */ +type GalleryCard = { + key: string; + title: string; + description: string; + path: string; + media: HomeFeatureMedia | null; +}; + +function featureCard( + feature: HomeFeatureDefinition & { id: GalleryHomeFeatureId }, +): GalleryCard { + return { + key: feature.id, + title: feature.title, + description: feature.description, + path: feature.path, + media: HOME_FEATURE_MEDIA[feature.id], + }; } function gallerySectionHeadingId(heading: string): string { const slug = heading .toLowerCase() - .replace(/[^a-z0-9]+/g, '-') - .replace(/^-|-$/g, '') - return `home-gallery-${slug}` + .replace(/[^a-z0-9]+/g, "-") + .replace(/^-|-$/g, ""); + return `home-gallery-${slug}`; } export function HomeGallery({ onOpen }: HomeGalleryProps) { - const highResVideoToVideo = useHighResVideoToVideoEnabled() + const featureFlags = useHomeFeatureFlags(); + const savedLoras = useCustomLoras().data; + // A chosen cover is a still image. No picture means a blank cover with the brush icon. + const loraCards: GalleryCard[] = (savedLoras ?? []).map((lora) => { + const posterUrl = customLoraPosterUrl(lora.cover_url); + return { + key: lora.id, + title: lora.name, + description: CUSTOM_LORA_LABEL, + path: customLoraRunPath(lora.id), + media: posterUrl == null ? null : { posterUrl }, + }; + }); return (
- {offeredHomeFeatureSections(highResVideoToVideo).map((section) => ( + {offeredHomeFeatureSections(featureFlags).map((section) => ( ))} @@ -44,24 +89,33 @@ export function HomeGallery({ onOpen }: HomeGalleryProps) { getHomeFeature(featureId))} + cards={section.featureIds.map((featureId) => + featureCard( + getHomeFeature(featureId) as HomeFeatureDefinition & { + id: GalleryHomeFeatureId; + }, + ), + )} onOpen={onOpen} /> ))} + {loraCards.length > 0 ? ( + + ) : null}
- ) + ); } function GallerySection({ heading, - features, + cards, onOpen, }: { - heading: string - features: readonly HomeFeatureDefinition[] - onOpen: (path: string) => void + heading: string; + cards: readonly GalleryCard[]; + onOpen: (path: string) => void; }) { - const headingId = gallerySectionHeadingId(heading) + const headingId = gallerySectionHeadingId(heading); return (
    - {features.map((feature) => ( -
  • - onOpen(feature.path)} - /> + {cards.map((card) => ( +
  • + onOpen(card.path)} />
  • ))}
- ) + ); } -function HomeSpotlightCard({ - feature, - media, - onOpen, -}: { - feature: HomeFeatureDefinition - media: HomeFeatureMedia - onOpen: () => void -}) { - const videoRef = useRef(null) - const [previewFailed, setPreviewFailed] = useState(false) - const [isActive, setIsActive] = useState(false) - const reducedMotion = usePrefersReducedMotion() - const previewUrl = media.previewUrl +function HomeSpotlightCard({ card, onOpen }: { card: GalleryCard; onOpen: () => void }) { + const { media } = card; + const videoRef = useRef(null); + const [previewFailed, setPreviewFailed] = useState(false); + const [failedUrl, setFailedUrl] = useState(null); + const [isActive, setIsActive] = useState(false); + const posterUrl = media?.posterUrl; + const showPoster = posterUrl != null && failedUrl !== posterUrl; + const reducedMotion = usePrefersReducedMotion(); + const previewUrl = media?.previewUrl; const canPreview = previewUrl != null && !previewFailed && !reducedMotion && - canAttachFeaturePreviewSrc(previewUrl, browserFeaturePreviewCanPlayType) - const showVideo = canPreview && isActive + canAttachFeaturePreviewSrc(previewUrl, browserFeaturePreviewCanPlayType); + const showVideo = canPreview && isActive; const keepSilent = useCallback(() => { - const video = videoRef.current - if (!video) return - if (video.muted && video.volume === 0) return - silenceFeaturePreview(video) - }, []) + const video = videoRef.current; + if (!video) return; + if (video.muted && video.volume === 0) return; + silenceFeaturePreview(video); + }, []); return ( - ) + ); } diff --git a/frontend/components/home/HomeSidebarMenu.tsx b/frontend/components/home/HomeSidebarMenu.tsx index c1ff82207..18dd2da4e 100644 --- a/frontend/components/home/HomeSidebarMenu.tsx +++ b/frontend/components/home/HomeSidebarMenu.tsx @@ -25,6 +25,9 @@ import { type HomeSidebarNavItem, type HomeSidebarNavItemId, } from "./home-sidebar-items"; +import { isCustomLoraNavId } from "@/lib/custom-lora"; +// eslint-disable-next-line no-restricted-imports +import { useCustomLoras, useRecentCustomLoraIds } from "@/ltx-io/hooks/useCustomLoras"; import { homeFeatureIcon } from "./homeFeatureIcons"; import styles from "./DesktopHomeSidebar.module.scss"; import { useRecentSidebarProjects } from "./useRecentSidebarProjects"; @@ -82,7 +85,8 @@ function iconForNavItem(id: HomeSidebarNavItemId): ReactNode { case "projects": return ; default: - return homeFeatureIcon(id); + // A saved LoRA uses the icon of the Custom LoRA feature. + return homeFeatureIcon(isCustomLoraNavId(id) ? "custom-lora" : id); } } @@ -98,10 +102,16 @@ export function HomeSidebarMenu({ const location = useLocation(); const recentFeatureIds = useRecentSidebarTools(); const recentProjects = useRecentSidebarProjects(); + const savedLoras = useCustomLoras().data; + const recentLoraIds = useRecentCustomLoraIds(); const navEntries = planHomeSidebarNavEntries( plan, recentFeatureIds, recentProjects, + { + saved: savedLoras ?? [], + recentIds: recentLoraIds, + }, ); const footerItems = planHomeSidebarFooterItems(plan); diff --git a/frontend/components/home/RecklessModePill.tsx b/frontend/components/home/RecklessModePill.tsx deleted file mode 100644 index afb956a0a..000000000 --- a/frontend/components/home/RecklessModePill.tsx +++ /dev/null @@ -1,31 +0,0 @@ -import { AlertTriangle } from "lucide-react"; - -import { useAppSettings } from "../../contexts/AppSettingsContext"; - -import styles from "./RecklessModePill.module.scss"; - -/** Header chip while Reckless mode is on, plus the last failed toggle. */ -export function RecklessModePill() { - const { settings, setBudgetMode, budgetModeSaving, settingsSyncError } = useAppSettings(); - const showPill = settings.budgetMode === "reckless"; - if (!showPill && settingsSyncError == null) return null; - return ( - - {showPill ? : null} - {showPill ? ( - Reckless mode is on — over-budget jobs are allowed. - ) : null} - {settingsSyncError ? {settingsSyncError} : null} - {showPill ? ( - - ) : null} - - ); -} diff --git a/frontend/components/home/home-media.ts b/frontend/components/home/home-media.ts index f7146d53f..a6a7d5edc 100644 --- a/frontend/components/home/home-media.ts +++ b/frontend/components/home/home-media.ts @@ -38,6 +38,8 @@ import motionTrackDiscoverPosterUrl from '@/assets/home/motion-track/discover-po import motionTrackDiscoverPreviewUrl from '@/assets/home/motion-track/discover-preview.mp4' import videoGuideDiscoverPosterUrl from '@/assets/home/video-guide/discover-poster.webp' import videoGuideDiscoverPreviewUrl from '@/assets/home/video-guide/discover-preview.mp4' +import refineDetailsDiscoverPosterUrl from '@/assets/home/refine-details/discover-poster.webp' +import refineDetailsDiscoverPreviewUrl from '@/assets/home/refine-details/discover-preview.mp4' import restoreDiscoverPosterUrl from '@/assets/home/restore/discover-poster.webp' import restoreDiscoverPreviewUrl from '@/assets/home/restore/discover-preview.mp4' import dayToNightDiscoverPosterUrl from '@/assets/home/day-to-night/discover-poster.webp' @@ -50,6 +52,8 @@ import fpvMotionDiscoverPosterUrl from '@/assets/home/fpv-motion/discover-poster import fpvMotionDiscoverPreviewUrl from '@/assets/home/fpv-motion/discover-preview.mp4' import imageToVideoDiscoverPosterUrl from '@/assets/home/image-to-video/discover-poster.webp' import imageToVideoDiscoverPreviewUrl from '@/assets/home/image-to-video/discover-preview.mp4' +import keyframesDiscoverPosterUrl from '@/assets/home/keyframes/discover-poster.webp' +import keyframesDiscoverPreviewUrl from '@/assets/home/keyframes/discover-preview.mp4' import jibDownPosterUrl from '@/assets/home/jib-down/poster.webp' import jibDownPreviewUrl from '@/assets/home/jib-down/preview.webm' import jibUpPosterUrl from '@/assets/home/jib-up/poster.webp' @@ -99,7 +103,9 @@ export const PEAK_CINEMATIC_EXAMPLES: readonly PeakCinematicExample[] = [ }, ] -export const HOME_FEATURE_MEDIA: Record = { +export type GalleryHomeFeatureId = Exclude + +export const HOME_FEATURE_MEDIA: Record = { 'text-to-video': { previewUrl: textToVideoDiscoverPreviewUrl, posterUrl: textToVideoDiscoverPosterUrl, @@ -108,6 +114,10 @@ export const HOME_FEATURE_MEDIA: Record = { previewUrl: imageToVideoDiscoverPreviewUrl, posterUrl: imageToVideoDiscoverPosterUrl, }, + keyframes: { + previewUrl: keyframesDiscoverPreviewUrl, + posterUrl: keyframesDiscoverPosterUrl, + }, 'audio-to-video': { previewUrl: audioToVideoDiscoverPreviewUrl, posterUrl: audioToVideoDiscoverPosterUrl, @@ -160,10 +170,9 @@ export const HOME_FEATURE_MEDIA: Record = { previewUrl: ingredientsDiscoverPreviewUrl, posterUrl: ingredientsDiscoverPosterUrl, }, - // Placeholder: the Restore card. Replace it with a Refine Details card. 'refine-details': { - previewUrl: restoreDiscoverPreviewUrl, - posterUrl: restoreDiscoverPosterUrl, + previewUrl: refineDetailsDiscoverPreviewUrl, + posterUrl: refineDetailsDiscoverPosterUrl, }, 'motion-track': { previewUrl: motionTrackDiscoverPreviewUrl, diff --git a/frontend/components/home/home-sidebar-items.test.ts b/frontend/components/home/home-sidebar-items.test.ts index 37b397d6a..8b10346e8 100644 --- a/frontend/components/home/home-sidebar-items.test.ts +++ b/frontend/components/home/home-sidebar-items.test.ts @@ -2,7 +2,7 @@ import assert from "node:assert/strict"; import { describe, it } from "node:test"; import { HOME_SIDEBAR_FEATURED_FEATURES } from "../../lib/home-features.ts"; -import { paths } from "../../paths.ts"; +import { customLoraRunPath, paths } from "../../paths.ts"; import { type HomeSidebarActions, @@ -42,7 +42,7 @@ describe("planHomeSidebarItems", () => { }); describe("planHomeSidebarNavItems", () => { - it("orders pages (Home, Assets, Remote, GenSpace) before Featured tools for a viable Desktop plan", () => { + it("orders pages (Home, Assets, Remote, GenSpace, Add custom LoRA) before Featured tools for a viable Desktop plan", () => { const plan = planHomeSidebarItems({ host: "desktop", localViable: true }); assert.deepEqual( planHomeSidebarNavItems(plan).map((item) => ({ @@ -55,6 +55,7 @@ describe("planHomeSidebarNavItems", () => { { id: "assets", path: paths.assets }, { id: "remote", path: paths.remote }, { id: "projects", path: paths.projects }, + { id: "custom-lora", path: paths.customLora }, ...HOME_SIDEBAR_FEATURED_FEATURES.map((feature) => ({ id: feature.id, path: feature.path, @@ -68,7 +69,12 @@ describe("planHomeSidebarNavItems", () => { const items = planHomeSidebarNavItems(plan); assert.deepEqual( items.map((item) => item.id), - ["home", "assistant", "assets", ...HOME_SIDEBAR_FEATURED_FEATURES.map((feature) => feature.id)], + [ + "home", + "assistant", + "assets", + ...HOME_SIDEBAR_FEATURED_FEATURES.map((feature) => feature.id), + ], ); for (const item of items) { assert.equal(item.path.includes("?"), false); @@ -119,6 +125,7 @@ describe("planHomeSidebarNavItems", () => { "assets", "remote", "projects", + "custom-lora", "featured", ...HOME_SIDEBAR_FEATURED_FEATURES.map((feature) => feature.id), ]); @@ -133,9 +140,11 @@ describe("planHomeSidebarNavItems", () => { it("lists recent Gen Space projects under the Gen Space nav item", () => { const plan = planHomeSidebarItems({ host: "desktop", localViable: true }); - const kinds = planHomeSidebarNavEntries(plan, [], [ - { id: "p1", name: "My timeline" }, - ]).map((entry) => + const kinds = planHomeSidebarNavEntries( + plan, + [], + [{ id: "p1", name: "My timeline" }], + ).map((entry) => entry.kind === "item" ? entry.item.id : entry.kind === "recent-project" @@ -148,6 +157,7 @@ describe("planHomeSidebarNavItems", () => { "assets", "remote", "projects", + "custom-lora", "recent-projects", "project:p1", "featured", @@ -161,16 +171,16 @@ describe("planHomeSidebarNavItems", () => { it("lists Recent workflows before Featured and omits recent tools from Featured", () => { const plan = planHomeSidebarItems({ host: "desktop", localViable: true }); - const kinds = planHomeSidebarNavEntries(plan, [ - "cozy-felt", - "text-to-video", - ]).map((entry) => (entry.kind === "item" ? entry.item.id : entry.id)); + const kinds = planHomeSidebarNavEntries(plan, ["cozy-felt", "text-to-video"]).map( + (entry) => (entry.kind === "item" ? entry.item.id : entry.id), + ); assert.deepEqual(kinds, [ "home", "assistant", "assets", "remote", "projects", + "custom-lora", "recent", "cozy-felt", "text-to-video", @@ -202,6 +212,90 @@ describe("sidebar Featured list", () => { }); }); +describe("sidebar saved custom LoRAs", () => { + const plan = planHomeSidebarItems({ host: "desktop", localViable: true }); + const saved = [ + { id: "ink", name: "Ink" }, + { id: "wash", name: "Wash" }, + ]; + const labels = ( + recentFeatureIds: Parameters[1], + recentIds: string[], + entryPlan = plan, + ) => + planHomeSidebarNavEntries(entryPlan, recentFeatureIds, [], { + saved, + recentIds, + }).map((entry) => + entry.kind === "item" + ? entry.item.label + : entry.kind === "section" + ? `[${entry.label}]` + : "", + ); + + it("puts Add custom LoRA right under Gen Space on a viable Desktop plan only", () => { + const result = labels([], []); + const genSpaceAt = result.indexOf("Gen Space"); + assert.ok(genSpaceAt >= 0); + assert.equal(result[genSpaceAt + 1], "Add custom LoRA"); + + const notViable = planHomeSidebarItems({ host: "desktop", localViable: false }); + assert.ok(!labels([], [], notViable).includes("Add custom LoRA")); + const remote = planHomeSidebarItems({ host: "remote", localViable: true }); + assert.ok(!labels([], [], remote).includes("Add custom LoRA")); + }); + + it("does not list a saved LoRA the user never ran, and has no My LoRAs section", () => { + const result = labels([], []); + + assert.ok(!result.includes("Ink") && !result.includes("Wash")); + assert.ok(!result.includes("[My LoRAs]")); + }); + + it("puts a LoRA the user ran under Recent workflows by its name, and does not list it twice", () => { + const result = labels(["custom-lora", "cozy-felt"], ["wash"]); + + assert.deepEqual( + result.slice(result.indexOf("[Recent workflows]"), result.indexOf("[Featured]")), + ["[Recent workflows]", "Wash", "Cozy Felt"], + ); + assert.equal(result.filter((label) => label === "Wash").length, 1); + assert.ok(!result.includes("Custom LoRA")); + }); + + it("omits a recent LoRA that was removed", () => { + const result = labels(["custom-lora"], ["gone"]); + + assert.ok(!result.includes("[Recent workflows]")); + }); + + it("opens the saved LoRA page and the add dialog for a new one", () => { + const calls: Array<{ path: string; clearActiveProject: boolean }> = []; + let addOpened = false; + const items = planHomeSidebarNavItems(plan, ["custom-lora"], [], { + saved, + recentIds: ["ink"], + }); + const ink = items.find((candidate) => candidate.label === "Ink"); + const add = items.find((candidate) => candidate.label === "Add custom LoRA"); + assert.ok(ink && add); + + selectHomeSidebarNavItem(ink, recordActions("desktop", calls)); + selectHomeSidebarNavItem(add, { + ...recordActions("desktop", calls), + openAddCustomLora: () => { + addOpened = true; + }, + }); + + assert.deepEqual(calls, [ + { path: customLoraRunPath("ink"), clearActiveProject: false }, + ]); + assert.equal(addOpened, true); + }); +}); + describe("planHomeSidebarFooterItems", () => { it("puts only Settings in the footer on a viable Desktop sidebar", () => { const plan = planHomeSidebarItems({ host: "desktop", localViable: true }); @@ -241,6 +335,7 @@ describe("selectHomeSidebarNavItem", () => { { path: paths.assets, clearActiveProject: false }, { path: paths.remote, clearActiveProject: true }, { path: paths.projects, clearActiveProject: true }, + { path: paths.customLora, clearActiveProject: false }, ...HOME_SIDEBAR_FEATURED_FEATURES.map((feature) => ({ path: feature.path, clearActiveProject: false, @@ -331,7 +426,9 @@ describe("isHomeSidebarFooterItemActive", () => { true, ); assert.equal( - isHomeSidebarFooterItemActive(paths.settings, settings, { settingsModalOpen: false }), + isHomeSidebarFooterItemActive(paths.settings, settings, { + settingsModalOpen: false, + }), true, ); }); diff --git a/frontend/components/home/home-sidebar-items.ts b/frontend/components/home/home-sidebar-items.ts index 375c162e5..cd9ec1563 100644 --- a/frontend/components/home/home-sidebar-items.ts +++ b/frontend/components/home/home-sidebar-items.ts @@ -1,23 +1,30 @@ import { generatePath } from "react-router"; import { - getHomeFeature, + CUSTOM_LORA_HOME_FEATURE, + type CustomLoraNavId, + customLoraNavId, + isCustomLoraNavId, +} from "../../lib/custom-lora.ts"; +import { HOME_SIDEBAR_FEATURED_FEATURES, - isHomeFeatureId, type HomeFeatureId, + getHomeFeature, + isHomeFeatureId, } from "../../lib/home-features.ts"; import type { RecentProjectSidebarItem } from "../../lib/home-recent-projects-preference.ts"; -import { MAX_SIDEBAR_RECENT_ITEMS } from "../../lib/home-sidebar-recents.ts"; -import { paths } from "../../paths.ts"; -import type { SettingsOpenDetail } from "../../lib/settings-navigation.ts"; import { + HOME_SHELL_ENTRIES, + type HomeShellHost, areHomeFeaturesInNav, getHomeShellEntry, - HOME_SHELL_ENTRIES, homeShellEntryServesHost, isHomeShellNavVisible, - type HomeShellHost, } from "../../lib/home-shell.ts"; +import { MAX_SIDEBAR_RECENT_ITEMS } from "../../lib/home-sidebar-recents.ts"; +import type { SettingsOpenDetail } from "../../lib/settings-navigation.ts"; +import { customLoraRunPath } from "../../paths.ts"; +import { paths } from "../../paths.ts"; export type HomeSidebarHost = HomeShellHost; @@ -42,6 +49,7 @@ export type HomeSidebarNavItemId = | "home" | "assistant" | HomeFeatureId + | CustomLoraNavId | "assets" | "remote" | "projects"; @@ -87,13 +95,38 @@ export type HomeSidebarActions = { openQuickSearch?: () => void; openProject?: (projectId: string) => void; openSettings?: (detail?: SettingsOpenDetail) => void; + /** Desktop only. Opens the add dialog instead of navigating to the add route. */ + openAddCustomLora?: () => void; isSettingsModalOpen?: boolean; }; +/** A LoRA the user saved. Only the id and the name matter to the sidebar. */ +export type SidebarCustomLora = { id: string; name: string }; + +/** + * What the sidebar needs of the custom LoRA feature. `saved` are the saved LoRAs. + * `recentIds` are the ones the user ran, newest run first. + */ +export type SidebarCustomLoras = { + saved: readonly SidebarCustomLora[]; + recentIds: readonly string[]; +}; + +const NO_CUSTOM_LORAS: SidebarCustomLoras = { saved: [], recentIds: [] }; + +function toCustomLoraNavItem(lora: SidebarCustomLora): HomeSidebarNavItem { + return { + id: customLoraNavId(lora.id), + label: lora.name, + path: customLoraRunPath(lora.id), + }; +} + export function planHomeSidebarNavEntries( plan: HomeSidebarItemPlan, recentFeatureIds: readonly HomeFeatureId[] = [], recentProjects: readonly RecentProjectSidebarItem[] = [], + customLoras: SidebarCustomLoras = NO_CUSTOM_LORAS, ): HomeSidebarNavEntry[] { const entries: HomeSidebarNavEntry[] = []; for (const entry of HOME_SHELL_ENTRIES) { @@ -108,11 +141,14 @@ export function planHomeSidebarNavEntries( path: entry.path, }, }); - if ( - entry.id === "projects" && - plan.host === "desktop" && - recentProjects.length > 0 - ) { + // Adding a LoRA needs the computer, so a phone does not get the entry. + if (entry.id === "projects" && plan.host === "desktop" && plan.localViable) { + entries.push({ + kind: "item", + item: toFeatureNavItem(getHomeFeature(CUSTOM_LORA_HOME_FEATURE.id)), + }); + } + if (entry.id === "projects" && plan.host === "desktop" && recentProjects.length > 0) { entries.push({ kind: "section", id: "recent-projects", @@ -128,16 +164,24 @@ export function planHomeSidebarNavEntries( } } if (areHomeFeaturesInNav(plan.host, plan.localViable)) { - const recentTools = recentFeatureIds.slice(0, MAX_SIDEBAR_RECENT_ITEMS); - const recentIds = new Set(recentTools); - if (recentTools.length > 0) { + // Every saved LoRA runs as the one Custom LoRA feature. Its place in the recent list goes to + // the saved LoRAs the user ran, each by its own name. + const savedById = new Map(customLoras.saved.map((lora) => [lora.id, lora])); + const recentLoras = customLoras.recentIds.flatMap((id) => { + const lora = savedById.get(id); + return lora === undefined ? [] : [lora]; + }); + const recent: HomeSidebarNavItem[] = recentFeatureIds + .flatMap((featureId): HomeSidebarNavItem[] => + featureId === CUSTOM_LORA_HOME_FEATURE.id + ? recentLoras.map(toCustomLoraNavItem) + : [toFeatureNavItem(getHomeFeature(featureId))], + ) + .slice(0, MAX_SIDEBAR_RECENT_ITEMS); + const recentIds = new Set(recent.map((item) => item.id)); + if (recent.length > 0) { entries.push({ kind: "section", id: "recent", label: "Recent workflows" }); - for (const featureId of recentTools) { - entries.push({ - kind: "item", - item: toFeatureNavItem(getHomeFeature(featureId)), - }); - } + for (const item of recent) entries.push({ kind: "item", item }); } const featured = HOME_SIDEBAR_FEATURED_FEATURES.filter( (feature) => !recentIds.has(feature.id), @@ -156,11 +200,13 @@ export function planHomeSidebarNavItems( plan: HomeSidebarItemPlan, recentFeatureIds: readonly HomeFeatureId[] = [], recentProjects: readonly RecentProjectSidebarItem[] = [], + customLoras: SidebarCustomLoras = NO_CUSTOM_LORAS, ): HomeSidebarNavItem[] { return planHomeSidebarNavEntries( plan, recentFeatureIds, recentProjects, + customLoras, ).flatMap((entry) => (entry.kind === "item" ? [entry.item] : [])); } @@ -222,7 +268,11 @@ export function selectHomeSidebarNavItem( item: HomeSidebarNavItem, actions: HomeSidebarActions, ): void { - if (isHomeFeatureId(item.id)) { + if (item.id === CUSTOM_LORA_HOME_FEATURE.id && actions.openAddCustomLora) { + actions.openAddCustomLora(); + return; + } + if (isHomeFeatureId(item.id) || isCustomLoraNavId(item.id)) { actions.goTo(item.path, { clearActiveProject: false }); return; } diff --git a/frontend/components/home/homeFeatureIcons.tsx b/frontend/components/home/homeFeatureIcons.tsx index 3a9429e2a..29cc564d2 100644 --- a/frontend/components/home/homeFeatureIcons.tsx +++ b/frontend/components/home/homeFeatureIcons.tsx @@ -5,6 +5,7 @@ import AlphaGenIcon from "@/ds/assets/Icons/AlphaGen.svg?react"; import AudioIcon from "@/ds/assets/Icons/Audio.svg?react"; import BackdropIcon from "@/ds/assets/Icons/Backdrop.svg?react"; import CubeSketchIcon from "@/ds/assets/Icons/CubeSketch.svg?react"; +import CustomLoraIcon from "@/ds/assets/Icons/CustomLora.svg?react"; import ExtendIcon from "@/ds/assets/Icons/ExtendDuration.svg?react"; import MagicWandIcon from "@/ds/assets/Icons/MagicWand.svg?react"; import PhotoIcon from "@/ds/assets/Icons/Photo.svg?react"; @@ -33,6 +34,7 @@ const FEATURE_ICONS: Partial> = { decompression: AdjustIcon, "layout-to-render": CubeSketchIcon, "motion-track": WorkflowIcon, + "custom-lora": CustomLoraIcon, }; export function homeFeatureIcon(id: HomeFeatureId): ReactNode { diff --git a/frontend/components/home/useRecentSidebarTools.ts b/frontend/components/home/useRecentSidebarTools.ts index 2f4d7fda3..839e540af 100644 --- a/frontend/components/home/useRecentSidebarTools.ts +++ b/frontend/components/home/useRecentSidebarTools.ts @@ -18,8 +18,7 @@ const RECENT_FEATURES_QUERY_KEY = generationQueryKeys.recentFeatures( ); /** - * Distinct features from the newest generations, shared by desktop and remote. The backend - * leaves out a feature that needs the `highResVideoToVideo` flag while the flag is off. + * Distinct features from the newest generations, shared by desktop and remote. */ export function useRecentSidebarTools(): readonly HomeFeatureId[] { const { api } = useExploreRuntime(); diff --git a/frontend/components/settings/AssetsFolderSection.tsx b/frontend/components/settings/AssetsFolderSection.tsx new file mode 100644 index 000000000..2503a78ce --- /dev/null +++ b/frontend/components/settings/AssetsFolderSection.tsx @@ -0,0 +1,99 @@ +import { useQuery } from '@tanstack/react-query' +import { useEffect, useState } from 'react' +import { ApiClient } from '../../lib/api-client' +import { useGlobalGenerationLock } from '../../hooks/use-global-generation-lock' +import { fetchGenerationQueue, generationQueryKeys } from '../../ltx-io/hooks/generationQueryKeys' +import { Button as DsButton } from '@/ds/Button/Button' +import { Tooltip } from '@/ds/Tooltip/Tooltip' +import { + SettingsFieldRow, + SettingsReadonlyField, + SettingsSubsection, +} from './SettingsContent' +import contentStyles from './SettingsContent.module.scss' + +const QUEUE_POLL_MS = 3000 +const RUNNING_TOOLTIP = + 'Changing the assets folder restarts the app server. Wait for the running generation to finish.' +const CHECKING_TOOLTIP = 'Checking for running generations…' +const UNKNOWN_TOOLTIP = + 'The app cannot check for running generations now. Changing the assets folder restarts the app server.' + +/** + * Why the folder cannot change now, or `null`. A generation that runs or waits blocks it. + * A queue that is not known also blocks it, with its own text: the restart must not hit a generation. + */ +function useChangeBlockedReason(): string | null { + const { isRunning } = useGlobalGenerationLock() + const queue = useQuery({ + queryKey: generationQueryKeys.queue, + queryFn: () => fetchGenerationQueue(ApiClient), + refetchInterval: QUEUE_POLL_MS, + }) + // After a failed poll the query keeps its last data, so the error is checked first. + if (isRunning || (!queue.isError && queue.data && queue.data.active.length + queue.data.queued.length > 0)) { + return RUNNING_TOOLTIP + } + if (queue.isError) return UNKNOWN_TOOLTIP + return queue.data ? null : CHECKING_TOOLTIP +} + +export function AssetsFolderSection() { + const [assetsDir, setAssetsDir] = useState('') + const blockedReason = useChangeBlockedReason() + + const load = () => + window.electronAPI + .getAssetsDir() + .then((dir) => setAssetsDir(dir)) + .catch(() => {}) + + useEffect(() => { + void load() + }, []) + + // The main process shows the dialogs and runs the move. The page reloads when it ends. + const change = async (reset: boolean) => { + const result = reset ? await window.electronAPI.resetAssetsDir() : await window.electronAPI.changeAssetsDir() + if (result.success) setAssetsDir(result.path) + } + + const control = (label: string, reset: boolean) => ( + + void change(reset)} + /> + + ) + + const wrap = (node: React.ReactNode) => + blockedReason ? ( + + {node} + + ) : ( + node + ) + + return ( + + + + {wrap(control('Change…', false))} + {wrap(control('Reset to default', true))} + + + ) +} diff --git a/frontend/components/settings/AssetsMoveOverlay.tsx b/frontend/components/settings/AssetsMoveOverlay.tsx new file mode 100644 index 000000000..7165c67fd --- /dev/null +++ b/frontend/components/settings/AssetsMoveOverlay.tsx @@ -0,0 +1,91 @@ +import { useEffect, useState } from 'react' +import { ActivityBar } from '@/ds/ActivityBar/ActivityBar' +import { Button as DsButton } from '@/ds/Button/Button' +import { formatBytes } from '@/lib/format' +import type { AssetsMoveState } from '../../../shared/electron-api-schema' +import { AppProductDialogShell } from '../dialog/AppProductDialogShell' + +const PHASE_LABEL: Record = { + checking: 'Checking the folder…', + stopping: 'Stopping the app server…', + copying: 'Copying and checking files…', + restarting: 'Restarting the app server…', + cleaning: 'Deleting the old files…', + done: '', +} + +/** + * Blocks the app while the main process moves the assets folder. The dialog shell makes the + * rest of the app inert and keeps the focus inside. It restores its state after a reload. + */ +export function AssetsMoveOverlay() { + const [move, setMove] = useState(null) + + useEffect(() => { + let received = false + const unsubscribe = window.electronAPI.onAssetsMoveProgress((next) => { + received = true + setMove(next) + }) + void window.electronAPI.getAssetsMoveState().then((current) => { + if (!received) setMove(current) + }) + return unsubscribe + }, []) + + if (!move) return null + + const result = move.phase === 'done' ? move.result : undefined + const percent = move.bytesTotal > 0 ? Math.min(100, (move.bytesDone / move.bytesTotal) * 100) : 0 + + const footer = result ? ( + (result.ok ? window.location.reload() : setMove(null))} + /> + ) : move.canCancel ? ( + void window.electronAPI.cancelAssetsMove()} + /> + ) : undefined + + return ( + <> + {/* The server is stopped during a move, so the pages behind show errors or "Coming soon". Hide them. */} +
+ + {result ? ( +

{result.message}

+ ) : ( + <> +

{PHASE_LABEL[move.phase]}

+ {move.phase === 'copying' && move.filesTotal > 0 ? ( +
+ +

+ {move.filesDone} of {move.filesTotal} files · {formatBytes(move.bytesDone)} of {formatBytes(move.bytesTotal)} +

+
+ ) : null} +

Do not close the app.

+ + )} +
+ + ) +} diff --git a/frontend/components/settings/CustomLoraSettingsBlock.tsx b/frontend/components/settings/CustomLoraSettingsBlock.tsx new file mode 100644 index 000000000..9e4de0951 --- /dev/null +++ b/frontend/components/settings/CustomLoraSettingsBlock.tsx @@ -0,0 +1,218 @@ +import { AlertCircle } from 'lucide-react' +import { Fragment, useCallback, useMemo, useState } from 'react' +import { Button as DsButton } from '@/ds/Button/Button' +import { Text } from '@/ds/Text/Text' +import type { components } from '@/generated/backend-openapi' +// eslint-disable-next-line no-restricted-imports +import { + useCustomLoraImport, + useCustomLorasWith, + useDeleteCustomLoraWeightsWith, + useRemoveCustomLoraWith, +} from '@/ltx-io/hooks/useCustomLoras' +// eslint-disable-next-line no-restricted-imports +import { ApiResultError } from '@/ltx-io/lib/unwrapApiResult' +import { useAppSettings } from '../../contexts/AppSettingsContext' +import { ApiClient } from '../../lib/api-client' +import { formatBytes } from '../../lib/format' +import { + ModelCatalogActionGroup, + ModelCatalogCellText, + ModelCatalogDetailRow, + ModelCatalogInstalledCheck, + ModelCatalogNameCell, + ModelCatalogSizeCell, + ModelCatalogSizeText, + ModelCatalogTable, + confirmCatalogModelDelete, + modelCatalogActionButtonWideClassName, + modelCatalogDownloadButtonLabel, + modelCatalogTableStyles, +} from './ModelCatalogTable' +import { SettingsStack, SettingsSubsection } from './SettingsContent' + +type CustomLoraItem = components['schemas']['CustomLoraItem'] + +// The backend refuses a delete with a message the user can act on (a queued run uses the LoRA). +// Any other failure shows the fallback. +function errorMessage(error: unknown, fallback: string): string { + return error instanceof ApiResultError && error.code === 'CUSTOM_LORA_IN_USE' + ? error.message + : fallback +} + +function pickWeightsFile(): Promise { + return window.electronAPI + .showOpenFileDialog({ + title: 'Choose LoRA weights', + filters: [{ name: 'LoRA weights', extensions: ['safetensors'] }], + properties: ['openFile'], + }) + .then((paths) => paths?.[0] ?? null) +} + +/** + * The LoRAs the user added. Each one is a row like a catalog LoRA: Download and Delete work on the + * weights. Delete keeps the entry, so the LoRA stays in the sidebar and asks for its weights + * again. A LoRA with no weights also has Remove, which drops the entry. + */ +export function CustomLoraSettingsBlock({ searchQuery = '' }: { searchQuery?: string }) { + const { notifyModelsChanged } = useAppSettings() + const lorasQuery = useCustomLorasWith(ApiClient) + const deleteWeights = useDeleteCustomLoraWeightsWith(ApiClient) + const removeLora = useRemoveCustomLoraWith(ApiClient) + const importer = useCustomLoraImport(ApiClient, () => notifyModelsChanged()) + const [errorById, setErrorById] = useState>>({}) + + const setError = useCallback((id: string, message: string | null) => { + setErrorById((current) => { + const { [id]: _removed, ...rest } = current + return message === null ? rest : { ...rest, [id]: message } + }) + }, []) + + const rows = useMemo(() => { + const all = lorasQuery.data ?? [] + return searchQuery + ? all.filter((lora) => lora.name.toLowerCase().includes(searchQuery)) + : all + }, [lorasQuery.data, searchQuery]) + + if (rows.length === 0) return null + + const busy = importer.state.status === 'running' + const progress = importer.state.status === 'running' ? importer.state.progress : 0 + + const handleDelete = async (lora: CustomLoraItem) => { + if (!confirmCatalogModelDelete(lora.name)) return + setError(lora.id, null) + try { + await deleteWeights.mutateAsync(lora.id) + notifyModelsChanged() + } catch (error) { + setError(lora.id, errorMessage(error, 'Could not remove this file.')) + } + } + + const handleRemove = async (lora: CustomLoraItem) => { + if (!confirmCatalogModelDelete(lora.name)) return + setError(lora.id, null) + try { + await removeLora.mutateAsync(lora.id) + notifyModelsChanged() + } catch (error) { + setError(lora.id, errorMessage(error, 'Could not remove this LoRA.')) + } + } + + const handleDownload = (lora: CustomLoraItem) => { + setError(lora.id, null) + importer.dismissError() + void importer.restore(lora.id, {}) + } + + const handleChooseFile = async (lora: CustomLoraItem) => { + setError(lora.id, null) + const picked = await pickWeightsFile() + if (picked === null) return + importer.dismissError() + void importer.restore(lora.id, { source_path: picked }) + } + + return ( + + + + {rows.map((lora) => { + const isRestoring = + importer.state.status === 'running' && + importer.state.customLoraId === lora.id + const restoreError = + importer.state.status === 'error' && + importer.state.customLoraId === lora.id + ? importer.state.message + : null + const detail = errorById[lora.id] ?? restoreError + return ( + + + + {lora.name} + {lora.downloaded ? : null} + + + + {lora.size_bytes ? formatBytes(lora.size_bytes) : '—'} + + + void handleRemove(lora)} + /> + ) + } + action={ + lora.downloaded ? ( + void handleDelete(lora)} + /> + ) : lora.can_download ? ( + handleDownload(lora)} + /> + ) : ( + void handleChooseFile(lora)} + /> + ) + } + /> + + {detail ? ( + + + + {detail} + + + ) : null} + + ) + })} + + + + ) +} diff --git a/frontend/components/settings/HardwareBudgetSection.tsx b/frontend/components/settings/HardwareBudgetSection.tsx index 81bcee0e8..927c41d78 100644 --- a/frontend/components/settings/HardwareBudgetSection.tsx +++ b/frontend/components/settings/HardwareBudgetSection.tsx @@ -1,34 +1,59 @@ import type { AppSettings } from "../../contexts/AppSettingsContext"; import { SettingToggle } from "./SettingToggle"; -import { SettingsSubsection } from "./SettingsContent"; +import { SettingsStack, SettingsSubsection } from "./SettingsContent"; export function HardwareBudgetSection({ settings, - onToggleReckless, + onSetCautious, + onSetAskBeforeRisky, + onSetNeverSplit, saving = false, + neverSplitSaving = false, syncError, }: { - settings: Pick; - onToggleReckless: () => void; + settings: Pick; + onSetCautious: (cautious: boolean) => void; + onSetAskBeforeRisky: (ask: boolean) => void; + onSetNeverSplit: (neverSplit: boolean) => void; saving?: boolean; + neverSplitSaving?: boolean; syncError?: string | null; }) { + const cautious = settings.budgetMode === "cautious"; + const askBeforeRisky = !settings.skipBudgetRiskConfirm; return ( - + + onSetCautious(!cautious)} + /> + onSetAskBeforeRisky(!askBeforeRisky)} + /> + onSetNeverSplit(!settings.neverSplitIntoParts)} + /> + ); } diff --git a/frontend/components/settings/LegacyProjectAssetsSection.tsx b/frontend/components/settings/LegacyProjectAssetsSection.tsx index 0e5266ce7..fd9fb910e 100644 --- a/frontend/components/settings/LegacyProjectAssetsSection.tsx +++ b/frontend/components/settings/LegacyProjectAssetsSection.tsx @@ -21,8 +21,8 @@ export function LegacyProjectAssetsSection() { return ( diff --git a/frontend/components/settings/LoraSettingsSection.tsx b/frontend/components/settings/LoraSettingsSection.tsx index 403637a6d..f27ceb70d 100644 --- a/frontend/components/settings/LoraSettingsSection.tsx +++ b/frontend/components/settings/LoraSettingsSection.tsx @@ -38,6 +38,9 @@ import { SettingsSubsection, } from './SettingsContent' import contentStyles from './SettingsContent.module.scss' +// eslint-disable-next-line no-restricted-imports +import { useCustomLorasWith } from '@/ltx-io/hooks/useCustomLoras' +import { CustomLoraSettingsBlock } from './CustomLoraSettingsBlock' function isGatedRepoError(message: string): boolean { return message.includes('gated repo') || message.includes('authorized list') @@ -345,13 +348,18 @@ export function LoraSettingsSection({ const styleEntries = useMemo(() => loras.map(loraListItemToEntry), [loras]) const icEntries = useMemo(() => icLoras.map(icListItemToEntry), [icLoras]) + const customLorasQuery = useCustomLorasWith(ApiClient) const searchMatchCount = useMemo(() => { if (!searchQuery) return 1 - const matches = (entries: LibraryEntry[]) => + const matches = (entries: readonly { name: string }[]) => entries.filter((entry) => entry.name.toLowerCase().includes(searchQuery)).length - return matches(styleEntries) + matches(icEntries) - }, [icEntries, searchQuery, styleEntries]) + return ( + matches(styleEntries) + + matches(icEntries) + + matches(customLorasQuery.data ?? []) + ) + }, [customLorasQuery.data, icEntries, searchQuery, styleEntries]) useLayoutEffect(() => { if (!onSearchHasMatches) return @@ -359,11 +367,22 @@ export function LoraSettingsSection({ onSearchHasMatches(true) return } - if (loraCatalogStatus === 'loading' || icCatalogStatus === 'loading') { + if ( + loraCatalogStatus === 'loading' || + icCatalogStatus === 'loading' || + customLorasQuery.isPending + ) { return } onSearchHasMatches(searchMatchCount > 0) - }, [icCatalogStatus, loraCatalogStatus, onSearchHasMatches, searchMatchCount, searchQuery]) + }, [ + customLorasQuery.isPending, + icCatalogStatus, + loraCatalogStatus, + onSearchHasMatches, + searchMatchCount, + searchQuery, + ]) const deleteStyleLora = useCallback(async (id: string, variantId?: string) => { const result = await ApiClient.deleteLoraInstallation({ @@ -427,6 +446,8 @@ export function LoraSettingsSection({ hfAuthStatus={hfAuthStatus} startHuggingFaceLogin={() => void startHuggingFaceLogin()} /> + + ) } diff --git a/frontend/components/settings/SettingToggle.tsx b/frontend/components/settings/SettingToggle.tsx index cbd8f2095..c5e0efacf 100644 --- a/frontend/components/settings/SettingToggle.tsx +++ b/frontend/components/settings/SettingToggle.tsx @@ -38,7 +38,7 @@ export function SettingToggle({ if (rowLayout === "preference") { return ( -
+
))} + {budgetControls ? ( +
+
Hardware capabilities
+ +
+ ) : null}
- {selected ? ( + {selectedItem?.kind === "budget" && budgetControls ? ( + budgetControls + ) : selected ? ( <>

{selected.label}

diff --git a/frontend/ltx-io/components/GenerationQueue/GenerationQueuePanel.module.scss b/frontend/ltx-io/components/GenerationQueue/GenerationQueuePanel.module.scss index 8093765d0..4204b96e8 100644 --- a/frontend/ltx-io/components/GenerationQueue/GenerationQueuePanel.module.scss +++ b/frontend/ltx-io/components/GenerationQueue/GenerationQueuePanel.module.scss @@ -425,6 +425,21 @@ margin-inline-start: 4px; } +.riskBadge { + display: inline-flex; + flex-shrink: 0; + align-items: center; + justify-content: center; + padding: 4px; + color: var(--semantic-fg-warning-primary-enabled); + + svg { + display: block; + width: 12px; + height: 12px; + } +} + .rowBadges { flex: 1 1 auto; min-width: 0; @@ -442,20 +457,6 @@ } } -.gripIcon { - display: block; - flex-shrink: 0; - // Two columns × three rows at 3px — needs 6×9px or the right column clips. - width: 6px; - height: 9px; - background-image: radial-gradient( - circle, - currentcolor 0.8px, - transparent 0.8px - ); - background-size: 3px 3px; -} - .promptRow { display: block; grid-area: prompt; @@ -505,6 +506,16 @@ -webkit-line-clamp: 2; } +/* The `showGenerationNegativePrompt` flag: one line under the prompt; the full text is in the title. */ +.negativePrompt { + margin: 0; + min-width: 0; + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; + color: var(--semantic-fg-tertiary); +} + @media (max-width: shell.$shell-compact-breakpoint) { .root { top: 68px; diff --git a/frontend/ltx-io/components/GenerationQueue/GenerationQueuePanel.test.ts b/frontend/ltx-io/components/GenerationQueue/GenerationQueuePanel.test.ts index 794d34181..1f9cc4e11 100644 --- a/frontend/ltx-io/components/GenerationQueue/GenerationQueuePanel.test.ts +++ b/frontend/ltx-io/components/GenerationQueue/GenerationQueuePanel.test.ts @@ -5,8 +5,13 @@ import { ApiResultError } from "../../lib/unwrapApiResult.ts"; import { formatActiveQueueProgress, formatActiveQueueProgressDetail, + activeQueueRowDetail, + activeQueueTitleStatus, getQueuePanelState, + isActiveCancelDisabled, isQueueReorderConflict, + queueLaneLabel, + queueRowBadges, progressPercentByGenerationId, orderedQueueInputAssets, reorderQueuedEntries, @@ -24,12 +29,11 @@ describe("GenerationQueuePanel queue behavior", () => { it("renders the active cancelling item as fixed without disabling queued cancel", () => { assert.deepEqual( getQueuePanelState({ - active: { generation: { id: "active", status: "cancelling" } }, + active: [{ generation: { id: "active", status: "cancelling" } }], queued, }), { activeIsFixed: true, - activeCancelDisabled: true, queuedCancelDisabled: false, sortableIds: ["queued-a", "queued-b", "queued-c"], sortingDisabled: false, @@ -39,22 +43,28 @@ describe("GenerationQueuePanel queue behavior", () => { it("keeps queued cancel enabled while the active job is running", () => { const state = getQueuePanelState({ - active: { generation: { id: "active", status: "running" } }, + active: [{ generation: { id: "active", status: "running" } }], queued, }); - assert.equal(state.activeCancelDisabled, false); + assert.equal( + isActiveCancelDisabled({ generation: { id: "active", status: "running" } }, false), + false, + ); assert.equal(state.queuedCancelDisabled, false); }); it("disables active and queued cancel only while a cancel request is pending", () => { const pending = getQueuePanelState( { - active: { generation: { id: "active", status: "running" } }, + active: [{ generation: { id: "active", status: "running" } }], queued, }, { isCancelPending: true }, ); - assert.equal(pending.activeCancelDisabled, true); + assert.equal( + isActiveCancelDisabled({ generation: { id: "active", status: "running" } }, true), + true, + ); assert.equal(pending.queuedCancelDisabled, true); }); @@ -141,10 +151,24 @@ describe("GenerationQueuePanel queue behavior", () => { } }); + it("gives a provider job its provider status as the row detail, not a stuck waiting text", () => { + // A provider job reports a phase with no step count, so the percent is not known. + const phaseOnly = { progress: 15, currentStep: null, totalSteps: null }; + + assert.equal(activeQueueRowDetail(phaseOnly, "pending"), "Waiting…"); + assert.equal(activeQueueRowDetail(phaseOnly, "processing"), "Generating…"); + assert.equal(activeQueueRowDetail(null, "processing"), "Generating…"); + assert.equal(activeQueueRowDetail(phaseOnly, null), "Waiting for progress…"); + assert.equal( + activeQueueRowDetail({ progress: 10, currentStep: 3, totalSteps: 10 }, "processing"), + "Step 3 of 10 (30%)", + ); + }); + it("shows the same percent as the placeholder once a step has run", () => { const progress = { progress: 10, currentStep: 3, totalSteps: 10 }; const placeholder = progressPercentByGenerationId({ - active: { generation: { id: "a" }, progress }, + active: [{ generation: { id: "a" }, progress }], queued: [], }).get("a"); @@ -165,10 +189,12 @@ describe("GenerationQueuePanel queue behavior", () => { it("maps denoise steps onto generation ids and skips phase placeholders", () => { const percents = progressPercentByGenerationId({ - active: { - generation: { id: "active" }, - progress: { progress: 10, currentStep: 3, totalSteps: 10 }, - }, + active: [ + { + generation: { id: "active" }, + progress: { progress: 10, currentStep: 3, totalSteps: 10 }, + }, + ], queued: [ { generation: { id: "waiting" }, progress: null }, { @@ -189,21 +215,83 @@ describe("GenerationQueuePanel queue behavior", () => { assert.equal(progressPercentByGenerationId(undefined).size, 0); }); + it("keeps every running row fixed and shows progress for each", () => { + // Bug caught: a second running job (another lane) loses its row or its progress. + const active = [ + { + generation: { id: "local-job", status: "running" }, + progress: { progress: 10, currentStep: 5, totalSteps: 10 }, + }, + { generation: { id: "fal-job", status: "running" }, progress: null }, + ]; + const state = getQueuePanelState({ active, queued }); + assert.equal(state.activeIsFixed, true); + assert.deepEqual(state.sortableIds, ["queued-a", "queued-b", "queued-c"]); + const percents = progressPercentByGenerationId({ active, queued: [] }); + assert.equal(percents.get("local-job"), 50); + assert.equal(percents.has("fal-job"), false); + }); + + it("cancels one running row without disabling the other", () => { + // Bug caught: a cancelling row disables Cancel on every running row. + assert.equal( + isActiveCancelDisabled({ generation: { id: "a", status: "cancelling" } }, false), + true, + ); + assert.equal( + isActiveCancelDisabled({ generation: { id: "b", status: "running" } }, false), + false, + ); + }); + + it("labels a provider lane and leaves the local lane unlabelled", () => { + // Bug caught: a later row starts first and the user sees no reason. + assert.equal(queueLaneLabel("local"), null); + assert.equal(queueLaneLabel(undefined), null); + assert.equal(queueLaneLabel("fal"), "fal"); + }); + + it("shows the lane label once when the provider badge already says it", () => { + // Bug caught: a fal row showed the "fal" badge twice (and a duplicate React key). + assert.deepEqual(queueRowBadges(["2K", "fal"], "fal"), ["2K", "fal"]); + assert.deepEqual(queueRowBadges(["2K"], "fal"), ["2K", "fal"]); + assert.deepEqual(queueRowBadges(["Local"], "local"), ["Local"]); + }); + + it("names the provider status of a running provider job", () => { + // Bug caught: a provider job that waits in the provider queue reads as "Generating". + assert.equal(activeQueueTitleStatus("pending"), "Waiting"); + assert.equal(activeQueueTitleStatus("processing"), "Generating"); + assert.equal(activeQueueTitleStatus(null), null); + }); + it("disables sorting while a reorder mutation is pending", () => { assert.equal( - getQueuePanelState({ active: null, queued }, { isReordering: true }) + getQueuePanelState({ active: [], queued }, { isReordering: true }) .sortingDisabled, true, ); }); it("opens any queue job on its feature result, or returns null for an unknown feature", () => { + const features = [ + { id: "text-to-video", path: "/text-to-video" }, + { id: "custom-lora", path: "/custom-lora" }, + ]; assert.deepEqual( - resultLocationForFeature("text-to-video", "job-a", [ - { id: "text-to-video", path: "/text-to-video" }, - ]), + resultLocationForFeature("text-to-video", "job-a", features), { pathname: "/text-to-video", search: "?result=job-a" }, ); + assert.deepEqual( + resultLocationForFeature("custom-lora", "job-b", features, { + params: { customLoraId: "ink-wash" }, + }), + { pathname: "/custom-lora/ink-wash", search: "?result=job-b" }, + ); + assert.equal( + resultLocationForFeature("custom-lora", "job-b", features, {}), + null, + ); assert.equal(resultLocationForFeature("missing", "job-a", []), null); }); }); diff --git a/frontend/ltx-io/components/GenerationQueue/GenerationQueuePanel.tsx b/frontend/ltx-io/components/GenerationQueue/GenerationQueuePanel.tsx index 30f3b855b..f0f7de768 100644 --- a/frontend/ltx-io/components/GenerationQueue/GenerationQueuePanel.tsx +++ b/frontend/ltx-io/components/GenerationQueue/GenerationQueuePanel.tsx @@ -27,6 +27,8 @@ import { Button } from "@/ds/Button/Button"; import { Text } from "@ds/Text/Text"; import { Skeleton } from "@ds/Skeleton/Skeleton"; import { TooltipProvider } from "@ds/Tooltip/Tooltip"; +import { GENERATION_CANCEL_CONFIRMATION } from "../../hooks/useCancelGeneration.ts"; +import { useConfirmDeleteAction } from "../../hooks/useConfirmDeleteAction.tsx"; import { generationQueueQueryOptions, useGenerationQueue, @@ -54,6 +56,7 @@ import { } from "./GenerationQueueRow.tsx"; import { getQueuePanelState, + isActiveCancelDisabled, isQueueReorderConflict, queuedEntryForActiveDrag, reorderQueuedEntries, @@ -132,12 +135,15 @@ export function GenerationQueuePanel({ useEffect(() => { if (!isOpen) return; + const overlaySelector = + '[role="dialog"], [role="alertdialog"], [role="menu"], [role="listbox"], [data-modal-backdrop]'; const onPointerDown = (event: PointerEvent) => { if (activeDragIdRef.current != null) return; const target = event.target; if (!(target instanceof Node)) return; const root = rootRef.current; if (root?.contains(target)) return; + if (target instanceof Element && target.closest(overlaySelector)) return; closePanel(); }; // Capture phase: the open popover owns Escape, so the Assistant panel around it @@ -149,7 +155,7 @@ export function GenerationQueuePanel({ if ( target instanceof Element && !rootRef.current?.contains(target) && - target.closest('[role="dialog"], [role="alertdialog"], [role="menu"], [role="listbox"]') + target.closest(overlaySelector) ) { return; } @@ -164,6 +170,7 @@ export function GenerationQueuePanel({ }, [isOpen]); const navigate = useNavigate(); const queryClient = useQueryClient(); + const confirmDelete = useConfirmDeleteAction(); const queueQuery = useGenerationQueue({ api, generationPolling, @@ -191,6 +198,7 @@ export function GenerationQueuePanel({ entry.generation.feature, entry.generation.id, HOME_FEATURES, + entry.generation.spec, ); if (location == null) { setFeedback("Couldn’t open this result."); @@ -208,10 +216,12 @@ export function GenerationQueuePanel({ }, }); const cancelGeneration = (generationId: string) => { - cancel.mutate(generationId, { - onError: () => { - setFeedback("Couldn’t cancel that generation. Try again."); - }, + confirmDelete(GENERATION_CANCEL_CONFIRMATION, () => { + cancel.mutate(generationId, { + onError: () => { + setFeedback("Couldn’t cancel that generation. Try again."); + }, + }); }); }; const sensors = useSensors( @@ -222,7 +232,7 @@ export function GenerationQueuePanel({ useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }), ); const snapshot: ExploreQueueSnapshot = queueQuery.data ?? { - active: null, + active: [], queued: [], done: [], failed: [], @@ -297,7 +307,7 @@ export function GenerationQueuePanel({ const queueCount = snapshot.queued.length + - (snapshot.active ? 1 : 0) + + snapshot.active.length + doneEntries.length + failedEntries.length; const queueToggleAriaLabel = @@ -308,9 +318,9 @@ export function GenerationQueuePanel({ ? "Couldn’t load the generation queue." : queueCount === 0 ? "No generations are waiting." - : snapshot.active != null && snapshot.queued.length > 0 + : snapshot.active.length > 0 && snapshot.queued.length > 0 ? `Generating. ${snapshot.queued.length} queued.` - : snapshot.active != null + : snapshot.active.length > 0 ? "Generating." : snapshot.queued.length > 0 ? `${snapshot.queued.length} queued.` @@ -322,7 +332,7 @@ export function GenerationQueuePanel({ const isQueueEmpty = !queueQuery.isLoading && queueQuery.data != null && - snapshot.active == null && + snapshot.active.length === 0 && snapshot.queued.length === 0 && doneEntries.length === 0 && failedEntries.length === 0; @@ -424,23 +434,22 @@ export function GenerationQueuePanel({ >
    - {snapshot.active ? ( + {snapshot.active.map((entry) => ( - cancelGeneration(snapshot.active!.generation.id) - } - onOpen={() => openResult(snapshot.active!)} + onCancel={() => cancelGeneration(entry.generation.id)} + onOpen={() => openResult(entry)} /> - ) : null} + ))} {snapshot.queued.length > 0 ? (
  • ; + return ; } function QueueDragHandle({ @@ -121,13 +128,22 @@ function QueueRowShell({ onOpen, }: QueueRowShellProps) { const presentation = generationPresentation(entry.generation); + const negativePromptLine = useGenerationNegativePrompt(entry.generation); + const hasPromptRow = presentation.prompt.length > 0 || negativePromptLine != null; const inputAssets = orderedQueueInputAssets(entry); const previewAsset = pickQueuePreviewAsset(inputAssets); const title = presentation.label; + // A row on a provider lane says so. Without it, a later row can start first with no visible reason. + const badges = queueRowBadges(presentation.badges, entry.generation.lane); + + // An image run has no Home screen to open on. Opening is the only way to read a done row, + // so such a row shows no unread dot. + const hasResultScreen = + resultLocationForFeature(entry.generation.feature, entry.generation.id, HOME_FEATURES) != null; const layoutAttrs = { "data-has-asset": previewAsset != null ? "" : undefined, - "data-has-prompt": presentation.prompt.length > 0 ? "" : undefined, + "data-has-prompt": hasPromptRow ? "" : undefined, }; const body = ( @@ -147,16 +163,30 @@ function QueueRowShell({ {title} {titleSuffix} - {showUnreadDot ? : null} + {showUnreadDot && hasResultScreen ? : null}
- {presentation.badges.length > 0 ? ( + {badges.length > 0 || presentation.riskTooltip != null ? ( - {presentation.badges.map((badge) => ( + {presentation.riskTooltip != null ? ( + + + + + + ) : null} + {badges.map((badge) => ( ) : null}
- {presentation.prompt.length > 0 ? ( + {hasPromptRow ? (
- - {presentation.prompt} - + {presentation.prompt.length > 0 ? ( + + {presentation.prompt} + + ) : null} + {negativePromptLine != null ? ( + + {negativePromptLine} + + ) : null}
) : null} ); - if (openable && onOpen != null) { + if (openable && onOpen != null && hasResultScreen) { return (
{body}; } -function rowLayoutDataAttrs(entry: ExploreQueueEntry) { +/** The outer row grid. Matches the shell's own attributes, negative prompt line included. */ +function useRowLayoutDataAttrs(entry: ExploreQueueEntry) { const presentation = generationPresentation(entry.generation); + const negativePromptLine = useGenerationNegativePrompt(entry.generation); const previewAsset = pickQueuePreviewAsset(orderedQueueInputAssets(entry)); return { "data-has-asset": previewAsset != null ? "" : undefined, - "data-has-prompt": presentation.prompt.length > 0 ? "" : undefined, + "data-has-prompt": + presentation.prompt.length > 0 || negativePromptLine != null ? "" : undefined, }; } @@ -232,14 +278,13 @@ export function ActiveQueueRow({ onOpen, listItemMotion, }: ActiveQueueRowProps) { + const layoutAttrs = useRowLayoutDataAttrs(entry); const presentation = generationPresentation(entry.generation); const progress = entry.progress; const progressLabel = progress != null ? formatActiveQueueProgress(progress) : null; - const progressDetail = - progress != null - ? formatActiveQueueProgressDetail(progress) - : "Waiting for progress…"; + const apiStatusLabel = activeQueueTitleStatus(entry.api_status); + const progressDetail = activeQueueRowDetail(progress, entry.api_status); const titleProgressSuffix = isCancelling ? ( {`\u00A0(Cancelling…)`} - ) : progressLabel != null ? ( + ) : progressLabel != null || apiStatusLabel != null ? ( - {`\u00A0(${progressLabel})`} + {`\u00A0(${progressLabel ?? apiStatusLabel})`} ) : null; @@ -268,7 +313,7 @@ export function ActiveQueueRow({ >
@@ -281,28 +326,30 @@ export function ActiveQueueRow({ onOpen={onOpen} />
- -
{isCancelling ? ( @@ -311,6 +358,8 @@ export function ActiveQueueRow({ {progressDetail} — {progressLabel} complete + ) : apiStatusLabel != null ? ( + {progressDetail} ) : null} ); @@ -337,13 +386,14 @@ export function FinishedQueueRow({ onRemove, listItemMotion, }: FinishedQueueRowProps) { + const layoutAttrs = useRowLayoutDataAttrs(entry); const presentation = generationPresentation(entry.generation); return (
@@ -485,11 +536,12 @@ export function GenerationQueueDragPreview({ mediaUrlForAsset: (asset: ExploreAsset) => string | null; thumbUrlForAsset: (asset: ExploreAsset) => string | null; }) { + const layoutAttrs = useRowLayoutDataAttrs(entry); return (
diff --git a/frontend/ltx-io/components/GenerationQueue/generationQueuePanelModel.ts b/frontend/ltx-io/components/GenerationQueue/generationQueuePanelModel.ts index 130e6fdf2..bd15b7ede 100644 --- a/frontend/ltx-io/components/GenerationQueue/generationQueuePanelModel.ts +++ b/frontend/ltx-io/components/GenerationQueue/generationQueuePanelModel.ts @@ -1,11 +1,18 @@ +import { CUSTOM_LORA_HOME_FEATURE } from "../../../lib/custom-lora.ts"; import type { ExploreAsset } from "../../../lib/explore-contract.ts"; +import { + formatRemainingTime, + formatShortRemainingTime, +} from "../../../lib/duration-format.ts"; import { MAX_IN_FLIGHT_PROGRESS_PERCENT } from "../../../lib/generation-display-progress.ts"; +import { customLoraRunPath } from "../../../paths.ts"; import type { ExploreQueueEntry, ReorderGenerationQueueRequest, } from "../../hooks/generationQueryKeys.ts"; import { generationPresentation } from "../../lib/generationPresentation.ts"; import { ApiResultError } from "../../lib/unwrapApiResult.ts"; +import { customLoraIdOfGeneration } from "../../screens/Feature/definitions/customLora.ts"; /** Input assets in spec order, then any remaining `input_assets` from the API. */ export function orderedQueueInputAssets( @@ -38,23 +45,56 @@ export type QueueEntryLike = { export function getQueuePanelState( snapshot: { - active: T | null; + active: readonly T[]; queued: readonly T[]; }, options?: { isReordering?: boolean; isCancelPending?: boolean }, ) { const cancelRequestPending = options?.isCancelPending === true; return { - activeIsFixed: snapshot.active != null, - activeCancelDisabled: - snapshot.active?.generation.status === "cancelling" || - cancelRequestPending, + activeIsFixed: snapshot.active.length > 0, queuedCancelDisabled: cancelRequestPending, sortableIds: snapshot.queued.map((entry) => entry.generation.id), sortingDisabled: options?.isReordering === true, }; } +/** A running row cannot be cancelled twice, and not while another cancel request is pending. */ +export function isActiveCancelDisabled( + entry: QueueEntryLike, + cancelRequestPending: boolean, +): boolean { + return entry.generation.status === "cancelling" || cancelRequestPending; +} + +/** The lane label for a row that runs outside the local GPU. Null for a local row. */ +export function queueLaneLabel(lane: string | null | undefined): string | null { + if (lane == null || lane === "local") return null; + return lane; +} + +/** The row badges plus the lane label. The label is not repeated when a badge already shows it. */ +export function queueRowBadges( + badges: readonly string[], + lane: string | null | undefined, +): string[] { + const laneLabel = queueLaneLabel(lane); + if (laneLabel == null || badges.includes(laneLabel)) return [...badges]; + return [...badges, laneLabel]; +} + +/** + * What a provider job reports while it runs. Null for a local job, which shows + * its own progress. + */ +export function activeQueueTitleStatus( + apiStatus: "pending" | "processing" | null | undefined, +): string | null { + if (apiStatus === "pending") return "Waiting"; + if (apiStatus === "processing") return "Generating"; + return null; +} + export function queuedEntryForActiveDrag( queued: readonly T[], activeId: string | null, @@ -103,6 +143,7 @@ export type QueueProgressSnapshot = { progress: number; currentStep: number | null; totalSteps: number | null; + remainingSeconds?: number | null; }; export function activeQueueProgressPercent(progress: QueueProgressSnapshot): number { @@ -144,7 +185,7 @@ function reportedDenoisePercent(progress: QueueProgressSnapshot): number | undef export function progressPercentByGenerationId( snapshot: | { - active: QueueEntryWithProgress | null; + active: readonly QueueEntryWithProgress[]; queued: readonly QueueEntryWithProgress[]; } | null @@ -152,10 +193,7 @@ export function progressPercentByGenerationId( ): Map { const map = new Map(); if (snapshot == null) return map; - const entries = [snapshot.active, ...snapshot.queued].filter( - (entry): entry is QueueEntryWithProgress => entry != null, - ); - for (const entry of entries) { + for (const entry of [...snapshot.active, ...snapshot.queued]) { if (entry.progress == null) continue; const percent = reportedDenoisePercent(entry.progress); if (percent == null) continue; @@ -164,30 +202,78 @@ export function progressPercentByGenerationId( return map; } +/** Live remaining seconds for each running queue row that reported an ETA. */ +export function remainingSecondsByGenerationId( + snapshot: + | { + active: readonly QueueEntryWithProgress[]; + queued: readonly QueueEntryWithProgress[]; + } + | null + | undefined, +): Map { + const map = new Map(); + if (snapshot == null) return map; + for (const entry of [...snapshot.active, ...snapshot.queued]) { + const rem = entry.progress?.remainingSeconds; + if (rem == null || rem < 0) continue; + map.set(entry.generation.id, rem); + } + return map; +} + /** * Label for the progress control. It follows the result placeholder: null until a denoise * step has run, so the queue row and the placeholder never show different percents. */ export function formatActiveQueueProgress(progress: QueueProgressSnapshot): string | null { const percent = reportedDenoisePercent(progress); - return percent == null ? null : `${percent}%`; + const remaining = formatShortRemainingTime(progress.remainingSeconds); + if (percent == null) return remaining; + return remaining == null ? `${percent}%` : `${percent}% · ${remaining}`; } export function resultLocationForFeature( feature: string, generationId: string, features: readonly { id: string; path: string }[], + spec?: unknown, ): { pathname: string; search: string } | null { const match = features.find((item) => item.id === feature); if (match == null) return null; + let pathname = match.path; + if (feature === CUSTOM_LORA_HOME_FEATURE.id) { + const customLoraId = customLoraIdOfGeneration(spec); + if (customLoraId == null) return null; + pathname = customLoraRunPath(customLoraId); + } return { - pathname: match.path, + pathname, search: `?result=${encodeURIComponent(generationId)}`, }; } export function formatActiveQueueProgressDetail(progress: QueueProgressSnapshot): string { const percent = reportedDenoisePercent(progress); - if (percent == null) return "Waiting for progress…"; - return `Step ${progress.currentStep} of ${progress.totalSteps} (${percent}%)`; + const remaining = formatRemainingTime(progress.remainingSeconds); + if (percent == null) { + return remaining ?? "Waiting for progress…"; + } + const stepText = `Step ${progress.currentStep} of ${progress.totalSteps} (${percent}%)`; + return remaining == null ? stepText : `${stepText} — ${remaining}`; +} + +/** + * The text a screen reader gets for a running row. A provider job reports a phase with no step + * count, so its provider status is the detail. Without either, the job has not reported yet. + */ +export function activeQueueRowDetail( + progress: QueueProgressSnapshot | null | undefined, + apiStatus: Parameters[0], +): string { + if (progress != null && formatActiveQueueProgress(progress) != null) { + return formatActiveQueueProgressDetail(progress); + } + const statusLabel = activeQueueTitleStatus(apiStatus); + return statusLabel != null ? `${statusLabel}…` : "Waiting for progress…"; } diff --git a/frontend/ltx-io/components/ImageGenerator/ImageGenerator.module.scss b/frontend/ltx-io/components/ImageGenerator/ImageGenerator.module.scss new file mode 100644 index 000000000..03cda1b4f --- /dev/null +++ b/frontend/ltx-io/components/ImageGenerator/ImageGenerator.module.scss @@ -0,0 +1,157 @@ +@import "@ds/styles/themes/mixins.module.scss"; + +// One column of controls. With an image, the preview joins in a second column. The buttons sit in a +// row below both columns. On a narrow screen the columns stack. The card width follows the screen +// width, because the modal caps its own width at 95vw minus the close button room. +.container { + display: grid; + grid-template-columns: minmax(0, 1fr); + gap: var(--spacing-lg); + width: min(560px, calc(95vw - 70px)); + // Room for the corner close button. + padding: calc(var(--spacing-lg) + 28px) var(--spacing-lg) var(--spacing-lg); +} + +.withPreview { + @media (min-width: 761px) { + grid-template-columns: repeat(2, minmax(0, 1fr)); + width: min(1040px, calc(95vw - 70px)); + + .actions { + grid-column: 1 / -1; + } + } +} + +.controls { + display: flex; + flex-direction: column; + gap: var(--spacing-lg); + min-width: 0; +} + +.field { + display: flex; + flex-direction: column; + align-items: flex-start; + gap: var(--spacing-sm); + min-width: 0; +} + +.label { + color: var(--semantic-fg-secondary); +} + +.textarea { + @include text_style_body_lg; + + display: block; + width: 100%; + min-width: 0; + min-height: 160px; + border: 1px solid transparent; + border-radius: var(--radius-md); + background: var(--semantic-bg-primary); + color: var(--semantic-fg-primary); + outline: none; + padding: var(--spacing-md); + resize: vertical; + + &:hover, + &:focus { + border-color: var(--semantic-bg-separator-primary); + } +} + +.enhanceRow { + display: flex; + flex-direction: column; + align-items: flex-start; + gap: var(--spacing-sm); +} + +.settings { + display: flex; + flex-wrap: wrap; + gap: var(--spacing-lg); +} + +// A labeled picker. The two pickers share a row and wrap on a narrow screen. +.sizeField { + display: flex; + flex: 1 1 120px; + flex-direction: column; + gap: var(--spacing-sm); + min-width: 0; +} + +.actions { + display: flex; + flex-wrap: wrap; + justify-content: flex-end; + gap: var(--spacing-sm); +} + +.status { + color: var(--semantic-fg-tertiary); +} + +.error { + @include text_style_body_md; + + color: var(--semantic-fg-danger-primary-enabled); +} + +// The frame has the shape of the chosen aspect ratio. A tall shape stops at the height limit. +.previewFrame { + --preview-max-height: min(70vh, 560px); + + position: relative; + display: flex; + align-items: center; + justify-content: center; + align-self: flex-start; + width: min(100%, calc(var(--preview-max-height) * var(--image-ratio))); + aspect-ratio: var(--image-ratio); + overflow: hidden; + border-radius: var(--radius-md); + background: var(--semantic-bg-tertiary); +} + +// The provider switch is a little wider than the pickers, so both labels fit. +.providerField { + flex: 1.3 1 160px; +} + +// The provider switch has the height and the width of the pickers beside it. +.sizeField .providerSegment { + --track-height: 40px; + --item-pad-y: 0; + --item-pad-x: var(--spacing-sm); + --label-size: 14px; + --label-line: 20px; +} + +.previewEmpty { + color: var(--semantic-fg-tertiary); +} + +// The progress sits over the frame, and over the last image while the next one is made. +.previewStatus { + position: absolute; + inset: 0; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: var(--spacing-sm); + background: color-mix(in srgb, var(--semantic-bg-primary) 70%, transparent); + color: var(--semantic-fg-secondary); +} + +.preview { + display: block; + width: 100%; + height: 100%; + object-fit: contain; +} diff --git a/frontend/ltx-io/components/ImageGenerator/ImageGenerator.tsx b/frontend/ltx-io/components/ImageGenerator/ImageGenerator.tsx new file mode 100644 index 000000000..9f9a4980b --- /dev/null +++ b/frontend/ltx-io/components/ImageGenerator/ImageGenerator.tsx @@ -0,0 +1,296 @@ +import { ActivityCircular } from "@ds/ActivityCircular/ActivityCircular"; +import { Button } from "@ds/Button/Button"; +import { Text } from "@ds/Text/Text"; +import { clsx } from "clsx"; +import { type CSSProperties, useEffect, useState } from "react"; + +import { EnhanceSplitButton } from "@/components/EnhanceSplitButton"; +import { enhanceActionLabel } from "@/lib/enhance-ui-copy"; +import type { ExploreAsset } from "@/lib/explore-contract"; +import { + DEFAULT_IMAGE_RESOLUTION, + type ImageResolution, +} from "@/lib/genspace-image-resolution"; +import { + type PromptHistoryEntry, + resolvePromptProvenance, +} from "@/lib/prompt-provenance"; + +import { + GENERATION_CANCEL_CONFIRMATION, + useCancelGeneration, +} from "../../hooks/useCancelGeneration"; +import { useConfirmDeleteAction } from "../../hooks/useConfirmDeleteAction"; +import { useImageEnhance } from "../../hooks/useImageEnhance"; +import { isInFlightGeneration } from "../../lib/resultsFeedModel"; +import { useExploreRuntime } from "../../runtime/ExploreRuntime"; + +import styles from "./ImageGenerator.module.scss"; +import { ImageProviderPicker } from "./ImageProviderPicker"; +import { ImageSizeFields } from "./ImageSizeFields"; +import { imageFailureMessage } from "./imageFailureMessage"; +import { + type ImageAspect, + aspectRatioNumber, + buildTextToImageRequest, + fittingImageResolution, + imageSizeForAspect, +} from "./imageGeneratorRequest"; +import { imageCreateErrorMessage } from "./imageProviderAvailability"; +import { useImageProviderChoice } from "./useImageProviderChoice"; +import { useOwnedGeneration } from "./useOwnedGeneration"; + +export function ImageGenerator({ + initialPrompt = "", + initialAspect = "16:9", + onUseImage, + useImageLabel = "Use image", + onCloseModal, + setShouldPreventDismiss, +}: { + initialPrompt?: string; + initialAspect?: ImageAspect; + /** When set, a finished image shows this action. The caller decides where the image goes. */ + onUseImage?: (asset: ExploreAsset) => void; + useImageLabel?: string; + onCloseModal?: () => void; + setShouldPreventDismiss?: (fn: (() => boolean) | undefined) => void; +}) { + const runtime = useExploreRuntime(); + const providers = useImageProviderChoice(); + const { + createError, + generation, + generationId, + hasStarted, + inFlight, + output, + start, + } = useOwnedGeneration(); + const cancel = useCancelGeneration(); + const confirmDelete = useConfirmDeleteAction(); + const isCancelling = + cancel.isPending || + generation?.status === "cancelling" || + (generation !== undefined && + cancel.isSuccess && + cancel.variables === generation.id); + + useEffect(() => { + if (!setShouldPreventDismiss || !onCloseModal) return; + setShouldPreventDismiss(() => { + if (!inFlight || isCancelling) return false; + confirmDelete(GENERATION_CANCEL_CONFIRMATION, onCloseModal); + return true; + }); + return () => setShouldPreventDismiss(undefined); + }, [confirmDelete, inFlight, isCancelling, onCloseModal, setShouldPreventDismiss]); + + const [prompt, setPrompt] = useState(initialPrompt); + const [history, setHistory] = useState<{ + entries: PromptHistoryEntry[]; + index: number; + }>({ + entries: [], + index: -1, + }); + const [aspect, setAspect] = useState(initialAspect); + const [resolutionChoice, setResolutionChoice] = useState( + DEFAULT_IMAGE_RESOLUTION, + ); + // A shape too wide for the choice shows a smaller resolution. The choice returns on a shape that fits. + const resolution = fittingImageResolution(aspect, resolutionChoice); + const enhance = useImageEnhance({ + prompt, + promptHistory: history.entries, + historyIndex: history.index, + onPromptHistoryChange: (entries, index) => { + setHistory({ entries, index }); + setPrompt(entries[index]?.text ?? prompt); + }, + disabled: inFlight, + }); + + const { provider, blockedReason } = providers; + + // As in FeatureFormScreen: Generate waits for a manual Enhance, which replaces the prompt. + const canGenerate = + prompt.trim().length > 0 && + provider !== null && + blockedReason === null && + !inFlight && + !enhance.isEnhancing; + const previewUrl = output ? runtime.mediaUrlForAsset(output) : null; + // The preview column opens on the first Generate and stays, so the card does not change size. + const showPreview = hasStarted; + const failed = createError !== null || generation?.status === "failed"; + const showCancel = generation !== undefined && isInFlightGeneration(generation); + + const generate = () => { + if (!canGenerate || provider === null) return; + start( + buildTextToImageRequest({ + prompt, + provenance: resolvePromptProvenance(prompt, history.entries, history.index), + size: imageSizeForAspect(aspect, resolution), + provider, + }), + ); + }; + + return ( +
+
+
+ + Prompt + +