Spaces:
Running on Zero

workflow-studio / studio_service.py
owenisas's picture
Reference to video (Ref2VA), custom workflow nodes and chain templates
95e8794 verified
Raw History Blame Contribute Delete
9.68 kB
"""Local conditioning contract and resource checks shared by UI and API."""
from __future__ import annotations
import math
from collections.abc import Mapping
# Calibrated on three hosted runs (2026-10-22). Node speed varies about 6x:
# downloads 178-243 s, conditioning 11-75 s, generation 31-205 s, whole
# allocation 224-524 s. Allowances keep >=1.5x over the slowest run.
COLD_DOWNLOAD_ALLOWANCE_S = 370
WORKFLOW_RESERVATION_CAP_S = 900
def initialization_blockers(env: Mapping[str, str]) -> list[str]:
blockers = []
if env.get("WORKFLOW_STUDIO_ENABLE_INFERENCE") != "1":
blockers.append("inference_disabled")
if env.get("H3_LICENSE_AUTHORIZED") != "1" or not env.get("H3_LICENSE_AUTHORIZATION_REF", "").strip():
blockers.append("license_reference_missing")
if env.get("H3_AOTI", "0") != "0":
blockers.append("compiled_mode_not_supported")
if env.get("H3_TURBO_PROFILE", "off") != "off":
blockers.append("startup_fusion_not_supported")
return blockers
def validate_local_conditioning(plan, embeds, tags, height, width, num_frames):
"""Validate internal model output, without files, signatures or remote trust."""
if (height, width, num_frames) != (plan["height"], plan["width"], plan["num_frames"]):
raise ValueError("local conditioning geometry differs from the requested plan")
import torch
if (not isinstance(embeds, torch.Tensor) or not isinstance(tags, torch.Tensor)
or embeds.ndim != 3 or embeds.shape[0] != 1
or embeds.shape[1] < 1 or embeds.shape[2] < 1
or tags.ndim != 1 or tags.numel() != embeds.shape[1]
or not embeds.is_floating_point() or tags.dtype not in (torch.int32, torch.int64)
or embeds.device.type != "cpu" or tags.device.type != "cpu"
or not torch.isfinite(embeds).all().item()):
raise ValueError("invalid local conditioning tensor contract")
def conditioning_reservation_seconds(plan, has_first=False, has_last=False) -> int:
"""Local load and encode allowance, no downloads (measured 11-75 s)."""
pixels = plan["height"] * plan["width"] * plan["num_frames"]
estimate = math.ceil(110 + 25 * (int(has_first) + int(has_last))
+ pixels / (960 * 544 * 124) * 20 + len(plan["prompt"]) / 400)
if estimate > 480:
raise ValueError("conditioning workload exceeds the 480-second reservation cap")
return max(120, estimate)
def reservation_seconds(plan, text_rows: int) -> int:
"""Legacy denoise/decode estimate plus local load and eager-adapter allowances.
The base covers loading the ~72 GiB generator stage, which dominates on slow
nodes (31-205 s measured). Admission budgeting, not latency or billing.
"""
latents = 5 * ((plan["num_frames"] - 5) // 17) + 2
sequence = latents * (plan["height"] // 32) * (plan["width"] // 32)
sequence += round(plan["num_frames"] / 24 * 40) * 2 + int(text_rows)
denoise = plan["steps"] * (1.1745e-4 * sequence + 3.8396e-9 * sequence**2) * 1.3
decode = 15 + 25 * plan["height"] * plan["width"] * plan["num_frames"] / (960 * 544 * 124)
adapter_margin = 90 if plan["adapter"] != "off" else 0
estimate = math.ceil(175 + denoise + decode + adapter_margin + 10)
if estimate > 480:
raise ValueError("workload exceeds the 480-second reservation cap; use a smaller canvas/duration")
return max(120, estimate)
def conditioning_text_rows_bound(plan, has_first=False, has_last=False) -> int:
"""Bound Qwen byte-level tokens before downloading its tokenizer.
The pinned FL2VA encoder uses the verbatim prompt without a chat template.
Keyframes are resized to the bounded output canvas before vision encoding;
reserve 4096 rows per keyframe for vision tokens, its label and delimiters.
Check the actual row count before staging the generator as a backstop.
"""
return len(plan["prompt"].encode("utf-8")) + 4096 * (int(has_first) + int(has_last))
def workflow_reservation_seconds(plan, has_first=False, has_last=False, *, text_rows=None) -> int:
"""Reserve both existing stage budgets plus cold downloads in one allocation.
Downloads now consume allocation time to avoid reusing an expired proxy
token for a second scheduling call. This is conservative admission budgeting,
not measured latency or billing. Reject over-cap jobs; never clamp estimates.
"""
if text_rows is None:
text_rows = conditioning_text_rows_bound(plan, has_first, has_last)
estimate = (conditioning_reservation_seconds(plan, has_first, has_last)
+ reservation_seconds(plan, text_rows) + COLD_DOWNLOAD_ALLOWANCE_S)
if estimate > WORKFLOW_RESERVATION_CAP_S:
raise ValueError("workflow exceeds the 900-second reservation cap; use a smaller canvas/duration or fewer steps")
return estimate
# Ref2VA, mirroring the source Space's encoders: images resized to a 1024 px
# short edge and encoded as one frame; a video on its own aspect's canvas (768 px
# short edge, at most 1344x768), truncated and snapped down to 17n+5 frames; a
# soundtrack adds two rows per 1/40 s.
REFERENCE_IMAGE_SHORT_EDGE = 1024
REFERENCE_VIDEO_SHORT_EDGE, REFERENCE_VIDEO_MAX_PIXELS = 768, 1344 * 768
# Conditioning rows for a video reference are not derivable from metadata here;
# reserve this many and stop before generation if the conditioner exceeds it.
REFERENCE_VIDEO_TEXT_ROWS = 8192
def _video_canvas(width, height):
scale = min(REFERENCE_VIDEO_SHORT_EDGE / min(width, height),
math.sqrt(REFERENCE_VIDEO_MAX_PIXELS / (width * height)))
return tuple(max(32, round(edge * scale / 32) * 32) for edge in (height, width))
def reference_rows(references, num_frames) -> int:
"""Packed rows the reference encoders add, from probed metadata only."""
rows = 0
for ref in references:
if ref["kind"] == "image":
scale = REFERENCE_IMAGE_SHORT_EDGE / min(ref["width"], ref["height"])
height, width = (max(32, round(edge * scale / 32) * 32) for edge in (ref["height"], ref["width"]))
rows += (height // 32) * (width // 32)
continue
if ref["kind"] == "video":
height, width = _video_canvas(ref["width"], ref["height"])
frames = min(round(ref["seconds"] * 24), num_frames)
snapped = max(1, (frames - 5) // 17) * 17 + 5
rows += (5 * ((snapped - 5) // 17) + 2) * (height // 32) * (width // 32)
seconds = ref.get("audio_seconds") if ref["kind"] == "video" else ref.get("seconds")
if seconds:
rows += round(min(seconds, num_frames / 24) * 40) * 2
return rows
# Labels and vision delimiters around each reference ("<Picture i>: ", ...).
REFERENCE_LABEL_ROWS = 64
def reference_text_rows_bound(plan, references) -> int:
"""Conditioning rows to preallocate; checked against the real count before generation.
Qwen3-VL emits one vision row per 32x32 px of the resized image, the same
grid the generator encodes, so an image's rows bound its vision block.
"""
rows = len(plan["prompt"].encode("utf-8"))
for ref in references:
if ref["kind"] == "image":
rows += reference_rows([ref], plan["num_frames"]) + REFERENCE_LABEL_ROWS
elif ref["kind"] == "video":
rows += REFERENCE_VIDEO_TEXT_ROWS + REFERENCE_LABEL_ROWS
else:
rows += REFERENCE_LABEL_ROWS
return rows
def reference_conditioning_seconds(plan) -> int:
"""Ref2VA conditioner load and encode, per-kind weights as in the source conditioner."""
kinds = plan["references"]
pixels = plan["height"] * plan["width"] * plan["num_frames"]
estimate = math.ceil(110 + 25 * kinds.count("image") + 15 * kinds.count("audio")
+ 75 * kinds.count("video") + pixels / (960 * 544 * 124) * 20
+ len(plan["prompt"]) / 400)
if estimate > 480:
raise ValueError("reference conditioning exceeds the 480-second reservation cap")
return max(120, estimate)
def reference_generation_seconds(plan, text_rows: int, ref_rows: int) -> int:
"""Generator load, reference encoders, denoise over the packed sequence, and decode."""
latents = 5 * ((plan["num_frames"] - 5) // 17) + 2
sequence = latents * (plan["height"] // 32) * (plan["width"] // 32)
sequence += round(plan["num_frames"] / 24 * 40) * 2 + int(text_rows) + int(ref_rows)
denoise = plan["steps"] * (1.1745e-4 * sequence + 3.8396e-9 * sequence**2) * 1.3
decode = 15 + 25 * plan["height"] * plan["width"] * plan["num_frames"] / (960 * 544 * 124)
estimate = math.ceil(175 + 5 + ref_rows * 1e-3 + denoise + decode + 10)
if estimate > 480:
raise ValueError("reference workload exceeds the 480-second reservation cap; "
"use fewer or smaller references, a smaller canvas or a shorter duration")
return estimate
def reference_workflow_seconds(plan, references, *, text_rows=None) -> int:
"""One allocation: Ref2VA conditioning, generation and cold downloads; never clamped."""
if text_rows is None:
text_rows = reference_text_rows_bound(plan, references)
estimate = (reference_conditioning_seconds(plan)
+ reference_generation_seconds(plan, text_rows, reference_rows(references, plan["num_frames"]))
+ COLD_DOWNLOAD_ALLOWANCE_S)
if estimate > WORKFLOW_RESERVATION_CAP_S:
raise ValueError("workflow exceeds the 900-second reservation cap; use fewer or smaller "
"references, a smaller canvas or a shorter duration")
return estimate