diff --git a/.cursor/rules/ltx2-patch-reverify.mdc b/.cursor/rules/ltx2-patch-reverify.mdc index f1ab70d7b..6aea51425 100644 --- a/.cursor/rules/ltx2-patch-reverify.mdc +++ b/.cursor/rules/ltx2-patch-reverify.mdc @@ -4,15 +4,15 @@ globs: backend/pyproject.toml alwaysApply: false --- -# LTX-2 bump → re-check `services.patches` +# LTX-2 bump → re-check CUDA patches in `inference.apply_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 swap of an upstream symbol. +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/inference/patches/` in `backend/inference/apply_patches.py` as suspect, plus Darwin leftovers imported from `backend/services/patches/` in `backend/ltx2_server.py`, and 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. For each patch: -1. Read the module's "Remove once ..." docstring. If upstream now includes the fix, delete the patch, its `ltx2_server.py` import, and its tests. +1. Read the module's "Remove once ..." docstring. If upstream now includes the fix, delete the patch, its `apply_patches.py` (CUDA) or `ltx2_server.py` (Darwin) import, and its tests. 2. Cautionary example: `diffvae_mps_tiling_budget` asserted `DiffusionVideoDecoder.recommended_tiling_config`, which 1.3.0 removed. Keeping it made the backend unable to boot. `safetensors_metadata_fix` is the opposite kind of patch (Windows 1455 / never-`safe_open` the 46GB distilled-1.1 checkpoint) — keep until that contract is upstream. 3. Otherwise diff the upstream function against the replacement and keep the contract identical. Re-earn; do not copy blindly. 4. Run that patch's tests (`backend/tests/test_.py`) plus the patch import-smoke test. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f3ef1f9fe..f54f13227 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -51,7 +51,7 @@ jobs: - name: Install Python dev dependencies working-directory: backend - run: uv sync --frozen --extra dev + run: uv sync --frozen --extra desktop --extra dev - name: Pyright type check working-directory: backend @@ -96,7 +96,7 @@ jobs: - &install-backend name: Install dependencies - run: uv sync --frozen --extra test --extra dev + run: uv sync --frozen --extra desktop --extra test --extra dev # 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. diff --git a/AGENTS.md b/AGENTS.md index 30fb658bf..e4b3b0dfc 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -82,7 +82,7 @@ Key patterns: - Python 3.13+ (per `.python-version`), managed with `uv` - Pyright strict mode (`backend/pyrightconfig.json`) - Dependencies in `backend/pyproject.toml` -- Bumping `ltx-core` / `ltx-pipelines`: re-verify every `services.patches` import in `backend/ltx2_server.py` (private upstream monkey-patches). Drop a patch only if upstream now includes the fix. +- Bumping `ltx-core` / `ltx-pipelines`: re-verify every CUDA patch in `backend/inference/patches/` (imported from `backend/inference/apply_patches.py`), plus the Darwin leftovers in `backend/services/patches/` (imported from `backend/ltx2_server.py`). These are private upstream monkey-patches. Drop a patch only if upstream now includes the fix. ## Key File Locations diff --git a/backend/api_model_specs.py b/backend/api_model_specs.py index 65f7652bd..c4994a0fc 100644 --- a/backend/api_model_specs.py +++ b/backend/api_model_specs.py @@ -29,9 +29,9 @@ WarnedFastAspectCell, WarnedFastCell, ) -from frame_math import compute_num_frames +from inference.frame_math import compute_num_frames from keyframe_request import validate_keyframe_inputs -from runtime_config.fast_chunking import job_window_count +from inference.fast_chunking import job_window_count from runtime_config.ltx_capabilities import ( CanvasMode, LtxOfferingCapabilities, diff --git a/backend/api_types.py b/backend/api_types.py index efa3ab015..2204cd846 100644 --- a/backend/api_types.py +++ b/backend/api_types.py @@ -3,7 +3,7 @@ from __future__ import annotations import re -from typing import Annotated, Literal, NamedTuple, Self, TypeAlias, cast, get_args +from typing import Annotated, Literal, Self, TypeAlias, cast, get_args from pydantic import ( BaseModel, @@ -51,7 +51,7 @@ LoraEntry as LoraEntry, ) from assistant_limits import ASSISTANT_LIMITS -from frame_math import compute_num_frames +from inference.frame_math import compute_num_frames from runtime_config.eta import EtaBasis, EtaFeature from runtime_config.reject_reasons import ( BudgetMode, @@ -64,7 +64,7 @@ WarnedCellTier, ) from runtime_config.ic_lora_stage_mode import IcLoraStageMode, ic_lora_stage_mode -from runtime_config.ic_lora_tiling import ( +from inference.ic_lora_tiling import ( MAX_TILE_OVERLAP, MIN_CARRY_FRAMES, MIN_TILE_OVERLAP, @@ -72,13 +72,23 @@ IcLoraTileSize, IcLoraTiling, ) -from runtime_config.nag_limits import ( +from inference.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, ) +from inference.types import ( + DEFAULT_EDIT_CONTEXT_MODE, + EditContextMode, + ExtendMode, + ImageConditioningInput as ImageConditioningInput, + LTXLocalModelId, + REFERENCE_STILL_FRAME_IDX as REFERENCE_STILL_FRAME_IDX, + RetakeMode, +) + NonEmptyPrompt = Annotated[str, StringConstraints(strip_whitespace=True, min_length=1)] LocalAssistantModel = Literal["qwen3.5:9b"] @@ -140,24 +150,10 @@ class AssistantModelsResponse(BaseModel): "gemma-4-e2b-it", "z-image-turbo", ] -LTXLocalModelId = Literal[ - "ltx-2.5-22b-distilled", - "ltx-2.3-22b-distilled-1.1", - "ltx-2.3-22b-distilled", -] # T2V/I2V/A2V/LoRA create-body `params.model`. Not a GenSpace pipeline (`fast`) # and not a checkpoint id. Future API rows (`ltx-2.5-pro`, …) join this union. OfferingId = Literal["ltx-2.3-fast", "ltx-2.5-fast"] - -class ImageConditioningInput(NamedTuple): - """Image conditioning triplet used by all video pipelines.""" - - path: str - frame_idx: int - strength: float - - JsonObject: TypeAlias = dict[str, object] VideoCameraMotion = Literal[ "none", @@ -253,9 +249,6 @@ class FeatureFlags(BaseModel): # 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): @@ -274,7 +267,6 @@ class FeatureFlagsPatch(BaseModel): highResVideoToVideo: bool | None = None createWithAi: bool | None = None showGenerationNegativePrompt: bool | None = None - keyframes: bool | None = None class GenerationProgressResponse(BaseModel): @@ -1068,10 +1060,6 @@ def _validate_input_image_mode(self) -> "SuggestGapPromptRequest": return self -RetakeMode: TypeAlias = Literal[ - "replace_audio_and_video", "replace_video", "replace_audio" -] - # ltxv-api /v2/retake and /v2/extend accept ltx-2-pro / ltx-2-3-pro. Desktop maps # those to pipeline "pro" — narrower than LTXVideoGenPipeline on purpose. RetakeExtendModel: TypeAlias = Literal["pro"] @@ -1101,9 +1089,6 @@ class RetakeRequest(BaseModel): model: RetakeExtendModel = "pro" -ExtendMode: TypeAlias = Literal["start", "end"] - - class ExtendRequest(BaseModel): model_config = ConfigDict(strict=True) @@ -1143,12 +1128,6 @@ class IcLoraExtractRequest(BaseModel): frame_time: float = 0 -# The frame index of a reference still (the look still of Layout To Render). Upstream -# rejects a negative index, so the pipeline keeps the still apart from the clip frames. -# Only a catalog entry can pin it (``reference_image_frame``). A request cannot send it. -REFERENCE_STILL_FRAME_IDX = -1 - - class IcLoraImageInput(BaseModel): model_config = ConfigDict(strict=True) @@ -2673,6 +2652,9 @@ class RetakeParams(NagParams): startTime: float = Field(ge=0, allow_inf_nan=False) duration: float = Field(ge=2, allow_inf_nan=False) mode: RetakeMode = "replace_audio_and_video" + # "short" keeps about 2 s of context on each side of the selection instead of filling the + # window to the cap (see continuation_context_frames). + contextMode: EditContextMode = DEFAULT_EDIT_CONTEXT_MODE resolution: TargetResolution | None = None seed: int | None = None # Accepted so the shared Home form can submit provenance like every other @@ -2717,6 +2699,9 @@ class ExtendParams(NagParams): model: OfferingId duration: float = Field(ge=2, le=20, allow_inf_nan=False) mode: ExtendMode = "end" + # "short" conditions on only the last frames of the clip (see + # CONTINUATION_CONTEXT_FRAMES) instead of the whole encode window. + contextMode: EditContextMode = DEFAULT_EDIT_CONTEXT_MODE resolution: TargetResolution | None = None seed: int | None = None # Accepted so the shared Home form can submit provenance like every other @@ -2771,8 +2756,9 @@ class EditPreflightRequest(BaseModel): presets, retake minimum) so every candidate has an exact resolution-level verdict; callers add the durations they display (extend presets, retake current selection) for exact per-cell messages. ``startTime`` only affects - retake windowing, ``mode`` only extend stitching; both default so each - feature sends what it needs. + retake windowing, ``mode`` only extend stitching and ``contextMode`` only how + much of the clip an extend keeps as context (which sets the window it is + priced at); all default so each feature sends what it needs. """ model_config = ConfigDict(strict=True, extra="forbid") @@ -2781,6 +2767,7 @@ class EditPreflightRequest(BaseModel): assetId: str = Field(min_length=1) startTime: float = Field(default=0, ge=0, allow_inf_nan=False) mode: ExtendMode = "end" + contextMode: EditContextMode = DEFAULT_EDIT_CONTEXT_MODE candidates: list[EditPreflightCandidate] = Field(min_length=1, max_length=8) durations: list[float] = Field(min_length=1, max_length=32) diff --git a/backend/app_handler.py b/backend/app_handler.py index 8c5b723ff..2568f7b56 100644 --- a/backend/app_handler.py +++ b/backend/app_handler.py @@ -47,21 +47,21 @@ from handlers.base import resolve_models_dir from handlers.assistant_models_handler import AssistantModelsHandler from runtime_config.runtime_config import RuntimeConfig +from inference.a2v_pipeline.a2v_pipeline import A2VPipeline +from inference.fast_video_pipeline.fast_video_pipeline import FastVideoPipeline +from inference.ic_lora_pipeline.ic_lora_pipeline import IcLoraPipeline +from inference.retake_pipeline.retake_pipeline import RetakePipeline from services.interfaces import ( - A2VPipeline, DepthProcessorPipeline, - FastVideoPipeline, ZitAPIClient, ImageGenerationPipeline, GpuCleaner, GpuInfo, HTTPClient, - IcLoraPipeline, LTXAPIClient, ModelDownloader, PoseProcessorPipeline, PromptEnhancerPipeline, - RetakePipeline, TaskRunner, TextEncoder, VideoProcessor, @@ -553,9 +553,6 @@ def _queued_enhancement_policy(self, generation: GenerationRecord) -> QueuedEnha def _high_res_video_to_video_enabled(self) -> bool: return self.feature_flags.get_flags().highResVideoToVideo - 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( @@ -618,7 +615,6 @@ def _bind_store(self, store: Store) -> None: 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, ) @@ -669,18 +665,18 @@ class ServiceBundle: def build_default_service_bundle(config: RuntimeConfig) -> ServiceBundle: """Build real runtime services with lazy heavy imports isolated from tests.""" - from services.fast_video_pipeline.ltx_fast_video_pipeline import LTXFastVideoPipeline + from inference.fast_video_pipeline.ltx_fast_video_pipeline import LTXFastVideoPipeline from services.zit_api_client.zit_api_client_impl import ZitAPIClientImpl from services.gpu_cleaner.torch_cleaner import TorchCleaner from services.gpu_info.gpu_info_impl import GpuInfoImpl from services.http_client.http_client_impl import HTTPClientImpl - from services.a2v_pipeline.ltx_a2v_pipeline import LTXa2vPipeline + from inference.a2v_pipeline.ltx_a2v_pipeline import LTXa2vPipeline from services.depth_processor_pipeline.midas_dpt_pipeline import MidasDPTPipeline - from services.ic_lora_pipeline.ltx_ic_lora_pipeline import LTXIcLoraPipeline + from inference.ic_lora_pipeline.ltx_ic_lora_pipeline import LTXIcLoraPipeline from services.image_generation_pipeline.zit_image_generation_pipeline import ZitImageGenerationPipeline from services.ltx_api_client.ltx_api_client_impl import LTXAPIClientImpl from services.model_downloader.hugging_face_downloader import HuggingFaceDownloader - from services.retake_pipeline.ltx_retake_pipeline import LTXRetakePipeline + from inference.retake_pipeline.ltx_retake_pipeline import LTXRetakePipeline 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 diff --git a/backend/handlers/assistant_handler.py b/backend/handlers/assistant_handler.py index 76fc94fe6..85065bcb2 100644 --- a/backend/handlers/assistant_handler.py +++ b/backend/handlers/assistant_handler.py @@ -86,7 +86,15 @@ - For a style no recipe covers, make it concrete: "low quality retro" becomes film grain, soft focus and faded colour. Keep every subject, setting and wording the user specified. - For image-to-video, describe motion consistent with the attached image. For - extensions and retakes, describe how the clip continues. + extensions and retakes, describe how the clip continues, and always write that + prompt. When one changes or adds speech, put the exact words in quotes in the prompt: + the video model says only what the prompt quotes. +- Extensions and retakes use the clip as context: contextMode "long" (the default) + keeps as much of it as fits, "short" keeps about 2 seconds (next to the new part + for an extension, on each side of the selection for a retake). Short is faster, but + the new part may drift from the rest of the clip. Leave contextMode out unless the + user asks for short, less context or a faster run, and say so in the reply when you + set it. - When the request refers to something in an attached image, describe its visible details in the prompt: colour, material, pattern and shape. - Style and motion recipes add their own trigger phrases; describe the scene only. diff --git a/backend/handlers/assistant_params.py b/backend/handlers/assistant_params.py index 6642493ec..8cc4bd872 100644 --- a/backend/handlers/assistant_params.py +++ b/backend/handlers/assistant_params.py @@ -9,6 +9,19 @@ LTXLocalA2VResolution, LTXQueuedAspectRatio, LTXVideoGenAspectRatio, LTXVideoGenFps, NonEmptyPrompt, OfferingId, PromptProvenance, RETAKE_MAX_DURATION_SECONDS, RetakeMode, TargetResolution, VideoCameraMotion, ) +from inference.types import DEFAULT_EDIT_CONTEXT_MODE, EditContextMode + +# Small models skip an optional field, and the video model says only what the prompt quotes. +EDIT_PROMPT_DESCRIPTION = ( + "Write it: how the new part looks and sounds, in one paragraph. " + "When the user says what someone should say, put those exact words in quotes here" +) + +# Long is the default, so a request that does not name a context mode never sets one. +CONTEXT_MODE_DESCRIPTION = ( + '"long" (default) keeps as much of the clip as fits as context. "short" keeps about 2 seconds of it: ' + "faster, but the result may drift from the rest of the clip. Set short only when the user asks for it" +) # The model repeats its tool schema as capabilities, so offer only what local models run. # list_video_models still decides which combinations a model supports. @@ -67,13 +80,14 @@ class AudioParams(AssistantParams): class ExtensionParams(AssistantParams): - prompt: str = "" + prompt: str = Field(default="", description=EDIT_PROMPT_DESCRIPTION) 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"') total_seconds: float | None = Field(default=None, gt=0, allow_inf_nan=False, description='"Extend it to 10 seconds": the final length') mode: ExtendMode = "end" + contextMode: EditContextMode = Field(default=DEFAULT_EDIT_CONTEXT_MODE, description=CONTEXT_MODE_DESCRIPTION) resolution: TargetResolution | None = Field(default=None, description="Omit to keep the source size; set only when the user asks") @@ -105,12 +119,13 @@ class IngredientsParams(AssistantParams): class ReplacementParams(AssistantParams): - prompt: str = "" + prompt: str = Field(default="", description=EDIT_PROMPT_DESCRIPTION) 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) mode: RetakeMode = "replace_audio_and_video" + contextMode: EditContextMode = Field(default=DEFAULT_EDIT_CONTEXT_MODE, description=CONTEXT_MODE_DESCRIPTION) # No resolution: a retake keeps the source's frame size, and small models fill it in from earlier clips. diff --git a/backend/handlers/assistant_tools.py b/backend/handlers/assistant_tools.py index 41c7c113e..1d91c6338 100644 --- a/backend/handlers/assistant_tools.py +++ b/backend/handlers/assistant_tools.py @@ -412,6 +412,22 @@ def _recipe_guard(deps: AssistantDeps, *, video_only: bool = False) -> None: ) +_QUOTED_WORDS = re.compile(r'["“]([^"”]{2,})["”]') + + +def _prompt_guard(deps: AssistantDeps, prompt: str) -> None: + # Small models leave an optional prompt empty, and the video model says only what the prompt quotes. + # Only when the user's message quotes words to be said, so every other empty prompt goes through as before. + # Once per request, so a job that needs no prompt goes through unchanged on the next call. + if prompt.strip() or deps.run.prompt_nudged or (quoted := _QUOTED_WORDS.search(deps.run.request.text)) is None: + return + deps.run.prompt_nudged = True + raise ModelRetry( + f'The user gave words to be said: "{quoted.group(1)}". The prompt is empty, so the new part will not say them. ' + "Write the prompt, with those exact words in quotes. If this job needs no prompt, call this tool again unchanged." + ) + + def _recipe_queued(deps: AssistantDeps) -> None: # In a mixed request ("one Cozy Felt clip and one plain clip") the recipe is already handled. deps.run.recipe_nudged = True @@ -900,15 +916,17 @@ def create(request: CreateIcLoraSheetRequest, /, *, generation_id: str, analytic return result.model_copy(update={"note": note}) -@tools.tool(retries=RECIPE_GUARDED_RETRIES) +@tools.tool(retries=RECIPE_GUARDED_RETRIES + 1) def extend_video(ctx: RunContext[AssistantDeps], params: ExtensionParams, job_number: JobNumber, generation_id: str | None = None, video_asset_id: str | None = None) -> AssistantGeneration: """Queue a local video extension; keeps the source size unless the user asks for a resolution, and inherits FPS. Pass exactly one of added_seconds ("add 3 seconds") or total_seconds ("extend it to 10 seconds"). Supply either a succeeded generation_id or an existing video_asset_id. - For chained jobs use the intended source's returned ID. Returns immediately. + For chained jobs use the intended source's returned ID. Set contextMode "short" only + when the user asks for it. Returns immediately. """ _recipe_guard(ctx.deps, video_only=True) + _prompt_guard(ctx.deps, params.prompt) _model(ctx.deps, params.model, "extend") if (params.added_seconds is None) == (params.total_seconds is None): raise ModelRetry("Pass exactly one of added_seconds or total_seconds.") @@ -933,14 +951,16 @@ def extend_video(ctx: RunContext[AssistantDeps], params: ExtensionParams, job_nu return _submit(ctx.deps, job_number, ctx.deps.generations.create_extend, request) -@tools.tool(retries=RECIPE_GUARDED_RETRIES) +@tools.tool(retries=RECIPE_GUARDED_RETRIES + 1) def retake_video(ctx: RunContext[AssistantDeps], params: ReplacementParams, job_number: JobNumber, generation_id: str | None = None, video_asset_id: str | None = None) -> AssistantGeneration: """Replace a time range's audio/video locally. startTime and duration are seconds, at most 10. Supply either a succeeded generation_id or an existing video_asset_id. Preserve - the user's requested mode and time range. Returns immediately. + the user's requested mode and time range. Write the prompt, with any new speech in + quotes. Set contextMode "short" only when the user asks for it. Returns immediately. """ _recipe_guard(ctx.deps, video_only=True) + _prompt_guard(ctx.deps, params.prompt) _model(ctx.deps, params.model, "retake") video = _video_input(ctx.deps, generation_id, video_asset_id) source = _source_seconds(ctx.deps, video) diff --git a/backend/handlers/base.py b/backend/handlers/base.py index fdb418e4e..ed9b91df1 100644 --- a/backend/handlers/base.py +++ b/backend/handlers/base.py @@ -22,7 +22,7 @@ build_local_job_filter, resolve_pass_shape, ) -from services.ltx_pipeline_common import offload_mode_for_prefetch_count +from inference.common import offload_mode_for_prefetch_count from state.app_settings import MAX_GENERATION_SEED, resolved_use_conv_vae from state.app_state_types import AppState diff --git a/backend/handlers/extend_handler.py b/backend/handlers/extend_handler.py index 93b0b4689..d6df4c8b5 100644 --- a/backend/handlers/extend_handler.py +++ b/backend/handlers/extend_handler.py @@ -40,7 +40,7 @@ from runtime_config.ltx_capabilities import local_caps, supports from runtime_config.model_download_specs import resolve_active_ltx_model_id from runtime_config.runtime_config import RuntimeConfig -from services.generation_interrupt import GenerationCancelledError, is_cancel_exception +from inference.interrupt import GenerationCancelledError, is_cancel_exception 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.interfaces import LTXAPIClient diff --git a/backend/handlers/generation_handler.py b/backend/handlers/generation_handler.py index 8b6318dd9..b3c98da3f 100644 --- a/backend/handlers/generation_handler.py +++ b/backend/handlers/generation_handler.py @@ -26,10 +26,11 @@ estimate_envelope_wall_time, remaining_wall_time_s, ) -from services import generation_interrupt -from services.generation_interrupt import GenerationCancelledError +from inference.interrupt import GenerationCancelledError +import inference.interrupt as interrupt from services.generation_queue.control import GenerationSlotWaitAborted -from services.patches import diffusion_stage_cache, mps_conv3d_as_conv2d +from inference.patches import diffusion_stage_cache +from services.patches import mps_conv3d_as_conv2d from state.app_settings import resolved_use_conv_vae from state.app_state_types import ( ApiGeneration, @@ -68,12 +69,12 @@ def __init__( self._calibration = calibration self._generation_slot = Condition(self._lock) self._queue_yields = 0 - from services.denoising_progress import configure_sink + from inference.progress import configure_sink configure_sink(self._on_denoise_step) def _on_denoise_step(self, current: int, total: int) -> None: - from services.denoising_progress import inference_percent + from inference.progress import inference_percent self.update_progress("inference", inference_percent(current, total), current, total) @@ -120,7 +121,7 @@ def try_reserve_generation_start(self, *, persistent: bool = False) -> bool: def release_generation_start_reservation(self) -> None: self.state.generation_in_flight = False self.state.generation_starting_since = None - generation_interrupt.clear() + interrupt.clear() self._generation_slot.notify_all() @contextmanager @@ -229,7 +230,7 @@ def start_generation( raise RuntimeError("Generation already in progress") if self.state.gpu_slot is None: raise RuntimeError("No active GPU pipeline") - if generation_interrupt.is_requested(): + if interrupt.is_requested(): # Stop during reservation (enhance / pipeline load). Do not clear the Event # or launch Running — that would let this call proceed and a second Start # overlap on the GPU. @@ -253,8 +254,8 @@ def start_generation( 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 + interrupt.clear() + from inference.progress import configure_sink configure_sink(self._on_denoise_step) @@ -296,7 +297,7 @@ def start_generation( def start_api_generation(self, generation_id: str) -> None: if self.is_generation_running(): raise RuntimeError("Generation already in progress") - if generation_interrupt.is_requested(): + if interrupt.is_requested(): self.state.generation_starting_since = None self.state.active_generation = ApiGeneration( state=GenerationCancelled(id=generation_id) @@ -308,7 +309,7 @@ def start_api_generation(self, generation_id: str) -> None: # local transformer itself, but evicting here still releases VRAM held by # a previous local generation's cached build. diffusion_stage_cache.evict() - generation_interrupt.clear() + interrupt.clear() self.state.active_generation = ApiGeneration( state=GenerationRunning( @@ -411,7 +412,7 @@ def raise_if_cancelled(self) -> None: Stop). The interrupt Event is cleared on release; it is the signal for this reservation. """ - generation_interrupt.raise_if_requested() + interrupt.raise_if_requested() @with_state_lock def update_progress( @@ -453,14 +454,14 @@ def _close_run_watch( def cancel_generation(self) -> CancelResponse: running_generation = self._running_generation() if running_generation is not None: - generation_interrupt.request() + 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) if self.state.generation_in_flight: - generation_interrupt.request() + interrupt.request() # After start_generation(), starting_since is None and active_generation is this # job. During reservation it still holds the previous job's sticky terminal id. if self.state.generation_starting_since is None: diff --git a/backend/handlers/ic_lora_handler.py b/backend/handlers/ic_lora_handler.py index 16d0a5aaf..25746e875 100644 --- a/backend/handlers/ic_lora_handler.py +++ b/backend/handlers/ic_lora_handler.py @@ -59,12 +59,12 @@ TargetResolution, ) from _routes._errors import HTTPError -from frame_math import compute_num_frames, snap_to_frame_grid, snap_up_to_frame_grid +from inference.frame_math import compute_num_frames, snap_to_frame_grid, snap_up_to_frame_grid from handlers.base import StateHandlerBase 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 ( +from inference.fast_video_pipeline.nag_config import ( NagConfig, NagDecision, decide_nag, @@ -102,7 +102,7 @@ ic_lora_output_canvas, ) from runtime_config.ic_lora_stage_mode import IcLoraStageMode, ic_lora_stage_mode -from runtime_config.ic_lora_tiling import DEFAULT_CARRY_FRAMES, IcLoraTiling, with_tiling_overrides +from inference.ic_lora_tiling import DEFAULT_CARRY_FRAMES, IcLoraTiling, with_tiling_overrides from runtime_config.evict_retry import evict_retry_filter from runtime_config.memory_meter import ( job_filter_machine_factor, @@ -144,7 +144,7 @@ from services.services_utils import FrameArray from server_utils.heartbeat import log_heartbeat from server_utils.oriented_image import open_oriented_image -from services.generation_interrupt import GenerationCancelledError, is_cancel_exception +from inference.interrupt import GenerationCancelledError, is_cancel_exception from state.app_state_types import AppState, ICLoraState logger = logging.getLogger(__name__) diff --git a/backend/handlers/image_generation_handler.py b/backend/handlers/image_generation_handler.py index 26f2c9bce..0c31c3406 100644 --- a/backend/handlers/image_generation_handler.py +++ b/backend/handlers/image_generation_handler.py @@ -27,7 +27,7 @@ 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 inference.interrupt import is_cancel_exception from services.interfaces import ImageGenerationPipeline, ZitAPIClient from server_utils.heartbeat import log_heartbeat from server_utils.media_validation import validate_image_file diff --git a/backend/handlers/pipelines_handler.py b/backend/handlers/pipelines_handler.py index 3e8b2d7ae..944a65eaf 100644 --- a/backend/handlers/pipelines_handler.py +++ b/backend/handlers/pipelines_handler.py @@ -16,6 +16,7 @@ EditPreflightResolution, EditPreflightResponse, EditPreflightSource, + EditContextMode, ExtendMode, ExtendParams, GenerationRisk, @@ -31,7 +32,8 @@ resolve_home_edit_size, resolve_requested_home_edit_size, ) -from runtime_config.ic_lora_tiling import IcLoraTiling +from inference.ic_lora_tiling import IcLoraTiling +from inference.types import DEFAULT_EDIT_CONTEXT_MODE from runtime_config.model_download_specs import ( IMG_GEN_MODEL_CP_ID, ltx_generation_bundle_on_disk, @@ -53,26 +55,27 @@ video_job_reject, vram_snapshot_suffix, ) -from services.retake_pipeline.window import ( +from inference.retake_pipeline.window import ( MAX_INPUT_FRAMES, EditRefusal, prepare_extend_window, prepare_retake_window, ) +from inference.a2v_pipeline.a2v_pipeline import A2VPipeline +from inference.fast_video_pipeline.fast_video_pipeline import FastVideoPipeline +from inference.ic_lora_pipeline.ic_lora_pipeline import IcLoraPipeline +from inference.retake_pipeline.retake_pipeline import RetakePipeline from services.interfaces import ( - A2VPipeline, DepthProcessorPipeline, - FastVideoPipeline, ImageGenerationPipeline, GpuCleaner, GpuInfo, - IcLoraPipeline, PoseProcessorPipeline, - RetakePipeline, VideoPipelineModelType, ) +from services.features.video.window_estimates import fast_window_estimate_gib from server_utils.generation_liveness import liveness_hold -from services.services_utils import device_supports_fp8, get_device_type +from inference.device import device_supports_fp8, get_device_type from state.app_state_types import ( A2VPipelineState, AppState, @@ -180,7 +183,8 @@ def __init__( self._runtime_device = get_device_type(self.config.device) def _resolve_ltx_paths(self, model_id: LTXLocalModelId, gemma_root: str | None): - from runtime_config.ltx_runtime_paths import ResolvedLtxModelPaths, resolve_ltx_runtime_paths + from inference.layout import ResolvedLtxModelPaths + from runtime_config.ltx_runtime_paths import resolve_ltx_runtime_paths from state.app_settings import resolved_use_conv_vae paths: ResolvedLtxModelPaths = resolve_ltx_runtime_paths( @@ -236,6 +240,14 @@ def _compile_if_enabled(self, state: VideoPipelineState) -> VideoPipelineState: if self._runtime_device == "mps": logger.info("Skipping torch.compile() for %s - not supported on MPS", state.pipeline.pipeline_kind) return state + if self.config.smart_app_control_on: + # Inductor builds Triton kernels as unsigned .pyd files at run time. + # Smart App Control blocks them, so the first forward would fail. + logger.info( + "Skipping torch.compile() for %s - Windows Smart App Control blocks Triton", + state.pipeline.pipeline_kind, + ) + return state if self.config.use_sage_attention: # SageAttention's Python-level kernel forces a Dynamo graph break at every # attention call. The resume graph Dynamo builds for the code after each @@ -281,6 +293,7 @@ def _create_video_pipeline( video_vae_path=paths.video_vae_path, audio_vae_path=paths.audio_vae_path, duration_head_path=paths.duration_head_path, + window_estimate_gib=fast_window_estimate_gib, ) state = VideoPipelineState( @@ -604,6 +617,7 @@ def _create() -> A2VPipelineState: video_vae_path=paths.video_vae_path, audio_vae_path=paths.audio_vae_path, duration_head_path=paths.duration_head_path, + window_estimate_gib=fast_window_estimate_gib, ) return A2VPipelineState( pipeline=pipeline, @@ -818,6 +832,7 @@ def _retake_verdict( job_filter: LocalJobFilter, start_time: float, duration: float, + context_mode: EditContextMode = DEFAULT_EDIT_CONTEXT_MODE, ) -> _EditVerdict: """Retake window + budget verdict. Window math is shared with the executor.""" prepared = prepare_retake_window( @@ -828,6 +843,7 @@ def _retake_verdict( frame_cap=frame_cap, start_time=start_time, duration=duration, + context_mode=context_mode, ) if isinstance(prepared, EditRefusal): return _EditVerdict( @@ -861,6 +877,7 @@ def _extend_verdict( job_filter: LocalJobFilter, duration: float, mode: ExtendMode, + context_mode: EditContextMode = DEFAULT_EDIT_CONTEXT_MODE, ) -> _EditVerdict: """Extend window + budget verdict. Window math is shared with the executor.""" prepared = prepare_extend_window( @@ -871,6 +888,7 @@ def _extend_verdict( frame_cap=frame_cap, duration=duration, mode=mode, + context_mode=context_mode, ) if isinstance(prepared, EditRefusal): return _EditVerdict( @@ -938,6 +956,7 @@ def _preflight_retake(self, asset_path: str, params: RetakeParams) -> Generation job_filter=job_filter, start_time=params.startTime, duration=params.duration, + context_mode=params.contextMode, ), ) @@ -976,6 +995,7 @@ def _preflight_extend(self, asset_path: str, params: ExtendParams) -> Generation job_filter=job_filter, duration=params.duration, mode=params.mode, + context_mode=params.contextMode, ), ) @@ -1008,6 +1028,7 @@ def preflight_edit_matrix( mode: ExtendMode, candidates: list[EditPreflightCandidate], durations: list[float], + context_mode: EditContextMode = DEFAULT_EDIT_CONTEXT_MODE, ) -> EditPreflightResponse: """Advisory per-cell verdicts for Home retake/extend pickers. @@ -1015,6 +1036,10 @@ def preflight_edit_matrix( window + budget verdicts the create path raises with, so a failing cell reads exactly like its create 422. Raises like create on unreadable/too-short sources; per-cell failures never raise. + + ``context_mode`` is the edit's own, as create sends it: it sets the + context kept in the window, so a ``short`` edit is priced and capped + at a smaller window than a ``long`` one. """ fps, source_width, source_height, source_frames = read_source_metadata( asset_path @@ -1063,6 +1088,7 @@ def verdict_at(d: float) -> _EditVerdict: job_filter=job_filter, start_time=start_time, duration=d, + context_mode=context_mode, ) else: @@ -1077,6 +1103,7 @@ def verdict_at(d: float) -> _EditVerdict: job_filter=job_filter, duration=d, mode=mode, + context_mode=context_mode, ) if not verdict_at(min_duration).ok or hi_cap <= 0: diff --git a/backend/handlers/prompt_enhancement_handler.py b/backend/handlers/prompt_enhancement_handler.py index ba348e681..7f7815891 100644 --- a/backend/handlers/prompt_enhancement_handler.py +++ b/backend/handlers/prompt_enhancement_handler.py @@ -48,7 +48,7 @@ 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 -from services.generation_interrupt import is_cancel_exception +from inference.interrupt import is_cancel_exception from services.interfaces import PromptEnhancerPipeline from services.lora_catalog import LoraCatalogProvider from services.prompt_enhancement import ( @@ -72,7 +72,7 @@ from services.prompt_enhancement.video_frames import sampled_video_frames from services.prompt_enhancer_pipeline.gemini_prompt_enhancer_pipeline import GeminiPromptEnhancerPipeline from services.records import MediaError -from services.services_utils import get_device_type +from inference.device import get_device_type from state.app_state_types import AppState logger = logging.getLogger(__name__) @@ -152,7 +152,7 @@ def status(self, *, prefer_gemini: bool) -> PromptEnhancerStatusResponse: ) local_encoding = self._text_handler.should_use_local_encoding() compile_on = ( - settings.use_torch_compile and not self.config.use_sage_attention + settings.use_torch_compile and self.config.torch_compile_available ) base_reason, reason_by_feature = nag_unavailable_reasons( nag_scale=settings.nag_scale, local_encoding=local_encoding, compile_on=compile_on diff --git a/backend/handlers/prompt_enhancer_nag.py b/backend/handlers/prompt_enhancer_nag.py index 1fcc5fc34..61d0268db 100644 --- a/backend/handlers/prompt_enhancer_nag.py +++ b/backend/handlers/prompt_enhancer_nag.py @@ -4,7 +4,7 @@ import os -from services.fast_video_pipeline.nag_config import decide_nag +from inference.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 ( diff --git a/backend/handlers/queued_generation_handler.py b/backend/handlers/queued_generation_handler.py index e613d4935..a68e764f9 100644 --- a/backend/handlers/queued_generation_handler.py +++ b/backend/handlers/queued_generation_handler.py @@ -79,7 +79,7 @@ stored_generation_risk, ) from services.aspect_ratio import find_closest_aspect_ratio_option -from services.fast_video_pipeline.nag_config import ( +from inference.fast_video_pipeline.nag_config import ( DEFAULT_SCALE as DEFAULT_NAG_SCALE, decide_nag, ) @@ -99,10 +99,10 @@ from services.lora_catalog import LoraCatalogProvider from services.store import Store from services.sqlite_store import collect_asset_ids +from inference.errors import CapabilityFailedError from services.records import ( AttemptError, AssetRecord, - CapabilityFailedError, GenerationRecord, MediaError, QueueGenerationRecord, @@ -141,9 +141,6 @@ logger = logging.getLogger(__name__) -# 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: payload = record.model_dump(mode="json") @@ -236,7 +233,6 @@ def __init__( 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: @@ -262,7 +258,6 @@ 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() @@ -295,7 +290,8 @@ def _dump_fast_params( uses_torch_compile and settings.use_torch_compile and not ( - self._config is not None and self._config.use_sage_attention + self._config is not None + and not self._config.torch_compile_available ) ) if self._should_use_local_encoding is not None: @@ -405,9 +401,6 @@ def create_keyframes( 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 @@ -954,6 +947,7 @@ def preflight_edit(self, req: EditPreflightRequest) -> EditPreflightResponse: asset_path=video.path, start_time=req.startTime, mode=req.mode, + context_mode=req.contextMode, candidates=req.candidates, durations=req.durations, ) @@ -1382,10 +1376,6 @@ 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._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 != KEYFRAMES_FEATURE] try: return self._db.list_recent_features(limit=limit, allowed=allowed) except UnavailableError as exc: diff --git a/backend/handlers/retake_handler.py b/backend/handlers/retake_handler.py index 9e60ef9f4..cb92bdf3f 100644 --- a/backend/handlers/retake_handler.py +++ b/backend/handlers/retake_handler.py @@ -34,8 +34,8 @@ from runtime_config.ltx_capabilities import local_caps, supports from runtime_config.model_download_specs import resolve_active_ltx_model_id from runtime_config.runtime_config import RuntimeConfig -from services.generation_interrupt import GenerationCancelledError, is_cancel_exception -from services.retake_pipeline.retake_mode import ( +from inference.interrupt import GenerationCancelledError, is_cancel_exception +from inference.retake_pipeline.retake_mode import ( InvalidRetakeModeError, resolve_retake_mode, ) diff --git a/backend/handlers/video_generation_handler.py b/backend/handlers/video_generation_handler.py index 8caf335f1..8591c427b 100644 --- a/backend/handlers/video_generation_handler.py +++ b/backend/handlers/video_generation_handler.py @@ -16,7 +16,7 @@ from PIL import Image -from frame_math import ( +from inference.frame_math import ( AutoDurationSpec, compute_num_frames, effective_a2v_audio_seconds, @@ -105,17 +105,17 @@ validate_image_file, ) 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 ( +from inference.progress import distilled_total_steps +from inference.fast_video_pipeline.nag_config import ( NagDecision, decide_nag, log_nag_decision, ) -from services.generation_interrupt import GenerationCancelledError, is_cancel_exception +from inference.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 inference.patches import diffusion_stage_cache from state.app_state_types import AppState from state.app_settings import resolved_use_conv_vae, should_video_generate_with_ltx_api @@ -815,7 +815,7 @@ def _decide_nag( compile_enabled = ( compiled and self.state.app_settings.use_torch_compile - and not self.config.use_sage_attention + and self.config.torch_compile_available ) return decide_nag( negative_prompt, @@ -925,7 +925,7 @@ def generate_video( 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 + and self.config.torch_compile_available ) nag = log_nag_decision( logger, diff --git a/backend/handlers/video_resolution.py b/backend/handlers/video_resolution.py index 701c388ec..cab421e44 100644 --- a/backend/handlers/video_resolution.py +++ b/backend/handlers/video_resolution.py @@ -8,12 +8,15 @@ from __future__ import annotations -from dataclasses import dataclass from pathlib import Path from typing import TYPE_CHECKING from _routes._errors import HTTPError -from frame_math import snap_up_to_multiple +from inference.frame_math import snap_up_to_multiple +from inference.retake_pipeline.letterbox import ( + SpatialLetterbox as SpatialLetterbox, + generation_letterbox as generation_letterbox, +) if TYPE_CHECKING: from api_types import TargetResolution @@ -86,45 +89,6 @@ def correct_resolution( _2160P_EDIT_BOX = (3840, 2176) -@dataclass(frozen=True) -class SpatialLetterbox: - """Picture rect centered on the ÷32 canvas the model actually encodes.""" - - content_width: int - content_height: int - canvas_width: int - canvas_height: int - left: int - top: int - - @property - def right(self) -> int: - return self.canvas_width - self.content_width - self.left - - @property - def bottom(self) -> int: - return self.canvas_height - self.content_height - self.top - - -def generation_letterbox(width: int, height: int) -> SpatialLetterbox: - """Pad ``width``×``height`` up to the next multiple of 32, split evenly. - - An odd remainder gives the extra pixel to the right or the bottom. - """ - canvas_width = ((width + _SPATIAL_FACTOR - 1) // _SPATIAL_FACTOR) * _SPATIAL_FACTOR - canvas_height = ((height + _SPATIAL_FACTOR - 1) // _SPATIAL_FACTOR) * _SPATIAL_FACTOR - pad_x = canvas_width - width - pad_y = canvas_height - height - return SpatialLetterbox( - content_width=width, - content_height=height, - canvas_width=canvas_width, - canvas_height=canvas_height, - left=pad_x // 2, - top=pad_y // 2, - ) - - def cap_edit_size(width: int, height: int, *, high_res: bool = False) -> tuple[int, int]: """Fit inside local 1080p (4K with ``high_res``) without upscaling or changing aspect. diff --git a/backend/ic_lora_preprocessing.py b/backend/ic_lora_preprocessing.py index 60e84010b..b3bfe18da 100644 --- a/backend/ic_lora_preprocessing.py +++ b/backend/ic_lora_preprocessing.py @@ -11,7 +11,7 @@ import numpy as np from api_types import PreprocessingStep -from frame_math import snap_to_frame_grid +from inference.frame_math import snap_to_frame_grid from runtime_config.ic_lora_loop_fps import resolve_loop_fps from services.interfaces import VideoProcessor from services.services_utils import FrameArray diff --git a/backend/inference/__init__.py b/backend/inference/__init__.py new file mode 100644 index 000000000..f6a5004c0 --- /dev/null +++ b/backend/inference/__init__.py @@ -0,0 +1,37 @@ +"""Headless inference library. Public exports only; no desktop infra.""" + +from __future__ import annotations + +import os +from typing import TYPE_CHECKING + +# Hosts should configure the allocator before importing inference. This +# setdefault protects direct library imports without overriding host policy. +os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True") + +from inference.types import ( + ExtendMode, + ImageConditioningInput, + LTXLocalModelId, + RetakeMode, +) + +if TYPE_CHECKING: + from inference.fast_video_pipeline.ltx_fast_video_pipeline import LTXFastVideoPipeline as LTXFastVideoPipeline + +__all__ = [ + "ExtendMode", + "ImageConditioningInput", + "LTXFastVideoPipeline", + "LTXLocalModelId", + "RetakeMode", +] + + +def __getattr__(name: str) -> object: + # TODO: the Pod image in the next PR imports LTXFastVideoPipeline from this package. + if name == "LTXFastVideoPipeline": + from inference.fast_video_pipeline.ltx_fast_video_pipeline import LTXFastVideoPipeline + + return LTXFastVideoPipeline + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") diff --git a/backend/services/a2v_pipeline/__init__.py b/backend/inference/a2v_pipeline/__init__.py similarity index 100% rename from backend/services/a2v_pipeline/__init__.py rename to backend/inference/a2v_pipeline/__init__.py diff --git a/backend/services/a2v_pipeline/a2v_pipeline.py b/backend/inference/a2v_pipeline/a2v_pipeline.py similarity index 83% rename from backend/services/a2v_pipeline/a2v_pipeline.py rename to backend/inference/a2v_pipeline/a2v_pipeline.py index 0e679517e..8c41bfbdf 100644 --- a/backend/services/a2v_pipeline/a2v_pipeline.py +++ b/backend/inference/a2v_pipeline/a2v_pipeline.py @@ -4,11 +4,12 @@ from typing import TYPE_CHECKING, Protocol -from api_types import ImageConditioningInput -from services.fast_video_pipeline.nag_config import NagConfig +from inference.types import ImageConditioningInput +from inference.fast_video_pipeline.nag_config import NagConfig if TYPE_CHECKING: import torch + from inference.fast_video_pipeline.windowed_run import WindowEstimate from ltx_pipelines.utils.types import OffloadMode @@ -26,6 +27,7 @@ def create( video_vae_path: str | None = None, audio_vae_path: str | None = None, duration_head_path: str | None = None, + window_estimate_gib: WindowEstimate | None = None, ) -> "A2VPipeline": ... def generate( diff --git a/backend/services/a2v_pipeline/distilled_a2v_pipeline.py b/backend/inference/a2v_pipeline/distilled_a2v_pipeline.py similarity index 97% rename from backend/services/a2v_pipeline/distilled_a2v_pipeline.py rename to backend/inference/a2v_pipeline/distilled_a2v_pipeline.py index 71b91775d..b88466c8b 100644 --- a/backend/services/a2v_pipeline/distilled_a2v_pipeline.py +++ b/backend/inference/a2v_pipeline/distilled_a2v_pipeline.py @@ -13,15 +13,15 @@ import torch -from services.audio_channels import stereo_waveform -from services.fast_video_pipeline.nag_config import NagConfig -from services.fast_video_pipeline.nag_distilled import ( +from inference.audio_channels import stereo_waveform +from inference.fast_video_pipeline.nag_config import NagConfig +from inference.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 +from inference.patches.nag_cross_attention import NagState +from inference.common import TilingConfigType if TYPE_CHECKING: from ltx_core.conditioning import ConditioningItem diff --git a/backend/services/a2v_pipeline/ltx_a2v_pipeline.py b/backend/inference/a2v_pipeline/ltx_a2v_pipeline.py similarity index 89% rename from backend/services/a2v_pipeline/ltx_a2v_pipeline.py rename to backend/inference/a2v_pipeline/ltx_a2v_pipeline.py index 60a4d37e5..626c40bcd 100644 --- a/backend/services/a2v_pipeline/ltx_a2v_pipeline.py +++ b/backend/inference/a2v_pipeline/ltx_a2v_pipeline.py @@ -6,16 +6,22 @@ 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, inference_result_from_output -from services.ltx_pipeline_common import ( +from inference.types import ImageConditioningInput +from inference.fast_video_pipeline.nag_config import NagConfig +from inference.fast_video_pipeline.windowed_run import ( + WindowEstimate, + encode_result, + measured_windows, + plan_windows, +) +from inference.ic_lora_pipeline.ic_lora_inference import InferenceResult, inference_result_from_output +from inference.common import ( build_model_paths, resolve_tiling_config, to_ltx_images, ) -from services.services_utils import TilingConfigType, device_supports_fp8 +from inference.device import device_supports_fp8 +from inference.common import TilingConfigType if TYPE_CHECKING: from ltx_pipelines.chunks import ChunkConfig @@ -36,6 +42,7 @@ def create( video_vae_path: str | None = None, audio_vae_path: str | None = None, duration_head_path: str | None = None, + window_estimate_gib: WindowEstimate | None = None, ) -> "LTXa2vPipeline": return LTXa2vPipeline( checkpoint_path=checkpoint_path, @@ -48,6 +55,7 @@ def create( video_vae_path=video_vae_path, audio_vae_path=audio_vae_path, duration_head_path=duration_head_path, + window_estimate_gib=window_estimate_gib, ) def __init__( @@ -63,13 +71,15 @@ def __init__( video_vae_path: str | None = None, audio_vae_path: str | None = None, duration_head_path: str | None = None, + window_estimate_gib: WindowEstimate | None = None, ) -> None: 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.a2v_pipeline.distilled_a2v_pipeline import DistilledA2VPipeline + from inference.a2v_pipeline.distilled_a2v_pipeline import DistilledA2VPipeline + self._window_estimate_gib = window_estimate_gib lora_entries = [ LoraPathStrengthAndSDOps(path=path, strength=scale, sd_ops=LTXV_LORA_COMFY_RENAMING_MAP) for path, scale in (loras or []) @@ -176,7 +186,7 @@ def generate( chunk_pixel_frames: int | None = None, nag: NagConfig | None = None, ) -> None: - from services.denoising_progress import distilled_total_steps, track_denoising + from inference.progress import distilled_total_steps, track_denoising chunk_config, chunk_count = plan_windows( chunk_pixel_frames, width=width, height=height, num_frames=num_frames, frame_rate=frame_rate @@ -192,6 +202,7 @@ def generate( measured = measured_windows( chunk_config, width=width, height=height, window_count=chunk_count, num_frames=num_frames, frame_rate=frame_rate, device=self.pipeline.device, + estimate_gib=self._window_estimate_gib, ) with track_denoising(distilled_total_steps() * chunk_count), measured: if chunk_config is None: diff --git a/backend/inference/apply_patches.py b/backend/inference/apply_patches.py new file mode 100644 index 000000000..489bd8d17 --- /dev/null +++ b/backend/inference/apply_patches.py @@ -0,0 +1,130 @@ +"""CUDA patches + SageAttention SDPA wrap (gated). Call after CUDA alloc env is set.""" + +from __future__ import annotations + +import logging +import os +from typing import Any, cast + +logger = logging.getLogger(__name__) + +_sageattention_runtime_fallback_logged = False +_sdpa_wrapped = False + + +def apply_patches(*, smart_app_control_on: bool = False) -> bool: + """Apply Linux CUDA monkey-patches and optionally wrap SDPA with SageAttention. + + SageAttention stays gated on ``USE_SAGE_ATTENTION`` (default ``"1"``). Returns + whether the wrap is enabled after import/setup (False if the env is off, Windows + Smart App Control blocks it, or sageattention fails to load). A second call does + not wrap SDPA again. + """ + global _sdpa_wrapped + if smart_app_control_on: + # Before the patch imports below pull in ltx-core: its VAE kernels use Triton even + # when SageAttention is off, and SAC blocks the .pyd files Triton builds. + from inference.triton_block import block_triton_import + + if not block_triton_import(): + logger.warning( + "Smart App Control is on but Triton was already imported; " + "VAE kernels may still hit blocked Triton files." + ) + # LLM: bumping ltx-core / ltx-pipelines (backend/pyproject.toml) MUST re-verify + # every import below. These monkey-patch private ltx-core / ltx-pipelines / + # safetensors symbols. Delete-first: drop a patch if upstream now includes the + # fix (see that file's "Remove once ..." docstring). Callers must set + # PYTORCH_CUDA_ALLOC_CONF before importing torch; Darwin mps_prebuilt_ext / + # MPS_SDPA_SKIP_CALIBRATION must run before this function (patches transitively + # import mps_sdpa). + import inference.patches.safetensors_metadata_fix as _safetensors_metadata_fix # pyright: ignore[reportUnusedImport] # Remove once safetensors supports read-only mmap + del _safetensors_metadata_fix + import inference.patches.gemma_assets_positional_read as _gemma_assets_positional_read # pyright: ignore[reportUnusedImport] # Remove once GemmaAssets.from_single_file reads the packed text encoder without mmap and Windows generates without an access violation (LTX-Desktop#203) + del _gemma_assets_positional_read + import inference.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) + del _pinned_pool_fix + import inference.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 inference.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 inference.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 inference.patches.diffusion_interrupt as _diffusion_interrupt # pyright: ignore[reportUnusedImport] # Remove once ltx-pipelines denoiser/loop accepts an interrupt callback + del _diffusion_interrupt + import inference.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 + + use_sage_attention = os.environ.get("USE_SAGE_ATTENTION", "1") == "1" + if not use_sage_attention: + return False + if smart_app_control_on: + # SageAttention launches Triton kernels. Triton compiles unsigned .pyd files at + # run time, which Smart App Control blocks. Plain torch SDPA needs no such code. + logger.warning( + "Windows Smart App Control is on and blocks the unsigned code that " + "SageAttention and Triton build at run time. SageAttention and torch.compile " + "are off; generation uses the default attention and runs slower." + ) + return False + if _sdpa_wrapped: + return True + + try: + from sageattention import sageattn # type: ignore[reportMissingImports] + import torch + import torch.nn.functional as F + + _original_sdpa = F.scaled_dot_product_attention + + _SAGE_SUPPORTED_HEADDIMS = {64, 96, 128} + + @torch.compiler.disable(recursive=True) # type: ignore[reportUntypedFunctionDecorator] + def _sageattn_call(query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, is_causal: bool) -> torch.Tensor: + # torch.compile must not trace into sageattn's Python internals (quant.py, + # core.py): it bakes the current call's shapes into the compiled graph's + # guards, which then hard-fails (ConstraintViolationError) on any later call + # with different video/audio dimensions. Disabling keeps this call eager — + # a graph break here, not a recompile — while the surrounding transformer + # forward stays compiled. + return cast(torch.Tensor, sageattn(query, key, value, is_causal=is_causal, tensor_layout="HND")) # type: ignore[reportUnnecessaryCast] + + def patched_sdpa( + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + attn_mask: torch.Tensor | None = None, + dropout_p: float = 0.0, + is_causal: bool = False, + scale: float | None = None, + **kwargs: Any, + ) -> torch.Tensor: + global _sageattention_runtime_fallback_logged + try: + if ( + query.dim() == 4 + and attn_mask is None + and dropout_p == 0.0 + and query.shape[-1] in _SAGE_SUPPORTED_HEADDIMS + ): + return _sageattn_call(query, key, value, is_causal) + else: + return _original_sdpa(query, key, value, attn_mask=attn_mask, + dropout_p=dropout_p, is_causal=is_causal, scale=scale, **kwargs) + except Exception: + if not _sageattention_runtime_fallback_logged: + logger.warning("SageAttention failed during runtime; falling back to default attention", exc_info=True) + _sageattention_runtime_fallback_logged = True + return _original_sdpa(query, key, value, attn_mask=attn_mask, + dropout_p=dropout_p, is_causal=is_causal, scale=scale, **kwargs) + + F.scaled_dot_product_attention = patched_sdpa + _sdpa_wrapped = True + logger.info("SageAttention enabled - attention operations will be faster") + return True + except ImportError: + logger.warning("SageAttention not installed - using default attention") + return False + except Exception: + logger.warning("Failed to enable SageAttention", exc_info=True) + return False diff --git a/backend/services/audio_channels.py b/backend/inference/audio_channels.py similarity index 100% rename from backend/services/audio_channels.py rename to backend/inference/audio_channels.py diff --git a/backend/services/ltx_pipeline_common.py b/backend/inference/common.py similarity index 92% rename from backend/services/ltx_pipeline_common.py rename to backend/inference/common.py index e3ecb6268..b4e14d2fa 100644 --- a/backend/services/ltx_pipeline_common.py +++ b/backend/inference/common.py @@ -4,25 +4,39 @@ from collections.abc import Iterator, Sequence import logging -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, TypeAlias import torch -from runtime_config.runtime_policy import CUDA_CPU_OFFLOAD_RAM_FLOOR_GB, should_disk_stream_cuda_weights -from services.services_utils import PipelineTilingType, TilingConfigType -from services.storage_info.storage_info import DriveType +from inference.device import ( + CUDA_CPU_OFFLOAD_RAM_FLOOR_GB, + DriveType, + should_disk_stream_cuda_weights, +) logger = logging.getLogger(__name__) if TYPE_CHECKING: - from api_types import ImageConditioningInput + from inference.types import ImageConditioningInput from ltx_core.components.guiders import MultiModalGuiderParams + from ltx_core.model.video_vae import TilingConfig from ltx_core.model.video_vae.transformer.config import DiffVAEMode + from ltx_core.tiling import PipelineTiling + from ltx_core.types import Audio as AudioType 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 + TilingConfigType: TypeAlias = TilingConfig + PipelineTilingType: TypeAlias = PipelineTiling +else: + TilingConfigType: TypeAlias = object + PipelineTilingType: TypeAlias = object + AudioType: TypeAlias = object + +AudioOrNone: TypeAlias = AudioType | None + 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. @@ -49,6 +63,20 @@ def auto_tiling_config() -> PipelineTilingType: return AUTO_TILING +def host_total_gib() -> int | None: + """Total system RAM in GiB, or None if it cannot be queried. + + TODO: the Pod image in the next PR reads host RAM from here. + """ + try: + import psutil + + return int(psutil.virtual_memory().total // (1024**3)) + except Exception: + logger.warning("Failed to query total system RAM", exc_info=True) + return None + + def host_available_bytes() -> int: """Currently available system RAM in bytes (unified memory on Apple Silicon).""" import psutil diff --git a/backend/inference/device.py b/backend/inference/device.py new file mode 100644 index 000000000..73a0fb958 --- /dev/null +++ b/backend/inference/device.py @@ -0,0 +1,180 @@ +"""Device type, fp8 capability, and CUDA RAM/VRAM floors for local inference.""" + +from __future__ import annotations + +import logging +from typing import Literal + +import torch + +logger = logging.getLogger(__name__) + +DriveType = Literal["nvme", "ssd", "hdd"] + +# CUDA discrete VRAM floors (integer GiB, ``total_memory // 1024**3``). +# At/above the full floor, fp8-capable cards can hold the halved transformer +# resident. +# +# The streaming floor is an early exit, not the policy. The per-cell model is +# the real gate: it refuses a cell that does not fit free VRAM. The floor only +# skips that check on hardware that cannot run the smallest cell. 10 GB-class +# cards report just under 10 GiB and stream. 8 GB-class cards report just under +# 8 GiB and stay excluded. Do not tighten this floor toward 8. The gap above +# the smallest cell is an estimate of ordinary desktop occupancy, and shaving +# it would exclude cards the per-cell model still runs. Measured for Windows +# fp8 only. Without fp8 the bf16 path is unmeasured, so Linux and non-fp8 CUDA +# keep the 15 floor. +CUDA_VRAM_FLOOR_GB = 9 +LINUX_VRAM_FLOOR_GB = 15 +CUDA_FULL_VRAM_GB = 31 + +# CUDA OffloadMode.CPU pre-pins every transformer block in host RAM. ltx-pipelines +# documents that path as ~36 GB RAM + ~5 GB VRAM. On Linux those buffers are +# page-locked (unswappable), so a 32 GB machine — the advertised local-gen floor — +# dies in the kernel OOM killer with VRAM still empty (LTX-Desktop#163). Below this +# total-RAM floor, stream from disk instead (OffloadMode.DISK, ~5 GB host). +CUDA_CPU_OFFLOAD_RAM_FLOOR_GB = 40 + +# First compute capability with native fp8 (E4M3/E5M2): Ada Lovelace. +# Ampere (8.x) and Turing (7.5) have no hardware fp8. +_FP8_MIN_COMPUTE_CAPABILITY = (8, 9) + + +def get_device_type(device: str | torch.device | object | None) -> str: + if device is None: + return "cpu" + + device_type = getattr(device, "type", None) + if isinstance(device_type, str): + return device_type + + if isinstance(device, str): + try: + return str(torch.device(device).type) + except Exception: + logger.warning("Could not parse device string '%s', using it as-is", device, exc_info=True) + return device + + return "cpu" + + +def _device_index(device: str | torch.device | object | None) -> int: + """CUDA device ordinal for capability probes. Unindexed shapes mean 0.""" + # NB: torch stubs type .index as int, but at runtime an unindexed device + # (torch.device("cuda")) carries None — hence `or 0`, not `is None`. + if isinstance(device, torch.device): + return device.index or 0 + if isinstance(device, str): + try: + return torch.device(device).index or 0 + except Exception: + return 0 + index = getattr(device, "index", None) + return index if isinstance(index, int) else 0 + + +def device_supports_fp8(device: str | torch.device | object | None) -> bool: + # ROCm PyTorch also reports device.type == "cuda" (see runtime_config.accelerator), + # so this must not be a plain device-type check: ROCm has no fp8_cast kernel support + # here yet, and would otherwise be silently misidentified as CUDA/NVIDIA. + # Pre-Ada NVIDIA (compute capability < 8.9) has no hardware fp8 either. + # Originally contributed by boxwrench in https://github.com/Lightricks/LTX-Desktop/pull/160 + if get_device_type(device) != "cuda": + return False + if getattr(torch.version, "hip", None): + return False + if not torch.cuda.is_available(): + return False + try: + return torch.cuda.get_device_capability(_device_index(device)) >= _FP8_MIN_COMPUTE_CAPABILITY + except Exception: + logger.warning("fp8 capability probe failed; treating device as non-fp8", exc_info=True) + return False + + +def windows_checkpoint_streams_from_disk( + system: str, drive_type: DriveType | None +) -> bool: + """Whether Windows can stream checkpoint weights from disk (NVMe only). + + 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, + cpu_ram_floor_gb: int | None = CUDA_CPU_OFFLOAD_RAM_FLOOR_GB, +) -> bool: + """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 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": + 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 + 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 decide_cuda_local_generation_mode( + system: str, + cuda_available: bool, + vram_gb: float | None, + fp8_capable: bool = True, +) -> Literal["full_models_loading", "streaming_models_loading", "unsupported"]: + """Windows and Linux load mode from discrete VRAM. + + ``runtime_config.runtime_policy.decide_local_generation_mode`` calls this for + those systems and keeps the Darwin rules. A host that copies only + ``inference/`` calls this directly. + + - "unsupported": CUDA is missing, VRAM is unknown, or VRAM is below the floor + (Windows fp8 uses ``CUDA_VRAM_FLOOR_GB``; Linux and non-fp8 use + ``LINUX_VRAM_FLOOR_GB``). + - "streaming_models_loading": enough to run, but below ``CUDA_FULL_VRAM_GB``, + or no hardware fp8. The full floor assumes the fp8-halved transformer. + - "full_models_loading": fp8-capable and at or above ``CUDA_FULL_VRAM_GB``. + """ + if system not in ("Windows", "Linux"): + return "unsupported" + if not cuda_available or vram_gb is None: + return "unsupported" + floor_gb = CUDA_VRAM_FLOOR_GB if system == "Windows" and fp8_capable else LINUX_VRAM_FLOOR_GB + if vram_gb < floor_gb: + return "unsupported" + # Without fp8 (ROCm today), holding the full bf16 transformer resident would + # OOM at CUDA_FULL_VRAM_GB. Stay on streaming until a bf16 floor exists. + # Originally contributed by boxwrench in https://github.com/Lightricks/LTX-Desktop/pull/160 + if not fp8_capable or vram_gb < CUDA_FULL_VRAM_GB: + return "streaming_models_loading" + return "full_models_loading" diff --git a/backend/inference/errors.py b/backend/inference/errors.py new file mode 100644 index 000000000..3d420b23c --- /dev/null +++ b/backend/inference/errors.py @@ -0,0 +1,14 @@ +"""Failures the pipeline can raise without importing desktop ``services.records``.""" + +from __future__ import annotations + +VIDEO_JOB_TOO_LARGE = "VIDEO_JOB_TOO_LARGE" + + +class CapabilityFailedError(Exception): + """Executor could not run this generation with the current local capability.""" + + def __init__(self, detail: str, *, code: str | None = None) -> None: + self.detail = detail + self.code = code + super().__init__(detail) diff --git a/backend/runtime_config/fast_chunking.py b/backend/inference/fast_chunking.py similarity index 100% rename from backend/runtime_config/fast_chunking.py rename to backend/inference/fast_chunking.py diff --git a/backend/inference/fast_envelope.py b/backend/inference/fast_envelope.py new file mode 100644 index 000000000..e58f5ebac --- /dev/null +++ b/backend/inference/fast_envelope.py @@ -0,0 +1,77 @@ +"""ltx-2.5-fast T2V/I2V canvases for a host that copies ``inference/``. + +Desktop keeps its own envelope and does not import this table. + +TODO: the Pod image in the next PR reads this table. +""" + +from __future__ import annotations + +SIZES_STAGE1_OR_TWO_PASS: frozenset[tuple[int, int]] = frozenset( + { + (576, 576), + (576, 704), + (576, 1024), + (704, 704), + (704, 896), + (704, 1280), + (768, 576), + (896, 576), + (960, 704), + (1024, 576), + (1088, 704), + (1280, 704), + (1344, 576), + (1664, 704), + } +) +SIZES_1080: frozenset[tuple[int, int]] = frozenset( + { + (1088, 1088), + (1088, 1344), + (1088, 1920), + (1472, 1088), + (1664, 1088), + (1920, 1088), + (2560, 1088), + } +) +ALL_SIZES = SIZES_STAGE1_OR_TWO_PASS | SIZES_1080 +ENVELOPE_FPS: tuple[int, ...] = (24, 25, 48, 50) +LONG_SECONDS: tuple[int, ...] = (2, 3, 4, 5, 6, 8, 10, 20) +SHORT_SECONDS: tuple[int, ...] = (2, 3, 4, 5, 10) + + +def frames_for(seconds: tuple[int, ...]) -> dict[int, frozenset[int]]: + return { + fps: frozenset(max(((duration * fps) // 8) * 8 + 1, 9) for duration in seconds) + for fps in ENVELOPE_FPS + } + + +LONG_FRAMES = frames_for(LONG_SECONDS) +SHORT_FRAMES = frames_for(SHORT_SECONDS) + + +def is_allowed_fast_geometry( + *, + width: int, + height: int, + num_frames: int, + fps: int, + skip_stage_2: bool, +) -> bool: + if height % 64 != 0 or width % 64 != 0: + return False + if num_frames < 1 or (num_frames - 1) % 8 != 0: + return False + if fps not in ENVELOPE_FPS: + return False + if (width, height) not in ALL_SIZES: + return False + band = SHORT_FRAMES if (width, height) in SIZES_1080 else LONG_FRAMES + if num_frames not in band[fps]: + return False + if skip_stage_2 and (width, height) in SIZES_1080: + return False + return True diff --git a/backend/inference/fast_video_pipeline/__init__.py b/backend/inference/fast_video_pipeline/__init__.py new file mode 100644 index 000000000..e51c0d6d4 --- /dev/null +++ b/backend/inference/fast_video_pipeline/__init__.py @@ -0,0 +1,3 @@ +from inference.fast_video_pipeline.fast_video_pipeline import FastVideoPipeline + +__all__ = ["FastVideoPipeline"] diff --git a/backend/services/fast_video_pipeline/distilled_skip_stage_2.py b/backend/inference/fast_video_pipeline/distilled_skip_stage_2.py similarity index 98% rename from backend/services/fast_video_pipeline/distilled_skip_stage_2.py rename to backend/inference/fast_video_pipeline/distilled_skip_stage_2.py index 5d76851fd..f47ef4f46 100644 --- a/backend/services/fast_video_pipeline/distilled_skip_stage_2.py +++ b/backend/inference/fast_video_pipeline/distilled_skip_stage_2.py @@ -37,8 +37,8 @@ VideoAudio, ) -from services.fast_video_pipeline.nag_config import NagConfig -from services.fast_video_pipeline.nag_distilled import NagDistilledMixin +from inference.fast_video_pipeline.nag_config import NagConfig +from inference.fast_video_pipeline.nag_distilled import NagDistilledMixin logger = logging.getLogger(__name__) diff --git a/backend/services/fast_video_pipeline/fast_video_pipeline.py b/backend/inference/fast_video_pipeline/fast_video_pipeline.py similarity index 82% rename from backend/services/fast_video_pipeline/fast_video_pipeline.py rename to backend/inference/fast_video_pipeline/fast_video_pipeline.py index 47e992c86..ad763842f 100644 --- a/backend/services/fast_video_pipeline/fast_video_pipeline.py +++ b/backend/inference/fast_video_pipeline/fast_video_pipeline.py @@ -4,12 +4,13 @@ from typing import TYPE_CHECKING, ClassVar, Literal, Protocol -from api_types import ImageConditioningInput -from frame_math import AutoDurationSpec -from services.fast_video_pipeline.nag_config import NagConfig +from inference.types import ImageConditioningInput +from inference.frame_math import AutoDurationSpec +from inference.fast_video_pipeline.nag_config import NagConfig if TYPE_CHECKING: import torch + from inference.fast_video_pipeline.windowed_run import WindowEstimate from ltx_pipelines.utils.types import OffloadMode @@ -29,6 +30,7 @@ def create( video_vae_path: str | None = None, audio_vae_path: str | None = None, duration_head_path: str | None = None, + window_estimate_gib: WindowEstimate | None = None, ) -> "FastVideoPipeline": ... diff --git a/backend/services/fast_video_pipeline/ltx_fast_video_pipeline.py b/backend/inference/fast_video_pipeline/ltx_fast_video_pipeline.py similarity index 88% rename from backend/services/fast_video_pipeline/ltx_fast_video_pipeline.py rename to backend/inference/fast_video_pipeline/ltx_fast_video_pipeline.py index 40a4cc7e6..356dd96c5 100644 --- a/backend/services/fast_video_pipeline/ltx_fast_video_pipeline.py +++ b/backend/inference/fast_video_pipeline/ltx_fast_video_pipeline.py @@ -7,17 +7,23 @@ import torch -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, inference_result_from_output -from services.ltx_pipeline_common import ( +from inference.types import ImageConditioningInput +from inference.frame_math import AutoDurationSpec +from inference.fast_video_pipeline.nag_config import NagConfig +from inference.fast_video_pipeline.windowed_run import ( + WindowEstimate, + encode_result, + measured_windows, + plan_windows, +) +from inference.ic_lora_pipeline.ic_lora_inference import InferenceResult, inference_result_from_output +from inference.common import ( auto_tiling_config, build_model_paths, to_ltx_images, ) -from services.services_utils import PipelineTilingType, device_supports_fp8 +from inference.device import device_supports_fp8 +from inference.common import PipelineTilingType if TYPE_CHECKING: from ltx_pipelines.chunks import ChunkConfig @@ -42,6 +48,7 @@ def create( video_vae_path: str | None = None, audio_vae_path: str | None = None, duration_head_path: str | None = None, + window_estimate_gib: WindowEstimate | None = None, ) -> "LTXFastVideoPipeline": return LTXFastVideoPipeline( checkpoint_path=checkpoint_path, @@ -54,6 +61,7 @@ def create( video_vae_path=video_vae_path, audio_vae_path=audio_vae_path, duration_head_path=duration_head_path, + window_estimate_gib=window_estimate_gib, ) def __init__( @@ -69,11 +77,12 @@ def __init__( video_vae_path: str | None = None, audio_vae_path: str | None = None, duration_head_path: str | None = None, + window_estimate_gib: WindowEstimate | None = None, ) -> None: 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 + from inference.fast_video_pipeline.distilled_skip_stage_2 import DistilledPipelineWithSkipStage2 self._checkpoint_path = checkpoint_path self._gemma_root = gemma_root @@ -83,6 +92,7 @@ def __init__( self._duration_head_path = duration_head_path self._device = device self._offload_mode = offload_mode + self._window_estimate_gib = window_estimate_gib self._quantization = build_fp8_cast_policy(checkpoint_path) if device_supports_fp8(device) else None self._loras = loras or [] @@ -179,7 +189,7 @@ def generate( chunk_pixel_frames: int | None = None, nag: NagConfig | None = None, ) -> None: - from services.denoising_progress import distilled_total_steps, track_denoising + from inference.progress import distilled_total_steps, track_denoising chunk_config, chunk_count = plan_windows( chunk_pixel_frames, width=width, height=height, num_frames=num_frames, frame_rate=frame_rate @@ -188,6 +198,7 @@ def generate( measured = measured_windows( chunk_config, width=width, height=height, window_count=chunk_count, num_frames=num_frames, frame_rate=frame_rate, device=self._device, + estimate_gib=self._window_estimate_gib, ) with track_denoising(steps), measured: result = self._run_inference( @@ -230,7 +241,7 @@ def compile_transformer(self) -> None: 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 + from inference.fast_video_pipeline.distilled_skip_stage_2 import DistilledPipelineWithSkipStage2 lora_entries = [ LoraPathStrengthAndSDOps(path=path, strength=scale, sd_ops=LTXV_LORA_COMFY_RENAMING_MAP) diff --git a/backend/services/fast_video_pipeline/nag_config.py b/backend/inference/fast_video_pipeline/nag_config.py similarity index 98% rename from backend/services/fast_video_pipeline/nag_config.py rename to backend/inference/fast_video_pipeline/nag_config.py index 8930a216a..bd44191fa 100644 --- a/backend/services/fast_video_pipeline/nag_config.py +++ b/backend/inference/fast_video_pipeline/nag_config.py @@ -1,7 +1,7 @@ """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``. +The attention patch lives in ``inference/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: @@ -15,7 +15,7 @@ from dataclasses import dataclass from enum import StrEnum -from runtime_config.nag_limits import ( +from inference.nag_limits import ( DEFAULT_ALPHA, DEFAULT_SCALE, DEFAULT_TAU, diff --git a/backend/services/fast_video_pipeline/nag_distilled.py b/backend/inference/fast_video_pipeline/nag_distilled.py similarity index 95% rename from backend/services/fast_video_pipeline/nag_distilled.py rename to backend/inference/fast_video_pipeline/nag_distilled.py index bdc000ab5..dfd0a2613 100644 --- a/backend/services/fast_video_pipeline/nag_distilled.py +++ b/backend/inference/fast_video_pipeline/nag_distilled.py @@ -6,7 +6,7 @@ 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 +The attention change is in ``inference/patches/nag_cross_attention.py``. A job with no ``NagConfig`` takes none of these steps. """ @@ -20,8 +20,8 @@ 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 +from inference.fast_video_pipeline.nag_config import NagConfig +from inference.patches.nag_cross_attention import NagState, nag_scope _T = TypeVar("_T") _RunCtx = TypeVar("_RunCtx") diff --git a/backend/services/fast_video_pipeline/windowed_run.py b/backend/inference/fast_video_pipeline/windowed_run.py similarity index 70% rename from backend/services/fast_video_pipeline/windowed_run.py rename to backend/inference/fast_video_pipeline/windowed_run.py index 41bf0dfab..24a48ade0 100644 --- a/backend/services/fast_video_pipeline/windowed_run.py +++ b/backend/inference/fast_video_pipeline/windowed_run.py @@ -3,27 +3,20 @@ from __future__ import annotations import logging -import sys from contextlib import AbstractContextManager, nullcontext -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Protocol import torch -from frame_math import AutoDurationSpec, compute_num_frames -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 ( +from inference.fast_chunking import CARRY_FRAMES, is_chunked_canvas, last_window_frames +from inference.frame_math import AutoDurationSpec, compute_num_frames +from inference.ic_lora_pipeline.ic_lora_inference import ( InferenceResult, close_streams, plan_chunks, ) -from services.ltx_pipeline_common import encode_segments_output, video_chunks_number -from services.phase_log import measured_gpu_phase +from inference.common import encode_segments_output, video_chunks_number +from inference.phase_log import measured_gpu_phase if TYPE_CHECKING: from ltx_pipelines.chunks import ChunkConfig @@ -33,6 +26,22 @@ LOG_PREFIX = "[hires-video]" +class WindowEstimate(Protocol): + def __call__( + self, + *, + width: int, + height: int, + frames: int, + windows: int, + last_frames: int, + ) -> float: ... + + +class EditEstimate(Protocol): + def __call__(self, *, width: int, height: int, frames: int) -> float: ... + + def _longest_frames(num_frames: int | AutoDurationSpec, frame_rate: float) -> int: """An automatic duration is counted at its longest.""" if isinstance(num_frames, AutoDurationSpec): @@ -68,6 +77,7 @@ def measured_windows( num_frames: int | AutoDurationSpec, frame_rate: float, device: torch.device, + estimate_gib: WindowEstimate | None = None, ) -> AbstractContextManager[None]: """Phase and peak-VRAM log for a 1440p or 4K run, windowed or one pass. Other runs keep their own logs.""" if chunk_config is None: @@ -92,16 +102,27 @@ def measured_windows( label, device=device, prefix=LOG_PREFIX, - estimate_gib=fast_job_stream_gib( - video_tokens(height, width, frames), - windows=window_count, - darwin=sys.platform == "darwin", - last_tokens=video_tokens(height, width, last_frames), + estimate_gib=( + None + if estimate_gib is None + else estimate_gib( + width=width, + height=height, + frames=frames, + windows=window_count, + last_frames=last_frames, + ) ), ) -def measured_edit(width: int, height: int, frames: int) -> AbstractContextManager[None]: +def measured_edit( + width: int, + height: int, + frames: int, + *, + estimate_gib: EditEstimate | None = None, +) -> AbstractContextManager[None]: """Phase and peak-VRAM log for a 1440p or 4K Retake or Extend run. Other sizes keep their own logs.""" if not is_chunked_canvas(width, height): return nullcontext() @@ -110,10 +131,10 @@ def measured_edit(width: int, height: int, frames: int) -> AbstractContextManage f"edit {width}x{height}, {frames} frames", device=torch.device("cuda"), prefix=LOG_PREFIX, - estimate_gib=edit_job_stream_gib( - video_tokens(height, width, frames), - darwin=sys.platform == "darwin", - decode_tokens=decode_tile_tokens(height, width, frames), + estimate_gib=( + None + if estimate_gib is None + else estimate_gib(width=width, height=height, frames=frames) ), ) diff --git a/backend/inference/ffmpeg.py b/backend/inference/ffmpeg.py new file mode 100644 index 000000000..4ad006b2e --- /dev/null +++ b/backend/inference/ffmpeg.py @@ -0,0 +1,135 @@ +"""ffmpeg invocation for inference stitch/restamp. No desktop ``services.records``.""" + +from __future__ import annotations + +import logging +import subprocess +import time +from collections.abc import Callable + +import imageio_ffmpeg + +logger = logging.getLogger(__name__) + +# Local file outputs and inputs only, plus pipe for stdio-style transports. +FFMPEG_PROTOCOL_WHITELIST = "file,pipe" +# Re-encoding a long import can legitimately take tens of seconds. +FFMPEG_TIMEOUT_SECONDS = 120.0 +# A stitch re-encode is slower than realtime on CPU. Floor at the shared timeout +# and cap so one long source cannot hold the worker all day. +STITCH_TIMEOUT_PER_SOURCE_SECOND = 8.0 +STITCH_TIMEOUT_CAP_SECONDS = 1800.0 +# Slowest encode of a frame that we plan for. The timeout is a ceiling, not a target. +_PIXELS_PER_SECOND = 10_000_000 +PIXEL_TIMEOUT_CAP_SECONDS = 3600.0 +_STDERR_LOG_CHARS = 800 +_CANCEL_POLL_SECONDS = 0.2 + + +class FfmpegCancelledError(Exception): + """``should_cancel`` turned true and ffmpeg was killed.""" + + +class FfmpegUnavailableError(Exception): + """ffmpeg could not be started. Safe to surface outside inference.""" + + def __init__(self) -> None: + super().__init__("ffmpeg is not available") + + +class FfmpegTimeoutError(Exception): + """ffmpeg exceeded its deadline. Safe to surface outside inference.""" + + def __init__(self) -> None: + super().__init__("ffmpeg timed out") + + +def timeout_for_source_duration(duration_seconds: float) -> float: + """How long a stitch of a source this long may run ffmpeg.""" + scaled = max(0.0, duration_seconds) * STITCH_TIMEOUT_PER_SOURCE_SECOND + return min(STITCH_TIMEOUT_CAP_SECONDS, max(FFMPEG_TIMEOUT_SECONDS, scaled)) + + +def timeout_for_pixels(width: int, height: int, frames: int) -> float: + """How long an encode of this many pixels may run. Never below the shared timeout. + + A 1080p clip of 10 s stays at the shared timeout. An 8K clip needs minutes. + """ + scaled = max(0, width) * max(0, height) * max(0, frames) / _PIXELS_PER_SECOND + return min(PIXEL_TIMEOUT_CAP_SECONDS, max(FFMPEG_TIMEOUT_SECONDS, scaled)) + + +def ffmpeg_seconds(value: float) -> str: + """``str(1e-05)`` is scientific notation, which ``-ss``/``-t`` reject.""" + return f"{value:.6f}" + + +def _ffmpeg() -> str: + return str(imageio_ffmpeg.get_ffmpeg_exe()) + + +def _run_until_cancelled( + command: list[str], timeout: float, should_cancel: Callable[[], bool] +) -> subprocess.CompletedProcess[bytes]: + """Like ``subprocess.run``, but kills ffmpeg when ``should_cancel`` turns true.""" + deadline = time.monotonic() + timeout + with subprocess.Popen( + command, stdout=subprocess.PIPE, stderr=subprocess.PIPE + ) as process: + while True: + try: + stdout, stderr = process.communicate(timeout=_CANCEL_POLL_SECONDS) + except subprocess.TimeoutExpired: + if should_cancel(): + process.kill() + process.communicate() + raise FfmpegCancelledError() from None + if time.monotonic() >= deadline: + process.kill() + process.communicate() + raise subprocess.TimeoutExpired(command, timeout) from None + continue + return subprocess.CompletedProcess( + process.args, process.returncode, stdout, stderr + ) + + +def run_ffmpeg( + args: list[str], + *, + ffmpeg_exe: str | list[str] | None = None, + timeout: float = FFMPEG_TIMEOUT_SECONDS, + check: bool = True, + should_cancel: Callable[[], bool] | None = None, +) -> subprocess.CompletedProcess[bytes]: + try: + if ffmpeg_exe is None: + command = [_ffmpeg()] + elif isinstance(ffmpeg_exe, str): + command = [ffmpeg_exe] + else: + command = ffmpeg_exe + full_command = [*command, "-nostdin", *args] + if should_cancel is None: + completed = subprocess.run( + full_command, + check=False, + capture_output=True, + timeout=timeout, + ) + else: + completed = _run_until_cancelled(full_command, timeout, should_cancel) + except FileNotFoundError as exc: + raise FfmpegUnavailableError() from exc + except subprocess.TimeoutExpired as exc: + raise FfmpegTimeoutError() from exc + if check and completed.returncode != 0: + # Logged only: stderr carries local paths that must not reach responses (CWE-209). + stderr = completed.stderr.decode("utf-8", "replace") if completed.stderr else "" + logger.warning( + "ffmpeg exited %s: %s", completed.returncode, stderr[-_STDERR_LOG_CHARS:] + ) + raise subprocess.CalledProcessError( + completed.returncode, completed.args, completed.stdout, completed.stderr + ) + return completed diff --git a/backend/inference/finite_guard.py b/backend/inference/finite_guard.py new file mode 100644 index 000000000..84581668c --- /dev/null +++ b/backend/inference/finite_guard.py @@ -0,0 +1,40 @@ +"""Fail a Mac generation when a denoise step returns NaN or Inf. + +A non-finite latent decodes to a solid green video, and the job still ends as succeeded +(LTX-Desktop#199). The check reads the host once per denoiser call, so it runs on MPS only. +CUDA keeps its asynchronous queue. +""" + +from __future__ import annotations + +from collections.abc import Callable +from typing import Any + +import torch + + +class NonFiniteLatentError(RuntimeError): + def __init__(self, modality: str) -> None: + super().__init__( + f"A {modality} denoise step returned NaN or Inf values. " + "The output would be corrupt, so the job was stopped." + ) + + +def raise_if_nonfinite(result: Any) -> None: + """Raise when a denoiser result (a ``VideoAudio``) holds a non-finite ``denoised`` tensor on MPS.""" + for modality in ("video", "audio"): + denoised = getattr(getattr(result, modality, None), "denoised", None) + if not isinstance(denoised, torch.Tensor) or denoised.device.type != "mps": + continue + if not bool(torch.isfinite(denoised).all()): + raise NonFiniteLatentError(modality) + + +def wrap_denoiser(denoiser: Callable[..., Any]) -> Callable[..., Any]: + def wrapped(*args: Any, **kwargs: Any) -> Any: + result = denoiser(*args, **kwargs) + raise_if_nonfinite(result) + return result + + return wrapped diff --git a/backend/frame_math.py b/backend/inference/frame_math.py similarity index 100% rename from backend/frame_math.py rename to backend/inference/frame_math.py diff --git a/shared/ic-lora-tiling-controls.json b/backend/inference/ic-lora-tiling-controls.json similarity index 100% rename from shared/ic-lora-tiling-controls.json rename to backend/inference/ic-lora-tiling-controls.json diff --git a/backend/inference/ic_lora_pipeline/__init__.py b/backend/inference/ic_lora_pipeline/__init__.py new file mode 100644 index 000000000..536ead043 --- /dev/null +++ b/backend/inference/ic_lora_pipeline/__init__.py @@ -0,0 +1,3 @@ +from inference.ic_lora_pipeline.ic_lora_pipeline import IcLoraPipeline + +__all__ = ["IcLoraPipeline"] diff --git a/backend/services/ic_lora_pipeline/ic_lora_inference.py b/backend/inference/ic_lora_pipeline/ic_lora_inference.py similarity index 95% rename from backend/services/ic_lora_pipeline/ic_lora_inference.py rename to backend/inference/ic_lora_pipeline/ic_lora_inference.py index e2e580f46..5697425ad 100644 --- a/backend/services/ic_lora_pipeline/ic_lora_inference.py +++ b/backend/inference/ic_lora_pipeline/ic_lora_inference.py @@ -9,11 +9,11 @@ import torch -from runtime_config.ic_lora_chunking import IC_LORA_CHUNK_CARRY_FRAMES -from services.audio_channels import stereo_waveform -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 +from inference.ic_lora_tiling import IC_LORA_CHUNK_CARRY_FRAMES +from inference.audio_channels import stereo_waveform +from inference.fast_video_pipeline.nag_config import NagConfig +from inference.common import encode_segments_output, video_chunks_number +from inference.common import AudioOrNone, PipelineTilingType, TilingConfigType if TYPE_CHECKING: from ltx_pipelines.chunks import ChunkConfig diff --git a/backend/services/ic_lora_pipeline/ic_lora_pipeline.py b/backend/inference/ic_lora_pipeline/ic_lora_pipeline.py similarity index 89% rename from backend/services/ic_lora_pipeline/ic_lora_pipeline.py rename to backend/inference/ic_lora_pipeline/ic_lora_pipeline.py index 64a04b312..8cc53cdf3 100644 --- a/backend/services/ic_lora_pipeline/ic_lora_pipeline.py +++ b/backend/inference/ic_lora_pipeline/ic_lora_pipeline.py @@ -4,9 +4,9 @@ from typing import TYPE_CHECKING, Protocol -from api_types import ImageConditioningInput -from runtime_config.ic_lora_tiling import IcLoraTiling -from services.fast_video_pipeline.nag_config import NagConfig +from inference.types import ImageConditioningInput +from inference.ic_lora_tiling import IcLoraTiling +from inference.fast_video_pipeline.nag_config import NagConfig if TYPE_CHECKING: import torch diff --git a/backend/services/ic_lora_pipeline/ltx_ic_lora_pipeline.py b/backend/inference/ic_lora_pipeline/ltx_ic_lora_pipeline.py similarity index 96% rename from backend/services/ic_lora_pipeline/ltx_ic_lora_pipeline.py rename to backend/inference/ic_lora_pipeline/ltx_ic_lora_pipeline.py index a3590d3f2..7899b1025 100644 --- a/backend/services/ic_lora_pipeline/ltx_ic_lora_pipeline.py +++ b/backend/inference/ic_lora_pipeline/ltx_ic_lora_pipeline.py @@ -16,19 +16,18 @@ import torch from numpy.typing import NDArray -from api_types import ImageConditioningInput -from runtime_config.ic_lora_chunking import ic_lora_carry_frames -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 ( +from inference.types import ImageConditioningInput +from inference.ic_lora_tiling import IcLoraTiling, ic_lora_carry_frames +from inference.fast_video_pipeline.nag_config import NagConfig +from inference.run_peak import fold_and_reset_cuda_peak +from inference.ic_lora_pipeline.ic_lora_inference import ( InferenceResult, PipelineKwargs, encode_result, inference_result_from_output, plan_chunks, ) -from services.ltx_pipeline_common import ( +from inference.common import ( auto_tiling_config, build_model_paths, is_decode_tile_shortage, @@ -36,7 +35,8 @@ resolve_tiling_config, to_ltx_images, ) -from services.services_utils import PipelineTilingType, TilingConfigType, device_supports_fp8 +from inference.device import device_supports_fp8 +from inference.common import PipelineTilingType, TilingConfigType if TYPE_CHECKING: from ltx_pipelines.chunks import ChunkConfig @@ -100,7 +100,7 @@ def __init__( 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 - from services.ic_lora_pipeline.tiled_ic_lora_pipeline import TiledICLoraPipeline + from inference.ic_lora_pipeline.tiled_ic_lora_pipeline import TiledICLoraPipeline self._device = device self._stage_2_ic_lora = stage_2_ic_lora @@ -393,7 +393,7 @@ def generate( free_gb, ) def _attempt(tiling_config: PipelineTilingType) -> None: - from services.denoising_progress import distilled_total_steps, track_denoising + from inference.progress import distilled_total_steps, track_denoising try: with track_denoising(distilled_total_steps(stage_2=not skip_stage_2) * chunk_count): diff --git a/backend/services/ic_lora_pipeline/tiled_ic_lora_pipeline.py b/backend/inference/ic_lora_pipeline/tiled_ic_lora_pipeline.py similarity index 97% rename from backend/services/ic_lora_pipeline/tiled_ic_lora_pipeline.py rename to backend/inference/ic_lora_pipeline/tiled_ic_lora_pipeline.py index ce95ed54a..c19a04d18 100644 --- a/backend/services/ic_lora_pipeline/tiled_ic_lora_pipeline.py +++ b/backend/inference/ic_lora_pipeline/tiled_ic_lora_pipeline.py @@ -29,9 +29,9 @@ 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 +from inference.types import REFERENCE_STILL_FRAME_IDX +from inference.fast_video_pipeline.nag_config import NagConfig +from inference.fast_video_pipeline.nag_distilled import NagDistilledMixin logger = logging.getLogger(__name__) diff --git a/backend/runtime_config/ic_lora_tiling.py b/backend/inference/ic_lora_tiling.py similarity index 95% rename from backend/runtime_config/ic_lora_tiling.py rename to backend/inference/ic_lora_tiling.py index fe5a35386..6fcb36226 100644 --- a/backend/runtime_config/ic_lora_tiling.py +++ b/backend/inference/ic_lora_tiling.py @@ -20,9 +20,9 @@ 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" +# The limits and the defaults of the tile overlap and the window carry. The Home form +# reads the same file, next to this module, so a copy of inference/ still imports. +_CONTROLS_PATH: Final = Path(__file__).resolve().with_name("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 @@ -244,3 +244,14 @@ def with_tiling_overrides( if not isinstance(original, Exception): raise ValueError("invalid tiling") from exc raise ValueError(str(original)) from exc + + +# ltx-pipelines default carry, used when a job has no LoRA-specific window. +IC_LORA_CHUNK_CARRY_FRAMES = DEFAULT_CARRY_FRAMES + + +def ic_lora_carry_frames(tiling: IcLoraTiling | None) -> int: + """The carry an IC-LoRA run chunks with: the LoRA's own, else the pipeline default.""" + if tiling is not None and tiling.carry_frames is not None: + return tiling.carry_frames + return IC_LORA_CHUNK_CARRY_FRAMES diff --git a/backend/services/generation_interrupt.py b/backend/inference/interrupt.py similarity index 100% rename from backend/services/generation_interrupt.py rename to backend/inference/interrupt.py diff --git a/backend/inference/job_budget.py b/backend/inference/job_budget.py new file mode 100644 index 000000000..ed8a039bb --- /dev/null +++ b/backend/inference/job_budget.py @@ -0,0 +1,9 @@ +"""Token count used by Pod logs. Desktop stream-GiB curves stay in ``runtime_config``.""" + +from __future__ import annotations + + +def video_tokens(height: int, width: int, frames: int) -> float: + """LTX-2 latent tokens: 8-frame temporal, 32 px spatial.""" + temporal = (max(1, frames) - 1) / 8.0 + 1.0 + return temporal * (height / 32.0) * (width / 32.0) diff --git a/backend/inference/layout.py b/backend/inference/layout.py new file mode 100644 index 000000000..42c9d6d81 --- /dev/null +++ b/backend/inference/layout.py @@ -0,0 +1,116 @@ +"""Optional Desktop ``models/`` path table. The image must not call this module.""" + +from __future__ import annotations + +from dataclasses import dataclass +from pathlib import Path +from typing import Literal, TypeAlias, assert_never + +# 2.5-native weights live under this family dir. 2.3 and shared tooling stay at models_root. +# 2.5.1 patches use new filenames in the same dir — not a nested ltx-2.5.1/. +LTX_2_5_FAMILY_DIR = Path("ltx-2.5") + +# Same ids as Desktop ``api_types.ModelCheckpointID``. Duplicated so this module +# never imports ``api_types``. +CheckpointId: TypeAlias = Literal[ + "ltx-2.3-22b-distilled", + "ltx-2.3-22b-distilled-1.1", + "ltx-2.3-spatial-upscaler-x2-1.0", + "ltx-2.3-spatial-upscaler-x2-1.1", + "ltx-2.3-22b-ic-lora-union-control-ref0.5", + "ltx-2.5-22b-distilled", + "ltx-2.5-spatial-upscaler-x2-1.0", + "ltx-2.5-video-vae", + "ltx-2.5-video-vae-conv", + "ltx-2.5-audio-vae", + "ltx-2.5-duration-head", + "dpt-hybrid-midas", + "yolox-l-torchscript", + "dw-ll-ucoco-384-bs5", + "gemma-3-12b-it-qat-q4_0-unquantized", + "gemma4-12b-with-proj-ltx-2.5", + "gemma-4-e2b-it", + "z-image-turbo", +] + + +@dataclass(frozen=True, slots=True) +class CheckpointLayout: + """Relative location of one checkpoint under a Desktop ``models/`` folder.""" + + relative_path: Path + is_folder: bool + + +@dataclass(frozen=True, slots=True) +class ResolvedLtxModelPaths: + """Filesystem paths for the active local LTX model bundle.""" + + checkpoint_path: str + upsampler_path: str + gemma_root: str | None + video_vae_path: str | None + audio_vae_path: str | None + duration_head_path: str | None + + +def get_checkpoint_layout(cp_id: CheckpointId) -> CheckpointLayout: + """Desktop ``models/`` relative path and folder-vs-file for ``cp_id``.""" + match cp_id: + case "ltx-2.3-22b-distilled": + return CheckpointLayout(Path("ltx-2.3-22b-distilled.safetensors"), False) + case "ltx-2.3-22b-distilled-1.1": + return CheckpointLayout(Path("ltx-2.3-22b-distilled-1.1.safetensors"), False) + case "ltx-2.3-spatial-upscaler-x2-1.0": + return CheckpointLayout(Path("ltx-2.3-spatial-upscaler-x2-1.0.safetensors"), False) + case "ltx-2.3-spatial-upscaler-x2-1.1": + return CheckpointLayout(Path("ltx-2.3-spatial-upscaler-x2-1.1.safetensors"), False) + case "ltx-2.3-22b-ic-lora-union-control-ref0.5": + return CheckpointLayout( + Path("ltx-2.3-22b-ic-lora-union-control-ref0.5.safetensors"), False + ) + case "ltx-2.5-22b-distilled": + return CheckpointLayout( + LTX_2_5_FAMILY_DIR / "ltx-2.5-22b-distilled-transformer-bf16.safetensors", + False, + ) + case "ltx-2.5-spatial-upscaler-x2-1.0": + return CheckpointLayout( + LTX_2_5_FAMILY_DIR / "ltx-2.5-latent-spatial-upscaler-x2-bf16-1.0.safetensors", + False, + ) + case "ltx-2.5-video-vae": + return CheckpointLayout( + LTX_2_5_FAMILY_DIR / "ltx-2.5-video-vae-bf16.safetensors", False + ) + case "ltx-2.5-video-vae-conv": + return CheckpointLayout( + LTX_2_5_FAMILY_DIR / "ltx-2.5-video-vae-conv-bf16.safetensors", False + ) + case "ltx-2.5-audio-vae": + return CheckpointLayout( + LTX_2_5_FAMILY_DIR / "ltx-2.5-audio-vae-bf16.safetensors", False + ) + case "ltx-2.5-duration-head": + return CheckpointLayout( + LTX_2_5_FAMILY_DIR / "ltx-2.5-duration-head-bf16.safetensors", False + ) + case "dpt-hybrid-midas": + return CheckpointLayout(Path("dpt-hybrid-midas"), True) + case "yolox-l-torchscript": + return CheckpointLayout(Path("yolox_l.torchscript.pt"), False) + case "dw-ll-ucoco-384-bs5": + return CheckpointLayout(Path("dw-ll_ucoco_384_bs5.torchscript.pt"), False) + case "gemma-3-12b-it-qat-q4_0-unquantized": + return CheckpointLayout(Path("gemma-3-12b-it-qat-q4_0-unquantized"), True) + case "gemma4-12b-with-proj-ltx-2.5": + return CheckpointLayout( + LTX_2_5_FAMILY_DIR / "gemma4-12b-with-proj-ltx-2.5-bf16.safetensors", + False, + ) + case "gemma-4-e2b-it": + return CheckpointLayout(Path("gemma-4-E2B-it"), True) + case "z-image-turbo": + return CheckpointLayout(Path("Z-Image-Turbo"), True) + case _: + assert_never(cp_id) diff --git a/backend/inference/media.py b/backend/inference/media.py new file mode 100644 index 000000000..7e29bdc96 --- /dev/null +++ b/backend/inference/media.py @@ -0,0 +1,10 @@ +"""Tiny media helpers the Pod pipelines need. No desktop ``services.media_probe``.""" + +from __future__ import annotations + +import av + + +def media_has_audio(path: str) -> bool: + with av.open(path) as container: + return any(stream.type == "audio" for stream in container.streams) diff --git a/backend/runtime_config/nag_limits.py b/backend/inference/nag_limits.py similarity index 100% rename from backend/runtime_config/nag_limits.py rename to backend/inference/nag_limits.py diff --git a/backend/inference/patches/__init__.py b/backend/inference/patches/__init__.py new file mode 100644 index 000000000..250d9315e --- /dev/null +++ b/backend/inference/patches/__init__.py @@ -0,0 +1 @@ +"""CUDA/shared ltx-core monkey-patches. Darwin/MPS patches stay in services.patches.""" diff --git a/backend/services/patches/diffusion_interrupt.py b/backend/inference/patches/diffusion_interrupt.py similarity index 90% rename from backend/services/patches/diffusion_interrupt.py rename to backend/inference/patches/diffusion_interrupt.py index d93276285..83e134d14 100644 --- a/backend/services/patches/diffusion_interrupt.py +++ b/backend/inference/patches/diffusion_interrupt.py @@ -7,7 +7,7 @@ Wrapping ``loop`` and intercepting ``tqdm`` iterations counts real denoise steps once per loop iteration (not once per denoiser call). Totals come from -``services.denoising_progress.distilled_total_steps``, which uses the same +``inference.progress.distilled_total_steps``, which uses the same sigma schedules the pipelines pass in. Step-based progress reporting was proposed by Sergio Gil (@jimeneztion). @@ -22,7 +22,7 @@ Remove once ltx-pipelines denoiser/loop accepts an interrupt callback. Usage: - import services.patches.diffusion_interrupt # noqa: F401 + import inference.patches.diffusion_interrupt # noqa: F401 """ from __future__ import annotations @@ -36,7 +36,8 @@ from ltx_pipelines.utils.blocks import DiffusionStage -from services.generation_interrupt import wrap_denoiser +from inference.finite_guard import wrap_denoiser as wrap_finite +from inference.interrupt import wrap_denoiser assert callable(getattr(DiffusionStage, "__call__", None)), ( "ltx_pipelines.utils.blocks.DiffusionStage.__call__ missing — re-verify this patch on rev bump" @@ -62,7 +63,7 @@ def flush_completed(self) -> None: happens even though the denoise ran. Flush only after a normal return — cancel/exception must not count the aborted iteration. """ - from services.denoising_progress import note_step + from inference.progress import note_step while self.counted < self.yielded: self.counted += 1 @@ -74,7 +75,7 @@ def _count_tqdm_iterations() -> Iterator[_TqdmStepCount]: """Count each sampler-loop tqdm iteration as one denoise step.""" import ltx_pipelines.utils.samplers as samplers - from services.denoising_progress import note_step + from inference.progress import note_step original_tqdm = samplers.tqdm state = _TqdmStepCount() @@ -118,7 +119,9 @@ def _call_with_interrupt(self: DiffusionStage, *args: Any, **kwargs: Any) -> Any bound.apply_defaults() if "denoiser" not in bound.arguments: raise TypeError("DiffusionStage.__call__ missing required argument: 'denoiser'") - bound.arguments["denoiser"] = wrap_denoiser(cast(Callable[..., Any], bound.arguments["denoiser"])) + bound.arguments["denoiser"] = wrap_denoiser( + wrap_finite(cast(Callable[..., Any], bound.arguments["denoiser"])) + ) if "loop" in bound.arguments: loop = bound.arguments["loop"] if loop is None: diff --git a/backend/services/patches/diffusion_stage_cache.py b/backend/inference/patches/diffusion_stage_cache.py similarity index 96% rename from backend/services/patches/diffusion_stage_cache.py rename to backend/inference/patches/diffusion_stage_cache.py index 88f252e11..c2a682d7f 100644 --- a/backend/services/patches/diffusion_stage_cache.py +++ b/backend/inference/patches/diffusion_stage_cache.py @@ -94,8 +94,13 @@ ``start_api_generation`` push the live setting into :func:`set_enabled` on every generation, so flipping it in Settings takes effect on the next generation without a restart. Also settable via env -``DIFFUSION_STAGE_CACHE_ENABLED`` (default "1") as the initial value before -any setting is pushed -- e.g. for headless/dev runs. +``DIFFUSION_STAGE_CACHE_ENABLED`` (default ``"0"``) before any setting is pushed. + +The import-time default is off. A host that wants the cache has to opt in, and +it owns the lifecycle this module does not run for it: ``set_enabled`` from its +setting, :func:`evict` before each job so a transformer does not survive into +the next one, and ``inference.interrupt.clear`` before each job so a previous +cancel does not abort the next. Desktop ``GenerationHandler`` does all three. EXPERIMENTAL: depends on DiffusionStage's private ``_is_streaming``, ``_prepared_builder()``, ``_build_transformer()``, ``_quantization``, @@ -104,7 +109,7 @@ against ltx_pipelines.utils.blocks.DiffusionStage on rev bumps. Usage: - import services.patches.diffusion_stage_cache # noqa: F401 + import inference.patches.diffusion_stage_cache # noqa: F401 """ from __future__ import annotations @@ -139,7 +144,7 @@ _CacheKey = tuple[object, ...] _lock = threading.Lock() -_enabled = os.environ.get("DIFFUSION_STAGE_CACHE_ENABLED", "1") != "0" +_enabled = os.environ.get("DIFFUSION_STAGE_CACHE_ENABLED", "0") != "0" _cached_key: _CacheKey | None = None _cached_model: object | None = None _logged_wrapper_skip = False diff --git a/backend/services/patches/diffvae_decode_vram.py b/backend/inference/patches/diffvae_decode_vram.py similarity index 98% rename from backend/services/patches/diffvae_decode_vram.py rename to backend/inference/patches/diffvae_decode_vram.py index aab28b357..195f6c726 100644 --- a/backend/services/patches/diffvae_decode_vram.py +++ b/backend/inference/patches/diffvae_decode_vram.py @@ -31,7 +31,7 @@ resolves AUTO_TILING against that post-offload budget with a max-tile constraint. Usage: - import services.patches.diffvae_decode_vram # noqa: F401 + import inference.patches.diffvae_decode_vram # noqa: F401 """ from __future__ import annotations @@ -50,8 +50,8 @@ from ltx_pipelines.utils.blocks import VideoDecoder from ltx_pipelines.utils.helpers import cleanup_memory, tiling_config_for_vae -from services.ltx_pipeline_common import is_decode_tile_shortage -from services.patches import diffusion_stage_cache +from inference.common import is_decode_tile_shortage +from inference.patches import diffusion_stage_cache logger = logging.getLogger(__name__) diff --git a/backend/inference/patches/gemma_assets_positional_read.py b/backend/inference/patches/gemma_assets_positional_read.py new file mode 100644 index 000000000..0bc4f953b --- /dev/null +++ b/backend/inference/patches/gemma_assets_positional_read.py @@ -0,0 +1,205 @@ +"""Monkey-patch: ``GemmaAssets.from_single_file`` reads the packed text encoder without mmap. + +Upstream opens the single-file Gemma text encoder (~26 GB for LTX 2.5) with +``safetensors.safe_open(..., framework="pt")`` and reads the tokenizer (~32 MB) and a few small +sidecars with ``get_tensor``. With the torch framework, ``get_tensor`` maps the whole file through +``torch.UntypedStorage.from_file(shared=False)``. On Windows that mapping can end in a native +access violation (exit code 3221225477 / 0xC0000005) inside ``torch/storage.py __getitem__``, which +kills the backend process and marks the running job INTERRUPTED +(https://github.com/Lightricks/LTX-Desktop/issues/203). + +This patch parses the safetensors header with plain positional file reads and reads only the bytes +of the tensors it needs. Output is byte-identical to upstream for ``U8`` and ``I8`` tensors, which +is what the packer writes. It is installed on Windows only. Other platforms keep the upstream +read, which has no reported failure. + +The file is user-supplied, so every read is bounded and checked before it is trusted: +- the header length is capped (the same 100 MB limit safetensors enforces), +- every ``data_offsets`` pair must lie inside the file and match the tensor shape, +- the total asset bytes read are capped. +Anything unexpected (other dtype, odd header, cap exceeded, short read) falls back to the original +implementation. Missing ``gemma_config`` metadata or a missing tokenizer tensor raise the same +``ValueError`` as upstream. + +Not replaced: ``_gemma4_unified_is_comfy_flat`` in ``ltx_core`` opens the same file with +``safe_open`` only to list tensor names. It never calls ``get_tensor``, so it does not create the +torch storage that crashed in the report. Revisit it if a crash points there. + +Remove once ``GemmaAssets.from_single_file`` reads without mapping the whole file, and a Windows +machine with the 26 GB text encoder generates without an access violation without this patch. + +Usage: + import inference.patches.gemma_assets_positional_read # noqa: F401 +""" + +from __future__ import annotations + +import json +import logging +import math +import os +import struct +import sys +from pathlib import Path +from typing import Any, BinaryIO, cast + +from ltx_core.text_encoders.gemma import gemma_assets as _gemma_assets +from ltx_core.text_encoders.gemma.gemma_assets import GemmaAssets + +logger = logging.getLogger(__name__) + +# safetensors rejects headers above 100 MB. A real packed text encoder header is far smaller. +_MAX_HEADER_BYTES = 100_000_000 +# tokenizer_json is ~32 MB for Gemma 4. All sidecars together stay far below this cap. +_MAX_ASSET_BYTES = 256 * 1024 * 1024 +# Only one-byte integer dtypes round-trip to the same bytes as upstream ``_tensor_to_bytes``. +_BYTE_DTYPES = frozenset({"U8", "I8"}) + +_FROM_SINGLE_FILE = "from_single_file" +_original_from_single_file = cast(Any, GemmaAssets.__dict__.get(_FROM_SINGLE_FILE)) +_logged_active = False + + +class _Unsupported(Exception): + """The file is not in the narrow layout this patch handles. Use the upstream read.""" + + +def _read_exact(fh: BinaryIO, size: int) -> bytes: + data = fh.read(size) + if len(data) != size: + raise _Unsupported(f"short read: wanted {size} bytes, got {len(data)}") + return data + + +def _read_header(fh: BinaryIO, file_size: int) -> tuple[dict[str, Any], int]: + """Return the JSON header and the offset where tensor data starts.""" + (header_size,) = struct.unpack(" _MAX_HEADER_BYTES or 8 + header_size > file_size: + raise _Unsupported(f"header size {header_size} is out of range for a {file_size}-byte file") + try: + header = json.loads(_read_exact(fh, header_size).decode("utf-8")) + except (UnicodeDecodeError, ValueError) as exc: + raise _Unsupported(f"header is not valid UTF-8 JSON: {exc}") from exc + if not isinstance(header, dict): + raise _Unsupported("header is not a JSON object") + return cast(dict[str, Any], header), 8 + header_size + + +def _is_int(value: object) -> bool: + return isinstance(value, int) and not isinstance(value, bool) + + +class _TensorBytes: + """Bounded positional reader for the one-byte tensors of a safetensors file.""" + + def __init__(self, fh: BinaryIO, header: dict[str, Any], data_start: int, file_size: int) -> None: + self._fh = fh + self._header = header + self._data_start = data_start + self._data_size = file_size - data_start + self._budget = _MAX_ASSET_BYTES + + def read(self, key: str) -> bytes: + info = self._header[key] + if not isinstance(info, dict): + raise _Unsupported(f"tensor {key!r} entry is not an object") + entry = cast(dict[str, Any], info) + if entry.get("dtype") not in _BYTE_DTYPES: + raise _Unsupported(f"tensor {key!r} has dtype {entry.get('dtype')!r}") + shape, offsets = entry.get("shape"), entry.get("data_offsets") + if not isinstance(shape, list) or not all(_is_int(d) and d >= 0 for d in cast(list[Any], shape)): + raise _Unsupported(f"tensor {key!r} has an invalid shape") + if not isinstance(offsets, list) or len(cast(list[Any], offsets)) != 2: + raise _Unsupported(f"tensor {key!r} has invalid data_offsets") + begin, end = cast(list[Any], offsets) + if not (_is_int(begin) and _is_int(end)) or not 0 <= begin <= end <= self._data_size: + raise _Unsupported(f"tensor {key!r} offsets {offsets} are outside the data section") + if end - begin != math.prod(cast(list[int], shape)): + raise _Unsupported(f"tensor {key!r} offsets do not match its shape") + if end - begin > self._budget: + raise _Unsupported(f"tensor {key!r} exceeds the asset size cap") + self._budget -= end - begin + self._fh.seek(self._data_start + begin) + return _read_exact(self._fh, end - begin) + + +def _read_assets(path: Path) -> tuple[dict[str, Any], bytes, dict[str, bytes]]: + """Return ``(config_dict, tokenizer_json, sidecars)``, matching upstream's output.""" + with open(path, "rb") as fh: + file_size = os.fstat(fh.fileno()).st_size + header, data_start = _read_header(fh, file_size) + raw_meta = header.pop("__metadata__", None) or {} + if not isinstance(raw_meta, dict) or not all(isinstance(v, str) for v in cast(dict[Any, Any], raw_meta).values()): + raise _Unsupported("__metadata__ is not a string map") + meta = cast(dict[str, str], raw_meta) + + raw_config = meta.get(_gemma_assets.GEMMA_CONFIG_METADATA_KEY) + if raw_config is None: + raise ValueError( + f"Safetensors text-encoder {path} is missing metadata key " + f"{_gemma_assets.GEMMA_CONFIG_METADATA_KEY!r} (JSON-encoded HuggingFace config)." + ) + config_dict = json.loads(raw_config) + + if _gemma_assets.TOKENIZER_JSON_TENSOR_KEY not in header: + raise ValueError( + f"Safetensors text-encoder {path} is missing tensor {_gemma_assets.TOKENIZER_JSON_TENSOR_KEY!r}." + ) + reader = _TensorBytes(fh, header, data_start, file_size) + tokenizer_json = reader.read(_gemma_assets.TOKENIZER_JSON_TENSOR_KEY) + + sidecars: dict[str, bytes] = {} + for key in header: + if key.startswith(_gemma_assets.HF_ASSET_TENSOR_PREFIX): + sidecars[key.removeprefix(_gemma_assets.HF_ASSET_TENSOR_PREFIX)] = reader.read(key) + + for name in _gemma_assets._METADATA_FALLBACK_FILENAMES: # pyright: ignore[reportPrivateUsage] + if name in sidecars or name not in meta: + continue + sidecars[name] = meta[name].encode() + return cast(dict[str, Any], config_dict), tokenizer_json, sidecars + + +def _patched_from_single_file(cls: type[GemmaAssets], path: Path) -> GemmaAssets: + global _logged_active + path = Path(path) + try: + config_dict, tokenizer_json, sidecars = _read_assets(path) + except _Unsupported as exc: + logger.warning( + "Gemma assets in %s use a layout the positional read does not handle (%s). " + "Falling back to the safetensors mmap read.", + path, + exc, + ) + return _original_from_single_file.__func__(cls, path) + if not _logged_active: + logger.info("Reading single-file Gemma assets with positional reads instead of mmap (LTX-Desktop#203).") + _logged_active = True + + assets = cls( + source=str(path), + config_dict=config_dict, + tokenizer_json=tokenizer_json, + sidecars=sidecars, + weight_paths=(str(path.resolve()),), + ) + assets._require_sidecars(*_gemma_assets._REQUIRED_ASSET_FILENAMES) # pyright: ignore[reportPrivateUsage] + return assets + + +assert isinstance(_original_from_single_file, classmethod), ( + "GemmaAssets.from_single_file is not a classmethod — patch needs updating." +) +for _name in ( + "GEMMA_CONFIG_METADATA_KEY", + "TOKENIZER_JSON_TENSOR_KEY", + "HF_ASSET_TENSOR_PREFIX", + "_METADATA_FALLBACK_FILENAMES", + "_REQUIRED_ASSET_FILENAMES", +): + assert hasattr(_gemma_assets, _name), f"ltx_core gemma_assets.{_name} not found — patch needs updating." + +if sys.platform == "win32": + # GemmaAssets is a frozen dataclass: that only blocks instance writes, not class attributes. + setattr(GemmaAssets, _FROM_SINGLE_FILE, classmethod(_patched_from_single_file)) diff --git a/backend/services/patches/nag_cross_attention.py b/backend/inference/patches/nag_cross_attention.py similarity index 98% rename from backend/services/patches/nag_cross_attention.py rename to backend/inference/patches/nag_cross_attention.py index 2a81a0e59..736dcb482 100644 --- a/backend/services/patches/nag_cross_attention.py +++ b/backend/inference/patches/nag_cross_attention.py @@ -29,7 +29,7 @@ Strict no-op: with no active ``nag_scope`` the upstream method runs unchanged. Usage: - import services.patches.nag_cross_attention # noqa: F401 + import inference.patches.nag_cross_attention # noqa: F401 """ from __future__ import annotations @@ -43,7 +43,7 @@ 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 +from inference.fast_video_pipeline.nag_config import NagConfig assert callable(getattr(BasicAVTransformerBlock, "_apply_text_cross_attention", None)), ( "BasicAVTransformerBlock._apply_text_cross_attention missing - " diff --git a/backend/services/patches/natten_libnatten_gate.py b/backend/inference/patches/natten_libnatten_gate.py similarity index 95% rename from backend/services/patches/natten_libnatten_gate.py rename to backend/inference/patches/natten_libnatten_gate.py index 7e9763e9a..ffc6a7105 100644 --- a/backend/services/patches/natten_libnatten_gate.py +++ b/backend/inference/patches/natten_libnatten_gate.py @@ -15,7 +15,7 @@ Remove once ltx-core's ``natten_available()`` checks ``natten.HAS_LIBNATTEN``. Usage: - import services.patches.natten_libnatten_gate # noqa: F401 + import inference.patches.natten_libnatten_gate # noqa: F401 """ from __future__ import annotations diff --git a/backend/services/patches/pinned_pool_fix.py b/backend/inference/patches/pinned_pool_fix.py similarity index 98% rename from backend/services/patches/pinned_pool_fix.py rename to backend/inference/patches/pinned_pool_fix.py index d4b38327a..f502eda66 100644 --- a/backend/services/patches/pinned_pool_fix.py +++ b/backend/inference/patches/pinned_pool_fix.py @@ -33,7 +33,7 @@ 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 + import inference.patches.pinned_pool_fix # noqa: F401 """ from __future__ import annotations diff --git a/backend/services/patches/safetensors_metadata_fix.py b/backend/inference/patches/safetensors_metadata_fix.py similarity index 77% rename from backend/services/patches/safetensors_metadata_fix.py rename to backend/inference/patches/safetensors_metadata_fix.py index 69b89df70..ef4825d92 100644 --- a/backend/services/patches/safetensors_metadata_fix.py +++ b/backend/inference/patches/safetensors_metadata_fix.py @@ -15,15 +15,16 @@ ``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. +- The Gemma 4 key probe (``_gemma4_unified_is_comfy_flat``): it opens the single-file text + encoder (~26 GB) only to list tensor names. The Windows paging-file check in the manual test + plan (D17) covers it. ``GemmaAssets.from_single_file`` is patched in + ``gemma_assets_positional_read`` (LTX-Desktop#203). 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 + import inference.patches.safetensors_metadata_fix # noqa: F401 """ from __future__ import annotations @@ -41,7 +42,7 @@ def _read_safetensors_header(path: str) -> tuple[dict[str, Any], int]: return header, 8 + header_size -def _read_safetensors_metadata(path: str) -> dict[str, str] | None: +def read_safetensors_metadata(path: str) -> dict[str, str] | None: """Read metadata from a safetensors file header without mmap.""" header, _ = _read_safetensors_header(path) meta = header.get("__metadata__") @@ -64,7 +65,7 @@ def _read_safetensors_metadata(path: str) -> dict[str, str] | None: def _patched_read_lora_reference_downscale_factor(lora_path: str) -> int: try: - meta = _read_safetensors_metadata(lora_path) or {} + meta = read_safetensors_metadata(lora_path) or {} return int(meta.get("reference_downscale_factor", 1)) except Exception: import logging @@ -99,7 +100,7 @@ def _patched_detect_model_version(checkpoint_path: str) -> tuple[int, ...]: logger = logging.getLogger(__name__) try: - meta = _read_safetensors_metadata(checkpoint_path) or {} + meta = read_safetensors_metadata(checkpoint_path) or {} version = meta.get("model_version", "") except Exception: logger.warning("Could not read checkpoint metadata from %s, treating it as unversioned", checkpoint_path) @@ -119,25 +120,3 @@ def _patched_detect_model_version(checkpoint_path: str) -> tuple[int, ...]: # reference (the sampler-selection call site) must be patched too. if hasattr(_distilled_module, _DETECT_VERSION_FN): setattr(_distilled_module, _DETECT_VERSION_FN, _patched_detect_model_version) - - -# --- services.text_encoder.ltx_text_encoder.LTXTextEncoder.get_model_id_from_checkpoint --- - -from services.text_encoder.ltx_text_encoder import LTXTextEncoder - - -def _patched_get_model_id_from_checkpoint(self: LTXTextEncoder, checkpoint_path: str) -> str | None: - try: - meta = _read_safetensors_metadata(checkpoint_path) or {} - if "encrypted_wandb_properties" in meta: - return meta["encrypted_wandb_properties"] - except Exception as exc: - import logging - logging.getLogger(__name__).warning("Could not extract model_id from checkpoint: %s", exc, exc_info=True) - return None - - -assert hasattr(LTXTextEncoder, "get_model_id_from_checkpoint"), ( - "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] diff --git a/backend/inference/phase_log.py b/backend/inference/phase_log.py new file mode 100644 index 000000000..83de30cc1 --- /dev/null +++ b/backend/inference/phase_log.py @@ -0,0 +1,81 @@ +"""Timing / peak-VRAM log for a GPU step. No desktop heartbeat. + +Start, done, and failure lines include this process and its children so a +stalled 4K or 8K run shows host memory, not only the CUDA peak. +""" + +from __future__ import annotations + +import logging +import time +from collections.abc import Iterator +from contextlib import contextmanager +from typing import TYPE_CHECKING + +import psutil + +from inference.run_peak import fold_and_reset_cuda_peak + +if TYPE_CHECKING: + import torch + + +def rss_gb() -> float: + """Memory of this process and its children. ffmpeg holds 10 GB or more at 8K.""" + process = psutil.Process() + total = process.memory_info().rss + for child in process.children(recursive=True): + try: + total += child.memory_info().rss + except psutil.Error: + continue + return total / 1e9 + + +@contextmanager +def measured_gpu_phase( + logger: logging.Logger, + label: str, + *, + device: "torch.device", + prefix: str, + estimate_gib: float | None = None, +) -> Iterator[None]: + """Log start/end of one GPU step and, on CUDA, the peak VRAM of that step.""" + import torch + + started = time.monotonic() + logger.info("%s %s: start (memory %.1f GB)", prefix, label, rss_gb()) + cuda = device.type == "cuda" and torch.cuda.is_available() + if cuda: + fold_and_reset_cuda_peak(device) + try: + yield + except BaseException as exc: + logger.warning( + "%s %s: %s after %.1fs (memory %.1f GB)", + prefix, + label, + type(exc).__name__, + time.monotonic() - started, + rss_gb(), + ) + raise + else: + logger.info( + "%s %s: done in %.1fs (memory %.1f GB)", + prefix, + label, + time.monotonic() - started, + rss_gb(), + ) + finally: + if cuda: + logger.info( + "%s %s: peak VRAM allocated %.1f GiB, reserved %.1f GiB (budget estimate %s)", + prefix, + label, + torch.cuda.max_memory_allocated(device) / 1024**3, + torch.cuda.max_memory_reserved(device) / 1024**3, + "none" if estimate_gib is None else f"{estimate_gib:.1f} GiB", + ) diff --git a/backend/services/denoising_progress.py b/backend/inference/progress.py similarity index 100% rename from backend/services/denoising_progress.py rename to backend/inference/progress.py diff --git a/backend/services/retake_pipeline/__init__.py b/backend/inference/retake_pipeline/__init__.py similarity index 100% rename from backend/services/retake_pipeline/__init__.py rename to backend/inference/retake_pipeline/__init__.py diff --git a/backend/inference/retake_pipeline/audio_latent.py b/backend/inference/retake_pipeline/audio_latent.py new file mode 100644 index 000000000..5de4b3d33 --- /dev/null +++ b/backend/inference/retake_pipeline/audio_latent.py @@ -0,0 +1,51 @@ +"""Audio latent for a source file whose sound may be mono. + +``ltx_pipelines`` ``audio_latent_from_file`` passes the channels of the file to the audio +encoder. The encoder reads two channels, so a mono source fails with a conv shape error. +This function repeats the steps of the library call and makes the sound stereo (see +``inference.audio_channels``). +""" + +from __future__ import annotations + +from typing import cast + +import torch +from ltx_core.model.audio_vae.audio_vae import AudioEncoder +from ltx_core.types import Audio, AudioLatentShape, VideoPixelShape +from ltx_pipelines.utils.helpers import ( + _conform_latent_length, # pyright: ignore[reportPrivateUsage] + decode_audio_from_file, + encode_audio, + is_exr_dir, +) + +from inference.audio_channels import stereo_waveform + + +def as_stereo(audio: Audio) -> Audio: + """Mono plays on both channels, and a layout with more than two keeps its first two.""" + return Audio(waveform=stereo_waveform(audio.waveform), sampling_rate=audio.sampling_rate) + + +def audio_latent_from_file( + *, + audio_encoder: torch.nn.Module, + file_path: str, + output_shape: VideoPixelShape, + device: torch.device, + dtype: torch.dtype, + start_time: float = 0.0, + max_duration: float | None = None, +) -> torch.Tensor | None: + """The result of the library call of the same name. A mono source plays on both channels.""" + if is_exr_dir(file_path): + return None + max_duration = max_duration or output_shape.frames / output_shape.fps + audio = decode_audio_from_file(file_path, device, start_time, max_duration) + if audio is None: + return None + latents = encode_audio(as_stereo(audio), cast(AudioEncoder, audio_encoder), None).to(device, dtype) + return _conform_latent_length( + latents, AudioLatentShape.from_video_pixel_shape(output_shape).frames + ) diff --git a/backend/inference/retake_pipeline/audio_level.py b/backend/inference/retake_pipeline/audio_level.py new file mode 100644 index 000000000..ede2435bc --- /dev/null +++ b/backend/inference/retake_pipeline/audio_level.py @@ -0,0 +1,133 @@ +"""Match the loudness of generated speech to the speech in the source. + +The model often returns speech that is much louder than the source. The stitch joins both +in one track, so the level jumps at the seam. Extend has one seam, Retake has one on each side +of the new part. +""" + +from __future__ import annotations + +import logging + +import numpy as np + +from inference.media import media_has_audio +from inference.retake_pipeline.speech_analysis import ( + ANALYSIS_SAMPLE_RATE, + AUDIO_ERRORS, + decode_mono, + speech_spans, +) +from inference.types import ExtendMode + +logger = logging.getLogger(__name__) + +# Largest correction. A bigger gap is more likely a wrong measurement than a real level. +MAX_CUT_DB = 18.0 +MAX_BOOST_DB = 6.0 +# The source level is read within this many seconds of the seam: the stretch a listener hears +# next to the generated speech. A clip with a loud intro and a quiet end would otherwise be +# matched to its average. A clip shorter than this is read whole. +SEAM_LEVEL_SECONDS = 10.0 + + +def _voiced(samples: np.ndarray) -> np.ndarray | None: + """The speech parts of ``samples`` joined, or ``None`` when there is no speech.""" + rate = ANALYSIS_SAMPLE_RATE + parts = [samples[int(span.start * rate) : int(span.end * rate)] for span in speech_spans(samples, rate)] + return np.concatenate(parts) if parts else None + + +def _rms_db(voiced: np.ndarray) -> float: + return float(20.0 * np.log10(np.sqrt((voiced**2).mean()) + 1e-9)) + + +def speech_level_db(samples: np.ndarray) -> float | None: + """RMS level in dBFS over the speech parts, or ``None`` when there is no speech.""" + voiced = _voiced(samples) + return None if voiced is None else _rms_db(voiced) + + +def generated_gain_db( + *, + source_path: str, + generated_path: str, + mode: ExtendMode, + generated_cut: float, + source_seconds: float, + generated_seconds: float, +) -> float: + """Gain in dB for the generated part, from the cut to the end (``end``) or from the start to + the cut (``start``). ``0.0`` when a level cannot be measured. Best effort.""" + try: + if not media_has_audio(source_path): + return 0.0 + # Only the stretch next to the seam is decoded, not the whole track. The source + # stretch is on the source timeline, so it uses the source length, not the length of + # the stitched output. + if mode == "end": + source_samples = decode_mono( + source_path, source_seconds, start=max(source_seconds - SEAM_LEVEL_SECONDS, 0.0) + ) + generated_samples = decode_mono(generated_path, generated_seconds, start=generated_cut) + else: + source_samples = decode_mono(source_path, source_seconds, end=SEAM_LEVEL_SECONDS) + generated_samples = decode_mono(generated_path, generated_seconds, end=generated_cut) + source = speech_level_db(source_samples) + piece = speech_level_db(generated_samples) + except AUDIO_ERRORS: + logger.warning("Extend level match skipped: could not measure the audio", exc_info=True) + return 0.0 + if source is None or piece is None: + return 0.0 + gain = min(MAX_BOOST_DB, max(-MAX_CUT_DB, source - piece)) + logger.info("Extend level match: source %.1f dB, generated %.1f dB, gain %.1f dB", source, piece, gain) + return gain + + +def retake_gain_db( + *, + source_path: str, + generated_path: str, + mask_start: float, + mask_end: float, + generated_start: float, + source_seconds: float, + generated_seconds: float, +) -> float: + """Gain in dB for the new part of a retake. ``mask_start`` and ``mask_end`` are the selection + on the source timeline, ``generated_start`` is where the selection starts in the generated + file. The new speech is matched to the speech on both sides of the selection, read within + ``SEAM_LEVEL_SECONDS`` of it, since a listener hears both joins. ``0.0`` when a level cannot be + measured. Best effort.""" + try: + if not media_has_audio(source_path): + return 0.0 + neighbours: list[np.ndarray] = [] + if mask_start > 0: + before = decode_mono( + source_path, source_seconds, start=max(mask_start - SEAM_LEVEL_SECONDS, 0.0), end=mask_start + ) + neighbours.append(before) + if mask_end < source_seconds: + after = decode_mono( + source_path, source_seconds, start=mask_end, end=min(mask_end + SEAM_LEVEL_SECONDS, source_seconds) + ) + neighbours.append(after) + generated_samples = decode_mono( + generated_path, + generated_seconds, + start=generated_start, + end=generated_start + (mask_end - mask_start), + ) + except AUDIO_ERRORS: + logger.warning("Retake level match skipped: could not measure the audio", exc_info=True) + return 0.0 + voiced = [part for part in map(_voiced, neighbours) if part is not None] + piece = speech_level_db(generated_samples) + if not voiced or piece is None: + return 0.0 + source = _rms_db(np.concatenate(voiced)) + gain = min(MAX_BOOST_DB, max(-MAX_CUT_DB, source - piece)) + logger.info("Retake level match: source %.1f dB, generated %.1f dB, gain %.1f dB", source, piece, gain) + return gain diff --git a/backend/services/retake_pipeline/extend_stitch.py b/backend/inference/retake_pipeline/extend_stitch.py similarity index 73% rename from backend/services/retake_pipeline/extend_stitch.py rename to backend/inference/retake_pipeline/extend_stitch.py index f95bbac20..fe589b867 100644 --- a/backend/services/retake_pipeline/extend_stitch.py +++ b/backend/inference/retake_pipeline/extend_stitch.py @@ -2,7 +2,7 @@ Ports ltxv-api ``stitch_frames`` / ``stitch_audio`` (``inference/pipelines/src/pipelines/retake/pipeline.py``): RGB ``lerp`` up to -``MAX_FADE_FRAMES``, audio hard-cut at the edit span. +``MAX_FADE_FRAMES``, audio cut at the edit span with a short fade on each side of the cut. """ from __future__ import annotations @@ -12,20 +12,21 @@ import numpy as np -from api_types import ExtendMode -from services.ffmpeg import FFMPEG_PROTOCOL_WHITELIST, run_ffmpeg, timeout_for_source_duration -from services.media_probe import media_has_audio -from handlers.video_resolution import SpatialLetterbox, generation_letterbox -from services.retake_pipeline.rgb_stitch import ( +from inference.ffmpeg import FFMPEG_PROTOCOL_WHITELIST, run_ffmpeg, timeout_for_source_duration +from inference.media import media_has_audio +from inference.retake_pipeline.audio_level import generated_gain_db +from inference.retake_pipeline.letterbox import SpatialLetterbox, generation_letterbox +from inference.types import ExtendMode +from inference.retake_pipeline.rgb_stitch import ( FadeWindow, blend_fade, iter_generated, iter_source, write_rgb_video, ) -from services.retake_pipeline.stitch_audio import AudioPiece, audio_cut_graph -from services.retake_pipeline.stitch_silence import append_silence_input -from services.retake_pipeline.window import ( +from inference.retake_pipeline.stitch_audio import AudioPiece, audio_cut_graph +from inference.retake_pipeline.stitch_silence import append_silence_input +from inference.retake_pipeline.window import ( MASK_DELTA_SECONDS, MAX_FADE_FRAMES, ExtendEncodeWindow, @@ -45,12 +46,19 @@ def fade_window_for_extend( mode: ExtendMode, extend_frames: int, fps: float, + seam_frames: int | None = None, ) -> FadeWindow: + """``seam_frames``: real source frames next to the seam, when the window holds a voice + bridge. The rest of the window is other moments of the source, so the lerp must not + reach into it.""" delta = _mask_delta_frames(fps, window.context_frames) context_end = window.context_frames + extend_frames + real = window.context_frames if seam_frames is None else seam_frames if mode == "end": - return FadeWindow(0, context_end, window.context_frames - delta, context_end) - return FadeWindow(0, context_end, 0, extend_frames + delta) + return FadeWindow( + window.context_frames - real, context_end, window.context_frames - delta, context_end + ) + return FadeWindow(0, extend_frames + real, 0, extend_frames + delta) def _stitched_frames( @@ -107,6 +115,7 @@ def _mux_audio( source_cut: float, generated_cut: float, silence_original: bool, + generated_gain_db: float, timeout: float, ) -> None: args: list[str] = [ @@ -129,13 +138,13 @@ def _mux_audio( graph = audio_cut_graph( [ AudioPiece(source_audio, end=source_cut), - AudioPiece(generated_audio, start=generated_cut), + AudioPiece(generated_audio, start=generated_cut, gain_db=generated_gain_db), ] ) else: graph = audio_cut_graph( [ - AudioPiece(generated_audio, end=generated_cut), + AudioPiece(generated_audio, end=generated_cut, gain_db=generated_gain_db), AudioPiece(source_audio, start=source_cut), ] ) @@ -168,10 +177,11 @@ def stitch_extend_output( extend_frames: int, target_width: int, target_height: int, + seam_frames: int | None = None, ) -> None: box = generation_letterbox(target_width, target_height) fade = fade_window_for_extend( - window, mode=mode, extend_frames=extend_frames, fps=fps + window, mode=mode, extend_frames=extend_frames, fps=fps, seam_frames=seam_frames ) dest = Path(dest_path) generated_has_audio = _has_audio(windowed_path) @@ -205,6 +215,19 @@ def stitch_extend_output( source_frames = ( window.dropped_prefix_frames + window.context_frames + window.dropped_suffix_frames ) + duration = (source_frames + extend_frames) / fps + gain_db = ( + 0.0 + if silence_original + else generated_gain_db( + source_path=source_path, + generated_path=windowed_path, + mode=mode, + generated_cut=generated_cut, + source_seconds=source_frames / fps, + generated_seconds=(window.context_frames + extend_frames) / fps, + ) + ) try: _mux_audio( video_path=str(video_dest), @@ -215,7 +238,8 @@ def stitch_extend_output( source_cut=source_cut, generated_cut=generated_cut, silence_original=silence_original, - timeout=timeout_for_source_duration((source_frames + extend_frames) / fps), + generated_gain_db=gain_db, + timeout=timeout_for_source_duration(duration), ) finally: if video_dest != dest: diff --git a/backend/services/retake_pipeline/frame_rate.py b/backend/inference/retake_pipeline/frame_rate.py similarity index 94% rename from backend/services/retake_pipeline/frame_rate.py rename to backend/inference/retake_pipeline/frame_rate.py index da021d824..db9ec94e9 100644 --- a/backend/services/retake_pipeline/frame_rate.py +++ b/backend/inference/retake_pipeline/frame_rate.py @@ -12,7 +12,7 @@ import os from pathlib import Path -from services.ffmpeg import FFMPEG_PROTOCOL_WHITELIST, run_ffmpeg +from inference.ffmpeg import FFMPEG_PROTOCOL_WHITELIST, run_ffmpeg _RATE_TOLERANCE = 1e-6 diff --git a/backend/services/retake_pipeline/letterbox.py b/backend/inference/retake_pipeline/letterbox.py similarity index 58% rename from backend/services/retake_pipeline/letterbox.py rename to backend/inference/retake_pipeline/letterbox.py index 848aa6416..a78e122a0 100644 --- a/backend/services/retake_pipeline/letterbox.py +++ b/backend/inference/retake_pipeline/letterbox.py @@ -8,10 +8,51 @@ from __future__ import annotations +from dataclasses import dataclass + import numpy as np from PIL import Image -from handlers.video_resolution import SpatialLetterbox +_SPATIAL_FACTOR = 32 + + +@dataclass(frozen=True) +class SpatialLetterbox: + """Picture rect centered on the ÷32 canvas the model actually encodes.""" + + content_width: int + content_height: int + canvas_width: int + canvas_height: int + left: int + top: int + + @property + def right(self) -> int: + return self.canvas_width - self.content_width - self.left + + @property + def bottom(self) -> int: + return self.canvas_height - self.content_height - self.top + + +def generation_letterbox(width: int, height: int) -> SpatialLetterbox: + """Pad ``width``×``height`` up to the next multiple of 32, split evenly. + + An odd remainder gives the extra pixel to the right or the bottom. + """ + canvas_width = ((width + _SPATIAL_FACTOR - 1) // _SPATIAL_FACTOR) * _SPATIAL_FACTOR + canvas_height = ((height + _SPATIAL_FACTOR - 1) // _SPATIAL_FACTOR) * _SPATIAL_FACTOR + pad_x = canvas_width - width + pad_y = canvas_height - height + return SpatialLetterbox( + content_width=width, + content_height=height, + canvas_width=canvas_width, + canvas_height=canvas_height, + left=pad_x // 2, + top=pad_y // 2, + ) def resize_rgb(frame: np.ndarray, width: int, height: int) -> np.ndarray: diff --git a/backend/services/retake_pipeline/ltx_retake_pipeline.py b/backend/inference/retake_pipeline/ltx_retake_pipeline.py similarity index 96% rename from backend/services/retake_pipeline/ltx_retake_pipeline.py rename to backend/inference/retake_pipeline/ltx_retake_pipeline.py index 08d8890e9..4d7b851d9 100644 --- a/backend/services/retake_pipeline/ltx_retake_pipeline.py +++ b/backend/inference/retake_pipeline/ltx_retake_pipeline.py @@ -35,24 +35,24 @@ from ltx_pipelines.utils.media_io import encode_video, get_videostream_metadata 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 ( +from inference.types import ExtendMode +from inference.fast_video_pipeline.nag_config import NagConfig +from inference.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 -from services.retake_pipeline.retake_sampler import resolve_sampler_plan -from services.retake_pipeline.source_encode import ( +from inference.common import build_model_paths, resolve_tiling_config +from inference.patches.nag_cross_attention import NagState, nag_scope +from inference.common import TilingConfigType +from inference.retake_pipeline.frame_rate import restamp_to_source_rate +from inference.retake_pipeline.retake_pipeline import RetakePipeline +from inference.retake_pipeline.retake_sampler import resolve_sampler_plan +from inference.retake_pipeline.source_encode import ( encode_source_video_latent, extend_freeze_pad_frames, source_encode_tiling, ) -from services.retake_pipeline.window import MASK_DELTA_SECONDS +from inference.retake_pipeline.window import MASK_DELTA_SECONDS logger = logging.getLogger(__name__) @@ -253,7 +253,7 @@ def _run( # noqa: PLR0913, PLR0915 from ltx_core.types import AudioLatentShape from ltx_pipelines.utils.constants import DISTILLED_SIGMA_VALUES as _distilled_sigmas from ltx_pipelines.utils.denoisers import GuidedDenoiser, SimpleDenoiser - from ltx_pipelines.utils.helpers import audio_latent_from_file + from inference.retake_pipeline.audio_latent import audio_latent_from_file from ltx_pipelines.utils.types import ModalitySpec is_extend = extend_frames > 0 @@ -482,7 +482,7 @@ def generate( meta = get_videostream_metadata(video_path) fps = meta.fps num_frames = target_frames if target_frames is not None else meta.frames - from services.denoising_progress import track_denoising + from inference.progress import track_denoising plan = resolve_sampler_plan( distilled=distilled, @@ -553,7 +553,7 @@ def extend( fps = meta.fps source_frames = target_frames if target_frames is not None else meta.frames total_frames = source_frames + extend_frames - from services.denoising_progress import track_denoising + from inference.progress import track_denoising plan = resolve_sampler_plan( distilled=distilled, diff --git a/backend/services/retake_pipeline/retake_mode.py b/backend/inference/retake_pipeline/retake_mode.py similarity index 93% rename from backend/services/retake_pipeline/retake_mode.py rename to backend/inference/retake_pipeline/retake_mode.py index e6f5f0b5a..d4ea2ae7c 100644 --- a/backend/services/retake_pipeline/retake_mode.py +++ b/backend/inference/retake_pipeline/retake_mode.py @@ -2,7 +2,7 @@ from __future__ import annotations -from api_types import RetakeMode +from inference.types import RetakeMode class InvalidRetakeModeError(ValueError): diff --git a/backend/services/retake_pipeline/retake_pipeline.py b/backend/inference/retake_pipeline/retake_pipeline.py similarity index 96% rename from backend/services/retake_pipeline/retake_pipeline.py rename to backend/inference/retake_pipeline/retake_pipeline.py index 19aa0c206..29e948acc 100644 --- a/backend/services/retake_pipeline/retake_pipeline.py +++ b/backend/inference/retake_pipeline/retake_pipeline.py @@ -4,8 +4,8 @@ from typing import TYPE_CHECKING, Protocol -from api_types import ExtendMode -from services.fast_video_pipeline.nag_config import NagConfig +from inference.types import ExtendMode +from inference.fast_video_pipeline.nag_config import NagConfig if TYPE_CHECKING: import torch diff --git a/backend/services/retake_pipeline/retake_sampler.py b/backend/inference/retake_pipeline/retake_sampler.py similarity index 97% rename from backend/services/retake_pipeline/retake_sampler.py rename to backend/inference/retake_pipeline/retake_sampler.py index 917554926..abf1c8ba3 100644 --- a/backend/services/retake_pipeline/retake_sampler.py +++ b/backend/inference/retake_pipeline/retake_sampler.py @@ -23,7 +23,7 @@ ) from ltx_pipelines.utils.samplers import euler_ancestral_denoising_loop -from services.denoising_progress import distilled_total_steps +from inference.progress import distilled_total_steps def _distilled_stage_sampler_kwargs( diff --git a/backend/services/retake_pipeline/retake_stitch.py b/backend/inference/retake_pipeline/retake_stitch.py similarity index 84% rename from backend/services/retake_pipeline/retake_stitch.py rename to backend/inference/retake_pipeline/retake_stitch.py index eaff103d0..97a4430bb 100644 --- a/backend/services/retake_pipeline/retake_stitch.py +++ b/backend/inference/retake_pipeline/retake_stitch.py @@ -20,23 +20,24 @@ import numpy as np -from services.ffmpeg import ( +from inference.ffmpeg import ( FFMPEG_PROTOCOL_WHITELIST, run_ffmpeg, timeout_for_source_duration, ) -from services.media_probe import media_has_audio -from handlers.video_resolution import SpatialLetterbox, generation_letterbox -from services.retake_pipeline.rgb_stitch import ( +from inference.media import media_has_audio +from inference.retake_pipeline.audio_level import retake_gain_db +from inference.retake_pipeline.letterbox import SpatialLetterbox, generation_letterbox +from inference.retake_pipeline.rgb_stitch import ( FadeWindow, blend_fade, exact_rate, iter_generated, write_rgb_video, ) -from services.retake_pipeline.stitch_audio import AudioPiece, audio_cut_graph -from services.retake_pipeline.stitch_silence import append_silence_input -from services.retake_pipeline.window import MAX_FADE_FRAMES, RetakeEncodeWindow +from inference.retake_pipeline.stitch_audio import AudioPiece, audio_cut_graph +from inference.retake_pipeline.stitch_silence import append_silence_input +from inference.retake_pipeline.window import MAX_FADE_FRAMES, RetakeEncodeWindow _has_audio = media_has_audio @@ -82,9 +83,15 @@ def reencode_span(window: RetakeEncodeWindow) -> ReencodeSpan: def retake_audio_graph( - window: RetakeEncodeWindow, fps: float, *, source_label: str, generated_label: str = "[2:a]" + window: RetakeEncodeWindow, + fps: float, + *, + source_label: str, + generated_label: str = "[2:a]", + generated_gain_db: float = 0.0, ) -> str: - """Hard-cut audio at the user mask. Video fades; audio does not.""" + """Cut audio at the user mask. Video cross-fades over frames; audio gets a short fade at each cut. + ``generated_gain_db`` levels the new part to the speech around it.""" mask_frames = window.mask_end_frame - window.mask_start_frame generated_start = window.context_before_frames / fps pieces: list[AudioPiece] = [] @@ -95,6 +102,7 @@ def retake_audio_graph( generated_label, start=generated_start, end=(window.context_before_frames + mask_frames) / fps, + gain_db=generated_gain_db, ) ) if window.mask_end_frame < window.source_frames: @@ -166,6 +174,7 @@ def _assemble( box: SpatialLetterbox, generated_has_audio: bool, silence_original: bool, + generated_gain_db: float = 0.0, ) -> None: rate = exact_rate(fps) args: list[str] = [ @@ -184,7 +193,13 @@ def _assemble( if silence_original: append_silence_input(args) source_label = "[3:a]" - graph = graph + ";" + retake_audio_graph(window, fps, source_label=source_label) + graph = ( + graph + + ";" + + retake_audio_graph( + window, fps, source_label=source_label, generated_gain_db=generated_gain_db + ) + ) args.extend( [ "-filter_complex", @@ -229,6 +244,7 @@ def stitch_retake_output( fps: float, target_width: int, target_height: int, + regenerate_audio: bool = True, ) -> None: dest = Path(dest_path) dest.parent.mkdir(parents=True, exist_ok=True) @@ -241,6 +257,19 @@ def stitch_retake_output( raise ValueError("retake re-encode span is inverted") generated_has_audio = _has_audio(windowed_path) silence_original = generated_has_audio and not _has_audio(source_path) + gain_db = ( + retake_gain_db( + source_path=source_path, + generated_path=windowed_path, + mask_start=window.mask_start_frame / fps, + mask_end=window.mask_end_frame / fps, + generated_start=window.context_before_frames / fps, + source_seconds=window.source_frames / fps, + generated_seconds=window.encode_frames / fps, + ) + if generated_has_audio and regenerate_audio and not silence_original + else 0.0 + ) middle = dest.with_name(f"{dest.stem}.middle{dest.suffix}") try: write_rgb_video( @@ -267,6 +296,7 @@ def stitch_retake_output( box=box, generated_has_audio=generated_has_audio, silence_original=silence_original, + generated_gain_db=gain_db, ) finally: middle.unlink(missing_ok=True) diff --git a/backend/services/retake_pipeline/rgb_stitch.py b/backend/inference/retake_pipeline/rgb_stitch.py similarity index 97% rename from backend/services/retake_pipeline/rgb_stitch.py rename to backend/inference/retake_pipeline/rgb_stitch.py index 35a4a40fe..12baea124 100644 --- a/backend/services/retake_pipeline/rgb_stitch.py +++ b/backend/inference/retake_pipeline/rgb_stitch.py @@ -16,9 +16,8 @@ import av import numpy as np -from handlers.video_resolution import SpatialLetterbox -from services.retake_pipeline.letterbox import crop_letterbox, resize_rgb -from services.retake_pipeline.window import MAX_FADE_FRAMES +from inference.retake_pipeline.letterbox import SpatialLetterbox, crop_letterbox, resize_rgb +from inference.retake_pipeline.window import MAX_FADE_FRAMES @dataclass(frozen=True) diff --git a/backend/services/retake_pipeline/source_encode.py b/backend/inference/retake_pipeline/source_encode.py similarity index 98% rename from backend/services/retake_pipeline/source_encode.py rename to backend/inference/retake_pipeline/source_encode.py index f6ccf98ca..f57ddb2c6 100644 --- a/backend/services/retake_pipeline/source_encode.py +++ b/backend/inference/retake_pipeline/source_encode.py @@ -21,8 +21,7 @@ from ltx_pipelines.utils.helpers import decode_video_from_file, video_preprocess from ltx_pipelines.utils.media_io.range_map import normalize_images -from handlers.video_resolution import generation_letterbox -from services.retake_pipeline.letterbox import fit_and_pad +from inference.retake_pipeline.letterbox import fit_and_pad, generation_letterbox # CUDA keeps small tiles: one encoder forward must stay small on a 32 GB card. diff --git a/backend/inference/retake_pipeline/speech_analysis.py b/backend/inference/retake_pipeline/speech_analysis.py new file mode 100644 index 000000000..2be6cfd39 --- /dev/null +++ b/backend/inference/retake_pipeline/speech_analysis.py @@ -0,0 +1,90 @@ +"""Read the sound of a clip and find where someone speaks. + +Shared by the voice bridge (``voice_context``) and the level match (``audio_level``). +``speech_spans`` is an energy check, not a voice detector. Music or noise counts as sound. +""" + +from __future__ import annotations + +import subprocess +from dataclasses import dataclass + +import av +import numpy as np + +from inference.ffmpeg import ( + FFMPEG_PROTOCOL_WHITELIST, + FfmpegTimeoutError, + FfmpegUnavailableError, + run_ffmpeg, + timeout_for_source_duration, +) + +# What reading or writing the sound of a clip can raise. The callers are best effort: they log +# it and carry on without the audio feature. +AUDIO_ERRORS = ( + subprocess.CalledProcessError, + FfmpegTimeoutError, + FfmpegUnavailableError, + av.FFmpegError, +) + +ANALYSIS_SAMPLE_RATE = 16_000 +ACTIVITY_WINDOW_SECONDS = 0.05 +# Sound counts as speech above the floor and within this many dB of the loud level. +SPEECH_FLOOR_DBFS = -50.0 +SPEECH_BELOW_LOUD_DB = 30.0 +# Pauses shorter than this stay inside one speech span. +MERGE_GAP_SECONDS = 0.2 + + +@dataclass(frozen=True) +class Span: + start: float + end: float + + +def speech_spans(samples: np.ndarray, rate: int) -> list[Span]: + hop = max(1, int(rate * ACTIVITY_WINDOW_SECONDS)) + count = len(samples) // hop + if count == 0: + return [] + frames = samples[: count * hop].reshape(count, hop) + level_db = 20.0 * np.log10(np.sqrt((frames**2).mean(axis=1)) + 1e-9) + threshold = max(SPEECH_FLOOR_DBFS, float(np.percentile(level_db, 95)) - SPEECH_BELOW_LOUD_DB) + seconds_per_hop = hop / rate + spans: list[Span] = [] + for index in np.flatnonzero(level_db > threshold): + start, end = float(index) * seconds_per_hop, float(index + 1) * seconds_per_hop + if spans and start - spans[-1].end <= MERGE_GAP_SECONDS: + spans[-1] = Span(spans[-1].start, end) + else: + spans.append(Span(start, end)) + return spans + + +def decode_mono( + source_path: str, duration: float, *, start: float | None = None, end: float | None = None +) -> np.ndarray: + """Mono samples on the clip's own timeline: sample 0 is time 0, the first video frame. + + A track that starts late (common in phone and screen recordings) is padded with silence, + and one that starts early is trimmed, so a speech span in seconds is the same moment as + that second of video. Only the start is aligned; the audio is never stretched. + + ``start`` and ``end`` (seconds on that timeline) keep only that stretch, so a short + measurement does not hold the whole track in memory. Sample 0 is then ``start``. + ``duration`` is the length of the file, for the ffmpeg time limit.""" + chain = "aresample=async=1:first_pts=0" + if start is not None or end is not None: + bounds = [f"start={max(start, 0.0):.6f}" if start is not None else "", f"end={end:.6f}" if end is not None else ""] + chain += ",atrim=" + ":".join(b for b in bounds if b) + completed = run_ffmpeg( + [ + "-protocol_whitelist", FFMPEG_PROTOCOL_WHITELIST, "-i", source_path, "-vn", + "-af", chain, + "-ac", "1", "-ar", str(ANALYSIS_SAMPLE_RATE), "-f", "f32le", "-", + ], + timeout=timeout_for_source_duration(duration), + ) + return np.frombuffer(completed.stdout, dtype=np.float32) diff --git a/backend/inference/retake_pipeline/stitch_audio.py b/backend/inference/retake_pipeline/stitch_audio.py new file mode 100644 index 000000000..cbecc1c13 --- /dev/null +++ b/backend/inference/retake_pipeline/stitch_audio.py @@ -0,0 +1,70 @@ +"""Audio cuts for retake and extend stitches. Video fades over many frames. Audio is cut at one +point with a very short fade on each side, so the join does not click.""" + +from __future__ import annotations + +from collections.abc import Sequence +from dataclasses import dataclass + +from inference.ffmpeg import ffmpeg_seconds + + +# Length of the fade on each side of a join. A hard join leaves a step in the waveform, which +# is heard as a click. A longer fade would dip the level in speech. +JOIN_FADE_SECONDS = 0.015 + + +@dataclass(frozen=True) +class AudioPiece: + """``label`` between ``start`` and ``end`` seconds. ``None`` runs to that edge. + + ``gain_db`` changes the level. A peak limiter stops clipping after a boost; a cut cannot + clip, so it gets none.""" + + label: str + start: float | None = None + end: float | None = None + gain_db: float = 0.0 + + +def _join_fades(piece: AudioPiece, *, after_join: bool, before_join: bool) -> str: + """Fade in after a join and fade out before one. Pieces keep their length, so audio and + video stay in sync. A piece that is too short for both fades gets shorter fades, and an + empty piece gets none (a zero-length fade is not a valid filter). + + The fade-out sits at the requested end of the piece. A track that stops before that end + simply ends where it ends, which leaves no cut to fade.""" + length = None if piece.end is None else piece.end - (piece.start or 0.0) + fade = JOIN_FADE_SECONDS if length is None else min(JOIN_FADE_SECONDS, length / 2) + if fade <= 0: + return "" + fades = "" + if after_join: + fades += f",afade=t=in:d={ffmpeg_seconds(fade)}" + if before_join and length is not None: + fades += f",afade=t=out:st={ffmpeg_seconds(length - fade)}:d={ffmpeg_seconds(fade)}" + return fades + + +def audio_cut_graph(pieces: Sequence[AudioPiece]) -> str: + """Concatenate ``pieces`` in order into ``[a]``, with a short fade at each join.""" + parts: list[str] = [] + outputs: list[str] = [] + for index, piece in enumerate(pieces): + bounds: list[str] = [] + if piece.start is not None: + bounds.append(f"start={ffmpeg_seconds(piece.start)}") + if piece.end is not None: + bounds.append(f"end={ffmpeg_seconds(piece.end)}") + output = f"[p{index}]" + gain = "" + if piece.gain_db: + gain = f",volume={piece.gain_db:.2f}dB" + if piece.gain_db > 0: + # ``level=0``: the limiter's auto level would add about +0.26 dB of its own. + gain += ",alimiter=limit=0.97:level=0" + fades = _join_fades(piece, after_join=index > 0, before_join=index < len(pieces) - 1) + parts.append(f"{piece.label}atrim={':'.join(bounds)},asetpts=PTS-STARTPTS{gain}{fades}{output}") + outputs.append(output) + parts.append(f"{''.join(outputs)}concat=n={len(outputs)}:v=0:a=1[a]") + return ";".join(parts) diff --git a/backend/services/retake_pipeline/stitch_silence.py b/backend/inference/retake_pipeline/stitch_silence.py similarity index 100% rename from backend/services/retake_pipeline/stitch_silence.py rename to backend/inference/retake_pipeline/stitch_silence.py diff --git a/backend/inference/retake_pipeline/voice_context.py b/backend/inference/retake_pipeline/voice_context.py new file mode 100644 index 000000000..ed9aaf71c --- /dev/null +++ b/backend/inference/retake_pipeline/voice_context.py @@ -0,0 +1,185 @@ +"""Keep a voice in the extend context when the kept source tail is silent. + +The Short context mode of Extend encodes about 2s of source. The model copies the voice from the +audio in that window. When the speaker stopped before the window starts, the window holds no +voice and the new speech comes out in another voice. + +The fix builds a short bridge clip for the model to read. It joins a piece of the last speech +(picture and sound together, so the lips match the voice) with the source frames at the seam +that the model regenerates. The bridge has as many frames as the window, so the run costs +the same. The stitch reads the original file for the source part of the output, so the bridge +never reaches the output. + +``speech_spans`` is an energy check, not a voice detector. Music or noise in the window +counts as sound, so the bridge is skipped there. +""" + +from __future__ import annotations + +import logging +import math +from dataclasses import dataclass +from pathlib import Path + +from inference.ffmpeg import ( + FFMPEG_PROTOCOL_WHITELIST, + ffmpeg_seconds, + run_ffmpeg, + timeout_for_source_duration, +) +from inference.media import media_has_audio +from inference.retake_pipeline.speech_analysis import ( + ANALYSIS_SAMPLE_RATE, + AUDIO_ERRORS, + Span, + decode_mono, + speech_spans, +) +from inference.retake_pipeline.window import MASK_DELTA_SECONDS, ExtendEncodeWindow +from inference.types import ExtendMode + +logger = logging.getLogger(__name__) + +BRIDGE_SAMPLE_RATE = 48_000 +# Shortest span that counts as a voice sample, and as speech already in the window. +MIN_SPEECH_SECONDS = 0.4 +# Real frames kept before the part the model regenerates. A longer run lets the model carry +# the pose across the seam. A short one gives a visible jump. The rest of the window is the +# speech piece, which must stay above ``MIN_SPEECH_SECONDS``. +KEPT_SEAM_SECONDS = 0.8 + + +@dataclass(frozen=True) +class VoiceBridge: + """Two source frame ranges. The bridge plays the speech piece next to the seam piece.""" + + speech_start_frame: int + speech_frames: int + seam_start_frame: int + seam_frames: int + mode: ExtendMode + + @property + def total_frames(self) -> int: + return self.speech_frames + self.seam_frames + + +def _speech_inside(spans: list[Span], start: float, end: float) -> float: + return sum(max(0.0, min(span.end, end) - max(span.start, start)) for span in spans) + + +def plan_voice_bridge( + spans: list[Span], + *, + window: ExtendEncodeWindow, + fps: float, + source_frames: int, + mode: ExtendMode, +) -> VoiceBridge | None: + """Pick the speech for the bridge, or ``None`` when the window has a voice or there is none. + + The model regenerates the ``MASK_DELTA_SECONDS`` next to the new content. The seam piece + keeps that part and ``KEPT_SEAM_SECONDS`` of real frames before it. The speech piece fills the rest of + the window. + """ + seam_frames = math.ceil((MASK_DELTA_SECONDS + KEPT_SEAM_SECONDS) * fps) + speech_frames = window.context_frames - seam_frames + if speech_frames / fps < MIN_SPEECH_SECONDS: + logger.info( + "Voice bridge skipped: a %d-frame window at %.2f fps leaves %.2fs for speech (needs %.2fs)", + window.context_frames, fps, max(speech_frames, 0) / fps, MIN_SPEECH_SECONDS, + ) + return None + window_start = window.start_time(fps) + window_end = window_start + window.context_frames / fps + seam_seconds = seam_frames / fps + if mode == "end": + zone = (window_start, window_end - seam_seconds) + seam_start_frame = window.encode_start_frame + speech_frames + else: + zone = (window_start + seam_seconds, window_end) + seam_start_frame = window.encode_start_frame + if _speech_inside(spans, *zone) >= MIN_SPEECH_SECONDS: + return None + # A span that runs into the zone counts up to the zone edge: that part is speech next to + # the window, and the piece must not reach into the window. + if mode == "end": + ends = [min(s.end, zone[0]) for s in spans if min(s.end, zone[0]) - s.start >= MIN_SPEECH_SECONDS] + if not ends: + return None + piece_end = min(source_frames, round(ends[-1] * fps)) + speech_start_frame = max(0, piece_end - speech_frames) + else: + starts = [max(s.start, zone[1]) for s in spans if s.end - max(s.start, zone[1]) >= MIN_SPEECH_SECONDS] + if not starts: + return None + speech_start_frame = max(0, min(round(starts[0] * fps), source_frames - speech_frames)) + return VoiceBridge(speech_start_frame, speech_frames, seam_start_frame, seam_frames, mode) + + +def _write_bridge_clip(source_path: str, dest_path: str, bridge: VoiceBridge, fps: float) -> None: + def video(label: str, start: int, count: int, out: str) -> str: + return f"[{label}]trim=start_frame={start}:end_frame={start + count},setpts=PTS-STARTPTS[{out}]" + + def audio(label: str, start: int, count: int, out: str) -> str: + return ( + f"[{label}]atrim=start={ffmpeg_seconds(start / fps)}:end={ffmpeg_seconds((start + count) / fps)}," + f"asetpts=PTS-STARTPTS,aformat=sample_rates={BRIDGE_SAMPLE_RATE}:channel_layouts=stereo[{out}]" + ) + + speech = (bridge.speech_start_frame, bridge.speech_frames) + seam = (bridge.seam_start_frame, bridge.seam_frames) + order = ("vs", "as", "vt", "at") if bridge.mode == "end" else ("vt", "at", "vs", "as") + graph = ";".join( + [ + "[0:v]split=2[v0][v1]", + # Same alignment as decode_mono: a late track is padded, so each piece's sound + # sits under its own frames. + "[0:a]aresample=async=1:first_pts=0,asplit=2[a0][a1]", + video("v0", *speech, "vs"), + video("v1", *seam, "vt"), + audio("a0", *speech, "as"), + audio("a1", *seam, "at"), + f"[{order[0]}][{order[1]}][{order[2]}][{order[3]}]concat=n=2:v=1:a=1[v][a]", + ] + ) + run_ffmpeg( + [ + "-y", "-protocol_whitelist", FFMPEG_PROTOCOL_WHITELIST, "-i", source_path, + "-filter_complex", graph, "-map", "[v]", "-map", "[a]", + "-r", f"{fps:.6f}", "-c:v", "libx264", "-preset", "veryfast", "-crf", "12", + "-pix_fmt", "yuv420p", "-c:a", "aac", "-b:a", "192k", dest_path, + ], + timeout=timeout_for_source_duration(bridge.total_frames / fps), + ) + + +def find_voice_bridge( + source_path: str, + *, + window: ExtendEncodeWindow, + fps: float, + source_frames: int, + mode: ExtendMode, +) -> VoiceBridge | None: + """Plan the bridge from the sound of the source. Writes no file. Best effort.""" + try: + if not media_has_audio(source_path): + return None + spans = speech_spans(decode_mono(source_path, source_frames / fps), ANALYSIS_SAMPLE_RATE) + except AUDIO_ERRORS: + logger.warning("Extend voice bridge skipped: could not read the audio", exc_info=True) + return None + return plan_voice_bridge(spans, window=window, fps=fps, source_frames=source_frames, mode=mode) + + +def write_voice_bridge(source_path: str, dest_path: str, bridge: VoiceBridge, fps: float) -> bool: + """Write the bridge clip to ``dest_path``. ``False``: nothing written, the extend reads the + plain source. Best effort.""" + try: + _write_bridge_clip(source_path, dest_path, bridge, fps) + except AUDIO_ERRORS: + logger.warning("Extend voice bridge skipped: could not write the clip", exc_info=True) + Path(dest_path).unlink(missing_ok=True) + return False + return True diff --git a/backend/services/retake_pipeline/window.py b/backend/inference/retake_pipeline/window.py similarity index 77% rename from backend/services/retake_pipeline/window.py rename to backend/inference/retake_pipeline/window.py index 154ac70d7..ca6e4dd9a 100644 --- a/backend/services/retake_pipeline/window.py +++ b/backend/inference/retake_pipeline/window.py @@ -10,9 +10,8 @@ from dataclasses import dataclass from typing import NoReturn -from api_types import ExtendMode -from runtime_config.video_job_budget import VIDEO_JOB_TOO_LARGE -from services.records import CapabilityFailedError +from inference.errors import VIDEO_JOB_TOO_LARGE, CapabilityFailedError +from inference.types import DEFAULT_EDIT_CONTEXT_MODE, EditContextMode, ExtendMode MAX_INPUT_FRAMES = 505 VAE_TEMPORAL_DIVISOR = 8 @@ -23,6 +22,16 @@ # coherence floor (approved default), not a measurement: below this the model # extends from slivers. Longer requests are refused with the max named. MIN_EXTEND_CONTEXT_FRAMES = 121 +# Context kept by the "short" extend mode: 49 = 8*6+1 frames (7 latents, about +# 2s at 24 fps) next to the new content. Enough latents to carry the motion +# direction, few enough that the sequence stays near the extension length. +# Untuned: compare seams and identity drift against the full-context mode +# before changing it or making the mode the default. +CONTINUATION_CONTEXT_FRAMES = 49 +# The same context in seconds, so a higher frame rate keeps the same stretch of the clip. A +# fixed 49 frames is only 1.6 s at 30 fps and 0.8 s at 60 fps, too short to hold the voice +# bridge's 1.3 s seam piece and a speech piece. +CONTINUATION_CONTEXT_SECONDS = 2.04 # ltxv-api ``stitch_frames`` lerp band (``MAX_FADE_FRAMES = 16``). MAX_FADE_FRAMES = 16 _BLEND_GUARD_FRAMES = 1 @@ -32,7 +41,7 @@ # test_retake_out_of_range_matches_home_advisory_copy. SELECTION_OUT_OF_RANGE_MESSAGE = "Selection is outside the usable video range" # The denoise mask covers whole latents, so it spills up to 7 frames past the -# feathered region, and the decoder bleeds about one more latent. The encode +# selection, and the decoder bleeds about one more latent. The encode # window keeps that much context so the 16-frame lerp has original frames # beside the regenerated span. LATENT_ROUNDING_FRAMES = VAE_TEMPORAL_DIVISOR - 1 @@ -83,6 +92,32 @@ def vae_align_down(length: int) -> int: return length - ((length - 1) % VAE_TEMPORAL_DIVISOR) +def continuation_context_frames(fps: float) -> int: + """Context the "short" extend mode keeps: about 2 s at any rate, ``8k + 1`` aligned, never + fewer than ``CONTINUATION_CONTEXT_FRAMES``. 49 frames at 24 and 25 fps, 57 at 30, 121 at 60.""" + if fps <= 0: + return CONTINUATION_CONTEXT_FRAMES + return max( + CONTINUATION_CONTEXT_FRAMES, vae_align_down(round(CONTINUATION_CONTEXT_SECONDS * fps)) + ) + + +def context_cap_frames(context_mode: EditContextMode, fps: float) -> int | None: + """Most context frames the mode keeps, or ``None`` when it keeps as much as the window fits.""" + return continuation_context_frames(fps) if context_mode == "short" else None + + +def extend_context_floor( + context_mode: EditContextMode, + fps: float, + minimum_context_frames: int = MIN_EXTEND_CONTEXT_FRAMES, +) -> int: + """Fewest context frames an extend needs: ``minimum_context_frames``, lowered to the + context the mode keeps.""" + cap = context_cap_frames(context_mode, fps) + return minimum_context_frames if cap is None else min(minimum_context_frames, cap) + + def duration_to_extend_frames(duration: float, fps: float) -> int: """Snap extend duration up to a multiple of 8 so the padded output stays 8k+1.""" frames = round(duration * fps) @@ -91,9 +126,11 @@ def duration_to_extend_frames(duration: float, fps: float) -> int: ) * VAE_TEMPORAL_DIVISOR -def max_extend_frames(frame_cap: int) -> int: +def max_extend_frames( + frame_cap: int, minimum_context_frames: int = MIN_EXTEND_CONTEXT_FRAMES +) -> int: """Longest extension that preserves the minimum context inside the cap.""" - return frame_cap - MIN_EXTEND_CONTEXT_FRAMES + return frame_cap - minimum_context_frames def extend_exceeds_cap( @@ -110,6 +147,7 @@ def extend_too_long_message( target_height: int, frame_cap: int, fps: float, + minimum_context_frames: int = MIN_EXTEND_CONTEXT_FRAMES, ) -> str: """Refusal naming the longest extension this machine fits at this size. @@ -119,7 +157,7 @@ def extend_too_long_message( cap the 121-frame context rule binds on every machine, so the copy stays machine-neutral; a shortened machine cap keeps "on this machine". """ - longest = max(0, max_extend_frames(frame_cap)) + longest = max(0, max_extend_frames(frame_cap, minimum_context_frames)) detail = f" (at most {int(longest / fps)}s)" if fps > 0 else "" if frame_cap >= MAX_INPUT_FRAMES: return ( @@ -160,7 +198,9 @@ def window_for_extend( extend_frames: int, mode: ExtendMode, max_input_frames: int | None = None, + max_context_frames: int | None = None, ) -> ExtendEncodeWindow: + """``max_context_frames`` caps the kept context; it applies with a frame cap only.""" if source_frames <= 0 or extend_frames <= 0: raise ValueError("source_frames and extend_frames must be positive") if max_input_frames is None: @@ -175,6 +215,8 @@ def window_for_extend( f"Extend duration ({extend_frames} frames) exceeds limit ({max_input_frames})" ) context_budget = max_input_frames - extend_frames + if max_context_frames is not None: + context_budget = min(context_budget, max_context_frames) context_frames = vae_align_down(min(source_frames, context_budget)) if context_frames <= 0: raise ValueError( @@ -203,7 +245,10 @@ def window_for_retake( mask_end_frame: int, max_input_frames: int | None = MAX_INPUT_FRAMES, fps: float | None = None, + max_context_frames: int | None = None, ) -> RetakeEncodeWindow: + """``max_context_frames`` caps the context kept on each side of the mask. Without it the + window fills to the cap, with leftover frames going to the far sides.""" if source_frames <= 0: raise ValueError("source_frames must be positive") mask_start_frame = max(0, min(source_frames, mask_start_frame)) @@ -233,6 +278,8 @@ def window_for_retake( ) per_side = max(0, (cap - mask_frames) // 2) + if max_context_frames is not None: + per_side = min(per_side, max_context_frames) context_before = min(per_side, available_before) context_after = min(per_side, available_after) @@ -249,12 +296,13 @@ def window_for_retake( context_before = grown_before context_after = grown_after - leftover = cap - (context_before + mask_frames + context_after) - grow_after = min(leftover, available_after - context_after) - context_after += max(0, grow_after) - leftover -= max(0, grow_after) - grow_before = min(leftover, available_before - context_before) - context_before += max(0, grow_before) + if max_context_frames is None: + leftover = cap - (context_before + mask_frames + context_after) + grow_after = min(leftover, available_after - context_after) + context_after += max(0, grow_after) + leftover -= max(0, grow_after) + grow_before = min(leftover, available_before - context_before) + context_before += max(0, grow_before) context_before, context_after = _align_context( context_before, @@ -317,9 +365,13 @@ def prepare_retake_window( frame_cap: int, start_time: float, duration: float, + context_mode: EditContextMode = DEFAULT_EDIT_CONTEXT_MODE, ) -> PreparedRetakeWindow | EditRefusal: """Mask + window math, one implementation for execute and preflight. + ``context_mode="short"`` keeps about 2 s of context on each side of the mask + (``continuation_context_frames(fps)``) instead of filling the window to the cap. + The executor raises refusals via ``raise_capability_error``; preflights return them as failing verdicts. Budget stays per-side (the executor loads the pipeline, preflights decide without loading), as do metadata @@ -344,6 +396,7 @@ def prepare_retake_window( mask_end_frame=mask_end_frame, max_input_frames=frame_cap, fps=fps, + max_context_frames=context_cap_frames(context_mode, fps), ) except ValueError as exc: # A short selection on a long clip used to pad to 505 and 422. If the @@ -376,6 +429,7 @@ def prepare_extend_window( duration: float, mode: ExtendMode, minimum_context_frames: int = MIN_EXTEND_CONTEXT_FRAMES, + context_mode: EditContextMode = DEFAULT_EDIT_CONTEXT_MODE, ) -> PreparedExtendWindow | EditRefusal: """Extend window math, one implementation for execute and preflight. @@ -383,8 +437,13 @@ def prepare_extend_window( is the coherence floor for admission; the shrink retry passes 1 so an admitted job salvages a run with reduced (far-side-trimmed) context instead of failing when free VRAM dips below the full-context ask. + + ``context_mode="short"`` keeps at most ``continuation_context_frames(fps)`` of + context (49 at 24 fps), and lowers the admission floor to match. """ extend_frames = duration_to_extend_frames(duration, fps) + max_context_frames = context_cap_frames(context_mode, fps) + minimum_context_frames = extend_context_floor(context_mode, fps, minimum_context_frames) # The extension must leave the minimum context inside the window # (MIN_EXTEND_CONTEXT_FRAMES): without the floor, long extensions # silently extend from slivers. @@ -396,6 +455,7 @@ def prepare_extend_window( target_height=target_height, frame_cap=frame_cap, fps=fps, + minimum_context_frames=minimum_context_frames, ), code=VIDEO_JOB_TOO_LARGE, ) @@ -405,22 +465,22 @@ def prepare_extend_window( extend_frames=extend_frames, mode=mode, max_input_frames=frame_cap, + max_context_frames=max_context_frames, ) except ValueError as exc: return EditRefusal(message=str(exc), code="INVALID_GENERATION_SPEC", cause=exc) return PreparedExtendWindow(window=window, extend_frames=extend_frames) -def feathered_mask_times(window: RetakeEncodeWindow, fps: float) -> tuple[float, float]: - """Widen the denoise mask MASK_DELTA into kept context (Home extend seam).""" - start = window.window_mask_start(fps) - end = window.window_mask_end(fps) - duration = window.encode_duration(fps) - if window.context_before_frames > 0: - start = max(0.0, start - MASK_DELTA_SECONDS) - if window.context_after_frames > 0: - end = min(duration, end + MASK_DELTA_SECONDS) - return start, end +def retake_mask_times(window: RetakeEncodeWindow, fps: float) -> tuple[float, float]: + """Denoise mask for retake: exactly the user's selection, in encode-window seconds. + + The mask and the stitch edit span are one range, so the 16-frame lerp runs over + frozen-latent frames (essentially the source). Widening + the mask by MASK_DELTA (as extend does at its seam) put the lerp on top of content the + model had regenerated differently, which showed as ghosting at the seam. + """ + return window.window_mask_start(fps), window.window_mask_end(fps) def _latent_frame_span(latent: int) -> tuple[int, int]: @@ -436,9 +496,9 @@ def denoised_frame_span(window: RetakeEncodeWindow, fps: float) -> tuple[int, in """Window frames ``[start, end)`` the retake actually regenerates. ``TemporalRegionMask`` denoises every latent whose frames overlap the - feathered region, so the span snaps outward to latent boundaries. + mask, so the span snaps outward to latent boundaries. """ - region_start, region_end = feathered_mask_times(window, fps) + region_start, region_end = retake_mask_times(window, fps) latents = (window.encode_frames - 1) // VAE_TEMPORAL_DIVISOR + 1 spans = [ span diff --git a/backend/services/gpu_info/run_peak.py b/backend/inference/run_peak.py similarity index 100% rename from backend/services/gpu_info/run_peak.py rename to backend/inference/run_peak.py diff --git a/backend/inference/triton_block.py b/backend/inference/triton_block.py new file mode 100644 index 000000000..cb4be00c8 --- /dev/null +++ b/backend/inference/triton_block.py @@ -0,0 +1,24 @@ +"""Hide Triton from this process (used when Windows Smart App Control is on).""" + +from __future__ import annotations + +import sys + + +def block_triton_import() -> bool: + """Make ``import triton`` raise ImportError for the rest of this process. + + SageAttention is not the only Triton user: the ltx-core video VAE (swiglu, + row_rms_norm, stage5_tail, loader kernels) launches Triton kernels whenever Triton + and CUDA are present. Each of those modules guards its import with + ``except ImportError`` and then takes a plain PyTorch path, so hiding Triton keeps + them off the run-time compiled ``.pyd`` files that Smart App Control blocks. + + Must run before anything imports Triton. Returns False when Triton was already + imported, because it cannot be undone then. + """ + modules: dict[str, object] = sys.modules # type: ignore[assignment] + if "triton" in modules: + return modules["triton"] is None + modules["triton"] = None + return True diff --git a/backend/inference/types.py b/backend/inference/types.py new file mode 100644 index 000000000..266125f53 --- /dev/null +++ b/backend/inference/types.py @@ -0,0 +1,37 @@ +"""Shared inference type aliases used by pipeline wrappers.""" + +from __future__ import annotations + +from typing import Literal, NamedTuple, TypeAlias + +LTXLocalModelId = Literal[ + "ltx-2.5-22b-distilled", + "ltx-2.3-22b-distilled-1.1", + "ltx-2.3-22b-distilled", +] + + +class ImageConditioningInput(NamedTuple): + """Image conditioning triplet used by all video pipelines.""" + + path: str + frame_idx: int + strength: float + + +RetakeMode: TypeAlias = Literal[ + "replace_audio_and_video", "replace_video", "replace_audio" +] + +ExtendMode: TypeAlias = Literal["start", "end"] + +# "long" encodes as much of the clip as fits the window. "short" keeps about 2 s of context +# next to the new content (Extend) or on each side of the selection (Retake), so the job +# denoises a much shorter sequence. +EditContextMode: TypeAlias = Literal["long", "short"] +# The mode a request, a preflight and a window use when none is stated. +DEFAULT_EDIT_CONTEXT_MODE: EditContextMode = "long" + +# Look-still frame for Layout To Render. Upstream rejects a negative index, so +# the pipeline keeps the still apart from the clip frames. +REFERENCE_STILL_FRAME_IDX = -1 diff --git a/backend/keyframe_request.py b/backend/keyframe_request.py index 422f757b9..7f5600c20 100644 --- a/backend/keyframe_request.py +++ b/backend/keyframe_request.py @@ -5,7 +5,7 @@ from collections.abc import Sequence from api_types import GenerateVideoRequest -from frame_math import compute_num_frames +from inference.frame_math import compute_num_frames from server_utils.media_validation import normalize_optional_path diff --git a/backend/ltx2_server.py b/backend/ltx2_server.py index c31f5c79f..d1d937024 100644 --- a/backend/ltx2_server.py +++ b/backend/ltx2_server.py @@ -9,8 +9,6 @@ remove_cwd_from_dll_search_path() faulthandler.enable(file=sys.stderr, all_threads=True) -from typing import Any, cast - if os.environ.get("BACKEND_DEBUG") == "1": try: import debugpy # type: ignore[reportMissingImports] @@ -55,29 +53,12 @@ import mps_prebuilt_ext as _mps_prebuilt_ext # pyright: ignore[reportUnusedImport] _mps_prebuilt_ext.setup_prebuilt_mps_extension() -# LLM: bumping ltx-core / ltx-pipelines (backend/pyproject.toml) MUST re-verify every -# import below (and mps_sdpa_torch later in this file). These monkey-patch private -# 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_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 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 +# Darwin transfer fence. Must run before apply_patches(), which imports +# ltx-pipelines attention. CUDA patches are applied after logging is configured. 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 +import services.patches.mps_tiling_weights_sync as _mps_tiling_weights_sync # pyright: ignore[reportUnusedImport] # Remove once ltx-core _device_weights uploads with non_blocking=allow_async_transfer(...) and Refine Details gives a real picture on a Mac without it (LTX-Desktop#199) +del _mps_tiling_weights_sync # ============================================================ # Logging Configuration @@ -108,68 +89,29 @@ # (the setup call at import time logs too early to be captured). No-op off Darwin. _mps_prebuilt_ext.log_mps_backend_status() -# ============================================================ -# SageAttention Integration -# ============================================================ -use_sage_attention = os.environ.get("USE_SAGE_ATTENTION", "1") == "1" -_sageattention_runtime_fallback_logged = False +# CUDA patches + SageAttention wrap (gated on USE_SAGE_ATTENTION, default on). +# LLM: bumping ltx-core / ltx-pipelines MUST re-verify every import in +# inference/apply_patches.py (and mps_sdpa_torch below). Delete-first. +# Import the function from its module. Binding it on the inference package +# would shadow the submodule of the same name. +from inference.apply_patches import apply_patches +from runtime_config.smart_app_control import ( + detect_smart_app_control, + smart_app_control_blocks_unsigned_code, +) -if use_sage_attention: - try: - from sageattention import sageattn # type: ignore[reportMissingImports] - import torch.nn.functional as F - - _original_sdpa = F.scaled_dot_product_attention - - _SAGE_SUPPORTED_HEADDIMS = {64, 96, 128} - - @torch.compiler.disable(recursive=True) # type: ignore[reportUntypedFunctionDecorator] - def _sageattn_call(query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, is_causal: bool) -> torch.Tensor: - # torch.compile must not trace into sageattn's Python internals (quant.py, - # core.py): it bakes the current call's shapes into the compiled graph's - # guards, which then hard-fails (ConstraintViolationError) on any later call - # with different video/audio dimensions. Disabling keeps this call eager — - # a graph break here, not a recompile — while the surrounding transformer - # forward stays compiled. - return cast(torch.Tensor, sageattn(query, key, value, is_causal=is_causal, tensor_layout="HND")) # type: ignore[reportUnnecessaryCast] - - def patched_sdpa( - query: torch.Tensor, - key: torch.Tensor, - value: torch.Tensor, - attn_mask: torch.Tensor | None = None, - dropout_p: float = 0.0, - is_causal: bool = False, - scale: float | None = None, - **kwargs: Any, - ) -> torch.Tensor: - global _sageattention_runtime_fallback_logged - try: - if ( - query.dim() == 4 - and attn_mask is None - and dropout_p == 0.0 - and query.shape[-1] in _SAGE_SUPPORTED_HEADDIMS - ): - return _sageattn_call(query, key, value, is_causal) - else: - return _original_sdpa(query, key, value, attn_mask=attn_mask, - dropout_p=dropout_p, is_causal=is_causal, scale=scale, **kwargs) - except Exception: - if not _sageattention_runtime_fallback_logged: - logger.warning("SageAttention failed during runtime; falling back to default attention", exc_info=True) - _sageattention_runtime_fallback_logged = True - return _original_sdpa(query, key, value, attn_mask=attn_mask, - dropout_p=dropout_p, is_causal=is_causal, scale=scale, **kwargs) - - F.scaled_dot_product_attention = patched_sdpa - logger.info("SageAttention enabled - attention operations will be faster") - except ImportError: - logger.warning("SageAttention not installed - using default attention") - use_sage_attention = False - except Exception: - logger.warning("Failed to enable SageAttention", exc_info=True) - use_sage_attention = False +_smart_app_control_state = detect_smart_app_control() +smart_app_control_on = smart_app_control_blocks_unsigned_code(_smart_app_control_state) +logger.info("Windows Smart App Control state: %s", _smart_app_control_state) +use_sage_attention = apply_patches(smart_app_control_on=smart_app_control_on) + +# state/__init__.py imports the queue runner, which imports CUDA patches. +# Importing AppSettings earlier installs those patches before logging exists. +from state.app_settings import AppSettings + +# Desktop-only LTXTextEncoder hook (split from safetensors_metadata_fix patch 4). +import services.patches.ltx_text_encoder_checkpoint_id as _ltx_text_encoder_checkpoint_id # pyright: ignore[reportUnusedImport] # Remove once safetensors supports read-only mmap +del _ltx_text_encoder_checkpoint_id # Darwin: Diffusers/Z-Image call F.sdpa (stock MPS SDPA materializes S×S and can # freeze the machine). Video already uses mps-sdpa via ltx-core; this covers Z-Image. @@ -334,6 +276,7 @@ def _effective_local_generations_mode(mode: LocalGenerationMode) -> LocalGenerat settings_file=SETTINGS_FILE, ltx_api_base_url=LTX_API_BASE_URL, use_sage_attention=use_sage_attention, + smart_app_control_on=smart_app_control_on, camera_motion_prompts=CAMERA_MOTION_PROMPTS, default_negative_prompt=DEFAULT_NEGATIVE_PROMPT, dev_mode=os.environ.get("LTX_DEV_MODE") == "1", diff --git a/backend/performance_runner/README.md b/backend/performance_runner/README.md index 32b4ba268..c3027c8bc 100644 --- a/backend/performance_runner/README.md +++ b/backend/performance_runner/README.md @@ -93,7 +93,7 @@ If the desktop app is already running, just launch the dashboard: ```bash cd backend/performance_runner -uv run python run_dashboard.py # cross-platform; also run_dashboard.sh / .ps1 +uv run --extra desktop python run_dashboard.py # cross-platform; also run_dashboard.sh / .ps1 # -> http://127.0.0.1:8750 ``` diff --git a/backend/performance_runner/run_dashboard.ps1 b/backend/performance_runner/run_dashboard.ps1 index 71a730904..0d43c40e6 100644 --- a/backend/performance_runner/run_dashboard.ps1 +++ b/backend/performance_runner/run_dashboard.ps1 @@ -39,7 +39,7 @@ try { try { if (Get-Command uv -ErrorAction SilentlyContinue) { - uv run python run_dashboard.py --port $Port + uv run --extra desktop python run_dashboard.py --port $Port } else { python run_dashboard.py --port $Port } diff --git a/backend/performance_runner/run_dashboard.py b/backend/performance_runner/run_dashboard.py index 394ce0722..3350aff41 100755 --- a/backend/performance_runner/run_dashboard.py +++ b/backend/performance_runner/run_dashboard.py @@ -7,8 +7,8 @@ still-running spawned perf runs. Run it with the backend env so fastapi/uvicorn/torch resolve, e.g.: - uv run python run_dashboard.py - uv run python run_dashboard.py --port 8750 + uv run --extra desktop python run_dashboard.py + uv run --extra desktop python run_dashboard.py --port 8750 Binds 127.0.0.1 only — never expose it. """ diff --git a/backend/performance_runner/run_dashboard.sh b/backend/performance_runner/run_dashboard.sh index f921d55f8..ca01c5271 100755 --- a/backend/performance_runner/run_dashboard.sh +++ b/backend/performance_runner/run_dashboard.sh @@ -4,7 +4,7 @@ set -euo pipefail cd "$(dirname "$0")" if command -v uv >/dev/null 2>&1; then - exec uv run python run_dashboard.py "$@" + exec uv run --extra desktop python run_dashboard.py "$@" else exec python3 run_dashboard.py "$@" fi diff --git a/backend/pyproject.toml b/backend/pyproject.toml index 975659949..bbc90c942 100644 --- a/backend/pyproject.toml +++ b/backend/pyproject.toml @@ -18,8 +18,6 @@ dependencies = [ "torchvision>=0.18.0", "huggingface-hub>=0.23.0", "tqdm>=4.66.0", - # Windows ships no IANA timezone database. ZoneInfo needs this for dashboard ranges. - "tzdata>=2024.1", "pynvml>=11.5.0; sys_platform != 'darwin'", "psutil>=5.9.0", "pydantic>=2.7.0", @@ -28,7 +26,9 @@ dependencies = [ "httpx>=0.27", # 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). + # every monkey-patch: CUDA ones in backend/inference/patches/ (imported from + # backend/inference/apply_patches.py), Darwin leftovers 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.6.0", @@ -58,11 +58,6 @@ dependencies = [ # memory per attention call and OOMs longer generations. macOS-only. "ninja>=1.11; sys_platform == 'darwin'", "opencv-python-headless>=4.8.0", - "fastapi>=0.141.1", - # FastAPI 0.129 pinned starlette<1; 0.141+ allows the 1.x line. - "starlette>=1.6.0", - "uvicorn[standard]>=0.30.0", - "python-multipart>=0.0.32", "triton-windows; sys_platform == 'win32'", "triton; sys_platform == 'linux'", ] @@ -95,7 +90,9 @@ natten = { url = "https://storage.googleapis.com/ltx-desktop-artifacts/wheels/na # 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). +# LLM: bumping this tag/version → re-verify backend/inference/patches/ (imported from +# backend/inference/apply_patches.py) and Darwin leftovers in backend/services/patches/ +# (imported from ltx2_server.py). 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" } @@ -124,6 +121,15 @@ version = "1.6.0" requires-dist = ["ltx-core", "av", "tqdm", "pillow", "openimageio", "cloudpickle>=3.1"] [project.optional-dependencies] +desktop = [ + # Windows ships no IANA timezone database. ZoneInfo needs this for dashboard ranges. + "tzdata>=2024.1", + "fastapi>=0.141.1", + # FastAPI 0.129 pinned starlette<1; 0.141+ allows the 1.x line. + "starlette>=1.6.0", + "uvicorn[standard]>=0.30.0", + "python-multipart>=0.0.32", +] test = [ "pytest>=8.0", "requests>=2.34.2", diff --git a/backend/pyrightconfig.json b/backend/pyrightconfig.json index 35c4323d7..fff1944be 100644 --- a/backend/pyrightconfig.json +++ b/backend/pyrightconfig.json @@ -14,7 +14,8 @@ "scripts", "performance_runner", "profile_results", - "services/patches" + "services/patches", + "inference/patches" ], "reportMissingImports": "warning", "reportMissingTypeStubs": false, diff --git a/backend/remote/dto.py b/backend/remote/dto.py index 0fa139f8f..fb7e016a7 100644 --- a/backend/remote/dto.py +++ b/backend/remote/dto.py @@ -17,6 +17,7 @@ ApiActivityStatus, Asset, AssetCore, + EditContextMode, ExtendMode, IcLoraAudioMode, IcLoraControlType, @@ -31,7 +32,7 @@ ) from api_motion_path import MotionPath from remote.media_urls import MediaUrlSigner -from runtime_config.ic_lora_tiling import ( +from inference.ic_lora_tiling import ( MAX_TILE_OVERLAP, MIN_CARRY_FRAMES, MIN_TILE_OVERLAP, @@ -53,6 +54,7 @@ "promptProvenance", "provider", "mode", + "contextMode", "audioMode", "passShape", "controlType", @@ -66,6 +68,7 @@ _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))) +_REMOTE_CONTEXT_MODES = frozenset(get_args(EditContextMode)) class RemoteAsset(AssetCore): @@ -135,6 +138,8 @@ class RemoteGenerationParams(BaseModel): customLoraName: str | None = None numFrames: int | None = None mode: RetakeMode | ExtendMode | None = None + # How much of the clip an Extend or Retake keeps as context, so the phone shows it and Reuse restores it. + contextMode: EditContextMode | None = None startTime: int | float | None = None seed: int | None = None audioMode: IcLoraAudioMode | None = None @@ -352,6 +357,7 @@ def _project_params(value: object) -> RemoteGenerationParams: customLoraName=_project_custom_lora_name(mapping.get("loras")), numFrames=_optional_int(mapping.get("numFrames")), mode=_project_mode(strings.get("mode")), + contextMode=_project_context_mode(strings.get("contextMode")), startTime=_non_negative_number(numbers.get("startTime")), seed=_optional_int(mapping.get("seed")), audioMode=_project_audio_mode(strings.get("audioMode")), @@ -519,6 +525,12 @@ def _project_mode(value: str | None) -> RetakeMode | ExtendMode | None: return None +def _project_context_mode(value: str | None) -> EditContextMode | None: + if value in _REMOTE_CONTEXT_MODES: + return cast(EditContextMode, value) + return None + + def _project_provider(value: str | None) -> ImageProvider | None: if value in _REMOTE_IMAGE_PROVIDERS: return cast(ImageProvider, value) diff --git a/backend/remote/prompt_enhancement.py b/backend/remote/prompt_enhancement.py index 3e3987734..01d0cfcb2 100644 --- a/backend/remote/prompt_enhancement.py +++ b/backend/remote/prompt_enhancement.py @@ -21,7 +21,7 @@ ReplacedWindow, ) from app_handler import AppHandler -from runtime_config.nag_limits import NEGATIVE_PROMPT_MAX_LENGTH +from inference.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 diff --git a/backend/runtime_config/accelerator.py b/backend/runtime_config/accelerator.py index 3feb01b59..155ad64ae 100644 --- a/backend/runtime_config/accelerator.py +++ b/backend/runtime_config/accelerator.py @@ -12,19 +12,12 @@ from __future__ import annotations -import logging from typing import Literal import torch -logger = logging.getLogger(__name__) - AcceleratorBackend = Literal["rocm", "cuda", "mps", "cpu"] -# First compute capability with native fp8 (E4M3/E5M2): Ada Lovelace. -# Ampere (8.x) and Turing (7.5) have no hardware fp8. -_FP8_MIN_COMPUTE_CAPABILITY = (8, 9) - def accelerator_backend() -> AcceleratorBackend: if getattr(torch.version, "hip", None): @@ -56,8 +49,6 @@ def accelerator_supports_fp8(device_index: int = 0) -> bool: """ if accelerator_backend() != "cuda": return False - try: - return torch.cuda.get_device_capability(device_index) >= _FP8_MIN_COMPUTE_CAPABILITY - except Exception: - logger.warning("fp8 capability probe failed; treating device as non-fp8", exc_info=True) - return False + from inference.device import device_supports_fp8 + + return device_supports_fp8(torch.device("cuda", device_index)) diff --git a/backend/runtime_config/custom_loras.py b/backend/runtime_config/custom_loras.py index 5ede08ee4..ab7921850 100644 --- a/backend/runtime_config/custom_loras.py +++ b/backend/runtime_config/custom_loras.py @@ -140,7 +140,7 @@ def validate_safetensors_weights(path: Path) -> None: 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``). + (``inference/patches/safetensors_metadata_fix.py``). """ try: file_size = path.stat().st_size diff --git a/backend/runtime_config/eta.py b/backend/runtime_config/eta.py index 65d51c72e..cd11cfc99 100644 --- a/backend/runtime_config/eta.py +++ b/backend/runtime_config/eta.py @@ -36,14 +36,14 @@ from dataclasses import dataclass, field from typing import TYPE_CHECKING, Literal -from runtime_config.fast_chunking import ( +from inference.fast_chunking import ( CARRY_FRAMES, is_chunked_canvas, last_window_frames, window_candidates, window_count, ) -from runtime_config.ic_lora_tiling import IcLoraTiling +from inference.ic_lora_tiling import IcLoraTiling if TYPE_CHECKING: from runtime_config.budget_evidence import JobShape diff --git a/backend/runtime_config/ic_lora_adaptive_window.py b/backend/runtime_config/ic_lora_adaptive_window.py index 1537cee16..8bcfe96d7 100644 --- a/backend/runtime_config/ic_lora_adaptive_window.py +++ b/backend/runtime_config/ic_lora_adaptive_window.py @@ -23,13 +23,13 @@ from dataclasses import dataclass from typing import Final, Literal -from frame_math import snap_to_frame_grid +from inference.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 +from inference.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). diff --git a/backend/runtime_config/ic_lora_auto_carry.py b/backend/runtime_config/ic_lora_auto_carry.py index 14fd25c3a..6d2477f4f 100644 --- a/backend/runtime_config/ic_lora_auto_carry.py +++ b/backend/runtime_config/ic_lora_auto_carry.py @@ -15,7 +15,7 @@ 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 +from inference.ic_lora_tiling import IcLoraTiling, auto_carry_candidates _ONE_PASS = float("inf") diff --git a/backend/runtime_config/ic_lora_chunking.py b/backend/runtime_config/ic_lora_chunking.py index f6e89be5c..89c62b42c 100644 --- a/backend/runtime_config/ic_lora_chunking.py +++ b/backend/runtime_config/ic_lora_chunking.py @@ -15,21 +15,18 @@ from __future__ import annotations -from frame_math import snap_to_frame_grid +from inference.frame_math import snap_to_frame_grid from runtime_config.ic_lora_stage_mode import IcLoraStageMode, heavy_pass_size -from runtime_config.ic_lora_tiling import DEFAULT_CARRY_FRAMES, IcLoraTiling, transformer_pass_size -from runtime_config.video_job_budget import video_tokens +from inference.ic_lora_tiling import ( + IC_LORA_CHUNK_CARRY_FRAMES as IC_LORA_CHUNK_CARRY_FRAMES, + IcLoraTiling, + ic_lora_carry_frames as ic_lora_carry_frames, + transformer_pass_size, +) +from inference.job_budget import video_tokens # ltx-pipelines default layout: 97-frame windows, 25-frame carry. IC_LORA_CHUNK_PIXEL_FRAMES = 97 -IC_LORA_CHUNK_CARRY_FRAMES = DEFAULT_CARRY_FRAMES - - -def ic_lora_carry_frames(tiling: IcLoraTiling | None) -> int: - """The carry an IC-LoRA run chunks with: the LoRA's own, else the pipeline default.""" - if tiling is not None and tiling.carry_frames is not None: - return tiling.carry_frames - return IC_LORA_CHUNK_CARRY_FRAMES _FORMER_CAP_PIXELS = 1024 * 576 IC_LORA_MAX_SINGLE_WINDOW_TOKENS = 32_940 diff --git a/backend/runtime_config/ic_lora_decode_window.py b/backend/runtime_config/ic_lora_decode_window.py index da066bdfa..e0e296095 100644 --- a/backend/runtime_config/ic_lora_decode_window.py +++ b/backend/runtime_config/ic_lora_decode_window.py @@ -32,8 +32,8 @@ from dataclasses import dataclass from typing import Final -from frame_math import snap_to_frame_grid -from runtime_config.fast_chunking import job_window_count +from inference.frame_math import snap_to_frame_grid +from inference.fast_chunking import job_window_count # Probed minimum decode budget: base + per_mpx * Mpx + per_mpx_frame * Mpx * frames. # 2160p 73f probes at 22.28 GiB (fit 22.54), 2160p 41f at 17.55 (17.77), 1080p 73f at 8.15 (8.25). diff --git a/backend/runtime_config/ic_lora_high_res.py b/backend/runtime_config/ic_lora_high_res.py index 2a92178b1..2f7e98d26 100644 --- a/backend/runtime_config/ic_lora_high_res.py +++ b/backend/runtime_config/ic_lora_high_res.py @@ -23,7 +23,7 @@ from typing import Final, Literal from api_types import IcLoraSettings -from runtime_config.ic_lora_tiling import HIGH_RES_CARRY_FRAMES, IC_LORA_TILE_OVERLAP, IcLoraTiling +from inference.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"] diff --git a/backend/runtime_config/ic_lora_job_budget.py b/backend/runtime_config/ic_lora_job_budget.py index cbcace963..9fd861dda 100644 --- a/backend/runtime_config/ic_lora_job_budget.py +++ b/backend/runtime_config/ic_lora_job_budget.py @@ -13,8 +13,8 @@ IcLoraControl, IcLoraSettings, ) -from frame_math import compute_num_frames -from runtime_config.fast_chunking import job_window_count, last_window_frames +from inference.frame_math import compute_num_frames +from inference.fast_chunking import job_window_count, last_window_frames from runtime_config.ic_lora_adaptive_window import ( HIGH_RES_CANVAS_PIXELS, AdaptiveRefusal, @@ -38,7 +38,7 @@ ) 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 inference.ic_lora_tiling import IcLoraTiling, transformer_pass_size from runtime_config.eta import spatial_tile_count from runtime_config.budget_admission import ( Admission, diff --git a/backend/runtime_config/ic_lora_local_envelope.py b/backend/runtime_config/ic_lora_local_envelope.py index bad846967..34d3a9ee5 100644 --- a/backend/runtime_config/ic_lora_local_envelope.py +++ b/backend/runtime_config/ic_lora_local_envelope.py @@ -24,7 +24,7 @@ from api_types import TargetResolution from runtime_config.grid_fit import fit_in_box, grows_into_box -from runtime_config.ic_lora_tiling import IcLoraTiling +from inference.ic_lora_tiling import IcLoraTiling IC_LORA_SOURCE_TOO_LARGE = "IC_LORA_SOURCE_TOO_LARGE" IC_LORA_V1_ENVELOPE_MESSAGE = ( diff --git a/backend/runtime_config/local_compat_matrix.py b/backend/runtime_config/local_compat_matrix.py index 3511db19e..f9c739535 100644 --- a/backend/runtime_config/local_compat_matrix.py +++ b/backend/runtime_config/local_compat_matrix.py @@ -15,7 +15,7 @@ LTXVideoGenResolution, LTXVideoGenerationResolutionSpec, ) -from frame_math import compute_num_frames +from inference.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, diff --git a/backend/runtime_config/ltx_runtime_paths.py b/backend/runtime_config/ltx_runtime_paths.py index 177467e6a..101a31568 100644 --- a/backend/runtime_config/ltx_runtime_paths.py +++ b/backend/runtime_config/ltx_runtime_paths.py @@ -2,10 +2,10 @@ from __future__ import annotations -from dataclasses import dataclass from pathlib import Path from api_types import LTXLocalModelId +from inference.layout import ResolvedLtxModelPaths from runtime_config.model_download_specs import ( get_existing_cp_path, get_ltx_model_spec, @@ -13,17 +13,7 @@ selected_video_vae_cp, ) - -@dataclass(frozen=True, slots=True) -class ResolvedLtxModelPaths: - """Filesystem paths for the active local LTX model bundle.""" - - checkpoint_path: str - upsampler_path: str - gemma_root: str | None - video_vae_path: str | None - audio_vae_path: str | None - duration_head_path: str | None +__all__ = ["ResolvedLtxModelPaths", "resolve_ltx_runtime_paths"] def resolve_ltx_runtime_paths( diff --git a/backend/runtime_config/model_download_specs.py b/backend/runtime_config/model_download_specs.py index 8392f0afc..517625595 100644 --- a/backend/runtime_config/model_download_specs.py +++ b/backend/runtime_config/model_download_specs.py @@ -20,6 +20,7 @@ LtxCatalogModelFamily, ModelCheckpointID, ) +from inference.layout import LTX_2_5_FAMILY_DIR, get_checkpoint_layout from runtime_config.ltx_api_text_encoder_ids import ( LTX_2_5_API_PROMPT_EMBEDDING_MODEL, LtxApiPromptEmbeddingModel, @@ -27,10 +28,6 @@ logger = logging.getLogger(__name__) -# 2.5-native weights live under this family dir. 2.3 and shared tooling stay at models_root. -# 2.5.1 patches use new filenames in the same dir — not a nested ltx-2.5.1/. -LTX_2_5_FAMILY_DIR = Path("ltx-2.5") - ALL_MODEL_CP_IDS = cast(tuple[ModelCheckpointID, ...], get_args(ModelCheckpointID)) ALL_LTX_LOCAL_MODEL_IDS = cast(tuple[LTXLocalModelId, ...], get_args(LTXLocalModelId)) @@ -267,20 +264,21 @@ def local_aspect_ratios(resolution: str, *, is_a2v: bool) -> tuple[str, ...]: def get_model_cp_spec(cp_id: ModelCheckpointID) -> ModelCheckpointSpec: + layout = get_checkpoint_layout(cp_id) match cp_id: case "ltx-2.3-22b-distilled": return ModelCheckpointSpec( - relative_path=Path("ltx-2.3-22b-distilled.safetensors"), + relative_path=layout.relative_path, expected_size_bytes=43_000_000_000, - is_folder=False, + is_folder=layout.is_folder, repo_id="Lightricks/LTX-2.3", description="Main transformer model", ) case "ltx-2.3-22b-distilled-1.1": return ModelCheckpointSpec( - relative_path=Path("ltx-2.3-22b-distilled-1.1.safetensors"), + relative_path=layout.relative_path, expected_size_bytes=46_149_345_334, - is_folder=False, + is_folder=layout.is_folder, repo_id="Lightricks/LTX-2.3", description="Main transformer model", ) @@ -292,17 +290,17 @@ def get_model_cp_spec(cp_id: ModelCheckpointID) -> ModelCheckpointSpec: # 1.1 so downloads land on the live path; this spec only describes the # orphaned local file. return ModelCheckpointSpec( - relative_path=Path("ltx-2.3-spatial-upscaler-x2-1.0.safetensors"), + relative_path=layout.relative_path, expected_size_bytes=995_743_504, - is_folder=False, + is_folder=layout.is_folder, repo_id="Lightricks/LTX-2.3", description="2x upscaler (legacy)", ) case "ltx-2.3-spatial-upscaler-x2-1.1": return ModelCheckpointSpec( - relative_path=Path("ltx-2.3-spatial-upscaler-x2-1.1.safetensors"), + relative_path=layout.relative_path, expected_size_bytes=995_743_560, - is_folder=False, + is_folder=layout.is_folder, repo_id="Lightricks/LTX-2.3", description="2x upscaler", ) @@ -313,17 +311,17 @@ def get_model_cp_spec(cp_id: ModelCheckpointID) -> ModelCheckpointSpec: # When GenSpace is removed: delete this spec and the GenSpace code that reads it. # The `video-guide` entry in `lora_catalog.json` is then the only definition. return ModelCheckpointSpec( - relative_path=Path("ltx-2.3-22b-ic-lora-union-control-ref0.5.safetensors"), + relative_path=layout.relative_path, expected_size_bytes=654_465_352, - is_folder=False, + is_folder=layout.is_folder, repo_id="Lightricks/LTX-2.3-22b-IC-LoRA-Union-Control", description="Union IC-LoRA control model", ) case "ltx-2.5-22b-distilled": return ModelCheckpointSpec( - relative_path=LTX_2_5_FAMILY_DIR / "ltx-2.5-22b-distilled-transformer-bf16.safetensors", + relative_path=layout.relative_path, expected_size_bytes=42_000_000_000, - is_folder=False, + is_folder=layout.is_folder, repo_id="Lightricks/LTX-2.5", description="LTX 2.5 distilled transformer", repo_filename="diffusion_models/ltx-2.5-22b-distilled-transformer-bf16.safetensors", @@ -331,9 +329,9 @@ def get_model_cp_spec(cp_id: ModelCheckpointID) -> ModelCheckpointSpec: ) case "ltx-2.5-spatial-upscaler-x2-1.0": return ModelCheckpointSpec( - relative_path=LTX_2_5_FAMILY_DIR / "ltx-2.5-latent-spatial-upscaler-x2-bf16-1.0.safetensors", + relative_path=layout.relative_path, expected_size_bytes=995_000_000, - is_folder=False, + is_folder=layout.is_folder, repo_id="Lightricks/LTX-2.5", description="LTX 2.5 2x spatial upscaler", repo_filename="latent_upscale_models/ltx-2.5-latent-spatial-upscaler-x2-bf16-1.0.safetensors", @@ -341,9 +339,9 @@ def get_model_cp_spec(cp_id: ModelCheckpointID) -> ModelCheckpointSpec: ) case "ltx-2.5-video-vae": return ModelCheckpointSpec( - relative_path=LTX_2_5_FAMILY_DIR / "ltx-2.5-video-vae-bf16.safetensors", + relative_path=layout.relative_path, expected_size_bytes=1_470_000_000, - is_folder=False, + is_folder=layout.is_folder, repo_id="Lightricks/LTX-2.5", description="LTX 2.5 video VAE", repo_filename="vae/ltx-2.5-video-vae-bf16.safetensors", @@ -351,9 +349,9 @@ def get_model_cp_spec(cp_id: ModelCheckpointID) -> ModelCheckpointSpec: ) case "ltx-2.5-video-vae-conv": return ModelCheckpointSpec( - relative_path=LTX_2_5_FAMILY_DIR / "ltx-2.5-video-vae-conv-bf16.safetensors", + relative_path=layout.relative_path, expected_size_bytes=1_200_000_000, - is_folder=False, + is_folder=layout.is_folder, repo_id="Lightricks/LTX-2.5", description="LTX 2.5 conv video VAE (fast decode)", repo_filename="vae/ltx-2.5-video-vae-conv-bf16.safetensors", @@ -361,9 +359,9 @@ def get_model_cp_spec(cp_id: ModelCheckpointID) -> ModelCheckpointSpec: ) case "ltx-2.5-audio-vae": return ModelCheckpointSpec( - relative_path=LTX_2_5_FAMILY_DIR / "ltx-2.5-audio-vae-bf16.safetensors", + relative_path=layout.relative_path, expected_size_bytes=365_000_000, - is_folder=False, + is_folder=layout.is_folder, repo_id="Lightricks/LTX-2.5", description="LTX 2.5 audio VAE", repo_filename="vae/ltx-2.5-audio-vae-bf16.safetensors", @@ -371,9 +369,9 @@ def get_model_cp_spec(cp_id: ModelCheckpointID) -> ModelCheckpointSpec: ) case "ltx-2.5-duration-head": return ModelCheckpointSpec( - relative_path=LTX_2_5_FAMILY_DIR / "ltx-2.5-duration-head-bf16.safetensors", + relative_path=layout.relative_path, expected_size_bytes=8_000_000, - is_folder=False, + is_folder=layout.is_folder, repo_id="Lightricks/LTX-2.5", description="LTX 2.5 duration head (auto duration)", repo_filename="model_patches/ltx-2.5-duration-head-bf16.safetensors", @@ -381,44 +379,44 @@ def get_model_cp_spec(cp_id: ModelCheckpointID) -> ModelCheckpointSpec: ) case "dpt-hybrid-midas": return ModelCheckpointSpec( - relative_path=Path("dpt-hybrid-midas"), + relative_path=layout.relative_path, expected_size_bytes=500_000_000, - is_folder=True, + is_folder=layout.is_folder, repo_id="Intel/dpt-hybrid-midas", revision="11eaf7a1cf4bd70740697dbc216f98980c0aeb03", description="DPT-Hybrid MiDaS depth processor", ) case "yolox-l-torchscript": return ModelCheckpointSpec( - relative_path=Path("yolox_l.torchscript.pt"), + relative_path=layout.relative_path, expected_size_bytes=217_697_649, - is_folder=False, + is_folder=layout.is_folder, repo_id="hr16/yolox-onnx", revision="a124b32c3b7c5cebda1c7cd96178f0f9d2050125", description="YOLOX person detector for pose preprocessing", ) case "dw-ll-ucoco-384-bs5": return ModelCheckpointSpec( - relative_path=Path("dw-ll_ucoco_384_bs5.torchscript.pt"), + relative_path=layout.relative_path, expected_size_bytes=135_059_124, - is_folder=False, + is_folder=layout.is_folder, repo_id="hr16/DWPose-TorchScript-BatchSize5", revision="359d662a9b33b73f6d0f21732baf8845f17bb4be", description="DW Pose TorchScript processor", ) case "gemma-3-12b-it-qat-q4_0-unquantized": return ModelCheckpointSpec( - relative_path=Path("gemma-3-12b-it-qat-q4_0-unquantized"), + relative_path=layout.relative_path, expected_size_bytes=25_000_000_000, - is_folder=True, + is_folder=layout.is_folder, repo_id="Lightricks/gemma-3-12b-it-qat-q4_0-unquantized", description="Gemma 3 text encoder (folder)", ) case "gemma4-12b-with-proj-ltx-2.5": return ModelCheckpointSpec( - relative_path=LTX_2_5_FAMILY_DIR / "gemma4-12b-with-proj-ltx-2.5-bf16.safetensors", + relative_path=layout.relative_path, expected_size_bytes=26_300_000_000, - is_folder=False, + is_folder=layout.is_folder, repo_id="Lightricks/LTX-2.5", description="Gemma 4 text encoder with LTX 2.5 projections", repo_filename="text_encoders/gemma4-12b-with-proj-ltx-2.5-bf16.safetensors", @@ -426,17 +424,17 @@ def get_model_cp_spec(cp_id: ModelCheckpointID) -> ModelCheckpointSpec: ) case "gemma-4-e2b-it": return ModelCheckpointSpec( - relative_path=Path("gemma-4-E2B-it"), + relative_path=layout.relative_path, expected_size_bytes=10_278_849_571, - is_folder=True, + is_folder=layout.is_folder, repo_id="google/gemma-4-E2B-it", description="Gemma 4 E2B instruct prompt enhancer (folder)", ) case "z-image-turbo": return ModelCheckpointSpec( - relative_path=Path("Z-Image-Turbo"), + relative_path=layout.relative_path, expected_size_bytes=31_000_000_000, - is_folder=True, + is_folder=layout.is_folder, repo_id="Tongyi-MAI/Z-Image-Turbo", description="Z-Image-Turbo model for text-to-image generation", ) diff --git a/backend/runtime_config/runtime_config.py b/backend/runtime_config/runtime_config.py index db81d1bb8..329d22ab4 100644 --- a/backend/runtime_config/runtime_config.py +++ b/backend/runtime_config/runtime_config.py @@ -64,6 +64,19 @@ class RuntimeConfig: parallel_queue_lanes: bool = True # User-chosen assets folder (LTX_ASSETS_DIR). None means /assets. assets_dir: Path | None = None + # Windows Smart App Control enforces. It blocks the unsigned .pyd files Triton + # compiles at run time, so torch.compile cannot run. Probed once at startup. + smart_app_control_on: bool = False + + @property + def torch_compile_available(self) -> bool: + """Whether the torch.compile setting can take effect on this runtime. + + SageAttention's graph breaks conflict with compile (see + ``PipelinesHandler._compile_if_enabled``). Smart App Control blocks the + Triton code that Inductor needs. + """ + return not self.use_sage_attention and not self.smart_app_control_on @property def in_flight_dir(self) -> Path: diff --git a/backend/runtime_config/runtime_policy.py b/backend/runtime_config/runtime_policy.py index f2a004d5f..491aba15b 100644 --- a/backend/runtime_config/runtime_policy.py +++ b/backend/runtime_config/runtime_policy.py @@ -2,12 +2,17 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Literal - -if TYPE_CHECKING: - # Runtime import would cycle: api_types initializes through this module - # while services/__init__ needs api_types (see runtime_config.py). - from services.storage_info.storage_info import DriveType +from typing import Literal + +from inference.device import ( + CUDA_CPU_OFFLOAD_RAM_FLOOR_GB as CUDA_CPU_OFFLOAD_RAM_FLOOR_GB, + CUDA_FULL_VRAM_GB as CUDA_FULL_VRAM_GB, + CUDA_VRAM_FLOOR_GB as CUDA_VRAM_FLOOR_GB, + LINUX_VRAM_FLOOR_GB as LINUX_VRAM_FLOOR_GB, + decide_cuda_local_generation_mode, + should_disk_stream_cuda_weights as should_disk_stream_cuda_weights, + windows_checkpoint_streams_from_disk as windows_checkpoint_streams_from_disk, +) LocalGenerationMode = Literal[ "full_models_loading", @@ -31,35 +36,6 @@ # copy — ``DARWIN_ADVERTISED_FLOOR_GB`` is the documented minimum. DARWIN_STREAMING_FLOOR_GB = 24 -# CUDA discrete VRAM floors, compared against exact GiB (bytes-derived via -# ``MemoryBudget.total_vram_gib`` at the production path; plain integers compare -# identically against integer floors). Below the streaming floor local gen is not -# viable. At/above the full floor, fp8-capable cards can hold the halved transformer -# resident. The streaming floor is 9: an early-out, not a policy — derived, not -# picked. The per-cell model is the real gate (it refuses unfitting cells against -# free VRAM per request), so the floor only skips grid evaluation on hardware that -# cannot run the smallest cell: 8.00 GiB (540p/5s, Phase 2 bracket (7.9, 8.0]) + -# ~1.00 GiB typical desktop occupancy (Phase 0). Cards report below nominal (16 GB -# cards report 15.99 — see ``test_gpu_raw_capacity``), so 10 GB-class cards at -# ~9.99 stream and the model offers them ~8 cells, while 8 GB-class cards at ~7.99 -# stay excluded. Per-cell budgets (not this floor) decide what each card offers. -# The 1.00 GiB desktop figure is an estimate (no Phase 0 survey was captured) — -# do not tighten this floor toward 8.00 on its strength. fp8 cards only: without -# fp8 the bf16 path is unmeasured, so non-fp8 CUDA keeps the 15 floor below. -CUDA_VRAM_FLOOR_GB = 9 -# CUDA_VRAM_FLOOR_GB is Windows-fp8-measured only (5090 laws; the bf16 -# path is unmeasured and the legacy curve under-asks 9-14 GB cards). Linux -# and non-fp8 Windows ride the legacy curve below 15 and keep the old floor. -LINUX_VRAM_FLOOR_GB = 15 -CUDA_FULL_VRAM_GB = 31 - -# CUDA OffloadMode.CPU pre-pins every transformer block in host RAM. ltx-pipelines -# documents that path as ~36 GB RAM + ~5 GB VRAM. On Linux those buffers are -# page-locked (unswappable), so a 32 GB machine — the advertised local-gen floor — -# dies in the kernel OOM killer with VRAM still empty (LTX-Desktop#163). Below this -# total-RAM floor, stream from disk instead (OffloadMode.DISK, ~5 GB host). -CUDA_CPU_OFFLOAD_RAM_FLOOR_GB = 40 - def decide_local_generation_mode( system: str, @@ -82,7 +58,9 @@ def decide_local_generation_mode( exact bytes-derived where available, integer-floored otherwise (both compare identically against these integer floors) — and "full_models_loading" (>=31 GB) holds the fp8-halved (~23 GB) transformer - resident. Pass ``fp8_capable=False`` (ROCm today — see + resident. That branch is ``inference.device.decide_cuda_local_generation_mode``, + so a host that copies only ``inference/`` can call it without this module. + Pass ``fp8_capable=False`` (ROCm today — see ``runtime_config.accelerator.accelerator_backend``) to stay on the streaming path regardless of VRAM: without fp8 the full ~42-46 GB bf16 transformer would try to stay resident at that floor and OOM. On Apple Silicon (Darwin) @@ -123,88 +101,12 @@ def decide_local_generation_mode( return "streaming_models_loading" if system in ("Windows", "Linux"): - if not cuda_available: - return "unsupported" - if vram_gb is None: - return "unsupported" - floor_gb = ( - CUDA_VRAM_FLOOR_GB - if system == "Windows" and fp8_capable - else LINUX_VRAM_FLOOR_GB - ) - if vram_gb < floor_gb: - return "unsupported" - # full_models_loading's CUDA_FULL_VRAM_GB floor assumes the fp8-halved (~23 GB) - # transformer (see module docstring). Without fp8 (ROCm today — see - # runtime_config.accelerator.accelerator_backend), holding the full bf16 - # (~42-46 GB) transformer resident instead would OOM at this floor, so stay on - # the streaming path regardless of VRAM until a real bf16-full-resident floor is - # established on non-CUDA hardware. - # Originally contributed by boxwrench in https://github.com/Lightricks/LTX-Desktop/pull/160 - if not fp8_capable: - return "streaming_models_loading" - if vram_gb < CUDA_FULL_VRAM_GB: - return "streaming_models_loading" - return "full_models_loading" + return decide_cuda_local_generation_mode(system, cuda_available, vram_gb, fp8_capable) # Fail closed for non-target platforms unless explicitly relaxed. return "unsupported" -def windows_checkpoint_streams_from_disk( - system: str, drive_type: DriveType | None -) -> bool: - """Whether Windows can stream checkpoint weights from disk (NVMe only). - - 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, - cpu_ram_floor_gb: int | None = CUDA_CPU_OFFLOAD_RAM_FLOOR_GB, -) -> bool: - """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 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": - 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 - 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: """Return the streaming_prefetch_count to pass to a local pipeline. diff --git a/backend/runtime_config/smart_app_control.py b/backend/runtime_config/smart_app_control.py new file mode 100644 index 000000000..0927af36a --- /dev/null +++ b/backend/runtime_config/smart_app_control.py @@ -0,0 +1,63 @@ +"""Detect Windows Smart App Control (SAC). + +SAC in enforcement mode blocks unsigned code that has no good reputation. The app +builds such code at run time: Triton compiles ``cuda_utils`` and every kernel launcher +into ``~/.triton/cache`` as unsigned ``.pyd`` files, and SageAttention needs Triton. +Windows then fails the import with "An Application Control policy has blocked this +file" (CodeIntegrity event 3077). Signing the cache output is not possible, so callers +must not start the Triton-dependent paths while SAC enforces. + +The state lives in ``HKLM\\SYSTEM\\CurrentControlSet\\Control\\CI\\Policy`` as the DWORD +``VerifiedAndReputablePolicyState``: 0 = off, 1 = on, 2 = evaluation. Evaluation mode +does not block code, so only ``on`` counts as blocking. +""" + +from __future__ import annotations + +import sys +from typing import Literal + +SmartAppControlState = Literal["off", "on", "evaluation", "unknown"] + +_CI_POLICY_KEY = r"SYSTEM\CurrentControlSet\Control\CI\Policy" +_SAC_STATE_VALUE = "VerifiedAndReputablePolicyState" + + +def parse_smart_app_control_state(value: object) -> SmartAppControlState: + """Map the registry DWORD to a state. Unexpected values map to "unknown".""" + match value: + case 0: + return "off" + case 1: + return "on" + case 2: + return "evaluation" + case _: + return "unknown" + + +def detect_smart_app_control() -> SmartAppControlState: + """Return the SAC state of this host. + + Non-Windows hosts and Windows builds without the value (no SAC) return "off". + Any other read failure returns "unknown". Callers treat "unknown" like "off", so + a failed probe never removes a feature that works today. + """ + if sys.platform != "win32": + return "off" + + import winreg + + try: + with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, _CI_POLICY_KEY) as key: + value, _value_type = winreg.QueryValueEx(key, _SAC_STATE_VALUE) + except FileNotFoundError: + return "off" + except OSError: + return "unknown" + return parse_smart_app_control_state(value) + + +def smart_app_control_blocks_unsigned_code(state: SmartAppControlState) -> bool: + """True when SAC enforces, so run-time compiled Triton code cannot load.""" + return state == "on" diff --git a/backend/runtime_config/video_job_budget.py b/backend/runtime_config/video_job_budget.py index 672ce0472..087738e4a 100644 --- a/backend/runtime_config/video_job_budget.py +++ b/backend/runtime_config/video_job_budget.py @@ -35,7 +35,10 @@ from typing import TYPE_CHECKING, Final, Literal, assert_never from api_types import LTXLocalModelId -from frame_math import compute_num_frames +from inference.frame_math import compute_num_frames +from inference.device import windows_checkpoint_streams_from_disk +from inference.errors import VIDEO_JOB_TOO_LARGE +from inference.job_budget import video_tokens as video_tokens from runtime_config.budget_admission import ( Admission, Admitted, @@ -64,7 +67,7 @@ DeviceCalibration, envelope_for, ) -from runtime_config.fast_chunking import ( +from inference.fast_chunking import ( MAX_WINDOW_TOKENS, PEAK_PLATEAU_WINDOWS, is_chunked_canvas, @@ -91,7 +94,6 @@ from runtime_config.runtime_policy import ( CUDA_CPU_OFFLOAD_RAM_FLOOR_GB, LocalGenerationMode, - windows_checkpoint_streams_from_disk, ) from services.storage_info.storage_info import DriveType @@ -99,7 +101,6 @@ # Runtime import would cycle (local_runtime imports this module). from runtime_config.runtime_config import RuntimeConfig -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." @@ -395,12 +396,6 @@ def required_gib(self, tokens: float) -> float: NOMINAL_MPS_POOL_RATIO = 0.78 -def video_tokens(height: int, width: int, frames: int) -> float: - """LTX-2 latent tokens: 8-frame temporal, 32 px spatial.""" - temporal = (max(1, frames) - 1) / 8.0 + 1.0 - 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)) diff --git a/backend/server_utils/heartbeat.py b/backend/server_utils/heartbeat.py index fd811a1b5..2749a1542 100644 --- a/backend/server_utils/heartbeat.py +++ b/backend/server_utils/heartbeat.py @@ -23,7 +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 +from inference.run_peak import fold_and_reset_cuda_peak, note_free_sample logger = logging.getLogger(__name__) _active = Lock() diff --git a/backend/services/__init__.py b/backend/services/__init__.py index 7bb0874d1..c912f7432 100644 --- a/backend/services/__init__.py +++ b/backend/services/__init__.py @@ -2,7 +2,6 @@ from services.interfaces import ( DepthProcessorPipeline, - FastVideoPipeline, ZitAPIClient, ImageGenerationPipeline, GpuCleaner, @@ -10,7 +9,6 @@ HTTPClient, HttpResponseLike, HttpTransportError, - IcLoraPipeline, LTXAPIClient, ModelDownloader, PoseProcessorPipeline, @@ -33,9 +31,7 @@ "TaskRunner", "TextEncoder", "VideoPipelineModelType", - "FastVideoPipeline", "ZitAPIClient", "ImageGenerationPipeline", - "IcLoraPipeline", "LTXAPIClient", ] diff --git a/backend/services/assistant_run.py b/backend/services/assistant_run.py index 828107930..84ef4a2ef 100644 --- a/backend/services/assistant_run.py +++ b/backend/services/assistant_run.py @@ -30,6 +30,8 @@ class AssistantRun(BaseModel): # The recipe nudge fires at most once per request, and not after a recipe job is queued, # so continuations after job updates and plain jobs beside a recipe job are not nudged. recipe_nudged: bool = False + # The empty-prompt nudge for an extension or retake fires at most once per request. + prompt_nudged: bool = False response: AssistantTurnResponse | None = None stopped: bool = False diff --git a/backend/services/fast_video_pipeline/__init__.py b/backend/services/fast_video_pipeline/__init__.py deleted file mode 100644 index d0175acd0..000000000 --- a/backend/services/fast_video_pipeline/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -from services.fast_video_pipeline.fast_video_pipeline import FastVideoPipeline - -__all__ = ["FastVideoPipeline"] diff --git a/backend/services/features/image/text_to_image.py b/backend/services/features/image/text_to_image.py index 925f71729..939cfa767 100644 --- a/backend/services/features/image/text_to_image.py +++ b/backend/services/features/image/text_to_image.py @@ -19,7 +19,7 @@ ) 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 inference.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 ( diff --git a/backend/services/features/video/alpha_cutout.py b/backend/services/features/video/alpha_cutout.py index dd33be211..0f9321a74 100644 --- a/backend/services/features/video/alpha_cutout.py +++ b/backend/services/features/video/alpha_cutout.py @@ -21,7 +21,7 @@ timeout_for_pixels, timeout_for_source_duration, ) -from services.generation_interrupt import GenerationCancelledError, is_requested +from inference.interrupt import GenerationCancelledError, is_requested from services.generation_queue.types import OutputAllocation, OutputPlan from services.media_probe import probe_file, video_fps, video_frame_count from services.records import MediaError diff --git a/backend/services/features/video/audio_to_video.py b/backend/services/features/video/audio_to_video.py index e101422e5..f667693a6 100644 --- a/backend/services/features/video/audio_to_video.py +++ b/backend/services/features/video/audio_to_video.py @@ -28,7 +28,7 @@ require_video_output, ) from runtime_config.model_download_specs import local_aspect_ratios -from services.generation_interrupt import GenerationCancelledError, is_cancel_exception +from inference.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 diff --git a/backend/services/features/video/cutout_alignment.py b/backend/services/features/video/cutout_alignment.py index 91ef337d1..340ce39fb 100644 --- a/backend/services/features/video/cutout_alignment.py +++ b/backend/services/features/video/cutout_alignment.py @@ -23,10 +23,10 @@ FFMPEG_TIMEOUT_SECONDS, FfmpegCancelledError, ffmpeg_seconds, - run_ffmpeg, timeout_for_pixels, ) -from services.generation_interrupt import GenerationCancelledError, is_requested +from services.ffmpeg import run_ffmpeg +from inference.interrupt import GenerationCancelledError, is_requested from services.media_probe import video_frame_count from services.records import MediaError diff --git a/backend/services/features/video/edit_executor.py b/backend/services/features/video/edit_executor.py index 336ce2b0c..e4660aa70 100644 --- a/backend/services/features/video/edit_executor.py +++ b/backend/services/features/video/edit_executor.py @@ -33,8 +33,9 @@ require_supported_contract_version, require_video_output, ) -from services.generation_interrupt import GenerationCancelledError, is_cancel_exception -from services.fast_video_pipeline.nag_config import ( +from inference.interrupt import GenerationCancelledError, is_cancel_exception +from services.ffmpeg import FfmpegTimeoutError, FfmpegUnavailableError +from inference.fast_video_pipeline.nag_config import ( DEFAULT_SCALE as DEFAULT_NAG_SCALE, NagConfig, NagDecision, @@ -44,9 +45,9 @@ 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 inference.errors import CapabilityFailedError from services.records import ( AssetRecord, - CapabilityFailedError, GenerationRecord, MediaError, ) @@ -431,6 +432,10 @@ def _infer() -> None: raise capability_failed_from_http(exc) from exc if isinstance(exc, CapabilityFailedError): raise + if isinstance(exc, FfmpegUnavailableError): + raise CapabilityFailedError("ffmpeg is not available") from exc + if isinstance(exc, FfmpegTimeoutError): + raise CapabilityFailedError("ffmpeg timed out") from exc if isinstance(exc, MediaError): raise CapabilityFailedError(str(exc)) from exc raise diff --git a/backend/services/features/video/extend.py b/backend/services/features/video/extend.py index acd88137f..2952ed52c 100644 --- a/backend/services/features/video/extend.py +++ b/backend/services/features/video/extend.py @@ -16,22 +16,24 @@ 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 +from inference.fast_video_pipeline.windowed_run import measured_edit +from services.features.video.window_estimates import edit_window_estimate_gib from services.records import AssetRecord, GenerationRecord -from services.retake_pipeline.window import ( - MIN_EXTEND_CONTEXT_FRAMES, +from inference.retake_pipeline.window import ( EditRefusal, ExtendEncodeWindow, + extend_context_floor, prepare_extend_window, ) -from services.retake_pipeline.extend_stitch import stitch_extend_output +from inference.retake_pipeline.extend_stitch import stitch_extend_output +from inference.retake_pipeline.voice_context import VoiceBridge, find_voice_bridge, write_voice_bridge from state.app_state_types import RetakePipelineState FEATURE = "extend" logger = logging.getLogger(__name__) -@dataclass(frozen=True) +@dataclass class _PreparedExtend: params: ExtendParams video: AssetRecord @@ -47,6 +49,9 @@ class _PreparedExtend: dest_path: Path windowed_path: str ran: JobEnvelope | None + # Set when the Short context window has no speech: the model reads a bridge clip, not the + # source. ``generate`` writes the clip, and clears this when it cannot. + bridge: VoiceBridge | None = None class ExtendExecutor(VideoEditExecutor[ExtendParams, ExtendInputs, _PreparedExtend]): @@ -105,6 +110,7 @@ def prepare( frame_cap=frame_cap, duration=params.duration, mode=params.mode, + context_mode=params.contextMode, ) if isinstance(prepared, EditRefusal): prepared.raise_capability_error() @@ -136,6 +142,7 @@ def rewindow(free_cap: int) -> int: duration=params.duration, mode=params.mode, minimum_context_frames=1, + context_mode=params.contextMode, ) # Unreachable while MAX_SHRINK_GAP_FRAMES < 120 (a passing first # gate leaves extend <= total - 121, which always fits a free cap @@ -143,12 +150,13 @@ def rewindow(free_cap: int) -> int: # with the max named instead of crashing on the refusal below. if isinstance(shrunk, EditRefusal): shrunk.raise_capability_error() - if shrunk.window.context_frames < MIN_EXTEND_CONTEXT_FRAMES: + floor = extend_context_floor(params.contextMode, fps) + if shrunk.window.context_frames < floor: logger.warning( "Extend %s running with %d context frames, below the %d-frame coherence floor (unmeasured regime)", generation.id, shrunk.window.context_frames, - MIN_EXTEND_CONTEXT_FRAMES, + floor, ) logger.info( "Extend %s free gate refused the total-fitting %d-frame window; shrinking to free-gated cap %d (encode %d)", @@ -172,9 +180,10 @@ def rewindow(free_cap: int) -> int: rewindow=rewindow, ) logger.info( - "Extend %s started (%s, source %dx%d → %dx%d canvas %dx%d, %d source frames @ %g fps, %s +%d, encode %d, seed=%d)", + "Extend %s started (%s, %s context, source %dx%d → %dx%d canvas %dx%d, %d source frames @ %g fps, %s +%d, encode %d, seed=%d)", generation.id, local_model_id, + params.contextMode, source_width, source_height, content_width, @@ -188,6 +197,7 @@ def rewindow(free_cap: int) -> int: window.context_frames, seed, ) + bridge = self._voice_bridge(params, video, window, fps, source_frames) return _PreparedExtend( params=params, video=video, @@ -203,17 +213,62 @@ def rewindow(free_cap: int) -> int: dest_path=dest, windowed_path=windowed_path, ran=ran, + bridge=bridge, ) + @staticmethod + def _voice_bridge( + params: ExtendParams, + video: AssetRecord, + window: ExtendEncodeWindow, + fps: float, + source_frames: int, + ) -> VoiceBridge | None: + """Plan a bridge with speech, when the Short context window has none. See voice_context.""" + if params.contextMode != "short": + return None + bridge = find_voice_bridge( + video.path, window=window, fps=fps, source_frames=source_frames, mode=params.mode + ) + if bridge is not None: + logger.info( + "Extend voice bridge: %d speech frames from frame %d, %d seam frames from frame %d", + bridge.speech_frames, + bridge.speech_start_frame, + bridge.seam_frames, + bridge.seam_start_frame, + ) + return bridge + def generate(self, prepared: _PreparedExtend) -> None: frames = prepared.window.context_frames + prepared.extend_frames - with measured_edit(prepared.canvas_width, prepared.canvas_height, frames): - self._generate(prepared) + dest = prepared.dest_path + bridge_path = dest.with_name(f"{dest.stem}.voice{dest.suffix}") + try: + if prepared.bridge is not None and not write_voice_bridge( + prepared.video.path, str(bridge_path), prepared.bridge, prepared.fps + ): + prepared.bridge = None + with measured_edit( + prepared.canvas_width, + prepared.canvas_height, + frames, + estimate_gib=edit_window_estimate_gib, + ): + self._generate(prepared, bridge_path if prepared.bridge is not None else None) + finally: + bridge_path.unlink(missing_ok=True) - def _generate(self, prepared: _PreparedExtend) -> None: + def _generate(self, prepared: _PreparedExtend, bridge_path: Path | None) -> None: nag = self.resolve_nag(prepared.params, prepared.pipeline_state) + # The bridge replaces the source window, so it is read from its start. + video_path, encode_start_time = ( + (str(bridge_path), 0.0) + if bridge_path + else (prepared.video.path, prepared.window.start_time(prepared.fps)) + ) prepared.pipeline_state.pipeline.extend( - video_path=prepared.video.path, + video_path=video_path, prompt=prepared.params.prompt, extend_frames=prepared.extend_frames, mode=prepared.params.mode, @@ -228,7 +283,7 @@ def _generate(self, prepared: _PreparedExtend) -> None: content_width=prepared.content_width, content_height=prepared.content_height, target_frames=prepared.window.context_frames, - encode_start_time=prepared.window.start_time(prepared.fps), + encode_start_time=encode_start_time, encode_max_duration=prepared.window.max_duration(prepared.fps), nag=nag, ) @@ -244,4 +299,5 @@ def stitch(self, prepared: _PreparedExtend) -> None: extend_frames=prepared.extend_frames, target_width=prepared.content_width, target_height=prepared.content_height, + seam_frames=prepared.bridge.seam_frames if prepared.bridge else None, ) diff --git a/backend/services/features/video/ic_lora_recipe.py b/backend/services/features/video/ic_lora_recipe.py index a70c0c57e..d28f45319 100644 --- a/backend/services/features/video/ic_lora_recipe.py +++ b/backend/services/features/video/ic_lora_recipe.py @@ -68,14 +68,15 @@ require_video_output, ) from services.ffmpeg import FFMPEG_PROTOCOL_WHITELIST, run_ffmpeg, timeout_for_pixels -from services.generation_interrupt import GenerationCancelledError, is_cancel_exception +from inference.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, MediaError +from inference.errors import CapabilityFailedError +from services.records import GenerationRecord, MediaError logger = logging.getLogger(__name__) diff --git a/backend/services/features/video/ic_lora_sheet_recipe.py b/backend/services/features/video/ic_lora_sheet_recipe.py index b49cd2d54..d77ebcb58 100644 --- a/backend/services/features/video/ic_lora_sheet_recipe.py +++ b/backend/services/features/video/ic_lora_sheet_recipe.py @@ -15,7 +15,7 @@ SynthesizedIcLoraExecutor, SynthesizedJob, ) -from services.records import CapabilityFailedError +from inference.errors import CapabilityFailedError class IcLoraSheetRecipeExecutor(SynthesizedIcLoraExecutor[IcLoraSheetInputs]): diff --git a/backend/services/features/video/image_to_video.py b/backend/services/features/video/image_to_video.py index fa2f58e5c..511484c1d 100644 --- a/backend/services/features/video/image_to_video.py +++ b/backend/services/features/video/image_to_video.py @@ -30,7 +30,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 inference.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 diff --git a/backend/services/features/video/job_common.py b/backend/services/features/video/job_common.py index f06537daf..6d537f1c3 100644 --- a/backend/services/features/video/job_common.py +++ b/backend/services/features/video/job_common.py @@ -25,7 +25,8 @@ 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 inference.errors import CapabilityFailedError +from services.records import AssetRecord from state.app_settings import MAX_GENERATION_SEED INPUT_ASSET_NOT_FOUND = "INPUT_ASSET_NOT_FOUND" diff --git a/backend/services/features/video/keyframes.py b/backend/services/features/video/keyframes.py index 4aebe9dca..7ccbd8782 100644 --- a/backend/services/features/video/keyframes.py +++ b/backend/services/features/video/keyframes.py @@ -30,7 +30,7 @@ require_video_output, require_supported_contract_version, ) -from services.generation_interrupt import GenerationCancelledError, is_cancel_exception +from inference.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 diff --git a/backend/services/features/video/lanczos_guide.py b/backend/services/features/video/lanczos_guide.py index e24ea469c..8138e50b8 100644 --- a/backend/services/features/video/lanczos_guide.py +++ b/backend/services/features/video/lanczos_guide.py @@ -17,7 +17,7 @@ run_ffmpeg, timeout_for_pixels, ) -from services.generation_interrupt import GenerationCancelledError, is_requested +from inference.interrupt import GenerationCancelledError, is_requested from services.media_probe import video_frame_count from services.records import MediaError diff --git a/backend/services/features/video/motion_path.py b/backend/services/features/video/motion_path.py index 0299d50d7..ffb00f95e 100644 --- a/backend/services/features/video/motion_path.py +++ b/backend/services/features/video/motion_path.py @@ -16,8 +16,8 @@ from numpy.typing import NDArray from api_motion_path import MotionPath, MotionPathEasing, MotionPathPoint, MotionPathVec2 -from frame_math import compute_num_frames -from services.retake_pipeline.rgb_stitch import write_rgb_video +from inference.frame_math import compute_num_frames +from inference.retake_pipeline.rgb_stitch import write_rgb_video _C1 = 1.70158 _C2 = _C1 * 1.525 diff --git a/backend/services/features/video/retake.py b/backend/services/features/video/retake.py index 61a77e6a9..e067dae9e 100644 --- a/backend/services/features/video/retake.py +++ b/backend/services/features/video/retake.py @@ -16,17 +16,19 @@ 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 -from services.records import AssetRecord, CapabilityFailedError, GenerationRecord -from services.retake_pipeline.retake_mode import ( +from inference.fast_video_pipeline.windowed_run import measured_edit +from services.features.video.window_estimates import edit_window_estimate_gib +from inference.errors import CapabilityFailedError +from services.records import AssetRecord, GenerationRecord +from inference.retake_pipeline.retake_mode import ( InvalidRetakeModeError, resolve_retake_mode, ) -from services.retake_pipeline.retake_stitch import stitch_retake_output -from services.retake_pipeline.window import ( +from inference.retake_pipeline.retake_stitch import stitch_retake_output +from inference.retake_pipeline.window import ( EditRefusal, RetakeEncodeWindow, - feathered_mask_times, + retake_mask_times, prepare_retake_window, ) from state.app_state_types import RetakePipelineState @@ -113,11 +115,12 @@ def prepare( frame_cap=frame_cap, start_time=params.startTime, duration=params.duration, + context_mode=params.contextMode, ) if isinstance(prepared, EditRefusal): prepared.raise_capability_error() window, end_time = prepared.window, prepared.end_time - region_start, region_end = feathered_mask_times(window, fps) + region_start, region_end = retake_mask_times(window, fps) if ( abs(content_width - source_width) > 31 or abs(content_height - source_height) > 31 @@ -140,6 +143,7 @@ def rewindow(free_cap: int) -> int: frame_cap=free_cap, start_time=params.startTime, duration=params.duration, + context_mode=params.contextMode, ) if isinstance(shrunk, EditRefusal): shrunk.raise_capability_error() @@ -151,7 +155,7 @@ def rewindow(free_cap: int) -> int: shrunk.window.encode_frames, ) window, end_time = shrunk.window, shrunk.end_time - region_start, region_end = feathered_mask_times(window, fps) + region_start, region_end = retake_mask_times(window, fps) return window.encode_frames pipeline_state, ran = self._load_edit_window( @@ -166,9 +170,10 @@ def rewindow(free_cap: int) -> int: rewindow=rewindow, ) logger.info( - "Retake %s started (%s, source %dx%d → %dx%d canvas %dx%d, %d frames @ %g fps, %s %.2fs–%.2fs, encode %d, seed=%d)", + "Retake %s started (%s, %s context, source %dx%d → %dx%d canvas %dx%d, %d frames @ %g fps, %s %.2fs–%.2fs, encode %d, seed=%d)", generation.id, local_model_id, + params.contextMode, source_width, source_height, content_width, @@ -204,7 +209,12 @@ def rewindow(free_cap: int) -> int: ) def generate(self, prepared: _PreparedRetake) -> None: - with measured_edit(prepared.canvas_width, prepared.canvas_height, prepared.window.encode_frames): + with measured_edit( + prepared.canvas_width, + prepared.canvas_height, + prepared.window.encode_frames, + estimate_gib=edit_window_estimate_gib, + ): self._generate(prepared) def _generate(self, prepared: _PreparedRetake) -> None: @@ -243,4 +253,5 @@ def stitch(self, prepared: _PreparedRetake) -> None: fps=prepared.fps, target_width=prepared.content_width, target_height=prepared.content_height, + regenerate_audio=prepared.regenerate_audio, ) diff --git a/backend/services/features/video/synthesized_ic_lora.py b/backend/services/features/video/synthesized_ic_lora.py index f6303affc..8047aac2c 100644 --- a/backend/services/features/video/synthesized_ic_lora.py +++ b/backend/services/features/video/synthesized_ic_lora.py @@ -41,14 +41,15 @@ require_supported_contract_version, require_video_output, ) -from services.generation_interrupt import GenerationCancelledError, is_cancel_exception +from inference.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 +from inference.errors import CapabilityFailedError +from services.records import GenerationRecord TInputs = TypeVar("TInputs", bound=BaseModel) diff --git a/backend/services/features/video/text_to_video.py b/backend/services/features/video/text_to_video.py index 8303b4837..579eddbd5 100644 --- a/backend/services/features/video/text_to_video.py +++ b/backend/services/features/video/text_to_video.py @@ -26,10 +26,11 @@ spec_pass_shape, spec_risk_allowance, ) -from services.generation_interrupt import GenerationCancelledError, is_cancel_exception +from inference.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 +from inference.errors import CapabilityFailedError +from services.records import GenerationRecord FEATURE = "text-to-video" diff --git a/backend/services/features/video/window_estimates.py b/backend/services/features/video/window_estimates.py new file mode 100644 index 000000000..0fe7153ee --- /dev/null +++ b/backend/services/features/video/window_estimates.py @@ -0,0 +1,36 @@ +"""Desktop budget estimates injected into headless window telemetry.""" + +from __future__ import annotations + +import sys + +from inference.job_budget import video_tokens +from runtime_config.video_job_budget import ( + decode_tile_tokens, + edit_job_stream_gib, + fast_job_stream_gib, +) + + +def fast_window_estimate_gib( + *, + width: int, + height: int, + frames: int, + windows: int, + last_frames: int, +) -> float: + return fast_job_stream_gib( + video_tokens(height, width, frames), + windows=windows, + darwin=sys.platform == "darwin", + last_tokens=video_tokens(height, width, last_frames), + ) + + +def edit_window_estimate_gib(*, width: int, height: int, frames: int) -> float: + return edit_job_stream_gib( + video_tokens(height, width, frames), + darwin=sys.platform == "darwin", + decode_tokens=decode_tile_tokens(height, width, frames), + ) diff --git a/backend/services/ffmpeg.py b/backend/services/ffmpeg.py index 2a68a3e44..e59b5382a 100644 --- a/backend/services/ffmpeg.py +++ b/backend/services/ffmpeg.py @@ -1,92 +1,30 @@ -"""ffmpeg invocation shared by audio trim and video stitch.""" +"""Desktop ffmpeg adapter: map pathless inference errors onto ``MediaError``. + +Desktop imports the constants, the errors, and ``run_ffmpeg`` from here. +Inference callers keep ``inference.ffmpeg``, which cannot import ``services``. +""" from __future__ import annotations -import logging import subprocess -import time from collections.abc import Callable -import imageio_ffmpeg - +from inference.ffmpeg import ( + FFMPEG_PROTOCOL_WHITELIST as FFMPEG_PROTOCOL_WHITELIST, + FFMPEG_TIMEOUT_SECONDS as FFMPEG_TIMEOUT_SECONDS, + PIXEL_TIMEOUT_CAP_SECONDS as PIXEL_TIMEOUT_CAP_SECONDS, + STITCH_TIMEOUT_CAP_SECONDS as STITCH_TIMEOUT_CAP_SECONDS, + STITCH_TIMEOUT_PER_SOURCE_SECOND as STITCH_TIMEOUT_PER_SOURCE_SECOND, + FfmpegCancelledError as FfmpegCancelledError, + FfmpegTimeoutError as FfmpegTimeoutError, + FfmpegUnavailableError as FfmpegUnavailableError, + ffmpeg_seconds as ffmpeg_seconds, + run_ffmpeg as _run_ffmpeg, + timeout_for_pixels as timeout_for_pixels, + timeout_for_source_duration as timeout_for_source_duration, +) from services.records import MediaError -logger = logging.getLogger(__name__) - -# Local file outputs/inputs only (plus pipe for stdio-style transports). -FFMPEG_PROTOCOL_WHITELIST = "file,pipe" -# Re-encoding a long import can legitimately take tens of seconds. -FFMPEG_TIMEOUT_SECONDS = 120.0 -# Wing re-encode is slower than realtime on CPU. Floor at the shared timeout -# and cap so one long source cannot hold the worker all day. -STITCH_TIMEOUT_PER_SOURCE_SECOND = 8.0 -STITCH_TIMEOUT_CAP_SECONDS = 1800.0 - - -class FfmpegCancelledError(Exception): - """``should_cancel`` turned true and ffmpeg was killed.""" - - -_STDERR_LOG_CHARS = 800 -# How often a cancellable run checks its cancel flag. -_CANCEL_POLL_SECONDS = 0.2 - - -def timeout_for_source_duration(duration_seconds: float) -> float: - """How long a stitch of a source this long may run ffmpeg.""" - scaled = max(0.0, duration_seconds) * STITCH_TIMEOUT_PER_SOURCE_SECOND - return min(STITCH_TIMEOUT_CAP_SECONDS, max(FFMPEG_TIMEOUT_SECONDS, scaled)) - - -# Slowest encode of a frame that we plan for (VP9 with alpha or a lossless guide on a -# CPU with 8 cores ran about 70 Mpx/s at 8K). The timeout is a ceiling, not a target. -_PIXELS_PER_SECOND = 10_000_000 -PIXEL_TIMEOUT_CAP_SECONDS = 3600.0 - - -def timeout_for_pixels(width: int, height: int, frames: int) -> float: - """How long an encode of this many pixels may run. Never below the shared timeout. - - A 1080p clip of 10 s stays at the shared timeout. An 8K clip needs minutes. - """ - scaled = max(0, width) * max(0, height) * max(0, frames) / _PIXELS_PER_SECOND - return min(PIXEL_TIMEOUT_CAP_SECONDS, max(FFMPEG_TIMEOUT_SECONDS, scaled)) - - -def ffmpeg_seconds(value: float) -> str: - """``str(1e-05)`` is scientific notation, which ``-ss``/``-t`` reject.""" - return f"{value:.6f}" - - -def _ffmpeg() -> str: - return str(imageio_ffmpeg.get_ffmpeg_exe()) - - -def _run_until_cancelled( - command: list[str], timeout: float, should_cancel: Callable[[], bool] -) -> subprocess.CompletedProcess[bytes]: - """Like ``subprocess.run``, but kills ffmpeg when ``should_cancel`` turns true.""" - deadline = time.monotonic() + timeout - with subprocess.Popen( - command, stdout=subprocess.PIPE, stderr=subprocess.PIPE - ) as process: - while True: - try: - stdout, stderr = process.communicate(timeout=_CANCEL_POLL_SECONDS) - except subprocess.TimeoutExpired: - if should_cancel(): - process.kill() - process.communicate() - raise FfmpegCancelledError() from None - if time.monotonic() >= deadline: - process.kill() - process.communicate() - raise subprocess.TimeoutExpired(command, timeout) from None - continue - return subprocess.CompletedProcess( - process.args, process.returncode, stdout, stderr - ) - def run_ffmpeg( args: list[str], @@ -96,36 +34,15 @@ def run_ffmpeg( check: bool = True, should_cancel: Callable[[], bool] | None = None, ) -> subprocess.CompletedProcess[bytes]: - if ffmpeg_exe is None: - command = [_ffmpeg()] - elif isinstance(ffmpeg_exe, str): - command = [ffmpeg_exe] - else: - command = ffmpeg_exe - full_command = [*command, "-nostdin", *args] try: - if should_cancel is None: - completed = subprocess.run( - full_command, - check=False, - capture_output=True, - timeout=timeout, - ) - else: - completed = _run_until_cancelled(full_command, timeout, should_cancel) - except subprocess.CalledProcessError as exc: - stderr = exc.stderr.decode("utf-8", "replace") if exc.stderr else "" - # Logged only: stderr carries local paths that must not reach responses. - logger.warning( - "ffmpeg exited %s: %s", exc.returncode, stderr[-_STDERR_LOG_CHARS:] + return _run_ffmpeg( + args, + ffmpeg_exe=ffmpeg_exe, + timeout=timeout, + check=check, + should_cancel=should_cancel, ) - raise - except FileNotFoundError as exc: + except FfmpegUnavailableError as exc: raise MediaError("UNREADABLE_MEDIA", "ffmpeg is not available") from exc - except subprocess.TimeoutExpired as exc: + except FfmpegTimeoutError as exc: raise MediaError("UNREADABLE_MEDIA", "ffmpeg timed out") from exc - if check and completed.returncode != 0: - raise subprocess.CalledProcessError( - completed.returncode, completed.args, completed.stdout, completed.stderr - ) - return completed diff --git a/backend/services/generation_queue/lane_sessions.py b/backend/services/generation_queue/lane_sessions.py index 6dda103f1..ef1ddb287 100644 --- a/backend/services/generation_queue/lane_sessions.py +++ b/backend/services/generation_queue/lane_sessions.py @@ -11,7 +11,7 @@ from collections.abc import Callable from api_types import ApiActivityStatus -from services.generation_interrupt import GenerationCancelledError +from inference.interrupt import GenerationCancelledError from services.generation_queue.sessions import JobProgress logger = logging.getLogger(__name__) diff --git a/backend/services/generation_queue/runner.py b/backend/services/generation_queue/runner.py index a307d4efa..dfb105ee6 100644 --- a/backend/services/generation_queue/runner.py +++ b/backend/services/generation_queue/runner.py @@ -9,9 +9,9 @@ from typing import Literal, TypeVar from services.store import Store +from inference.errors import CapabilityFailedError from services.records import ( AttemptError, - CapabilityFailedError, GenerationErrorCode, GenerationRecord, MarkSucceededError, @@ -40,10 +40,10 @@ 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 inference.interrupt import is_cancel_exception from services.gpu_info.gpu_info import GpuInfo -from services.patches import diffusion_stage_cache -from services.patches.pinned_pool_fix import is_cuda_oom_error +from inference.patches import diffusion_stage_cache +from inference.patches.pinned_pool_fix import is_cuda_oom_error from services.storage_info.storage_info import DriveType logger = logging.getLogger(__name__) diff --git a/backend/services/generation_queue/sessions.py b/backend/services/generation_queue/sessions.py index b5a1b489a..b7eeebb11 100644 --- a/backend/services/generation_queue/sessions.py +++ b/backend/services/generation_queue/sessions.py @@ -13,7 +13,7 @@ from typing import Protocol from api_types import ApiActivityStatus, GenerationProgressResponse -from services import generation_interrupt +import inference.interrupt as interrupt from services.generation_queue.control import SharedGenerationSlot @@ -171,7 +171,7 @@ def raise_if_cancelled(self) -> None: 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) + return interrupt.wait_requested(timeout) def cancel(self) -> None: self._generation.cancel_generation() diff --git a/backend/services/gpu_info/gpu_info_impl.py b/backend/services/gpu_info/gpu_info_impl.py index e6f677f5c..fba495a30 100644 --- a/backend/services/gpu_info/gpu_info_impl.py +++ b/backend/services/gpu_info/gpu_info_impl.py @@ -13,7 +13,7 @@ import torch from runtime_config.device_calibration import RunMemoryBaseline, RunMemoryEnd -from services.gpu_info import run_peak +import inference.run_peak as run_peak from services.gpu_info.gpu_info import GpuTelemetryPayload logger = logging.getLogger(__name__) diff --git a/backend/services/ic_lora_pipeline/__init__.py b/backend/services/ic_lora_pipeline/__init__.py deleted file mode 100644 index 72960b01b..000000000 --- a/backend/services/ic_lora_pipeline/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -from services.ic_lora_pipeline.ic_lora_pipeline import IcLoraPipeline - -__all__ = ["IcLoraPipeline"] diff --git a/backend/services/image_generation_pipeline/zit_image_generation_pipeline.py b/backend/services/image_generation_pipeline/zit_image_generation_pipeline.py index 777a5d0e4..38ee1ad71 100644 --- a/backend/services/image_generation_pipeline/zit_image_generation_pipeline.py +++ b/backend/services/image_generation_pipeline/zit_image_generation_pipeline.py @@ -11,7 +11,7 @@ from diffusers.pipelines.auto_pipeline import ZImagePipeline # type: ignore[reportUnknownVariableType] from PIL.Image import Image as PILImage -from services.generation_interrupt import diffusers_step_callback +from inference.interrupt import diffusers_step_callback from services.services_utils import ( ImagePipelineOutputLike, PILImageType, diff --git a/backend/services/interfaces.py b/backend/services/interfaces.py index 55a9dcdb3..87cd65b02 100644 --- a/backend/services/interfaces.py +++ b/backend/services/interfaces.py @@ -1,20 +1,16 @@ -"""Compatibility re-exports for service interfaces.""" +"""Desktop service protocols. GPU pipeline protocols live in ``inference``.""" from __future__ import annotations from typing import Literal -from services.a2v_pipeline.a2v_pipeline import A2VPipeline from services.depth_processor_pipeline.depth_processor_pipeline import DepthProcessorPipeline -from services.fast_video_pipeline.fast_video_pipeline import FastVideoPipeline from services.zit_api_client.zit_api_client import ZitAPIClient from services.gpu_cleaner.gpu_cleaner import GpuCleaner from services.gpu_info.gpu_info import GpuInfo, GpuTelemetryPayload from services.http_client.http_client import HTTPClient, HttpResponseLike, HttpTransportError -from services.ic_lora_pipeline.ic_lora_pipeline import IcLoraPipeline from services.image_generation_pipeline.image_generation_pipeline import ImageGenerationPipeline from services.ltx_api_client.ltx_api_client import LTXAPIClient -from services.retake_pipeline.retake_pipeline import RetakePipeline from services.model_downloader.model_downloader import ModelDownloader from services.pose_processor_pipeline.pose_processor_pipeline import PoseProcessorPipeline from services.prompt_enhancer_pipeline.prompt_enhancer_pipeline import PromptEnhancerPipeline @@ -26,7 +22,6 @@ VideoPipelineModelType = Literal["fast"] __all__ = [ - "A2VPipeline", "JSONScalar", "JSONValue", "GpuTelemetryPayload", @@ -42,12 +37,9 @@ "PoseProcessorPipeline", "TaskRunner", "VideoPipelineModelType", - "FastVideoPipeline", "ZitAPIClient", "ImageGenerationPipeline", - "IcLoraPipeline", "LTXAPIClient", - "RetakePipeline", "TextEncoder", "PromptEnhancerPipeline", ] diff --git a/backend/services/media_probe.py b/backend/services/media_probe.py index f206f1276..189820953 100644 --- a/backend/services/media_probe.py +++ b/backend/services/media_probe.py @@ -390,11 +390,6 @@ def first_audio_codec(path: Path) -> str | None: return None -def media_has_audio(path: str) -> bool: - with av.open(path) as container: - return any(stream.type == "audio" for stream in container.streams) - - def _frame_timestamp(frame: object, time_base: object) -> float | None: timestamp = cast(float | None, getattr(frame, "time", None)) if timestamp is None: diff --git a/backend/services/patches/ltx_text_encoder_checkpoint_id.py b/backend/services/patches/ltx_text_encoder_checkpoint_id.py new file mode 100644 index 000000000..bd3660844 --- /dev/null +++ b/backend/services/patches/ltx_text_encoder_checkpoint_id.py @@ -0,0 +1,35 @@ +"""Desktop-only: LTXTextEncoder.get_model_id_from_checkpoint via header read. + +Split from safetensors_metadata_fix so inference.apply_patches() does not import +services.text_encoder. + +TODO: drop this desktop hook in a follow-up. It is the only patch that reaches +services.text_encoder. + +Remove once safetensors supports read-only mmap (same as safetensors_metadata_fix). + +Usage: + import services.patches.ltx_text_encoder_checkpoint_id # noqa: F401 +""" + +from __future__ import annotations + +from inference.patches.safetensors_metadata_fix import read_safetensors_metadata +from services.text_encoder.ltx_text_encoder import LTXTextEncoder + + +def _patched_get_model_id_from_checkpoint(self: LTXTextEncoder, checkpoint_path: str) -> str | None: + try: + meta = read_safetensors_metadata(checkpoint_path) or {} + if "encrypted_wandb_properties" in meta: + return meta["encrypted_wandb_properties"] + except Exception as exc: + import logging + logging.getLogger(__name__).warning("Could not extract model_id from checkpoint: %s", exc, exc_info=True) + return None + + +assert hasattr(LTXTextEncoder, "get_model_id_from_checkpoint"), ( + "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] diff --git a/backend/services/patches/mps_tiling_weights_sync.py b/backend/services/patches/mps_tiling_weights_sync.py new file mode 100644 index 000000000..0e456b280 --- /dev/null +++ b/backend/services/patches/mps_tiling_weights_sync.py @@ -0,0 +1,66 @@ +"""Monkey-patch: upload tile blend weights to MPS with a blocking copy. + +Credit: diagnosis, measurements and the original patch are by Cemalettin Serit (@cemserit), +Lightricks/LTX-Desktop#199 (issue) and Lightricks/LTX-Desktop#200 (pull request). + +ltx-core 1.6.0 added ``_device_weights`` (``ltx_core/modality_tiling.py``). It builds a tile's blend +weights on the host and uploads them once per plan with ``non_blocking=True`` on every backend. +``ltx_core.devices.allow_async_transfer`` says only CUDA orders a non-blocking transfer against the +kernel that consumes it, and ``upload_from_host`` follows that rule. ``_device_weights`` does not. +On MPS ``VideoModalityTilingHelper.blend`` can then multiply the tile prediction by weights that +have not landed yet. + +Every job that tiles the transformer is affected. On an M5 Pro (48 GB, macOS 26.5.1) Refine Details +finished as ``succeeded`` and wrote a video whose frames are all zero in Y, U and V (solid green), +at 540p, 720p and 1080p and with every tiling setting (LTX-Desktop#199). + +Measured on that machine by running ``LTXIcLoraPipeline`` with hooks on ``LTXModel.forward`` and +``EulerDiffusionStep.step`` (refine-details, 9 frames, 576 x 1024, one tile, same seed): + +- As shipped: transformer output of step 1 is in -6.9 .. 6.8, the blended ``denoised`` passed to the + Euler step is in -3.0e28 .. 3.8e28, step 2 is non-finite, the output is solid green. +- Blocking copy: ``denoised`` is in -5.9 .. 4.4, every step is finite, the picture is correct. + +This patch keeps upstream's upload wherever ``allow_async_transfer`` allows it (CUDA) and copies +with a blocking ``.to`` everywhere else, so it is a no-op off Mac. + +Remove once ltx-core's ``_device_weights`` passes ``non_blocking=allow_async_transfer(like.device)`` +and Refine Details gives a real picture on a Mac without this patch. + +Usage: + import services.patches.mps_tiling_weights_sync # noqa: F401 +""" + +from __future__ import annotations + +import inspect +from collections.abc import Callable + +import torch +from ltx_core import modality_tiling as _tiling +from ltx_core.devices import allow_async_transfer + +_WeightsCache = dict[tuple[torch.dtype, torch.device], torch.Tensor] + +_orig_device_weights: Callable[[_WeightsCache, Callable[[], torch.Tensor], torch.Tensor], torch.Tensor] = ( + _tiling._device_weights # pyright: ignore[reportPrivateUsage] +) + + +def _device_weights_ordered( + cache: _WeightsCache, + weights: Callable[[], torch.Tensor], + like: torch.Tensor, +) -> torch.Tensor: + """Like upstream ``_device_weights``, but the upload blocks where the backend does not order it.""" + if allow_async_transfer(like.device): + return _orig_device_weights(cache, weights, like) + key = (like.dtype, like.device) + if key not in cache: + cache[key] = weights().to(dtype=like.dtype).to(device=like.device) + return cache[key] + + +if list(inspect.signature(_orig_device_weights).parameters) != ["cache", "weights", "like"]: + raise RuntimeError("modality_tiling._device_weights changed its signature — patch needs updating.") +_tiling._device_weights = _device_weights_ordered # pyright: ignore[reportPrivateUsage] diff --git a/backend/services/patches/mps_transfer_sync.py b/backend/services/patches/mps_transfer_sync.py index 94d365f5e..03d77ee11 100644 --- a/backend/services/patches/mps_transfer_sync.py +++ b/backend/services/patches/mps_transfer_sync.py @@ -22,10 +22,23 @@ 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. +The wait must not hold the GIL. ``torch.mps.synchronize()`` and ``torch.mps.Event.synchronize()`` +both block in ``MPSStream::synchronize`` / ``waitUntilCompleted`` with the GIL held (torch 2.11.0). +Every other Python thread then stops for as long as the GPU needs to drain its queue: the asyncio +event loop (``/health`` answered after 9 to 16 s on an M4 Pro during Extend, so Electron logged +``Backend liveness probe failed``), the heartbeat thread, and ltx-core's read-ahead worker. The wait +here records an event on the same stream and polls ``Event.query()`` with a short sleep, then calls +``torch.mps.synchronize()`` as before (it returns at once). That keeps the same ordering (the event +signals after all earlier queued work), keeps the original call in the same place, and releases the +GIL for the long wait. A micro-benchmark with a second Python thread measured a 6 ms maximum gap with +polling, against a gap of the full wait (4.6 to 7.2 s) for both blocking calls, with no visible +increase in total time. + 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. +48 GB Mac without this patch. Replace the polling wait with ``torch.mps.synchronize()`` only once +PyTorch releases the GIL in it (CUDA's ``synchronize`` already does). Usage: import services.patches.mps_transfer_sync # noqa: F401 @@ -33,6 +46,7 @@ from __future__ import annotations +import time from collections.abc import Iterator from contextlib import contextmanager from typing import Any @@ -42,11 +56,35 @@ _orig_transfer = _transport.MpsTransport.transfer +# A sleep of 1 ms takes about 1.2 ms on macOS. A wait that is already done never sleeps. +_POLL_INTERVAL_S = 0.001 +# A block takes about 7 s at the slowest measured case (1080p stage 2, M4 Pro). A poll that +# outlasts this limit falls back to the blocking call, so a GPU error cannot spin forever. +_POLL_TIMEOUT_S = 60.0 + + +def _wait_for_queued_compute() -> None: + """Block until all MPS work queued so far has finished, without holding the GIL. + + The event poll does the long wait with the GIL released. ``torch.mps.synchronize()`` then runs + exactly as before, so its commit and flush semantics stay. It returns at once, because the + queue is already empty (measured 0.1 ms), so the GIL is held only for that moment. + + If the event is still not signalled after ``_POLL_TIMEOUT_S``, the poll stops and the same + ``torch.mps.synchronize()`` call blocks (with the GIL), as it did before the poll existed. + """ + event = torch.mps.Event() + event.record() + deadline = time.monotonic() + _POLL_TIMEOUT_S + while not event.query() and time.monotonic() < deadline: + time.sleep(_POLL_INTERVAL_S) + torch.mps.synchronize() + @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() + _wait_for_queued_compute() with _orig_transfer(self, after) as handle: yield handle diff --git a/backend/services/phase_log.py b/backend/services/phase_log.py index 6d7f88d76..5da5363f7 100644 --- a/backend/services/phase_log.py +++ b/backend/services/phase_log.py @@ -10,31 +10,13 @@ import time from collections.abc import Iterator from contextlib import contextmanager -from typing import TYPE_CHECKING - -import psutil +from inference.phase_log import rss_gb as rss_gb from server_utils.heartbeat import log_heartbeat -from services.gpu_info.run_peak import fold_and_reset_cuda_peak - -if TYPE_CHECKING: - import torch PREFIX = "[alpha-gen]" -def rss_gb() -> float: - """Memory of the backend and its child processes (ffmpeg holds 10 GB or more at 8K).""" - process = psutil.Process() - total = process.memory_info().rss - for child in process.children(recursive=True): - try: - total += child.memory_info().rss - except psutil.Error: - continue - return total / 1e9 - - @contextmanager def logged_phase( logger: logging.Logger, label: str, *, heartbeat: bool = False, prefix: str = PREFIX @@ -58,36 +40,3 @@ def logged_phase( ) raise logger.info("%s %s: done in %.1fs (memory %.1f GB)", prefix, label, time.monotonic() - started, rss_gb()) - - -@contextmanager -def measured_gpu_phase( - logger: logging.Logger, - label: str, - *, - device: "torch.device", - prefix: str, - estimate_gib: float | None = None, -) -> Iterator[None]: - """``logged_phase`` with a heartbeat, plus the peak VRAM of the step next to the budget estimate. - - The estimate is the job-budget curve. Real peaks from a 4K run refit it. - """ - import torch - - cuda = device.type == "cuda" and torch.cuda.is_available() - if cuda: - fold_and_reset_cuda_peak(device) - try: - with logged_phase(logger, label, heartbeat=True, prefix=prefix): - yield - finally: - if cuda: - logger.info( - "%s %s: peak VRAM allocated %.1f GiB, reserved %.1f GiB (budget estimate %s)", - prefix, - label, - torch.cuda.max_memory_allocated(device) / 1024**3, - torch.cuda.max_memory_reserved(device) / 1024**3, - "none" if estimate_gib is None else f"{estimate_gib:.1f} GiB", - ) diff --git a/backend/services/records.py b/backend/services/records.py index aecd7fe26..fdb0c5124 100644 --- a/backend/services/records.py +++ b/backend/services/records.py @@ -50,15 +50,6 @@ def __init__(self, generation_id: str, error_code: GenerationErrorCode) -> None: super().__init__(error_code) -class CapabilityFailedError(Exception): - """Executor could not run this generation with the current local capability.""" - - def __init__(self, detail: str, *, code: str | None = None) -> None: - self.detail = detail - self.code = code - super().__init__(detail) - - class UnavailableError(Exception): """Raised when the sqlite store cannot be opened or recovered.""" diff --git a/backend/services/retake_pipeline/stitch_audio.py b/backend/services/retake_pipeline/stitch_audio.py deleted file mode 100644 index 39d24c2c1..000000000 --- a/backend/services/retake_pipeline/stitch_audio.py +++ /dev/null @@ -1,34 +0,0 @@ -"""Hard-cut audio for retake and extend stitches. Video fades; audio does not.""" - -from __future__ import annotations - -from collections.abc import Sequence -from dataclasses import dataclass - -from services.ffmpeg import ffmpeg_seconds - - -@dataclass(frozen=True) -class AudioPiece: - """``label`` between ``start`` and ``end`` seconds. ``None`` runs to that edge.""" - - label: str - start: float | None = None - end: float | None = None - - -def audio_cut_graph(pieces: Sequence[AudioPiece]) -> str: - """Concatenate ``pieces`` in order into ``[a]``.""" - parts: list[str] = [] - outputs: list[str] = [] - for index, piece in enumerate(pieces): - bounds: list[str] = [] - if piece.start is not None: - bounds.append(f"start={ffmpeg_seconds(piece.start)}") - if piece.end is not None: - bounds.append(f"end={ffmpeg_seconds(piece.end)}") - output = f"[p{index}]" - parts.append(f"{piece.label}atrim={':'.join(bounds)},asetpts=PTS-STARTPTS{output}") - outputs.append(output) - parts.append(f"{''.join(outputs)}concat=n={len(outputs)}:v=0:a=1[a]") - return ";".join(parts) diff --git a/backend/services/services_utils.py b/backend/services/services_utils.py index 38594684c..d53547474 100644 --- a/backend/services/services_utils.py +++ b/backend/services/services_utils.py @@ -9,13 +9,13 @@ import torch from PIL.Image import Image as PILImage +from inference.device import device_supports_fp8 as device_supports_fp8 +from inference.device import get_device_type + if TYPE_CHECKING: import numpy as np from numpy.typing import NDArray - from ltx_core.model.video_vae import TilingConfig - from ltx_core.tiling import PipelineTiling - JSONScalar: TypeAlias = str | int | float | bool | None JSONValue: TypeAlias = JSONScalar | list["JSONValue"] | dict[str, "JSONValue"] @@ -27,41 +27,15 @@ PILImageType: TypeAlias = PILImage if TYPE_CHECKING: - from ltx_core.types import Audio as AudioType - FrameArray: TypeAlias = NDArray[np.uint8] - TilingConfigType: TypeAlias = TilingConfig - PipelineTilingType: TypeAlias = PipelineTiling else: FrameArray: TypeAlias = object - TilingConfigType: TypeAlias = object - PipelineTilingType: TypeAlias = object - AudioType: TypeAlias = object TensorOrNone: TypeAlias = TensorType | None -AudioOrNone: TypeAlias = AudioType | None logger = logging.getLogger(__name__) -def get_device_type(device: str | torch.device | object | None) -> str: - if device is None: - return "cpu" - - device_type = getattr(device, "type", None) - if isinstance(device_type, str): - return device_type - - if isinstance(device, str): - try: - return str(torch.device(device).type) - except Exception: - logger.warning("Could not parse device string '%s', using it as-is", device, exc_info=True) - return device - - return "cpu" - - def compute_edit_dimensions(width: int, height: int) -> tuple[int, int]: """Floor each dimension to a multiple of 16 (Z-Image VAE constraint), min 16. @@ -89,35 +63,6 @@ def effective_edit_steps(num_inference_steps: int, strength: float) -> int: return num_inference_steps - t_start -def _device_index(device: str | torch.device | object | None) -> int: - """CUDA device ordinal for capability probes. Unindexed shapes mean 0.""" - # NB: torch stubs type .index as int, but at runtime an unindexed device - # (torch.device("cuda")) carries None — hence `or 0`, not `is None`. - if isinstance(device, torch.device): - return device.index or 0 - if isinstance(device, str): - try: - return torch.device(device).index or 0 - except Exception: - return 0 - index = getattr(device, "index", None) - return index if isinstance(index, int) else 0 - - -def device_supports_fp8(device: str | torch.device | object | None) -> bool: - # ROCm PyTorch also reports device.type == "cuda" (see runtime_config.accelerator), - # so this must not be a plain device-type check: ROCm has no fp8_cast kernel support - # here yet, and would otherwise be silently misidentified as CUDA/NVIDIA. - # Pre-Ada NVIDIA (compute capability < 8.9) has no hardware fp8 either. - # Originally contributed by boxwrench in https://github.com/Lightricks/LTX-Desktop/pull/160 - if get_device_type(device) != "cuda": - return False - - from runtime_config.accelerator import accelerator_supports_fp8 - - return accelerator_supports_fp8(_device_index(device)) - - def sync_device(device: str | torch.device | object | None) -> None: device_type = get_device_type(device) if device_type == "cuda": 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 fe498a810..570f7e7b6 100644 --- a/backend/services/zit_api_client/zit_api_client_impl.py +++ b/backend/services/zit_api_client/zit_api_client_impl.py @@ -11,7 +11,7 @@ from urllib.parse import urlsplit from api_types import ApiActivityStatus -from services.generation_interrupt import GenerationCancelledError +from inference.interrupt import GenerationCancelledError from services.http_client.http_client import ( HTTPClient, HttpBodyTooLargeError, diff --git a/backend/state/app_settings.py b/backend/state/app_settings.py index 45b6022f4..b9872d7b4 100644 --- a/backend/state/app_settings.py +++ b/backend/state/app_settings.py @@ -9,7 +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 +from inference.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"] diff --git a/backend/state/app_state_types.py b/backend/state/app_state_types.py index cf4706cee..1ae9fcb7a 100644 --- a/backend/state/app_state_types.py +++ b/backend/state/app_state_types.py @@ -13,20 +13,20 @@ RunMemoryBaseline, ) from runtime_config.eta import WallTimeEstimate -from runtime_config.ic_lora_tiling import IcLoraTiling +from inference.ic_lora_tiling import IcLoraTiling from runtime_config.runtime_policy import LocalGenerationMode from state.conditioning_cache import ConditioningCache if TYPE_CHECKING: from state.app_settings import AppSettings + from inference.a2v_pipeline.a2v_pipeline import A2VPipeline + from inference.fast_video_pipeline.fast_video_pipeline import FastVideoPipeline + from inference.ic_lora_pipeline.ic_lora_pipeline import IcLoraPipeline + from inference.retake_pipeline.retake_pipeline import RetakePipeline from services.interfaces import ( - A2VPipeline, DepthProcessorPipeline, - FastVideoPipeline, ImageGenerationPipeline, - IcLoraPipeline, PoseProcessorPipeline, - RetakePipeline, TextEncoder, ) import torch diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index cead6aeaf..6297b7c85 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -109,7 +109,7 @@ def generate_queued( @pytest.fixture(autouse=True) def _reset_generation_interrupt() -> None: - from services.generation_interrupt import clear + from inference.interrupt import clear clear() yield @@ -118,7 +118,7 @@ def _reset_generation_interrupt() -> None: @pytest.fixture(autouse=True) def _reset_denoising_progress() -> None: - from services.denoising_progress import reset + from inference.progress import reset reset() yield diff --git a/backend/tests/fakes/fake_gpu_info.py b/backend/tests/fakes/fake_gpu_info.py index 502fadc42..c683069d0 100644 --- a/backend/tests/fakes/fake_gpu_info.py +++ b/backend/tests/fakes/fake_gpu_info.py @@ -5,7 +5,7 @@ from collections.abc import Callable from runtime_config.device_calibration import RunMemoryBaseline, RunMemoryEnd -from services.gpu_info import run_peak +import inference.run_peak as run_peak from services.interfaces import GpuTelemetryPayload diff --git a/backend/tests/fakes/generation.py b/backend/tests/fakes/generation.py index 100d405d5..7897fd78c 100644 --- a/backend/tests/fakes/generation.py +++ b/backend/tests/fakes/generation.py @@ -28,7 +28,7 @@ TextToVideoParams, ) from services.features.ic_lora_recipes import get_ic_lora_recipe -from services.generation_interrupt import GenerationCancelledError, is_requested +from inference.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 diff --git a/backend/tests/fakes/services.py b/backend/tests/fakes/services.py index 46d164f40..548eec4e0 100644 --- a/backend/tests/fakes/services.py +++ b/backend/tests/fakes/services.py @@ -5,13 +5,13 @@ from collections.abc import Callable, Sequence from dataclasses import dataclass, field from pathlib import Path -from typing import Any, ClassVar +from typing import TYPE_CHECKING, Any, ClassVar import shutil import threading import time from PIL import Image -from frame_math import AutoDurationSpec +from inference.frame_math import AutoDurationSpec from ltx_pipelines.utils.types import OffloadMode from api_types import ( ApiActivityStatus, @@ -31,9 +31,9 @@ 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 inference.ic_lora_tiling import IcLoraTiling +from inference.fast_video_pipeline.nag_config import NagConfig +from inference.interrupt import GenerationCancelledError from services.http_client import HttpBodyTooLargeError from services.interfaces import VideoInfoPayload from services.ltx_api_client.ltx_api_client import LTXRetakeResult @@ -43,6 +43,9 @@ from tests.fakes.assistant import FakeAssistantModels, FakeAssistantProvider from tests.fakes.fake_gpu_info import FakeGpuInfo +if TYPE_CHECKING: + from inference.fast_video_pipeline.windowed_run import WindowEstimate + def _dl(repo_id: str, filename: str, size_bytes: int = 10) -> DownloadSpec: """Single-checkpoint DownloadSpec (first/only variant = default).""" @@ -995,6 +998,7 @@ def create( video_vae_path: str | None = None, audio_vae_path: str | None = None, duration_head_path: str | None = None, + window_estimate_gib: WindowEstimate | None = None, ) -> "FakeFastVideoPipeline": del ( checkpoint_path, @@ -1004,6 +1008,7 @@ def create( video_vae_path, audio_vae_path, duration_head_path, + window_estimate_gib, ) pipeline = FakeFastVideoPipeline._singleton if pipeline is None: @@ -1045,7 +1050,7 @@ def generate( "nag": nag, } if self.inference_steps: - from services.generation_interrupt import raise_if_requested + from inference.interrupt import raise_if_requested self.entered_inference.set() for _ in range(self.inference_steps): @@ -1098,7 +1103,7 @@ def generate(self, **kwargs: Any) -> FakeZitOutput: self.generate_calls.append(kwargs) callback = kwargs.get("callback_on_step_end") if self.inference_steps: - from services.generation_interrupt import raise_if_requested + from inference.interrupt import raise_if_requested self.entered_inference.set() for step_idx in range(self.inference_steps): @@ -1367,6 +1372,7 @@ def create( video_vae_path: str | None = None, audio_vae_path: str | None = None, duration_head_path: str | None = None, + window_estimate_gib: WindowEstimate | None = None, ) -> "FakeA2VPipeline": del ( checkpoint_path, @@ -1376,6 +1382,7 @@ def create( video_vae_path, audio_vae_path, duration_head_path, + window_estimate_gib, ) pipeline = FakeA2VPipeline._singleton if pipeline is None: diff --git a/backend/tests/test_accelerator.py b/backend/tests/test_accelerator.py index 0da577fc0..f10f9b0d4 100644 --- a/backend/tests/test_accelerator.py +++ b/backend/tests/test_accelerator.py @@ -9,7 +9,7 @@ accelerator_supports_fp8, ) from services.gpu_info.gpu_info_impl import GpuInfoImpl -from services.services_utils import device_supports_fp8 +from inference.device import device_supports_fp8 def test_accelerator_backend_rocm_when_hip_is_set(monkeypatch) -> None: @@ -62,16 +62,24 @@ def test_device_supports_fp8_false_on_cpu() -> None: def test_device_supports_fp8_true_on_cuda_not_rocm(monkeypatch) -> None: + import inference.device as device_mod + + monkeypatch.setattr(device_mod.torch.version, "hip", None, raising=False) + monkeypatch.setattr(device_mod.torch.cuda, "is_available", lambda: True) monkeypatch.setattr( - "runtime_config.accelerator.accelerator_supports_fp8", lambda device_index=0: True + device_mod.torch.cuda, "get_device_capability", lambda device=0: (8, 9) ) assert device_supports_fp8("cuda") is True assert device_supports_fp8(SimpleNamespace(type="cuda")) is True def test_device_supports_fp8_false_when_accelerator_lacks_fp8(monkeypatch) -> None: + import inference.device as device_mod + + monkeypatch.setattr(device_mod.torch.version, "hip", None, raising=False) + monkeypatch.setattr(device_mod.torch.cuda, "is_available", lambda: True) monkeypatch.setattr( - "runtime_config.accelerator.accelerator_supports_fp8", lambda device_index=0: False + device_mod.torch.cuda, "get_device_capability", lambda device=0: (8, 6) ) assert device_supports_fp8("cuda") is False assert device_supports_fp8(SimpleNamespace(type="cuda")) is False @@ -156,14 +164,17 @@ def _capture(device: object = None) -> tuple[int, int]: def test_device_supports_fp8_probes_the_passed_device_index(monkeypatch) -> None: import torch + import inference.device as device_mod seen: list[object] = [] - def _capture(device_index: object = 0) -> bool: - seen.append(device_index) - return True + def _capture(device: object = 0) -> tuple[int, int]: + seen.append(device) + return (8, 9) - monkeypatch.setattr("runtime_config.accelerator.accelerator_supports_fp8", _capture) + monkeypatch.setattr(device_mod.torch.version, "hip", None, raising=False) + monkeypatch.setattr(device_mod.torch.cuda, "is_available", lambda: True) + monkeypatch.setattr(device_mod.torch.cuda, "get_device_capability", _capture) assert device_supports_fp8("cuda:1") is True assert device_supports_fp8(torch.device("cuda:2")) is True assert device_supports_fp8("cuda") is True diff --git a/backend/tests/test_alpha_cutout.py b/backend/tests/test_alpha_cutout.py index 372ba6fea..896b64940 100644 --- a/backend/tests/test_alpha_cutout.py +++ b/backend/tests/test_alpha_cutout.py @@ -366,7 +366,8 @@ def test_only_alpha_gen_is_a_cutout_recipe() -> None: def test_a_cancel_during_the_bake_stops_ffmpeg(tmp_path: Path) -> None: """The flag is polled while ffmpeg runs, so a cancel does not wait for the encode.""" - from services.ffmpeg import FfmpegCancelledError, run_ffmpeg + from inference.ffmpeg import FfmpegCancelledError + from services.ffmpeg import run_ffmpeg started = time.monotonic() with pytest.raises(FfmpegCancelledError): @@ -381,8 +382,8 @@ def test_a_cancelled_bake_is_a_generation_cancel( tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: """The ffmpeg helper has its own cancel error. The bake maps it to the queue's.""" - from services.ffmpeg import FfmpegCancelledError - from services.generation_interrupt import GenerationCancelledError + from inference.ffmpeg import FfmpegCancelledError + from inference.interrupt import GenerationCancelledError def cancelled(*_args: object, **_kwargs: object) -> None: raise FfmpegCancelledError() @@ -404,8 +405,8 @@ def test_a_failed_bake_is_reported_as_a_bake_failure(tmp_path: Path) -> None: def test_a_cancelled_gif_bake_is_a_generation_cancel( tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: - from services.ffmpeg import FfmpegCancelledError - from services.generation_interrupt import GenerationCancelledError + from inference.ffmpeg import FfmpegCancelledError + from inference.interrupt import GenerationCancelledError def cancelled(*_args: object, **_kwargs: object) -> None: raise FfmpegCancelledError() @@ -449,8 +450,8 @@ def write_garbage(*_args: object, **_kwargs: object) -> None: def test_a_cancel_during_the_gif_still_cancels_the_run( tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: - from services.ffmpeg import FfmpegCancelledError - from services.generation_interrupt import GenerationCancelledError + from inference.ffmpeg import FfmpegCancelledError + from inference.interrupt import GenerationCancelledError def cancelled(*_args: object, **_kwargs: object) -> None: raise FfmpegCancelledError() diff --git a/backend/tests/test_assistant.py b/backend/tests/test_assistant.py index 8fbc01790..05f27ecdb 100644 --- a/backend/tests/test_assistant.py +++ b/backend/tests/test_assistant.py @@ -476,6 +476,89 @@ def test_retake_past_the_source_end_is_refused_with_the_start_time_that_fits(cli assert "use startTime 2.0" in saved_history(test_state, body["request_id"]) +def test_extend_and_retake_default_to_long_context_and_queue_short_when_asked(client, test_state, tmp_path, setup_agent): + # Bug: the assistant had no way to ask for the short context, so a user who asked for it got long. + provider, _args = setup_agent + video = ingest(client, _mp4(tmp_path / "clip.mp4", duration_seconds=6)) + extend_params = {"model": "ltx-2.5-fast", "prompt": "The wave continues rolling", "added_seconds": 2} + retake_params = {"model": "ltx-2.5-fast", "startTime": 1, "duration": 2} + cases = [ + ("extend_video", extend_params, "long"), + ("extend_video", {**extend_params, "contextMode": "short"}, "short"), + ("retake_video", retake_params, "long"), + ("retake_video", {**retake_params, "contextMode": "short"}, "short"), + ] + for number, (tool, params, expected) in enumerate(cases, start=1): + provider.responses.extend([call(tool, {"video_asset_id": video["id"], "params": params, "job_number": number}), say("Queued.")]) + response = client.post("/api/assistant/turn", json=request_body(f"{tool} {expected}")) + assert response.status_code == 200, response.text + queued = last_generation(response, client) + assert queued is not None + assert queued["spec"]["params"]["contextMode"] == expected, (tool, params) + + +QUOTED_RETAKE = 'Retake seconds 1 to 3 so the speaker says "Because AI avoids risk."' + + +def test_a_retake_with_quoted_words_and_no_prompt_is_nudged_once_to_write_them_in(client, test_state, tmp_path, setup_agent): + # Bug: a small model left the prompt empty, so the retake never said the words the user quoted. + provider, _args = setup_agent + video = ingest(client, _mp4(tmp_path / "clip.mp4", duration_seconds=6)) + params = {"model": "ltx-2.5-fast", "startTime": 1, "duration": 2} + written = {**params, "prompt": 'The speaker says "Because AI avoids risk."'} + provider.responses.extend([ + call("retake_video", {"video_asset_id": video["id"], "params": params}), + call("retake_video", {"video_asset_id": video["id"], "params": written}), + say("Queued."), + ]) + body = request_body(QUOTED_RETAKE) + response = client.post("/api/assistant/turn", json=body) + assert response.status_code == 200, response.text + queued = last_generation(response, client) + assert queued is not None and queued["spec"]["params"]["prompt"] == written["prompt"] + history = saved_history(test_state, body["request_id"]) + assert "The user gave words to be said" in history and "The prompt is empty" in history + + +def test_the_empty_prompt_nudge_only_asks_once_and_lets_an_unchanged_call_through(client, tmp_path, setup_agent): + provider, _args = setup_agent + video = ingest(client, _mp4(tmp_path / "clip.mp4", duration_seconds=6)) + params = {"model": "ltx-2.5-fast", "startTime": 1, "duration": 2} + provider.responses.extend([ + call("retake_video", {"video_asset_id": video["id"], "params": params}), + call("retake_video", {"video_asset_id": video["id"], "params": params}), + say("Queued."), + ]) + response = client.post("/api/assistant/turn", json=request_body(QUOTED_RETAKE)) + assert response.status_code == 200, response.text + queued = last_generation(response, client) + assert queued is not None and queued["spec"]["params"]["prompt"] == "" + + +def test_an_empty_prompt_is_not_nudged_when_the_user_quoted_nothing(client, tmp_path, setup_agent): + # An empty prompt goes through as before unless the user gave words to say. + provider, _args = setup_agent + video = ingest(client, _mp4(tmp_path / "clip.mp4", duration_seconds=6)) + provider.responses.extend([ + call("retake_video", {"video_asset_id": video["id"], "params": {"model": "ltx-2.5-fast", "startTime": 1, "duration": 2}}), + say("Queued."), + ]) + response = client.post("/api/assistant/turn", json=request_body("Retake seconds 1 to 3")) + assert response.status_code == 200, response.text + queued = last_generation(response, client) + assert queued is not None and queued["spec"]["params"]["prompt"] == "" + + +def test_the_context_mode_is_offered_to_the_model_and_explained_in_the_instructions(client, setup_agent): + provider, _args = setup_agent + provider.responses.append(say("Hi.")) + assert client.post("/api/assistant/turn", json=request_body("Hello")).status_code == 200 + instructions = provider.instructions[-1] + assert "contextMode" in instructions + assert '"short"' in instructions + assert "asks for short" in instructions + + def test_a_retake_cannot_resize_the_source_video(client, tmp_path, setup_agent): provider, _args = setup_agent video = ingest(client, _mp4(tmp_path / "clip.mp4", duration_seconds=4)) diff --git a/backend/tests/test_audio_channels.py b/backend/tests/test_audio_channels.py index 9c08bdf52..14ed78db0 100644 --- a/backend/tests/test_audio_channels.py +++ b/backend/tests/test_audio_channels.py @@ -2,7 +2,7 @@ import torch -from services.audio_channels import stereo_waveform +from inference.audio_channels import stereo_waveform def test_stereo_waveform_upmixes_batched_mono() -> None: diff --git a/backend/tests/test_audio_latent.py b/backend/tests/test_audio_latent.py new file mode 100644 index 000000000..8ecdbc658 --- /dev/null +++ b/backend/tests/test_audio_latent.py @@ -0,0 +1,72 @@ +"""Mono sources must reach the audio encoder as two channels.""" + +from __future__ import annotations + +from pathlib import Path + +import torch +from ltx_core.types import VideoPixelShape +from ltx_pipelines.utils import helpers as library +from ltx_pipelines.utils.helpers import decode_audio_from_file + +from inference.retake_pipeline.audio_latent import as_stereo, audio_latent_from_file +from tests.video_fixtures import write_clip_with_tone_spans + + +class _FakeAudioEncoder(torch.nn.Module): + sample_rate = 16000 + mel_bins = 64 + mel_hop_length = 160 + n_fft = 1024 + + def __init__(self) -> None: + super().__init__() + self.anchor = torch.nn.Parameter(torch.zeros(1)) + + def forward(self, mel: torch.Tensor) -> torch.Tensor: + return mel.mean(dim=-1, keepdim=True) + + +def test_a_mono_source_reaches_the_encoder_as_two_equal_channels(tmp_path: Path) -> None: + # Bug: the audio encoder reads two channels, so a mono phone clip fails the whole extend + # with a conv shape error. + mono = write_clip_with_tone_spans(tmp_path / "mono.mp4", frames=48, spans=[(0.0, 2.0)], channels=1) + audio = decode_audio_from_file(str(mono), torch.device("cpu"), 0.0, 2.0) + assert audio is not None + assert audio.waveform.shape[1] == 1 + stereo = as_stereo(audio) + assert stereo.waveform.shape[1] == 2 + assert torch.equal(stereo.waveform[:, 0], stereo.waveform[:, 1]) + + +def test_a_stereo_source_is_not_changed(tmp_path: Path) -> None: + stereo_clip = write_clip_with_tone_spans(tmp_path / "stereo.mp4", frames=48, spans=[(0.0, 2.0)], channels=2) + audio = decode_audio_from_file(str(stereo_clip), torch.device("cpu"), 0.0, 2.0) + assert audio is not None + assert as_stereo(audio).waveform is audio.waveform + + +def test_a_surround_source_reaches_the_encoder_as_two_channels(tmp_path: Path) -> None: + # Bug: the audio encoder reads two channels, so a 5.1 clip fails the whole extend. + surround = write_clip_with_tone_spans(tmp_path / "surround.mp4", frames=48, spans=[(0.0, 2.0)], channels=6) + audio = decode_audio_from_file(str(surround), torch.device("cpu"), 0.0, 2.0) + assert audio is not None + assert audio.waveform.shape[1] == 6 + stereo = as_stereo(audio) + assert stereo.waveform.shape[1] == 2 + assert torch.equal(stereo.waveform, audio.waveform[:, :2]) + + +def test_the_local_latent_matches_the_library_one_for_a_stereo_source(tmp_path: Path) -> None: + # Our copy of ltx_pipelines.audio_latent_from_file only adds the mono fix. If a library + # bump changes the original, this fails so the copy gets updated with it. + clip = write_clip_with_tone_spans(tmp_path / "stereo.mp4", frames=48, spans=[(0.0, 2.0)], channels=2) + shape = VideoPixelShape(batch=1, frames=48, height=64, width=64, fps=24.0) + kwargs = { + "audio_encoder": _FakeAudioEncoder(), + "file_path": str(clip), + "output_shape": shape, + "device": torch.device("cpu"), + "dtype": torch.float32, + } + assert torch.equal(audio_latent_from_file(**kwargs), library.audio_latent_from_file(**kwargs)) diff --git a/backend/tests/test_audio_level.py b/backend/tests/test_audio_level.py new file mode 100644 index 000000000..9fff574fc --- /dev/null +++ b/backend/tests/test_audio_level.py @@ -0,0 +1,186 @@ +"""Level match for generated extend speech: measure the speech, clamp the gain, fail soft.""" + +from __future__ import annotations + +from pathlib import Path + +import pytest + +from inference.retake_pipeline.audio_level import ( + MAX_BOOST_DB, + MAX_CUT_DB, + generated_gain_db, + retake_gain_db, +) +from tests.video_fixtures import write_clip_with_tone_spans, write_mp4 + +DURATION = 4.0 +FRAMES = 96 # 4 s at 24 fps + + +def _gain(source: Path, generated: Path, *, mode: str = "end", cut: float = 2.0) -> float: + return generated_gain_db( + source_path=str(source), + generated_path=str(generated), + mode=mode, # type: ignore[arg-type] + generated_cut=cut, + source_seconds=DURATION, + generated_seconds=DURATION, + ) + + +@pytest.mark.parametrize( + ("source_amplitude", "generated_amplitude", "expected"), + [ + (0.1, 0.2, -6.0), + (0.5, 0.1, MAX_BOOST_DB), + (0.07, 0.8, -MAX_CUT_DB), + ], +) +def test_gain_matches_the_source_speech_and_stays_inside_the_clamp( + tmp_path: Path, source_amplitude: float, generated_amplitude: float, expected: float +) -> None: + # Bug: a near-silent or very loud measurement gives a runaway gain. + source = write_clip_with_tone_spans( + tmp_path / "source.mp4", frames=FRAMES, spans=[(0.0, 2.0)], amplitude=source_amplitude + ) + generated = write_clip_with_tone_spans( + tmp_path / "generated.mp4", frames=FRAMES, spans=[(2.0, 4.0)], amplitude=generated_amplitude + ) + assert _gain(source, generated) == pytest.approx(expected, abs=0.7) + + +def test_only_the_generated_side_of_the_cut_is_measured(tmp_path: Path) -> None: + # Bug: the audio the stitch throws away (before the cut in end mode, after it in start mode) + # sets the gain, so a loud source-side tone changes a quiet new part. + source = write_clip_with_tone_spans(tmp_path / "source.mp4", frames=FRAMES, spans=[(0.0, 2.0)]) + loud_before_cut = write_clip_with_tone_spans( + tmp_path / "before.mp4", frames=FRAMES, spans=[(0.0, 2.0)], amplitude=0.8 + ) + loud_after_cut = write_clip_with_tone_spans( + tmp_path / "after.mp4", frames=FRAMES, spans=[(2.0, 4.0)], amplitude=0.8 + ) + assert _gain(source, loud_before_cut, mode="end", cut=2.5) == 0.0 + assert _gain(source, loud_after_cut, mode="start", cut=1.5) == 0.0 + + +def test_no_gain_when_there_is_nothing_to_compare(tmp_path: Path) -> None: + # Bug: the stitch fails or applies a gain computed from silence. + generated = write_clip_with_tone_spans(tmp_path / "generated.mp4", frames=FRAMES, spans=[(2.0, 4.0)]) + no_audio = write_mp4(tmp_path / "no_audio.mp4", seconds=DURATION, fps=24) + silent = write_clip_with_tone_spans(tmp_path / "silent.mp4", frames=FRAMES, spans=[]) + broken = tmp_path / "broken.mp4" + broken.write_bytes(b"not a video") + for source in (no_audio, silent, broken): + assert _gain(source, generated) == 0.0 + + +def test_the_source_level_is_read_near_the_seam_only(tmp_path: Path) -> None: + # Bug: a long clip was matched to the speech of its whole length, not to the stretch beside the + # new part, so a loud intro set the level for a quiet end. + frames = 20 * 24 + source = write_clip_with_tone_spans(tmp_path / "source.mp4", frames=frames, spans=[(0.0, 5.0)], amplitude=0.5) + generated = write_clip_with_tone_spans( + tmp_path / "generated.mp4", frames=frames, spans=[(0.0, 5.0), (10.0, 20.0)], amplitude=0.1 + ) + common = { + "source_path": str(source), + "generated_path": str(generated), + "source_seconds": 20.0, + "generated_seconds": 20.0, + } + # End mode: the last 10 s of the source hold no speech, so there is nothing to match to. + assert generated_gain_db(**common, mode="end", generated_cut=10.0) == 0.0 + # Start mode: the first 10 s hold the loud speech, so the quiet new part is boosted (clamped). + assert generated_gain_db(**common, mode="start", generated_cut=10.0) == pytest.approx(MAX_BOOST_DB, abs=0.7) + + +def test_the_source_stretch_is_counted_on_the_source_timeline_not_the_output_timeline(tmp_path: Path) -> None: + # Bug: the stretch was counted from the length of the stitched output (source plus extension), + # so a long extension moved it past the end of the source and the level match did nothing. + early_speech = write_clip_with_tone_spans( + tmp_path / "early.mp4", frames=12 * 24, spans=[(0.0, 1.5)], amplitude=0.5 + ) + late_speech = write_clip_with_tone_spans( + tmp_path / "late.mp4", frames=12 * 24, spans=[(10.5, 12.0)], amplitude=0.1 + ) + generated = write_clip_with_tone_spans(tmp_path / "generated.mp4", frames=8 * 24, spans=[(2.0, 8.0)], amplitude=0.2) + common = {"generated_path": str(generated), "mode": "end", "generated_cut": 2.0, "generated_seconds": 8.0} + # The speech in the last 10 s of the 12 s source sets the level. + gain = generated_gain_db(source_path=str(late_speech), source_seconds=12.0, **common) # type: ignore[arg-type] + assert gain == pytest.approx(-6.0, abs=1.0) + # Speech only in the first 1.5 s is outside the last 10 s: nothing to match to. + assert generated_gain_db(source_path=str(early_speech), source_seconds=12.0, **common) == 0.0 # type: ignore[arg-type] + + +# Retake: the selection is 2.0-4.0 s of an 8 s clip. The generated file is the whole clip, so the +# selection starts at 2.0 s in it too. +RETAKE_SECONDS = 8.0 +RETAKE_FRAMES = 192 + + +def _retake_gain(source: Path, generated: Path) -> float: + return retake_gain_db( + source_path=str(source), + generated_path=str(generated), + mask_start=2.0, + mask_end=4.0, + generated_start=2.0, + source_seconds=RETAKE_SECONDS, + generated_seconds=RETAKE_SECONDS, + ) + + +def test_retake_gain_matches_the_speech_on_both_sides_of_the_selection(tmp_path: Path) -> None: + # Bug: the regenerated speech of a retake came out several dB louder than the speech around it. + source = write_clip_with_tone_spans( + tmp_path / "source.mp4", frames=RETAKE_FRAMES, spans=[(0.0, 2.0), (4.0, 6.0)], amplitude=0.1 + ) + generated = write_clip_with_tone_spans( + tmp_path / "generated.mp4", frames=RETAKE_FRAMES, spans=[(2.0, 4.0)], amplitude=0.2 + ) + assert _retake_gain(source, generated) == pytest.approx(-6.0, abs=0.7) + + +def test_retake_gain_uses_the_side_that_has_speech(tmp_path: Path) -> None: + # A selection next to silence on one side still matches the speech on the other. + source = write_clip_with_tone_spans( + tmp_path / "source.mp4", frames=RETAKE_FRAMES, spans=[(4.0, 6.0)], amplitude=0.1 + ) + generated = write_clip_with_tone_spans( + tmp_path / "generated.mp4", frames=RETAKE_FRAMES, spans=[(2.0, 4.0)], amplitude=0.2 + ) + assert _retake_gain(source, generated) == pytest.approx(-6.0, abs=0.7) + + +def test_retake_gain_measures_only_the_selection_of_the_generated_file(tmp_path: Path) -> None: + # Bug: the context around the selection in the generated file set the gain. + source = write_clip_with_tone_spans( + tmp_path / "source.mp4", frames=RETAKE_FRAMES, spans=[(0.0, 2.0), (4.0, 6.0)], amplitude=0.1 + ) + loud_context = write_clip_with_tone_spans( + tmp_path / "loud_context.mp4", frames=RETAKE_FRAMES, spans=[(0.0, 1.8), (4.2, 6.0)], amplitude=0.8 + ) + assert _retake_gain(source, loud_context) == 0.0 + + +def test_retake_gain_is_zero_when_there_is_nothing_to_compare(tmp_path: Path) -> None: + generated = write_clip_with_tone_spans( + tmp_path / "generated.mp4", frames=RETAKE_FRAMES, spans=[(2.0, 4.0)], amplitude=0.2 + ) + no_audio = write_mp4(tmp_path / "no_audio.mp4", seconds=RETAKE_SECONDS, fps=24) + silent = write_clip_with_tone_spans(tmp_path / "silent.mp4", frames=RETAKE_FRAMES, spans=[]) + broken = tmp_path / "broken.mp4" + broken.write_bytes(b"not a video") + for source in (no_audio, silent, broken): + assert _retake_gain(source, generated) == 0.0 + + +def test_retake_gain_stays_inside_the_clamp(tmp_path: Path) -> None: + source = write_clip_with_tone_spans( + tmp_path / "source.mp4", frames=RETAKE_FRAMES, spans=[(0.0, 2.0), (4.0, 6.0)], amplitude=0.07 + ) + generated = write_clip_with_tone_spans( + tmp_path / "generated.mp4", frames=RETAKE_FRAMES, spans=[(2.0, 4.0)], amplitude=0.8 + ) + assert _retake_gain(source, generated) == pytest.approx(-MAX_CUT_DB, abs=0.7) diff --git a/backend/tests/test_audio_trim.py b/backend/tests/test_audio_trim.py index 0973abce1..4e7041fdc 100644 --- a/backend/tests/test_audio_trim.py +++ b/backend/tests/test_audio_trim.py @@ -21,7 +21,8 @@ extract_audio_file, trim_audio_file, ) -from services.ffmpeg import FFMPEG_TIMEOUT_SECONDS, run_ffmpeg +from inference.ffmpeg import FFMPEG_TIMEOUT_SECONDS +from services.ffmpeg import run_ffmpeg from services.media_probe import MAX_AUDIO_BYTES from services.records import MediaError from services.sqlite_store import SqliteStore diff --git a/backend/tests/test_automatic_prompt_enhancement.py b/backend/tests/test_automatic_prompt_enhancement.py index b7a3acc6a..0a79ae2d7 100644 --- a/backend/tests/test_automatic_prompt_enhancement.py +++ b/backend/tests/test_automatic_prompt_enhancement.py @@ -32,7 +32,7 @@ ) from runtime_config.model_download_specs import get_latest_ltx_model_id, get_ltx_model_spec from services.features.lora_recipes import get_lora_recipe, make_recipe_prompt_wrap -from services.generation_interrupt import GenerationCancelledError +from inference.interrupt import GenerationCancelledError from tests.fakes import FakeCapture from tests.lora_catalog_helpers import add_ic_lora, add_lora, download_spec diff --git a/backend/tests/test_block_triton_import.py b/backend/tests/test_block_triton_import.py new file mode 100644 index 000000000..056995f9f --- /dev/null +++ b/backend/tests/test_block_triton_import.py @@ -0,0 +1,38 @@ +"""block_triton_import hides Triton so ltx-core VAE kernels use their non-Triton path.""" + +from __future__ import annotations + +import importlib +import sys + +import pytest + +from inference.triton_block import block_triton_import + + +def test_block_triton_import_makes_import_raise(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.delitem(sys.modules, "triton", raising=False) + monkeypatch.delitem(sys.modules, "triton.language", raising=False) + + assert block_triton_import() is True + + with pytest.raises(ImportError): + importlib.import_module("triton") + with pytest.raises(ImportError): + importlib.import_module("triton.language") + + +def test_block_triton_import_is_idempotent(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setitem(sys.modules, "triton", None) # pyright: ignore[reportArgumentType] + + assert block_triton_import() is True + + +def test_block_triton_import_reports_when_triton_already_loaded( + monkeypatch: pytest.MonkeyPatch, +) -> None: + fake = type(sys)("triton") + monkeypatch.setitem(sys.modules, "triton", fake) + + assert block_triton_import() is False + assert sys.modules["triton"] is fake diff --git a/backend/tests/test_budget_mode.py b/backend/tests/test_budget_mode.py index e02322086..b50fa7148 100644 --- a/backend/tests/test_budget_mode.py +++ b/backend/tests/test_budget_mode.py @@ -35,8 +35,8 @@ 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 inference.ic_lora_tiling import IcLoraTiling +from inference.frame_math import compute_num_frames from runtime_config.ltx_capabilities import budget_shape, local_caps from tests.conftest import TEST_ADMIN_TOKEN from tests.fakes import FakeCapture @@ -46,7 +46,7 @@ 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 inference.interrupt import GenerationCancelledError from services.generation_queue.types import OutputAllocation from tests.fakes.generation import FakeJobSession from services.records import AssetRecord, GenerationRecord diff --git a/backend/tests/test_custom_lora.py b/backend/tests/test_custom_lora.py index 6cfcd2d64..dd5c21490 100644 --- a/backend/tests/test_custom_lora.py +++ b/backend/tests/test_custom_lora.py @@ -37,7 +37,7 @@ 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 inference.errors import CapabilityFailedError from services.sqlite_store import SqliteStore from services.url_downloader import UrlDownloadError from state.app_state_types import CatalogDownloadSession, DownloadSessionId diff --git a/backend/tests/test_day_to_night.py b/backend/tests/test_day_to_night.py index fb69530ba..d94856226 100644 --- a/backend/tests/test_day_to_night.py +++ b/backend/tests/test_day_to_night.py @@ -47,11 +47,12 @@ ) from services.features.video.ic_lora_recipe import ic_lora_video_filters from services.features.video.ic_lora_recipe import IcLoraRecipeExecutor -from services.generation_interrupt import GenerationCancelledError +from inference.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 inference.errors import CapabilityFailedError +from services.records import AssetRecord, GenerationRecord from services.sqlite_store import SqliteStore from state import build_initial_state, set_state_service_for_tests from tests.conftest import TEST_ADMIN_TOKEN diff --git a/backend/tests/test_decode_tiling_retry.py b/backend/tests/test_decode_tiling_retry.py index 728cb0512..1dd9b2e7d 100644 --- a/backend/tests/test_decode_tiling_retry.py +++ b/backend/tests/test_decode_tiling_retry.py @@ -4,7 +4,7 @@ import torch -from services.ltx_pipeline_common import is_decode_tile_shortage, stable_cuda_decode_budget_bytes +from inference.common import is_decode_tile_shortage, stable_cuda_decode_budget_bytes _GIB = 1024**3 diff --git a/backend/tests/test_denoising_progress.py b/backend/tests/test_denoising_progress.py index b63d9ef65..c23b3cad2 100644 --- a/backend/tests/test_denoising_progress.py +++ b/backend/tests/test_denoising_progress.py @@ -8,7 +8,7 @@ from ltx_pipelines.utils.constants import DISTILLED_SIGMA_VALUES, STAGE_2_DISTILLED_SIGMA_VALUES -from services.denoising_progress import ( +from inference.progress import ( DISTILLED_STAGE_1_STEPS, DISTILLED_STAGE_2_STEPS, DISTILLED_TOTAL_STEPS, @@ -38,7 +38,7 @@ def test_stage_1_only_total_omits_stage_2() -> None: def test_note_step_reports_current_and_total_to_the_sink() -> None: seen: list[tuple[int, int]] = [] - from services import denoising_progress + import inference.progress as denoising_progress denoising_progress.configure_sink(lambda current, total: seen.append((current, total))) total = distilled_total_steps() diff --git a/backend/tests/test_device_calibration.py b/backend/tests/test_device_calibration.py index 1e13aead5..28a252195 100644 --- a/backend/tests/test_device_calibration.py +++ b/backend/tests/test_device_calibration.py @@ -27,7 +27,7 @@ ) 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 inference import run_peak from services.records import UnavailableError from services.sqlite_store import SqliteStore diff --git a/backend/tests/test_diffusion_interrupt.py b/backend/tests/test_diffusion_interrupt.py index b24000251..cd41fa785 100644 --- a/backend/tests/test_diffusion_interrupt.py +++ b/backend/tests/test_diffusion_interrupt.py @@ -7,8 +7,8 @@ import pytest from ltx_pipelines.utils.blocks import DiffusionStage -import services.patches.diffusion_interrupt as diffusion_interrupt -from services.generation_interrupt import GenerationCancelledError, request +import inference.patches.diffusion_interrupt as diffusion_interrupt +from inference.interrupt import GenerationCancelledError, request def test_patch_rebinds_diffusion_stage_call() -> None: @@ -79,7 +79,7 @@ def test_loop_tqdm_iterations_count_as_one_step_even_when_denoiser_runs_twice( monkeypatch: pytest.MonkeyPatch, ) -> None: """res2s calls the denoiser twice per loop step; the bar must move once per step.""" - from services.denoising_progress import configure_sink, reset, track_denoising + from inference.progress import configure_sink, reset, track_denoising seen: list[tuple[int, int]] = [] configure_sink(lambda current, total: seen.append((current, total))) @@ -142,7 +142,7 @@ def test_ancestral_terminal_break_still_counts_the_last_iteration( """euler_ancestral_denoising_loop breaks when the next sigma is 0, so the tqdm consumer never resumes after that yield. The completed iteration must still count when the loop returns normally.""" - from services.denoising_progress import configure_sink, reset, track_denoising + from inference.progress import configure_sink, reset, track_denoising seen: list[tuple[int, int]] = [] configure_sink(lambda current, total: seen.append((current, total))) @@ -172,7 +172,7 @@ def ancestral_loop(*, sigmas: object, denoiser: object, **kwargs: object) -> Non def test_cancelled_loop_does_not_count_the_aborted_iteration( monkeypatch: pytest.MonkeyPatch, ) -> None: - from services.denoising_progress import configure_sink, reset, track_denoising + from inference.progress import configure_sink, reset, track_denoising seen: list[tuple[int, int]] = [] configure_sink(lambda current, total: seen.append((current, total))) diff --git a/backend/tests/test_diffusion_stage_cache.py b/backend/tests/test_diffusion_stage_cache.py index ced626c1d..ab316447b 100644 --- a/backend/tests/test_diffusion_stage_cache.py +++ b/backend/tests/test_diffusion_stage_cache.py @@ -22,7 +22,7 @@ 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 +from inference.patches import diffusion_stage_cache as dsc class _FakeModel: diff --git a/backend/tests/test_diffvae_decode_vram.py b/backend/tests/test_diffvae_decode_vram.py index 1cbc7fe6d..46b31adb9 100644 --- a/backend/tests/test_diffvae_decode_vram.py +++ b/backend/tests/test_diffvae_decode_vram.py @@ -7,8 +7,8 @@ from ltx_core.model.video_vae import DimensionSizeConfig, TileSizeConfig from ltx_core.tiling import _validate_overlap -from services.patches import diffusion_stage_cache as dsc -from services.patches import diffvae_decode_vram as patch +from inference.patches import diffusion_stage_cache as dsc +from inference.patches import diffvae_decode_vram as patch def _tiles(*, frames: int, height: int, width: int, overlap_t: int = 40, overlap_hw: int = 160) -> TileSizeConfig: diff --git a/backend/tests/test_distilled_a2v_stages.py b/backend/tests/test_distilled_a2v_stages.py index af2472391..f9314a778 100644 --- a/backend/tests/test_distilled_a2v_stages.py +++ b/backend/tests/test_distilled_a2v_stages.py @@ -18,7 +18,7 @@ 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 +from inference.a2v_pipeline.distilled_a2v_pipeline import DistilledA2VPipeline # 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) diff --git a/backend/tests/test_distilled_skip_stage_2.py b/backend/tests/test_distilled_skip_stage_2.py index 94c5718e2..cf6f27e77 100644 --- a/backend/tests/test_distilled_skip_stage_2.py +++ b/backend/tests/test_distilled_skip_stage_2.py @@ -10,7 +10,7 @@ import ltx_pipelines.distilled as distilled from ltx_pipelines.utils.types import ImageConditioningInput, LoadedImageConditioning, PipelineOutput -from services.fast_video_pipeline.distilled_skip_stage_2 import DistilledPipelineWithSkipStage2 +from inference.fast_video_pipeline.distilled_skip_stage_2 import DistilledPipelineWithSkipStage2 class _Encoding: @@ -52,12 +52,12 @@ def fake_latents(*, pixel_shape, video_scale_factors, **_kwargs): return video, audio monkeypatch.setattr( - "services.fast_video_pipeline.distilled_skip_stage_2.image_conditionings", + "inference.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", + "inference.fast_video_pipeline.distilled_skip_stage_2.create_initial_av_latents", fake_latents, ) monkeypatch.setattr("ltx_pipelines.utils.helpers.tiling_scale_factors_for_vae", lambda _path: decoder_scale) @@ -196,7 +196,7 @@ def recording_latents(*, pixel_shape, **_kwargs): 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", + "inference.fast_video_pipeline.distilled_skip_stage_2.create_initial_av_latents", recording_latents, ) diff --git a/backend/tests/test_edit_preflight.py b/backend/tests/test_edit_preflight.py index 574aefba8..66ae51c0a 100644 --- a/backend/tests/test_edit_preflight.py +++ b/backend/tests/test_edit_preflight.py @@ -68,8 +68,9 @@ def _preflight_body( durations: list[float] | None = None, start_time: float = 0, mode: str = "end", + context_mode: str | None = None, ) -> dict: - return { + body = { "feature": feature, "assetId": asset_id, "startTime": start_time, @@ -81,6 +82,9 @@ def _preflight_body( ), "durations": durations if durations is not None else [4], } + if context_mode is not None: + body["contextMode"] = context_mode + return body def _clip_1080p(test_state, tmp_path: Path) -> str: @@ -124,6 +128,76 @@ def test_preflight_cell_mirrors_create_422( assert cell["code"] == payload["code"] +def test_preflight_short_context_refusal_mirrors_create_422( + test_state, create_fake_model_files, tmp_path: Path +) -> None: + create_fake_model_files() + _configure_windows_edit(test_state, vram_gib=12, total_ram_gib=64) + asset_id = _clip_1080p(test_state, tmp_path) + with _client(test_state) as client: + preflight = client.post( + "/api/generations/edit/preflight", + json=_preflight_body(asset_id, durations=[12], context_mode="short"), + ) + assert preflight.status_code == 200 + (cell,) = [c for c in preflight.json()["cells"] if c["duration"] == 12] + assert cell["ok"] is False + + create = client.post( + "/api/generations/extend", + json={ + "params": { + "prompt": "the scene continues", + "model": "ltx-2.5-fast", + "duration": 12, + "mode": "end", + "contextMode": "short", + }, + "inputs": {"video": {"assetId": asset_id}}, + }, + ) + assert create.status_code == 422 + payload = create.json() + assert cell["message"] == payload["message"] + assert cell["code"] == payload["code"] + + +def test_preflight_short_context_allows_a_longer_extend_than_long( + test_state, create_fake_model_files, tmp_path: Path +) -> None: + """A Short context extend keeps about 2 s of the clip as context, a Long one at least 5 s, so + the same card fits a longer extension. The picker must show what create would allow.""" + create_fake_model_files() + _configure_windows_edit(test_state, vram_gib=24, total_ram_gib=64) + asset_id = _clip_1080p(test_state, tmp_path) + + def max_seconds(client: TestClient, context_mode: str | None) -> float: + response = client.post( + "/api/generations/edit/preflight", + json=_preflight_body(asset_id, durations=[4], context_mode=context_mode), + ) + assert response.status_code == 200 + (row,) = response.json()["resolutions"] + return row["maxDurationSeconds"] + + with _client(test_state) as client: + long = max_seconds(client, "long") + short = max_seconds(client, "short") + # Leaving the field out is a Long context extend, as create treats it. + assert max_seconds(client, None) == long + assert 0 < long < short + + # A duration that Long refuses is admitted for Short, cell by cell. + longer = long + 0.5 + probe = client.post( + "/api/generations/edit/preflight", + json=_preflight_body(asset_id, durations=[longer], context_mode="short"), + ) + assert probe.status_code == 200 + (cell,) = [c for c in probe.json()["cells"] if c["duration"] == longer] + assert cell["ok"] is True + + def test_preflight_max_shrinks_at_higher_tier( test_state, create_fake_model_files, tmp_path: Path ) -> None: diff --git a/backend/tests/test_edit_shrink_then_run.py b/backend/tests/test_edit_shrink_then_run.py index 5bfc6fd20..4ca15b5ab 100644 --- a/backend/tests/test_edit_shrink_then_run.py +++ b/backend/tests/test_edit_shrink_then_run.py @@ -25,7 +25,7 @@ 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 inference.errors import CapabilityFailedError from services.sqlite_store import SqliteStore from tests.video_fixtures import write_mp4 diff --git a/backend/tests/test_eta.py b/backend/tests/test_eta.py index ad7795d50..e17a079b6 100644 --- a/backend/tests/test_eta.py +++ b/backend/tests/test_eta.py @@ -4,7 +4,7 @@ import pytest -from frame_math import compute_num_frames +from inference.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 ( @@ -19,7 +19,7 @@ remaining_wall_time_s, spatial_tile_count, ) -from runtime_config.ic_lora_tiling import IcLoraTiling +from inference.ic_lora_tiling import IcLoraTiling # (width, height, seconds, full_cold, stream_cpu_cold) _CELLS = [ diff --git a/backend/tests/test_extend_edit_window.py b/backend/tests/test_extend_edit_window.py index 6b0222d90..d845f5b09 100644 --- a/backend/tests/test_extend_edit_window.py +++ b/backend/tests/test_extend_edit_window.py @@ -8,8 +8,16 @@ import pytest -from services.retake_pipeline.window import ( +from inference.retake_pipeline.window import ( + CONTINUATION_CONTEXT_FRAMES, + VIDEO_JOB_TOO_LARGE, + EditRefusal, MAX_INPUT_FRAMES, + PreparedExtendWindow, + context_cap_frames, + continuation_context_frames, + extend_context_floor, + prepare_extend_window, MIN_EXTEND_CONTEXT_FRAMES, duration_to_extend_frames, extend_exceeds_cap, @@ -134,3 +142,72 @@ def test_extend_too_long_at_shortened_cap_names_the_machine() -> None: frame_cap=300, fps=24.0, ) assert message == "Extend of 10s is too long for 1920x1080 on this machine (at most 7s)." + + +def _prepare(context_mode: str, *, frame_cap: int, source_frames: int = 144, mode: str = "end"): + return prepare_extend_window( + fps=24.0, + source_frames=source_frames, + target_width=1280, + target_height=720, + frame_cap=frame_cap, + duration=2.0, + mode=mode, # type: ignore[arg-type] + context_mode=context_mode, # type: ignore[arg-type] + ) + + +def test_short_context_is_admitted_where_long_context_is_refused() -> None: + # Bug: Short context keeps the 121 frame admission floor, so the shorter window it needs + # never gets a chance on a machine with a small frame cap. + refusal = _prepare("long", frame_cap=100) + assert isinstance(refusal, EditRefusal) + assert refusal.code == VIDEO_JOB_TOO_LARGE + prepared = _prepare("short", frame_cap=100) + assert isinstance(prepared, PreparedExtendWindow) + + +@pytest.mark.parametrize("mode", ["end", "start"]) +def test_short_context_is_capped_and_long_context_is_not(mode: str) -> None: + short = _prepare("short", frame_cap=MAX_INPUT_FRAMES, mode=mode) + long = _prepare("long", frame_cap=MAX_INPUT_FRAMES, mode=mode) + assert isinstance(short, PreparedExtendWindow) and isinstance(long, PreparedExtendWindow) + assert short.window.context_frames == CONTINUATION_CONTEXT_FRAMES + # 144 source frames snap down to the 8k+1 length 137. Long mode keeps all of it. + assert long.window.context_frames == 137 + + +@pytest.mark.parametrize( + ("fps", "expected"), [(24.0, 49), (25.0, 49), (30.0, 57), (50.0, 97), (60.0, 121)] +) +def test_continuation_context_is_about_two_seconds_at_any_frame_rate(fps: float, expected: int) -> None: + # Bug: a fixed 49 frames is 1.6 s at 30 fps and 0.8 s at 60 fps, too short for the voice bridge. + frames = continuation_context_frames(fps) + assert frames == expected + assert (frames - 1) % 8 == 0 + assert 1.85 <= frames / fps <= 2.3 + + +def test_short_context_window_follows_the_frame_rate() -> None: + prepared = prepare_extend_window( + fps=30.0, + source_frames=180, + target_width=1920, + target_height=1088, + frame_cap=MAX_INPUT_FRAMES, + duration=2.0, + mode="end", + context_mode="short", + ) + assert isinstance(prepared, PreparedExtendWindow) + assert prepared.window.context_frames == continuation_context_frames(30.0) == 57 + + +def test_the_context_mode_sets_the_cap_and_the_admission_floor() -> None: + assert context_cap_frames("long", 24.0) is None + assert context_cap_frames("short", 24.0) == CONTINUATION_CONTEXT_FRAMES + assert extend_context_floor("long", 24.0) == MIN_EXTEND_CONTEXT_FRAMES + # Short keeps less than the Long floor, so its floor is lowered to what it keeps. + assert extend_context_floor("short", 24.0) == CONTINUATION_CONTEXT_FRAMES + # An explicit floor (the shrink retry passes 1) is never raised. + assert extend_context_floor("short", 24.0, 1) == 1 diff --git a/backend/tests/test_extend_frame_math.py b/backend/tests/test_extend_frame_math.py index c44d72c74..eca6ec67a 100644 --- a/backend/tests/test_extend_frame_math.py +++ b/backend/tests/test_extend_frame_math.py @@ -11,7 +11,7 @@ from ltx_core.types import VideoLatentShape, VideoPixelShape from handlers.extend_handler import ExtendHandler -from services.retake_pipeline.ltx_retake_pipeline import LTXRetakePipeline +from inference.retake_pipeline.ltx_retake_pipeline import LTXRetakePipeline def test_pad_latent_frames_appends_for_end(): diff --git a/backend/tests/test_extend_stitch.py b/backend/tests/test_extend_stitch.py index 54771e823..83afa5476 100644 --- a/backend/tests/test_extend_stitch.py +++ b/backend/tests/test_extend_stitch.py @@ -7,9 +7,14 @@ import numpy as np import pytest -from services.retake_pipeline.window import MAX_FADE_FRAMES, MAX_INPUT_FRAMES, window_for_extend -from services.retake_pipeline.extend_stitch import fade_window_for_extend, stitch_extend_output -from services.retake_pipeline.rgb_stitch import FadeWindow, blend_rgb, generated_weight +from inference.retake_pipeline.audio_level import speech_level_db +from inference.retake_pipeline.window import MAX_FADE_FRAMES, MAX_INPUT_FRAMES, window_for_extend +from inference.retake_pipeline.extend_stitch import fade_window_for_extend, stitch_extend_output +from inference.retake_pipeline.rgb_stitch import FadeWindow, blend_rgb, generated_weight +from inference.ffmpeg import run_ffmpeg +from inference.retake_pipeline.stitch_audio import JOIN_FADE_SECONDS, AudioPiece, audio_cut_graph +from inference.retake_pipeline.speech_analysis import ANALYSIS_SAMPLE_RATE, decode_mono +from tests.video_fixtures import write_clip_with_tone_spans def test_generated_weight_matches_ltxv_api_full_fade_bands() -> None: @@ -139,9 +144,9 @@ def test_stitch_extend_output_keeps_generated_audio_when_source_is_silent( def _capture(args: list[str], **_kwargs: object) -> None: captured.append(args) - monkeypatch.setattr("services.retake_pipeline.extend_stitch.run_ffmpeg", _capture) + monkeypatch.setattr("inference.retake_pipeline.extend_stitch.run_ffmpeg", _capture) monkeypatch.setattr( - "services.retake_pipeline.extend_stitch._has_audio", + "inference.retake_pipeline.extend_stitch._has_audio", lambda path: "generated" in path or "window" in path, ) source = _solid_video(tmp_path / "source.mp4", rgb=(0, 0, 0), frames=25, fps=25) @@ -172,3 +177,126 @@ def _capture(args: list[str], **_kwargs: object) -> None: assert "[3:a]" in args[args.index("-filter_complex") + 1] assert "lutrgb=" not in args[args.index("-filter_complex") + 1] assert "xfade=" not in args[args.index("-filter_complex") + 1] + + +def test_audio_cut_graph_adds_gain_and_limiter_only_for_a_nonzero_gain() -> None: + # Bug: a zero gain still runs the limiter, which changes untouched audio. + plain = audio_cut_graph([AudioPiece("[0:a]", end=1.0), AudioPiece("[1:a]", start=1.0)]) + assert "volume=" not in plain + assert "alimiter" not in plain + boosted = audio_cut_graph([AudioPiece("[0:a]", end=1.0), AudioPiece("[1:a]", start=1.0, gain_db=3.0)]) + first, second = boosted.split(";")[:2] + assert "volume" not in first + # ``level=0``: the limiter's auto level would add a gain of its own. + assert "volume=3.00dB,alimiter=limit=0.97:level=0," in second + # A cut cannot clip, so it gets no limiter. + cut = audio_cut_graph([AudioPiece("[0:a]", end=1.0), AudioPiece("[1:a]", start=1.0, gain_db=-6.0)]) + cut_second = cut.split(";")[1] + assert "volume=-6.00dB," in cut_second + assert "alimiter" not in cut_second + + +def test_audio_cut_graph_gives_an_empty_piece_no_fade() -> None: + # Bug: an empty piece asked for a zero-length fade, which ffmpeg rejects. + graph = audio_cut_graph([AudioPiece("[0:a]", end=0.0), AudioPiece("[1:a]", start=0.0)]) + first = graph.split(";")[0] + assert "afade" not in first + + +@pytest.mark.parametrize("mode", ["end", "start"]) +def test_voice_bridge_fade_stays_inside_the_real_seam_frames(mode: str) -> None: + # Bug: the lerp reaches into the speech piece of the bridge, a different moment of the source, + # and the picture jumps to it for a few frames (the "ghost jump"). + window = window_for_extend( + source_frames=144, + extend_frames=48, + mode=mode, # type: ignore[arg-type] + max_input_frames=MAX_INPUT_FRAMES, + max_context_frames=49, + ) + seam_frames = 32 + fade = fade_window_for_extend( + window, mode=mode, extend_frames=48, fps=24.0, seam_frames=seam_frames # type: ignore[arg-type] + ) + plain = fade_window_for_extend(window, mode=mode, extend_frames=48, fps=24.0) + if mode == "end": + assert fade.context_start == window.context_frames - seam_frames + assert (fade.edit_start, fade.edit_end) == (plain.edit_start, plain.edit_end) + assert min(MAX_FADE_FRAMES, fade.edit_start - fade.context_start) <= seam_frames + else: + assert fade.context_end == 48 + seam_frames + assert fade.context_end < plain.context_end + + +def test_stitch_brings_loud_generated_speech_to_the_source_level(tmp_path: Path) -> None: + # Bug: the model returns speech much louder than the source, so the level jumps at the cut. + source = write_clip_with_tone_spans( + tmp_path / "source.mp4", frames=25, fps=25, spans=[(0.0, 1.0)], amplitude=0.1 + ) + generated = write_clip_with_tone_spans( + tmp_path / "generated.mp4", frames=41, fps=25, spans=[(0.0, 1.64)], amplitude=0.8 + ) + window = window_for_extend( + source_frames=25, extend_frames=16, mode="end", max_input_frames=MAX_INPUT_FRAMES + ) + dest = tmp_path / "out.mp4" + stitch_extend_output( + source_path=str(source), + windowed_path=str(generated), + dest_path=str(dest), + window=window, + fps=25.0, + mode="end", + extend_frames=16, + target_width=64, + target_height=64, + ) + duration = 41 / 25 + out = decode_mono(str(dest), duration) + rate = ANALYSIS_SAMPLE_RATE + source_level = speech_level_db(decode_mono(str(source), 1.0)) + new_part_level = speech_level_db(out[int(1.05 * rate) :]) + assert source_level is not None and new_part_level is not None + assert new_part_level == pytest.approx(source_level, abs=2.0) + + +def test_audio_cut_graph_fades_each_side_of_a_join_and_nowhere_else() -> None: + graph = audio_cut_graph( + [AudioPiece("[0:a]", end=1.0), AudioPiece("[1:a]", start=0.5, end=2.0), AudioPiece("[2:a]", start=3.0)] + ) + first, middle, last = graph.split(";")[:3] + fade_in = f"afade=t=in:d={JOIN_FADE_SECONDS:.6f}" + assert "afade=t=in" not in first and "afade=t=out:st=0.985000" in first + assert fade_in in middle and "afade=t=out:st=1.485000" in middle + assert fade_in in last and "afade=t=out" not in last + # A single piece has no join, so it is not faded. + assert "afade" not in audio_cut_graph([AudioPiece("[0:a]", end=1.0)]) + + +def test_audio_cut_graph_keeps_the_length_of_the_pieces() -> None: + # Bug: a crossfade that overlaps the pieces shortens the audio, and sound and picture drift. + graph = audio_cut_graph([AudioPiece("[0:a]", end=0.5), AudioPiece("[1:a]", start=0.5)]) + assert "acrossfade" not in graph + assert "concat=n=2:v=0:a=1[a]" in graph + + +def test_a_join_between_two_tones_does_not_step_in_the_waveform(tmp_path: Path) -> None: + # Bug: a hard cut between two sounds is heard as a click. + out = tmp_path / "joined.wav" + run_ffmpeg( + [ + "-y", "-f", "lavfi", "-i", "sine=f=220:d=1:r=48000", + "-f", "lavfi", "-i", "sine=f=331:d=1:r=48000", + "-filter_complex", audio_cut_graph([AudioPiece("[0:a]", end=0.5), AudioPiece("[1:a]", start=0.5)]), + "-map", "[a]", "-ar", "48000", str(out), + ] + ) + import av + + with av.open(str(out)) as container: + samples = np.concatenate([f.to_ndarray().reshape(-1) for f in container.decode(audio=0)]).astype(np.float32) + assert len(samples) == pytest.approx(48000, abs=2) + steps = np.abs(np.diff(samples)) + join = int(0.5 * 48000) + steady = steps[: join - 2000].max() + assert steps[join - 240 : join + 240].max() <= 1.5 * steady diff --git a/backend/tests/test_fast_chunked_budget.py b/backend/tests/test_fast_chunked_budget.py index f07e841f8..8ef483de2 100644 --- a/backend/tests/test_fast_chunked_budget.py +++ b/backend/tests/test_fast_chunked_budget.py @@ -11,11 +11,11 @@ import pytest -from frame_math import compute_num_frames +from inference.frame_math import compute_num_frames 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 inference.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 ( diff --git a/backend/tests/test_fast_chunked_cells.py b/backend/tests/test_fast_chunked_cells.py index 1fa3e830d..5ada1316d 100644 --- a/backend/tests/test_fast_chunked_cells.py +++ b/backend/tests/test_fast_chunked_cells.py @@ -3,8 +3,8 @@ from __future__ import annotations from api_model_specs import _filter_local_fast_resolution_map # pyright: ignore[reportPrivateUsage] -from frame_math import compute_num_frames -from runtime_config.fast_chunking import job_window_count +from inference.frame_math import compute_num_frames +from inference.fast_chunking import job_window_count from runtime_config.ltx_capabilities import local_caps from runtime_config.model_download_specs import get_ltx_model_spec from tests.test_video_job_budget import _job_filter, _mac_profile, _windows_measured_filter diff --git a/backend/tests/test_fast_fallback_windows.py b/backend/tests/test_fast_fallback_windows.py index 2103dc632..c5b47e166 100644 --- a/backend/tests/test_fast_fallback_windows.py +++ b/backend/tests/test_fast_fallback_windows.py @@ -11,7 +11,7 @@ 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 ( +from inference.fast_chunking import ( CARRY_FRAMES, MIN_WINDOW_FRAMES, is_chunked_canvas, diff --git a/backend/tests/test_feature_flags.py b/backend/tests/test_feature_flags.py index 02285e294..6e4434724 100644 --- a/backend/tests/test_feature_flags.py +++ b/backend/tests/test_feature_flags.py @@ -15,7 +15,6 @@ "highResVideoToVideo": False, "createWithAi": False, "showGenerationNegativePrompt": False, - "keyframes": False, } AUTH = {"Authorization": "Bearer pair-token"} @@ -62,6 +61,20 @@ def test_corrupt_file_falls_back_to_defaults(client, test_state): assert client.get("/api/feature-flags").json() == DEFAULTS +def test_file_with_a_removed_flag_keeps_the_other_flags_and_drops_it_on_write(client, test_state): + saved = test_state.config.app_data_dir / "feature_flags.json" + saved.write_text(json.dumps({"customIcLora": True, "keyframes": True}), encoding="utf-8") + + assert client.get("/api/feature-flags").json() == {**DEFAULTS, "customIcLora": True} + + client.request("PATCH", "/api/feature-flags", json={"createWithAi": True}) + assert json.loads(saved.read_text(encoding="utf-8")) == { + **DEFAULTS, + "customIcLora": True, + "createWithAi": True, + } + + def test_remote_serves_flags_with_bearer_only(test_state): app = create_remote_app(handler=test_state, remote_token="pair-token") with TestClient(app) as remote: diff --git a/backend/tests/test_finite_guard.py b/backend/tests/test_finite_guard.py new file mode 100644 index 000000000..89075718e --- /dev/null +++ b/backend/tests/test_finite_guard.py @@ -0,0 +1,61 @@ +"""A denoise step with NaN or Inf must fail the job on MPS (see ``inference.finite_guard``).""" + +from __future__ import annotations + +import dataclasses +from collections.abc import Callable +from typing import Any + +import pytest +import torch +from ltx_pipelines.utils.types import DenoisedLatentResult, VideoAudio + +from inference.finite_guard import NonFiniteLatentError, raise_if_nonfinite, wrap_denoiser + +needs_mps = pytest.mark.skipif(not torch.backends.mps.is_available(), reason="the guard only reads MPS tensors") + + +def _result(*, video: torch.Tensor | None = None, audio: torch.Tensor | None = None) -> VideoAudio[DenoisedLatentResult]: + return VideoAudio( + video=DenoisedLatentResult(denoised=video) if video is not None else None, + audio=DenoisedLatentResult(denoised=audio) if audio is not None else None, + ) + + +def test_guard_reads_the_field_names_ltx_pipelines_uses() -> None: + # The guard reads these by name. A rename upstream would turn it into a silent no-op. + assert {"video", "audio"} <= {f.name for f in dataclasses.fields(VideoAudio)} + assert "denoised" in {f.name for f in dataclasses.fields(DenoisedLatentResult)} + + +def test_nonfinite_values_off_mps_are_not_checked() -> None: + raise_if_nonfinite(_result(video=torch.tensor([float("nan")]))) + + +@needs_mps +@pytest.mark.parametrize( + ("bad_side", "bad_value"), + [("video", float("nan")), ("video", float("inf")), ("audio", float("nan"))], +) +def test_nonfinite_denoised_on_mps_fails_the_job(bad_side: str, bad_value: float) -> None: + good = torch.ones(4, device="mps") + bad = torch.tensor([1.0, bad_value], device="mps") + result = _result(video=bad if bad_side == "video" else good, audio=bad if bad_side == "audio" else good) + + with pytest.raises(NonFiniteLatentError, match=bad_side): + raise_if_nonfinite(result) + + +@needs_mps +def test_finite_denoised_on_mps_passes_through_unchanged() -> None: + result = _result(video=torch.ones(4, device="mps")) + seen: list[tuple[tuple[Any, ...], dict[str, Any]]] = [] + + def denoiser(*args: Any, **kwargs: Any) -> VideoAudio[DenoisedLatentResult]: + seen.append((args, kwargs)) + return result + + wrapped: Callable[..., Any] = wrap_denoiser(denoiser) + + assert wrapped("transformer", step_index=3) is result + assert seen == [(("transformer",), {"step_index": 3})] diff --git a/backend/tests/test_frame_math.py b/backend/tests/test_frame_math.py index 388dfde7b..0ebc7c333 100644 --- a/backend/tests/test_frame_math.py +++ b/backend/tests/test_frame_math.py @@ -1,6 +1,6 @@ """Unit tests for shared video frame-count calculations.""" -from frame_math import effective_a2v_audio_seconds, num_frames_for_audio_duration +from inference.frame_math import effective_a2v_audio_seconds, num_frames_for_audio_duration def test_audio_duration_10_563_seconds_floors_to_249_frames_under_cap() -> None: diff --git a/backend/tests/test_generation.py b/backend/tests/test_generation.py index cc4e8a9ad..6706e8b86 100644 --- a/backend/tests/test_generation.py +++ b/backend/tests/test_generation.py @@ -18,14 +18,14 @@ GenerateVideoCompleteResponse, GenerateVideoRequest, ) -from frame_math import AutoDurationSpec, compute_num_frames +from inference.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 +import inference.interrupt as generation_interrupt +from inference.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 diff --git a/backend/tests/test_generation_interrupt.py b/backend/tests/test_generation_interrupt.py index 31ebe3be6..2796a26f1 100644 --- a/backend/tests/test_generation_interrupt.py +++ b/backend/tests/test_generation_interrupt.py @@ -4,7 +4,7 @@ import pytest -from services.generation_interrupt import ( +from inference.interrupt import ( GenerationCancelledError, clear, diffusers_step_callback, diff --git a/backend/tests/test_generation_queue.py b/backend/tests/test_generation_queue.py index 2ca77c895..b32b1acea 100644 --- a/backend/tests/test_generation_queue.py +++ b/backend/tests/test_generation_queue.py @@ -25,7 +25,7 @@ GenerateVideoResponse, GenerationErrorCode, ) -from frame_math import compute_num_frames +from inference.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 @@ -46,7 +46,7 @@ ) from services.generation_queue.registry import ExecutorRegistry from services.generation_queue.runner import QueueRunner -from services.patches import diffusion_stage_cache +from inference.patches import diffusion_stage_cache from services.generation_queue.sessions import JobSession from services.generation_queue.types import ( ExecutionOutcome, @@ -55,9 +55,10 @@ OutputPlan, ) from services.media_probe import probe_file -from services.records import AttemptError, CapabilityFailedError, GenerationRecord +from inference.errors import CapabilityFailedError +from services.records import AttemptError, GenerationRecord from services.sqlite_store import SqliteStore -from services.generation_interrupt import ( +from inference.interrupt import ( GenerationCancelledError, is_requested, request, diff --git a/backend/tests/test_gpu_job.py b/backend/tests/test_gpu_job.py index c1ae2a5ef..99dd23fe8 100644 --- a/backend/tests/test_gpu_job.py +++ b/backend/tests/test_gpu_job.py @@ -6,7 +6,7 @@ from runtime_config.device_calibration import JobEnvelope from services.features.video.edit_executor import run_gpu_job -from services.generation_interrupt import GenerationCancelledError +from inference.interrupt import GenerationCancelledError class _Slot: diff --git a/backend/tests/test_http.py b/backend/tests/test_http.py index 46aed385a..f26fa2a72 100644 --- a/backend/tests/test_http.py +++ b/backend/tests/test_http.py @@ -14,7 +14,7 @@ from api_types import RetakeParams, RetakeRequestParams from app_factory import create_app from app_handler import ServiceBundle, open_store -from frame_math import compute_num_frames, num_frames_for_audio_duration +from inference.frame_math import compute_num_frames, num_frames_for_audio_duration from handlers.queued_generation_handler import QueuedGenerationHandler from services.store import Store from services.media_probe import MAX_IMAGE_BYTES, MAX_VIDEO_BYTES diff --git a/backend/tests/test_ic_lora.py b/backend/tests/test_ic_lora.py index e549640f1..84dc3ee02 100644 --- a/backend/tests/test_ic_lora.py +++ b/backend/tests/test_ic_lora.py @@ -369,7 +369,7 @@ def test_custom_requires_lora_and_control_video(self, client, test_state, create def test_resolve_settings_keeps_a_tiled_entry_single_stage() -> None: from api_types import IcLoraGenerateRequest, IcLoraSettings from handlers.ic_lora_handler import _resolve_settings - from runtime_config.ic_lora_tiling import IcLoraTiling + from inference.ic_lora_tiling import IcLoraTiling tiled = IcLoraSettings(skip_stage_2=True, tiling=IcLoraTiling(long_side=960, short_side=544)) for override in (None, True, False): diff --git a/backend/tests/test_ic_lora_adaptive_budget.py b/backend/tests/test_ic_lora_adaptive_budget.py index 3aa8e81a1..10a8b9171 100644 --- a/backend/tests/test_ic_lora_adaptive_budget.py +++ b/backend/tests/test_ic_lora_adaptive_budget.py @@ -13,7 +13,7 @@ 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 inference.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) diff --git a/backend/tests/test_ic_lora_adaptive_window.py b/backend/tests/test_ic_lora_adaptive_window.py index e5d90f219..eaf5b47b0 100644 --- a/backend/tests/test_ic_lora_adaptive_window.py +++ b/backend/tests/test_ic_lora_adaptive_window.py @@ -8,7 +8,7 @@ adaptive_window_candidates, resolution_window_cap, ) -from runtime_config.ic_lora_tiling import ADAPTIVE_MAX_WINDOW_FRAMES, _CONTROLS # pyright: ignore[reportPrivateUsage] +from inference.ic_lora_tiling import ADAPTIVE_MAX_WINDOW_FRAMES, _CONTROLS # pyright: ignore[reportPrivateUsage] @pytest.mark.parametrize( diff --git a/backend/tests/test_ic_lora_auto_carry.py b/backend/tests/test_ic_lora_auto_carry.py index e7aa9e323..04530a043 100644 --- a/backend/tests/test_ic_lora_auto_carry.py +++ b/backend/tests/test_ic_lora_auto_carry.py @@ -9,7 +9,7 @@ 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 ( +from inference.ic_lora_tiling import ( CARRY_PRESETS, IcLoraTiling, auto_carry_candidates, diff --git a/backend/tests/test_ic_lora_chunking.py b/backend/tests/test_ic_lora_chunking.py index 4f8a515e9..d56b8d8c9 100644 --- a/backend/tests/test_ic_lora_chunking.py +++ b/backend/tests/test_ic_lora_chunking.py @@ -7,7 +7,7 @@ ic_lora_chunk_pixel_frames, ) from runtime_config.ic_lora_stage_mode import IcLoraStageMode -from runtime_config.ic_lora_tiling import IcLoraTiling +from inference.ic_lora_tiling import IcLoraTiling def test_large_single_stage_long_clip_chunks() -> None: diff --git a/backend/tests/test_ic_lora_generate.py b/backend/tests/test_ic_lora_generate.py index 25611f769..0d1ed42a1 100644 --- a/backend/tests/test_ic_lora_generate.py +++ b/backend/tests/test_ic_lora_generate.py @@ -5,7 +5,7 @@ from fastapi.testclient import TestClient from PIL import Image -from frame_math import compute_num_frames +from inference.frame_math import compute_num_frames 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, @@ -1154,7 +1154,7 @@ def test_outpaint_over_spatial_cap_unlinks_mask( def test_catalog_preprocess_runs_after_generation_started( client: TestClient, tmp_path: Path, create_fake_model_files, test_state, monkeypatch ): - from services.generation_interrupt import GenerationCancelledError + from inference.interrupt import GenerationCancelledError import handlers.ic_lora_handler as handler_mod diff --git a/backend/tests/test_ic_lora_high_res_budget.py b/backend/tests/test_ic_lora_high_res_budget.py index 6d1011645..dd66bc8f2 100644 --- a/backend/tests/test_ic_lora_high_res_budget.py +++ b/backend/tests/test_ic_lora_high_res_budget.py @@ -7,7 +7,7 @@ from runtime_config.ic_lora_high_res import high_res_tiling 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 inference.ic_lora_tiling import IcLoraTiling from runtime_config.measured_cells import MEASURED_HIGH_RES_CELLS from tests.test_video_job_budget import _windows_measured_filter diff --git a/backend/tests/test_ic_lora_local_envelope.py b/backend/tests/test_ic_lora_local_envelope.py index 27627757c..3f8ec74bc 100644 --- a/backend/tests/test_ic_lora_local_envelope.py +++ b/backend/tests/test_ic_lora_local_envelope.py @@ -3,7 +3,7 @@ from __future__ import annotations from api_types import TargetResolution -from frame_math import compute_num_frames +from inference.frame_math import compute_num_frames from runtime_config.ic_lora_local_envelope import ( IC_LORA_SOURCE_TOO_LARGE, ic_lora_output_canvas, diff --git a/backend/tests/test_ic_lora_recipe_executor_frames.py b/backend/tests/test_ic_lora_recipe_executor_frames.py index 76a864eb2..1ed347f7d 100644 --- a/backend/tests/test_ic_lora_recipe_executor_frames.py +++ b/backend/tests/test_ic_lora_recipe_executor_frames.py @@ -23,7 +23,8 @@ 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 inference.errors import CapabilityFailedError +from services.records import AssetRecord, GenerationRecord from tests.lora_catalog_helpers import add_ic_lora from tests.video_fixtures import write_pattern_clip 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 e3aad304c..698fbfdd0 100644 --- a/backend/tests/test_ic_lora_recipe_run_frames_mac.py +++ b/backend/tests/test_ic_lora_recipe_run_frames_mac.py @@ -13,7 +13,7 @@ from _routes._errors import HTTPError from api_types import IcLoraRecipeStoredParams, IcLoraSettings, LoraEntry from runtime_config.budget_admission import RiskAllowance -from runtime_config.ic_lora_tiling import IcLoraTiling +from inference.ic_lora_tiling import IcLoraTiling from tests.lora_catalog_helpers import add_ic_lora from tests.test_ic_lora_recipe_run_frames import Gate, Runner, _configure_windows diff --git a/backend/tests/test_ic_lora_tile_size.py b/backend/tests/test_ic_lora_tile_size.py index cac5bfb6b..bec9cd41a 100644 --- a/backend/tests/test_ic_lora_tile_size.py +++ b/backend/tests/test_ic_lora_tile_size.py @@ -11,7 +11,7 @@ from api_types import IcLoraSettings, parse_lora_catalog from handlers.base import resolve_models_dir -from runtime_config.ic_lora_tiling import ( +from inference.ic_lora_tiling import ( TILE_SIZES, IcLoraTileSize, IcLoraTiling, diff --git a/backend/tests/test_iclora_preflight.py b/backend/tests/test_iclora_preflight.py index af33c775d..e62d7e1c5 100644 --- a/backend/tests/test_iclora_preflight.py +++ b/backend/tests/test_iclora_preflight.py @@ -17,7 +17,7 @@ InstructionSection, PreprocessingStep, ) -from frame_math import compute_num_frames +from inference.frame_math import compute_num_frames 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 ( diff --git a/backend/tests/test_image_edit.py b/backend/tests/test_image_edit.py index fddd41e16..08eaa6abc 100644 --- a/backend/tests/test_image_edit.py +++ b/backend/tests/test_image_edit.py @@ -5,7 +5,7 @@ import io from pathlib import Path -from services.generation_interrupt import GenerationCancelledError +from inference.interrupt import GenerationCancelledError from services.services_utils import compute_edit_dimensions from runtime_config.video_job_budget import ( LOCAL_GENERATION_UNSUPPORTED, diff --git a/backend/tests/test_image_prompt_plan.py b/backend/tests/test_image_prompt_plan.py index 3f846a5da..344916336 100644 --- a/backend/tests/test_image_prompt_plan.py +++ b/backend/tests/test_image_prompt_plan.py @@ -12,7 +12,7 @@ import pytest from handlers.image_prompt_plan import plan_fal_image_prompt -from services.generation_interrupt import GenerationCancelledError +from inference.interrupt import GenerationCancelledError def _cancelled() -> None: diff --git a/backend/tests/test_inference_import_fence.py b/backend/tests/test_inference_import_fence.py new file mode 100644 index 000000000..ebe8e294f --- /dev/null +++ b/backend/tests/test_inference_import_fence.py @@ -0,0 +1,47 @@ +"""The Pod image copies only inference/ and installs without the desktop extra. + +A sibling import breaks the copy. An import of fastapi, starlette, uvicorn, or +multipart breaks the install. +""" + +from __future__ import annotations + +import ast +from pathlib import Path + +_BACKEND_ROOT = Path(__file__).resolve().parents[1] +_INFERENCE_ROOT = _BACKEND_ROOT / "inference" +_SKIP_DIRS = frozenset({"inference", "__pycache__", ".venv", ".pytest_cache"}) +# Installed by `uv sync --extra desktop`. A Pod image omits that extra. +_DESKTOP_ONLY_ROOTS = frozenset({"fastapi", "starlette", "uvicorn", "multipart"}) + + +def _sibling_roots() -> frozenset[str]: + roots: set[str] = set() + for path in _BACKEND_ROOT.iterdir(): + if path.name in _SKIP_DIRS or path.name.startswith("."): + continue + if path.is_dir() or path.suffix == ".py": + roots.add(path.stem if path.suffix == ".py" else path.name) + return frozenset(roots) + + +def test_inference_import_of_sibling_backend_module_fails() -> None: + roots = _sibling_roots() | _DESKTOP_ONLY_ROOTS + assert "services" in roots + assert "fastapi" in roots + leaks: list[str] = [] + for path in _INFERENCE_ROOT.rglob("*.py"): + tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path)) + relative = path.relative_to(_INFERENCE_ROOT) + for node in ast.walk(tree): + names: list[str] = [] + if isinstance(node, ast.Import): + names = [alias.name for alias in node.names] + elif isinstance(node, ast.ImportFrom) and node.level == 0 and node.module is not None: + names = [node.module] + for name in names: + root = name.split(".", 1)[0] + if root in roots: + leaks.append(f"{relative}: {name}") + assert leaks == [] diff --git a/backend/tests/test_ingredients_recipe.py b/backend/tests/test_ingredients_recipe.py index c440e7ea5..87644370c 100644 --- a/backend/tests/test_ingredients_recipe.py +++ b/backend/tests/test_ingredients_recipe.py @@ -17,7 +17,7 @@ LoraEntry, parse_lora_catalog, ) -from frame_math import compute_num_frames +from inference.frame_math import compute_num_frames from handlers.base import resolve_models_dir from remote.dto import project_remote_spec from runtime_config.ltx_capabilities import budget_pixels, local_caps @@ -26,7 +26,7 @@ from services.features.video.ic_lora_sheet_recipe import IcLoraSheetRecipeExecutor from services.features.video.job_common import resolve_job_local_model_id from services.features.video.reference_sheet import build_reference_sheet, layout_panels -from services.generation_interrupt import GenerationCancelledError +from inference.interrupt import GenerationCancelledError from services.generation_queue.types import OutputAllocation, OutputPlan from tests.fakes.generation import FakeJobSession from services.records import AssetRecord, GenerationRecord diff --git a/backend/tests/test_job_sessions.py b/backend/tests/test_job_sessions.py index d1b7083e1..d2469f51c 100644 --- a/backend/tests/test_job_sessions.py +++ b/backend/tests/test_job_sessions.py @@ -9,7 +9,7 @@ import time from api_types import GenerationProgressResponse -from services import generation_interrupt +import inference.interrupt as generation_interrupt from services.generation_queue.lane_sessions import LaneJobSession from services.generation_queue.sessions import LocalJobSession from tests.fakes.generation import FakeJobSession diff --git a/backend/tests/test_keyframes_create.py b/backend/tests/test_keyframes_create.py index 001400bfe..6d6c99af6 100644 --- a/backend/tests/test_keyframes_create.py +++ b/backend/tests/test_keyframes_create.py @@ -1,4 +1,4 @@ -"""POST /api/generations/keyframes: the flag gate, what the row stores, and the refusals.""" +"""POST /api/generations/keyframes: what the row stores and the refusals.""" from __future__ import annotations @@ -12,7 +12,6 @@ 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"} @@ -45,31 +44,10 @@ def _body( } -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]] = [ @@ -88,6 +66,23 @@ def test_create_stores_asset_ids_and_never_a_file_path( assert len(_rows(test_state)) == 1 +def test_keyframes_job_shows_in_recent_features( + client, create_fake_model_files, tmp_path: Path +) -> None: + create_fake_model_files() + asset_id, _ = _asset(client, tmp_path, "a.png") + created = client.post( + "/api/generations/keyframes", + json=_body([{"assetId": asset_id, "frameIndex": 0, "strength": 1}]), + ) + assert created.status_code == 200, created.text + + recent = client.get("/api/generations/recent-features") + + assert recent.status_code == 200, recent.text + assert recent.json() == ["keyframes"] + + @pytest.mark.parametrize( ("case", "frames", "duration"), [ @@ -108,7 +103,6 @@ def test_create_refuses_bad_timelines_and_queues_nothing( 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 @@ -120,7 +114,7 @@ def test_create_refuses_bad_timelines_and_queues_nothing( assert _rows(test_state) == [] -def test_remote_create_is_blocked_by_the_flag_and_then_hides_paths( +def test_remote_create_hides_paths( test_state, create_fake_model_files, tmp_path: Path ) -> None: create_fake_model_files() @@ -136,11 +130,8 @@ def test_remote_create_is_blocked_by_the_flag_and_then_hides_paths( 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}] diff --git a/backend/tests/test_letterbox.py b/backend/tests/test_letterbox.py index 36aa5fab5..8e2288a15 100644 --- a/backend/tests/test_letterbox.py +++ b/backend/tests/test_letterbox.py @@ -5,7 +5,7 @@ import numpy as np from handlers.video_resolution import generation_letterbox -from services.retake_pipeline.letterbox import crop_letterbox, fit_and_pad +from inference.retake_pipeline.letterbox import crop_letterbox, fit_and_pad def test_pad_then_crop_restores_the_1080p_picture() -> None: diff --git a/backend/tests/test_ltx_image_inputs.py b/backend/tests/test_ltx_image_inputs.py index 2a6430015..134dea0a7 100644 --- a/backend/tests/test_ltx_image_inputs.py +++ b/backend/tests/test_ltx_image_inputs.py @@ -4,7 +4,7 @@ from api_types import ImageConditioningInput from ltx_pipelines.utils.types import ImageGuide, ImageReplace -from services.ltx_pipeline_common import to_ltx_images +from inference.common import to_ltx_images def test_first_frame_replaces_and_later_frames_guide() -> None: @@ -36,7 +36,7 @@ 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 + from inference.fast_video_pipeline.ltx_fast_video_pipeline import LTXFastVideoPipeline seen: list[object] = [] diff --git a/backend/tests/test_ltx_runtime_paths.py b/backend/tests/test_ltx_runtime_paths.py index eafaceae7..24e1d0415 100644 --- a/backend/tests/test_ltx_runtime_paths.py +++ b/backend/tests/test_ltx_runtime_paths.py @@ -6,9 +6,10 @@ import pytest +from inference.common import build_model_paths +from inference.layout import ResolvedLtxModelPaths from runtime_config.ltx_runtime_paths import resolve_ltx_runtime_paths from runtime_config.model_download_specs import get_ltx_model_spec, resolve_model_path -from services.ltx_pipeline_common import build_model_paths def _write_cp(models_dir: Path, cp_id: str) -> Path: @@ -69,7 +70,7 @@ def test_monolith_duration_head_is_the_fat_checkpoint() -> None: def test_resolve_runtime_paths_includes_downloaded_duration_head(tmp_path: Path) -> None: spec = get_ltx_model_spec("ltx-2.5-22b-distilled") _write_2_5_bundle(tmp_path) - paths = resolve_ltx_runtime_paths( + paths: ResolvedLtxModelPaths = resolve_ltx_runtime_paths( tmp_path, "ltx-2.5-22b-distilled", gemma_root=None, use_conv_vae=False ) assert paths.duration_head_path == str(resolve_model_path(tmp_path, spec.duration_head_cp)) @@ -78,7 +79,7 @@ def test_resolve_runtime_paths_includes_downloaded_duration_head(tmp_path: Path) def test_resolve_runtime_paths_omits_missing_duration_head(tmp_path: Path) -> None: spec = get_ltx_model_spec("ltx-2.5-22b-distilled") _write_2_5_bundle(tmp_path, include_duration_head=False) - paths = resolve_ltx_runtime_paths( + paths: ResolvedLtxModelPaths = resolve_ltx_runtime_paths( tmp_path, "ltx-2.5-22b-distilled", gemma_root=None, use_conv_vae=False ) assert paths.duration_head_path is None @@ -88,7 +89,7 @@ def test_resolve_runtime_paths_omits_missing_duration_head(tmp_path: Path) -> No def test_resolve_runtime_paths_picks_conv_vae(tmp_path: Path) -> None: spec = get_ltx_model_spec("ltx-2.5-22b-distilled") _write_2_5_bundle(tmp_path) - paths = resolve_ltx_runtime_paths( + paths: ResolvedLtxModelPaths = resolve_ltx_runtime_paths( tmp_path, "ltx-2.5-22b-distilled", gemma_root=None, use_conv_vae=True ) assert paths.video_vae_path == str(resolve_model_path(tmp_path, spec.video_vae_conv_cp)) @@ -97,7 +98,7 @@ def test_resolve_runtime_paths_picks_conv_vae(tmp_path: Path) -> None: def test_resolve_runtime_paths_picks_diffvae(tmp_path: Path) -> None: spec = get_ltx_model_spec("ltx-2.5-22b-distilled") _write_2_5_bundle(tmp_path) - paths = resolve_ltx_runtime_paths( + paths: ResolvedLtxModelPaths = resolve_ltx_runtime_paths( tmp_path, "ltx-2.5-22b-distilled", gemma_root=None, use_conv_vae=False ) assert paths.video_vae_path == str(resolve_model_path(tmp_path, spec.video_vae_cp)) @@ -108,7 +109,7 @@ def test_resolve_runtime_paths_2_3_ignores_conv_toggle(tmp_path: Path) -> None: for cp_id in (spec.model_cp, spec.upscale_cp): _write_cp(tmp_path, cp_id) for use_conv_vae in (True, False): - paths = resolve_ltx_runtime_paths( + paths: ResolvedLtxModelPaths = resolve_ltx_runtime_paths( tmp_path, "ltx-2.3-22b-distilled-1.1", gemma_root=None, use_conv_vae=use_conv_vae ) assert paths.video_vae_path is None diff --git a/backend/tests/test_mac_fast_chunked_budget.py b/backend/tests/test_mac_fast_chunked_budget.py index 694a1c785..471f10cd8 100644 --- a/backend/tests/test_mac_fast_chunked_budget.py +++ b/backend/tests/test_mac_fast_chunked_budget.py @@ -10,7 +10,7 @@ import pytest from runtime_config.budget_admission import Admitted, RiskAllowance -from runtime_config.fast_chunking import window_candidates +from inference.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, diff --git a/backend/tests/test_memory_meter_specs.py b/backend/tests/test_memory_meter_specs.py index 11749cd70..3abd1b3c7 100644 --- a/backend/tests/test_memory_meter_specs.py +++ b/backend/tests/test_memory_meter_specs.py @@ -5,7 +5,7 @@ from collections import Counter from api_model_specs import build_generate_video_model_specs_response -from frame_math import compute_num_frames +from inference.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 diff --git a/backend/tests/test_motion_track_executor.py b/backend/tests/test_motion_track_executor.py index 5360bfe70..c4040b5a4 100644 --- a/backend/tests/test_motion_track_executor.py +++ b/backend/tests/test_motion_track_executor.py @@ -18,7 +18,7 @@ LoraEntry, parse_lora_catalog, ) -from frame_math import compute_num_frames +from inference.frame_math import compute_num_frames from handlers.base import resolve_models_dir from runtime_config.ltx_capabilities import budget_pixels, local_caps from runtime_config.model_download_specs import resolve_ic_lora_path @@ -26,10 +26,11 @@ from services.features.video.ic_lora_track_recipe import IcLoraTrackRecipeExecutor from services.features.video.job_common import resolve_job_local_model_id from services.features.video.motion_path import positions, render_motion_track -from services.generation_interrupt import GenerationCancelledError +from inference.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 inference.errors import CapabilityFailedError +from services.records import AssetRecord, GenerationRecord from tests.lora_catalog_helpers import download_spec _WEIGHTS = "motion-track.safetensors" diff --git a/backend/tests/test_mps_tiling_weights_sync.py b/backend/tests/test_mps_tiling_weights_sync.py new file mode 100644 index 000000000..1394dd753 --- /dev/null +++ b/backend/tests/test_mps_tiling_weights_sync.py @@ -0,0 +1,57 @@ +"""Tile blend weights must not take upstream's non-blocking upload off CUDA (see ``mps_tiling_weights_sync``).""" + +from __future__ import annotations + +import pytest +import torch +from ltx_core import modality_tiling + +from services.patches import mps_tiling_weights_sync as patch + + +def _upstream_must_not_run(*_args: object) -> torch.Tensor: + raise AssertionError("a non-CUDA upload went through upstream's non-blocking copy") + + +def test_patch_is_installed_on_modality_tiling() -> None: + assert modality_tiling._device_weights is patch._device_weights_ordered # pyright: ignore[reportPrivateUsage] + + +def test_non_cuda_upload_skips_upstream_and_keeps_values_and_dtype(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(patch, "_orig_device_weights", _upstream_must_not_run) + cache: dict[tuple[torch.dtype, torch.device], torch.Tensor] = {} + like = torch.zeros(1, dtype=torch.bfloat16) + + result = patch._device_weights_ordered(cache, lambda: torch.tensor([0.0, 0.5, 1.0]), like) # pyright: ignore[reportPrivateUsage] + + assert result.dtype == torch.bfloat16 + assert result.tolist() == [0.0, 0.5, 1.0] + assert cache[(torch.bfloat16, like.device)] is result + + +def test_weights_are_built_once_per_plan(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(patch, "_orig_device_weights", _upstream_must_not_run) + built: list[int] = [] + + def build() -> torch.Tensor: + built.append(1) + return torch.ones(3) + + cache: dict[tuple[torch.dtype, torch.device], torch.Tensor] = {} + like = torch.zeros(1, dtype=torch.bfloat16) + first = patch._device_weights_ordered(cache, build, like) # pyright: ignore[reportPrivateUsage] + second = patch._device_weights_ordered(cache, build, like) # pyright: ignore[reportPrivateUsage] + + assert second is first + assert len(built) == 1 + + +def test_cuda_keeps_the_upstream_upload(monkeypatch: pytest.MonkeyPatch) -> None: + # No CUDA device here, so the backend rule is forced on for a CPU tensor. + sentinel = torch.full((1,), 7.0) + monkeypatch.setattr(patch, "allow_async_transfer", lambda _device: True) # pyright: ignore[reportUnknownArgumentType,reportUnknownLambdaType] + monkeypatch.setattr(patch, "_orig_device_weights", lambda _cache, _weights, _like: sentinel) + + result = patch._device_weights_ordered({}, lambda: torch.ones(1), torch.zeros(1)) # pyright: ignore[reportPrivateUsage] + + assert result is sentinel diff --git a/backend/tests/test_mps_transfer_sync.py b/backend/tests/test_mps_transfer_sync.py index 3c78441b9..77320c0b8 100644 --- a/backend/tests/test_mps_transfer_sync.py +++ b/backend/tests/test_mps_transfer_sync.py @@ -1,14 +1,23 @@ -"""MPS weight transfers must wait for queued compute first (see ``mps_transfer_sync``).""" +"""MPS weight transfers must wait for queued compute first, without holding the GIL. + +See ``mps_transfer_sync``. The two tests marked ``requires_mps`` need a real MPS device and are +skipped elsewhere. +""" from __future__ import annotations +import threading +import time from contextlib import contextmanager import pytest +import torch from ltx_core.loader import streaming_transport from services.patches import mps_transfer_sync as patch +requires_mps = pytest.mark.skipif(not torch.backends.mps.is_available(), reason="needs an MPS device") + def _record_calls(monkeypatch: pytest.MonkeyPatch) -> list[str]: calls: list[str] = [] @@ -22,22 +31,42 @@ def fake_transfer(_self, after): calls.append("exit") monkeypatch.setattr(patch, "_orig_transfer", fake_transfer) - monkeypatch.setattr(patch.torch.mps, "synchronize", lambda: calls.append("sync")) + monkeypatch.setattr(patch, "_wait_for_queued_compute", lambda: calls.append("wait")) return calls +def _queue_gpu_work(seconds: float) -> torch.Tensor: + """Queue about ``seconds`` of MPS work and return before it finishes.""" + a = torch.randn(4096, 4096, device="mps", dtype=torch.bfloat16) + + def queue(count: int) -> torch.Tensor: + x = a + for _ in range(count): + x = x @ a + x = x / (x.abs().max() + 1) + return x + + queue(5) + torch.mps.synchronize() + started = time.perf_counter() + queue(20) + torch.mps.synchronize() + per_matmul = (time.perf_counter() - started) / 20 + return queue(max(20, int(seconds / per_matmul))) + + 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: +def test_waits_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"] + assert calls == ["wait", "enter after=prev", "body", "exit"] def test_body_errors_propagate_and_upstream_exit_runs(monkeypatch: pytest.MonkeyPatch) -> None: @@ -45,4 +74,81 @@ def test_body_errors_propagate_and_upstream_exit_runs(monkeypatch: pytest.Monkey 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"] + assert calls == ["wait", "enter after=None", "exit"] + + +def test_wait_stops_polling_and_falls_back_to_the_blocking_sync(monkeypatch: pytest.MonkeyPatch) -> None: + queries = 0 + synchronized = 0 + + class NeverSignalledEvent: + def record(self) -> None: + pass + + def query(self) -> bool: + nonlocal queries + queries += 1 + return False + + def count_synchronize() -> None: + nonlocal synchronized + synchronized += 1 + + monkeypatch.setattr(torch.mps, "Event", NeverSignalledEvent) + monkeypatch.setattr(torch.mps, "synchronize", count_synchronize) + monkeypatch.setattr(patch, "_POLL_TIMEOUT_S", 0.05) + + started = time.perf_counter() + patch._wait_for_queued_compute() # pyright: ignore[reportPrivateUsage] + elapsed = time.perf_counter() - started + + assert queries > 1, "the poll never ran" + assert synchronized == 1, "the blocking sync must run once after the poll gives up" + assert elapsed < 1.0, f"the poll ignored its timeout: {elapsed:.3f}s" + + +@requires_mps +def test_wait_returns_only_after_queued_work_is_done() -> None: + work = _queue_gpu_work(1.0) + + started = time.perf_counter() + patch._wait_for_queued_compute() # pyright: ignore[reportPrivateUsage] + waited = time.perf_counter() - started + + started = time.perf_counter() + torch.mps.synchronize() + residual = time.perf_counter() - started + + del work + assert waited > 0.3, "the queued work finished before the wait started, so this test proves nothing" + assert residual < 0.05, f"queued work was still running after the wait: {residual:.3f}s" + + +@requires_mps +def test_wait_does_not_hold_the_gil() -> None: + ticks: list[float] = [] + stop = threading.Event() + + def ticker() -> None: + while not stop.is_set(): + ticks.append(time.perf_counter()) + time.sleep(0.005) + + thread = threading.Thread(target=ticker, daemon=True) + thread.start() + time.sleep(0.1) + work = _queue_gpu_work(1.5) + ticks.clear() + + started = time.perf_counter() + patch._wait_for_queued_compute() # pyright: ignore[reportPrivateUsage] + ended = time.perf_counter() + stop.set() + thread.join() + del work + + window = [t for t in ticks if started <= t <= ended] + gaps = [later - earlier for earlier, later in zip(window, window[1:])] + assert ended - started > 0.5, "the wait was too short to show a held GIL" + assert len(window) >= 20, f"the other thread ran only {len(window)} times during the wait" + assert max(gaps) < 0.25, f"another thread was blocked for {max(gaps):.3f}s during the wait" diff --git a/backend/tests/test_nag_cross_attention.py b/backend/tests/test_nag_cross_attention.py index 4287e0e51..e62c4f238 100644 --- a/backend/tests/test_nag_cross_attention.py +++ b/backend/tests/test_nag_cross_attention.py @@ -14,19 +14,19 @@ 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 ( +from inference.nag_limits import NEGATIVE_PROMPT_MAX_LENGTH +from inference.fast_video_pipeline.distilled_skip_stage_2 import DistilledPipelineWithSkipStage2 +from inference.fast_video_pipeline.nag_config import ( NagConfig, NagOffReason, decide_nag, nag_config_for_request, ) -from services.fast_video_pipeline.nag_distilled import NagDistilledMixin +from inference.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 ( +from inference.ic_lora_pipeline.tiled_ic_lora_pipeline import TiledICLoraPipeline +from inference.patches.nag_cross_attention import ( NagState, active_state, nag_scope, @@ -296,11 +296,11 @@ def test_scoped_chunks_activates_nag_only_inside_next_and_not_between_chunks() - 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", + "inference.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", + "inference.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), diff --git a/backend/tests/test_nag_strength_e2e.py b/backend/tests/test_nag_strength_e2e.py index a1c8e9900..ab2600a34 100644 --- a/backend/tests/test_nag_strength_e2e.py +++ b/backend/tests/test_nag_strength_e2e.py @@ -16,7 +16,7 @@ from starlette.testclient import TestClient from app_factory import create_app -from services.fast_video_pipeline.nag_config import NagConfig +from inference.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 diff --git a/backend/tests/test_natten_libnatten_gate.py b/backend/tests/test_natten_libnatten_gate.py index dbe4136fc..7ccb167f9 100644 --- a/backend/tests/test_natten_libnatten_gate.py +++ b/backend/tests/test_natten_libnatten_gate.py @@ -5,7 +5,7 @@ import sys from types import SimpleNamespace -from services.patches.natten_libnatten_gate import _gate_natten_available, _has_libnatten +from inference.patches.natten_libnatten_gate import _gate_natten_available, _has_libnatten def test_has_libnatten_is_false_when_import_fails(monkeypatch) -> None: diff --git a/backend/tests/test_offload_mode.py b/backend/tests/test_offload_mode.py index d487ec870..86023fb1d 100644 --- a/backend/tests/test_offload_mode.py +++ b/backend/tests/test_offload_mode.py @@ -5,7 +5,7 @@ import torch from ltx_pipelines.utils.types import OffloadMode -from services.ltx_pipeline_common import offload_mode_for_prefetch_count +from inference.common import offload_mode_for_prefetch_count _GIB = 1024**3 diff --git a/backend/tests/test_pass_shape.py b/backend/tests/test_pass_shape.py index 42d804216..bfbf9001b 100644 --- a/backend/tests/test_pass_shape.py +++ b/backend/tests/test_pass_shape.py @@ -13,9 +13,9 @@ from starlette.testclient import TestClient from app_factory import create_app -from frame_math import compute_num_frames +from inference.frame_math import compute_num_frames from remote.app import create_remote_app -from runtime_config.fast_chunking import job_window_count +from inference.fast_chunking import job_window_count from runtime_config.video_job_budget import ( MPS_SEQUENCE_OVER_MESSAGE, ONE_PASS_UNAVAILABLE, diff --git a/backend/tests/test_patch_import_smoke.py b/backend/tests/test_patch_import_smoke.py index 586205376..91144cd51 100644 --- a/backend/tests/test_patch_import_smoke.py +++ b/backend/tests/test_patch_import_smoke.py @@ -9,11 +9,16 @@ import importlib from pathlib import Path -PATCHES_DIR = Path(__file__).resolve().parents[1] / "services" / "patches" +_BACKEND_DIR = Path(__file__).resolve().parents[1] +_PATCH_PACKAGES = ( + (_BACKEND_DIR / "inference" / "patches", "inference.patches"), + (_BACKEND_DIR / "services" / "patches", "services.patches"), +) 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}") + for patches_dir, package in _PATCH_PACKAGES: + modules = sorted(p.stem for p in patches_dir.glob("*.py") if p.stem != "__init__") + assert modules, f"expected {package}/*.py modules" + for name in modules: + importlib.import_module(f"{package}.{name}") diff --git a/backend/tests/test_perf_runner_regression.py b/backend/tests/test_perf_runner_regression.py index 9a1b48d65..8e01204b2 100644 --- a/backend/tests/test_perf_runner_regression.py +++ b/backend/tests/test_perf_runner_regression.py @@ -131,7 +131,7 @@ def test_every_queued_create_route_has_a_scenario() -> None: def test_last_keyframe_index_is_the_final_frame_of_a_two_second_clip() -> None: import regression_scenarios as reg - from frame_math import compute_num_frames + from inference.frame_math import compute_num_frames assert reg.KEYFRAME_LAST == compute_num_frames(2, 24) - 1 diff --git a/backend/tests/test_pinned_pool_fix.py b/backend/tests/test_pinned_pool_fix.py index 29743da6f..723b9062a 100644 --- a/backend/tests/test_pinned_pool_fix.py +++ b/backend/tests/test_pinned_pool_fix.py @@ -6,7 +6,7 @@ import torch from ltx_core.loader import buffers, registry, state_loader, streaming_builder -import services.patches.pinned_pool_fix as patch +import inference.patches.pinned_pool_fix as patch _PINNED_REQUEST_BYTES = 4 << 20 diff --git a/backend/tests/test_prompt_enhancement.py b/backend/tests/test_prompt_enhancement.py index ef46ffa19..b65f7cafe 100644 --- a/backend/tests/test_prompt_enhancement.py +++ b/backend/tests/test_prompt_enhancement.py @@ -17,7 +17,7 @@ PromptTemplateSpec, ) from runtime_config.model_download_specs import resolve_model_path -from services import generation_interrupt +import inference.interrupt as 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 diff --git a/backend/tests/test_queue_dispatcher.py b/backend/tests/test_queue_dispatcher.py index 102e4f7ce..bc605a6a9 100644 --- a/backend/tests/test_queue_dispatcher.py +++ b/backend/tests/test_queue_dispatcher.py @@ -18,7 +18,7 @@ DISPLACED_PROVIDER_JOBS_FILENAME, DisplacedProviderJobs, ) -from services.generation_interrupt import GenerationCancelledError +from inference.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 diff --git a/backend/tests/test_remote_generations.py b/backend/tests/test_remote_generations.py index 4e9fe59f0..6b884cccc 100644 --- a/backend/tests/test_remote_generations.py +++ b/backend/tests/test_remote_generations.py @@ -35,6 +35,7 @@ "numFrames", "promptProvenance", "mode", + "contextMode", "startTime", "seed", "passShape", @@ -1047,6 +1048,7 @@ def test_remote_create_extend_keeps_video_asset_id_and_omits_paths( "model": "ltx-2.5-fast", "duration": 4, "mode": "start", + "contextMode": "short", }, "inputs": {"video": {"assetId": video.id}}, }, @@ -1069,6 +1071,7 @@ def test_remote_create_extend_keeps_video_asset_id_and_omits_paths( assert params["model"] == "ltx-2.5-fast" assert params["duration"] == 4 assert params["mode"] == "start" + assert params["contextMode"] == "short" assert video.path not in json.dumps(body) _assert_no_path_keys(body) _assert_no_secret_paths(body) @@ -1308,3 +1311,31 @@ def test_desktop_asset_and_generation_keep_filesystem_paths( assert Path(fetched_asset.json()["path"]).is_file() finally: test_state.generation.release_generation_start_reservation() + + +def test_remote_create_retake_keeps_the_context_mode( + test_state, create_fake_model_files, tmp_path: Path +) -> None: + create_fake_model_files() + store = _store(test_state) + video = store.ingest_upload(str(_mp4(tmp_path / "clip.mp4"))) + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as client: + created = client.post( + "/api/generations/retake", + headers=AUTH, + json={ + "params": { + "prompt": "the speaker says the new name", + "model": "ltx-2.5-fast", + "startTime": 0, + "duration": 2, + "contextMode": "short", + }, + "inputs": {"video": {"assetId": video.id}}, + }, + ) + assert created.status_code == 200, created.text + params = created.json()["spec"]["params"] + assert set(params) <= _APPROVED_PARAM_KEYS + assert params["contextMode"] == "short" diff --git a/backend/tests/test_retake_audio_spec.py b/backend/tests/test_retake_audio_spec.py index 1fe8d773b..96ab29376 100644 --- a/backend/tests/test_retake_audio_spec.py +++ b/backend/tests/test_retake_audio_spec.py @@ -10,7 +10,7 @@ from ltx_core.conditioning.types.noise_mask_cond import TemporalRegionMask from ltx_core.types import VIDEO_SCALE_FACTORS, AudioLatentShape, SpatioTemporalScaleFactors -from services.retake_pipeline.ltx_retake_pipeline import _audio_modality_spec +from inference.retake_pipeline.ltx_retake_pipeline import _audio_modality_spec _FPS = 24.0 # 4 latent frames at time-scale 8 is 25 pixel frames, about 1.04 s. diff --git a/backend/tests/test_retake_edit_window.py b/backend/tests/test_retake_edit_window.py index 18b2a8391..cf1cf003f 100644 --- a/backend/tests/test_retake_edit_window.py +++ b/backend/tests/test_retake_edit_window.py @@ -6,12 +6,14 @@ import pytest -from services.retake_pipeline.window import ( - MASK_DELTA_SECONDS, +from inference.retake_pipeline.window import ( + PreparedRetakeWindow, MAX_INPUT_FRAMES, RETAKE_BLEND_SECONDS, SELECTION_OUT_OF_RANGE_MESSAGE, - feathered_mask_times, + continuation_context_frames, + prepare_retake_window, + retake_mask_times, window_for_retake, ) @@ -135,7 +137,9 @@ def test_min_blend_does_not_push_the_window_over_the_cap() -> None: assert window.mask_end_frame - window.mask_start_frame == 496 -def test_feather_pulls_the_denoise_mask_into_kept_context() -> None: +def test_denoise_mask_is_exactly_the_selection() -> None: + """Mask == stitch edit span. A wider mask put the 16-frame lerp over + regenerated content, which ghosted at the seam.""" window = window_for_retake( source_frames=241, mask_start_frame=96, @@ -143,21 +147,86 @@ def test_feather_pulls_the_denoise_mask_into_kept_context() -> None: max_input_frames=MAX_INPUT_FRAMES, ) fps = 24.0 - start, end = feathered_mask_times(window, fps) - assert start == pytest.approx(96 / fps - MASK_DELTA_SECONDS) - assert end == pytest.approx(144 / fps + MASK_DELTA_SECONDS) - assert start >= 0 - assert end <= window.encode_duration(fps) + start, end = retake_mask_times(window, fps) + assert start == pytest.approx(window.window_mask_start(fps)) + assert end == pytest.approx(window.window_mask_end(fps)) + assert end - start == pytest.approx(48 / fps) -def test_feather_does_not_cross_a_missing_prefix() -> None: +def test_denoise_mask_at_clip_start_begins_at_zero() -> None: window = window_for_retake( source_frames=241, mask_start_frame=0, mask_end_frame=48, max_input_frames=MAX_INPUT_FRAMES, ) - start, end = feathered_mask_times(window, 24.0) + start, end = retake_mask_times(window, 24.0) assert start == 0.0 - assert end > 48 / 24.0 + assert end == pytest.approx(48 / 24.0) assert RETAKE_BLEND_SECONDS == 0.3 + + +@pytest.mark.parametrize("fps", [24.0, 30.0, 60.0]) +def test_short_context_keeps_about_two_seconds_on_each_side(fps: float) -> None: + mask = round(3 * fps) + cap_frames = continuation_context_frames(fps) + window = window_for_retake( + source_frames=int(60 * fps), + mask_start_frame=int(20 * fps), + mask_end_frame=int(20 * fps) + mask, + max_input_frames=MAX_INPUT_FRAMES, + fps=fps, + max_context_frames=cap_frames, + ) + # Alignment to 8k + 1 may add a few frames to one side. + assert cap_frames - 8 <= window.context_before_frames <= cap_frames + 8 + assert cap_frames - 8 <= window.context_after_frames <= cap_frames + 8 + assert (window.encode_frames - 1) % 8 == 0 + assert window.encode_frames < MAX_INPUT_FRAMES + + +def test_long_context_still_fills_the_window_to_the_cap() -> None: + kwargs = dict( + source_frames=1440, + mask_start_frame=480, + mask_end_frame=552, + max_input_frames=MAX_INPUT_FRAMES, + fps=24.0, + ) + long = window_for_retake(**kwargs) + short = window_for_retake(**kwargs, max_context_frames=continuation_context_frames(24.0)) + assert long.encode_frames >= MAX_INPUT_FRAMES - 8 + assert short.encode_frames < long.encode_frames // 2 + + +def test_short_context_is_clamped_by_the_source_edges() -> None: + window = window_for_retake( + source_frames=300, + mask_start_frame=10, + mask_end_frame=82, + max_input_frames=MAX_INPUT_FRAMES, + fps=24.0, + max_context_frames=continuation_context_frames(24.0), + ) + assert window.context_before_frames <= 10 + assert window.encode_start_frame >= 0 + + +def test_prepare_retake_window_short_mode_shrinks_the_window() -> None: + kwargs = dict( + fps=24.0, + target_frames=721, + target_width=1920, + target_height=1080, + frame_cap=MAX_INPUT_FRAMES, + start_time=12.0, + duration=3.0, + ) + long = prepare_retake_window(**kwargs) + short = prepare_retake_window(**kwargs, context_mode="short") + assert isinstance(long, PreparedRetakeWindow) and isinstance(short, PreparedRetakeWindow) + assert short.window.encode_frames < long.window.encode_frames + assert (short.window.mask_start_frame, short.window.mask_end_frame) == ( + long.window.mask_start_frame, + long.window.mask_end_frame, + ) diff --git a/backend/tests/test_retake_extend_generation.py b/backend/tests/test_retake_extend_generation.py index a15abb39e..731966267 100644 --- a/backend/tests/test_retake_extend_generation.py +++ b/backend/tests/test_retake_extend_generation.py @@ -8,6 +8,7 @@ import logging import uuid +from pathlib import Path from types import SimpleNamespace import pytest @@ -23,11 +24,11 @@ ) from services.features.video.extend import ExtendExecutor from services.features.video.retake import RetakeExecutor -from services.records import CapabilityFailedError +from inference.errors import CapabilityFailedError from state.app_settings import resolved_use_conv_vae from state.app_state_types import GpuSlot, RetakePipelineState from tests.http_error_assertions import assert_http_error -from tests.video_fixtures import write_mp4 +from tests.video_fixtures import write_clip_with_tone_spans, write_mp4 _LOCAL_2_3: LTXLocalModelId = "ltx-2.3-22b-distilled" _LOCAL_2_5: LTXLocalModelId = "ltx-2.5-22b-distilled" @@ -312,21 +313,29 @@ def test_retake_on_2_5_rebuilds_pipeline_after_2_3( assert len(fake_services.retake_pipeline.create_calls) == 2 -def _prepare_extend(test_state, video_path: str, duration: float): - """Drive ExtendExecutor.prepare directly: records are namespaces because - prepare reads generation.id and video.path only (verified by reading).""" - executor = ExtendExecutor( +def _extend_executor(test_state) -> ExtendExecutor: + """``prepare`` reads generation.id and video.path only, so the tests pass namespaces for them.""" + return ExtendExecutor( pipelines=test_state.pipelines, assets=None, # type: ignore[arg-type] - text=None, # type: ignore[arg-type] + text=test_state.text, models_dir=lambda: test_state.config.default_models_dir, default_negative_prompt="", - generation=None, # type: ignore[arg-type] - prompt_enhancement=None, # type: ignore[arg-type] + generation=test_state.generation, + prompt_enhancement=test_state.prompt_enhancement, ) - return executor.prepare( + + +def _prepare_extend(test_state, video_path: str, duration: float, context_mode: str = "long"): + return _extend_executor(test_state).prepare( SimpleNamespace(id="gen-1"), - ExtendParams(prompt="x", model="ltx-2.3-fast", duration=duration, mode="end"), + ExtendParams( + prompt="x", + model="ltx-2.3-fast", + duration=duration, + mode="end", + contextMode=context_mode, # type: ignore[arg-type] + ), SimpleNamespace(path=video_path), _LOCAL_2_3, 42, @@ -401,3 +410,84 @@ def test_queued_home_edit_loads_the_text_encoder_of_its_own_model( ) assert fake_services.retake_pipeline.create_calls[-1]["gemma_root"] == expected_gemma_root + + +def _speech_clip(test_state) -> str: + """6 s, 24 fps, with a voice from 0.2 s to 2.5 s and silence after it.""" + return str( + write_clip_with_tone_spans( + test_state.config.outputs_dir / f"speech_{uuid.uuid4().hex[:6]}.mp4", + frames=144, + spans=[(0.2, 2.5)], + ) + ) + + +def _bridge_files(test_state) -> list: + return list(test_state.config.outputs_dir.glob("*.voice.mp4")) + + +def test_full_context_extend_makes_no_voice_bridge( + test_state, create_fake_model_files, fake_services +) -> None: + # Bug: the bridge replaces the real clip in the default mode and changes a path that worked. + _install_local(test_state, create_fake_model_files, _LOCAL_2_3) + prepared = _prepare_extend(test_state, _speech_clip(test_state), duration=2.0, context_mode="long") + assert prepared.bridge is None + assert _bridge_files(test_state) == [] + + +def test_short_context_extend_plans_a_voice_bridge_when_the_window_has_no_speech( + test_state, create_fake_model_files, fake_services +) -> None: + _install_local(test_state, create_fake_model_files, _LOCAL_2_3) + prepared = _prepare_extend(test_state, _speech_clip(test_state), duration=2.0, context_mode="short") + assert prepared.bridge is not None + assert prepared.bridge.total_frames == prepared.window.context_frames + # Bug: a job refused or cancelled before generate left its bridge clip behind. Prepare + # writes no file, so there is nothing to leave. + assert _bridge_files(test_state) == [] + + +def test_short_context_extend_without_earlier_speech_uses_the_source_clip( + test_state, create_fake_model_files, fake_services +) -> None: + _install_local(test_state, create_fake_model_files, _LOCAL_2_3) + prepared = _prepare_extend( + test_state, _make_valid_video(test_state, frames=144), duration=2.0, context_mode="short" + ) + assert prepared.bridge is None + assert _bridge_files(test_state) == [] + + +def test_extend_falls_back_to_the_source_clip_when_the_bridge_cannot_be_written( + test_state, create_fake_model_files, fake_services +) -> None: + # Bug: the bridge is only an aid, so a clip that cannot be written must not fail the job, and + # the stitch must not assume a bridge the model never read. + _install_local(test_state, create_fake_model_files, _LOCAL_2_3) + source = _speech_clip(test_state) + prepared = _prepare_extend(test_state, source, duration=2.0, context_mode="short") + assert prepared.bridge is not None + Path(source).unlink() + _extend_executor(test_state).generate(prepared) + assert fake_services.retake_pipeline.extend_calls[-1]["video_path"] == source + assert prepared.bridge is None + assert _bridge_files(test_state) == [] + + +@pytest.mark.parametrize("fails", [False, True]) +def test_extend_removes_the_voice_bridge_file_after_the_run( + test_state, create_fake_model_files, fake_services, fails: bool +) -> None: + # Bug: every Short context extend leaves a bridge clip in the outputs folder. + _install_local(test_state, create_fake_model_files, _LOCAL_2_3) + prepared = _prepare_extend(test_state, _speech_clip(test_state), duration=2.0, context_mode="short") + if fails: + fake_services.retake_pipeline.raise_on_extend = RuntimeError("boom") + with pytest.raises(RuntimeError, match="boom"): + _extend_executor(test_state).generate(prepared) + else: + _extend_executor(test_state).generate(prepared) + assert str(fake_services.retake_pipeline.extend_calls[-1]["video_path"]).endswith(".voice.mp4") + assert _bridge_files(test_state) == [] diff --git a/backend/tests/test_retake_frame_rate.py b/backend/tests/test_retake_frame_rate.py index a72a664a7..2d9df7371 100644 --- a/backend/tests/test_retake_frame_rate.py +++ b/backend/tests/test_retake_frame_rate.py @@ -9,7 +9,7 @@ import imageio_ffmpeg import pytest -from services.retake_pipeline.frame_rate import restamp_to_source_rate +from inference.retake_pipeline.frame_rate import restamp_to_source_rate NTSC_FILM = 24000 / 1001 FRAMES = 46 diff --git a/backend/tests/test_retake_sampler_selection.py b/backend/tests/test_retake_sampler_selection.py index 5bd432246..9715783ab 100644 --- a/backend/tests/test_retake_sampler_selection.py +++ b/backend/tests/test_retake_sampler_selection.py @@ -25,9 +25,9 @@ from ltx_pipelines.utils.samplers import euler_ancestral_denoising_loop from safetensors.torch import save_file -from services.denoising_progress import distilled_total_steps -from services.retake_pipeline.ltx_retake_pipeline import LTXRetakePipeline -from services.retake_pipeline.retake_sampler import resolve_sampler_plan +from inference.progress import distilled_total_steps +from inference.retake_pipeline.ltx_retake_pipeline import LTXRetakePipeline +from inference.retake_pipeline.retake_sampler import resolve_sampler_plan def _checkpoint_with_version(tmp_path: Path, version: str) -> str: diff --git a/backend/tests/test_retake_stitch.py b/backend/tests/test_retake_stitch.py index 8050bbe15..a292b8190 100644 --- a/backend/tests/test_retake_stitch.py +++ b/backend/tests/test_retake_stitch.py @@ -10,22 +10,22 @@ import numpy as np import pytest -from services.retake_pipeline.retake_stitch import ( +from inference.retake_pipeline.retake_stitch import ( fade_window_for_retake, reencode_span, retake_audio_graph, stitch_retake_output, ) -from services.ffmpeg import ( +from inference.ffmpeg import ( FFMPEG_TIMEOUT_SECONDS, STITCH_TIMEOUT_CAP_SECONDS, timeout_for_source_duration, ) -from services.retake_pipeline.rgb_stitch import iter_span, write_rgb_video -from services.retake_pipeline.window import ( +from inference.retake_pipeline.rgb_stitch import iter_span, write_rgb_video +from inference.retake_pipeline.window import ( MAX_FADE_FRAMES, denoised_frame_span, - feathered_mask_times, + retake_mask_times, window_for_retake, ) @@ -63,7 +63,7 @@ def test_fade_sits_on_the_user_mask_for_at_most_16_frames() -> None: def test_denoised_span_snaps_out_to_whole_latents() -> None: window = _ted_retake_window() start, end = denoised_frame_span(window, NTSC_FILM) - region_start, region_end = feathered_mask_times(window, NTSC_FILM) + region_start, region_end = retake_mask_times(window, NTSC_FILM) assert start / NTSC_FILM <= region_start and end / NTSC_FILM >= region_end assert (start - 1) % 8 == 0 and (end - 1) % 8 == 0 @@ -256,9 +256,9 @@ def _capture(dest: Path, frames: object, **_kwargs: object) -> None: seen.append(sum(1 for _ in frames)) # type: ignore[arg-type] Path(dest).write_bytes(b"middle") - monkeypatch.setattr("services.retake_pipeline.retake_stitch.write_rgb_video", _capture) - monkeypatch.setattr("services.retake_pipeline.retake_stitch.run_ffmpeg", lambda *_a, **_k: None) - monkeypatch.setattr("services.retake_pipeline.retake_stitch._has_audio", lambda _path: False) + monkeypatch.setattr("inference.retake_pipeline.retake_stitch.write_rgb_video", _capture) + monkeypatch.setattr("inference.retake_pipeline.retake_stitch.run_ffmpeg", lambda *_a, **_k: None) + monkeypatch.setattr("inference.retake_pipeline.retake_stitch._has_audio", lambda _path: False) stitch_retake_output( source_path=str(tmp_path / "source.mp4"), windowed_path=str(tmp_path / "generated.mp4"), @@ -302,13 +302,13 @@ def test_silent_source_keeps_generated_audio(monkeypatch, tmp_path: Path) -> Non def _capture(args: list[str], **_kwargs: object) -> None: captured.append(args) - monkeypatch.setattr("services.retake_pipeline.retake_stitch.run_ffmpeg", _capture) + monkeypatch.setattr("inference.retake_pipeline.retake_stitch.run_ffmpeg", _capture) monkeypatch.setattr( - "services.retake_pipeline.retake_stitch.write_rgb_video", + "inference.retake_pipeline.retake_stitch.write_rgb_video", lambda *_args, **_kwargs: None, ) monkeypatch.setattr( - "services.retake_pipeline.retake_stitch._has_audio", + "inference.retake_pipeline.retake_stitch._has_audio", lambda path: path == "/window.mp4", ) window = window_for_retake( @@ -428,3 +428,57 @@ def frames(): assert closed == [True] else: pytest.fail("an odd width should not encode") + + +def test_audio_graph_levels_only_the_new_part() -> None: + window = _ted_retake_window() + graph = retake_audio_graph(window, NTSC_FILM, source_label="[1:a]", generated_gain_db=-6.0) + assert graph.count("volume=-6.00dB") == 1 + plain = retake_audio_graph(window, NTSC_FILM, source_label="[1:a]") + assert "volume=" not in plain + + +def _output_speech_db(path: Path, start: float, end: float, seconds: float) -> float: + from inference.retake_pipeline.audio_level import speech_level_db + from inference.retake_pipeline.speech_analysis import decode_mono + + level = speech_level_db(decode_mono(str(path), seconds, start=start, end=end)) + assert level is not None + return level + + +@pytest.mark.parametrize(("regenerate_audio", "expected_gap_db"), [(True, 0.0), (False, 12.0)]) +def test_stitched_retake_speech_is_leveled_to_the_speech_around_it( + tmp_path: Path, regenerate_audio: bool, expected_gap_db: float +) -> None: + # Bug: the new speech of a retake came out louder than the original speech around it. + from tests.video_fixtures import write_clip_with_tone_spans + + fps = 24 + window = window_for_retake( + source_frames=192, mask_start_frame=48, mask_end_frame=96, max_input_frames=505, fps=float(fps) + ) + source = write_clip_with_tone_spans( + tmp_path / "source.mp4", frames=192, spans=[(0.0, 2.0), (4.0, 8.0)], amplitude=0.1 + ) + new_start = window.context_before_frames / fps + generated = write_clip_with_tone_spans( + tmp_path / "generated.mp4", + frames=window.encode_frames, + spans=[(new_start, new_start + 2.0)], + amplitude=0.4, + ) + dest = tmp_path / "out.mp4" + stitch_retake_output( + source_path=str(source), + windowed_path=str(generated), + dest_path=str(dest), + window=window, + fps=float(fps), + target_width=64, + target_height=64, + regenerate_audio=regenerate_audio, + ) + around = _output_speech_db(dest, 0.2, 1.8, 8.0) + new_part = _output_speech_db(dest, 2.3, 3.7, 8.0) + assert new_part - around == pytest.approx(expected_gap_db, abs=1.5) diff --git a/backend/tests/test_retake_stitch_e2e.py b/backend/tests/test_retake_stitch_e2e.py index a7226cd14..52591bc2a 100644 --- a/backend/tests/test_retake_stitch_e2e.py +++ b/backend/tests/test_retake_stitch_e2e.py @@ -9,9 +9,9 @@ import imageio_ffmpeg import numpy as np -from services.retake_pipeline.frame_rate import restamp_to_source_rate -from services.retake_pipeline.retake_stitch import stitch_retake_output -from services.retake_pipeline.window import window_for_retake +from inference.retake_pipeline.frame_rate import restamp_to_source_rate +from inference.retake_pipeline.retake_stitch import stitch_retake_output +from inference.retake_pipeline.window import window_for_retake NTSC_FILM = 24000 / 1001 SOURCE_FRAMES = 300 diff --git a/backend/tests/test_source_encode.py b/backend/tests/test_source_encode.py index 921be1b56..c75d1f433 100644 --- a/backend/tests/test_source_encode.py +++ b/backend/tests/test_source_encode.py @@ -12,7 +12,7 @@ import torch from ltx_core.types import VIDEO_SCALE_FACTORS, VideoPixelShape -from services.retake_pipeline.source_encode import ( +from inference.retake_pipeline.source_encode import ( _freeze_pad_pixels, _match_latent_length, encode_source_video_latent, @@ -67,7 +67,7 @@ def test_encode_source_video_latent_keeps_pixels_on_cpu(monkeypatch) -> None: encoder = _FakeEncoder() frames = [torch.zeros(1, 64, 64, 3, dtype=torch.uint8) for _ in range(9)] monkeypatch.setattr( - "services.retake_pipeline.source_encode.decode_video_from_file", + "inference.retake_pipeline.source_encode.decode_video_from_file", lambda **_kwargs: iter(frames), ) shape = VideoPixelShape(batch=1, frames=9, height=64, width=64, fps=24.0) @@ -85,7 +85,7 @@ def test_encode_source_video_latent_keeps_pixels_on_cpu(monkeypatch) -> None: def test_extend_and_generate_both_encode_source_from_cpu() -> None: """Home/GenSpace extend shares ``_run`` with retake; that is the CUDA hang path.""" - from services.retake_pipeline.ltx_retake_pipeline import LTXRetakePipeline + from inference.retake_pipeline.ltx_retake_pipeline import LTXRetakePipeline run_src = inspect.getsource(LTXRetakePipeline._run) assert "encode_source_video_latent(" in run_src @@ -130,7 +130,7 @@ def test_encode_source_video_latent_freeze_pads_pixels_before_vae(monkeypatch) - torch.full((1, 64, 64, 3), fill_value=i, dtype=torch.uint8) for i in range(9) ] monkeypatch.setattr( - "services.retake_pipeline.source_encode.decode_video_from_file", + "inference.retake_pipeline.source_encode.decode_video_from_file", lambda **_kwargs: iter(frames), ) shape = VideoPixelShape(batch=1, frames=17, height=64, width=64, fps=24.0) @@ -156,7 +156,7 @@ def test_encode_without_freeze_pad_repeats_the_latent_edge(monkeypatch) -> None: torch.full((1, 64, 64, 3), fill_value=i, dtype=torch.uint8) for i in range(9) ] monkeypatch.setattr( - "services.retake_pipeline.source_encode.decode_video_from_file", + "inference.retake_pipeline.source_encode.decode_video_from_file", lambda **_kwargs: iter(frames), ) shape = VideoPixelShape(batch=1, frames=17, height=64, width=64, fps=24.0) diff --git a/backend/tests/test_state_actions.py b/backend/tests/test_state_actions.py index 2ebde7e7f..53a80793e 100644 --- a/backend/tests/test_state_actions.py +++ b/backend/tests/test_state_actions.py @@ -17,9 +17,9 @@ decide_edit_job, ) from runtime_config.budget_decision import VideoJobLoad -from frame_math import compute_num_frames +from inference.frame_math import compute_num_frames from handlers.generation_handler import GenerationSlotWaitAborted, _RESERVATION_TIMEOUT_S -from services import generation_interrupt +import inference.interrupt as generation_interrupt from runtime_config.model_download_specs import ( DEPTH_PROCESSOR_CP_ID, get_ltx_model_spec, @@ -184,7 +184,7 @@ def test_raise_if_cancelled_ignores_sticky_cancelled_from_previous_job( def test_start_generation_honors_cancel_during_reservation(test_state, create_fake_model_files): - from services.generation_interrupt import GenerationCancelledError + from inference.interrupt import GenerationCancelledError create_fake_model_files() test_state.pipelines.load_gpu_pipeline("fast") diff --git a/backend/tests/test_stitch_silence.py b/backend/tests/test_stitch_silence.py index c08d5b71b..1e33b80c0 100644 --- a/backend/tests/test_stitch_silence.py +++ b/backend/tests/test_stitch_silence.py @@ -10,7 +10,7 @@ from services.ffmpeg import run_ffmpeg from services.records import MediaError -from services.retake_pipeline.stitch_silence import append_silence_input +from inference.retake_pipeline.stitch_silence import append_silence_input def _silent_video(path: Path, *, frames: int, fps: int) -> str: diff --git a/backend/tests/test_tiled_ic_lora_pipeline.py b/backend/tests/test_tiled_ic_lora_pipeline.py index 2a18c79ff..91e8d0b43 100644 --- a/backend/tests/test_tiled_ic_lora_pipeline.py +++ b/backend/tests/test_tiled_ic_lora_pipeline.py @@ -12,8 +12,8 @@ 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 ( +from inference.ic_lora_pipeline.ic_lora_inference import InferenceResult, encode_result +from inference.ic_lora_pipeline.tiled_ic_lora_pipeline import ( TiledICLoraPipeline, encode_tiling_for_canvas, reference_encode_canvas, @@ -168,7 +168,7 @@ 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.image_conditionings", fake_stills + "inference.ic_lora_pipeline.tiled_ic_lora_pipeline.image_conditionings", fake_stills ) first_frame = _loaded("first.png", 0) still = _loaded("look.png", -1) diff --git a/backend/tests/test_video_aware_prompt_enhancement.py b/backend/tests/test_video_aware_prompt_enhancement.py index 449938266..a67c6215c 100644 --- a/backend/tests/test_video_aware_prompt_enhancement.py +++ b/backend/tests/test_video_aware_prompt_enhancement.py @@ -22,7 +22,7 @@ ReplacedWindow, parse_lora_catalog, ) -from services.generation_interrupt import GenerationCancelledError +from inference.interrupt import GenerationCancelledError from runtime_config.model_download_specs import resolve_ic_lora_path from services.prompt_enhancement import ( build_video_user_prompt_text, diff --git a/backend/tests/test_video_job_budget.py b/backend/tests/test_video_job_budget.py index 04421171a..3c25e2cbe 100644 --- a/backend/tests/test_video_job_budget.py +++ b/backend/tests/test_video_job_budget.py @@ -16,7 +16,7 @@ InstructionSection, PreprocessingStep, ) -from frame_math import compute_num_frames +from inference.frame_math import compute_num_frames import pytest from pytest import approx from runtime_config.ic_lora_chunking import IC_LORA_CHUNK_PIXEL_FRAMES @@ -54,7 +54,7 @@ from runtime_config.ltx_capabilities import local_caps, pixels_for from runtime_config.model_download_specs import get_ltx_model_spec from runtime_config.ic_lora_stage_mode import IcLoraStageMode -from runtime_config.ic_lora_tiling import IcLoraTiling +from inference.ic_lora_tiling import IcLoraTiling from runtime_config.video_job_budget import ( LOCAL_GENERATION_RAM_SHORTFALL, LOCAL_GENERATION_RAM_SHORTFALL_MESSAGE, @@ -82,7 +82,7 @@ reject_message_and_code, video_tokens, ) -from services.retake_pipeline.window import ( +from inference.retake_pipeline.window import ( duration_to_extend_frames, window_for_extend, window_for_retake, diff --git a/backend/tests/test_video_trim.py b/backend/tests/test_video_trim.py index 36d28af7e..cf97eacd4 100644 --- a/backend/tests/test_video_trim.py +++ b/backend/tests/test_video_trim.py @@ -12,7 +12,7 @@ from remote.app import create_remote_app from services import video_trim from services.encoded_media import derived_file_name -from services.ffmpeg import FFMPEG_TIMEOUT_SECONDS +from inference.ffmpeg import FFMPEG_TIMEOUT_SECONDS from services.media_probe import MAX_VIDEO_BYTES from services.video_trim import trim_video_file from tests.http_error_assertions import assert_http_error diff --git a/backend/tests/test_voice_context.py b/backend/tests/test_voice_context.py new file mode 100644 index 000000000..9a7e60f1e --- /dev/null +++ b/backend/tests/test_voice_context.py @@ -0,0 +1,237 @@ +"""Voice bridge for Short context Extend: pick the speech, build the clip, fail soft. + +The planner is pure. ``find_voice_bridge`` and ``write_voice_bridge`` run real ffmpeg on small +clips whose "speech" is a tone, so no GPU or model is needed. +""" + +from __future__ import annotations + +from pathlib import Path + +import av +import numpy as np +import pytest + +from inference.ffmpeg import run_ffmpeg +from inference.retake_pipeline.speech_analysis import ANALYSIS_SAMPLE_RATE, Span, decode_mono, speech_spans +from inference.retake_pipeline.voice_context import ( + VoiceBridge, + _write_bridge_clip, + find_voice_bridge, + plan_voice_bridge, + write_voice_bridge, +) +from inference.retake_pipeline.window import ( + CONTINUATION_CONTEXT_FRAMES, + MAX_INPUT_FRAMES, + ExtendEncodeWindow, + continuation_context_frames, + window_for_extend, +) +from tests.video_fixtures import write_clip_with_tone_spans, write_mp4 + +FPS = 24.0 +SOURCE_FRAMES = 144 # 6 s + + +def _window(mode: str) -> ExtendEncodeWindow: + return window_for_extend( + source_frames=SOURCE_FRAMES, + extend_frames=48, + mode=mode, # type: ignore[arg-type] + max_input_frames=MAX_INPUT_FRAMES, + max_context_frames=CONTINUATION_CONTEXT_FRAMES, + ) + + +def _plan(spans: list[Span], mode: str = "end") -> VoiceBridge | None: + return plan_voice_bridge( + spans, window=_window(mode), fps=FPS, source_frames=SOURCE_FRAMES, mode=mode # type: ignore[arg-type] + ) + + +def test_end_bridge_fills_the_window_and_the_seam_piece_ends_at_the_source_end() -> None: + # Bug: a bridge longer or shorter than the window shifts every latent the model reads. + window = _window("end") + bridge = _plan([Span(0.2, 2.5)]) + assert bridge is not None + assert bridge.total_frames == window.context_frames + assert bridge.seam_start_frame + bridge.seam_frames == SOURCE_FRAMES + assert bridge.speech_start_frame + bridge.speech_frames == round(2.5 * FPS) + + +def test_start_bridge_puts_the_seam_piece_first_and_takes_the_next_speech() -> None: + window = _window("start") + bridge = _plan([Span(3.0, 5.0)], mode="start") + assert bridge is not None + assert bridge.total_frames == window.context_frames + assert bridge.seam_start_frame == window.encode_start_frame + assert bridge.speech_start_frame == round(3.0 * FPS) + + +def test_no_bridge_when_the_far_part_of_the_window_already_has_a_voice() -> None: + # Bug: the bridge replaces a window that already holds the voice, and the real picture is lost. + window_start = _window("end").start_time(FPS) + in_window = Span(window_start + 0.05, window_start + 0.65) + assert _plan([Span(0.2, 2.5), in_window]) is None + + +def test_no_bridge_without_a_usable_earlier_speech() -> None: + # Bug: negative start frame, or a click is taken as the voice sample. + assert _plan([]) is None + assert _plan([Span(1.0, 1.3)]) is None + + +def test_speech_piece_start_is_clamped_to_the_first_frame() -> None: + bridge = _plan([Span(0.0, 0.5)]) + assert bridge is not None + assert bridge.speech_start_frame == 0 + + +def test_a_short_pause_stays_inside_one_span() -> None: + # Bug: a breath between words counts as a gap and wrongly triggers a bridge. + rate = ANALYSIS_SAMPLE_RATE + tone = np.sin(np.linspace(0, 2000 * np.pi, rate * 3, dtype=np.float32)) * 0.5 + short_pause, long_pause = tone.copy(), tone.copy() + short_pause[rate : rate + int(rate * 0.15)] = 0 + long_pause[rate : rate + int(rate * 0.4)] = 0 + assert len(speech_spans(short_pause, rate)) == 1 + assert len(speech_spans(long_pause, rate)) == 2 + + +def _frames(path: str) -> list[np.ndarray]: + with av.open(path) as container: + return [f.to_ndarray(format="rgb24").astype(np.float32) for f in container.decode(video=0)] + + +def _nearest_source_frame(frame: np.ndarray, source: list[np.ndarray]) -> int: + return int(np.argmin([np.abs(frame - other).mean() for other in source])) + + +def test_bridge_clip_plays_the_speech_piece_then_the_seam_piece(tmp_path: Path) -> None: + # Bug: the concat order is swapped, or the sound and the picture come from different pieces. + source = write_clip_with_tone_spans(tmp_path / "source.mp4", frames=SOURCE_FRAMES, spans=[(0.2, 2.5)]) + dest = tmp_path / "bridge.mp4" + window = _window("end") + bridge = find_voice_bridge(str(source), window=window, fps=FPS, source_frames=SOURCE_FRAMES, mode="end") + assert bridge is not None + assert write_voice_bridge(str(source), str(dest), bridge, FPS) + frames = _frames(str(dest)) + source_frames = _frames(str(source)) + assert len(frames) == window.context_frames + assert abs(_nearest_source_frame(frames[0], source_frames) - bridge.speech_start_frame) <= 1 + assert abs(_nearest_source_frame(frames[bridge.speech_frames], source_frames) - bridge.seam_start_frame) <= 1 + audio = decode_mono(str(dest), window.context_frames / FPS) + split = int(bridge.speech_frames / FPS * ANALYSIS_SAMPLE_RATE) + assert np.abs(audio[: split - 800]).max() > 0.05 + assert np.abs(audio[split + 800 :]).max() < 0.01 + + +def test_no_bridge_for_a_source_without_audio_or_one_that_cannot_be_read(tmp_path: Path) -> None: + # Bug: the extend job fails because the bridge is only an aid. + silent_source = write_mp4(tmp_path / "silent.mp4", seconds=6, fps=24) + broken_source = tmp_path / "broken.mp4" + broken_source.write_bytes(b"not a video") + for source in (silent_source, broken_source): + assert ( + find_voice_bridge(str(source), window=_window("end"), fps=FPS, source_frames=SOURCE_FRAMES, mode="end") + is None + ) + + +def test_a_bridge_clip_that_cannot_be_written_leaves_no_file(tmp_path: Path) -> None: + # Bug: a half-written file stays in the outputs folder, or the extend job fails. + broken_source = tmp_path / "broken.mp4" + broken_source.write_bytes(b"not a video") + dest = tmp_path / "bridge.mp4" + bridge = VoiceBridge(speech_start_frame=0, speech_frames=24, seam_start_frame=48, seam_frames=24, mode="end") + assert write_voice_bridge(str(broken_source), str(dest), bridge, FPS) is False + assert not dest.exists() + + +def test_end_bridge_uses_speech_that_runs_into_the_window() -> None: + # Bug: a speaker who talks on into the window was dropped, because the span did not end + # before the window, so there was no speech to build the bridge from. + window = _window("end") + window_start = window.start_time(FPS) + bridge = _plan([Span(0.5, window_start + 0.2)]) + assert bridge is not None + # The piece ends where the window starts, not inside it. + assert bridge.speech_start_frame + bridge.speech_frames == round(window_start * FPS) + + +def test_start_bridge_uses_speech_that_runs_out_of_the_window() -> None: + window = _window("start") + window_end = window.context_frames / FPS + bridge = _plan([Span(window_end - 0.2, window_end + 3.0)], mode="start") + assert bridge is not None + assert bridge.speech_start_frame == window.context_frames + + +def test_decode_mono_keeps_a_late_audio_track_on_the_clip_timeline(tmp_path: Path) -> None: + # Bug: a track that starts 0.5 s late was read from time 0, so every speech span came out + # 0.5 s early and the bridge cut the wrong frames (phone and screen recordings do this). + clip = tmp_path / "late.mp4" + run_ffmpeg( + [ + "-y", "-f", "lavfi", "-i", "testsrc=size=64x64:rate=24", + "-itsoffset", "0.5", "-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000", + "-t", "3", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-c:a", "aac", str(clip), + ] + ) + samples = decode_mono(str(clip), 3.0) + first_loud = int(np.argmax(np.abs(samples) > 0.05)) / ANALYSIS_SAMPLE_RATE + assert abs(first_loud - 0.5) < 0.05 + + +def _late_track_clip(path: Path) -> Path: + run_ffmpeg( + [ + "-y", "-f", "lavfi", "-i", "testsrc=size=64x64:rate=24", + "-itsoffset", "0.5", "-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000", + "-t", "3", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-c:a", "aac", str(path), + ] + ) + return path + + +def test_decode_mono_reads_only_the_asked_stretch_on_the_clip_timeline(tmp_path: Path) -> None: + # Bug: the level match decoded the whole track to measure ten seconds of it. + clip = _late_track_clip(tmp_path / "late.mp4") + first_second = decode_mono(str(clip), 3.0, end=1.0) + assert abs(len(first_second) / ANALYSIS_SAMPLE_RATE - 1.0) < 0.05 + assert abs(int(np.argmax(np.abs(first_second) > 0.05)) / ANALYSIS_SAMPLE_RATE - 0.5) < 0.05 + last_second = decode_mono(str(clip), 3.0, start=2.0) + assert abs(len(last_second) / ANALYSIS_SAMPLE_RATE - 1.0) < 0.1 + assert np.abs(last_second[: ANALYSIS_SAMPLE_RATE // 2]).max() > 0.05 + + +def test_bridge_clip_keeps_a_late_audio_track_under_its_own_frames(tmp_path: Path) -> None: + # Bug: a seam piece starting at frame 0 of a clip whose audio starts 0.5 s late had its + # trim drop the missing lead-in, so the voice played before the lips moved. + clip = _late_track_clip(tmp_path / "late.mp4") + dest = tmp_path / "bridge.mp4" + bridge = VoiceBridge(speech_start_frame=48, speech_frames=24, seam_start_frame=0, seam_frames=24, mode="start") + _write_bridge_clip(str(clip), str(dest), bridge, FPS) + audio = decode_mono(str(dest), 2.0) + assert np.abs(audio[: int(0.4 * ANALYSIS_SAMPLE_RATE)]).max() < 0.01 + assert np.abs(audio[int(0.6 * ANALYSIS_SAMPLE_RATE) : int(0.9 * ANALYSIS_SAMPLE_RATE)]).max() > 0.05 + + +@pytest.mark.parametrize("fps", [24.0, 30.0, 60.0]) +def test_a_short_context_window_holds_a_voice_bridge_at_any_frame_rate(fps: float) -> None: + # Bug: the fixed 49-frame window left under 0.4 s for speech once the 1.3 s seam piece took its + # share at 30 fps, and nothing at 60 fps, so no bridge was ever built and nothing said why. + source_frames = int(6 * fps) + window = window_for_extend( + source_frames=source_frames, + extend_frames=48, + mode="end", + max_input_frames=MAX_INPUT_FRAMES, + max_context_frames=continuation_context_frames(fps), + ) + bridge = plan_voice_bridge( + [Span(0.2, 2.5)], window=window, fps=fps, source_frames=source_frames, mode="end" + ) + assert bridge is not None + assert bridge.total_frames == window.context_frames diff --git a/backend/tests/test_windows_edit_queued.py b/backend/tests/test_windows_edit_queued.py index 08f3f2902..d528e0aaa 100644 --- a/backend/tests/test_windows_edit_queued.py +++ b/backend/tests/test_windows_edit_queued.py @@ -13,7 +13,7 @@ LOCAL_GENERATION_UNSUPPORTED_MESSAGE, VIDEO_JOB_TOO_LARGE, ) -from services.retake_pipeline.window import retake_selection_too_long_message +from inference.retake_pipeline.window import retake_selection_too_long_message from services.sqlite_store import SqliteStore from tests.conftest import TEST_ADMIN_TOKEN from tests.http_error_assertions import assert_http_error diff --git a/backend/tests/test_zit_queue_client.py b/backend/tests/test_zit_queue_client.py index 676ab2c8f..75736e45d 100644 --- a/backend/tests/test_zit_queue_client.py +++ b/backend/tests/test_zit_queue_client.py @@ -8,7 +8,7 @@ import pytest from api_types import ApiActivityStatus -from services.generation_interrupt import GenerationCancelledError +from inference.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 diff --git a/backend/tests/video_fixtures.py b/backend/tests/video_fixtures.py index 1e3d31efb..2c0c44b3c 100644 --- a/backend/tests/video_fixtures.py +++ b/backend/tests/video_fixtures.py @@ -4,6 +4,7 @@ import random import subprocess +from collections.abc import Sequence from pathlib import Path import imageio.v2 as imageio @@ -50,6 +51,35 @@ def write_pattern_clip( return path +def write_clip_with_tone_spans( + path: Path, + *, + frames: int, + spans: Sequence[tuple[float, float]], + fps: int = 24, + channels: int = 2, + amplitude: float = 0.5, + size: str = "64x64", +) -> Path: + """A moving test pattern with a tone that plays only inside ``spans`` (seconds). + + The tone stands in for speech: loud inside a span, silent outside. ``channels=1`` makes a + mono track, as phone clips have. + """ + inside = "+".join(f"between(t,{start},{end})" for start, end in spans) or "0" + run_ffmpeg( + [ + "-y", "-f", "lavfi", "-i", f"testsrc=size={size}:rate={fps}", + "-f", "lavfi", "-i", "sine=frequency=220:sample_rate=48000", + "-af", f"volume=eval=frame:volume='{amplitude}*({inside})'", + "-frames:v", str(frames), "-t", f"{frames / fps:.4f}", + "-c:v", "libx264", "-pix_fmt", "yuv420p", + "-ac", str(channels), "-c:a", "aac", str(path), + ] + ) + return path + + def write_mp4_with_display_rotation(path: Path, *, angle: str) -> Path: """A landscape clip whose container says "show it rotated", as a phone records it.""" source = write_mp4(path.with_name(f"{path.stem}-source.mp4"), seconds=1) diff --git a/backend/uv.lock b/backend/uv.lock index 3b7738507..283ee7d69 100644 --- a/backend/uv.lock +++ b/backend/uv.lock @@ -31,13 +31,13 @@ name = "accelerate" version = "1.12.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "huggingface-hub", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "numpy", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "packaging", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "psutil", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "pyyaml", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "safetensors", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "torch", version = "2.10.0+cu128", source = { registry = "https://download.pytorch.org/whl/cu128" }, marker = "(python_full_version == '3.13.*' and sys_platform == 'win32') or sys_platform == 'linux'" }, + { name = "huggingface-hub" }, + { name = "numpy" }, + { name = "packaging" }, + { name = "psutil" }, + { name = "pyyaml" }, + { name = "safetensors" }, + { name = "torch", version = "2.10.0+cu128", source = { registry = "https://download.pytorch.org/whl/cu128" }, marker = "sys_platform == 'linux' or sys_platform == 'win32'" }, { name = "torch", version = "2.11.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform == 'darwin'" }, { name = "torch", version = "2.12.1", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform != 'darwin' and sys_platform != 'linux' and sys_platform != 'win32'" }, ] @@ -69,7 +69,7 @@ name = "anyio" version = "4.12.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "idna", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, + { name = "idna" }, { name = "typing-extensions", marker = "python_full_version < '3.13' and sys_platform != 'win32'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/96/f0/5eb65b2bb0d09ac6776f2eb54adee6abe8228ea05b20a5ad0e4945de8aac/anyio-4.12.1.tar.gz", hash = "sha256:41cfcc3a4c85d3f05c932da7c26d0201ac36f72abd4435ba90d0464a3ffed703", size = 228685, upload-time = "2026-01-06T11:45:21.246Z" } @@ -134,7 +134,7 @@ name = "cffi" version = "2.1.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "pycparser", marker = "(python_full_version == '3.13.*' and implementation_name != 'PyPy') or (implementation_name != 'PyPy' and sys_platform != 'win32')" }, + { name = "pycparser", marker = "implementation_name != 'PyPy'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/9e/ef/008a1939e372c06329a3fce4279c02f328488f3526744906eeec3da7ad5f/cffi-2.1.1.tar.gz", hash = "sha256:dd31f52ea1086513bb9df30f8fcee9b8918323ae067a3d5b78bc826a000712be", size = 530807, upload-time = "2026-08-03T21:21:18.939Z" } wheels = [ @@ -276,7 +276,7 @@ name = "click" version = "8.4.2" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "colorama", marker = "python_full_version == '3.13.*' and sys_platform == 'win32'" }, + { name = "colorama", marker = "sys_platform == 'win32'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/76/d4/81420972a676e8ffea40450d8c8c92943e7218a78fe9b64359836cc9876b/click-8.4.2.tar.gz", hash = "sha256:9a6cea6e60b17ebe0a44c5cc636d94f09bd66142c1cd7d8b4cd731c4917a15f6", size = 338000, upload-time = "2026-06-24T17:45:15.148Z" } wheels = [ @@ -306,7 +306,7 @@ name = "colour-science" version = "0.4.7" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "numpy", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, + { name = "numpy" }, ] sdist = { url = "https://files.pythonhosted.org/packages/f4/66/6e2216ffae6f0008118c99d6f425f7591e688671ab99f5636f7f65021395/colour_science-0.4.7.tar.gz", hash = "sha256:b34773dc4dd3f9ba99cca5297fa10e9f532134d994b3a2308dacbe970dfd5079", size = 13283171, upload-time = "2025-12-06T08:15:08.229Z" } wheels = [ @@ -318,7 +318,7 @@ name = "contourpy" version = "1.4.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "numpy", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, + { name = "numpy" }, ] sdist = { url = "https://files.pythonhosted.org/packages/83/5a/a55177dd22553a277388e8a1b3220e92de91bacb28356cdc73caa240121d/contourpy-1.4.0.tar.gz", hash = "sha256:20156f5a1ac4f8ce02656e39a61e82164a3d359796dc8026f75b062783d500e1", size = 13323726, upload-time = "2026-09-11T19:05:05.808Z" } wheels = [ @@ -398,7 +398,7 @@ name = "cryptography" version = "50.0.2" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "cffi", marker = "(python_full_version == '3.13.*' and platform_python_implementation != 'PyPy') or (platform_python_implementation != 'PyPy' and sys_platform != 'win32')" }, + { name = "cffi", marker = "platform_python_implementation != 'PyPy'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/9d/af/182eb91b0df3fe75c4d9f26fe70684569566745f6ba7e5c9c73a862c5252/cryptography-50.0.2.tar.gz", hash = "sha256:7b46165bb56eb4704e2eaaf86f3c940d19154535d9b0ca7d6d590b04060e00d5", size = 880623, upload-time = "2026-09-30T15:30:04.884Z" } wheels = [ @@ -461,7 +461,7 @@ name = "cuda-bindings" version = "12.9.4" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "cuda-pathfinder", marker = "sys_platform == 'linux'" }, + { name = "cuda-pathfinder" }, ] wheels = [ { url = "https://files.pythonhosted.org/packages/0c/c2/65bfd79292b8ff18be4dd7f7442cea37bcbc1a228c1886f1dea515c45b67/cuda_bindings-12.9.4-cp312-cp312-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:694ba35023846625ef471257e6b5a4bc8af690f961d197d77d34b1d1db393f56", size = 11760260, upload-time = "2025-10-21T14:51:40.79Z" }, @@ -519,15 +519,15 @@ name = "diffusers" version = "0.39.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "filelock", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "httpx", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "huggingface-hub", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "importlib-metadata", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "numpy", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "pillow", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "regex", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "requests", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "safetensors", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, + { name = "filelock" }, + { name = "httpx" }, + { name = "huggingface-hub" }, + { name = "importlib-metadata" }, + { name = "numpy" }, + { name = "pillow" }, + { name = "regex" }, + { name = "requests" }, + { name = "safetensors" }, ] sdist = { url = "https://files.pythonhosted.org/packages/1a/81/6095237b86a3116c4789f28c4435d5296c00c0fc74ffde99008fd6b3a36c/diffusers-0.39.0.tar.gz", hash = "sha256:14bb1d98c85a0e463d734c99aaa73b480a7bc9bad22af30fbf730ef8f09c1d67", size = 4651240, upload-time = "2026-07-03T08:48:47.904Z" } wheels = [ @@ -557,11 +557,11 @@ name = "fastapi" version = "0.141.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "annotated-doc", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "pydantic", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "starlette", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "typing-extensions", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "typing-inspection", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, + { name = "annotated-doc" }, + { name = "pydantic" }, + { name = "starlette" }, + { name = "typing-extensions" }, + { name = "typing-inspection" }, ] sdist = { url = "https://files.pythonhosted.org/packages/8a/02/91e3416a8fdd715abb903a952a6bec7cdd8d14eed55d415fc8595524c319/fastapi-0.141.1.tar.gz", hash = "sha256:e8822fc40db1e1858054d7a949a888695bc9bdce70139178e33bd2871a453ca1", size = 425799, upload-time = "2026-07-29T17:18:05.568Z" } wheels = [ @@ -648,7 +648,7 @@ name = "ftfy" version = "6.3.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "wcwidth", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, + { name = "wcwidth" }, ] sdist = { url = "https://files.pythonhosted.org/packages/a5/d3/8650919bc3c7c6e90ee3fa7fd618bf373cbbe55dff043bd67353dbb20cd8/ftfy-6.3.1.tar.gz", hash = "sha256:9b3c3d90f84fb267fe64d375a07b7f8912d817cf86009ae134aa03e1819506ec", size = 308927, upload-time = "2024-10-26T00:50:35.149Z" } wheels = [ @@ -660,8 +660,8 @@ name = "genai-prices" version = "0.1.9" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "httpx2", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "pydantic", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, + { name = "httpx2" }, + { name = "pydantic" }, ] sdist = { url = "https://files.pythonhosted.org/packages/d6/f0/4b4c7f63de6d558714d2207808080dd0988d0317a54ebcde790e4f6c1b6e/genai_prices-0.1.9.tar.gz", hash = "sha256:20ec774d32ec5d345510877fac415f2560bbfeb081bc4cd4e7ebce57a5503e8d", size = 118447, upload-time = "2026-09-25T03:47:27.569Z" } wheels = [ @@ -673,8 +673,8 @@ name = "google-auth" version = "2.59.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "cryptography", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "pyasn1-modules", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, + { name = "cryptography" }, + { name = "pyasn1-modules" }, ] sdist = { url = "https://files.pythonhosted.org/packages/81/e3/9f752a968e487fbc10b2c2a1dd561b62489f923972911009577bb88fe7bb/google_auth-2.59.1.tar.gz", hash = "sha256:ce50fc533ac02f489a2b183a0c156672c376ecb2091b1127bc7efba2975fff27", size = 384298, upload-time = "2026-09-30T17:26:25.738Z" } wheels = [ @@ -683,7 +683,7 @@ wheels = [ [package.optional-dependencies] requests = [ - { name = "requests", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, + { name = "requests" }, ] [[package]] @@ -691,16 +691,16 @@ name = "google-genai" version = "2.28.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "anyio", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "distro", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "google-auth", extra = ["requests"], marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "httpx", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "pydantic", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "requests", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "sniffio", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "tenacity", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "typing-extensions", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "websockets", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, + { name = "anyio" }, + { name = "distro" }, + { name = "google-auth", extra = ["requests"] }, + { name = "httpx" }, + { name = "pydantic" }, + { name = "requests" }, + { name = "sniffio" }, + { name = "tenacity" }, + { name = "typing-extensions" }, + { name = "websockets" }, ] sdist = { url = "https://files.pythonhosted.org/packages/59/16/4af15d65cb72ebc21a99c5e64f09072e97334c05a48d4cede19c347e6ad2/google_genai-2.28.0.tar.gz", hash = "sha256:970cb2eaf1951949851c3e0a5b70265cfea8a408fb7361c7c980a84d90672bf2", size = 707359, upload-time = "2026-10-02T17:58:14.454Z" } wheels = [ @@ -754,8 +754,8 @@ name = "httpcore" version = "1.0.9" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "certifi", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "h11", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, + { name = "certifi" }, + { name = "h11" }, ] sdist = { url = "https://files.pythonhosted.org/packages/06/94/82699a10bca87a5556c9c59b5963f2d039dbd239f25bc2a63907a05a14cb/httpcore-1.0.9.tar.gz", hash = "sha256:6e34463af53fd2ab5d807f399a9b45ea31c3dfa2276f15a2c3f00afff6e176e8", size = 85484, upload-time = "2025-04-24T22:06:22.219Z" } wheels = [ @@ -767,8 +767,8 @@ name = "httpcore2" version = "2.13.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "h11", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "truststore", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, + { name = "h11" }, + { name = "truststore" }, ] sdist = { url = "https://files.pythonhosted.org/packages/cb/f3/1db7aa2bc2524062192bb0e0323969492d1883152a232fe36eea65f4e35c/httpcore2-2.13.1.tar.gz", hash = "sha256:e0aa977abe17e69a3b820a24542a6fa88702676d83880b8d194dcd18408e5103", size = 68071, upload-time = "2026-09-23T07:47:22.372Z" } wheels = [ @@ -809,10 +809,10 @@ name = "httpx" version = "0.28.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "anyio", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "certifi", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "httpcore", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "idna", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, + { name = "anyio" }, + { name = "certifi" }, + { name = "httpcore" }, + { name = "idna" }, ] sdist = { url = "https://files.pythonhosted.org/packages/b1/df/48c586a5fe32a0f01324ee087459e112ebb7224f646c0b5023f5e79e9956/httpx-0.28.1.tar.gz", hash = "sha256:75e98c5f16b0f35b567856f597f06ff2270a374470a5c2392242528e3e3e42fc", size = 141406, upload-time = "2024-12-06T15:37:23.222Z" } wheels = [ @@ -824,11 +824,11 @@ name = "httpx2" version = "2.13.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "anyio", marker = "(python_full_version == '3.13.*' and sys_platform == 'win32') or (sys_platform != 'emscripten' and sys_platform != 'win32')" }, - { name = "httpcore2", marker = "(python_full_version == '3.13.*' and sys_platform == 'win32') or (sys_platform != 'emscripten' and sys_platform != 'win32')" }, + { name = "anyio", marker = "sys_platform != 'emscripten'" }, + { name = "httpcore2", marker = "sys_platform != 'emscripten'" }, { name = "httpx2-jsfetch", marker = "sys_platform == 'emscripten'" }, - { name = "idna", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "truststore", marker = "(python_full_version == '3.13.*' and sys_platform == 'win32') or (sys_platform != 'emscripten' and sys_platform != 'win32')" }, + { name = "idna" }, + { name = "truststore", marker = "sys_platform != 'emscripten'" }, { name = "typing-extensions", marker = "python_full_version < '3.13' and sys_platform != 'win32'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/d5/44/474bef2a0e9d90f1715d32cb98b0738695ca17ba324095fb2497ed7fbd59/httpx2-2.13.1.tar.gz", hash = "sha256:e48744a19e3af5ee48313d0ce5fe941d5422fae5705ea922a4aabf94d7800dfa", size = 100405, upload-time = "2026-09-23T07:47:23.052Z" } @@ -850,15 +850,15 @@ name = "huggingface-hub" version = "1.27.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "click", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "filelock", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "fsspec", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "hf-xet", marker = "(python_full_version == '3.13.*' and platform_machine == 'AMD64') or (python_full_version == '3.13.*' and platform_machine == 'aarch64') or (python_full_version == '3.13.*' and platform_machine == 'amd64') or (python_full_version == '3.13.*' and platform_machine == 'arm64') or (python_full_version == '3.13.*' and platform_machine == 'x86_64') or (platform_machine == 'AMD64' and sys_platform != 'win32') or (platform_machine == 'aarch64' and sys_platform != 'win32') or (platform_machine == 'amd64' and sys_platform != 'win32') or (platform_machine == 'arm64' and sys_platform != 'win32') or (platform_machine == 'x86_64' and sys_platform != 'win32')" }, - { name = "httpx", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "packaging", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "pyyaml", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "tqdm", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "typing-extensions", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, + { name = "click" }, + { name = "filelock" }, + { name = "fsspec" }, + { name = "hf-xet", marker = "platform_machine == 'AMD64' or platform_machine == 'aarch64' or platform_machine == 'amd64' or platform_machine == 'arm64' or platform_machine == 'x86_64'" }, + { name = "httpx" }, + { name = "packaging" }, + { name = "pyyaml" }, + { name = "tqdm" }, + { name = "typing-extensions" }, ] sdist = { url = "https://files.pythonhosted.org/packages/3e/9b/ddf3d02a8681f1b9ce52fda03d755dad6b74c4f8172304c4c8d2975450f9/huggingface_hub-1.27.0.tar.gz", hash = "sha256:c1fed40ea82a6b41b477f5243546549b792ae0a93abcea608cff66089bf8f8df", size = 942668, upload-time = "2026-08-07T12:48:05.161Z" } wheels = [ @@ -879,8 +879,8 @@ name = "imageio" version = "2.37.2" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "numpy", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "pillow", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, + { name = "numpy" }, + { name = "pillow" }, ] sdist = { url = "https://files.pythonhosted.org/packages/a3/6f/606be632e37bf8d05b253e8626c2291d74c691ddc7bcdf7d6aaf33b32f6a/imageio-2.37.2.tar.gz", hash = "sha256:0212ef2727ac9caa5ca4b2c75ae89454312f440a756fcfc8ef1993e718f50f8a", size = 389600, upload-time = "2025-11-04T14:29:39.898Z" } wheels = [ @@ -906,7 +906,7 @@ name = "importlib-metadata" version = "8.7.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "zipp", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, + { name = "zipp" }, ] sdist = { url = "https://files.pythonhosted.org/packages/f3/49/3b30cad09e7771a4982d9975a8cbf64f00d4a1ececb53297f1d9a7be1b10/importlib_metadata-8.7.1.tar.gz", hash = "sha256:49fef1ae6440c182052f407c8d34a68f72efc36db9ca90dc0113398f2fdde8bb", size = 57107, upload-time = "2025-12-21T10:00:19.278Z" } wheels = [ @@ -927,7 +927,7 @@ name = "jinja2" version = "3.1.6" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "markupsafe", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, + { name = "markupsafe" }, ] sdist = { url = "https://files.pythonhosted.org/packages/df/bf/f7da0350254c0ed7c72f3e33cef02e048281fec7ecec5f032d4aac52226b/jinja2-3.1.6.tar.gz", hash = "sha256:0137fb05990d35f1275a587e9aee6d56da821fc83491a0fb838183be43f66d6d", size = 245115, upload-time = "2025-03-05T20:05:02.478Z" } wheels = [ @@ -1153,22 +1153,22 @@ name = "ltx-core" 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 = "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 = "accelerate" }, + { name = "colour-science" }, + { name = "einops" }, { name = "mps-sdpa", marker = "platform_machine == 'arm64' and sys_platform == 'darwin'" }, - { name = "numpy", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "safetensors", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "scipy", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "torch", version = "2.10.0+cu128", source = { registry = "https://download.pytorch.org/whl/cu128" }, marker = "(python_full_version == '3.13.*' and sys_platform == 'win32') or sys_platform == 'linux'" }, + { name = "numpy" }, + { name = "safetensors" }, + { name = "scipy" }, + { name = "torch", version = "2.10.0+cu128", source = { registry = "https://download.pytorch.org/whl/cu128" }, marker = "sys_platform == 'linux' or sys_platform == 'win32'" }, { name = "torch", version = "2.11.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform == 'darwin'" }, { name = "torch", version = "2.12.1", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform != 'darwin' and sys_platform != 'linux' and sys_platform != 'win32'" }, - { name = "torchaudio", version = "2.10.0", source = { registry = "https://pypi.org/simple" }, marker = "(python_full_version == '3.13.*' and sys_platform == 'win32') or sys_platform == 'linux'" }, + { name = "torchaudio", version = "2.10.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform == 'linux' or sys_platform == 'win32'" }, { name = "torchaudio", version = "2.11.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform != 'linux' and sys_platform != 'win32'" }, - { name = "torchvision", version = "0.25.0+cu128", source = { registry = "https://download.pytorch.org/whl/cu128" }, marker = "(python_full_version == '3.13.*' and sys_platform == 'win32') or sys_platform == 'linux'" }, + { name = "torchvision", version = "0.25.0+cu128", source = { registry = "https://download.pytorch.org/whl/cu128" }, marker = "sys_platform == 'linux' or sys_platform == 'win32'" }, { name = "torchvision", version = "0.26.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform == 'darwin'" }, { name = "torchvision", version = "0.27.1", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform != 'darwin' and sys_platform != 'linux' and sys_platform != 'win32'" }, - { name = "transformers", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, + { name = "transformers" }, ] [[package]] @@ -1176,58 +1176,60 @@ name = "ltx-desktop-backend" version = "1.0.0" source = { virtual = "." } dependencies = [ - { name = "av", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "diffusers", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "fastapi", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "ftfy", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "httpx", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "httpx2", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "huggingface-hub", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "imageio", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "imageio-ffmpeg", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "ltx-core", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "ltx-pipelines", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "matplotlib", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "natten", marker = "python_full_version == '3.13.*' and sys_platform == 'win32'" }, + { name = "av" }, + { name = "diffusers" }, + { name = "ftfy" }, + { name = "httpx" }, + { name = "httpx2" }, + { name = "huggingface-hub" }, + { name = "imageio" }, + { name = "imageio-ffmpeg" }, + { name = "ltx-core" }, + { name = "ltx-pipelines" }, + { name = "matplotlib" }, + { name = "natten", marker = "sys_platform == 'win32'" }, { name = "ninja", marker = "sys_platform == 'darwin'" }, - { name = "opencv-python-headless", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "peft", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "pillow", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "protobuf", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "psutil", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "pydantic", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { 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 = "opencv-python-headless" }, + { name = "peft" }, + { name = "pillow" }, + { name = "protobuf" }, + { name = "psutil" }, + { name = "pydantic" }, + { name = "pydantic-ai-slim", extra = ["google", "openai"] }, + { name = "pynvml", marker = "sys_platform != 'darwin'" }, + { name = "pyyaml" }, { 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'" }, - { name = "starlette", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "torch", version = "2.10.0+cu128", source = { registry = "https://download.pytorch.org/whl/cu128" }, marker = "(python_full_version == '3.13.*' and sys_platform == 'win32') or sys_platform == 'linux'" }, + { 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 = "sys_platform == 'win32'" }, + { name = "sentencepiece" }, + { name = "torch", version = "2.10.0+cu128", source = { registry = "https://download.pytorch.org/whl/cu128" }, marker = "sys_platform == 'linux' or sys_platform == 'win32'" }, { name = "torch", version = "2.11.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform == 'darwin'" }, { name = "torch", version = "2.12.1", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform != 'darwin' and sys_platform != 'linux' and sys_platform != 'win32'" }, - { name = "torchvision", version = "0.25.0+cu128", source = { registry = "https://download.pytorch.org/whl/cu128" }, marker = "(python_full_version == '3.13.*' and sys_platform == 'win32') or sys_platform == 'linux'" }, + { name = "torchvision", version = "0.25.0+cu128", source = { registry = "https://download.pytorch.org/whl/cu128" }, marker = "sys_platform == 'linux' or sys_platform == 'win32'" }, { name = "torchvision", version = "0.26.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform == 'darwin'" }, { name = "torchvision", version = "0.27.1", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform != 'darwin' and sys_platform != 'linux' and sys_platform != 'win32'" }, - { name = "tqdm", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "transformers", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, + { name = "tqdm" }, + { name = "transformers" }, { name = "triton", marker = "sys_platform == 'linux'" }, - { name = "triton-windows", marker = "python_full_version == '3.13.*' and sys_platform == 'win32'" }, - { name = "tzdata", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "uvicorn", extra = ["standard"], marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, + { name = "triton-windows", marker = "sys_platform == 'win32'" }, ] [package.optional-dependencies] +desktop = [ + { name = "fastapi" }, + { name = "python-multipart" }, + { name = "starlette" }, + { name = "tzdata" }, + { name = "uvicorn", extra = ["standard"] }, +] dev = [ - { name = "debugpy", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "pyright", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, + { name = "debugpy" }, + { name = "pyright" }, ] test = [ - { name = "httpx", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "pytest", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "pytest-split", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "requests", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, + { name = "httpx" }, + { name = "pytest" }, + { name = "pytest-split" }, + { name = "requests" }, ] [package.metadata] @@ -1235,7 +1237,7 @@ requires-dist = [ { name = "av", specifier = ">=16.1.0" }, { name = "debugpy", marker = "extra == 'dev'", specifier = ">=1.8" }, { name = "diffusers", specifier = ">=0.39.0" }, - { name = "fastapi", specifier = ">=0.141.1" }, + { name = "fastapi", marker = "extra == 'desktop'", specifier = ">=0.141.1" }, { name = "ftfy", specifier = ">=6.0.0" }, { name = "httpx", specifier = ">=0.27" }, { name = "httpx", marker = "extra == 'test'", specifier = ">=0.27" }, @@ -1259,13 +1261,13 @@ requires-dist = [ { name = "pyright", marker = "extra == 'dev'", specifier = ">=1.1.380" }, { 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 = "python-multipart", marker = "extra == 'desktop'", 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" }, { name = "sentencepiece", specifier = ">=0.1.99" }, - { name = "starlette", specifier = ">=1.6.0" }, + { name = "starlette", marker = "extra == 'desktop'", specifier = ">=1.6.0" }, { name = "torch", marker = "sys_platform != 'darwin' and sys_platform != 'linux' and sys_platform != 'win32'", specifier = ">=2.3.0" }, { name = "torch", marker = "sys_platform == 'darwin'", specifier = ">=2.3.0,<2.12" }, { name = "torch", marker = "sys_platform == 'linux' or sys_platform == 'win32'", specifier = ">=2.3.0", index = "https://download.pytorch.org/whl/cu128" }, @@ -1275,22 +1277,22 @@ requires-dist = [ { name = "transformers", specifier = ">=5.14.1,<5.15" }, { name = "triton", marker = "sys_platform == 'linux'" }, { name = "triton-windows", marker = "sys_platform == 'win32'" }, - { name = "tzdata", specifier = ">=2024.1" }, - { name = "uvicorn", extras = ["standard"], specifier = ">=0.30.0" }, + { name = "tzdata", marker = "extra == 'desktop'", specifier = ">=2024.1" }, + { name = "uvicorn", extras = ["standard"], marker = "extra == 'desktop'", specifier = ">=0.30.0" }, ] -provides-extras = ["test", "dev"] +provides-extras = ["desktop", "test", "dev"] [[package]] name = "ltx-pipelines" 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'" }, - { name = "ltx-core", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "openimageio", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "pillow", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "tqdm", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, + { name = "av" }, + { name = "cloudpickle" }, + { name = "ltx-core" }, + { name = "openimageio" }, + { name = "pillow" }, + { name = "tqdm" }, ] [[package]] @@ -1298,7 +1300,7 @@ name = "markdown-it-py" version = "4.2.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "mdurl", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, + { name = "mdurl" }, ] sdist = { url = "https://files.pythonhosted.org/packages/06/ff/7841249c247aa650a76b9ee4bbaeae59370dc8bfd2f6c01f3630c35eb134/markdown_it_py-4.2.0.tar.gz", hash = "sha256:04a21681d6fbb623de53f6f364d352309d4094dd4194040a10fd51833e418d49", size = 82454, upload-time = "2026-05-07T12:08:28.36Z" } wheels = [ @@ -1373,15 +1375,15 @@ name = "matplotlib" version = "3.11.2" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "contourpy", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "cycler", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "fonttools", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "kiwisolver", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "numpy", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "packaging", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "pillow", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "pyparsing", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "python-dateutil", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, + { name = "contourpy" }, + { name = "cycler" }, + { name = "fonttools" }, + { name = "kiwisolver" }, + { name = "numpy" }, + { name = "packaging" }, + { name = "pillow" }, + { name = "pyparsing" }, + { name = "python-dateutil" }, ] sdist = { url = "https://files.pythonhosted.org/packages/e7/c8/9aa712a0afb882649424dd8de8ad9aa6235e796e84c6052e8f6dc1598d0d/matplotlib-3.11.2.tar.gz", hash = "sha256:cec596316640f2b394b8f0daa0ea61a8eae82d017b620b9f202befb972a59ea4", size = 32660610, upload-time = "2026-09-11T19:05:31.214Z" } wheels = [ @@ -1452,13 +1454,13 @@ name = "mps-sdpa" version = "0.2.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "ninja", marker = "sys_platform == 'darwin'" }, - { name = "numpy", marker = "sys_platform == 'darwin'" }, - { name = "psutil", marker = "sys_platform == 'darwin'" }, - { name = "pyobjc-core", marker = "sys_platform == 'darwin'" }, - { name = "pyobjc-framework-metal", marker = "sys_platform == 'darwin'" }, - { name = "pyobjc-framework-metalperformanceshadersgraph", marker = "sys_platform == 'darwin'" }, - { name = "torch", version = "2.11.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform == 'darwin'" }, + { name = "ninja" }, + { name = "numpy" }, + { name = "psutil" }, + { name = "pyobjc-core" }, + { name = "pyobjc-framework-metal" }, + { name = "pyobjc-framework-metalperformanceshadersgraph" }, + { name = "torch", version = "2.11.0", source = { registry = "https://pypi.org/simple" } }, ] sdist = { url = "https://files.pythonhosted.org/packages/f0/c2/cf52e4364c4a5f9db84238a34974a9498e5922720349ec6f6a3700cd492c/mps_sdpa-0.2.0.tar.gz", hash = "sha256:1d6b6024801657bbdc4a6420ec7a0b52191ab0b88d847143a3ea1728ba3f93b5", size = 81037, upload-time = "2026-04-30T16:12:53.581Z" } wheels = [ @@ -1602,7 +1604,7 @@ name = "nvidia-cudnn-cu12" version = "9.10.2.21" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "nvidia-cublas-cu12", marker = "sys_platform == 'linux'" }, + { name = "nvidia-cublas-cu12" }, ] wheels = [ { url = "https://files.pythonhosted.org/packages/fa/41/e79269ce215c857c935fd86bcfe91a451a584dfc27f1e068f568b9ad1ab7/nvidia_cudnn_cu12-9.10.2.21-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:c9132cc3f8958447b4910a1720036d9eff5928cc3179b0a51fb6d167c6cc87d8", size = 705026878, upload-time = "2025-06-06T21:52:51.348Z" }, @@ -1614,7 +1616,7 @@ name = "nvidia-cufft-cu12" version = "11.3.3.83" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "nvidia-nvjitlink-cu12", marker = "sys_platform == 'linux'" }, + { name = "nvidia-nvjitlink-cu12" }, ] wheels = [ { url = "https://files.pythonhosted.org/packages/60/bc/7771846d3a0272026c416fbb7e5f4c1f146d6d80704534d0b187dd6f4800/nvidia_cufft_cu12-11.3.3.83-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:848ef7224d6305cdb2a4df928759dca7b1201874787083b6e7550dd6765ce69a", size = 193109211, upload-time = "2025-03-07T01:44:56.873Z" }, @@ -1644,9 +1646,9 @@ name = "nvidia-cusolver-cu12" version = "11.7.3.90" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "nvidia-cublas-cu12", marker = "sys_platform == 'linux'" }, - { name = "nvidia-cusparse-cu12", marker = "sys_platform == 'linux'" }, - { name = "nvidia-nvjitlink-cu12", marker = "sys_platform == 'linux'" }, + { name = "nvidia-cublas-cu12" }, + { name = "nvidia-cusparse-cu12" }, + { name = "nvidia-nvjitlink-cu12" }, ] wheels = [ { url = "https://files.pythonhosted.org/packages/c8/32/f7cd6ce8a7690544d084ea21c26e910a97e077c9b7f07bf5de623ee19981/nvidia_cusolver_cu12-11.7.3.90-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:db9ed69dbef9715071232caa9b69c52ac7de3a95773c2db65bdba85916e4e5c0", size = 267229841, upload-time = "2025-03-07T01:46:54.356Z" }, @@ -1658,7 +1660,7 @@ name = "nvidia-cusparse-cu12" version = "12.5.8.93" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "nvidia-nvjitlink-cu12", marker = "sys_platform == 'linux'" }, + { name = "nvidia-nvjitlink-cu12" }, ] wheels = [ { url = "https://files.pythonhosted.org/packages/bc/f7/cd777c4109681367721b00a106f491e0d0d15cfa1fd59672ce580ce42a97/nvidia_cusparse_cu12-12.5.8.93-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:9b6c161cb130be1a07a27ea6923df8141f3c295852f4b260c65f18f3e0a091dc", size = 288117129, upload-time = "2025-03-07T01:47:40.407Z" }, @@ -1724,12 +1726,12 @@ name = "openai" version = "3.24.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "anyio", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "httpx2", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "jiter", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "pydantic", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "sniffio", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "typing-extensions", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, + { name = "anyio" }, + { name = "httpx2" }, + { name = "jiter" }, + { name = "pydantic" }, + { name = "sniffio" }, + { name = "typing-extensions" }, ] sdist = { url = "https://files.pythonhosted.org/packages/73/4f/e57670227cb7b61362d8f9bfba54d4e9f7bde799798c342782788bc12d6c/openai-3.24.0.tar.gz", hash = "sha256:1e7463f7d78773ab2ce4fe85710481aa5bd5ffefd54c8de4b067506cd2d42895", size = 1797218, upload-time = "2026-10-02T15:55:18.851Z" } wheels = [ @@ -1741,7 +1743,7 @@ name = "opencv-python-headless" version = "4.13.0.92" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "numpy", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, + { name = "numpy" }, ] wheels = [ { url = "https://files.pythonhosted.org/packages/79/42/2310883be3b8826ac58c3f2787b9358a2d46923d61f88fedf930bc59c60c/opencv_python_headless-4.13.0.92-cp37-abi3-macosx_13_0_arm64.whl", hash = "sha256:1a7d040ac656c11b8c38677cc8cccdc149f98535089dbe5b081e80a4e5903209", size = 46247192, upload-time = "2026-02-05T07:01:35.187Z" }, @@ -1759,7 +1761,7 @@ name = "openimageio" version = "3.1.14.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "numpy", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, + { name = "numpy" }, ] sdist = { url = "https://files.pythonhosted.org/packages/37/4a/d6defe6b758e58f9bd2d1a4ae87cfdf7290968db7d0be854d52fc6c26c81/openimageio-3.1.14.1.tar.gz", hash = "sha256:52d194bc8c3f8ff512fb3eaf6de2e313c8559684d6310f7441c67c914844a72c", size = 6615452, upload-time = "2026-06-15T02:59:06.109Z" } wheels = [ @@ -1785,7 +1787,7 @@ name = "opentelemetry-api" version = "1.45.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "typing-extensions", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, + { name = "typing-extensions" }, ] sdist = { url = "https://files.pythonhosted.org/packages/1f/dc/e12c1fe1ed8a7b7149777127b1a0e12ce5bd5a81d97408bedc2128c260f5/opentelemetry_api-1.45.0.tar.gz", hash = "sha256:711ede81773c8025c2c03dac0450bc89f3d30aea6eabcc815c570d4e35a963f7", size = 72115, upload-time = "2026-09-25T12:32:28.399Z" } wheels = [ @@ -1806,18 +1808,18 @@ name = "peft" version = "0.18.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "accelerate", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "huggingface-hub", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "numpy", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "packaging", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "psutil", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "pyyaml", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "safetensors", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "torch", version = "2.10.0+cu128", source = { registry = "https://download.pytorch.org/whl/cu128" }, marker = "(python_full_version == '3.13.*' and sys_platform == 'win32') or sys_platform == 'linux'" }, + { name = "accelerate" }, + { name = "huggingface-hub" }, + { name = "numpy" }, + { name = "packaging" }, + { name = "psutil" }, + { name = "pyyaml" }, + { name = "safetensors" }, + { name = "torch", version = "2.10.0+cu128", source = { registry = "https://download.pytorch.org/whl/cu128" }, marker = "sys_platform == 'linux' or sys_platform == 'win32'" }, { name = "torch", version = "2.11.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform == 'darwin'" }, { name = "torch", version = "2.12.1", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform != 'darwin' and sys_platform != 'linux' and sys_platform != 'win32'" }, - { name = "tqdm", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "transformers", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, + { name = "tqdm" }, + { name = "transformers" }, ] sdist = { url = "https://files.pythonhosted.org/packages/d8/48/147b3ea999560b40a34fd78724c7777aa9d18409c2250bdcaf9c4f2db7fc/peft-0.18.1.tar.gz", hash = "sha256:2dd0d6bfce936d1850e48aaddbd250941c5c02fc8ef3237cd8fd5aac35e0bae2", size = 635030, upload-time = "2026-01-09T13:08:01.136Z" } wheels = [ @@ -1961,7 +1963,7 @@ name = "pyasn1-modules" version = "0.4.2" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "pyasn1", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, + { name = "pyasn1" }, ] sdist = { url = "https://files.pythonhosted.org/packages/e9/e6/78ebbb10a8c8e4b61a59249394a4a594c1a7af95593dc933a349c8d00964/pyasn1_modules-0.4.2.tar.gz", hash = "sha256:677091de870a80aae844b1ca6134f54652fa2c8c5a52aa396440ac3106e941e6", size = 307892, upload-time = "2025-03-28T02:41:22.17Z" } wheels = [ @@ -1982,10 +1984,10 @@ name = "pydantic" version = "2.12.5" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "annotated-types", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "pydantic-core", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "typing-extensions", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "typing-inspection", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, + { name = "annotated-types" }, + { name = "pydantic-core" }, + { name = "typing-extensions" }, + { name = "typing-inspection" }, ] sdist = { url = "https://files.pythonhosted.org/packages/69/44/36f1a6e523abc58ae5f928898e4aca2e0ea509b5aa6f6f392a5d882be928/pydantic-2.12.5.tar.gz", hash = "sha256:4d351024c75c0f085a9febbb665ce8c0c6ec5d30e903bdb6394b7ede26aebb49", size = 821591, upload-time = "2025-11-26T15:11:46.471Z" } wheels = [ @@ -1997,14 +1999,14 @@ name = "pydantic-ai-slim" version = "2.54.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "anyio", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "genai-prices", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "griffelib", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "httpx2", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "opentelemetry-api", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "pydantic", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "pydantic-graph", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "typing-inspection", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, + { name = "anyio" }, + { name = "genai-prices" }, + { name = "griffelib" }, + { name = "httpx2" }, + { name = "opentelemetry-api" }, + { name = "pydantic" }, + { name = "pydantic-graph" }, + { name = "typing-inspection" }, ] sdist = { url = "https://files.pythonhosted.org/packages/54/c0/b5e33b82b05c87a03e2c18089e89671da5c8fb0ba0da143011917d102745/pydantic_ai_slim-2.54.0.tar.gz", hash = "sha256:e39fd5ded83c5f2f1b271f42707de04fba420c4fd2c3bbc809d8d57614b904df", size = 1802066, upload-time = "2026-10-03T03:38:51.982Z" } wheels = [ @@ -2013,11 +2015,11 @@ wheels = [ [package.optional-dependencies] google = [ - { name = "google-genai", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, + { name = "google-genai" }, ] openai = [ - { name = "openai", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "tiktoken", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, + { name = "openai" }, + { name = "tiktoken" }, ] [[package]] @@ -2025,7 +2027,7 @@ name = "pydantic-core" version = "2.41.5" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "typing-extensions", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, + { name = "typing-extensions" }, ] sdist = { url = "https://files.pythonhosted.org/packages/71/70/23b021c950c2addd24ec408e9ab05d59b035b39d97cdc1130e1bce647bb6/pydantic_core-2.41.5.tar.gz", hash = "sha256:08daa51ea16ad373ffd5e7606252cc32f07bc72b28284b6bc9c6df804816476e", size = 460952, upload-time = "2025-11-04T13:43:49.098Z" } wheels = [ @@ -2096,10 +2098,10 @@ name = "pydantic-graph" version = "2.54.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "anyio", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "logfire-api", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "pydantic", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "typing-inspection", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, + { name = "anyio" }, + { name = "logfire-api" }, + { name = "pydantic" }, + { name = "typing-inspection" }, ] sdist = { url = "https://files.pythonhosted.org/packages/ef/6f/b5cb10c937c8d00a219eb5a07aeb991d0c44d09d5ac31a087cd1ad40dbcd/pydantic_graph-2.54.0.tar.gz", hash = "sha256:948ff7249c28643ff028b47fab22b8a5b36912c59bb947c2a9b9bc18de1d5fa5", size = 45970, upload-time = "2026-10-03T03:38:55.987Z" } wheels = [ @@ -2120,7 +2122,7 @@ name = "pynvml" version = "13.0.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "nvidia-ml-py", marker = "(python_full_version == '3.13.*' and sys_platform == 'win32') or (sys_platform != 'darwin' and sys_platform != 'win32')" }, + { name = "nvidia-ml-py" }, ] sdist = { url = "https://files.pythonhosted.org/packages/5c/57/da7dc63a79f59e082e26a66ac02d87d69ea316b35b35b7a00d82f3ce3d2f/pynvml-13.0.1.tar.gz", hash = "sha256:1245991d9db786b4d2f277ce66869bd58f38ac654e38c9397d18f243c8f6e48f", size = 35226, upload-time = "2025-09-05T20:33:25.377Z" } wheels = [ @@ -2147,7 +2149,7 @@ name = "pyobjc-framework-cocoa" version = "12.2.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "pyobjc-core", marker = "sys_platform == 'darwin'" }, + { name = "pyobjc-core" }, ] sdist = { url = "https://files.pythonhosted.org/packages/51/34/fbe38a204643aa4e1b91391cdce07a34da565a69171ebcad08de7438a556/pyobjc_framework_cocoa-12.2.1.tar.gz", hash = "sha256:b94b37fe5730e5ae1fb0052912cd174e6ec329b0bfba4a012ae5db1014b5864b", size = 3125751, upload-time = "2026-06-19T16:20:05.159Z" } wheels = [ @@ -2165,8 +2167,8 @@ name = "pyobjc-framework-metal" version = "12.2.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "pyobjc-core", marker = "sys_platform == 'darwin'" }, - { name = "pyobjc-framework-cocoa", marker = "sys_platform == 'darwin'" }, + { name = "pyobjc-core" }, + { name = "pyobjc-framework-cocoa" }, ] sdist = { url = "https://files.pythonhosted.org/packages/15/46/5920d6cb66cbbe298744889b10b3266b1408ad823855f55cdcb967c0d51d/pyobjc_framework_metal-12.2.1.tar.gz", hash = "sha256:cd362194bdb7fd2a9116b8dc1e6b14ce19629136304cdf6b88d105a969fda72c", size = 238139, upload-time = "2026-06-19T16:21:06.897Z" } wheels = [ @@ -2184,8 +2186,8 @@ name = "pyobjc-framework-metalperformanceshaders" version = "12.2.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "pyobjc-core", marker = "sys_platform == 'darwin'" }, - { name = "pyobjc-framework-metal", marker = "sys_platform == 'darwin'" }, + { name = "pyobjc-core" }, + { name = "pyobjc-framework-metal" }, ] sdist = { url = "https://files.pythonhosted.org/packages/50/ff/6938291dd5a71e39f6948037dbb271993d86a3ecd7706e7cc38034feeaea/pyobjc_framework_metalperformanceshaders-12.2.1.tar.gz", hash = "sha256:a4395f8619ad6f1d382aab5cf116e058b18d3646bec6b730c77daa8f692b5de4", size = 190474, upload-time = "2026-06-19T16:21:09.743Z" } wheels = [ @@ -2203,8 +2205,8 @@ name = "pyobjc-framework-metalperformanceshadersgraph" version = "12.2.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "pyobjc-core", marker = "sys_platform == 'darwin'" }, - { name = "pyobjc-framework-metalperformanceshaders", marker = "sys_platform == 'darwin'" }, + { name = "pyobjc-core" }, + { name = "pyobjc-framework-metalperformanceshaders" }, ] sdist = { url = "https://files.pythonhosted.org/packages/da/11/15e3acf0636f9418384cd3e213296ad9882f546889865913cfaee2339ed6/pyobjc_framework_metalperformanceshadersgraph-12.2.1.tar.gz", hash = "sha256:656e70c86645814ef1d02bac74933eebc5ff6427100bee4a3bbffde921020ab6", size = 60199, upload-time = "2026-06-19T16:21:10.716Z" } wheels = [ @@ -2225,8 +2227,8 @@ name = "pyright" version = "1.1.408" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "nodeenv", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "typing-extensions", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, + { name = "nodeenv" }, + { name = "typing-extensions" }, ] sdist = { url = "https://files.pythonhosted.org/packages/74/b2/5db700e52554b8f025faa9c3c624c59f1f6c8841ba81ab97641b54322f16/pyright-1.1.408.tar.gz", hash = "sha256:f28f2321f96852fa50b5829ea492f6adb0e6954568d1caa3f3af3a5f555eb684", size = 4400578, upload-time = "2026-01-08T08:07:38.795Z" } wheels = [ @@ -2238,11 +2240,11 @@ name = "pytest" version = "9.0.2" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "colorama", marker = "python_full_version == '3.13.*' and sys_platform == 'win32'" }, - { name = "iniconfig", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "packaging", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "pluggy", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "pygments", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, + { name = "colorama", marker = "sys_platform == 'win32'" }, + { name = "iniconfig" }, + { name = "packaging" }, + { name = "pluggy" }, + { name = "pygments" }, ] sdist = { url = "https://files.pythonhosted.org/packages/d1/db/7ef3487e0fb0049ddb5ce41d3a49c235bf9ad299b6a25d5780a89f19230f/pytest-9.0.2.tar.gz", hash = "sha256:75186651a92bd89611d1d9fc20f0b4345fd827c41ccd5c299a868a05d70edf11", size = 1568901, upload-time = "2025-12-06T21:30:51.014Z" } wheels = [ @@ -2254,7 +2256,7 @@ name = "pytest-split" version = "0.11.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "pytest", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, + { name = "pytest" }, ] sdist = { url = "https://files.pythonhosted.org/packages/2f/16/8af4c5f2ceb3640bb1f78dfdf5c184556b10dfe9369feaaad7ff1c13f329/pytest_split-0.11.0.tar.gz", hash = "sha256:8ebdb29cc72cc962e8eb1ec07db1eeb98ab25e215ed8e3216f6b9fc7ce0ec2b5", size = 13421, upload-time = "2026-02-03T09:14:31.469Z" } wheels = [ @@ -2266,7 +2268,7 @@ name = "python-dateutil" version = "2.9.0.post0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "six", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, + { name = "six" }, ] sdist = { url = "https://files.pythonhosted.org/packages/66/c0/0c8b6ad9f17a802ee498c46e004a0eb49bc148f2fd230864601a86dcf6db/python-dateutil-2.9.0.post0.tar.gz", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 342432, upload-time = "2024-03-01T18:36:20.211Z" } wheels = [ @@ -2430,10 +2432,10 @@ name = "requests" version = "2.34.2" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "certifi", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "charset-normalizer", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "idna", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "urllib3", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, + { name = "certifi" }, + { name = "charset-normalizer" }, + { name = "idna" }, + { name = "urllib3" }, ] sdist = { url = "https://files.pythonhosted.org/packages/ac/c3/e2a2b89f2d3e2179abd6d00ebd70bff6273f37fb3e0cc209f48b39d00cbf/requests-2.34.2.tar.gz", hash = "sha256:f288924cae4e29463698d6d60bc6a4da69c89185ad1e0bcc4104f584e960b9ed", size = 142856, upload-time = "2026-05-14T19:25:27.735Z" } wheels = [ @@ -2445,8 +2447,8 @@ name = "rich" version = "15.0.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "markdown-it-py", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "pygments", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, + { name = "markdown-it-py" }, + { name = "pygments" }, ] sdist = { url = "https://files.pythonhosted.org/packages/c0/8f/0722ca900cc807c13a6a0c696dacf35430f72e0ec571c4275d2371fca3e9/rich-15.0.0.tar.gz", hash = "sha256:edd07a4824c6b40189fb7ac9bc4c52536e9780fbbfbddf6f1e2502c31b068c36", size = 230680, upload-time = "2026-04-12T08:24:00.75Z" } wheels = [ @@ -2508,7 +2510,7 @@ name = "scipy" version = "1.17.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "numpy", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, + { name = "numpy" }, ] sdist = { url = "https://files.pythonhosted.org/packages/56/3e/9cca699f3486ce6bc12ff46dc2031f1ec8eb9ccc9a320fdaf925f1417426/scipy-1.17.0.tar.gz", hash = "sha256:2591060c8e648d8b96439e111ac41fd8342fdeff1876be2e19dea3fe8930454e", size = 30396830, upload-time = "2026-01-10T21:34:23.009Z" } wheels = [ @@ -2673,7 +2675,7 @@ name = "starlette" version = "1.6.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "anyio", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, + { name = "anyio" }, { name = "typing-extensions", marker = "python_full_version < '3.13' and sys_platform != 'win32'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/b5/b4/205b0d5241d934e8add0c38aa924c4f9fb7330834ff11e5444db964ec3f9/starlette-1.6.0.tar.gz", hash = "sha256:d4e3ac5e546444960c710297a3c9fc3f7ebae1b7e963f3d36173b49da535be9b", size = 2716969, upload-time = "2026-08-08T18:27:57.512Z" } @@ -2686,7 +2688,7 @@ name = "sympy" version = "1.14.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "mpmath", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, + { name = "mpmath" }, ] sdist = { url = "https://files.pythonhosted.org/packages/83/d3/803453b36afefb7c2bb238361cd4ae6125a569b4db67cd9e79846ba2d68c/sympy-1.14.0.tar.gz", hash = "sha256:d3d3fe8df1e5a0b42f0e7bdf50541697dbe7d23746e894990c030e2b05e72517", size = 7793921, upload-time = "2025-04-27T18:05:01.611Z" } wheels = [ @@ -2707,8 +2709,8 @@ name = "tiktoken" version = "0.14.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "regex", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "requests", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, + { name = "regex" }, + { name = "requests" }, ] sdist = { url = "https://files.pythonhosted.org/packages/66/62/167a842aa0429d45f5e797354fd4343a96f6043d67d0513c675c7b8d36e6/tiktoken-0.14.0.tar.gz", hash = "sha256:231dec90efcdccf1b565a1416107736f1e09b1a08fe736ef9d6363e626d03874", size = 38898, upload-time = "2026-08-17T19:49:49.514Z" } wheels = [ @@ -2761,7 +2763,7 @@ name = "tokenizers" version = "0.22.2" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "huggingface-hub", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, + { name = "huggingface-hub" }, ] sdist = { url = "https://files.pythonhosted.org/packages/73/6f/f80cfef4a312e1fb34baf7d85c72d4411afde10978d4657f8cdd811d3ccc/tokenizers-0.22.2.tar.gz", hash = "sha256:473b83b915e547aa366d1eee11806deaf419e17be16310ac0a14077f1e28f917", size = 372115, upload-time = "2026-01-05T10:45:15.988Z" } wheels = [ @@ -2792,30 +2794,30 @@ resolution-markers = [ "python_full_version < '3.14' and sys_platform == 'linux'", ] dependencies = [ - { name = "cuda-bindings", marker = "sys_platform == 'linux'" }, - { name = "filelock", marker = "(python_full_version == '3.13.*' and sys_platform == 'win32') or sys_platform == 'linux'" }, - { name = "fsspec", marker = "(python_full_version == '3.13.*' and sys_platform == 'win32') or sys_platform == 'linux'" }, - { name = "jinja2", marker = "(python_full_version == '3.13.*' and sys_platform == 'win32') or sys_platform == 'linux'" }, - { name = "networkx", marker = "(python_full_version == '3.13.*' and sys_platform == 'win32') or sys_platform == 'linux'" }, - { name = "nvidia-cublas-cu12", marker = "sys_platform == 'linux'" }, - { name = "nvidia-cuda-cupti-cu12", marker = "sys_platform == 'linux'" }, - { name = "nvidia-cuda-nvrtc-cu12", marker = "sys_platform == 'linux'" }, - { name = "nvidia-cuda-runtime-cu12", marker = "sys_platform == 'linux'" }, - { name = "nvidia-cudnn-cu12", marker = "sys_platform == 'linux'" }, - { name = "nvidia-cufft-cu12", marker = "sys_platform == 'linux'" }, - { name = "nvidia-cufile-cu12", marker = "sys_platform == 'linux'" }, - { name = "nvidia-curand-cu12", marker = "sys_platform == 'linux'" }, - { name = "nvidia-cusolver-cu12", marker = "sys_platform == 'linux'" }, - { name = "nvidia-cusparse-cu12", marker = "sys_platform == 'linux'" }, - { name = "nvidia-cusparselt-cu12", marker = "sys_platform == 'linux'" }, - { name = "nvidia-nccl-cu12", marker = "sys_platform == 'linux'" }, - { name = "nvidia-nvjitlink-cu12", marker = "sys_platform == 'linux'" }, - { name = "nvidia-nvshmem-cu12", marker = "sys_platform == 'linux'" }, - { name = "nvidia-nvtx-cu12", marker = "sys_platform == 'linux'" }, - { name = "setuptools", version = "82.0.0", source = { registry = "https://pypi.org/simple" }, marker = "(python_full_version == '3.13.*' and sys_platform == 'win32') or sys_platform == 'linux'" }, - { name = "sympy", marker = "(python_full_version == '3.13.*' and sys_platform == 'win32') or sys_platform == 'linux'" }, - { name = "triton", marker = "sys_platform == 'linux'" }, - { name = "typing-extensions", marker = "(python_full_version == '3.13.*' and sys_platform == 'win32') or sys_platform == 'linux'" }, + { name = "cuda-bindings", marker = "sys_platform != 'win32'" }, + { name = "filelock" }, + { name = "fsspec" }, + { name = "jinja2" }, + { name = "networkx" }, + { name = "nvidia-cublas-cu12", marker = "sys_platform != 'win32'" }, + { name = "nvidia-cuda-cupti-cu12", marker = "sys_platform != 'win32'" }, + { name = "nvidia-cuda-nvrtc-cu12", marker = "sys_platform != 'win32'" }, + { name = "nvidia-cuda-runtime-cu12", marker = "sys_platform != 'win32'" }, + { name = "nvidia-cudnn-cu12", marker = "sys_platform != 'win32'" }, + { name = "nvidia-cufft-cu12", marker = "sys_platform != 'win32'" }, + { name = "nvidia-cufile-cu12", marker = "sys_platform != 'win32'" }, + { name = "nvidia-curand-cu12", marker = "sys_platform != 'win32'" }, + { name = "nvidia-cusolver-cu12", marker = "sys_platform != 'win32'" }, + { name = "nvidia-cusparse-cu12", marker = "sys_platform != 'win32'" }, + { name = "nvidia-cusparselt-cu12", marker = "sys_platform != 'win32'" }, + { name = "nvidia-nccl-cu12", marker = "sys_platform != 'win32'" }, + { name = "nvidia-nvjitlink-cu12", marker = "sys_platform != 'win32'" }, + { name = "nvidia-nvshmem-cu12", marker = "sys_platform != 'win32'" }, + { name = "nvidia-nvtx-cu12", marker = "sys_platform != 'win32'" }, + { name = "setuptools", version = "82.0.0", source = { registry = "https://pypi.org/simple" } }, + { name = "sympy" }, + { name = "triton", marker = "sys_platform != 'win32'" }, + { name = "typing-extensions" }, ] wheels = [ { url = "https://download-r2.pytorch.org/whl/cu128/torch-2.10.0%2Bcu128-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:6f09cdf2415516be028ae82e6b985bcfc3eac37bc52ab401142689f6224516ca", upload-time = "2026-01-21T15:22:03Z" }, @@ -2844,13 +2846,13 @@ resolution-markers = [ "python_full_version < '3.14' and sys_platform == 'darwin'", ] dependencies = [ - { name = "filelock", marker = "sys_platform == 'darwin'" }, - { name = "fsspec", marker = "sys_platform == 'darwin'" }, - { name = "jinja2", marker = "sys_platform == 'darwin'" }, - { name = "networkx", marker = "sys_platform == 'darwin'" }, - { name = "setuptools", version = "81.0.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform == 'darwin'" }, - { name = "sympy", marker = "sys_platform == 'darwin'" }, - { name = "typing-extensions", marker = "sys_platform == 'darwin'" }, + { name = "filelock" }, + { name = "fsspec" }, + { name = "jinja2" }, + { name = "networkx" }, + { name = "setuptools", version = "81.0.0", source = { registry = "https://pypi.org/simple" } }, + { name = "sympy" }, + { name = "typing-extensions" }, ] wheels = [ { url = "https://files.pythonhosted.org/packages/6f/8b/69e3008d78e5cee2b30183340cc425081b78afc5eff3d080daab0adda9aa/torch-2.11.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:4b5866312ee6e52ea625cd211dcb97d6a2cdc1131a5f15cc0d87eec948f6dd34", size = 80606338, upload-time = "2026-03-23T18:11:34.781Z" }, @@ -2869,13 +2871,13 @@ resolution-markers = [ "python_full_version < '3.14' and sys_platform != 'darwin' and sys_platform != 'linux' and sys_platform != 'win32'", ] dependencies = [ - { name = "filelock", marker = "sys_platform != 'darwin' and sys_platform != 'linux' and sys_platform != 'win32'" }, - { name = "fsspec", marker = "sys_platform != 'darwin' and sys_platform != 'linux' and sys_platform != 'win32'" }, - { name = "jinja2", marker = "sys_platform != 'darwin' and sys_platform != 'linux' and sys_platform != 'win32'" }, - { name = "networkx", marker = "sys_platform != 'darwin' and sys_platform != 'linux' and sys_platform != 'win32'" }, - { name = "setuptools", version = "81.0.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform != 'darwin' and sys_platform != 'linux' and sys_platform != 'win32'" }, - { name = "sympy", marker = "sys_platform != 'darwin' and sys_platform != 'linux' and sys_platform != 'win32'" }, - { name = "typing-extensions", marker = "sys_platform != 'darwin' and sys_platform != 'linux' and sys_platform != 'win32'" }, + { name = "filelock" }, + { name = "fsspec" }, + { name = "jinja2" }, + { name = "networkx" }, + { name = "setuptools", version = "81.0.0", source = { registry = "https://pypi.org/simple" } }, + { name = "sympy" }, + { name = "typing-extensions" }, ] [[package]] @@ -2888,7 +2890,7 @@ resolution-markers = [ "python_full_version < '3.14' and sys_platform == 'linux'", ] dependencies = [ - { name = "torch", version = "2.10.0+cu128", source = { registry = "https://download.pytorch.org/whl/cu128" }, marker = "(python_full_version == '3.13.*' and sys_platform == 'win32') or sys_platform == 'linux'" }, + { name = "torch", version = "2.10.0+cu128", source = { registry = "https://download.pytorch.org/whl/cu128" } }, ] wheels = [ { url = "https://files.pythonhosted.org/packages/ea/3f/df620439a76ece170472d41438d11a1545d5db5dc9f1eaeab8c6e055a328/torchaudio-2.10.0-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:42b148a0921a3721abd1f6ae098b1ec9f89703e555c4f7a0d44da87b8decbcb9", size = 391973, upload-time = "2026-01-21T16:28:39.732Z" }, @@ -2936,9 +2938,9 @@ resolution-markers = [ "python_full_version < '3.14' and sys_platform == 'linux'", ] dependencies = [ - { name = "numpy", marker = "(python_full_version == '3.13.*' and sys_platform == 'win32') or sys_platform == 'linux'" }, - { name = "pillow", marker = "(python_full_version == '3.13.*' and sys_platform == 'win32') or sys_platform == 'linux'" }, - { name = "torch", version = "2.10.0+cu128", source = { registry = "https://download.pytorch.org/whl/cu128" }, marker = "(python_full_version == '3.13.*' and sys_platform == 'win32') or sys_platform == 'linux'" }, + { name = "numpy" }, + { name = "pillow" }, + { name = "torch", version = "2.10.0+cu128", source = { registry = "https://download.pytorch.org/whl/cu128" } }, ] wheels = [ { url = "https://download-r2.pytorch.org/whl/cu128/torchvision-0.25.0%2Bcu128-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:8623e534ef6a815bd6407d4b52dd70c7154e2eda626ad4b9cb895d36c5a3305b", upload-time = "2026-01-21T22:32:23Z" }, @@ -2967,9 +2969,9 @@ resolution-markers = [ "python_full_version < '3.14' and sys_platform == 'darwin'", ] dependencies = [ - { name = "numpy", marker = "sys_platform == 'darwin'" }, - { name = "pillow", marker = "sys_platform == 'darwin'" }, - { name = "torch", version = "2.11.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform == 'darwin'" }, + { name = "numpy" }, + { name = "pillow" }, + { name = "torch", version = "2.11.0", source = { registry = "https://pypi.org/simple" } }, ] wheels = [ { url = "https://files.pythonhosted.org/packages/ae/e7/56b47cc3b132aea90ccce22bcb8975dec688b002150012acc842846039d0/torchvision-0.26.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:c409e1c3fdebec7a3834465086dbda8bf7680eff79abf7fd2f10c6b59520a7a4", size = 1863502, upload-time = "2026-03-23T18:12:57.326Z" }, @@ -2988,9 +2990,9 @@ resolution-markers = [ "python_full_version < '3.14' and sys_platform != 'darwin' and sys_platform != 'linux' and sys_platform != 'win32'", ] dependencies = [ - { name = "numpy", marker = "sys_platform != 'darwin' and sys_platform != 'linux' and sys_platform != 'win32'" }, - { name = "pillow", marker = "sys_platform != 'darwin' and sys_platform != 'linux' and sys_platform != 'win32'" }, - { name = "torch", version = "2.12.1", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform != 'darwin' and sys_platform != 'linux' and sys_platform != 'win32'" }, + { name = "numpy" }, + { name = "pillow" }, + { name = "torch", version = "2.12.1", source = { registry = "https://pypi.org/simple" } }, ] [[package]] @@ -2998,7 +3000,7 @@ name = "tqdm" version = "4.67.3" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "colorama", marker = "python_full_version == '3.13.*' and sys_platform == 'win32'" }, + { name = "colorama", marker = "sys_platform == 'win32'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/09/a9/6ba95a270c6f1fbcd8dac228323f2777d886cb206987444e4bce66338dd4/tqdm-4.67.3.tar.gz", hash = "sha256:7d825f03f89244ef73f1d4ce193cb1774a8179fd96f31d7e1dcde62092b960bb", size = 169598, upload-time = "2026-02-03T17:35:53.048Z" } wheels = [ @@ -3010,15 +3012,15 @@ name = "transformers" version = "5.14.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "huggingface-hub", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "numpy", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "packaging", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "pyyaml", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "regex", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "safetensors", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "tokenizers", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "tqdm", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "typer", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, + { name = "huggingface-hub" }, + { name = "numpy" }, + { name = "packaging" }, + { name = "pyyaml" }, + { name = "regex" }, + { name = "safetensors" }, + { name = "tokenizers" }, + { name = "tqdm" }, + { name = "typer" }, ] sdist = { url = "https://files.pythonhosted.org/packages/5a/fb/2a2ba88f325e68a921d8b69ff63b477830b2e73ade9a3c8c8cab2f06d741/transformers-5.14.1.tar.gz", hash = "sha256:60d196c27781eacf8637e2b533f517582907ad6f9ae142046d6b69431a5b2173", size = 9295927, upload-time = "2026-07-16T09:41:57.773Z" } wheels = [ @@ -3066,10 +3068,10 @@ name = "typer" version = "0.27.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "annotated-doc", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "colorama", marker = "python_full_version == '3.13.*' and sys_platform == 'win32'" }, - { name = "rich", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "shellingham", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, + { name = "annotated-doc" }, + { name = "colorama", marker = "sys_platform == 'win32'" }, + { name = "rich" }, + { name = "shellingham" }, ] sdist = { url = "https://files.pythonhosted.org/packages/ae/40/4a3db7990d1f62a53182aa96eaef57aeb2886a27f90a195bc66713565d31/typer-0.27.1.tar.gz", hash = "sha256:a79bef8469a79c45498e7b814ecf8d603cc7644e9acbd9e19cac0334240b18df", size = 203994, upload-time = "2026-08-03T14:41:03.438Z" } wheels = [ @@ -3090,7 +3092,7 @@ name = "typing-inspection" version = "0.4.2" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "typing-extensions", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, + { name = "typing-extensions" }, ] sdist = { url = "https://files.pythonhosted.org/packages/55/e3/70399cb7dd41c10ac53367ae42139cf4b1ca5f36bb3dc6c9d33acdb43655/typing_inspection-0.4.2.tar.gz", hash = "sha256:ba561c48a67c5958007083d386c3295464928b01faa735ab8547c5692e87f464", size = 75949, upload-time = "2025-10-01T02:14:41.687Z" } wheels = [ @@ -3120,8 +3122,8 @@ name = "uvicorn" version = "0.41.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "click", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "h11", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, + { name = "click" }, + { name = "h11" }, ] sdist = { url = "https://files.pythonhosted.org/packages/32/ce/eeb58ae4ac36fe09e3842eb02e0eb676bf2c53ae062b98f1b2531673efdd/uvicorn-0.41.0.tar.gz", hash = "sha256:09d11cf7008da33113824ee5a1c6422d89fbc2ff476540d69a34c87fab8b571a", size = 82633, upload-time = "2026-02-16T23:07:24.1Z" } wheels = [ @@ -3130,13 +3132,13 @@ wheels = [ [package.optional-dependencies] standard = [ - { name = "colorama", marker = "python_full_version == '3.13.*' and sys_platform == 'win32'" }, - { name = "httptools", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "python-dotenv", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "pyyaml", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, + { name = "colorama", marker = "sys_platform == 'win32'" }, + { name = "httptools" }, + { name = "python-dotenv" }, + { name = "pyyaml" }, { name = "uvloop", marker = "platform_python_implementation != 'PyPy' and sys_platform != 'cygwin' and sys_platform != 'win32'" }, - { name = "watchfiles", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, - { name = "websockets", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, + { name = "watchfiles" }, + { name = "websockets" }, ] [[package]] @@ -3176,7 +3178,7 @@ name = "watchfiles" version = "1.1.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "anyio", marker = "python_full_version == '3.13.*' or sys_platform != 'win32'" }, + { name = "anyio" }, ] sdist = { url = "https://files.pythonhosted.org/packages/c2/c9/8869df9b2a2d6c59d79220a4db37679e74f807c559ffe5265e08b227a210/watchfiles-1.1.1.tar.gz", hash = "sha256:a173cb5c16c4f40ab19cecf48a534c409f7ea983ab8fed0741304a1c0a31b3f2", size = 94440, upload-time = "2025-10-14T15:06:21.08Z" } wheels = [ diff --git a/docs/INSTALLER.md b/docs/INSTALLER.md index f501b8df0..791f4b860 100644 --- a/docs/INSTALLER.md +++ b/docs/INSTALLER.md @@ -114,6 +114,13 @@ Ensure you have internet access. The script downloads Python automatically. ### Build fails with CUDA errors The build doesn't require a GPU. CUDA packages are pre-built binaries. +### Windows: Smart App Control blocks a file + +Smart App Control (SAC) blocks unsigned code that has no good reputation. Do not tell users to turn SAC off. + +- `electron-builder.yml` signs the installer and the Electron executables (Azure Trusted Signing). It does **not** sign `python-embed`. On Windows, the app downloads `python-embed` on first launch. The release pipeline that builds that archive is outside this repo. Every `.dll`, `.pyd` and `.exe` in it (for example `torch_python.dll`, `openjp2.dll`, the OpenEXR and OpenImageIO files) must be signed before the archive is created. Without this, SAC can block the backend at start (`WinError 4551`). +- Triton builds `cuda_utils` and kernel launchers as unsigned `.pyd` files in `~/.triton/cache` at run time. Nobody can sign these in advance. The backend reads the SAC state (`backend/runtime_config/smart_app_control.py`). When SAC is on, it turns off SageAttention and torch.compile, and it hides Triton from the process (`block_triton_import`), because the ltx-core video VAE also launches Triton kernels and falls back to plain PyTorch when Triton is missing. Generation then uses the default attention and runs slower. + ### macOS: "App is damaged" or Gatekeeper warning On unsigned builds, macOS Gatekeeper may block the app. Right-click the app and select "Open", or run: ```bash diff --git a/docs/TELEMETRY.md b/docs/TELEMETRY.md index 645dda84a..a24afb45e 100644 --- a/docs/TELEMETRY.md +++ b/docs/TELEMETRY.md @@ -16,7 +16,7 @@ Every event includes the app version, a device timestamp, the installation ID, a - A random generation ID, and the attempt number when a job is retried - Where it ran: the desktop app or a remote client on the local network, whether it started from Home or Gen Space, and whether the assistant queued it. Your messages to the assistant are never included -- What was requested: feature (for example text-to-video, image-to-video, audio-to-video, multi-keyframe, retake, extend, or a Home LoRA recipe), image or video, local or LTX API execution, model, resolution, frames per second, and requested duration +- What was requested: feature (for example text-to-video, image-to-video, audio-to-video, keyframes, multi-keyframe, retake, extend, or a Home LoRA recipe; Home records `keyframes` and Gen Space records `multi-keyframe`), image or video, local or LTX API execution, model, resolution, frames per second, and requested duration - How many images were requested, for an image generation - LoRA catalog IDs for built-in adapters. A custom LoRA is recorded only as a boolean, never as a file name or path - How the prompt was passed: `raw` (sent as typed), `manually-enhanced` (the user ran Enhance), or `auto-enhanced` (the app rewrote it before generation). The prompt text is never included diff --git a/docs/hardware-compatibility.md b/docs/hardware-compatibility.md index 8a21a90bb..e617110b8 100644 --- a/docs/hardware-compatibility.md +++ b/docs/hardware-compatibility.md @@ -334,7 +334,12 @@ up to about 5 s with the whole model on the GPU (**Full**). - **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). + single extension is about 16 seconds (less at 1080p on smaller cards). With + **Short** context, Extend keeps only about the last 2 seconds of your clip + (a "10 second" extension is then budgeted as ~12 seconds). It processes less + footage, so it runs faster and fits longer extensions, up to about 19 seconds. + Retake has the same **Long** / **Short** choice: **Short** keeps about 2 seconds + of context on each side of the part you select, instead of filling the window. - **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 @@ -790,7 +795,9 @@ instead. 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 +extensions always keep at least ~5 seconds of your clip as context. With **Short** +context only about the last 2 seconds are kept, so the same Mac fits a +longer extension and runs it faster. 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. diff --git a/docs/ltx-2-1-5-0-upgrade.md b/docs/ltx-2-1-5-0-upgrade.md index 955812acd..f4dde5e18 100644 --- a/docs/ltx-2-1-5-0-upgrade.md +++ b/docs/ltx-2-1-5-0-upgrade.md @@ -10,7 +10,7 @@ The manual test plan is in `docs/ltx-2-1-5-0-manual-test-plan.md`. | --- | --- | | 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. | +| Image inputs | One helper, `to_ltx_images` in `inference/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. | @@ -91,7 +91,7 @@ Proposed experiment after the upgrade ships: - `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. +- Developers run `uv sync --extra desktop` in `backend/` after they pull. A plain `uv sync` removes FastAPI. ## Open PRs diff --git a/docs/skills/measuring-hardware-cells.md b/docs/skills/measuring-hardware-cells.md index 3ca055be9..820fa76d1 100644 --- a/docs/skills/measuring-hardware-cells.md +++ b/docs/skills/measuring-hardware-cells.md @@ -97,11 +97,11 @@ from pathlib import Path import torch -from frame_math import compute_num_frames +from inference.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 inference.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 ( @@ -110,7 +110,7 @@ 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 inference.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 @@ -130,7 +130,7 @@ from runtime_config.video_job_budget import ( video_tokens, ) from services.gpu_info.gpu_info_impl import GpuInfoImpl -from services.retake_pipeline.window import MAX_INPUT_FRAMES +from inference.retake_pipeline.window import MAX_INPUT_FRAMES from services.storage_info.storage_info import DriveType from services.storage_info.storage_info_impl import StorageInfoImpl diff --git a/electron-builder.yml b/electron-builder.yml index 859793697..0004e8bb2 100644 --- a/electron-builder.yml +++ b/electron-builder.yml @@ -41,6 +41,8 @@ extraResources: - "**/*.sql" - pyproject.toml - runtime_config/lora_catalog.json + # inference/ic_lora_tiling.py reads this at import. The *.py filter does not ship it. + - inference/ic-lora-tiling-controls.json - "!**/__pycache__/**" - "!**/*.pyc" - "!.venv/**" @@ -48,8 +50,7 @@ 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, - # runtime_config/ic_lora_tiling.py). + # services/features/video/motion_path.py, runtime_config/ic_lora_local_envelope.py). # Name each file. Do not use a glob. - from: shared to: shared @@ -57,7 +58,6 @@ 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/explore-seed.test.ts b/electron/explore-seed.test.ts index 292b442ea..a1345d6a1 100644 --- a/electron/explore-seed.test.ts +++ b/electron/explore-seed.test.ts @@ -187,9 +187,9 @@ describe("packaged seed path resolution", () => { "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); } + assert.equal(yaml.includes("- inference/ic-lora-tiling-controls.json"), true); }); }); diff --git a/electron/python-setup.ts b/electron/python-setup.ts index 5bfc65efd..51dfc75d9 100644 --- a/electron/python-setup.ts +++ b/electron/python-setup.ts @@ -265,17 +265,24 @@ async function fetchRemoteDepsHash(base: string, tempFileName: string): Promise< if (base.endsWith('.tar.gz')) return null // can't inspect a single tar.gz without extracting return readHash(path.join(base, 'deps-hash.txt')) } - const hashUrl = `${base}/python-deps-hash.txt` + // Prefer the per-platform hash: the Windows hash can differ from the Linux hash. + // Releases built before the per-platform file existed only have the shared one. + const hashUrls = [ + `${base}/${getPythonArchivePrefix()}.deps-hash.txt`, + `${base}/python-deps-hash.txt`, + ] const hashDest = path.join(app.getPath('userData'), tempFileName) - try { - await downloadFileRaw(hashUrl, hashDest) - return readHash(hashDest) - } catch (err) { - logger.warn( `[python-setup] Could not fetch deps hash from ${hashUrl}: ${err}`) - return null - } finally { - try { fs.unlinkSync(hashDest) } catch { /* ignore */ } + for (const hashUrl of hashUrls) { + try { + await downloadFileRaw(hashUrl, hashDest) + return readHash(hashDest) + } catch (err) { + logger.warn( `[python-setup] Could not fetch deps hash from ${hashUrl}: ${err}`) + } finally { + try { fs.unlinkSync(hashDest) } catch { /* ignore */ } + } } + return null } /** diff --git a/frontend/components/home/HomeGallery.tsx b/frontend/components/home/HomeGallery.tsx index 1d61900d8..6b5ba6931 100644 --- a/frontend/components/home/HomeGallery.tsx +++ b/frontend/components/home/HomeGallery.tsx @@ -12,7 +12,6 @@ import { 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"; @@ -62,7 +61,6 @@ function gallerySectionHeadingId(heading: string): string { } export function HomeGallery({ onOpen }: HomeGalleryProps) { - 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) => { @@ -77,7 +75,7 @@ export function HomeGallery({ onOpen }: HomeGalleryProps) { }); return (
- {offeredHomeFeatureSections(featureFlags).map((section) => ( + {offeredHomeFeatureSections().map((section) => ( { }) }) -describe('Keyframes flag', () => { - it('lists Keyframes only with its own flag, not the high-res video flag', () => { - assert.equal(isHomeFeatureOffered('keyframes'), false) - assert.equal(isHomeFeatureOffered('keyframes', {}), false) - assert.equal(isHomeFeatureOffered('keyframes', { keyframes: true }), true) - assert.equal(isHomeFeatureOffered('image-to-video'), true) +describe('offered Home features', () => { + it('lists Keyframes for everyone, and never lists Add custom LoRA', () => { + assert.equal(isHomeFeatureOffered('keyframes'), true) + assert.equal(isHomeFeatureOffered('custom-lora'), false) + const workflows = offeredHomeFeatureSections().find((section) => section.id === 'workflows') + assert.ok(workflows?.features.some((feature) => feature.id === 'keyframes')) }) }) diff --git a/frontend/lib/home-features.ts b/frontend/lib/home-features.ts index 3314cbfdf..427dd2192 100644 --- a/frontend/lib/home-features.ts +++ b/frontend/lib/home-features.ts @@ -3,7 +3,6 @@ import { matchPath } from "react-router"; import type { FetcherToolId } from "../../shared/deep-link.ts"; import { paths } from "../paths.ts"; -import type { DevFlagKey } from "./dev-flags.ts"; import { CUSTOM_LORA_HOME_FEATURE } from "./custom-lora.ts"; import { IC_LORA_RECIPES } from "./ic-lora-recipes.ts"; import { LORA_RECIPE_HOME_FEATURES } from "./lora-recipes.ts"; @@ -203,32 +202,19 @@ export const HOME_FEATURE_SECTIONS = HOME_FEATURE_SECTION_DEFINITIONS.map((secti features: section.featureIds.map(firstClassFeature), })); -/** The dev flags that hide a Home feature while they are off. */ -export type HomeFeatureFlagKey = Extract; -/** A flag that is missing counts as off. */ -export type HomeFeatureFlags = Readonly>>; - -/** The flag a feature needs. A feature that is not in the map needs none. */ -const FEATURE_REQUIRED_FLAG: ReadonlyMap = new Map([ - ["keyframes", "keyframes"], -]); - /** - * Whether Home lists the feature. Keyframes needs the `keyframes` flag. The backend - * refuses it without the flag as well. + * Whether Home lists the feature. * "Add custom LoRA" is never listed: it is an entry of the sidebar, not a LoRA with a tile. */ -export function isHomeFeatureOffered(id: string, flags: HomeFeatureFlags = {}): boolean { - if (id === CUSTOM_LORA_HOME_FEATURE.id) return false; - const required = FEATURE_REQUIRED_FLAG.get(id); - return required === undefined || flags[required] === true; +export function isHomeFeatureOffered(id: string): boolean { + return id !== CUSTOM_LORA_HOME_FEATURE.id; } -/** The gallery sections with the features that need a flag removed when the flag is off. */ -export function offeredHomeFeatureSections(flags: HomeFeatureFlags = {}) { +/** The gallery sections with the features that Home does not list removed. */ +export function offeredHomeFeatureSections() { return HOME_FEATURE_SECTIONS.map((section) => ({ ...section, - features: section.features.filter((feature) => isHomeFeatureOffered(feature.id, flags)), + features: section.features.filter((feature) => isHomeFeatureOffered(feature.id)), })); } diff --git a/frontend/lib/keyframe-timeline.test.ts b/frontend/lib/keyframe-timeline.test.ts index f0231eee4..6d58cfe98 100644 --- a/frontend/lib/keyframe-timeline.test.ts +++ b/frontend/lib/keyframe-timeline.test.ts @@ -28,7 +28,7 @@ describe('lastFrameFromDuration', () => { it('matches backend compute_num_frames - 1 so stills cannot sit past the clip', () => { // Cross-language parity (no shared code with frame_math). Re-verify with: // cd backend && uv run python -c " - // from frame_math import compute_num_frames + // from inference.frame_math import compute_num_frames // for s, f in [(5,24),(5,25),(5,50),(10,24),(10,25),(10,50),(4,50)]: print(s, f, compute_num_frames(s,f)-1)" assert.equal(lastFrameFromDuration(5, 24), 120) assert.equal(lastFrameFromDuration(5, 25), 120) diff --git a/frontend/ltx-io/components/QuickSearch/LtxioQuickSearch.tsx b/frontend/ltx-io/components/QuickSearch/LtxioQuickSearch.tsx index 8ed203b74..ab110668a 100644 --- a/frontend/ltx-io/components/QuickSearch/LtxioQuickSearch.tsx +++ b/frontend/ltx-io/components/QuickSearch/LtxioQuickSearch.tsx @@ -15,8 +15,6 @@ import { useKeyboardShortcut } from "@ds/lib/useKeyboardShortcut"; import { useThemedPortalContainer } from "@ds/styles/themes/useTheme"; import { useRecentSidebarTools } from "@/components/home/useRecentSidebarTools"; import { useCustomLoras } from "../../hooks/useCustomLoras.ts"; -import { useHomeFeatureFlags } from "../../hooks/useHomeFeatureFlags.ts"; - import type { QuickSearchNavigateOptions } from "./quickSearchNavigation.ts"; import { useQuickSearch } from "./QuickSearchContext.tsx"; @@ -54,27 +52,20 @@ export function LtxioQuickSearch({ const stickActiveItem = useRef(false); const trimmedQuery = query.trim(); - const featureFlags = useHomeFeatureFlags(); - const savedLoras = useCustomLoras().data; const customLoras = useMemo(() => savedLoras ?? [], [savedLoras]); const browseSections = useMemo( - () => - buildQuickSearchBrowseSections( - recentFeatureIds, - featureFlags, - customLoras, - ), - [recentFeatureIds, featureFlags, customLoras], + () => buildQuickSearchBrowseSections(recentFeatureIds, customLoras), + [recentFeatureIds, customLoras], ); const rows = useMemo(() => { if (trimmedQuery) { - return searchQuickSearchRows(trimmedQuery, featureFlags, customLoras); + return searchQuickSearchRows(trimmedQuery, customLoras); } return browseSectionsToRows(browseSections); - }, [browseSections, trimmedQuery, featureFlags, customLoras]); + }, [browseSections, trimmedQuery, customLoras]); const filters = useMemo( () => diff --git a/frontend/ltx-io/components/QuickSearch/quickSearchModel.test.ts b/frontend/ltx-io/components/QuickSearch/quickSearchModel.test.ts index fab46014d..438479a5b 100644 --- a/frontend/ltx-io/components/QuickSearch/quickSearchModel.test.ts +++ b/frontend/ltx-io/components/QuickSearch/quickSearchModel.test.ts @@ -33,7 +33,7 @@ describe("quickSearchModel", () => { }); it("includes workflows and LoRA gallery sections in browse", () => { - const sections = buildQuickSearchBrowseSections([], {}); + const sections = buildQuickSearchBrowseSections([]); const ids = sections.map((section) => section.id); assert.ok(ids.includes("workflows")); assert.ok(ids.includes("styles")); @@ -41,7 +41,7 @@ describe("quickSearchModel", () => { const workflows = sections.find((section) => section.id === "workflows"); assert.deepEqual( workflows?.features.map((feature) => feature.id), - ["text-to-video", "image-to-video", "audio-to-video"], + ["text-to-video", "image-to-video", "keyframes", "audio-to-video"], ); const postProduction = sections.find((section) => section.id === "post-production"); assert.deepEqual( @@ -66,7 +66,7 @@ describe("quickSearchModel", () => { }); it("keeps a recent post-production tool in Post production and out of Featured", () => { - const sections = buildQuickSearchBrowseSections(["day-to-night", "extend"], {}); + const sections = buildQuickSearchBrowseSections(["day-to-night", "extend"]); const idsOf = (id: string) => sections.find((section) => section.id === id)?.features.map((f) => f.id); assert.deepEqual(idsOf("recent"), ["day-to-night", "extend"]); @@ -92,10 +92,10 @@ describe("quickSearchModel", () => { }); it("never lists the Add custom LoRA page in search or browse, even as a recent tool", () => { - const search = searchQuickSearchFeatures("custom lora add", undefined, {}).map( + const search = searchQuickSearchFeatures("custom lora add").map( (feature) => feature.id, ); - const browse = buildQuickSearchBrowseSections(["custom-lora"], {}).flatMap( + const browse = buildQuickSearchBrowseSections(["custom-lora"]).flatMap( (section) => section.features.map((feature) => feature.id), ); @@ -104,7 +104,7 @@ describe("quickSearchModel", () => { }); it("hides the My LoRAs section when the user has no saved LoRA", () => { - const sections = buildQuickSearchBrowseSections([], {}, []); + const sections = buildQuickSearchBrowseSections([], []); assert.ok(!sections.some((section) => section.id === "custom-lora")); }); @@ -121,9 +121,9 @@ describe("quickSearchModel", () => { } as const; const browse = browseSectionsToRows( - buildQuickSearchBrowseSections([], {}, [lora]), + buildQuickSearchBrowseSections([], [lora]), ); - const search = searchQuickSearchRows("ink", {}, [lora]); + const search = searchQuickSearchRows("ink", [lora]); const listed = browse.filter((row) => row.kind === "custom-lora"); assert.deepEqual( diff --git a/frontend/ltx-io/components/QuickSearch/quickSearchModel.ts b/frontend/ltx-io/components/QuickSearch/quickSearchModel.ts index 3fa6e829a..40352bf82 100644 --- a/frontend/ltx-io/components/QuickSearch/quickSearchModel.ts +++ b/frontend/ltx-io/components/QuickSearch/quickSearchModel.ts @@ -3,7 +3,6 @@ import { HOME_FEATURES, HOME_SIDEBAR_FEATURED_FEATURES, type HomeFeatureDefinition, - type HomeFeatureFlags, type HomeFeatureId, getHomeFeature, isHomeFeatureOffered, @@ -203,13 +202,12 @@ function featureHaystack(feature: HomeFeatureDefinition): string { export function searchQuickSearchFeatures( query: string, limit = 24, - featureFlags: HomeFeatureFlags = {}, ): HomeFeatureDefinition[] { const tokens = tokenizeQuickSearchQuery(query); if (tokens.length === 0) return []; return HOME_FEATURES.flatMap((feature) => { - if (!isHomeFeatureOffered(feature.id, featureFlags)) return []; + if (!isHomeFeatureOffered(feature.id)) return []; const listing = featureListingFields(feature); const aliases = featureSearchAliases(feature); const score = scoreQuickSearchMatch(tokens, { @@ -261,7 +259,6 @@ export function searchQuickSearchPages( export function buildQuickSearchBrowseSections( recentFeatureIds: readonly HomeFeatureId[], - featureFlags: HomeFeatureFlags = {}, customLoras: readonly QuickSearchCustomLora[] = [], ): QuickSearchBrowseSection[] { const recentIds = new Set(recentFeatureIds); @@ -283,7 +280,7 @@ export function buildQuickSearchBrowseSections( sections.push({ id: "recent", label: "Recent workflows", features: recent }); } - for (const section of offeredHomeFeatureSections(featureFlags)) { + for (const section of offeredHomeFeatureSections()) { sections.push({ id: section.id, label: section.heading, @@ -347,21 +344,18 @@ function searchQuickSearchCustomLoras( export function searchQuickSearchRows( query: string, - featureFlags: HomeFeatureFlags = {}, customLoras: readonly QuickSearchCustomLora[] = [], ): QuickSearchRow[] { const trimmed = query.trim(); if (!trimmed) return []; - const featureRows: QuickSearchFeatureRow[] = searchQuickSearchFeatures( - trimmed, - undefined, - featureFlags, - ).map((feature) => ({ - kind: "feature", - id: feature.id, - feature, - section: "Tools", - })); + const featureRows: QuickSearchFeatureRow[] = searchQuickSearchFeatures(trimmed).map( + (feature) => ({ + kind: "feature", + id: feature.id, + feature, + section: "Tools", + }), + ); const pageRows: QuickSearchPageRow[] = searchQuickSearchPages(trimmed).map( (destination) => ({ kind: "page", diff --git a/frontend/ltx-io/hooks/useEditPreflight.ts b/frontend/ltx-io/hooks/useEditPreflight.ts index b16fe9a6e..29eb289df 100644 --- a/frontend/ltx-io/hooks/useEditPreflight.ts +++ b/frontend/ltx-io/hooks/useEditPreflight.ts @@ -8,6 +8,7 @@ import type { EditPreflightFeature, EditPreflightState, } from "../lib/editPreflight"; +import type { EditContextMode } from "../lib/editContextMode"; type EditPreflightCandidate = components["schemas"]["EditPreflightCandidate"]; @@ -17,6 +18,8 @@ export type EditPreflightRequestInput = { assetId: string | null; startTime: number; mode: "start" | "end"; + /** How much of the clip the edit keeps as context. Sets the window it is priced at. */ + contextMode: EditContextMode; candidates: EditPreflightCandidate[]; durations: number[]; }; @@ -40,6 +43,7 @@ export function useEditPreflight( deferred.assetId, deferred.startTime, deferred.mode, + deferred.contextMode, deferred.candidates .map((candidate) => `${candidate.key}:${candidate.width}x${candidate.height}`) .join(","), @@ -61,11 +65,12 @@ export function useEditPreflight( assetId, startTime: deferred.startTime, mode: deferred.mode, + contextMode: deferred.contextMode, candidates: deferred.candidates, durations: deferred.durations, }), ); - return { assetId, response }; + return { assetId, contextMode: deferred.contextMode, response }; }, enabled, retry: false, diff --git a/frontend/ltx-io/hooks/useHomeFeatureFlags.ts b/frontend/ltx-io/hooks/useHomeFeatureFlags.ts deleted file mode 100644 index 97b634337..000000000 --- a/frontend/ltx-io/hooks/useHomeFeatureFlags.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { useMemo } from "react"; - -import type { HomeFeatureFlags } from "../../lib/home-features.ts"; -import { useFeatureFlagEnabled } from "./useFeatureFlagEnabled.ts"; - -/** - * The flags that hide a Home feature. Each is false until the backend answers, so a - * feature behind a flag stays hidden until the flag is known. - */ -export function useHomeFeatureFlags(): HomeFeatureFlags { - const keyframes = useFeatureFlagEnabled("keyframes"); - return useMemo(() => ({ keyframes }), [keyframes]); -} diff --git a/frontend/ltx-io/lib/a2vDurationPolicy.test.ts b/frontend/ltx-io/lib/a2vDurationPolicy.test.ts index 60a4d52b4..231341994 100644 --- a/frontend/ltx-io/lib/a2vDurationPolicy.test.ts +++ b/frontend/ltx-io/lib/a2vDurationPolicy.test.ts @@ -221,7 +221,7 @@ describe("a2vDurationPolicy", () => { // (frame_math.num_frames_for_audio_duration / compute_num_frames) with no // shared code, so these vectors pin the agreement. Expected values from: // cd backend && uv run python -c " - // from frame_math import compute_num_frames, num_frames_for_audio_duration + // from inference.frame_math import compute_num_frames, num_frames_for_audio_duration // for d, m in [(10.563,481),(5.0,481),(5.0,113),(5.0,112),(5.04,481),(5.375,481),(2.0,481),(0.05,481),(30.0,481)]: print(d, m, num_frames_for_audio_duration(d, 24, max_frames=m)) // for s in [20,5,0]: print(s, compute_num_frames(s,24))" const audioVectors: Array< diff --git a/frontend/ltx-io/lib/editContextMode.ts b/frontend/ltx-io/lib/editContextMode.ts new file mode 100644 index 000000000..6a2a18aec --- /dev/null +++ b/frontend/ltx-io/lib/editContextMode.ts @@ -0,0 +1,11 @@ +import type { components } from "../../generated/backend-openapi"; + +/** How much of the clip an Extend or Retake keeps as context. Both features share one set. */ +export type EditContextMode = components["schemas"]["ExtendParams"]["contextMode"]; + +/** What the form, a restored run and the preflight use when no mode is stated. */ +export const DEFAULT_EDIT_CONTEXT_MODE: EditContextMode = "long"; + +export function isEditContextMode(value: unknown): value is EditContextMode { + return value === "long" || value === "short"; +} diff --git a/frontend/ltx-io/lib/editPreflight.test.ts b/frontend/ltx-io/lib/editPreflight.test.ts index 31582e8cc..0c56f909e 100644 --- a/frontend/ltx-io/lib/editPreflight.test.ts +++ b/frontend/ltx-io/lib/editPreflight.test.ts @@ -6,6 +6,7 @@ import { preflightCellStatus } from "../../lib/budget-risk.ts"; import { type EditPreflightState, preflightFallbackMessage, + scopeToContextMode, selectFreshPreflight, selectTrimMaxSeconds, } from "./editPreflight.ts"; @@ -13,6 +14,7 @@ import { function preflight(overrides: Partial = {}): EditPreflightState { return { assetId: "video-1", + contextMode: "long", response: { source: { width: 1920, height: 1080, fps: 24, frames: 481, durationSeconds: 20 }, resolutions: [ @@ -45,6 +47,26 @@ describe("selectFreshPreflight", () => { it("stays null without a selected video", () => { assert.equal(selectFreshPreflight(preflight(), null), null); }); + + it("drops verdicts priced at another Extend context mode", () => { + const short = preflight({ contextMode: "short" }); + assert.equal(selectFreshPreflight(short, "video-1", "long"), null); + assert.equal(selectFreshPreflight(short, "video-1", "short"), short); + }); +}); + +describe("scopeToContextMode", () => { + it("keeps the context when its verdicts match the values", () => { + const context = { preflight: preflight({ contextMode: "short" }) }; + assert.equal(scopeToContextMode({ contextMode: "short" }, context), context); + }); + + it("drops verdicts priced at another mode and keeps the rest of the context", () => { + const context = { preflight: preflight({ contextMode: "short" }), videoWidth: 1920 }; + const scoped = scopeToContextMode({ contextMode: "long" }, context); + assert.equal(scoped.preflight, null); + assert.equal(scoped.videoWidth, 1920); + }); }); describe("selectTrimMaxSeconds", () => { diff --git a/frontend/ltx-io/lib/editPreflight.ts b/frontend/ltx-io/lib/editPreflight.ts index 84579f56b..01b51685a 100644 --- a/frontend/ltx-io/lib/editPreflight.ts +++ b/frontend/ltx-io/lib/editPreflight.ts @@ -5,6 +5,7 @@ import { import type { BudgetReadout } from "../../lib/budget-figure.ts"; import { formatEstimatedDuration } from "../../lib/duration-format.ts"; import type { components } from "../../generated/backend-openapi"; +import { DEFAULT_EDIT_CONTEXT_MODE, type EditContextMode } from "./editContextMode.ts"; export type EditPreflightResponse = components["schemas"]["EditPreflightResponse"]; @@ -22,9 +23,31 @@ export type EditPreflightFeature = "retake" | "extend"; */ export type EditPreflightState = { assetId: string; + /** The context mode the verdicts were priced at. */ + contextMode: EditContextMode; response: EditPreflightResponse; }; +/** The verdicts only when they were priced at this context mode. */ +export function preflightForContextMode( + preflight: EditPreflightState | null | undefined, + contextMode: EditContextMode, +): EditPreflightState | null { + if (preflight == null) return null; + return preflight.contextMode === contextMode ? preflight : null; +} + +/** + * The context with only the verdicts priced at the mode these values hold. The screen fetches + * for the stored mode, but restored or just-changed values can name another one for a render. + */ +export function scopeToContextMode< + TContext extends { preflight?: EditPreflightState | null }, +>(values: { contextMode: EditContextMode }, context: TContext): TContext { + const preflight = preflightForContextMode(context.preflight, values.contextMode); + return preflight === context.preflight ? context : { ...context, preflight }; +} + /** Request grid: 0.5s keeps trim drags from refetching every pixel. */ export function roundPreflightSeconds(value: number): number { return Math.round(value * 2) / 2; @@ -113,17 +136,19 @@ export function preflightMaxDuration( } /** - * Fresh-or-absent gate: verdicts for another video never reach the - * definitions, so a new selection never wears the old video's disables. + * Fresh-or-absent gate: verdicts for another video, or priced at another + * Extend or Retake context mode, never reach the definitions, so a new selection never wears the old + * disables. */ export function selectFreshPreflight( result: EditPreflightState | null, assetId: string | null, + contextMode: EditContextMode = DEFAULT_EDIT_CONTEXT_MODE, ): EditPreflightState | null { if (result == null || assetId == null || result.assetId !== assetId) { return null; } - return result; + return preflightForContextMode(result, contextMode); } /** diff --git a/frontend/ltx-io/lib/extendLabels.ts b/frontend/ltx-io/lib/extendLabels.ts new file mode 100644 index 000000000..0985ad2fa --- /dev/null +++ b/frontend/ltx-io/lib/extendLabels.ts @@ -0,0 +1,26 @@ +import { isEditContextMode } from "./editContextMode.ts"; + +/** Where the new part goes, as the Extend form and the result metadata name it. */ +export const EXTEND_MODE_LABELS = { + start: "Before the clip", + end: "After the clip", +} as const; + +/** How much of the clip the new part continues from. */ +export const EDIT_CONTEXT_LABELS = { + long: "Long", + short: "Short", +} as const; + +export function isExtendMode(value: unknown): value is keyof typeof EXTEND_MODE_LABELS { + return value === "start" || value === "end"; +} + +export function extendModeLabel(value: unknown): string | null { + return isExtendMode(value) ? EXTEND_MODE_LABELS[value] : null; +} + +/** The result metadata names the context ("Short context"); the form field does not. */ +export function editContextBadge(value: unknown): string | null { + return isEditContextMode(value) ? `${EDIT_CONTEXT_LABELS[value]} context` : null; +} diff --git a/frontend/ltx-io/lib/generationPresentation.test.ts b/frontend/ltx-io/lib/generationPresentation.test.ts index 9548010d6..23de58163 100644 --- a/frontend/ltx-io/lib/generationPresentation.test.ts +++ b/frontend/ltx-io/lib/generationPresentation.test.ts @@ -124,6 +124,45 @@ describe("generationPresentation", () => { assert.deepEqual(presentation.badges, ["LTX 2.5 Fast", "4s"]); }); + for (const [mode, contextMode, placement, context] of [ + ["end", "long", "After the clip", "Long context"], + ["start", "short", "Before the clip", "Short context"], + ] as const) { + it(`names where the extension goes and how much it continues from (${mode}, ${contextMode})`, () => { + const presentation = generationPresentation({ + feature: "extend", + spec: { + params: { prompt: "p", model: "ltx-2.5-fast", duration: 4, mode, contextMode, seed: 7 }, + }, + }); + assert.deepEqual(presentation.badges, ["LTX 2.5 Fast", "4s", placement, context, "Seed 7"]); + }); + } + + it("shows no context badge for an old extend run that did not save one", () => { + const presentation = generationPresentation({ + feature: "extend", + spec: { params: { prompt: "p", model: "ltx-2.5-fast", duration: 4, mode: "end" } }, + }); + assert.deepEqual(presentation.badges, ["LTX 2.5 Fast", "4s", "After the clip"]); + }); + + it("names the context on a retake but not the extend placement", () => { + const presentation = generationPresentation({ + feature: "retake", + spec: { params: { prompt: "p", duration: 4, mode: "end", contextMode: "short" } }, + }); + assert.deepEqual(presentation.badges, ["4s", "Short context"]); + }); + + it("adds no context badge to a feature that has no context mode", () => { + const presentation = generationPresentation({ + feature: "text-to-video", + spec: { params: { prompt: "p", duration: 4, contextMode: "short" } }, + }); + assert.deepEqual(presentation.badges, ["4s"]); + }); + it("appends a seed badge when params.seed is a number", () => { const presentation = generationPresentation({ feature: "text-to-video", diff --git a/frontend/ltx-io/lib/generationPresentation.ts b/frontend/ltx-io/lib/generationPresentation.ts index 6d38331f0..93949f161 100644 --- a/frontend/ltx-io/lib/generationPresentation.ts +++ b/frontend/ltx-io/lib/generationPresentation.ts @@ -4,6 +4,7 @@ import { CUSTOM_LORA_RUN_FALLBACK_LABEL, } from "../../lib/custom-lora.ts"; import { HOME_FEATURES } from "../../lib/home-features.ts"; +import { editContextBadge, extendModeLabel } from "./extendLabels.ts"; import { formatPipelineDisplayName } from "../../lib/video-generation-model-specs.ts"; import { videoGenerationResolutionLabel } from "../../lib/video-resolution.ts"; @@ -27,7 +28,9 @@ type GenerationPresentationSource = Pick & { * Retake and Extend keep the source picture size unless a smaller one is asked for, and the * run caps it. The spec holds the request, not the result, so the label comes from the output. */ -const OUTPUT_SIZED_FEATURES: ReadonlySet = new Set(["retake", "extend"]); +const EXTEND_FEATURE = "extend"; +const RETAKE_FEATURE = "retake"; +const OUTPUT_SIZED_FEATURES: ReadonlySet = new Set([RETAKE_FEATURE, EXTEND_FEATURE]); function outputResolutionLabel(generation: GenerationPresentationSource): string | null { if (!OUTPUT_SIZED_FEATURES.has(generation.feature)) return null; @@ -210,6 +213,14 @@ export function generationPresentation( ) { badges.push(formatA2vDurationBadge(params.numFrames, params.fps)); } + if (generation.feature === EXTEND_FEATURE) { + const placement = extendModeLabel(params?.mode); + if (placement) badges.push(placement); + } + if (generation.feature === EXTEND_FEATURE || generation.feature === RETAKE_FEATURE) { + const context = editContextBadge(params?.contextMode); + if (context) badges.push(context); + } if (typeof params?.fps === "number") badges.push(`${params.fps} fps`); if ( params?.aspectRatio === "21:9" || diff --git a/frontend/ltx-io/lib/nagStrength.ts b/frontend/ltx-io/lib/nagStrength.ts index 4a736d91f..8bc90aef1 100644 --- a/frontend/ltx-io/lib/nagStrength.ts +++ b/frontend/ltx-io/lib/nagStrength.ts @@ -1,7 +1,7 @@ /** * Per-run strength of the negative prompt (NAG), behind the "Per-run strength controls" setting. * - * NAG has three knobs (backend `runtime_config/nag_limits.py`): + * NAG has three knobs (backend `inference/nag_limits.py`): * - scale extrapolates away from the negative: Z⁺ + (scale − 1)(Z⁺ − Z⁻). * - τ caps that per token (‖Ẑ‖₁ / ‖Z⁺‖₁ ≤ τ), so past a point more scale is clipped away. * - α blends the capped result back toward the positive: α·Ẑ + (1 − α)·Z⁺. diff --git a/frontend/ltx-io/screens/Feature/ExtendFeatureScreen.tsx b/frontend/ltx-io/screens/Feature/ExtendFeatureScreen.tsx index ec57e3059..4ad30c296 100644 --- a/frontend/ltx-io/screens/Feature/ExtendFeatureScreen.tsx +++ b/frontend/ltx-io/screens/Feature/ExtendFeatureScreen.tsx @@ -43,6 +43,7 @@ export function ExtendFeatureScreen() { selectPreflightInput={(values: ExtendValues | undefined) => ({ startTime: 0, mode: values?.mode ?? EXTEND_DEFAULTS.mode, + contextMode: values?.contextMode ?? EXTEND_DEFAULTS.contextMode, durations: [...EXTEND_DURATION_PRESETS], })} /> diff --git a/frontend/ltx-io/screens/Feature/KeyframesFeatureScreen.tsx b/frontend/ltx-io/screens/Feature/KeyframesFeatureScreen.tsx index af06e4cdf..07710924c 100644 --- a/frontend/ltx-io/screens/Feature/KeyframesFeatureScreen.tsx +++ b/frontend/ltx-io/screens/Feature/KeyframesFeatureScreen.tsx @@ -1,17 +1,12 @@ import { useMemo } from "react"; -import { Navigate } from "react-router"; - -import { paths } from "@/paths"; import { KEYFRAMES_SEED_KINDS } from "../../../../shared/explore-seed-filenames"; import { useImageAssetSize } from "../../hooks/useAsset"; import { useCreateKeyframes } from "../../hooks/useCreateKeyframes"; -import { useFeatureFlags } from "../../hooks/useFeatureFlags"; import { useGenerations } from "../../hooks/useGenerations"; import { planPackagedSeed } from "../../hooks/packagedSeed.ts"; import { usePackagedSeedAssets } from "../../hooks/usePackagedSeedAsset"; import { useVideoGenerationModelSpecs } from "../../hooks/useVideoGenerationModelSpecs"; -import { useExploreRuntime } from "../../runtime/ExploreRuntime"; import { useFeatureFormStore } from "../../stores/featureFormStore"; import { earliestKeyframe, @@ -26,8 +21,6 @@ import { KeyframesExampleEmpty } from "./results/KeyframesExampleEmpty"; import { ResultFrame } from "./results/ResultFrame"; export function KeyframesFeatureScreen() { - const { api } = useExploreRuntime(); - const flagsQuery = useFeatureFlags(api); const specsQuery = useVideoGenerationModelSpecs(); const createGeneration = useCreateKeyframes(); // The earliest still sets the ratio that Auto runs at. @@ -48,8 +41,7 @@ export function KeyframesFeatureScreen() { }); const seedQuery = usePackagedSeedAssets(KEYFRAMES_SEED_KINDS, { media: "image", - // No ingest for a user who cannot open the page. - enabled: seedPlan === "ingest" && flagsQuery.data?.keyframes === true, + enabled: seedPlan === "ingest", }); const seedAssets = seedQuery.data; const seed = useMemo( @@ -68,22 +60,16 @@ export function KeyframesFeatureScreen() { const seedReady = seedPlan === "skip" || (seedPlan === "ingest" && seedQuery.isSuccess); const resourceError = specsQuery.error ?? - flagsQuery.error ?? (seedPlan === "ingest" ? seedQuery.error : null) ?? (hasStoredValues ? null : generationsQuery.error); - // The feature has no page without its flag. The backend refuses the request too. - if (flagsQuery.isSuccess && flagsQuery.data.keyframes !== true) { - return ; - } - if (!seedReady && resourceError == null) return null; return ( ( () => ({ diff --git a/frontend/ltx-io/screens/Feature/definitions/editContextMode.ts b/frontend/ltx-io/screens/Feature/definitions/editContextMode.ts new file mode 100644 index 000000000..cc5a44693 --- /dev/null +++ b/frontend/ltx-io/screens/Feature/definitions/editContextMode.ts @@ -0,0 +1,17 @@ +import { EDIT_CONTEXT_LABELS } from "../../../lib/extendLabels.ts"; +import type { EditContextMode } from "../../../lib/editContextMode.ts"; +import type { FieldOption } from "../types.ts"; + +export const EDIT_CONTEXT_MODE_OPTIONS: FieldOption[] = [ + { value: "long", label: EDIT_CONTEXT_LABELS.long }, + { value: "short", label: EDIT_CONTEXT_LABELS.short }, +]; + +/** The tooltip of the Context field. ``shortScope`` names where Short keeps its 2 seconds. */ +export function contextModeTooltip(shortScope: string): string { + return ( + "Long: uses as much of the clip as fits as context. Most consistent, slower.\n\n" + + `Short: uses only the 2 seconds ${shortScope} as context. ` + + "Faster, but may drift from the rest of the clip." + ); +} diff --git a/frontend/ltx-io/screens/Feature/definitions/extend.test.ts b/frontend/ltx-io/screens/Feature/definitions/extend.test.ts index 0ce3467b1..4db876ce1 100644 --- a/frontend/ltx-io/screens/Feature/definitions/extend.test.ts +++ b/frontend/ltx-io/screens/Feature/definitions/extend.test.ts @@ -207,11 +207,25 @@ describe("extend definition", () => { model: "ltx-2.5-fast", duration: 8, mode: "start", + contextMode: "long", promptProvenance: "typed", }, }); }); + it("sends and restores the Short context mode", () => { + const body = toCreateBody(values({ contextMode: "short" })); + assert.equal(body.params.contextMode, "short"); + const restored = fromGeneration( + { + params: { prompt: "continue", model: "ltx-2.5-fast", duration: 6, mode: "end", contextMode: "short" }, + inputs: { video: { assetId: "clip-9" } }, + }, + context(), + ); + assert.equal(restored?.contextMode, "short"); + }); + it("rounds duration to one decimal on create", () => { const body = toCreateBody( values({ duration: 4.724674999999999995 as ExtendValues["duration"] }), @@ -240,6 +254,7 @@ describe("extend definition", () => { model: "ltx-2.5-fast", resolution: "original", mode: "start", + contextMode: "long", duration: 6, }); }); @@ -318,6 +333,7 @@ describe("extend preflight", () => { ): EditPreflightState { return { assetId: "video-1", + contextMode: "long", response: { source, resolutions: [], cells, budgetMode: "brave" }, }; } @@ -436,4 +452,25 @@ describe("extend preflight", () => { ); assert.equal(snapped.duration, 8); }); + + it("ignores verdicts priced at the other context mode", () => { + // Long tops out at 6s here; Short would allow the longer extension. + const longPriced = preflight([ + cell("720p", 4, true), + cell("720p", 6, true), + cell("720p", 8, false, "too long"), + cell("720p", 10, false, "too long"), + cell("720p", 12, false, "too long"), + ]); + const short = extendDefinition.normalize( + values({ resolution: "720p", duration: 12, contextMode: "short" }), + context({ ...dims, preflight: longPriced }), + ); + assert.equal(short.duration, 12); + const long = extendDefinition.normalize( + values({ resolution: "720p", duration: 12, contextMode: "long" }), + context({ ...dims, preflight: longPriced }), + ); + assert.equal(long.duration, 6); + }); }); diff --git a/frontend/ltx-io/screens/Feature/definitions/extend.ts b/frontend/ltx-io/screens/Feature/definitions/extend.ts index 38423718a..e670fe9b0 100644 --- a/frontend/ltx-io/screens/Feature/definitions/extend.ts +++ b/frontend/ltx-io/screens/Feature/definitions/extend.ts @@ -9,8 +9,10 @@ import { blockedOptionFields, findPreflightCell, preflightEstimatedTimeText, + scopeToContextMode, preflightFallbackMessage, } from "../../../lib/editPreflight.ts"; +import { EXTEND_MODE_LABELS, isExtendMode } from "../../../lib/extendLabels.ts"; import { roundDurationSeconds } from "../../../lib/roundDuration.ts"; import { readGenerationParams } from "../../../lib/resultsFeedModel.ts"; import { @@ -23,6 +25,12 @@ import { type FieldOption, type ValidationIssue, } from "../types.ts"; +import { + DEFAULT_EDIT_CONTEXT_MODE, + isEditContextMode, + type EditContextMode, +} from "../../../lib/editContextMode.ts"; +import { EDIT_CONTEXT_MODE_OPTIONS, contextModeTooltip } from "./editContextMode.ts"; import { negativePromptField } from "./negativePrompt.ts"; import { capabilityModelOptions, @@ -57,6 +65,7 @@ export type ExtendSchema = { model: { kind: "options"; value: OfferingId }; resolution: { kind: "options"; value: EditResolutionKey }; mode: { kind: "options"; value: ExtendMode }; + contextMode: { kind: "options"; value: EditContextMode }; duration: { kind: "options"; value: ExtendDuration }; }; @@ -69,8 +78,8 @@ export const EXTEND_EXAMPLE_NEGATIVE_PROMPT = "zoom in, push forward, frozen frame, abrupt cut, seam jump, blurry background, flicker"; const MODE_OPTIONS: FieldOption[] = [ - { value: "start", label: "Before the clip" }, - { value: "end", label: "After the clip" }, + { value: "start", label: EXTEND_MODE_LABELS.start }, + { value: "end", label: EXTEND_MODE_LABELS.end }, ]; const DURATION_OPTIONS: FieldOption[] = EXTEND_DURATION_PRESETS.map( @@ -84,13 +93,10 @@ export const EXTEND_DEFAULTS: ExtendValues = { model: "ltx-2.5-fast", resolution: "original", mode: "end", + contextMode: DEFAULT_EDIT_CONTEXT_MODE, duration: 4, }; -function isExtendMode(value: unknown): value is ExtendMode { - return value === "start" || value === "end"; -} - function isExtendDuration(value: unknown): value is ExtendDuration { return EXTEND_DURATION_PRESETS.some((preset) => preset === value); } @@ -134,6 +140,9 @@ export function fromGeneration( model: restoreOfferingId(params.model, context.specs) ?? EXTEND_DEFAULTS.model, resolution: editResolutionKeyFromParams(params), mode: isExtendMode(params.mode) ? params.mode : EXTEND_DEFAULTS.mode, + contextMode: isEditContextMode(params.contextMode) + ? params.contextMode + : EXTEND_DEFAULTS.contextMode, duration: isExtendDuration(params.duration) ? params.duration : EXTEND_DEFAULTS.duration, @@ -154,8 +163,9 @@ function videoLengthIssue( function preflightIssues( values: ExtendValues, - context: ExtendContext, + rawContext: ExtendContext, ): ValidationIssue[] { + const context = scopeToContextMode(values, rawContext); return editPreflightIssues({ video: values.video, preflight: context.preflight, @@ -207,6 +217,7 @@ export function toCreateBody( model: values.model, duration: roundDurationSeconds(values.duration), mode: values.mode, + contextMode: values.contextMode, promptProvenance: "typed", ...editResolutionParam(values, context), }, @@ -227,8 +238,9 @@ function editResolutionParam( export function buildExtendForm( values: ExtendValues, - context: ExtendContext, + rawContext: ExtendContext, ): FeatureFormModel { + const context = scopeToContextMode(values, rawContext); const resolutionOptions = editResolutionFieldOptions( context.videoWidth, context.videoHeight, @@ -280,6 +292,14 @@ export function buildExtendForm( dataKey: "mode", options: MODE_OPTIONS, }, + { + kind: "options", + id: "contextMode", + label: "Context", + dataKey: "contextMode", + tooltip: contextModeTooltip("next to the new part"), + options: EDIT_CONTEXT_MODE_OPTIONS, + }, ...(resolutionOptions.length > 0 ? [ { @@ -340,8 +360,9 @@ function resolvePreflightDuration( export function normalizeExtend( values: ExtendValues, - context: ExtendContext, + rawContext: ExtendContext, ): ExtendValues { + const context = scopeToContextMode(values, rawContext); const model = resolveExtendModel(values.model, context); const resolution = resolvePreflightResolution( normalizeEditResolution( diff --git a/frontend/ltx-io/screens/Feature/definitions/icLoraTileSize.test.ts b/frontend/ltx-io/screens/Feature/definitions/icLoraTileSize.test.ts index 645098e88..65206a8c8 100644 --- a/frontend/ltx-io/screens/Feature/definitions/icLoraTileSize.test.ts +++ b/frontend/ltx-io/screens/Feature/definitions/icLoraTileSize.test.ts @@ -3,7 +3,7 @@ import { describe, it } from "node:test"; import type { components } from "../../../../generated/backend-openapi.ts"; import { getIcLoraRecipe } from "../../../../lib/ic-lora-recipes.ts"; -import controls from "../../../../../shared/ic-lora-tiling-controls.json" with { type: "json" }; +import controls from "../../../../../backend/inference/ic-lora-tiling-controls.json" with { type: "json" }; import { createIcLoraRecipeDefinition, type IcLoraRecipeContext } from "./icLoraRecipe.ts"; import { tileSizeOptions } from "./icLoraTileOptions.ts"; import { AUTO_TILE, TILE_CHOICES, TILE_PRESETS } from "./icLoraTilingControls.ts"; diff --git a/frontend/ltx-io/screens/Feature/definitions/icLoraTilingControls.ts b/frontend/ltx-io/screens/Feature/definitions/icLoraTilingControls.ts index 5e056c40e..4c7e3e7eb 100644 --- a/frontend/ltx-io/screens/Feature/definitions/icLoraTilingControls.ts +++ b/frontend/ltx-io/screens/Feature/definitions/icLoraTilingControls.ts @@ -1,4 +1,4 @@ -import controls from "../../../../../shared/ic-lora-tiling-controls.json" with { type: "json" }; +import controls from "../../../../../backend/inference/ic-lora-tiling-controls.json" with { type: "json" }; /** * The one stored value of Auto in a numeric Advanced control. Each control needs a number for diff --git a/frontend/ltx-io/screens/Feature/definitions/retake.test.ts b/frontend/ltx-io/screens/Feature/definitions/retake.test.ts index 0cdab4f8a..7c6fd48a9 100644 --- a/frontend/ltx-io/screens/Feature/definitions/retake.test.ts +++ b/frontend/ltx-io/screens/Feature/definitions/retake.test.ts @@ -214,7 +214,7 @@ describe("retake definition", () => { const form = retakeDefinition.form(values(), context()); assert.deepEqual( form.fields.map((field) => field.id), - ["video", "prompt", "negativePrompt", "model"], + ["video", "prompt", "negativePrompt", "contextMode", "model"], ); const video = form.fields[0]; assert.equal(video?.kind, "video-asset"); @@ -318,11 +318,25 @@ describe("retake definition", () => { startTime: 1, duration: 3, mode: "replace_audio_and_video", + contextMode: "long", promptProvenance: "typed", }, }); }); + it("sends the chosen context mode and restores it from a result", () => { + const body = toCreateBody(values({ startTime: 1, duration: 3, contextMode: "short" })); + assert.equal(body.params.contextMode, "short"); + const restored = fromGeneration( + { + params: { prompt: "p", model: "ltx-2.5-fast", startTime: 1, duration: 3, contextMode: "short" }, + inputs: { video: { assetId: "clip-9" } }, + }, + context(), + ); + assert.equal(restored?.contextMode, "short"); + }); + it("rounds duration to one decimal on create", () => { const body = toCreateBody( values({ startTime: 0, duration: 4.724674999999999995 }), @@ -359,6 +373,7 @@ describe("retake definition", () => { negativePrompt: "abrupt cut", model: "ltx-2.5-fast", resolution: "original", + contextMode: "long", startTime: 0.5, duration: 2, }); @@ -541,6 +556,7 @@ describe("retake preflight", () => { ): EditPreflightState { return { assetId: "video-1", + contextMode: "long", response: { source, resolutions: [], cells }, }; } diff --git a/frontend/ltx-io/screens/Feature/definitions/retake.ts b/frontend/ltx-io/screens/Feature/definitions/retake.ts index 1f38bf0d6..abb68328d 100644 --- a/frontend/ltx-io/screens/Feature/definitions/retake.ts +++ b/frontend/ltx-io/screens/Feature/definitions/retake.ts @@ -4,7 +4,10 @@ import { withDefaultOffering, type OfferingId, } from "../../../../lib/video-generation-model-specs.ts"; -import { preflightEstimatedTimeText } from "../../../lib/editPreflight.ts"; +import { + preflightEstimatedTimeText, + scopeToContextMode, +} from "../../../lib/editPreflight.ts"; import { roundDurationSeconds } from "../../../lib/roundDuration.ts"; import { readGenerationParams } from "../../../lib/resultsFeedModel.ts"; import { @@ -17,6 +20,12 @@ import { type FieldOption, type ValidationIssue, } from "../types.ts"; +import { + DEFAULT_EDIT_CONTEXT_MODE, + isEditContextMode, + type EditContextMode, +} from "../../../lib/editContextMode.ts"; +import { EDIT_CONTEXT_MODE_OPTIONS, contextModeTooltip } from "./editContextMode.ts"; import { negativePromptField } from "./negativePrompt.ts"; import { capabilityModelOptions, @@ -48,6 +57,7 @@ export type RetakeSchema = { negativePrompt: { kind: "textarea" }; model: { kind: "options"; value: OfferingId }; resolution: { kind: "options"; value: EditResolutionKey }; + contextMode: { kind: "options"; value: EditContextMode }; startTime: { kind: "slider"; value: number }; duration: { kind: "slider"; value: number }; }; @@ -81,6 +91,7 @@ export const RETAKE_DEFAULTS: RetakeValues = { negativePrompt: RETAKE_EXAMPLE_NEGATIVE_PROMPT, model: "ltx-2.5-fast", resolution: "original", + contextMode: DEFAULT_EDIT_CONTEXT_MODE, startTime: RETAKE_EXAMPLE_START_SECONDS, duration: RETAKE_EXAMPLE_DURATION_SECONDS, }; @@ -154,6 +165,9 @@ export function fromGeneration( negativePrompt: readNegativePrompt(spec), model: restoreOfferingId(params.model, context.specs) ?? RETAKE_DEFAULTS.model, resolution: editResolutionKeyFromParams(params), + contextMode: isEditContextMode(params.contextMode) + ? params.contextMode + : RETAKE_DEFAULTS.contextMode, startTime: typeof params.startTime === "number" ? params.startTime : RETAKE_DEFAULTS.startTime, duration: @@ -192,8 +206,9 @@ function videoLengthIssue( function preflightIssues( values: RetakeValues, - context: RetakeContext, + rawContext: RetakeContext, ): ValidationIssue[] { + const context = scopeToContextMode(values, rawContext); return editPreflightIssues({ video: values.video, preflight: context.preflight, @@ -247,6 +262,7 @@ export function toCreateBody( startTime: wire.startTime, duration: wire.duration, mode: RETAKE_CREATE_MODE, + contextMode: values.contextMode, promptProvenance: "typed", ...editResolutionParam(values, context), }, @@ -267,8 +283,9 @@ function editResolutionParam( export function buildRetakeForm( values: RetakeValues, - context: RetakeContext, + rawContext: RetakeContext, ): FeatureFormModel { + const context = scopeToContextMode(values, rawContext); const resolutionOptions = editResolutionFieldOptions( context.videoWidth, context.videoHeight, @@ -292,6 +309,14 @@ export function buildRetakeForm( placeholder: "Describe what should change in this region...", }, negativePromptField(), + { + kind: "options", + id: "contextMode", + label: "Context", + dataKey: "contextMode", + tooltip: contextModeTooltip("on each side of the selection"), + options: EDIT_CONTEXT_MODE_OPTIONS, + }, ...(resolutionOptions.length > 0 ? [ { diff --git a/frontend/ltx-io/screens/Feature/results/useResultsFeedVirtualizer.ts b/frontend/ltx-io/screens/Feature/results/useResultsFeedVirtualizer.ts index 635264b4a..3a849038e 100644 --- a/frontend/ltx-io/screens/Feature/results/useResultsFeedVirtualizer.ts +++ b/frontend/ltx-io/screens/Feature/results/useResultsFeedVirtualizer.ts @@ -150,13 +150,21 @@ export function useResultsFeedVirtualizer({ // A row that is off screen keeps its old cached height, so its offset would be wrong. // Drop the cache, then measure the mounted rows again. They do not report on their own, // because the layout change happened before the cache was cleared. + // + // `measure()` empties the cache, so the library treats each measure below as the first one + // for that row. For a row above the scroll position it then moves the scroll by the + // difference between its estimate and its size. Here the user did not move, so that move + // is wrong: leaving fullscreen (the window width changes twice) scrolled the feed down + // whenever it was not at the top. The scroll position stays as it is during this measure. const feedWidth = layout.width; useLayoutEffect(() => { if (!listElement || feedWidth === 0) return; + virtualizer.shouldAdjustScrollPositionOnItemSizeChange = () => false; virtualizer.measure(); for (const row of listElement.querySelectorAll("[data-index]")) { virtualizer.measureElement(row); } + virtualizer.shouldAdjustScrollPositionOnItemSizeChange = undefined; }, [virtualizer, listElement, feedWidth]); const virtualItems = virtualizer.getVirtualItems(); diff --git a/package.json b/package.json index 058ac8ea4..cffd34d6c 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "ltx-desktop", - "version": "1.3.2", + "version": "1.3.3", "description": "LTX-2 Video Generation - Desktop App", "type": "module", "main": "dist-electron/main.js", @@ -23,12 +23,12 @@ "lint": "eslint frontend", "format-check": "prettier . --check", "format-fix": "prettier . --write --list-different", - "typecheck:py": "cd backend && uv run pyright", - "openapi:export": "cd backend && uv run python export_openapi_schema.py", + "typecheck:py": "cd backend && uv run --extra desktop pyright", + "openapi:export": "cd backend && uv run --extra desktop python export_openapi_schema.py", "openapi:types": "openapi-typescript frontend/generated/backend-openapi.json -o frontend/generated/backend-openapi.ts", "openapi:generate": "pnpm openapi:export && pnpm openapi:types", "openapi:check": "pnpm openapi:generate && git diff --exit-code -- frontend/generated/backend-openapi.json frontend/generated/backend-openapi.ts", - "backend:test": "cd backend && uv sync --frozen --extra test --extra dev && uv run pytest -v --tb=short", + "backend:test": "cd backend && uv sync --frozen --extra desktop --extra test --extra dev && uv run pytest -v --tb=short", "scripts:test": "node --test scripts/copy-koffi-native.test.cjs && node --experimental-strip-types --test --test-reporter=spec \"frontend/**/*.test.ts\" \"electron/**/*.test.ts\" \"shared/**/*.test.ts\"", "build": "node scripts/run-script.js scripts/local-build", "build:skip-python": "node scripts/run-script.js scripts/local-build --skip-python", diff --git a/scripts/clean-dev.ps1 b/scripts/clean-dev.ps1 index 8754149ec..bcf3d2bd4 100644 --- a/scripts/clean-dev.ps1 +++ b/scripts/clean-dev.ps1 @@ -26,7 +26,7 @@ Ok "pnpm install complete" Write-Host "`nReinstalling Python backend venv..." Set-Location (Join-Path $ProjectDir "backend") -uv sync --extra dev +uv sync --extra desktop --extra dev if ($LASTEXITCODE -ne 0) { Write-Host "✗ uv sync failed" -ForegroundColor Red; exit 1 } Ok "uv sync complete" diff --git a/scripts/clean-dev.sh b/scripts/clean-dev.sh index 1e143779f..57ddc8500 100755 --- a/scripts/clean-dev.sh +++ b/scripts/clean-dev.sh @@ -24,7 +24,7 @@ ok "pnpm install complete" echo "" echo "Reinstalling Python backend venv..." cd "$PROJECT_DIR/backend" -uv sync --extra dev +uv sync --extra desktop --extra dev ok "uv sync complete" echo "" diff --git a/scripts/perf-dev.mjs b/scripts/perf-dev.mjs index 1f1a51e42..322b8996c 100644 --- a/scripts/perf-dev.mjs +++ b/scripts/perf-dev.mjs @@ -45,7 +45,9 @@ function appDataDir() { } const HAS_UV = spawnSync('uv', ['--version'], { stdio: 'ignore' }).status === 0 -const runPy = (script) => (HAS_UV ? ['uv', ['run', 'python', script]] : ['python', [script]]) +// fastapi and uvicorn live in the desktop extra. A plain `uv run` does not install them. +const runPy = (script) => + HAS_UV ? ['uv', ['run', '--extra', 'desktop', 'python', script]] : ['python', [script]] function tee(child, tag) { const write = (buf) => { diff --git a/scripts/prepare-python.ps1 b/scripts/prepare-python.ps1 index b59dd7c42..eed6784fc 100644 --- a/scripts/prepare-python.ps1 +++ b/scripts/prepare-python.ps1 @@ -60,6 +60,7 @@ $RequirementsFile = Join-Path $BackendDir "requirements-dist.txt" # Export pinned deps, excluding the project itself (--no-emit-project) & uv export --frozen --no-hashes --no-editable --no-emit-project ` --no-header --no-annotate ` + --extra desktop ` --project $BackendDir ` > $RequirementsFile diff --git a/scripts/prepare-python.sh b/scripts/prepare-python.sh index 8a577e796..a5a2f50fb 100755 --- a/scripts/prepare-python.sh +++ b/scripts/prepare-python.sh @@ -90,6 +90,7 @@ REQUIREMENTS_FILE="$BACKEND_DIR/requirements-dist.txt" # (e.g. triton-windows on Linux/macOS, triton on macOS/Windows). uv export --frozen --no-hashes --no-editable --no-emit-project \ --no-header --no-annotate \ + --extra desktop \ --project "$BACKEND_DIR" \ > "$REQUIREMENTS_FILE" diff --git a/scripts/setup-dev.ps1 b/scripts/setup-dev.ps1 index fe7cf463d..569906b94 100644 --- a/scripts/setup-dev.ps1 +++ b/scripts/setup-dev.ps1 @@ -28,7 +28,7 @@ Ok "npm install complete" # ── uv sync ───────────────────────────────────────────────────────── Write-Host "`nSetting up Python backend venv..." Set-Location (Join-Path $ProjectDir "backend") -uv sync --extra dev +uv sync --extra desktop --extra dev if ($LASTEXITCODE -ne 0) { Fail "uv sync failed" } Ok "uv sync complete" diff --git a/scripts/setup-dev.sh b/scripts/setup-dev.sh index 476a6d8f7..ebbbe2ec5 100755 --- a/scripts/setup-dev.sh +++ b/scripts/setup-dev.sh @@ -31,7 +31,7 @@ ok "pnpm install complete" echo "" echo "Setting up Python backend venv..." cd "$PROJECT_DIR/backend" -uv sync --extra dev +uv sync --extra desktop --extra dev ok "uv sync complete" # Verify torch + accelerator