Spaces:
Running on Zero
Running on Zero
Add optional resumable render (.pt state file) under Advanced
#1
by ezmarynoori - opened
547 unmodified lines54854955055155255334 unmodified lines58858959059159259315 unmodified lines609610611612613614615547 unmodified linesreturn f"(estimate unavailable: {error})"with gr.Blocks(title="MiniMax-H3-Turbo-LoRA-Fast") as demo:gr.Markdown("""# MiniMax-H3-Turbo-LoRA-Fast""")34 unmodified linesinfo=f"Allowed: {', '.join(str(v) for v in GPU_DURATION_CHOICES)} s · "f"default {DEFAULT_GPU_DURATION} s · overrides ZeroGPU booking per clip.",)cost = gr.Markdown()run_button = gr.Button("Generate video", variant="primary")15 unmodified lines)load_models()if __name__ == "__main__":demo.queue(default_concurrency_limit=1, max_size=10).launch(theme=gr.themes.Citrus(), show_error=True, allowed_paths=[OUTPUT_DIR])547 unmodified lines548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139934 unmodified lines14341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146915 unmodified lines1485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509547 unmodified linesreturn f"(estimate unavailable: {error})"# ----------------------------------------------------------------------------------------------------------# Resumable render — pause anywhere (between denoise blocks, between decode clips), save a .pt, continue later.## Everything below is additive and only reached from the "Resumable render" box under Advanced. The normal# "Generate video" button above never touches it: `generate()` is unchanged.## One press of "Run one GPU window" is ONE @spaces.GPU booking whose length the visitor picks (2 / 5 / 40 min of# ZeroGPU quota). Inside the booking the render may stop at three kinds of seams:# - between denoise steps -> the small .pt state file holds the latents of that step;# - between the 50 transformer -> the half-finished step is cut at a block boundary; the (large) activation is# blocks inside one step parked on this Space's disk, the .pt only records "step N, block K";# - between the temporal decode -> every finished decode clip is written to this Space's disk, so a decode that# clips of the VAE is longer than one window is finished over several windows.# Feed the .pt back in (it is put in the input box automatically) and the next press continues from the exact seam —# today, tomorrow, or from another browser. If the Space restarted in between, the disk parts are gone and the render# falls back to the last step boundary / the start of the decode; the .pt itself is always enough to continue.# The state file is self-contained (prompt, keyframes, conditioner output, latents, step), so the form does not# have to match.# ----------------------------------------------------------------------------------------------------------import uuidSTATE_VERSION = 1STATE_KIND = "h3-turbo-lora-fast-state"# What the visitor picks is the ZeroGPU *quota* they are willing to spend per press. On `xlarge` ZeroGPU counts# every GPU second twice, so the window that is actually booked is half of it.WINDOW_CHOICES = [("2 min quota — no login", 120),("5 min quota", 300),("40 min quota — Pro", 2400),]DEFAULT_WINDOW = 120BILLING_FACTOR = 2 if GPU_SIZE == "xlarge" else 1ATTACH_SECONDS = 6 # time the booking has already used before the function body startsSAVE_PAD_SECONDS = 3 # fixed part of the time reserved to park a seam on the CPU / diskMIN_SAFETY_SECONDS = 4SAFETY_FRACTION = 0.04 # of the window, kept free at the endSHRINK_ATTEMPTS = 3MAX_LADDER = (1500, 1200, 900, 600, 300, 180, 120, 90, 60)DISK_BYTES_PER_SECOND = 0.7e9 # assumed speed for parking / reloading a seamMIN_MID_BLOCKS = 2 # a stop before this block just falls back to the step boundaryRESUME_OVERHEAD_SECONDS = 3 # re-embedding the step that was cut + reloading the parked activationTAIL_BASE_SECONDS = 8.0 # after the last decode clip: stitch + float + PIL frames + audio decode ...TAIL_FRACTION = 0.15 # ... plus this share of the whole decode estimateVAE_TOKENS_CHUNK, VAE_TOKEN_DROP = 5, 3 # AutoencoderKLMiniMaxH3 defaults (17-frame clips, 4x temporal)NUM_BLOCKS_DEFAULT, HIDDEN_SIZE = 50, 5376 # MiniMaxH3Transformer3DModel defaultsCACHE_DIR = os.path.join(tempfile.gettempdir(), "h3-resume")CACHE_KEEP_SECONDS = 3 * 24 * 3600CACHE_MAX_BYTES = 40 * 10**9WINDOW = None # set only inside the GPU worker while a window runsSAFETY_BOOST = 1.0 # widened whenever ZeroGPU cuts a window offclass WindowStop(BaseException):"""Leaves the pipeline at a seam. A BaseException on purpose: diffusers' `except Exception` blocks log everyerror with a full traceback, and a planned stop is not an error."""class QuotaTooLow(Exception):def __init__(self, needed, left=None, retry_in=None):super().__init__(f"ZeroGPU quota too low: needs ~{needed}s, has {left}s")self.needed, self.left, self.retry_in = needed, left, retry_indef _step_seconds(rows: int) -> float:return _DUR_B * rows + _DUR_C * rows**2def _latent_frames(num_frames) -> int:return (int(num_frames) - LATENTS_PER_CHUNK) // FRAMES_PER_CHUNK * LATENTS_PER_CHUNK + 2def _rows_for(height, width, num_frames, keyframes=0) -> int:patches = (int(height) // 32) * (int(width) // 32)return _latent_frames(num_frames) * patches + int(keyframes) * patchesdef _decode_seconds(height, width, num_frames, with_audio=True) -> float:decode = _DECODE_BASE + _DECODE_PER_DEFAULT_CANVAS * (int(height) * int(width) * int(num_frames)) / _DEFAULT_CANVAS_PIXELSreturn decode if with_audio else decode * 0.85def _clip_count(num_latent_frames, tokens_chunk=VAE_TOKENS_CHUNK, token_drop=VAE_TOKEN_DROP) -> int:"""How many `_decode_clip` calls the VAE makes for a video (mirrors AutoencoderKLMiniMaxH3._decode)."""num_tokens = int(num_latent_frames) + token_droppad = (-num_tokens) % tokens_chunkreturn max(1, (num_tokens + pad) // tokens_chunk - int(token_drop > 0))def _tail_seconds(decode_seconds) -> float:return TAIL_BASE_SECONDS + TAIL_FRACTION * decode_secondsdef _safety(budget: float) -> float:return max(MIN_SAFETY_SECONDS, SAFETY_FRACTION * budget) * SAFETY_BOOSTdef _window_clock(window) -> float:return time.time() - window["t0"] + ATTACH_SECONDSdef _error_text(error) -> str:parts = (getattr(error, "title", None), getattr(error, "message", None), str(error))return " ".join(str(part) for part in parts if part)def parse_quota_error(error) -> dict:"""What a ZeroGPU refusal says: "(240s requested vs. 124s left)", "larger than the maximum allowed", ..."""import retext = _error_text(error).lower()left = re.search(r"(-?\d+)\s*s\s*left", text)retry = re.search(r"(?:try again|retry) in\s*(?:(\d+):)?(\d{1,2}):(\d{2})", text)return {"quota": left is not None or ("exceeded" in text and "quota" in text),"left": int(left.group(1)) if left else None,"retry_in": (int(retry.group(1) or 0) * 3600 + int(retry.group(2)) * 60 + int(retry.group(3))) if retry else None,"max": "larger than the maximum allowed" in text or "illegal duration" in text,"queue": "no gpu was available" in text,"aborted": "gpu task aborted" in text or "task aborted" in text,}def _clock(seconds) -> str:if not seconds:return ""seconds = int(seconds)return f"{seconds // 3600}:{seconds % 3600 // 60:02d}:{seconds % 60:02d}"# -- seams on disk ---------------------------------------------------------------------------------------------def _mid_path(job, step, block) -> str:return os.path.join(CACHE_DIR, f"mid-{job}-s{int(step)}-b{int(block)}.pt")def _write_mid(window, step, block, hidden) -> str:import torchos.makedirs(CACHE_DIR, exist_ok=True)path = _mid_path(window["job"], step, block)torch.save({"step": int(step), "block": int(block), "hidden": hidden}, path + ".tmp")os.replace(path + ".tmp", path)return pathdef _digest(tensor) -> str:import hashlibimport torchflat = tensor.detach().to("cpu").contiguous().reshape(-1).view(torch.uint8)return hashlib.sha1(flat.numpy().tobytes()).hexdigest()[:10]def _forget_job(job, keep=()) -> None:"""Drop the parked seams of a job (all of them, or all but `keep`)."""if not job or not os.path.isdir(CACHE_DIR):returnkeep = {os.path.abspath(path) for path in keep if path}for name in os.listdir(CACHE_DIR):path = os.path.abspath(os.path.join(CACHE_DIR, name))if f"-{job}-" in name and path not in keep:shutil.rmtree(path, ignore_errors=True) if os.path.isdir(path) else _silent_remove(path)def _silent_remove(path) -> None:try:os.remove(path)except OSError:passdef _prune_cache() -> None:"""Old jobs go after a few days; the folder is kept under a size cap, oldest first."""if not os.path.isdir(CACHE_DIR):returnnow, entries = time.time(), []for name in os.listdir(CACHE_DIR):path = os.path.join(CACHE_DIR, name)try:size = sum(os.path.getsize(os.path.join(root, f)) for root, _, files in os.walk(path) for f in files) if os.path.isdir(path) else os.path.getsize(path)entries.append((os.path.getmtime(path), size, path))except OSError:continuetotal = sum(size for _, size, _ in entries)for mtime, size, path in sorted(entries):if now - mtime > CACHE_KEEP_SECONDS or total > CACHE_MAX_BYTES:shutil.rmtree(path, ignore_errors=True) if os.path.isdir(path) else _silent_remove(path)total -= size# -- the hooks -------------------------------------------------------------------------------------------------def _install_window_hook() -> None:"""Wrap `MiniMaxH3DenoiseLoopWrapper.__call__` once. With no window active it is the stock loop, untouched."""import torchfrom diffusers.modular_pipelines.minimax_h3.denoise import MiniMaxH3DenoiseLoopWrapper as wrapperif getattr(wrapper, "_h3_window_hook", False):returnstock = wrapper.__call__def snapshot(block_state, step):audio = getattr(block_state, "audio_latents", None)return {"step": int(step),"block": 0,"latents": block_state.latents.detach().to("cpu").clone(),"audio_latents": audio.detach().to("cpu").clone() if audio is not None else None,}@torch.no_grad()def windowed(self, components, state):window = WINDOWif window is None:return stock(self, components, state)block_state = self.get_block_state(state)timesteps = block_state.timestepstotal = len(timesteps)start = int(window["start"])saved = window.get("saved")window["total"] = totalif saved is not None and saved.get("latents") is not None:if tuple(saved["latents"].shape) != tuple(block_state.latents.shape):raise ValueError(f"The state file does not fit this request: saved video rows {tuple(saved['latents'].shape)} vs "f"{tuple(block_state.latents.shape)} now.")block_state.latents.copy_(saved["latents"].to(device=block_state.latents.device, dtype=block_state.latents.dtype))audio = getattr(block_state, "audio_latents", None)if audio is not None and saved.get("audio_latents") is not None:if tuple(saved["audio_latents"].shape) != tuple(audio.shape):raise ValueError("The state file does not fit this request: the audio rows differ.")audio.copy_(saved["audio_latents"].to(device=audio.device, dtype=audio.dtype))if start:# The scheduler keeps its own position; it is rebuilt at step 0 for every request.components.scheduler._step_index = startcomponents.audio_scheduler._step_index = startrows = int(block_state.latents.shape[0])window["nblocks"] = len(components.transformer.transformer_blocks)window["block_guess"] = _step_seconds(rows) * 1.25 / max(window["nblocks"], 1)# A step that was cut between two blocks: reload its parked activation (only if it is really that step).resume_block, resume_hidden = 0, Nonewanted = int(window.get("block") or 0)path = window.get("mid_path")if start < total and wanted > 0 and path and os.path.exists(path):try:parked = torch.load(path, map_location="cpu", weights_only=True)if int(parked["step"]) == start and int(parked["block"]) == wanted:resume_block, resume_hidden = wanted, parked["hidden"]window["resumed_block"] = wantedexcept Exception as error: # noqa: BLE001 - a bad cache only costs the half stepprint(f"[window] parked block activation unusable ({type(error).__name__}: {error}); redoing the step", flush=True)i = startwith self.progress_bar(total=total) as progress_bar:progress_bar.update(start)while i < total:blk = {"resume_k": resume_block if resume_hidden is not None else 0,"hidden": resume_hidden,"times": [],}resume_block, resume_hidden = 0, Nonewindow["blk"] = blktry:components, block_state = self.loop_step(components, block_state, i=i, t=timesteps[i])except WindowStop:snap = snapshot(block_state, i)if blk.get("stop_hidden") is not None:snap["block"] = int(blk["stop_block"])snap["mid_path"] = _write_mid(window, i, blk["stop_block"], blk["stop_hidden"])elif blk.get("stop_reuse"):snap["block"] = int(blk["stop_block"])snap["mid_path"] = window.get("mid_path")window["snapshot"] = snapwindow["reason"] = "window full"raisefinally:window["blk"] = Nonei += 1window["done_steps"] = i - startprogress_bar.update()# Every denoise step is done. The decode that follows may span windows too (see `_arm_decode`).window["final"] = snapshot(block_state, total)window["dec_dir"] = os.path.join(CACHE_DIR, f"dec-{window['job']}-{_digest(window['final']['latents'])}")# A decode-only window runs no step, so the loop's per-step outputs were never produced; nothing reads them.for output in self.intermediate_outputs:if not hasattr(block_state, output.name):setattr(block_state, output.name, None)self.set_block_state(state, block_state)return components, statewrapper.__call__ = windowedwrapper._h3_window_hook = Truedef _arm_blocks(transformer):"""Make every transformer block a seam. Returns the function that undoes it."""import torchblocks = list(transformer.transformer_blocks)def make(index, original):def forward(hidden_states, *args, **kwargs):window = WINDOWblk = window.get("blk") if window else Noneif blk is None:return original(hidden_states, *args, **kwargs)resume = blk["resume_k"]if index < resume:return hidden_states # already applied before the stop; the parked state replaces thisif index == resume and blk["hidden"] is not None:hidden_states = blk["hidden"].to(device=hidden_states.device, dtype=hidden_states.dtype)blk["hidden"] = Noneblk["reloaded"] = Trueestimate = max(blk["times"][-2:]) if blk["times"] else window["block_guess"]park = hidden_states.numel() * hidden_states.element_size() / DISK_BYTES_PER_SECONDif _window_clock(window) + estimate * 1.2 + SAVE_PAD_SECONDS + park > window["budget"] - _safety(window["budget"]):blk["stop_block"] = indexif blk.get("reloaded") and not blk["times"]:blk["stop_reuse"] = True # nothing new since the parked file: keep itelif index >= MIN_MID_BLOCKS:blk["stop_hidden"] = hidden_states.detach().to("cpu")raise WindowStop("window full")began = time.time()out = original(hidden_states, *args, **kwargs)if torch.cuda.is_available():torch.cuda.synchronize()blk["times"].append(time.time() - began)window["blocks"] = window.get("blocks", 0) + 1return outreturn forwardfor index, block in enumerate(blocks):block.forward = make(index, block.forward)def restore():for block in blocks:block.__dict__.pop("forward", None)return restoredef _arm_decode(vae):"""Make every temporal decode clip of the video VAE a seam: finished clips live on disk. Returns the undo."""import torchoriginal = vae._decode_clipcounter = {"n": 0}def clip(z):window = WINDOWdirectory = window.get("dec_dir") if window else Noneif directory is None:return original(z)if counter.get("window") is not window: # a new booking decodes from clip 0 againcounter["window"], counter["n"] = window, 0n = counter["n"]counter["n"] += 1if window.get("clip_total") is None:window["clip_total"] = _clip_count(window["nlf"], vae.tokens_chunk_size, vae.config.token_drop)window["clips_seen"] = n + 1path = os.path.join(directory, f"clip-{n:04d}.pt")if os.path.exists(path):try:parked = torch.load(path, map_location=z.device, weights_only=True)if list(parked["z_shape"]) == list(z.shape):window["clips_cached"] = window.get("clips_cached", 0) + 1return parked["out"]except Exception as error: # noqa: BLE001 - a bad clip file is simply decoded againprint(f"[window] decode clip {n} unusable ({type(error).__name__}: {error}); decoding it again", flush=True)times = window["clip_times"]total = window["clip_total"]estimate = max(times[-2:]) if times else window["decode_estimate"] / total * 1.5tail = window["tail_estimate"] if n >= total - 1 else 0.0 # only the last clip is followed by the tailif _window_clock(window) + estimate * 1.2 + SAVE_PAD_SECONDS + tail > window["budget"] - _safety(window["budget"]):window["snapshot"] = window["final"]window["reason"] = "decode partial"raise WindowStop("decode partial")began = time.time()out = original(z)os.makedirs(directory, exist_ok=True)torch.save({"z_shape": list(z.shape), "out": out.detach().to("cpu")}, path + ".tmp")os.replace(path + ".tmp", path)times.append(time.time() - began)window["clips_new"] = window.get("clips_new", 0) + 1return outvae._decode_clip = clipdef restore():vae.__dict__.pop("_decode_clip", None)return restoredef get_window_duration(window_seconds, *a, **k):return int(window_seconds)@spaces.GPU(duration=get_window_duration, size=GPU_SIZE)def _generate_window(window_seconds, prompt_embeds, text_token_tags, image, last_image, height, width, num_frames, steps, seed,lora, with_audio, resume, job,):"""One ZeroGPU booking of `window_seconds`: the stock `_generate`, but it may stop at any seam."""global WINDOWimport torch_install_window_hook()active_lora = _set_lora(PIPE.transformer, lora)if PLACEMENT == "lazy":PIPE.to("cuda")elif PLACEMENT == "pack":PIPE.vae.to("cuda")PIPE.audio_vae.to("cuda")decode = _decode_seconds(height, width, num_frames, True)WINDOW = {"t0": time.time(),"budget": float(window_seconds),"start": int((resume or {}).get("step") or 0),"saved": resume,"block": int((resume or {}).get("block") or 0),"mid_path": (resume or {}).get("mid_path"),"job": job,"nlf": _latent_frames(num_frames),"decode_estimate": decode,"tail_estimate": _tail_seconds(decode),"clip_times": [],}undo = [_arm_blocks(PIPE.transformer), _arm_decode(PIPE.vae)]try:try:state = PIPE(prompt_embeds=prompt_embeds.to("cuda"),text_token_tags=text_token_tags,image=image,last_image=last_image,height=int(height),width=int(width),num_frames=int(num_frames),num_inference_steps=int(steps) + 1,generator=torch.Generator("cpu").manual_seed(int(seed)),)except WindowStop:return {"done": False, "snapshot": WINDOW["snapshot"], "reason": WINDOW.get("reason"),**_window_report(WINDOW), "lora": active_lora,}return {"done": True, "frames": state.get("videos")[0], "audio": state.get("audio")[0].cpu(),"sampling_rate": state.get("sampling_rate"), "snapshot": WINDOW.get("final"),**_window_report(WINDOW), "lora": active_lora,}finally:for restore in undo:restore()WINDOW = Nonedef _window_report(window) -> dict:return {"ran": window.get("done_steps", 0), "total": window.get("total"), "blocks": window.get("blocks", 0),"nblocks": window.get("nblocks"), "clips_new": window.get("clips_new", 0),"clips_done": window.get("clips_cached", 0) + window.get("clips_new", 0), "clip_total": window.get("clip_total"),"elapsed": time.time() - window["t0"], "resumed": window.get("resumed_block", 0),}def _png_tensor(path):import ioimport torchif not path:return Nonebuffer = io.BytesIO()keyframe(path).save(buffer, format="PNG")return torch.frombuffer(bytearray(buffer.getvalue()), dtype=torch.uint8).clone()def _png_image(tensor):import iofrom PIL import Imageif tensor is None:return Nonereturn Image.open(io.BytesIO(bytes(tensor.numpy().tobytes()))).convert("RGB")def _save_state(state: dict, name: str) -> str:import torchos.makedirs(OUTPUT_DIR, exist_ok=True)path = os.path.join(OUTPUT_DIR, name)torch.save(state, path + ".tmp")os.replace(path + ".tmp", path)return pathdef _load_state(path: str) -> dict:import torchtry:state = torch.load(path, map_location="cpu", weights_only=True)except Exception as error:raise gr.Error(f"Could not read the state file: {type(error).__name__}: {error}") from errorif not isinstance(state, dict) or state.get("kind") != STATE_KIND:raise gr.Error("This is not a state file made by this Space.")if int(state.get("version", 0)) != STATE_VERSION:raise gr.Error(f"Unsupported state file version {state.get('version')} (this Space reads {STATE_VERSION}).")for key in ("meta", "prompt_embeds", "text_token_tags", "step", "total_steps"):if key not in state:raise gr.Error(f"The state file is incomplete (missing `{key}`).")return statedef _window_seconds(quota_seconds) -> int:try:quota = int(quota_seconds)except (TypeError, ValueError):quota = DEFAULT_WINDOWreturn max(20, quota // BILLING_FACTOR)def _run_window_with_fallback(request_seconds, args):"""Book the window; when ZeroGPU refuses it for the quota left, book what is actually left instead."""global SAFETY_BOOSTseconds = int(request_seconds)for _ in range(SHRINK_ATTEMPTS + 1):try:return _generate_window(seconds, *args), secondsexcept Exception as error: # noqa: BLE001 - classified belowinfo = parse_quota_error(error)if info["aborted"]:SAFETY_BOOST = min(3.0, SAFETY_BOOST + 0.5)raise gr.Error("ZeroGPU cut this window off before it finished (the time estimate was too optimistic). ""Nothing was lost: your state file is unchanged, and decode clips that were already finished ""are kept on this Space. The safety margin was widened — press again.") from errorif info["quota"] and info["left"] is not None:smaller = int(info["left"] // BILLING_FACTOR) - 1elif info["max"]:lower = [v for v in MAX_LADDER if v < seconds]smaller = lower[0] if lower else 0elif info["quota"]:raise QuotaTooLow(0, None, info["retry_in"]) from errorelse:raiseif smaller < 1:raise QuotaTooLow(0, info["left"], info["retry_in"]) from errorprint(f"[window] booking of {seconds}s refused ({str(error)[:120]}); retrying with {smaller}s", flush=True)seconds = min(smaller, seconds - 1)raise gr.Error("ZeroGPU kept refusing the booking; try again in a moment.")def _fit_verdict(height, width, num_frames, keyframes, with_audio, quota, steps_left):"""None when a window of `quota` can make progress on this job, else why not (no GPU is booked for this).With seams between blocks and decode clips the size of the job no longer matters, only the *smallest piece* awindow has to hold: one transformer block (plus parking its activation), and — in the very last window — onedecode clip followed by the tail (stitch, PIL frames, audio)."""budget = _window_seconds(quota)setup = ATTACH_SECONDS + _PLACEMENT_ALLOWANCErows = _rows_for(height, width, num_frames, keyframes)block = _step_seconds(rows) * 1.25 / NUM_BLOCKS_DEFAULTpark = rows * HIDDEN_SIZE * 2 / DISK_BYTES_PER_SECONDdecode = _decode_seconds(height, width, num_frames, bool(with_audio))clip = decode / _clip_count(_latent_frames(num_frames))margin = SAVE_PAD_SECONDS + _safety(budget)need_block = setup + RESUME_OVERHEAD_SECONDS + block * 1.2 + park + margin if steps_left > 0 else 0.0need_final = setup + clip * 1.2 + _tail_seconds(decode) + marginneed = max(need_block, need_final)if budget >= need:return Noneneed_quota = int(math.ceil(need * BILLING_FACTOR / 10.0) * 10)pick = next((label for label, value in WINDOW_CHOICES if value >= need_quota), None)what = (f"one transformer block plus parking its activation needs ~{need_block:.0f}s"if need_block >= need_finalelse f"the last decode clip plus the tail (stitching, frames, audio) needs ~{need_final:.0f}s")return (f"⛔ **Even the smallest piece of this job does not fit a {budget}s window** ({int(quota)}s of quota at "f"`{GPU_SIZE}`): at {width}x{height} and {num_frames} frames {what}. Nothing was booked, so no quota was "f"spent.\n\n"f"- a bigger window: about **{need_quota}s of quota per press** "+ (f"(the “{pick}” choice)" if pick else "(more than any choice here offers)")+ "\n- or a smaller canvas / a shorter video\n""- to start a *different* job, **remove the state file from the box above first** (it carries the old size ""and settings; the form is ignored while a file is loaded)")def estimate_window(canvas, duration, steps, first_frame, last_frame, with_audio, window_choice, state_file):try:if state_file:state = _load_state(_as_path(state_file))meta = state["meta"]height, width, num_frames = int(meta["height"]), int(meta["width"]), int(meta["num_frames"])keyframes = int(state.get("first_png") is not None) + int(state.get("last_png") is not None)total, done, with_audio = int(state["total_steps"]), int(state["step"]), bool(int(meta["with_audio"]))else:height, width = CANVASES.get(canvas, CANVASES[DEFAULT_CANVAS])num_frames = snap_frames(max(MIN_UI_DURATION, min(float(duration), MAX_UI_DURATION)))keyframes = int(bool(first_frame)) + int(bool(last_frame))total, done = int(steps), 0verdict = _fit_verdict(height, width, num_frames, keyframes, with_audio, window_choice, total - done)if verdict:return verdictstep_seconds = _step_seconds(_rows_for(height, width, num_frames, keyframes))decode = _decode_seconds(height, width, num_frames, bool(with_audio))tail = _tail_seconds(decode)budget = _window_seconds(window_choice)setup = ATTACH_SECONDS + _PLACEMENT_ALLOWANCE + RESUME_OVERHEAD_SECONDSusable = budget - setup - SAVE_PAD_SECONDS - _safety(budget)work = (total - done) * step_seconds + decode + tailwindows = max(1, math.ceil(work / max(usable, 1.0)))gpu_total = work + windows * setupquota_total = int(gpu_total * BILLING_FACTOR)days = max(1, math.ceil(quota_total / max(int(window_choice), 1)))return (f"{width}x{height} · {num_frames} frames · ~{step_seconds:.0f}s per step · decode ~{decode:.0f}s "f"(+ ~{tail:.0f}s tail) · window {budget}s booked ({int(window_choice)}s of quota at `{GPU_SIZE}`)\n\n"f"→ about **{windows} press(es)** and **~{quota_total}s of quota in total** for the "f"{total - done} remaining step(s) plus the decode. If that choice is your whole daily quota, the job "f"spans about **{days} day(s)** — the render is split at block and decode-clip seams, so it will finish, "f"but the quota is what sets the pace. Estimate only.")except gr.Error as error:return f"⚠️ {error}"except Exception as error:return f"(estimate unavailable: {error})"def run_window(prompt, first_frame, last_frame, canvas, duration, mode, steps, seed, upsample, lora, with_audio,window_choice, state_file, request: gr.Request = None, progress=gr.Progress(),):"""One press = one GPU window. Returns (video, state file, status, refined prompt, state file for the input box)."""if LOAD_ERROR:raise gr.Error(LOAD_ERROR.replace("**", "").replace("`", ""))if PIPE is None:raise gr.Error("The denoiser is still loading — check the Space logs and try again in a moment.")notes = []state_path = _as_path(state_file)_prune_cache()if state_path:saved = _load_state(state_path)meta = saved["meta"]prompt_embeds, text_token_tags = saved["prompt_embeds"], saved["text_token_tags"]first_png, last_png = saved.get("first_png"), saved.get("last_png")height, width, num_frames = int(meta["height"]), int(meta["width"]), int(meta["num_frames"])steps, seed, lora = int(meta["steps"]), int(meta["seed"]), str(meta["lora"])with_audio = bool(int(meta["with_audio"]))refined = str(meta.get("refined") or "")job = str(saved.get("job") or "") or uuid.uuid4().hex[:12]windows_before, gpu_before = int(saved.get("windows", 0)), float(saved.get("gpu_seconds", 0.0))notes.append("Settings are taken from the state file.")else:if not prompt or not str(prompt).strip():raise gr.Error("MiniMax-H3 always needs a prompt, with or without keyframes.")prompt = str(prompt).strip()lora = _resolve_lora(lora)canvas = canvas if canvas in CANVASES else DEFAULT_CANVASduration = max(MIN_UI_DURATION, min(float(duration), MAX_UI_DURATION))with_audio = bool(with_audio)steps, seed = int(steps), int(seed)first, last = _as_path(first_frame), _as_path(last_frame)if first:first, canvas = _fit_keyframe(first, canvas)if last:last, canvas = _fit_keyframe(last, canvas)verdict = _fit_verdict(*CANVASES[canvas], snap_frames(duration), int(bool(first)) + int(bool(last)), with_audio, window_choice, steps)if verdict:return gr.update(), None, verdict, "", Noneif mode != "single":notes.append("Resumable mode renders one pass (single); the chain setting is ignored.")if duration > 15:notes.append("Beyond 15 s is outside the H3 training distribution.")progress(0.0, desc="Conditioning on the remote text encoder ...")try:prompt_embeds, text_token_tags, metadata, plan = encode_remote(prompt, first, last, canvas, snap_frames(duration), rewrite_prompt=upsample,ip_token=_caller_ip_token(request),)except gr.Error:raiseexcept Exception as error:traceback.print_exc()if parse_quota_error(error)["quota"]:raise gr.Error("Not enough ZeroGPU quota for the conditioner step (it is billed to you too). Turn off "f"“Prompt upsampling”, or retry after the quota refills. ({error})") from errorraise gr.Error(f"Conditioning failed: {type(error).__name__}: {error}") from errorheight, width, num_frames = (int(metadata[key]) for key in ("height", "width", "num_frames"))refined = plan.get("refined_prompt") or ""first_png, last_png = _png_tensor(first), _png_tensor(last)saved = Nonejob = uuid.uuid4().hex[:12]windows_before, gpu_before = 0, 0.0meta = {"prompt": prompt, "canvas": canvas, "duration": float(duration), "height": height, "width": width,"num_frames": num_frames, "steps": steps, "seed": seed, "lora": lora, "with_audio": int(with_audio),"refined": refined,}total_steps = stepsquota = window_choicebegin_block = int(saved.get("block", 0) or 0) if saved else 0resume = Noneif saved:resume = {key: saved[key] for key in ("step", "latents", "audio_latents")}resume["block"] = begin_blockresume["mid_path"] = _mid_path(job, saved["step"], begin_block) if begin_block else Nonewindow_args = (prompt_embeds, text_token_tags, _png_image(first_png), _png_image(last_png), height, width, num_frames,steps, seed, lora, with_audio, resume, job,)def package(snapshot, extra=None):return {"kind": STATE_KIND, "version": STATE_VERSION, "meta": meta, "job": job,"block": int(snapshot.get("block", 0)) if snapshot else 0,"prompt_embeds": prompt_embeds, "text_token_tags": text_token_tags,"first_png": first_png, "last_png": last_png,"step": int(snapshot["step"]) if snapshot else 0, "total_steps": total_steps,"latents": snapshot["latents"] if snapshot else None,"audio_latents": snapshot["audio_latents"] if snapshot else None,"windows": windows_before + (1 if extra else 0), "gpu_seconds": gpu_before + float((extra or {}).get("elapsed", 0.0)),"created": time.time(),}begin_step = int(saved["step"]) if saved else 0verdict = _fit_verdict(height, width, num_frames, int(first_png is not None) + int(last_png is not None), with_audio, quota,total_steps - begin_step,)if verdict:return gr.update(), state_path, verdict, refined, state_pathprogress(0.1, desc=f"GPU window: step {begin_step}/{total_steps}, booking {_window_seconds(quota)}s ...")try:result, booked = _run_window_with_fallback(_window_seconds(quota), window_args)except QuotaTooLow as low:# Nothing ran. Keep what the conditioner already cost by handing the step-0 state back.path = state_path or _save_state(package(None), f"h3-state-{int(time.time())}-s0.pt")wait = f" Try again in about {_clock(low.retry_in)}." if low.retry_in else ""left = f"{low.left}s" if low.left is not None else "not reported"return (gr.update(), path, f"⏳ **Not enough ZeroGPU quota left for even one window** (quota left: {left}).{wait} ""Nothing was spent or lost — keep the state file below and press the button again later.",refined, path,)except gr.Error:raiseexcept Exception as error:message = str(error).lower()if any(hint in message for hint in ("gpu limit", "could not allocate", "too many", "concurrent")):raise gr.Error("The shared ZeroGPU pool is currently at its limit — this is not a problem with your inputs. ""Wait a minute and try again.") from errortraceback.print_exc()raise gr.Error(f"Window failed: {type(error).__name__}: {error}") from errorsummary = (f"window {windows_before + 1} · booked {booked}s ({booked * BILLING_FACTOR}s quota at `{GPU_SIZE}`) · "f"used {result['elapsed']:.0f}s · ran {result['ran']} step(s) + {result['blocks']} block(s) + "f"{result['clips_new']} decode clip(s) · LoRA {result['lora']} · "f"{width}x{height}, {num_frames} frames, seed {seed}")print(f"[window] {summary}", flush=True)if result.get("total") is None:notes.append("⚠️ The denoise-loop hook did not engage, so this window ran like a normal render.")if not result["done"]:snapshot = result["snapshot"]path = _save_state(package(snapshot, result),f"h3-state-{int(time.time())}-s{snapshot['step']}of{total_steps}"+ (f"b{snapshot['block']}" if snapshot.get("block") else "") + ".pt",)_forget_job(job, keep=[snapshot.get("mid_path")])if snapshot["step"] >= total_steps:clips = f"{result['clips_done']} of {result['clip_total']}" if result.get("clip_total") else str(result["clips_done"])what = f"All denoise steps are done. **Decoding: {clips} clips finished** (kept on this Space)."elif snapshot.get("block"):what = (f"Progress: **step {snapshot['step']} of {total_steps}, block {snapshot['block']} of "f"{result.get('nblocks') or NUM_BLOCKS_DEFAULT}** (the half step is parked on this Space; the .pt stays small).")else:what = f"Progress: **step {snapshot['step']} of {total_steps}**."status = (f"⏸ {what} State saved — it is already in the input box above, so press **Run one GPU window** again "f"(now or later), or download it to keep.\n\n{summary}")if result["ran"] == 0 and result["blocks"] == 0 and result["clips_new"] == 0 and not result.get("resumed"):status += "\n\n> This window made no progress: pick a longer window, or remove the state file and start a smaller job."if notes:status += "\n\n" + " ".join(notes)return gr.update(), path, status, refined, pathfrom diffusers.utils import encode_videoos.makedirs(OUTPUT_DIR, exist_ok=True)final = os.path.join(OUTPUT_DIR, f"h3-{int(time.time() * 1000)}.mp4")if with_audio:encode_video(result["frames"], fps=FPS, output_path=final, audio=result["audio"],audio_sample_rate=result["sampling_rate"])else:encode_video(result["frames"], fps=FPS, output_path=final)_forget_job(job)finished_path = Noneif result.get("snapshot"):finished_path = _save_state(package(result["snapshot"], result), f"h3-state-{int(time.time())}-final.pt")status = (f"✅ **Finished** in {windows_before + 1} window(s) · {total_steps} steps · "f"{num_frames / FPS:.2f}s of video.\n\n{summary}"+ ("\n\n" + " ".join(notes) if notes else "")+ ("\n\nThe state file below holds the finished latents — loading it later only re-runs the decode." if finished_path else ""))return final, finished_path, status, refined, Nonewith gr.Blocks(title="MiniMax-H3-Turbo-LoRA-Fast") as demo:gr.Markdown("""# MiniMax-H3-Turbo-LoRA-Fast""")34 unmodified linesinfo=f"Allowed: {', '.join(str(v) for v in GPU_DURATION_CHOICES)} s · "f"default {DEFAULT_GPU_DURATION} s · overrides ZeroGPU booking per clip.",)with gr.Accordion("Resumable render · save progress to a .pt file", open=False):gr.Markdown("For long or high-quality videos and small ZeroGPU quotas. Each press books **one GPU window** ""of the size you pick and stops at a *seam*: between denoise steps, between the transformer's ""blocks inside a step, or between the VAE's decode clips — so a single step or a decode that is ""longer than one window is finished over several presses. You get the finished video, or a ""**.pt state file** that is put in the box below automatically; press again (now, tomorrow, or ""from another browser) to continue from the exact seam. The .pt stays small; the half-finished ""block / decode parts are parked on this Space's disk (if the Space restarts you only redo that ""part). The state file holds the prompt, keyframes, conditioner output and latents, so the ""settings above do not have to match. Renders one pass (single mode). The window length does ""not limit the job's size — your total ZeroGPU quota sets how fast it finishes.")window_choice = gr.Dropdown(label="GPU window per press",choices=WINDOW_CHOICES,value=DEFAULT_WINDOW,info=("ZeroGPU quota you are willing to spend per press"+ (f"; on `{GPU_SIZE}` ZeroGPU counts double, so the window actually booked is "f"{BILLING_FACTOR}x shorter" if BILLING_FACTOR > 1 else "")+ ". A refused booking is retried with what is actually left."),)state_in = gr.File(label="State file to continue from (.pt)", file_types=[".pt"], type="filepath")with gr.Row():estimate_button = gr.Button("Estimate windows", size="sm")window_button = gr.Button("Run one GPU window", variant="secondary")state_out = gr.File(label="State file — keep it to continue (.pt)", interactive=False)window_status = gr.Markdown()cost = gr.Markdown()run_button = gr.Button("Generate video", variant="primary")15 unmodified lines)window_inputs = [prompt, first_frame, last_frame, canvas, duration, mode, steps, seed, upsample, lora, with_audio,window_choice, state_in,]window_button.click(run_window,window_inputs,[output_video, state_out, window_status, refined, state_in],api_name="generate_window",)estimate_button.click(estimate_window,[canvas, duration, steps, first_frame, last_frame, with_audio, window_choice, state_in],[window_status],api_name=False,)load_models()if __name__ == "__main__":demo.queue(default_concurrency_limit=None, max_size=None).launch(theme=gr.themes.Citrus(), show_error=True, allowed_paths=[OUTPUT_DIR])
app.py+895-1