Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

94.5 KB
Raw Blame
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0

"""MiniMax-H3 helpers shared by the Diffusers and stable-diffusion.cpp paths."""

from __future__ import annotations

import math
import os
import tempfile
import weakref
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Callable, Optional

# Must equal the minimax-h3 family gguf_repo, or the family test passes while downloads come from a community repack (pinned in test_video_backend.py).
H3_GGUF_REPO = "unsloth/MiniMax-H3-GGUF"
# The VAEs live beside the denoisers, so the native pick is one repo we control end to end. It was the Comfy-Org repack
# once; a video load never reads from that repack any more, cached or not.
H3_COMPONENT_REPO = "unsloth/MiniMax-H3-GGUF"
# Built from the official MiniMaxAI vae/ and audio_vae/ weights (diffusers layout -> sd.cpp layout; video cast to fp16)
# and uploaded beside the originals under vae/official/. They are byte-identical to the vae/ copies that came from the
# Comfy-Org repack, which stay in place for released builds; this build reads only the official-provenance paths.
H3_VIDEO_VAE = "vae/official/minimax_h3_video_vae_fp16.safetensors"
H3_AUDIO_VAE = "vae/official/minimax_h3_audio_vae_fp32.safetensors"
H3_QWEN_Q2 = "qwen3vl_32b_minimax_h3-Q2_K_M.gguf"
H3_QWEN_Q4 = "qwen3vl_32b_minimax_h3-Q4_K_M.gguf"

# diffusers' H3 grid of n points (terminal 0 included) runs n - 1 evaluations; SGLang/ComfyUI/sd.cpp run n. "0" = old grid.
H3_STEP_EVALUATIONS_ENV = "UNSLOTH_H3_STEP_EVALUATIONS"


def h3_step_evaluations_enabled() -> bool:
    return os.environ.get(H3_STEP_EVALUATIONS_ENV, "").strip().lower() not in (
        "0",
        "false",
        "no",
        "off",
    )


def h3_num_inference_steps(steps: int) -> int:
    return int(steps) + 1 if h3_step_evaluations_enabled() else int(steps)


# Measured (Diffusers T2VA, component CPU offload, 960x544..1344x768, 124-345 frames); base is largest component plus overhead; margin = allocator variance.
H3_DIFFUSERS_VRAM_BASE_GB = 68.5
H3_DIFFUSERS_VRAM_GB_PER_MPIXEL_FRAME = 0.08

# Floor is largest resident component, but a pinned torchao denoiser (cannot move mid-block) makes it additive; 2.6 GB covers that overhead.
H3_DIFFUSERS_VRAM_OVERHEAD_GB = 1.8
H3_DIFFUSERS_VRAM_PINNED_OVERHEAD_GB = 2.6
H3_TEXT_ENCODER_BF16_GB = 66.7
H3_TRANSFORMER_BF16_GB = 66.3
# Video + audio VAE (bf16_components_gb), a floor so a tiny conditioner can't claim an unfit base.
H3_VAE_RESIDENT_GB = 11.1
# Streamed denoiser's device footprint (running + prefetched group + top-level modules); below the VAE term.
H3_TRANSFORMER_STREAMED_GB = 3.0


# Resident GB of each hosted prequant denoiser; PRUNED (curve-form adaLN), so well under half of 66.3.
H3_TRANSFORMER_PREQUANT_GB: dict[str, float] = {"int8": 20.3, "fp8": 20.3}


def h3_transformer_resident_gb(scheme: Optional[str]) -> float:
    """Resident GB: the hosted pre-quantized size for an engaged scheme, else the bf16 size."""
    return H3_TRANSFORMER_PREQUANT_GB.get(scheme or "", H3_TRANSFORMER_BF16_GB)


def h3_diffusers_vram_base_gb(
    *,
    text_encoder_gb: Optional[float] = None,
    transformer_gb: Optional[float] = None,
    transformer_pinned: bool = False,
) -> float:
    """H3 Diffusers resident-weights VRAM floor; transformer_pinned is the engaged pin, not the request."""
    text_encoder = H3_TEXT_ENCODER_BF16_GB if text_encoder_gb is None else float(text_encoder_gb)
    transformer = H3_TRANSFORMER_BF16_GB if transformer_gb is None else float(transformer_gb)
    if transformer_pinned:
        offloaded = max(text_encoder, H3_VAE_RESIDENT_GB)
        return transformer + offloaded + H3_DIFFUSERS_VRAM_PINNED_OVERHEAD_GB
    return max(text_encoder, transformer) + H3_DIFFUSERS_VRAM_OVERHEAD_GB


def estimate_h3_diffusers_vram_gb(
    width: int,
    height: int,
    num_frames: int,
    *,
    text_encoder_gb: Optional[float] = None,
    transformer_gb: Optional[float] = None,
    transformer_pinned: bool = False,
    transformer_streamed: bool = False,
    text_encoder_streamed: bool = False,
) -> float:
    """Measured VRAM floor for H3 Diffusers; unset sizes keep released bf16 floor; streamed transformer means no two large components are ever resident together."""
    volume_mpixel_frames = width * height * num_frames / 1_000_000
    if text_encoder_streamed:
        from .video_minimax_h3_te import H3_TE_STREAMED_GB
        text_encoder_gb = H3_TE_STREAMED_GB
        if transformer_streamed:
            # Nothing big is resident: the largest phase plus the top-level group.
            from .video_minimax_h3_residency import H3_TOP_LEVEL_GB, h3_phase_need_gb
            return h3_phase_need_gb(
                width,
                height,
                num_frames,
                te_streamed_gb = H3_TE_STREAMED_GB,
                fragmentation = False,
                top_gb = H3_TOP_LEVEL_GB,
            )
    if transformer_streamed:
        text_encoder = (
            H3_TEXT_ENCODER_BF16_GB if text_encoder_gb is None else float(text_encoder_gb)
        )
        activations = H3_DIFFUSERS_VRAM_GB_PER_MPIXEL_FRAME * volume_mpixel_frames
        from .video_minimax_h3_sol_vae import sol_decode_need_gb

        return max(
            text_encoder + H3_DIFFUSERS_VRAM_OVERHEAD_GB,
            max(H3_TRANSFORMER_STREAMED_GB, H3_VAE_RESIDENT_GB)
            + H3_DIFFUSERS_VRAM_OVERHEAD_GB
            + max(activations, sol_decode_need_gb(width, height, num_frames)),
        )
    base = h3_diffusers_vram_base_gb(
        text_encoder_gb = text_encoder_gb,
        transformer_gb = transformer_gb,
        transformer_pinned = transformer_pinned,
    )
    from .video_minimax_h3_sol_vae import sol_decode_need_gb

    # 0.0 unless UNSLOTH_H3_SOL_VAE=1: the Sol decode runs after the denoise, so it is a max, not a sum
    return base + max(
        H3_DIFFUSERS_VRAM_GB_PER_MPIXEL_FRAME * volume_mpixel_frames,
        sol_decode_need_gb(width, height, num_frames),
    )


# Shipped values kept: offload tier at 132 GB VRAM; no measurement here justifies moving it.
H3_DIFFUSERS_HOST_RAM_TIER_VRAM_GB = 132.0
H3_DIFFUSERS_HOST_RAM_HIGH_VRAM_GB = 85.0
# Offload tier parks everything on host, so floor is the SUM; shipped 150.0 minus released sum.
H3_DIFFUSERS_HOST_RAM_HEADROOM_GB = 5.9


# Kill switch for the held-memory accounting below; "0" restores MemAvailable + whole RSS.
H3_HOST_GUARD_HELD_ENV = "UNSLOTH_H3_HOST_GUARD_HELD"


def _proc_status_kb(fields: tuple[str, ...]) -> Optional[dict[str, int]]:
    """``/proc/self/status`` fields in kB, or None off Linux / when unreadable."""
    try:
        with open("/proc/self/status", encoding = "utf-8") as handle:
            found = {}
            for line in handle:
                key, _, value = line.partition(":")
                if key in fields:
                    found[key] = int(value.split()[0])
    except (OSError, ValueError, IndexError):
        return None
    return found if len(found) == len(fields) else None


def h3_native_host_available_bytes() -> int:
    """Host RAM a native (sd-cli / sd-server) render can still take: available RAM, cgroup-capped. Unlike
    ``h3_host_capacity_bytes`` nothing this process holds is added back: the render is a separate process and
    reuses none of it."""
    from utils import host_memory

    usable_mib = host_memory.usable_host_ram_mib()
    if usable_mib is None:
        raise RuntimeError("available host RAM could not be read")
    return max(int(usable_mib), 0) << 20


def h3_process_held_host_bytes() -> int:
    """Host bytes this process holds that a render reuses: RssAnon + RssShmem (pinned copies are shmem). File-backed
    pages are left out: MemAvailable already counts them as reclaimable. Off Linux, the whole RSS."""
    import psutil

    fields = _proc_status_kb(("RssAnon", "RssShmem"))
    if fields is None or str(os.environ.get(H3_HOST_GUARD_HELD_ENV, "1")).strip() == "0":
        return int(psutil.Process().memory_info().rss)
    return (fields["RssAnon"] + fields["RssShmem"]) * 1024


def h3_host_capacity_bytes() -> int:
    """Usable host RAM (cgroup-capped) plus what this process already holds and the render reuses,
    capped at the cgroup limit."""
    import psutil
    from utils import host_memory

    available = int(psutil.virtual_memory().available)
    budgets = host_memory.cgroup_memory_budgets()
    headroom_mib = host_memory.cgroup_headroom_mib(budgets)
    if headroom_mib is not None:
        available = min(available, int(headroom_mib) << 20)
    capacity = available + h3_process_held_host_bytes()
    limit_mib = host_memory.cgroup_limit_mib(budgets)
    if limit_mib is not None:
        capacity = min(capacity, int(limit_mib) << 20)
    return capacity


# Streamed int8 conditioner + int8 / fp8 denoiser floor, measured as non-reclaimable memory (not RSS, which counts
# mmap'd checkpoint pages the kernel reclaims under a limit): highest MemoryMax kill on main, 34 GiB, plus ~10% margin.
H3_DIFFUSERS_HOST_RAM_STREAMED_SET_GB = 40.0
# RSS-based floor for streamed sets larger than the measured one (not re-measured).
H3_DIFFUSERS_HOST_RAM_STREAMED_RSS_GB = 70.0


def estimate_h3_diffusers_host_ram_gb(
    available_vram_gb: float,
    *,
    text_encoder_gb: Optional[float] = None,
    transformer_gb: Optional[float] = None,
    transformer_streamed: bool = False,
    text_encoder_streamed: bool = False,
) -> float:
    """Host-RAM floor for offload tier from resident sizes; streamed denoiser counts twice, pinned still counts; a slab-arena pin passes False."""
    if available_vram_gb >= H3_DIFFUSERS_HOST_RAM_TIER_VRAM_GB and not transformer_streamed:
        return H3_DIFFUSERS_HOST_RAM_HIGH_VRAM_GB
    text_encoder = H3_TEXT_ENCODER_BF16_GB if text_encoder_gb is None else float(text_encoder_gb)
    transformer = H3_TRANSFORMER_BF16_GB if transformer_gb is None else float(transformer_gb)
    if (
        text_encoder_streamed
        and not transformer_streamed
        and _within_measured_streamed_set(text_encoder, transformer)
    ):
        # Both stream from reclaimable page cache, so the component sum overstates the floor.
        return H3_DIFFUSERS_HOST_RAM_STREAMED_SET_GB
    if transformer_streamed:
        transformer *= 2
    total = text_encoder + transformer + H3_VAE_RESIDENT_GB + H3_DIFFUSERS_HOST_RAM_HEADROOM_GB
    if text_encoder_streamed:
        total = max(total, H3_DIFFUSERS_HOST_RAM_STREAMED_RSS_GB)
    return total


def _within_measured_streamed_set(text_encoder_gb: float, transformer_gb: float) -> bool:
    """Whether a streamed load is no larger than the set ``H3_DIFFUSERS_HOST_RAM_STREAMED_SET_GB`` was measured on."""
    from .video_minimax_h3_te import H3_TE_QUANT_RESIDENT_GB
    return (
        text_encoder_gb <= H3_TE_QUANT_RESIDENT_GB["int8"] + 1e-6
        and transformer_gb <= max(H3_TRANSFORMER_PREQUANT_GB.values()) + 1e-6
    )


def h3_host_ram_shortfall(
    available_vram_gb: float,
    *,
    text_encoder_gb: Optional[float] = None,
    transformer_gb: Optional[float] = None,
    transformer_streamed: bool = False,
    text_encoder_streamed: bool = False,
) -> Optional[str]:
    """The refusal message when the host-RAM floor exceeds ``h3_host_capacity_bytes`` (free + already held), else
    None."""
    required_host_gb = estimate_h3_diffusers_host_ram_gb(
        available_vram_gb,
        text_encoder_gb = text_encoder_gb,
        transformer_gb = transformer_gb,
        transformer_streamed = transformer_streamed,
        text_encoder_streamed = text_encoder_streamed,
    )
    host_capacity_gb = h3_host_capacity_bytes() / 1_000_000_000
    if host_capacity_gb + 0.5 < required_host_gb:
        return (
            f"MiniMax-H3 needs about {required_host_gb:.0f} GB available "
            f"system RAM at this VRAM tier; {host_capacity_gb:.1f} GB is "
            "available. Load the GGUF artifact instead."
        )
    return None


# Extra picker tiers gated by kill switches: VRAM by UNSLOTH_H3_TE_STREAM (else catalog 30), RAM by UNSLOTH_DIFFUSION_PIN_ARENA (else catalog 80).
H3_DIFFUSERS_FIT_TIERS_ENV = "UNSLOTH_H3_DIFFUSERS_WIDE_TIERS"
H3_DIFFUSERS_CATALOG_TIER_GPU_GIB = 30.0
H3_DIFFUSERS_CATALOG_TIER_RAM_GIB = 80.0


def _h3_streamed_default_request_gpu_gib() -> float:
    from .video_families import detect_video_family

    fam = detect_video_family("MiniMaxAI/MiniMax-H3")
    width, height = fam.resolution_presets[0]
    floor_gb = estimate_h3_diffusers_vram_gb(
        width,
        height,
        fam.default_num_frames,
        transformer_streamed = True,
        text_encoder_streamed = True,
    )
    # Total VRAM in GiB, rounded up to half a GiB.
    return math.ceil(floor_gb * 1e9 / 2**30 * 2) / 2


def _h3_streamed_host_floor_gib(
    single_host_copy: bool, text_encoder_streamed: bool = False
) -> float:
    from .video_minimax_h3_te import H3_TE_QUANT_RESIDENT_GB
    floor_gb = estimate_h3_diffusers_host_ram_gb(
        0.0,
        text_encoder_gb = H3_TE_QUANT_RESIDENT_GB["int8"],
        transformer_gb = H3_TRANSFORMER_PREQUANT_GB["int8"],
        transformer_streamed = not single_host_copy,
        text_encoder_streamed = text_encoder_streamed,
    )
    # The picker reads available RAM in GiB; round up to the next whole GiB.
    return float(math.ceil(floor_gb * 1e9 / 2**30))


def h3_diffusers_fit_tiers() -> list[dict]:
    """Extra H3 Diffusers picker tiers; [] when UNSLOTH_H3_DIFFUSERS_WIDE_TIERS=0; must stay torch-free since /api/system polls it."""
    import os

    flag = os.environ.get(H3_DIFFUSERS_FIT_TIERS_ENV, "1").strip().lower()
    if flag in ("0", "false", "no", "off"):
        return []
    from .diffusion_pinned_arena import pin_arena_enabled
    from .video_minimax_h3_te import h3_te_stream_enabled

    te_streamed = h3_te_stream_enabled()
    single_copy = pin_arena_enabled()
    if not te_streamed and not single_copy:
        return []
    gpu_gib = (
        _h3_streamed_default_request_gpu_gib() if te_streamed else H3_DIFFUSERS_CATALOG_TIER_GPU_GIB
    )
    ram_gib = (
        _h3_streamed_host_floor_gib(True, text_encoder_streamed = te_streamed)
        if single_copy
        else H3_DIFFUSERS_CATALOG_TIER_RAM_GIB
    )
    return [{"gpu_gb": gpu_gib, "system_ram_gb": ram_gib, "requires_quantised_streaming": True}]


# autocast casts these modules' weights; norms and bare params must keep source precision.
_AUTOCAST_WEIGHT_MODULE_NAMES = ("Linear", "Conv1d", "Conv2d", "Conv3d")


def _module_bytes(module: Any) -> int:
    seen: set[int] = set()
    total = 0
    for tensor in list(module.parameters()) + list(module.buffers()):
        if id(tensor) in seen:
            continue
        seen.add(id(tensor))
        total += tensor.numel() * tensor.element_size()
    return total


def trim_h3_video_vae(vae: Any, *, workflow: str) -> dict[str, int]:
    """Pre-cast VAE weights to float16 so autocast keeps no float32 twin; drop encoder for t2va only; never raises, so renames cost the saving, not the render."""
    import torch

    # Lookups are getattr with defaults, so a None vae or moved attributes both report zero.
    report = {"encoder_freed": 0, "decoder_freed": 0}

    if workflow == "t2va":
        for name in ("encoder", "quant_conv"):
            module = getattr(vae, name, None)
            if module is None:
                continue
            report["encoder_freed"] += _module_bytes(module)
            setattr(vae, name, None)

    for holder in ("decoder", "post_quant_conv"):
        module = getattr(vae, holder, None)
        if module is None:
            continue
        before = _module_bytes(module)
        for sub in module.modules():
            if type(sub).__name__ not in _AUTOCAST_WEIGHT_MODULE_NAMES:
                continue
            for name, param in list(sub.named_parameters(recurse = False)):
                if param.dtype is not torch.float32:
                    continue
                setattr(
                    sub,
                    name,
                    torch.nn.Parameter(param.data.to(torch.float16), requires_grad = False),
                )
        report["decoder_freed"] += before - _module_bytes(module)

    return report


# MiniMax-H3's upstream canvas rule, shared by both engines.
H3_CANVAS_SHORT_EDGE = 768
H3_CANVAS_MAX_PIXELS = 768 * 1344
H3_CANVAS_MULTIPLE = 32
# Trained aspect-ratio range.
H3_MIN_ASPECT_RATIO = 1 / 4
H3_MAX_ASPECT_RATIO = 4

# Upstream stretches the first frame and center cover-crops the last.
H3_ANCHOR_FIRST = "first"
H3_ANCHOR_LAST = "last"


def h3_canvas_for_aspect(aspect_width: float, aspect_height: float) -> tuple[int, int]:
    """Canvas for an aspect ratio; ValueError outside the trained 1:4 to 4:1 range."""
    if aspect_width <= 0 or aspect_height <= 0:
        raise ValueError(
            f"The source image has no usable aspect ratio ({aspect_width}x{aspect_height})."
        )
    ratio = aspect_width / aspect_height
    if not H3_MIN_ASPECT_RATIO <= ratio <= H3_MAX_ASPECT_RATIO:
        raise ValueError(
            f"MiniMax-H3 supports aspect ratios from 1:4 to 4:1; this image is "
            f"{aspect_width:g}x{aspect_height:g} ({ratio:.2f}:1). Crop it first."
        )
    if ratio >= 1.0:
        width, height = H3_CANVAS_SHORT_EDGE * ratio, float(H3_CANVAS_SHORT_EDGE)
    else:
        width, height = float(H3_CANVAS_SHORT_EDGE), H3_CANVAS_SHORT_EDGE / ratio
    area = width * height
    if area > H3_CANVAS_MAX_PIXELS:
        scale = math.sqrt(H3_CANVAS_MAX_PIXELS / area)
        width, height = width * scale, height * scale
    from .video_families import snap_canvas_within_cap

    return snap_canvas_within_cap(width, height, H3_CANVAS_MULTIPLE, H3_CANVAS_MAX_PIXELS)


def fit_h3_keyframe(image: Any, width: int, height: int, *, anchor: str) -> Any:
    """Fit a keyframe using MiniMax-H3's asymmetric first/last-frame rules."""
    from PIL import Image

    target = (max(1, int(width)), max(1, int(height)))
    if anchor == H3_ANCHOR_FIRST:
        return image.resize(target, Image.LANCZOS)
    if anchor != H3_ANCHOR_LAST:
        raise ValueError(f"Unknown keyframe anchor {anchor!r}.")
    source_w, source_h = image.size
    scale = max(target[0] / source_w, target[1] / source_h)
    crop_w = min(source_w, math.ceil(target[0] / scale))
    crop_h = min(source_h, math.ceil(target[1] / scale))
    left = (source_w - crop_w) // 2
    top = (source_h - crop_h) // 2
    return image.resize(target, Image.LANCZOS, box = (left, top, left + crop_w, top + crop_h))


# Ref2VA uses a separate transformer partition selected at load time.
H3_TASK_KEYFRAMES = "fl2va"
H3_TASK_REFERENCES = "ref2va"

H3_MAX_REF_IMAGES = 9
H3_MAX_REF_VIDEOS = 3
H3_MAX_REF_AUDIOS = 3
H3_MAX_REFERENCES = 12
# A reference video's trained window, in seconds.
H3_REF_VIDEO_MIN_SECONDS = 2.0
H3_REF_VIDEO_MAX_SECONDS = 15.0
# Containers report the longest track, so allow this slack and hold the last frame.
H3_REF_TRIM_COVERAGE_SLACK_SECONDS = 0.5
H3_FPS = 24

# "match" uses the generation area. Diffusers-only "max" uses a 2048px short edge.
H3_REF_SIZE_MATCH = "match"
H3_REF_SIZE_MAX = "max"
H3_REF_IMAGE_SHORT_EDGE = 2048
# H3 downscales references immediately, so this path can accept larger bounded sources
H3_REF_IMAGE_SOURCE_MAX_SIDE = 8192
H3_REF_IMAGE_SOURCE_MAX_PIXELS = 32_000_000


def validate_h3_reference_trim(
    start_seconds: Optional[float], end_seconds: Optional[float]
) -> Optional[tuple[float, float]]:
    """Validate an explicit reference-media interval, or return None for the whole source."""
    if start_seconds is None and end_seconds is None:
        return None
    if start_seconds is None or end_seconds is None:
        raise ValueError("Reference video trim start and end must be provided together.")
    start, end = float(start_seconds), float(end_seconds)
    if not math.isfinite(start) or not math.isfinite(end) or start < 0 or end <= start:
        raise ValueError("Reference video trim must satisfy 0 <= start < end.")
    duration = end - start
    if duration + 1e-6 < H3_REF_VIDEO_MIN_SECONDS or duration - 1e-6 > H3_REF_VIDEO_MAX_SECONDS:
        raise ValueError(
            f"MiniMax-H3 reference video trims must be {H3_REF_VIDEO_MIN_SECONDS:g} to "
            f"{H3_REF_VIDEO_MAX_SECONDS:g} seconds; this one is {duration:.1f}s."
        )
    return start, end


def h3_transformer_task(filename: str) -> str:
    """Which H3 task a picked GGUF denoiser serves, from its published name."""
    name = Path(filename).name.lower()
    return H3_TASK_REFERENCES if name.startswith("minimax_h3_ref2va") else H3_TASK_KEYFRAMES


def h3_denoiser_component(task: Optional[str]) -> str:
    """Denoiser subfolder for a task: transformer_ref for references, else transformer; a wrong one pulls the dense 66.28 GB partition."""
    return (
        "transformer_ref" if (task or "").strip().lower() == H3_TASK_REFERENCES else "transformer"
    )


def fit_h3_reference_image(image: Any, *, width: int, height: int, policy: str) -> Any:
    """Scale a reference to its policy limit without changing its aspect ratio or upscaling."""
    from PIL import Image

    source_w, source_h = image.size
    if policy == H3_REF_SIZE_MAX:
        scale = min(1.0, H3_REF_IMAGE_SHORT_EDGE / max(1, min(source_w, source_h)))
    elif policy == H3_REF_SIZE_MATCH:
        scale = min(1.0, math.sqrt((width * height) / max(1, source_w * source_h)))
    else:
        raise ValueError(f"Unknown reference image size policy {policy!r}.")
    snap = lambda v: max(  # noqa: E731
        H3_CANVAS_MULTIPLE, round(v * scale / H3_CANVAS_MULTIPLE) * H3_CANVAS_MULTIPLE
    )
    return image.resize((snap(source_w), snap(source_h)), Image.LANCZOS)


def h3_reference_frame_size(source_w: int, source_h: int) -> tuple[int, int]:
    """Resolve a reference-video frame size without upscaling."""
    width, height = h3_canvas_for_aspect(source_w, source_h)
    if source_w * source_h < width * height:
        snap = lambda v: max(  # noqa: E731
            H3_CANVAS_MULTIPLE, round(v / H3_CANVAS_MULTIPLE) * H3_CANVAS_MULTIPLE
        )
        width, height = snap(source_w), snap(source_h)
    return width, height


def _open_reference_media(av: Any, blob: bytes) -> Any:
    # No protocols: a probed concat or HLS playlist would otherwise open the files it names.
    import io
    return av.open(io.BytesIO(blob), options = {"protocol_whitelist": "none"})


def decode_h3_reference_video(
    blob: bytes,
    *,
    trim_start_seconds: Optional[float] = None,
    trim_end_seconds: Optional[float] = None,
    decode_audio: bool = True,
) -> tuple[list, Optional[Any], Optional[int]]:
    """Decode one uploaded video to 24 fps frames plus its soundtrack, if it carries one.

    Returns ``(frames, waveform, sample_rate)``. The frames land on MiniMax-H3's own 24 fps by
    whole-frame drop and duplicate -- the selection ffmpeg's fps filter made in the reference
    implementation, and the one the Diffusers blocks make from a declared rate -- so both
    engines receive a stream that is already on the model's clock. The waveform is float32
    ``(samples, channels)`` at the container's own rate; both engines resample it themselves.
    ``decode_audio=False`` avoids touching an embedded track that a replacement will supersede.
    """
    import av
    import numpy as np

    trim = validate_h3_reference_trim(trim_start_seconds, trim_end_seconds)
    video_timeline_start = None
    if trim is None:
        frames, duration, video_timeline_start = _decode_h3_video_without_trim(blob, av)
    else:
        try:
            frames, video_timeline_start = _decode_h3_video_trim_by_timestamp(blob, av, trim)
        except _H3MediaTimestampsUnavailable:
            # Ordinal selection must restart because a seek makes frame zero keyframe-relative.
            frames, video_timeline_start = _decode_h3_video_trim_by_ordinal(blob, av, trim)
        duration = trim[1] - trim[0]
    if not frames or duration + 1e-6 < H3_REF_VIDEO_MIN_SECONDS:
        raise ValueError(
            f"MiniMax-H3 reference videos run {H3_REF_VIDEO_MIN_SECONDS:g} to "
            f"{H3_REF_VIDEO_MAX_SECONDS:g} seconds; this one is {duration:.1f}s."
        )
    expected_frames = int(round(duration * H3_FPS))
    if trim is not None and len(frames) < expected_frames:
        # Hold the last frame across a shortfall within the slack; a larger gap is a real error.
        if len(frames) + math.ceil(H3_REF_TRIM_COVERAGE_SLACK_SECONDS * H3_FPS) < expected_frames:
            raise ValueError("That reference video did not cover the selected range.")
        frames.extend([frames[-1]] * (expected_frames - len(frames)))
    frames = frames[:expected_frames]

    waveform, sample_rate = (None, None)
    if decode_audio:
        with _open_reference_media(av, blob) as container:
            if container.streams.audio:
                waveform, sample_rate = _decode_audio_stream(
                    container,
                    np,
                    trim_start_seconds = trim[0] if trim else None,
                    trim_end_seconds = trim[1] if trim else None,
                    timeline_start_seconds = video_timeline_start,
                    untrimmed_duration_seconds = len(frames) / H3_FPS if trim is None else None,
                )
    return frames, waveform, sample_rate


class _H3MediaTimestampsUnavailable(Exception):
    """Internal signal to retry a trim from the beginning using the declared rate."""


def _stream_start_seconds(stream: Any) -> Optional[float]:
    start_time = getattr(stream, "start_time", None)
    time_base = getattr(stream, "time_base", None)
    if start_time is None or time_base is None:
        return None
    return float(start_time * time_base)


def _frame_timestamp_seconds(frame: Any) -> Optional[float]:
    pts = getattr(frame, "pts", None)
    time_base = getattr(frame, "time_base", None)
    if pts is None or time_base is None:
        return None
    return float(pts * time_base)


def _seek_media(container: Any, stream: Any, absolute_seconds: float, *, label: str) -> bool:
    """Seek backward near an absolute stream timestamp when its time base permits it."""
    time_base = getattr(stream, "time_base", None)
    if time_base is None:
        return False
    offset = math.floor(absolute_seconds / float(time_base) + 1e-6)
    try:
        container.seek(offset, backward = True, any_frame = False, stream = stream)
    except Exception as exc:  # noqa: BLE001 -- decoder-specific seek errors become input feedback
        raise ValueError(f"Could not seek to the requested reference {label} trim start.") from exc
    return True


def _fit_h3_video_frame(
    frame: Any, fitted_size: Optional[tuple[int, int]]
) -> tuple[Any, tuple[int, int]]:
    from PIL import Image

    image = frame.to_image()
    if image.mode != "RGB":  # PyAV already returns a fresh RGB image; convert only copies it
        image = image.convert("RGB")
    if fitted_size is None:
        fitted_size = h3_reference_frame_size(*image.size)
    if image.size != fitted_size:
        image = image.resize(fitted_size, Image.LANCZOS)
    return image, fitted_size


def _decode_h3_video_without_trim(blob: bytes, av: Any) -> tuple[list, float, Optional[float]]:
    """Preserve the existing whole-file rate-based behavior and its 15-second refusal."""
    with _open_reference_media(av, blob) as container:
        if not container.streams.video:
            raise ValueError("That reference file carries no video track.")
        stream = container.streams.video[0]
        timeline_start = _stream_start_seconds(stream)
        source_fps = float(stream.average_rate or stream.guessed_rate or H3_FPS)
        if source_fps <= 0:
            source_fps = float(H3_FPS)
        max_source_frames = math.floor(H3_REF_VIDEO_MAX_SECONDS * source_fps + 1e-6)
        frames = []
        decoded_count = 0
        next_target = 0
        fitted_size = None
        for source_index, frame in enumerate(container.decode(video = 0)):
            decoded_count = source_index + 1
            if decoded_count > max_source_frames:
                raise ValueError(
                    f"MiniMax-H3 reference videos run {H3_REF_VIDEO_MIN_SECONDS:g} to "
                    f"{H3_REF_VIDEO_MAX_SECONDS:g} seconds; this one is longer than "
                    f"{H3_REF_VIDEO_MAX_SECONDS:g}s. Trim it first."
                )
            target_source = int(next_target * source_fps / H3_FPS)
            if target_source > source_index:
                continue
            image, fitted_size = _fit_h3_video_frame(frame, fitted_size)
            while int(next_target * source_fps / H3_FPS) <= source_index:
                frames.append(image)
                next_target += 1
    if decoded_count == 0:
        raise ValueError("That reference video decoded to no frames.")
    return frames, decoded_count / source_fps, timeline_start


def _decode_h3_video_trim_by_timestamp(
    blob: bytes, av: Any, trim: tuple[float, float]
) -> tuple[list, Optional[float]]:
    """Select an explicit interval from presentation timestamps and stop at its endpoint."""
    start, end = trim
    target_count = int(round((end - start) * H3_FPS))
    with _open_reference_media(av, blob) as container:
        if not container.streams.video:
            raise ValueError("That reference file carries no video track.")
        stream = container.streams.video[0]
        timeline_start = _stream_start_seconds(stream)
        if timeline_start is not None and start > 0:
            _seek_media(container, stream, timeline_start + start, label = "video")

        frames = []
        fitted_size = None
        candidate = None
        last_relative = None
        last_duration = None

        def _fill_until(relative_limit: float) -> None:
            nonlocal fitted_size
            if candidate is None:
                return
            wanted = min(
                target_count,
                max(0, math.ceil((relative_limit - start) * H3_FPS - 1e-6)),
            )
            if wanted <= len(frames):
                return
            image, fitted_size = _fit_h3_video_frame(candidate, fitted_size)
            frames.extend([image] * (wanted - len(frames)))

        for frame in container.decode(video = 0):
            timestamp = _frame_timestamp_seconds(frame)
            if timestamp is None:
                raise _H3MediaTimestampsUnavailable
            if timeline_start is None:
                # Without a declared start or seek, the first frame is the timeline origin.
                timeline_start = timestamp
            relative = timestamp - timeline_start
            if candidate is not None:
                _fill_until(relative)
                if len(frames) >= target_count:
                    return frames, timeline_start
            candidate = frame
            last_relative = relative
            duration = getattr(frame, "duration", None)
            time_base = getattr(frame, "time_base", None)
            last_duration = (
                float(duration * time_base)
                if duration is not None and time_base is not None and duration > 0
                else None
            )

        if candidate is None or last_relative is None:
            raise ValueError("That reference video decoded to no frames in the selected range.")
        declared_duration = getattr(stream, "duration", None)
        stream_time_base = getattr(stream, "time_base", None)
        source_end = (
            float(declared_duration * stream_time_base)
            if declared_duration is not None and stream_time_base is not None
            else last_relative + (last_duration or 0.0)
        )
        if source_end + H3_REF_TRIM_COVERAGE_SLACK_SECONDS < end:
            raise ValueError("Reference video trim ends after the source video.")
        _fill_until(end)
        if len(frames) < target_count:
            raise ValueError("That reference video decoded to no frames in the selected range.")
        return frames, timeline_start


def _decode_h3_video_trim_by_ordinal(
    blob: bytes, av: Any, trim: tuple[float, float]
) -> tuple[list, Optional[float]]:
    """Fallback for streams whose decoded frames carry no presentation timestamps."""
    with _open_reference_media(av, blob) as container:
        if not container.streams.video:
            raise ValueError("That reference file carries no video track.")
        stream = container.streams.video[0]
        source_fps = float(stream.average_rate or stream.guessed_rate or H3_FPS)
        if source_fps <= 0:
            source_fps = float(H3_FPS)
        # Start floors, exclusive end ceils: ceiling both skips the frame straddling a fractional start.
        start_source_frame = math.floor(trim[0] * source_fps + 1e-6)
        end_source_frame = math.ceil(trim[1] * source_fps - 1e-6)
        target_count = int(round((trim[1] - trim[0]) * H3_FPS))
        frames = []
        decoded_count = 0
        next_target = 0
        fitted_size = None
        for source_index, frame in enumerate(container.decode(video = 0)):
            decoded_count = source_index + 1
            if source_index < start_source_frame:
                continue
            if source_index >= end_source_frame:
                break
            selected_index = source_index - start_source_frame
            target_source = int(next_target * source_fps / H3_FPS)
            if target_source > selected_index:
                continue
            image, fitted_size = _fit_h3_video_frame(frame, fitted_size)
            while (
                len(frames) < target_count
                and int(next_target * source_fps / H3_FPS) <= selected_index
            ):
                frames.append(image)
                next_target += 1
        slack_frames = math.ceil(H3_REF_TRIM_COVERAGE_SLACK_SECONDS * source_fps)
        if decoded_count + slack_frames < end_source_frame:
            raise ValueError("Reference video trim ends after the source video.")
        if not frames:
            raise ValueError("That reference video decoded to no frames in the selected range.")
        return frames, _stream_start_seconds(stream)


def decode_h3_reference_audio(
    blob: bytes,
    *,
    trim_start_seconds: Optional[float] = None,
    trim_end_seconds: Optional[float] = None,
) -> tuple[Any, int]:
    """Decode one uploaded audio file to a float32 ``(samples, channels)`` waveform + its rate."""
    import av
    import numpy as np

    with _open_reference_media(av, blob) as container:
        if not container.streams.audio:
            raise ValueError("That reference file carries no audio track.")
        waveform, sample_rate = _decode_audio_stream(
            container,
            np,
            trim_start_seconds = trim_start_seconds,
            trim_end_seconds = trim_end_seconds,
        )
    if waveform is None:
        raise ValueError("That reference audio decoded to no samples.")
    return waveform, sample_rate


def _decode_audio_stream(
    container: Any,
    np: Any,
    *,
    trim_start_seconds: Optional[float] = None,
    trim_end_seconds: Optional[float] = None,
    timeline_start_seconds: Optional[float] = None,
    untrimmed_duration_seconds: Optional[float] = None,
) -> tuple[Optional[Any], Optional[int]]:
    """Decode first audio stream as float32 samples at native rate, incrementally to enforce H3's 15-second limit; untrimmed video caps audio at timeline."""
    import av

    trim = validate_h3_reference_trim(trim_start_seconds, trim_end_seconds)
    stream = container.streams.audio[0]
    sample_rate = int(stream.codec_context.sample_rate or 48_000)
    if trim is not None:
        try:
            return _decode_audio_trim_by_timestamp(
                container,
                stream,
                np,
                av,
                sample_rate,
                trim,
                timeline_start_seconds = timeline_start_seconds,
            )
        except _H3MediaTimestampsUnavailable:
            start_time = getattr(stream, "start_time", None)
            time_base = getattr(stream, "time_base", None)
            if time_base is None:
                raise ValueError(
                    "Reference audio timestamps are unavailable and its stream cannot be reset."
                ) from None
            try:
                container.seek(int(start_time or 0), backward = True, any_frame = False, stream = stream)
            except Exception as exc:  # noqa: BLE001 -- decoder-specific reset errors
                raise ValueError(
                    "Reference audio timestamps are unavailable and its stream cannot be reset."
                ) from exc

    resampler = av.AudioResampler(format = "flt", layout = stream.layout.name, rate = sample_rate)
    channels = len(stream.layout.channels)
    max_samples = math.floor(H3_REF_VIDEO_MAX_SECONDS * sample_rate + 1e-6)
    start_sample = math.floor(trim[0] * sample_rate + 1e-6) if trim else 0
    untrimmed_end_sample = (
        int(round(untrimmed_duration_seconds * sample_rate))
        if untrimmed_duration_seconds is not None
        else None
    )
    end_sample = math.floor(trim[1] * sample_rate + 1e-6) if trim else untrimmed_end_sample
    chunks = []
    source_total = 0

    def _take(resampled: Any) -> bool:
        nonlocal source_total
        block = resampled.to_ndarray().reshape(-1, channels)
        block_start = source_total
        block_end = block_start + block.shape[0]
        source_total = block_end
        if trim is None and untrimmed_duration_seconds is None and source_total > max_samples:
            raise ValueError(
                f"MiniMax-H3 reference audio runs up to {H3_REF_VIDEO_MAX_SECONDS:g} seconds; "
                f"this one is longer. Trim it first."
            )
        take_start = max(block_start, start_sample)
        take_end = min(block_end, end_sample) if end_sample is not None else block_end
        if take_start < take_end:
            chunks.append(block[take_start - block_start : take_end - block_start])
        # Clamp, not refuse: encoder padding overshoots routinely.
        return end_sample is not None and block_end >= end_sample

    stopped = False
    for frame in container.decode(audio = 0):
        for resampled in resampler.resample(frame):
            if _take(resampled):
                stopped = True
                break
        if stopped:
            break
    if not stopped:
        for resampled in resampler.resample(None):
            _take(resampled)
    # Short soundtracks are kept, not refused, as in the timestamp path above.
    if not chunks:
        return None, None
    return np.concatenate(chunks, axis = 0).astype("float32"), sample_rate


def _decode_audio_trim_by_timestamp(
    container: Any,
    stream: Any,
    np: Any,
    av: Any,
    sample_rate: int,
    trim: tuple[float, float],
    *,
    timeline_start_seconds: Optional[float],
) -> tuple[Any, int]:
    """Place decoded samples on the requested media timeline and stop at the endpoint."""
    start, end = trim
    origin = timeline_start_seconds
    if origin is None:
        origin = _stream_start_seconds(stream)
    if origin is not None and start > 0:
        _seek_media(container, stream, origin + start, label = "audio")

    channels = len(stream.layout.channels)
    target_count = int(round((end - start) * sample_rate))
    output = np.zeros((target_count, channels), dtype = "float32")
    resampler = av.AudioResampler(format = "flt", layout = stream.layout.name, rate = sample_rate)
    copied_any = False
    stopped = False

    def _take(resampled: Any) -> bool:
        nonlocal origin, copied_any
        timestamp = _frame_timestamp_seconds(resampled)
        if timestamp is None:
            raise _H3MediaTimestampsUnavailable
        if origin is None:
            origin = timestamp
        block = resampled.to_ndarray().reshape(-1, channels)
        block_start = timestamp - origin
        block_end = block_start + block.shape[0] / sample_rate
        if block_start >= end:
            return True
        destination_start = int(round((block_start - start) * sample_rate))
        source_start = max(0, -destination_start)
        destination_start = max(0, destination_start)
        take = min(block.shape[0] - source_start, target_count - destination_start)
        if take > 0:
            output[destination_start : destination_start + take] = block[
                source_start : source_start + take
            ]
            copied_any = True
        return block_end >= end

    for frame in container.decode(audio = 0):
        for resampled in resampler.resample(frame):
            if _take(resampled):
                stopped = True
                break
        if stopped:
            break
    if not stopped:
        for resampled in resampler.resample(None):
            if _take(resampled):
                break
    # No copied samples means no soundtrack; silence would hide the gap from positional pairing.
    if not copied_any:
        return None, None
    return output, sample_rate


def write_h3_reference_wav(path: Path, waveform: Any, sample_rate: int) -> None:
    """Write a reference waveform as the 16-bit PCM WAV sd-cli's --ref-audio loader reads."""
    import wave

    import numpy as np

    samples = np.clip(np.asarray(waveform, dtype = "float32"), -1.0, 1.0)
    if samples.ndim == 1:
        samples = samples[:, None]
    with wave.open(str(path), "wb") as handle:
        handle.setnchannels(int(samples.shape[1]))
        handle.setsampwidth(2)
        handle.setframerate(int(sample_rate))
        handle.writeframes((samples * 32767.0).astype("<i2").tobytes())


@dataclass(frozen = True)
class MiniMaxH3References:
    """Decoded references in model order: canvas-sized images in <Picture i> order, then videos, then standalone audio."""

    images: tuple = ()
    # (frames, waveform, sample_rate) per <Video k>; waveform is None when silent.
    videos: tuple = ()
    # (waveform, sample_rate) per standalone reference, in <Audio j> order.
    audios: tuple = ()

    def __bool__(self) -> bool:
        return bool(self.images or self.videos or self.audios)

    def count(self) -> int:
        return len(self.images) + len(self.videos) + len(self.audios)


@dataclass(frozen = True)
class DecodedReferenceAudios:
    """Untrimmed ``decode_h3_reference_audio`` results for ``sources``, reused only for those exact inputs."""

    sources: tuple = ()
    decoded: tuple = ()

    def for_inputs(self, audios: list) -> Optional[tuple]:
        return self.decoded if tuple(audios) == self.sources else None


@dataclass(frozen = True)
class DecodedReferenceImages:
    """One RGB image and its pre-EXIF dimensions per input slot."""

    entries: tuple = ()

    def pool(self) -> list:
        return list(self.entries)


def take_decoded_image(
    pool: Optional[list], source: str, *, max_side: int, max_pixels: Optional[int]
) -> Any:
    from .diffusion import decode_b64_image, refuse_oversized_image
    if pool:
        for index, (known, size, image) in enumerate(pool):
            if known is source or known == source:
                del pool[index]
                refuse_oversized_image(*size, max_side, max_pixels)
                return image
    return decode_b64_image(source, mode = "RGB", max_side = max_side, max_pixels = max_pixels)


@dataclass(frozen = True)
class MiniMaxH3StagedReferences:
    """``MiniMaxH3References`` written to disk the way sd-cli reads them back."""

    images: tuple[str, ...] = ()
    # frame DIRECTORIES: sd-cli reads a reference video as images sorted lexicographically
    videos: tuple[str, ...] = ()
    video_audios: tuple[str, ...] = ()
    audios: tuple[str, ...] = ()


# Pillow's zlib encoder releases the GIL, so a few threads write a reference video's PNGs in parallel.
H3_REF_FRAME_WRITERS = 4


def _write_h3_reference_frames(directory: Path, frames: Any) -> None:
    """Write ``frames`` as 00000.png onward, encoding a repeated frame object (24 fps fill) once."""
    import io
    from concurrent.futures import ThreadPoolExecutor

    # Keyed by identity: ``frames`` holds every object, so no id is reused while this runs.
    slots: dict[int, tuple[Any, list[Path]]] = {}
    for frame_index, frame in enumerate(frames):
        slots.setdefault(id(frame), (frame, []))[1].append(directory / f"{frame_index:05d}.png")

    def write(slot: tuple[Any, list[Path]]) -> None:
        frame, paths = slot
        if len(paths) == 1:
            frame.save(paths[0], format = "PNG", compress_level = 1)
            return
        buffer = io.BytesIO()
        frame.save(buffer, format = "PNG", compress_level = 1)
        data = buffer.getvalue()
        for path in paths:
            path.write_bytes(data)

    work = list(slots.values())
    workers = min(H3_REF_FRAME_WRITERS, len(work), os.cpu_count() or 1)
    if workers <= 1:
        for slot in work:
            write(slot)
        return
    pool = ThreadPoolExecutor(max_workers = workers, thread_name_prefix = "h3-ref-frames")
    try:
        futures = [pool.submit(write, slot) for slot in work]
        for future in futures:
            future.result()  # first failure in frame order, as the sequential loop raised
    finally:
        pool.shutdown(wait = True, cancel_futures = True)


def stage_h3_references(
    references: MiniMaxH3References, scratch: Path
) -> MiniMaxH3StagedReferences:
    """Video soundtracks must form a prefix, as sd-cli pairs audio to video by index position."""
    images: list[str] = []
    for index, image in enumerate(references.images):
        path = scratch / f"ref-image-{index:02d}.png"
        # Scratch files sd-cli decodes once: zlib level 1 is lossless and faster than Pillow's default.
        image.save(path, format = "PNG", compress_level = 1)
        images.append(str(path))

    videos: list[str] = []
    video_audios: list[str] = []
    pairing_holds = True
    for index, (frames, waveform, sample_rate) in enumerate(references.videos):
        directory = scratch / f"ref-video-{index:02d}"
        directory.mkdir()
        _write_h3_reference_frames(directory, frames)
        videos.append(str(directory))
        if waveform is None:
            # Positional pairing cannot express "skip this one", so stop pairing here.
            pairing_holds = False
            continue
        if not pairing_holds:
            raise ValueError(
                "stable-diffusion.cpp reference-video soundtracks must form a leading "
                "sequence without silent gaps."
            )
        path = scratch / f"ref-video-audio-{index:02d}.wav"
        write_h3_reference_wav(path, waveform, sample_rate)
        video_audios.append(str(path))

    audios: list[str] = []
    for index, (waveform, sample_rate) in enumerate(references.audios):
        path = scratch / f"ref-audio-{index:02d}.wav"
        write_h3_reference_wav(path, waveform, sample_rate)
        audios.append(str(path))

    return MiniMaxH3StagedReferences(
        images = tuple(images),
        videos = tuple(videos),
        video_audios = tuple(video_audios),
        audios = tuple(audios),
    )


def h3_diffusers_references(references: MiniMaxH3References) -> list:
    """Convert to Diffusers reference dataclasses in order; each rate travels with its own media."""
    import torch
    from diffusers.modular_pipelines.minimax_h3 import (
        MiniMaxH3AudioReference,
        MiniMaxH3ImageReference,
        MiniMaxH3VideoReference,
    )

    def waveform_tensor(waveform: Any) -> Any:
        # the blocks take a (channels, samples) tensor; the decoder produces (samples, channels)
        return torch.from_numpy(waveform).transpose(0, 1).contiguous()

    built: list = []
    for image in references.images:
        built.append(MiniMaxH3ImageReference(image = image))
    for frames, waveform, sample_rate in references.videos:
        built.append(
            MiniMaxH3VideoReference(
                frames = list(frames),
                fps = float(H3_FPS),
                audio = None if waveform is None else waveform_tensor(waveform),
                sample_rate = sample_rate,
            )
        )
    for waveform, sample_rate in references.audios:
        built.append(
            MiniMaxH3AudioReference(audio = waveform_tensor(waveform), sample_rate = sample_rate)
        )
    return built


def h3_conditioning_mode(
    *,
    has_first: bool = False,
    has_last: bool = False,
    has_references: bool = False,
) -> str:
    """Task name for a request's conditioning, as MiniMax-H3 and sd.cpp spell it; stored on the clip."""
    if has_references:
        return H3_TASK_REFERENCES
    if has_first and has_last:
        return H3_TASK_KEYFRAMES
    if has_first:
        return "i2va"
    if has_last:
        return "l2va"
    return "t2va"


def is_h3_native(family: Any, kind: str) -> bool:
    return getattr(family, "name", None) == "minimax-h3" and kind == "gguf"


def h3_text_encoder_filename(transformer_filename: str) -> str:
    return H3_QWEN_Q2 if "-q2_" in transformer_filename.lower() else H3_QWEN_Q4


def validate_h3_transformer_filename(filename: str) -> None:
    """Only the fl2va and ref2va denoisers are valid; the encoder and VAEs are companions, not denoisers."""
    name = Path(filename).name.lower()
    partitions = ("minimax_h3_fl2va", "minimax_h3_ref2va")
    if not name.startswith(partitions) or not name.endswith(".gguf"):
        raise ValueError(
            "MiniMax-H3 needs a minimax_h3_fl2va*.gguf transformer (text-to-video and "
            "first/last-frame video) or a minimax_h3_ref2va*.gguf one (reference video). The "
            "Qwen encoder and the VAEs are companion models, not picks for either."
        )


def _h3_role(filename: str) -> str:
    return {
        H3_VIDEO_VAE: "video VAE",
        H3_AUDIO_VAE: "audio VAE",
        H3_QWEN_Q2: "text encoder",
        H3_QWEN_Q4: "text encoder",
    }.get(filename, "denoiser")


def h3_offline_miss_error(repo_id: str, filename: str) -> RuntimeError:
    """A cache-only load (offline, or an auto-switch) missing an H3 file, e.g. VAEs cached before the vae/official/ move."""
    return RuntimeError(
        f"MiniMax-H3 needs its {_h3_role(filename)} ({filename}) from {repo_id}, and it is not in the local "
        "Hugging Face cache. This load may only use cached files (offline, or a load Studio started on its own), "
        "so it could not download it. Load MiniMax-H3 once while online (or reconnect) so Studio can fetch it; "
        "after that it loads offline."
    )


def h3_download_error(repo_id: str, filename: str, exc: Exception) -> Exception:
    """Returns (never raises) an H3 access error naming repo and component, since private/gated look like not-found; other errors pass through unchanged."""
    from huggingface_hub.errors import GatedRepoError, RepositoryNotFoundError

    if not isinstance(exc, (RepositoryNotFoundError, GatedRepoError)):
        return exc

    role = _h3_role(filename)
    gated = isinstance(exc, GatedRepoError)
    detail = (
        "accept its licence on the Hub, then set a token in Settings"
        if gated
        else "it may be private or not published yet, or your token may not cover it"
    )
    return RuntimeError(
        f"MiniMax-H3 could not download its {role} ({filename}) from {repo_id}: {detail}. "
        f"The other H3 components are unaffected."
    )


def h3_component_source(*files: str) -> str:
    """The repo to fetch the shared VAEs from: always ``H3_COMPONENT_REPO``.

    An install that pulled them from the Comfy-Org repack before the move re-downloads them from here once: a video
    load never reads from a Comfy repack, not even bytes already cached under one. ``files`` is kept so the callers
    that ask per file need not change."""
    del files
    return H3_COMPONENT_REPO


def h3_component_metadata_repo(repo_id: str) -> str:
    """Which repo to read a shared VAE's SIZE from: the repo its bytes come from (kept for the callers)."""
    return repo_id


# Resident peak is the four files + ~1 GiB; the estimate adds the compute buffer anyway.
H3_NATIVE_RESIDENT_ENV = "UNSLOTH_H3_NATIVE_RESIDENT"
# Unsloth sd.cpp fork: quantized matmuls with >= this many rows run BF16 cuBLAS instead of int8 MMQ. Unset/0 = MMQ.
H3_QUANT_CUBLAS_ENV = "GGML_CUDA_QUANT_CUBLAS_MIN_BATCH"
H3_QUANT_CUBLAS_MIN_BATCH = "1024"
# The fork's own floor (bf16_mma_hardware_available); below it the env changes nothing.
H3_QUANT_CUBLAS_MIN_CC = (8, 0)


def h3_quant_cublas_env(
    cuda_cc: "Optional[tuple[int, int]]",
    *,
    sage: bool,
    environ: Optional[dict] = None,
) -> tuple[tuple[str, str], ...]:
    """sd-cli env for the BF16 cuBLAS route: known sm80+ always, known older never, unknown
    (``cuda_cc`` None) only with sage. A user-exported value (0 included) always wins."""
    environ = os.environ if environ is None else environ
    if H3_QUANT_CUBLAS_ENV in environ:
        return ()
    if cuda_cc is not None:
        take = tuple(cuda_cc) >= H3_QUANT_CUBLAS_MIN_CC
    else:
        take = sage
    return ((H3_QUANT_CUBLAS_ENV, H3_QUANT_CUBLAS_MIN_BATCH),) if take else ()


# Denoiser compute buffer at 960x544x124, from sd-cli's log; scaled by pixel volume.
H3_NATIVE_DIT_COMPUTE_BYTES_H1 = int(5.4 * 1024**3)
H3_NATIVE_H1_PIXEL_VOLUME = 960 * 544 * 124
H3_NATIVE_RESIDENT_MARGIN_BYTES = 2 * 1024**3
_H3_STREAM_ONLY_FLAGS = ("--offload-to-cpu", "--stream-layers")


def h3_native_compute_bytes(width: int, height: int, frames: int) -> int:
    volume = max(1, int(width)) * max(1, int(height)) * max(1, int(frames))
    return math.ceil(H3_NATIVE_DIT_COMPUTE_BYTES_H1 * max(1.0, volume / H3_NATIVE_H1_PIXEL_VOLUME))


def h3_native_resident_bytes(file_bytes: int, width: int, height: int, frames: int) -> int:
    return (
        int(file_bytes)
        + h3_native_compute_bytes(width, height, frames)
        + H3_NATIVE_RESIDENT_MARGIN_BYTES
    )


def h3_native_render_flags(
    offload_flags: "tuple[str, ...] | list[str]",
    *,
    memory_mode: Optional[str],
    free_bytes: Optional[int],
    need_bytes: Optional[int],
    env: Optional[dict] = None,
) -> tuple[list[str], bool]:
    """Flags for one render and whether it runs resident: only memory auto, only when the live free VRAM covers
    the estimate; anything unknown keeps the committed flags."""
    flags = list(offload_flags)
    environ = env if env is not None else os.environ
    if str(environ.get(H3_NATIVE_RESIDENT_ENV, "")).strip().lower() in ("0", "false", "no", "off"):
        return flags, False
    if (memory_mode or "auto") != "auto" or "--offload-to-cpu" not in flags:
        return flags, False
    if free_bytes is None or need_bytes is None or int(free_bytes) < int(need_bytes):
        return flags, False
    return [f for f in flags if f not in _H3_STREAM_ONLY_FLAGS], True


# --offload-to-cpu pins GPU-run weights in the device host buffer (GTT on Vulkan/radv, capped by TTM pages_limit,
# overflow = "device lost"); --clip-on-cpu modules use plain RAM. Measured Q4_K, 864x480x124: 31.35 vs 15.49 GiB pinned.
H3_NATIVE_PINNED_MARGIN_BYTES = 1 << 30
# sd-cli's own host use beyond the weights (CPU compute buffers, decoded frames, audio), and Studio itself.
H3_NATIVE_HOST_OVERHEAD_BYTES = 3 << 30
H3_NATIVE_FIT_ENV = "UNSLOTH_H3_NATIVE_FIT_CHECK"
# Published sizes of the smallest pair (minimax_h3_fl2va_pruned-Q2_K + its Q2_K_M encoder), for the refusal text.
H3_NATIVE_Q2_PAIR_BYTES = (int(6.26 * 1024**3), int(12.2 * 1024**3))


def _sysfs_int(path: Path) -> Optional[int]:
    try:
        return int(path.read_text(encoding = "utf-8").strip(), 0)
    except (OSError, ValueError):
        return None


def _sysfs_pci_slot(device_dir: Path) -> Optional[str]:
    """``DDDD:BB:DD.F`` of a DRM card's PCI device, lower-cased, or None."""
    try:
        for line in (device_dir / "uevent").read_text(encoding = "utf-8").splitlines():
            if line.startswith("PCI_SLOT_NAME="):
                return line.split("=", 1)[1].strip().lower() or None
    except OSError:
        pass
    try:
        name = Path(os.path.realpath(device_dir)).name.lower()
    except OSError:
        return None
    return name if name.count(":") == 2 else None


def h3_native_fit_check_enabled(env: Optional[dict] = None) -> bool:
    """The one kill switch for every H3 native memory guard (UNSLOTH_H3_NATIVE_FIT_CHECK=0 turns them all off)."""
    environ = env if env is not None else os.environ
    return str(environ.get(H3_NATIVE_FIT_ENV, "")).strip().lower() not in (
        "0",
        "false",
        "no",
        "off",
    )


def amdgpu_gtt_reading(
    pci_slot: Optional[str] = None, sysfs_root: str = "/sys"
) -> "tuple[Optional[int], bool]":
    """``(free GTT, use known)`` from ONE pass over sysfs, so both halves describe the same reading.

    TTM's page limit is shared by every amdgpu device, so what is left is the pool's size less the GTT used on ALL
    amdgpu cards, not only on the selected one. The pool's size is the ``mem_info_gtt_total`` of the card at
    ``pci_slot`` (``DDDD:BB:DD.F``, or ``DDDD:BB:DD`` for any function), or the smallest total when the slot is
    unknown; that bound is never above the selected card's own ``total - used``. A card whose use cannot be read
    makes ``use known`` False. ``(None, True)`` when no amdgpu card, or none at that slot, reports a total."""
    want = pci_slot.lower() if pci_slot else None
    selected_total: Optional[int] = None
    smallest_total: Optional[int] = None
    used_all = 0
    known = True
    for total_path in Path(sysfs_root, "class", "drm").glob("card*/device/mem_info_gtt_total"):
        device = total_path.parent
        if _sysfs_int(device / "vendor") != 0x1002:
            continue
        total = _sysfs_int(total_path)
        if not total or total <= 0:
            continue
        used = _sysfs_int(device / "mem_info_gtt_used")
        if used is None or used < 0:
            known = False
            used = 0
        used_all += used
        smallest_total = total if smallest_total is None else min(smallest_total, total)
        if want is not None:
            slot = _sysfs_pci_slot(device)
            if slot == want or (slot or "").startswith(want + "."):
                selected_total = total if selected_total is None else min(selected_total, total)
    pool = selected_total if want is not None else smallest_total
    if pool is None:
        return None, True
    return max(pool - used_all, 0), known


def amdgpu_vram_free_bytes(
    pci_slot: Optional[str] = None, sysfs_root: str = "/sys"
) -> Optional[int]:
    """Free VRAM of the amdgpu card at pci_slot, or the sole one; None without both readings."""
    want = pci_slot.lower() if pci_slot else None
    found: list[int] = []
    for total_path in Path(sysfs_root, "class", "drm").glob("card*/device/mem_info_vram_total"):
        device = total_path.parent
        if _sysfs_int(device / "vendor") != 0x1002:
            continue
        if want is not None:
            slot = _sysfs_pci_slot(device)
            if not (slot == want or (slot or "").startswith(want + ".")):
                continue
        total = _sysfs_int(total_path)
        used = _sysfs_int(device / "mem_info_vram_used")
        if total is None or used is None:
            return None
        found.append(max(total - used, 0))
    return found[0] if len(found) == 1 else None


def amdgpu_gtt_free_bytes(
    pci_slot: Optional[str] = None, sysfs_root: str = "/sys"
) -> Optional[int]:
    return amdgpu_gtt_reading(pci_slot, sysfs_root)[0]


def amdgpu_gtt_used_unknown(pci_slot: Optional[str] = None, sysfs_root: str = "/sys") -> bool:
    return not amdgpu_gtt_reading(pci_slot, sysfs_root)[1]


def vulkan_device_is_amd(description: Optional[str]) -> bool:
    """Whether a ggml Vulkan device description names an AMD GPU (RADV, AMDVLK, or the Radeon marketing name)."""
    text = (description or "").lower()
    return any(token in text for token in ("radv", "amd", "radeon"))


class H3NativeMemoryRefusal(RuntimeError):
    """A render refused because it cannot fit; its message is built only from fixed text and sizes."""


def h3_native_offloaded_render_flags(
    render_flags: "list[str]",
    *,
    render_resident: bool,
    offloaded_flags: Optional["tuple[str, ...]"],
    offload_refusal: Optional[str],
) -> list[str]:
    """The flags a render runs with once Auto has chosen between resident and offloaded: a resident render keeps
    its own, an offloaded one takes the GTT-fitted set the load prepared, or is refused when none fits."""
    if render_resident or "--offload-to-cpu" not in render_flags:
        return list(render_flags)
    if offload_refusal:
        raise H3NativeMemoryRefusal(offload_refusal)
    return list(offloaded_flags) if offloaded_flags else list(render_flags)


@dataclass(frozen = True)
class H3NativeFit:
    flags: tuple[str, ...]
    # Why the flags changed, for the log and the resolved record; None when they did not.
    note: Optional[str] = None
    # A user-facing reason to refuse the load, or None.
    refusal: Optional[str] = None
    # The --max-vram value a UMA device needs (its budget less the pinned weights), or None to keep the committed one.
    max_vram: Optional[str] = None


def h3_native_with_max_vram(
    flags: "tuple[str, ...] | list[str]", value: Optional[str]
) -> list[str]:
    """``flags`` with the value after ``--max-vram`` replaced by ``value`` (unchanged when None or absent)."""
    out = list(flags)
    if value is not None:
        for i in range(len(out) - 1):
            if out[i] == "--max-vram":
                out[i + 1] = value
    return out


def _gib(value: int) -> str:
    return f"{value / 1024**3:.1f} GiB"


def h3_native_memory_fit(
    flags: "tuple[str, ...] | list[str]",
    *,
    accelerator: Optional[str],
    memory_mode: Optional[str],
    dit_bytes: int,
    te_bytes: int,
    vae_bytes: int,
    pinned_free_bytes: Optional[int],
    host_ram_bytes: Optional[int],
    host_swap_bytes: int = 0,
    pinned_used_unknown: bool = False,
    device_spill_bytes: int = 0,
    reserve_pinned: bool = False,
    env: Optional[dict] = None,
) -> H3NativeFit:
    """Fit offloaded sd-cli flags to the host: pinned weights must fit RAM alone (swap covers only CPU-run modules)
    and ``pinned_free_bytes`` (free GTT, None skips). ``device_spill_bytes`` is the part of the render's device memory
    that VRAM cannot hold, which a Vulkan build takes from GTT too. ``reserve_pinned`` (a UMA device, whose free memory
    sd.cpp reads before it pins anything) sets ``--max-vram`` to reserve the pinned weights. ``auto`` may move the text
    encoder to the CPU; else refuse."""
    flags = tuple(flags)
    if not h3_native_fit_check_enabled(env):
        return H3NativeFit(flags)
    if "--offload-to-cpu" not in flags:
        return H3NativeFit(flags)
    mode = memory_mode or "auto"
    vae_on_cpu = "--vae-on-cpu" in flags
    te_given = "--clip-on-cpu" in flags
    total = dit_bytes + te_bytes + vae_bytes
    overhead = H3_NATIVE_HOST_OVERHEAD_BYTES
    swap = max(int(host_swap_bytes or 0), 0)
    vulkan_gtt = (accelerator or "").strip().lower() == "vulkan" and pinned_free_bytes is not None
    budget = int(pinned_free_bytes) - H3_NATIVE_PINNED_MARGIN_BYTES if vulkan_gtt else None
    spill = max(int(device_spill_bytes or 0), 0) if vulkan_gtt else 0
    activations = (
        f" That includes about {_gib(spill)} of activations, which this GPU keeps in the same memory as the "
        f"weights; they grow with resolution and length."
        if spill
        else ""
    )
    mapped = "weights and activations" if spill else "weights"

    def pinned(te_on_cpu: bool) -> int:
        return spill + dit_bytes + (0 if te_on_cpu else te_bytes) + (0 if vae_on_cpu else vae_bytes)

    def host_problem(te_on_cpu: bool) -> Optional[str]:
        if host_ram_bytes is None:
            return None
        if pinned(te_on_cpu) + overhead > host_ram_bytes:
            return "pinned"
        if total + spill + overhead > host_ram_bytes + swap:
            return "total"
        return None

    def gtt_ok(te_on_cpu: bool) -> bool:
        if budget is None:
            return True
        # Unreadable GTT use: the pool is only an upper bound, so admit only a user-chosen small set (Low VRAM).
        return pinned(te_on_cpu) <= budget and (te_given or not pinned_used_unknown)

    def ok(te_on_cpu: bool) -> bool:
        return host_problem(te_on_cpu) is None and gtt_ok(te_on_cpu)

    def admit(
        fitted: tuple[str, ...],
        te_on_cpu: bool,
        note: Optional[str] = None,
    ) -> H3NativeFit:
        # Only where GTT was read: without sysfs (Windows) nothing measured the pool the reserve is taken from.
        if not (reserve_pinned and vulkan_gtt and "--max-vram" in fitted):
            return H3NativeFit(fitted, note = note)
        # A negative --max-vram reserves that much of the free memory sd.cpp reads at startup.
        reserve = pinned(te_on_cpu) - spill + H3_NATIVE_PINNED_MARGIN_BYTES
        value = f"-{reserve / 1024**3:.2f}"
        return H3NativeFit(tuple(h3_native_with_max_vram(fitted, value)), note = note, max_vram = value)

    if ok(te_given):
        return admit(flags, te_given)
    ram = _gib(int(host_ram_bytes)) if host_ram_bytes is not None else "unknown"
    limit = _gib(int(pinned_free_bytes)) if vulkan_gtt else None
    if (
        pinned_used_unknown
        and budget is not None
        and not te_given
        and host_problem(True) is None
        and pinned(True) <= budget
    ):
        # Fail closed (Auto included) while the encoder stays on the GPU: free GTT is unknowable.
        return H3NativeFit(
            flags,
            refusal = (
                f"MiniMax-H3 GGUF could not read how much of this card's GPU-accessible system memory (GTT) is in "
                f"use, so it cannot check that the {_gib(pinned(False))} it maps here fits the {limit} pool. Set "
                f"Memory mode to Low VRAM, which runs the text encoder on the CPU ({_gib(pinned(True))})."
            ),
        )
    if not te_given and ok(True):
        if not gtt_ok(False):
            note = (
                f"text encoder on the CPU: the Vulkan build keeps GPU-run weights in GPU-mapped system memory "
                f"(GTT), {_gib(pinned(False))} here against {limit} free"
            )
            refusal = (
                f"MiniMax-H3 GGUF cannot run in this memory mode on the Vulkan build: it maps "
                f"{_gib(pinned(False))} of {mapped} into GPU-accessible system memory (GTT), and {limit} of it is "
                f"free. Set Memory mode to Auto or Low VRAM, which runs the text encoder on the CPU "
                f"({_gib(pinned(True))}).{activations}"
            )
        else:
            note = (
                f"text encoder on the CPU: GPU-run weights are held in page-locked system RAM that cannot be "
                f"swapped, {_gib(pinned(False) + overhead)} here against {ram} of RAM available"
            )
            refusal = (
                f"MiniMax-H3 GGUF cannot run in this memory mode: it locks {_gib(pinned(False) + overhead)} of "
                f"{mapped} in system RAM, which cannot be swapped, and {ram} of RAM is available. Set Memory mode "
                f"to Auto or Low VRAM, which runs the text encoder on the CPU ({_gib(pinned(True) + overhead)} "
                f"locked)."
            )
        if mode == "auto":
            return admit(flags + ("--clip-on-cpu",), True, note)
        return H3NativeFit(flags, refusal = refusal)
    q2_dit, q2_te = H3_NATIVE_Q2_PAIR_BYTES
    q2_pinned = spill + q2_dit + (0 if vae_on_cpu else vae_bytes)
    q2_total = spill + q2_dit + q2_te + vae_bytes + overhead
    problem = host_problem(True)
    if problem == "total":
        smaller = (
            f" The Q2_K denoiser (with its Q2_K_M encoder) needs about {_gib(q2_total)}."
            if q2_total < total + spill + overhead
            else ""
        )
        return H3NativeFit(
            flags,
            refusal = (
                f"MiniMax-H3 GGUF keeps its denoiser, text encoder and VAEs in system RAM while it renders: about "
                f"{_gib(total + spill + overhead)} for this quant, and {ram} of RAM plus {_gib(swap)} of swap is "
                f"available. Close other applications or load a smaller quant.{smaller}{activations}"
            ),
        )
    if problem == "pinned":
        smaller = (
            f" The Q2_K denoiser locks about {_gib(q2_pinned + overhead)} with Memory mode Low VRAM."
            if q2_pinned < pinned(True)
            else ""
        )
        return H3NativeFit(
            flags,
            refusal = (
                f"MiniMax-H3 GGUF locks the {mapped} of its GPU-run parts in system RAM, which cannot be swapped: "
                f"about {_gib(pinned(True) + overhead)} even with the text encoder on the CPU, and {ram} of RAM "
                f"is available. Close other applications or load a smaller quant.{smaller}{activations}"
            ),
        )
    smaller = (
        f" The Q2_K denoiser needs about {_gib(q2_pinned)} with Memory mode Low VRAM."
        if budget is not None and q2_pinned <= budget
        else ""
    )
    return H3NativeFit(
        flags,
        refusal = (
            f"MiniMax-H3 GGUF does not fit this system on the Vulkan build: even with the text encoder on the CPU it "
            f"maps {_gib(pinned(True))} of {mapped} into GPU-accessible system memory (GTT), and {limit} of it is free "
            f"(the pool is half of system RAM by default; raise it with the ttm.pages_limit kernel parameter).{smaller}"
            f"{activations}"
        ),
    )


@dataclass(frozen = True)
class H3NativeFitInputs:
    """What ``h3_native_live_fit`` needs that does not change between renders, resolved once at load (the device
    listing and torch PCI reading included), so a re-fit reads only files."""

    base_flags: tuple[str, ...]  # the committed offload flags BEFORE the device pin
    accelerator: Optional[str]
    check_gtt: bool
    gtt_pci_slot: Optional[str]
    dit_bytes: int
    te_bytes: int
    vae_bytes: int
    device_name: Optional[str]
    # ggml-vulkan's "uma: 1": device memory and the pinned weights come from one pool.
    uma: bool = False


def h3_native_host_budgets() -> "tuple[Optional[int], int]":
    """(RAM, swap) a native render may still take: RAM cgroup-capped, without Studio's own RSS, and on cgroup v1 no
    more than the RAM+swap (memsw) headroom; swap bounded by the cgroup against that RAM budget, so the two never
    sum past what the cgroup can charge. (None, 0) only when RAM cannot be read; unreadable swap is 0 swap."""
    try:
        ram = h3_native_host_available_bytes()
    except Exception:  # noqa: BLE001 - an unreadable reading skips the host check
        return None, 0
    from utils.host_memory import cgroup_swap_allowance_bytes, cgroup_v1_memsw_headroom_bytes

    try:
        combined = cgroup_v1_memsw_headroom_bytes()
    except Exception:  # noqa: BLE001
        combined = None
    if combined is not None:
        ram = min(ram, combined)
    try:
        import psutil
        free_swap = int(psutil.swap_memory().free)
    except Exception:  # noqa: BLE001 - no swap reading: count none, keep the RAM check
        free_swap = 0
    try:
        swap = cgroup_swap_allowance_bytes(free_swap, ram_budget = ram)
    except Exception:  # noqa: BLE001
        swap = 0
    return ram, swap


def h3_native_live_fit(
    inputs: H3NativeFitInputs,
    memory_mode: Optional[str],
    compute_bytes: Optional[int] = None,
) -> H3NativeFit:
    """``h3_native_memory_fit`` on live RAM, swap, GTT and VRAM readings: /proc, cgroup and sysfs files only.
    ``compute_bytes`` is the render's denoiser compute buffer; None leaves activations out."""
    ram, swap = h3_native_host_budgets()
    gtt_free, gtt_known = (
        amdgpu_gtt_reading(inputs.gtt_pci_slot) if inputs.check_gtt else (None, True)
    )
    if inputs.check_gtt and gtt_free is None and inputs.gtt_pci_slot:
        # The device is AMD but its slot matched no amdgpu card: read the tightest card rather than skip the check.
        gtt_free, gtt_known = amdgpu_gtt_reading(None)
    spill = 0
    if inputs.check_gtt and inputs.uma and compute_bytes:
        # What the carve-out cannot hold of the compute buffer comes from GTT. A segment's weights come on top, but
        # sd.cpp's own capacity check reports that remainder, so only the compute buffer is charged here.
        # An unreadable or ambiguous carve-out (several cards, no slot) holds none of it, like the tightest GTT.
        vram_free = amdgpu_vram_free_bytes(inputs.gtt_pci_slot) or 0
        spill = max(int(compute_bytes) - vram_free, 0)
    return h3_native_memory_fit(
        inputs.base_flags,
        accelerator = inputs.accelerator,
        memory_mode = memory_mode,
        dit_bytes = inputs.dit_bytes,
        te_bytes = inputs.te_bytes,
        vae_bytes = inputs.vae_bytes,
        pinned_free_bytes = gtt_free,
        pinned_used_unknown = not gtt_known,
        host_ram_bytes = ram,
        host_swap_bytes = swap,
        device_spill_bytes = spill,
        reserve_pinned = inputs.check_gtt and inputs.uma,
    )


def h3_native_render_overhead_refusal() -> Optional[str]:
    """Why a render that places no new weights (a reused server, or a resident render) cannot start: live
    available RAM (``h3_native_host_budgets``) below the per-render host overhead. None when it fits or RAM cannot
    be read. File reads only."""
    if not h3_native_fit_check_enabled():
        return None
    ram, _swap = h3_native_host_budgets()
    if ram is None or ram >= H3_NATIVE_HOST_OVERHEAD_BYTES:
        return None
    return (
        f"A MiniMax-H3 render needs about {_gib(H3_NATIVE_HOST_OVERHEAD_BYTES)} of free system RAM for its frames, "
        f"audio and CPU buffers, and {_gib(ram)} is available. Close other applications and try again."
    )


H3_NATIVE_RENDER_RUNNING_HINT = " A render on the model being replaced is still running and holds that memory; try again after it finishes."


def h3_native_hub_files(transformer_filename: str) -> tuple[tuple[str, str], ...]:
    validate_h3_transformer_filename(transformer_filename)
    return (
        (H3_GGUF_REPO, transformer_filename),
        (H3_GGUF_REPO, h3_text_encoder_filename(transformer_filename)),
        (h3_component_source(H3_VIDEO_VAE), H3_VIDEO_VAE),
        (h3_component_source(H3_AUDIO_VAE), H3_AUDIO_VAE),
    )


@dataclass(frozen = True)
class MiniMaxH3NativeRuntime:
    engine: Any
    files: Any
    offload_flags: tuple[str, ...]
    # sd-cli identity taken at load; every generation compares against it since an install can replace the binary in place; None means cannot vouch.
    binary_identity: Optional[tuple[int, int]] = None
    # The card the load resolved, kept for failure records: re-resolving at failure time can read None.
    selected_card: Optional[str] = None
    env: tuple[tuple[str, str], ...] = ()
    # sd_cpp_cudnn.CudnnAttention; its env is already in ``env``.
    cudnn: Any = None
    # H3NativeServerSlot, or None for one-shot sd-cli only.
    server_slot: Any = None
    # Auto only: the GTT-fitted flags an OFFLOADED render runs with, and the refusal when none fits.
    offloaded_flags: Optional[tuple[str, ...]] = None
    offload_refusal: Optional[str] = None
    # Auto only: re-fit inputs, so an offloaded render is judged on live readings rather than the load's.
    fit_inputs: Any = None
    # Free VRAM now (bytes or ``{device: bytes}``), read per launch for the explicit ``--max-vram`` budget.
    vram_free_probe: Optional[Callable[[], Any]] = None
    vram_reserve_probe: Optional[Callable[[], Optional[int]]] = None


# 0 / false / off: every render on a fresh one-shot sd-cli.
H3_NATIVE_SERVER_ENV = "UNSLOTH_H3_NATIVE_SERVER"
H3_NATIVE_SERVER_IDLE_ENV = "UNSLOTH_H3_NATIVE_SERVER_IDLE_S"
# Covers watching a clip and editing the next prompt; an absent user gets the memory back within 3 minutes.
H3_NATIVE_SERVER_IDLE_DEFAULT_S = 180.0
# Idle server stays only while VRAM and RAM keep max(4 GiB, 15%); same as _PIN_RESERVE_*.
H3_NATIVE_SERVER_RESERVE_MIN_BYTES = 4 << 30
H3_NATIVE_SERVER_RESERVE_FRACTION = 0.15


def h3_native_server_enabled() -> bool:
    value = os.environ.get(H3_NATIVE_SERVER_ENV, "").strip().lower()
    return value not in ("0", "false", "no", "off")


def h3_native_server_idle_s(env: Optional[dict] = None) -> float:
    """The idle window in seconds; an unreadable or negative value falls back to the default."""
    environ = env if env is not None else os.environ
    raw = str(environ.get(H3_NATIVE_SERVER_IDLE_ENV, "") or "").strip()
    if not raw:
        return H3_NATIVE_SERVER_IDLE_DEFAULT_S
    try:
        value = float(raw)
    except ValueError:
        return H3_NATIVE_SERVER_IDLE_DEFAULT_S
    if value != value or value < 0:  # NaN or negative
        return H3_NATIVE_SERVER_IDLE_DEFAULT_S
    return value


def h3_native_server_reserve_bytes(total_bytes: Optional[int]) -> int:
    total = int(total_bytes or 0)
    return max(H3_NATIVE_SERVER_RESERVE_MIN_BYTES, int(total * H3_NATIVE_SERVER_RESERVE_FRACTION))


def h3_native_server_pressure(
    *,
    vram_free: Optional[int],
    vram_total: Optional[int],
    host_available: Optional[int],
    host_total: Optional[int],
) -> Optional[str]:
    """Why an idle server must not be kept, or None. An unknown reading decides nothing for its side."""
    if vram_free is not None and vram_total:
        floor = h3_native_server_reserve_bytes(vram_total)
        if int(vram_free) < floor:
            return f"free VRAM {int(vram_free) >> 20} MiB below the {floor >> 20} MiB reserve"
    if host_available is not None and host_total:
        floor = h3_native_server_reserve_bytes(host_total)
        if int(host_available) < floor:
            return f"available host RAM {int(host_available) >> 20} MiB below the {floor >> 20} MiB reserve"
    return None


def h3_sibling_server_binary(cli_binary: Optional[str]) -> Optional[str]:
    """The ``sd-server`` beside the vetted ``sd-cli``, or None. Not ``find_sd_server_binary``: that may resolve an
    unvetted build from ``SD_SERVER_PATH`` / ``PATH``."""
    if not cli_binary:
        return None
    cli = Path(cli_binary)
    suffix = ".exe" if cli.suffix.lower() == ".exe" else ""
    candidate = cli.with_name("sd-server" + suffix)
    return str(candidate) if candidate.is_file() else None


_LIVE_SLOTS: "weakref.WeakSet[H3NativeServerSlot]" = weakref.WeakSet()


def release_h3_native_servers(reason: str) -> int:
    """Stop every resident H3 sd-server (a busy one after its render). Returns how many; never raises."""
    count = 0
    for slot in list(_LIVE_SLOTS):
        try:
            if slot.release(reason):
                count += 1
        except Exception:  # noqa: BLE001 -- a release must never break the caller that needs the memory
            continue
    return count


class H3NativeServerSlot:
    """At most one resident ``sd-server`` for a loaded MiniMax-H3 native runtime, so renders skip the ~32 GB reload.

    Spawned with exactly the flags and env the one-shot sd-cli would get; another signature respawns it. Stopped by
    the idle timer, ``pressure_probe`` after a render, ``release`` (busy: at render end) and ``stop`` on unload.
    Registered as a managed-tree holder while alive so an install stands down.
    """

    def __init__(
        self,
        server_binary: str,
        files: Any,
        offload_flags: "tuple[str, ...] | list[str]" = (),
        *,
        pressure_probe: Optional[Callable[[], Optional[str]]] = None,
    ) -> None:
        import threading

        self.server_binary = server_binary
        self.files = files
        self.offload_flags = tuple(offload_flags)
        self.pressure_probe = pressure_probe
        self.disabled_reason: Optional[str] = None
        self.last_release_reason: Optional[str] = None
        self._server: Any = None
        self._stopping: Any = None
        self._signature: Optional[tuple] = None
        self.launched_flags: Optional[tuple[str, ...]] = None
        # Set before a start runs; ``launched_flags`` only after it succeeds.
        self.attempted_flags: Optional[tuple[str, ...]] = None
        self._lock = threading.RLock()
        self._busy = 0
        self._release_pending: Optional[str] = None
        self._timer: Any = None
        # Bumped on every arm / cancel so a timer that fired as it was cancelled sees it is stale.
        self._timer_token = 0
        _LIVE_SLOTS.add(self)

    def is_alive(self) -> bool:
        # A server mid-stop still runs out of the managed tree.
        return any(s is not None and s.is_alive() for s in (self._server, self._stopping))

    @property
    def signature(self) -> Optional[tuple]:
        return self._signature

    def _signature_for(self, flags: "tuple[str, ...]", env: "tuple[tuple[str, str], ...]") -> tuple:
        files = self.files
        file_key = tuple(
            getattr(files, name, None)
            for name in ("diffusion_model", "llm", "vae", "audio_vae", "llm_vision")
        )
        return (self.server_binary, file_key, tuple(flags), tuple(sorted(env)))

    def alive_signature(self) -> Optional[tuple]:
        with self._lock:
            return self._signature if self.is_alive() else None

    def get(
        self,
        flags: "Optional[tuple[str, ...] | list[str]]" = None,
        env: "Optional[dict[str, str] | tuple[tuple[str, str], ...]]" = None,
        *,
        cancel_event: Any = None,
        pre_spawn: "Optional[Callable[[], Any]]" = None,
        launch_transform: "Optional[Callable[[tuple[str, ...]], Any]]" = None,
    ) -> Any:
        """The live server for this (flags, env), (re)spawning one if needed. ``cancel_event`` aborts a start: the
        render holds the generate lock through the model load, so unload and Cancel would otherwise wait it out.
        ``pre_spawn`` runs only when a process is about to start, under the slot lock and after any old server has
        stopped: it returns the flags to start with (a live memory fit) or raises to refuse the start.
        ``launch_transform`` rewrites only the argv; the signature keeps untransformed flags so a varying budget
        never makes a reusable server look stale."""
        import threading

        from .sd_cpp_backend import register_tree_holder, unregister_tree_holder
        from .sd_cpp_engine import SdCppCancelled, is_managed_binary
        from .sd_cpp_server import SdCppServer

        flag_tuple = tuple(self.offload_flags if flags is None else flags)
        env_pairs = tuple((env or {}).items()) if isinstance(env, dict) else tuple(env or ())
        wanted = self._signature_for(flag_tuple, env_pairs)
        with self._lock:
            self._cancel_timer_locked()
            if self._server is not None and self._server.is_alive() and self._signature == wanted:
                return self._server
            if self._server is not None:
                self._stop_locked(
                    "signature changed" if self._server.is_alive() else "server exited"
                )
            if cancel_event is not None and cancel_event.is_set():
                raise SdCppCancelled("sd-server start was cancelled before launch.")
            if pre_spawn is not None:
                # Reuse was decided above, under this lock: from here a process starts, so it is fitted now.
                flag_tuple = tuple(pre_spawn())
                wanted = self._signature_for(flag_tuple, env_pairs)
            launch_tuple = (
                tuple(launch_transform(flag_tuple)) if launch_transform is not None else flag_tuple
            )
            self.attempted_flags = launch_tuple
            server = SdCppServer(self.server_binary)
            managed = is_managed_binary(self.server_binary)
            self._server = server
            self._signature = wanted
            if managed:
                register_tree_holder(self)
            started = threading.Event()
            if cancel_event is not None:

                def abort_on_cancel() -> None:
                    # stop() sets the abort before taking the lifecycle lock, so start() leaves its readiness wait.
                    while not started.is_set():
                        if cancel_event.wait(0.2):
                            if not started.is_set():
                                server.stop()
                            return

                threading.Thread(
                    target = abort_on_cancel, daemon = True, name = "h3-sd-server-start-cancel"
                ).start()
            try:
                from .sd_cpp_backend import _explicit_threads
                server.start(
                    self.files,
                    offload = list(launch_tuple),
                    threads = _explicit_threads(),
                    env = dict(env_pairs) or None,
                    # A context flag on sd-server (per-run on sd-cli); same RNG keeps seeds identical across paths.
                    extra_args = ["--rng", "cpu"],
                )
            except BaseException:
                started.set()
                self._server = None
                self._signature = None
                self._stopping = server
                try:
                    server.stop()
                finally:
                    self._stopping = None
                    unregister_tree_holder(self)
                raise
            started.set()
            self.launched_flags = launch_tuple
            if cancel_event is not None and cancel_event.is_set() and not server.is_alive():
                self._stop_locked("cancelled")
                raise SdCppCancelled("sd-server start was cancelled.")
            return server

    def begin_render(self) -> None:
        with self._lock:
            self._busy += 1
            self._cancel_timer_locked()

    def end_render(self) -> Optional[str]:
        """Stop the server (pending release, memory pressure, idle 0) or arm the idle timer. Returns the stop reason."""
        with self._lock:
            self._busy = max(0, self._busy - 1)
            if self._busy:
                return None
            if self._server is None:
                self._release_pending = (
                    None  # nothing left to release; a stale one would refuse the next retry
                )
                return None
            reason = self._release_pending
        if reason is None and self.pressure_probe is not None:
            try:
                reason = self.pressure_probe()
            except Exception:  # noqa: BLE001 -- an unreadable probe keeps the idle timeout as the bound
                reason = None
            if reason:
                reason = f"memory pressure: {reason}"
        idle_s = h3_native_server_idle_s()
        if reason is None and idle_s <= 0:
            reason = "idle timeout 0"
        with self._lock:
            if self._busy or self._server is None:
                return None
            if reason is not None:
                self._stop_locked(reason)
                return reason
            self._arm_timer_locked(idle_s)
        return None

    def release(self, reason: str) -> bool:
        """Never waits on a server start under the lock (minutes; caller may hold the GPU arbiter); busy server defers stop to end_render; True if one was stopped."""
        if not self._lock.acquire(timeout = 0.5):
            self._release_pending = reason
            return True
        try:
            # Busy first: between restart_for_retry's stop and the respawn the render still owns the slot.
            if self._busy:
                self._release_pending = reason
                return True
            if self._server is None:
                return False
            self._stop_locked(reason)
            return True
        finally:
            self._lock.release()

    @property
    def release_pending(self) -> Optional[str]:
        return self._release_pending

    def restart_for_retry(self, reason: str) -> bool:
        """Stop for a retry unless a release is pending. One locked step: a release racing a separate check would be
        cleared by ``_stop_locked`` and the fresh server would outlive the render asked to free its memory."""
        with self._lock:
            if self._release_pending is not None:
                return False
            self._stop_locked(reason)
            return True

    def stop(self, reason: str = "stopped") -> None:
        with self._lock:
            self._stop_locked(reason)

    def disable(self, reason: str) -> None:
        self.disabled_reason = reason
        self.stop(reason)

    def _stop_locked(self, reason: str) -> None:
        from .sd_cpp_backend import unregister_tree_holder

        self._cancel_timer_locked()
        server, self._server = self._server, None
        self._signature = None
        self._release_pending = None
        if server is None:
            return
        self._stopping = server
        self.last_release_reason = reason
        try:
            import logging
            logging.getLogger(__name__).info("h3 native sd-server stopped: %s", reason)
        except Exception:  # noqa: BLE001
            pass
        try:
            server.stop()
        finally:
            self._stopping = None
            unregister_tree_holder(self)

    def _cancel_timer_locked(self) -> None:
        self._timer_token += 1
        timer, self._timer = self._timer, None
        if timer is not None:
            timer.cancel()

    def _arm_timer_locked(self, idle_s: float) -> None:
        import threading

        self._cancel_timer_locked()
        token = self._timer_token
        ref = weakref.ref(self)

        def fire() -> None:
            slot = ref()
            if slot is not None:
                slot._on_idle(token)

        timer = threading.Timer(idle_s, fire)
        timer.daemon = True
        timer.name = "h3-sd-server-idle"
        self._timer = timer
        timer.start()

    def _on_idle(self, token: int) -> None:
        with self._lock:
            if token != self._timer_token or self._busy:
                return
            self._timer = None
            self._stop_locked("idle timeout")


def transcode_video_to_mp4(source: Path, *, fps: int) -> bytes:
    """Convert sd.cpp WebM to H.264/AAC MP4 entirely in PyAV, not Diffusers, so the no-torch native runtime can export the clip."""
    import av

    tmp = tempfile.NamedTemporaryFile(suffix = ".mp4", delete = False)
    tmp.close()
    target = Path(tmp.name)
    try:
        with av.open(str(source)) as src, av.open(str(target), mode = "w", format = "mp4") as dst:
            source_video = src.streams.video[0]
            output_video = dst.add_stream("libx264", rate = fps)
            output_video.width = int(source_video.codec_context.width)
            output_video.height = int(source_video.codec_context.height)
            output_video.pix_fmt = "yuv420p"

            source_audio = src.streams.audio[0] if src.streams.audio else None
            output_audio = None
            audio_resampler = None
            if source_audio is not None:
                sample_rate = int(source_audio.codec_context.sample_rate or 32000)
                output_audio = dst.add_stream("aac", rate = sample_rate)
                output_audio.layout = "stereo"
                audio_resampler = av.AudioResampler(
                    format = "fltp", layout = "stereo", rate = sample_rate
                )

            selected = (source_video,) if source_audio is None else (source_video, source_audio)
            for packet in src.demux(*selected):
                for frame in packet.decode():
                    if packet.stream.type == "video":
                        for encoded in output_video.encode(frame):
                            dst.mux(encoded)
                    elif output_audio is not None and audio_resampler is not None:
                        for resampled in audio_resampler.resample(frame):
                            for encoded in output_audio.encode(resampled):
                                dst.mux(encoded)

            if output_audio is not None and audio_resampler is not None:
                for resampled in audio_resampler.resample(None):
                    for encoded in output_audio.encode(resampled):
                        dst.mux(encoded)
            for encoded in output_video.encode():
                dst.mux(encoded)
            if output_audio is not None:
                for encoded in output_audio.encode():
                    dst.mux(encoded)
        return target.read_bytes()
    finally:
        target.unlink(missing_ok = True)


def _shown_vp8_key_frames(container: Any, stream: Any) -> Optional[int]:
    """Frames of a VP8 track whose every packet is a shown key frame (sd.cpp's WebM), from headers; else None."""
    if getattr(stream.codec_context, "name", None) != "vp8":
        return None
    count = 0
    try:
        for packet in container.demux(stream):
            size = int(packet.size)
            if size == 0:
                continue
            head = bytes(memoryview(packet)[:10])
            if len(head) < 10:
                return None
            tag = head[0] | (head[1] << 8) | (head[2] << 16)
            # RFC 6386 9.1: bit 0 = 0 key frame, bit 4 show_frame, bits 5-23 first partition size
            if (
                tag & 0x1
                or not tag & 0x10
                or head[3:6] != b"\x9d\x01\x2a"
                or (tag >> 5) > size - 10
            ):
                return None
            count += 1
    except Exception:  # noqa: BLE001
        return None
    return count or None


def inspect_video(path: Path) -> tuple[int, int, int, bool]:
    """Return width, height, decoded frame count, and audio presence."""
    import av

    with av.open(str(path)) as container:
        stream = container.streams.video[0]
        width = int(stream.codec_context.width)
        height = int(stream.codec_context.height)
        frames = int(stream.frames or 0)
        has_audio = bool(container.streams.audio)
        counted = _shown_vp8_key_frames(container, stream) if frames <= 0 else frames
    if counted is None:
        with av.open(str(path)) as container:
            counted = sum(1 for _ in container.decode(video = 0))
    return width, height, counted, has_audio


def _full_scale_constant(samples: Any) -> Optional[float]:
    """The one value every sample of ``samples`` holds when it is a full-scale (+-1) DC level, else None."""
    import numpy as np

    if samples.size == 0:
        return None
    lo, hi = samples.min(), samples.max()
    if lo != hi:
        return None
    level = float(lo)
    if np.issubdtype(samples.dtype, np.integer):
        level /= float(np.iinfo(samples.dtype).max)
    return level if abs(level) >= 0.999 else None


def h3_native_clip_is_nan_render(path: Path) -> bool:
    """True for an sd.cpp NaN render: flat 0/255 frames AND constant full-scale PCM, since frames
    alone false-flag lossy near-black clips; no audio or unreadable is never flagged"""
    import av

    with av.open(str(path)) as container:
        if not container.streams.audio:
            return False
        level = None
        for frame in container.decode(audio = 0):
            value = _full_scale_constant(frame.to_ndarray())
            if value is None or (level is not None and value != level):
                return False
            level = value
        if level is None:
            return False
    seen = False
    with av.open(str(path)) as container:
        if not container.streams.video:
            return False
        for frame in container.decode(video = 0):
            pixels = frame.to_ndarray(format = "rgb24")
            if pixels.size == 0:
                return False
            lo, hi = int(pixels.min()), int(pixels.max())
            # Black must be exact: a near-black scene decodes to 1-2. A white JPEG can come back at 253-255.
            if not (hi == 0 or lo >= 250):
                return False
            seen = True
    return seen