Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion freevideo_engine/agent/media.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from pathlib import Path
import uuid

from .. import video_threads
from ..comfy_assets import media_kind_of

FPS = 24
Expand Down Expand Up @@ -248,7 +249,7 @@ def emit(writer, stream, array, sound, limit):
progress(dict(done=written, total=total))
try:
with av.open(str(temporary), 'w', format='mp4', options={'movflags': 'faststart'}) as writer:
stream = writer.add_stream('libx264', rate=FPS)
stream = video_threads.pin(writer.add_stream('libx264', rate=FPS))
stream.width, stream.height, stream.pix_fmt = width, height, 'yuv420p'
stream.options = dict(VIDEO_OPTIONS)
sound = _Audio(writer, rate) if rate else None
Expand Down
8 changes: 5 additions & 3 deletions freevideo_engine/chain_join.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
import shutil
import uuid

from . import video_threads

FPS = 24
SEAM_TAIL = 12000
SEAM_HEAD = 240
Expand Down Expand Up @@ -110,10 +112,10 @@ def _exact_tail(source, target, wanted, cancelled=None):
# Seek to the preceding key frame; only the remaining shown frames are encoded.
container.seek(begin + prefix * step, stream=video, backward=True)
with av.open(str(temporary), 'w', format='mp4') as output:
tail = output.add_stream('libx264', rate=FPS)
tail = video_threads.pin(output.add_stream('libx264', rate=FPS))
tail.width, tail.height, tail.pix_fmt = shape[1:4]
tail.time_base = shape[4]
# decode_to_file's encode_video uses these libx264 defaults and yuv420p.
# decode_to_file's encode_video uses these libx264 defaults (and its fixed thread count) and yuv420p.
encoded = 0
for frame in container.decode(video):
_check(cancelled)
Expand Down Expand Up @@ -221,7 +223,7 @@ def _conform(source, shape, directory, cancelled):
video = container.streams.video[0]
if abs(float(video.average_rate or 0) - FPS) > .01:
return None
picture = output.add_stream('libx264', rate=FPS)
picture = video_threads.pin(output.add_stream('libx264', rate=FPS))
picture.width, picture.height, picture.pix_fmt = shape[1:4]
picture.time_base = shape[4]
sound = container.streams.audio[0] if container.streams.audio else None
Expand Down
9 changes: 9 additions & 0 deletions freevideo_engine/comfy_launcher_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,15 @@ def register():
async def launcher(request):
return web.json_response(info)

# Observes the event loop only: when it stops answering for five seconds, what every thread was doing is written down once.
from . import loop_stall
server._freevideo_loop_watchdog = loop_stall.install(getattr(server, 'loop', None), info['engine_root'])

@server.routes.get('/freevideo/launcher/loop-stalls')
async def loop_stalls(request):
"""The latest times the engine's loop was held up: when, how long, the loop thread's innermost calls."""
return web.json_response(dict(stalls=loop_stall.public(loop_stall.read(info['engine_root']))), headers={'Cache-Control': 'no-store'})

@server.routes.get('/freevideo/launcher/last-exit')
async def last_exit(request):
"""When the ComfyUI before this one stopped by itself: numbers and fixed words, never log text."""
Expand Down
2 changes: 1 addition & 1 deletion freevideo_engine/decode.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ def phase(name):
wide_path.parent.mkdir(parents=True, exist_ok=True)
phase('vae_load')
from diffusers import AutoencoderKLMiniMaxH3
from diffusers.utils.export_utils import encode_video
from .video_threads import encode_video
from src.inference.render import PIXEL_MEAN, PIXEL_STD, FPS

started = time.perf_counter()
Expand Down
38 changes: 37 additions & 1 deletion freevideo_engine/diagnostics.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,19 @@
ABSOLUTE_PATH = long_paths.ABSOLUTE_PATH


SHORT_PROMPT = 4
# Scripts written without spaces between words (Myanmar, Hangul, Khmer, CJK, kana, Thai,
# Lao and others): a short prompt in one is removed at any position. web/error_panel.js
# has the same ranges (NO_WORD_BOUNDARY); a test compares the two.
NO_WORD_BOUNDARY_RANGES = (
(0x0e00, 0x0eff), (0x1000, 0x109f), (0x1100, 0x11ff), (0x1780, 0x17ff), (0x19e0, 0x19ff),
(0x2e80, 0x2fdf), (0x3005, 0x3007), (0x3021, 0x3029), (0x3038, 0x303b), (0x3040, 0x30ff),
(0x3130, 0x318f), (0x31f0, 0x31ff), (0x3400, 0x4dbf), (0x4e00, 0x9fff), (0xa960, 0xa97f),
(0xa9e0, 0xa9ff), (0xaa60, 0xaa7f), (0xac00, 0xd7ff), (0xf900, 0xfaff), (0xff66, 0xff9f),
(0xffa0, 0xffdc), (0x1b000, 0x1b16f), (0x20000, 0x3134f))
NO_WORD_BOUNDARY = re.compile('[%s]' % ''.join('%s-%s' % (chr(low), chr(high)) for low, high in NO_WORD_BOUNDARY_RANGES))


class Redactor:
def __init__(self, replacements=()):
self.replacements = sorted(((str(a), b) for a, b in replacements if len(str(a)) > 1),
Expand Down Expand Up @@ -76,7 +89,7 @@ def structured(self, value):
def text(self, value):
value = plain_text(value)
for prompt in sorted(self.prompts, key=len, reverse=True):
value = value.replace(prompt, '<PROMPT REMOVED>')
value = self._hide_prompt(value, prompt)
for secret in sorted(self.secrets, key=len, reverse=True):
value = value.replace(secret, '<REDACTED>')
for source, target in self.replacements:
Expand All @@ -93,6 +106,29 @@ def text(self, value):
value = ABSOLUTE_PATH.sub(self._path_match, value)
return value

@staticmethod
def _hide_prompt(value, prompt):
"""Remove a prompt; one under 4 characters only as a whole word.

"2" must not turn "2.00 GiB" into "<PROMPT REMOVED>.00 GiB". A short prompt is
not removed next to a letter (digits and underscores do not protect it:
"cat_0001", "Li2024@example.com"); a prompt of digits only is not removed next
to a digit or inside a decimal number. A side that is itself a symbol ("@xy",
"C++") has no such limit; a prompt in a script without word boundaries goes
everywhere, and so does any prompt of 4 characters or more."""
if len(prompt) >= SHORT_PROMPT or NO_WORD_BOUNDARY.search(prompt):
return value.replace(prompt, '<PROMPT REMOVED>')
if not any(ch.isalnum() for ch in prompt):
return value # spaces, ".", "-": nothing to hide, and removing them would ruin the text
digits = prompt.isascii() and prompt.strip('0123456789.,') == '' and any(ch.isdigit() for ch in prompt)
near = r'\d' if digits else r'[^\W\d_]'
left = '(?<!%s)' % near if prompt[0].isalnum() or prompt[0] == '_' else ''
right = '(?!%s)' % near if prompt[-1].isalnum() or prompt[-1] == '_' else ''
if digits:
left += r'(?<!\d[.,])'
right += r'(?![.,]\d)'
return re.sub(left + re.escape(prompt) + right, '<PROMPT REMOVED>', value)

@staticmethod
def _path_match(match):
return long_paths.path_match(match)
Expand Down
16 changes: 16 additions & 0 deletions freevideo_engine/encode_worker.py
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,12 @@ def _reserve(resident):
def encode(args, request, resident=None, diagnostics=None):
from .encoder_diagnostics import EncoderTrace
trace = diagnostics or EncoderTrace(request, resident=resident is not None)
if resident is not None and hasattr(resident, 'commit_cap'):
# The retained models are counted against the commit headroom too: what does not fit beside it goes
# (make_room) before the encoder is placed, instead of the encoder running the headroom out.
import torch
from .encoder_commit import live_cap
resident.commit_cap = lambda: live_cap(torch, resident.gpu_budget or 0) if resident.gpu_budget else None
try:
metrics = _encode(args, request, resident, trace)
except BaseException:
Expand All @@ -261,6 +267,9 @@ def encode(args, request, resident=None, diagnostics=None):
stop_model_read_ahead(trace)
trace.finish(False)
raise
finally:
if resident is not None and hasattr(resident, 'commit_cap'):
resident.commit_cap = None
stop_read_ahead(trace)
stop_model_read_ahead(trace)
result = trace.finish(True, metrics)
Expand Down Expand Up @@ -338,6 +347,13 @@ def phase(name, **metrics):
# a fixed 128 GB ceiling refused the request before encoding started.
# Clamp to the capacity the reserve is computed against.
budget = min(budget, total / 1e9)
# Windows commit backs the card's allocations: the encoder is placed within the headroom, and the layers
# beyond it stream from the checkpoint (not charged to commit) instead of taking the headroom to the guard.
from .encoder_commit import live_cap
commit_cap = live_cap(torch, budget * 1e9)
if commit_cap is not None:
loading['encoder_commit_gpu_cap_bytes'] = commit_cap
budget = commit_cap / 1e9
# Let the native model manager leave space for CUDA and live activations.
# This is placement guidance, not an enforced capacity result.
reserve_gib = max(0.5, (available - budget * 1e9 + 1e9) / 2**30)
Expand Down
61 changes: 61 additions & 0 deletions freevideo_engine/encoder_commit.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
"""GPU bytes Windows commit headroom can back while the text encoder is placed.

Windows charges every byte the CUDA allocator reserves to system commit. A native encoder that fits the card can
still take the commit headroom to the RAM guard's floor while its weights are placed (weights it leaves on the host
are read-only file mappings, which are not charged), and the request then stops with commit exhausted although
physical RAM is free. The sampling plan already keeps its GPU allocation inside the headroom (policy.commit_gpu_limit);
the encoder stage did not, because the budget it is given is the card's alone.

The cap here is the same idea for the encoder: the GPU the process already holds, plus the commit headroom, less what
its own CUDA context and working set add beside the weights and a spare for other programs. The encoder streams the
layers beyond the cap, so the arithmetic is unchanged; only the resident share of the weights gives way.
"""
GiB = 2**30
# The process's CUDA context, tokenizer, working set and encoder workspace beside the weights.
ENCODER_HOST_BYTES = 2 * GiB
# Growth of other programs during the stage.
ENCODER_SPARE_BYTES = GiB
# Below this the card's own budget stays: a smaller placement is slower than the failure it avoids.
ENCODER_GPU_FLOOR = 8 * GiB


def encoder_commit_gpu_cap(commit_available, held_gpu_bytes, request_budget):
"""Total GPU bytes (those the process already holds included) the commit headroom backs for the encoder;
None when it does not bind or is not known."""
if type(commit_available) is not int or commit_available < 0 or type(request_budget) is not int:
return None
held = held_gpu_bytes if type(held_gpu_bytes) is int and held_gpu_bytes > 0 else 0
limit = max(commit_available + held - ENCODER_HOST_BYTES - ENCODER_SPARE_BYTES,
min(request_budget, ENCODER_GPU_FLOOR))
return int(limit) if limit < request_budget else None


def live_commit_available():
"""Windows commit headroom now; None elsewhere or when it cannot be read."""
from .system import windows
if not windows():
return None
try:
from .win32 import memory_status
value = memory_status()['commit_available_bytes']
except Exception:
return None
return value if type(value) is int else None


def live_cap(torch, request_budget):
"""encoder_commit_gpu_cap from the live commit headroom and what this process holds on the card."""
commit = live_commit_available()
if commit is None:
return None
try:
held = int(torch.cuda.memory_reserved())
except Exception:
held = 0
return encoder_commit_gpu_cap(commit, held, int(request_budget))


def commit_exhausted(error):
"""Whether a RAM-guard failure is Windows commit exhaustion (physical RAM may be free)."""
text = str(error)
return isinstance(error, MemoryError) and 'commit headroom' in text and 'RAM guard' in text
4 changes: 2 additions & 2 deletions freevideo_engine/frame_upscale.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
import tempfile
import time

from . import processes
from . import processes, video_threads

STAGE = 'frame_upscale'
LONG_SIDE = 3840
Expand Down Expand Up @@ -303,7 +303,7 @@ def write(source, target, video, frame, emit, check):
sound = sound_reader.streams.audio[0] if sound_reader.streams.audio else None
with av.open(str(target), 'w', format='mp4',
options={'movflags': 'use_metadata_tags+faststart', 'movie_timescale': '48000'}) as output:
picture_stream = output.add_stream('libx264', rate=24)
picture_stream = video_threads.pin(output.add_stream('libx264', rate=24))
picture_stream.width, picture_stream.height, picture_stream.pix_fmt = width, height, 'yuv420p'
picture_stream.options = {'crf': '18', 'preset': 'fast'}
audio = output.add_stream_from_template(sound) if sound is not None else None
Expand Down
18 changes: 16 additions & 2 deletions freevideo_engine/image_gen/h3_pipeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -384,8 +384,22 @@ def _encode(prompt, *, encoder, comfy_root, comfy_python, model_paths, vram_gib,
if resident_endpoint:
os.environ[ENV] = resident_endpoint
try:
return _encode_once(prompt, encoder, comfy_root, comfy_python, model_paths, vram_gib, ram_gib, vision_images,
release_gpu=release_gpu)
try:
return _encode_once(prompt, encoder, comfy_root, comfy_python, model_paths, vram_gib, ram_gib, vision_images,
release_gpu=release_gpu)
except MemoryError as error:
import json
from ..encoder_commit import ENCODER_GPU_FLOOR, commit_exhausted
if not commit_exhausted(error):
raise
# Windows commit ran out while the weights were placed (physical RAM may be free). Once more with the
# card's share of the weights cut to the floor: the layers beyond it stream from the checkpoint, which
# commit does not charge, and the arithmetic is the same.
retry_gib = ENCODER_GPU_FLOOR / 2**30
print(json.dumps({'event': 'encoder_commit_retry', 'vram_gib': retry_gib}), flush=True)
return _encode_once(prompt, encoder, comfy_root, comfy_python, model_paths,
min(vram_gib, retry_gib) if vram_gib else retry_gib, ram_gib, vision_images,
release_gpu=release_gpu)
except BaseException as error:
# The caller's classifier keeps only a code; the text of the failure goes to the worker's log.
print('H3 encode failed: %s: %s' % (type(error).__name__, str(error)[-2000:]), file=sys.stderr, flush=True)
Expand Down
Loading