diff --git a/constraints/windows-arm64.txt b/constraints/windows-arm64.txt new file mode 100644 index 00000000..832be1d6 --- /dev/null +++ b/constraints/windows-arm64.txt @@ -0,0 +1,98 @@ +# Windows on Arm (win_arm64, CPython 3.12) portable runtime. Same set as windows-portable.txt except the rows below. +# torch, torchvision and torchaudio come from NVIDIA's nvtorch_oot index (pypi.nvidia.com/nvtorch_oot/); every other wheel is on PyPI. +# Differences from the x64 set: the torch family (cu134), triton-windows 3.8, blake3 / cryptography / kornia-rs at the newest versions that ship a win_arm64 wheel. +# SageAttention has no win_arm64 build and is left out. Diffusers and antlr4-python3-runtime are built from source as on x64. +accelerate==1.14.0 +aiohappyeyeballs==2.7.1 +aiohttp==3.14.3 +aiosignal==1.4.0 +alembic==1.20.0 +annotated-doc==0.0.5 +annotated-types==0.8.0 +antlr4-python3-runtime==4.9.3 +anyio==4.15.1 +attrs==26.1.0 +av==18.1.0 +blake3==1.0.11 +certifi==2026.7.22 +cffi==2.1.1 +charset-normalizer==3.5.1 +click==8.5.0 +colorama==0.4.6 +comfy-aimdo==0.5.3 +comfy-angle==0.1.1 +comfy-kitchen==0.2.33 +comfyui-embedded-docs==0.5.11 +comfyui-frontend-package==1.51.10 +cryptography==46.0.3 +diffusers==0.40.0.dev0 +einops==0.8.2 +filelock==3.32.3 +frozenlist==1.8.0 +fsspec==2026.7.0 +greenlet==3.5.5 +h11==0.16.0 +hf-xet==1.6.1a0 +httpcore==1.0.9 +httpx==0.28.1 +huggingface-hub==1.30.0 +idna==3.19 +importlib-metadata==9.0.1 +jinja2==3.1.6 +kornia==0.8.3 +kornia-rs==0.1.15 +mako==1.4.1 +markdown-it-py==4.2.0 +markupsafe==3.0.3 +mdurl==0.1.2 +modelscope-hub==0.4.2 +mpmath==1.3.0 +multidict==6.8.0 +networkx==3.6.1 +ninja==1.13.2 +numpy==2.5.2 +omegaconf==2.3.1 +packaging==26.3 +peft==0.20.0 +pillow==12.3.0 +pip==26.2.1 +propcache==0.5.2 +psutil==7.2.2 +pycparser==3.0 +pydantic==2.13.5 +pydantic-core==2.46.5 +pydantic-settings==2.15.0 +pygments==2.21.0 +pyopengl==3.1.10 +pysocks==1.7.1 +python-dotenv==1.2.3 +pyyaml==6.0.3 +regex==2026.9.3 +requests==2.34.2 +rich==15.0.0 +safetensors==0.8.0 +scipy==1.18.1 +sentencepiece==0.2.2 +setuptools==78.1.0 +shellingham==1.5.4 +simpleeval==1.0.8 +socksio==1.0.0 +spandrel==0.4.2 +sqlalchemy==2.0.52 +sympy==1.14.0 +tokenizers==0.23.0rc0 +torch==2.14.0+cu134 +torchaudio==2.11.0+cu134 +torchsde==0.2.6 +torchvision==0.29.0+cu134 +tqdm==4.70.0 +trampoline==0.1.2 +transformers==5.15.0 +triton-windows==3.8.0.post28 +typer==0.27.2 +typing-extensions==4.16.0 +typing-inspection==0.4.4 +urllib3==2.7.0 +wheel==0.48.0 +yarl==1.24.5 +zipp==4.1.0 diff --git a/freevideo_engine/activation_staging.py b/freevideo_engine/activation_staging.py index 8a3e1d58..97a48256 100644 --- a/freevideo_engine/activation_staging.py +++ b/freevideo_engine/activation_staging.py @@ -1,4 +1,4 @@ -"""Contiguous D2H head groups with double-buffered CPU projection tiles.""" +"""Contiguous D2H head groups, joined into projection tiles on the device.""" import collections import contextlib import torch @@ -123,8 +123,6 @@ def __init__(self, rows, head_widths, dtype, tile_rows): self.dtype = dtype self.tile_rows = tile_rows self.groups = [torch.empty((self.capacity, width), dtype=dtype, pin_memory=True) for width in head_widths] - self.tiles = [torch.empty((tile_rows, sum(head_widths)), dtype=dtype, pin_memory=True) for _ in range(2)] - self.events = [None, None] self.copies = LockedCopies() def supports(self, rows, head_widths, dtype, tile_rows): @@ -137,19 +135,22 @@ def store(self, group, values): def project(self, module, output, rows): # The caller synchronizes once after all D2H groups have been written. - stream = torch.cuda.current_stream(output.device) - for index, start in enumerate(range(0, rows, self.tile_rows)): - slot = index % 2 - if self.events[slot] is not None: - self.events[slot].synchronize() + # Each group's rows of a tile are contiguous on the host, so they go to the + # device as they are and the tile is joined there. Joining it on the host, + # one strided copy per group and tile, kept the processor busy for most of + # the second pass at 1344x768x362 while the device waited (about 200k + # small copies a step). The tile holds the same values in the same rows, + # so the projection is unchanged bit for bit. The host-to-device copies and + # the next layer's device-to-host stores share the current stream, so a + # group is not overwritten before its rows have been read. + width = sum(self.widths) + for start in range(0, rows, self.tile_rows): count = min(self.tile_rows, rows - start) - tile = self.tiles[slot][:count] + device_values = torch.empty((count, width), dtype=self.dtype, device=output.device) offset = 0 - for group, width in zip(self.groups, self.widths): - tile[:, offset:offset + width].copy_(group[start:start + count]) - offset += width - device_values = self.copies.to_device(tile, output.device) - done = torch.cuda.Event() - done.record(stream) - self.events[slot] = done + for group, group_width in zip(self.groups, self.widths): + part = self.copies.to_device(group[start:start + count], output.device) + device_values[:, offset:offset + group_width].copy_(part) + del part + offset += group_width yield slice(start, start + count), module(device_values) diff --git a/freevideo_engine/agent/errors.py b/freevideo_engine/agent/errors.py index 55d21cfb..353e9626 100644 --- a/freevideo_engine/agent/errors.py +++ b/freevideo_engine/agent/errors.py @@ -612,7 +612,8 @@ def _failure_line(error): lines = str(error.get('message') or '').strip().splitlines() line = lines[0] if lines else '' if line.startswith('FreeVideo generation failed') and len(lines) > 1: - line = lines[1].strip() + # The engine puts the child's last error here as "Cause: " (failure_details). + line = re.sub(r'^Cause:\s+', '', lines[1].strip()) return re.sub(r'^(?:[\w.]*Error|[\w.]*Exception):\s*', '', line) diff --git a/freevideo_engine/agent/jobs.py b/freevideo_engine/agent/jobs.py index 04f40876..6482218d 100644 --- a/freevideo_engine/agent/jobs.py +++ b/freevideo_engine/agent/jobs.py @@ -87,6 +87,11 @@ def __init__(self, code, message, **details): self.code, self.message, self.details = code, message, details def view(self): + if self.details.get('show') is True: + # A fixed sentence written at the raise site (no path, name or backend text): it is the reason. + return errors.build(self.code, validation=True, message=self.message, details=[], + retry_after_seconds=self.details.get('retry_after_seconds'), + kind=self.details.get('kind'), report_id=self.details.get('report_id')) return errors.build(self.code, details=self.details.get('details'), owner=self.details.get('owner'), retry_after_seconds=self.details.get('retry_after_seconds'), @@ -1797,6 +1802,9 @@ def run(): except specs.SpecError as error: failure = ('failed', dict(code='invalid_request', message=str(error), details=error.errors)) except Exception as error: # noqa: BLE001 - a job must always end with a reason + # The request_id in the user's message is searched in the log: record the cause under it. + logging.getLogger(__name__).exception('agent job %s (%s) failed unexpectedly, request %s', + row.get('id'), row.get('kind'), row.get('request_id')) failure = ('failed', dict(code='internal_error', message='%s: %s' % ( type(error).__name__, str(error)[:2000]))) finally: diff --git a/freevideo_engine/agent/stems.py b/freevideo_engine/agent/stems.py index cecaa304..7aa15257 100644 --- a/freevideo_engine/agent/stems.py +++ b/freevideo_engine/agent/stems.py @@ -34,7 +34,7 @@ def run_stems(jobs, row, *, poll=.5): raise JobError('stems_failed', 'The clip media is not readable', kind='stems') from error source = found['audio'] if source is None: - raise JobError('stems_failed', 'The clip has no sound', kind='stems') + raise JobError('stems_failed', 'The clip has no sound', kind='stems', show=True) folder = '%s/%s-%s' % (FOLDER, row['id'], secrets.token_hex(4)) out = port.output_path(folder + '/dialogue.mp4', create=True).parent diff --git a/freevideo_engine/agent/voice.py b/freevideo_engine/agent/voice.py index 16778ffd..c3962938 100644 --- a/freevideo_engine/agent/voice.py +++ b/freevideo_engine/agent/voice.py @@ -218,7 +218,7 @@ def context(jobs, spec): raise JobError('voice_failed', 'The clip media is not readable') from error path = found_source['audio'] if path is None: - raise JobError('voice_failed', 'The clip has no sound') + raise JobError('voice_failed', 'The clip has no sound', show=True) wav = Path(path).with_suffix('.wav') return dict(clip=clip, parent=parent, dialogue=dialogue, separated=dialogue is not None, base=carrier.get('in', 0) / FPS, start=start, end=min(end, length), diff --git a/freevideo_engine/background_compile.py b/freevideo_engine/background_compile.py index a2aa7657..652b38c2 100644 --- a/freevideo_engine/background_compile.py +++ b/freevideo_engine/background_compile.py @@ -40,6 +40,9 @@ # Windows ends a stopped tree asynchronously: CUDA memory and the lease can # outlive the top process by seconds. RELEASE_SECONDS = 15. +# Beside the installation's receipt: its presence stops the run (precompile.STOP_ENV). +STOP_FILE = 'precompile.stop' + ATTEMPTS = 8 @@ -74,6 +77,9 @@ def __init__(self): self.attempts = [] self.root = None + def stop_path(self): + return Path(self.root) / STOP_FILE + def start(self, command, *, environment, cwd, log, lock, busy, delay=START_DELAY): """Run `command` once the session is quiet; False when this session already did. @@ -109,8 +115,23 @@ def stop(self, *, final=False): # instead of reading the exit as a finished run. row['stopped'] = True record(self.root, 'not_started', reason='foreground_work', final=final) + # The file first: the run gives way at its next checkpoint on + # every platform, before the signal's grace would end in a kill. + try: + if self.root is not None: + io_path(self.stop_path()).touch() + except OSError: + pass processes.stop(process, grace=STOP_GRACE) row['stop_seconds'] = time.monotonic() - tick + if gave_way(process): + # Its supervisor ended the tree and the run closed its own + # lease: a lease still held belongs to whoever took the card. + row.update(gave_way=True, released=None, release_seconds=row['stop_seconds']) + logging.info('[FreeVideo] Background compile gave way in %.1f s.', row['stop_seconds']) + return dict(row) + elif gave_way(process): + return None # Every process of the tree holds the lease; once it is free the # tree is gone, even when the top process had already exited. On a # timeout the request reports the busy lease. One deadline for all. @@ -170,10 +191,14 @@ def _work(self, command, environment, cwd, log, busy, delay): row = dict(started=time.time()) self.attempts.append(row) try: + # A stop file left by the last stop would end this run at once. + io_path(self.stop_path()).unlink(missing_ok=True) with io_path(log).open('ab') as stream: from .triton_compat import temporary_environment + from .precompile import STOP_ENV environment = temporary_environment(environment.get('FREEVIDEO_HOME') or self.lock.parent, environment) + environment = dict(environment, **{STOP_ENV: str(self.stop_path())}) process = self.process = processes.popen( command, env=environment, cwd=cwd, stdin=subprocess.DEVNULL, stdout=stream, stderr=subprocess.STDOUT, start_new_session=True, supervise=True) @@ -193,7 +218,9 @@ def _work(self, command, environment, cwd, log, busy, delay): with self.guard: # A stop in progress holds the guard and has marked the row. stopped = row.get('stopped') - if not stopped and self.process is process: + if not stopped and self.process is process and gave_way(process): + self.process = None + elif not stopped and self.process is process: # Ended by itself: confirm its tree let go before forgetting # it, so a later stop never waits on someone else's lease. row['released'] = self._released(time.monotonic() + RELEASE_SECONDS) @@ -212,4 +239,15 @@ def _work(self, command, environment, cwd, log, busy, delay): record(self.root, 'not_started') +def gave_way(process): + """The compile exited because the card or the memory was taken (BUSY_EXIT). + + Its supervisor (the Linux and Mac process hosts, the Windows Job closed by poll) ends every descendant before this + code is passed on, so the tree is gone. A lease still held belongs to whoever took the card, such as a warm-up + or a kept picture model, and a stop must not wait for it: a starting video stops those after this returns. + """ + from .precompile import BUSY_EXIT + return process.poll() == BUSY_EXIT + + COMPILE = BackgroundCompile() diff --git a/freevideo_engine/comfy_bridge.py b/freevideo_engine/comfy_bridge.py index f289c2eb..0c63bb1c 100644 --- a/freevideo_engine/comfy_bridge.py +++ b/freevideo_engine/comfy_bridge.py @@ -22,9 +22,10 @@ from .monitoring import save -# Longer than the idle encoder's yield window (YIELD_SECONDS plus its join slack), so a speculative -# warm-up of the previous request on the same device releases the lease before the wait runs out. -DEVICE_LEASE_WAIT_SECONDS = 20. +# Longer than the longest yield window of a speculative placement (idle_encoder.KEPT_YIELD_SECONDS when the +# worker keeps video models, plus its join slack), so a warm-up of the previous request on the same device +# releases the lease before the wait runs out. +DEVICE_LEASE_WAIT_SECONDS = 30. @contextlib.contextmanager diff --git a/freevideo_engine/comfy_monitor.py b/freevideo_engine/comfy_monitor.py index 6ef67c92..670aa075 100644 --- a/freevideo_engine/comfy_monitor.py +++ b/freevideo_engine/comfy_monitor.py @@ -98,7 +98,9 @@ def disk_free(path): return int(free) if isinstance(free, (int, float)) and free >= 0 else None -def snapshot(reader, root, busy, paused): +def snapshot(reader, root, busy, paused, local=True): + """local: the request came from this machine; others (the LAN) see only how much of the card another program + held, never its name or pid.""" result = {'busy': bool(busy), 'paused': bool(paused)} result.update(reader.read()) free = disk_free(root) @@ -107,12 +109,24 @@ def snapshot(reader, root, busy, paused): try: from . import server_mode # Why the video or picture models last left the card, newest last. - result['model_releases'] = server_mode.releases() + events = server_mode.releases() + if not local: + for event in events: + others = event.pop('other_programs', None) + if isinstance(others, list): + event['other_programs_gpu_bytes'] = [other.get('gpu_bytes') for other in others] + result['model_releases'] = events except Exception: pass return result +def from_this_machine(request): + """A request made on this machine itself, not one the LAN access proxy forwarded from another device.""" + from .proxy_identity import HEADER + return request.remote in ('127.0.0.1', '::1') and HEADER not in request.headers + + def register(): from aiohttp import web import asyncio @@ -143,7 +157,7 @@ def reply(value, status=200): @server.routes.get('/freevideo/monitor') async def read(request): - return reply(await asyncio.to_thread(snapshot, reader, root, busy(), gate.paused)) + return reply(await asyncio.to_thread(snapshot, reader, root, busy(), gate.paused, from_this_machine(request))) @server.routes.post('/freevideo/monitor/stop') async def stop(request): diff --git a/freevideo_engine/doctor.py b/freevideo_engine/doctor.py index c10295d2..b50e989d 100644 --- a/freevideo_engine/doctor.py +++ b/freevideo_engine/doctor.py @@ -2,7 +2,7 @@ import json import os import subprocess -import sys +from contextlib import nullcontext from .hardware import detect, installed_backends from .paths import vdn_root, base_path, checkpoint_path, comfy_root from .locking import LOCK_ENV, runtime_lock @@ -17,7 +17,9 @@ def missing_required_paths(result, *, video_models=True): return [k for k, row in result['paths'].items() if k not in skipped and not row['exists']] -def doctor(*, probe=False, hardware=None, backends=None, progress=None): +def doctor(*, probe=False, hardware=None, backends=None, progress=None, lease=None): + """``lease``: the descriptor of the GPU-work lease a caller already holds; the probes run under it + instead of taking the lease again, which the caller's own hold would refuse.""" if progress is None and os.environ.get('FREEVIDEO_INSTALL_PROGRESS') == '1': from .install_activity import step progress = step @@ -36,14 +38,16 @@ def doctor(*, probe=False, hardware=None, backends=None, progress=None): 'validation': 'Package and path discovery only. Run bench to check actual kernels and performance.'} if probe: result['kernel_probes'] = [] - with runtime_lock() as descriptor: + with (nullcontext(lease) if lease is not None else runtime_lock()) as descriptor: env = dict(os.environ, **{LOCK_ENV: str(descriptor)}) linear = ['linear'] + (['linear-int8'] if hardware.system in ('Windows', 'Linux') else []) probes = [*sorted(backends), *linear] for index, backend in enumerate(probes): if progress: progress('GPU tests running', index, len(probes)) - command = [sys.executable, '-m', 'freevideo_engine.probe', backend] + # The check finds this source itself (through the launch view, as compilers need): ComfyUI + # loads the engine by file location and starts without PYTHONPATH. + command = processes.module_command('freevideo_engine.probe', backend) try: child = subprocess_output.run_python(command, capture_output=True, timeout=180, env=env, pass_fds=(descriptor,), runner=processes.run) diff --git a/freevideo_engine/dubbing/service.py b/freevideo_engine/dubbing/service.py index 0f569cf7..8d8d4523 100644 --- a/freevideo_engine/dubbing/service.py +++ b/freevideo_engine/dubbing/service.py @@ -17,6 +17,7 @@ import uuid from . import backends, pack +from ..disk_space import ran_out from ..prompt_vlm.service import Worker OUTPUT = 'freevideo-dubbing' @@ -335,8 +336,11 @@ def work(self, root, machine, action, value): self.progress(dict(phase='failed', error=error.reason)) except Exception as error: reason = str(error) + if reason not in KNOWN: + logging.warning('[FreeVideo] Dubbing job %s failed: %s', action, type(error).__name__, exc_info=True) self.progress(dict(phase='failed', exception=type(error).__name__, - error=reason if reason in KNOWN else 'download_failed' if action == 'install' + error=reason if reason in KNOWN else 'disk_space' if isinstance(error, OSError) and ran_out(error) + else 'download_failed' if action == 'install' else 'dub_failed')) finally: if self.stop.is_set(): @@ -565,4 +569,6 @@ async def action(request): result = service.start(name, value) return web.json_response(result) except (ValueError, OSError) as error: + if isinstance(error, OSError): + logging.warning('[FreeVideo] Dubbing request failed: %s', type(error).__name__, exc_info=True) return web.json_response(dict(error=str(error) if str(error) in CODES else 'invalid_media'), status=400) diff --git a/freevideo_engine/encode_worker.py b/freevideo_engine/encode_worker.py index a30ccc1c..1bc005ae 100644 --- a/freevideo_engine/encode_worker.py +++ b/freevideo_engine/encode_worker.py @@ -21,6 +21,17 @@ def encoder_on_gpu(clip): patcher.loaded_size() >= patcher.model_size() > 0) +def cancel_check(cancel): + """Raise PreloadCancelled once the cancel file exists: speculative work yields to foreground work.""" + from .idle_encoder import PreloadCancelled + cancel = Path(cancel) + + def check(): + if cancel.exists(): + raise PreloadCancelled('New foreground work takes priority') + return check + + def preload(clip, request, resident): """Only weight placement; independent of the next prompt or input media.""" import torch @@ -407,9 +418,22 @@ def phase(name, **metrics): if clip is None: from .encoder_checkpoint import load_clip print(json.dumps({'event': 'encoder_load_start', 'encoder': name}), flush=True) - clip = load_clip(ckpt_paths=[path], embedding_directory=folder_paths.get_folder_paths('embeddings'), - clip_type=comfy.sd.CLIPType.MINIMAX, - model_options={'initial_device': torch.device('cpu')}, progress=phase) + from .idle_encoder import PreloadCancelled + try: + clip = load_clip(ckpt_paths=[path], embedding_directory=folder_paths.get_folder_paths('embeddings'), + clip_type=comfy.sd.CLIPType.MINIMAX, model_options={'initial_device': torch.device('cpu')}, + progress=phase, check=cancel_check(request['cancel']) if idle else None) + except PreloadCancelled: + # A speculative build stopped on the CPU, between layers: nothing reached the card or the cache, and the + # partial model goes now rather than with the process. + import gc + gc.collect() + result = dict(success=True, state='cancelled', stage='encoder_construct', + reason='New foreground work takes priority', + elapsed_seconds=time.perf_counter() - started) + save(request['metrics'], result) + print(json.dumps(dict(event='encoder_prewarm_complete', **result)), flush=True) + return result else: loading['checkpoint']['state'] = 'resident_reuse' print(json.dumps({'event': 'encoder_cache_hit', 'encoder': name, 'gpu_ready': encoder_on_gpu(clip)}), flush=True) diff --git a/freevideo_engine/encoder_checkpoint.py b/freevideo_engine/encoder_checkpoint.py index 90b64040..0c217918 100644 --- a/freevideo_engine/encoder_checkpoint.py +++ b/freevideo_engine/encoder_checkpoint.py @@ -7,8 +7,10 @@ import stat import struct import sys +import threading import warnings import weakref +from contextlib import contextmanager PACKAGE = Path(__file__).resolve().parent @@ -232,9 +234,60 @@ def release_mapped_pages(paths): return dict(advised_bytes=advised, errors=errors) if advised or errors else None +# Builds being checked, by thread: one shared hook on nn.Module serves them all, installed by the first and removed by +# the last, so overlapping builds never restore each other's replacement. +_checks = {} +_checks_lock = threading.Lock() +_native_load = [] + + +def _checked_load(self, *args, **kwargs): + check = _checks.get(threading.get_ident()) + if check is not None: + check() + return _native_load[0](self, *args, **kwargs) + + +@contextmanager +def checked_construction(check): + """Call ``check`` before each module of a native construction takes its weights, in this thread only. + + The native build is one call of a few seconds (5-6 s while a video starts beside it) that never looks back; a + speculative build asked to stop must not run to its end first. Every module's weights pass through + ``nn.Module._load_from_state_dict`` (ComfyUI's quantized operations extend it and call it), about 20 ms apart + for this encoder, so an exception from ``check`` ends the build there and the partial model is discarded. + Other threads loading meanwhile only pass through: their modules are never checked.""" + if check is None: + yield + return + import torch + owner = threading.get_ident() + with _checks_lock: + if not _checks and torch.nn.Module._load_from_state_dict is not _checked_load: + _native_load[:] = [torch.nn.Module._load_from_state_dict] + torch.nn.Module._load_from_state_dict = _checked_load + outer = _checks.get(owner) + _checks[owner] = check + try: + yield + finally: + with _checks_lock: + if outer is None: + del _checks[owner] + else: + _checks[owner] = outer + if not _checks: + # The native function stays in _native_load: a load another thread began just before this still + # passes through _checked_load and needs it. + if torch.nn.Module._load_from_state_dict is _checked_load: + torch.nn.Module._load_from_state_dict = _native_load[0] + + def load_clip(ckpt_paths, embedding_directory=None, clip_type=None, model_options=None, - disable_dynamic=False, progress=None): - """Keep the native CLIP construction and quantization, replace only file IO.""" + disable_dynamic=False, progress=None, check=None): + """Keep the native CLIP construction and quantization, replace only file IO. + + ``check`` (optional) is called between modules while the encoder is built; whatever it raises ends the build.""" import comfy.sd import comfy.utils options = {} if model_options is None else model_options @@ -259,8 +312,11 @@ def load_clip(ckpt_paths, embedding_directory=None, clip_type=None, model_option states.append(state) if progress: progress('encoder_construct') - clip = comfy.sd.load_text_encoder_state_dicts(states, embedding_directory=embedding_directory, - clip_type=clip_type, model_options=options, disable_dynamic=disable_dynamic) + if check is not None: + check() + with checked_construction(check): + clip = comfy.sd.load_text_encoder_state_dicts(states, embedding_directory=embedding_directory, + clip_type=clip_type, model_options=options, disable_dynamic=disable_dynamic) # Native patcher recreation must use the same reader, not return to COW. clip.patcher.cached_patcher_init = (load_clip_model_patcher, (ckpt_paths, embedding_directory, clip_type, options, disable_dynamic)) diff --git a/freevideo_engine/engine_preload.py b/freevideo_engine/engine_preload.py new file mode 100644 index 00000000..99a75596 --- /dev/null +++ b/freevideo_engine/engine_preload.py @@ -0,0 +1,120 @@ +"""The video model on the card before the next video asks for it. + +Every warm-up (the start of the app, a return after a release, the creation panel) put only the text encoder back on +the card: the first video after any of them still loaded the video model itself. Now the settings that decide whether +a loaded video model can serve a request (``ModelBank.engine_parts``: the model pack and LoRAs, the size and length, +the execution options the planner chose) are kept from the last successful video, and the warm-up loads the video +model with them into the resident worker, once the encoder is in place: + +- only into room that is free: the card holds the model beside everything on it now, and host memory holds the + weights it keeps there beside the next encoder's start, as after a video (``ModelBank.settle``); nothing else is + released for it; +- a next video with the same settings uses it (a hit); one with other settings loads its own, as before (a miss); +- a video or a picture that starts stops a preload under way, as it stops the encoder's placement. + +Each preload, hit and miss is logged and kept in the worker's status (``preloads``) with what differed. + +Nothing derived from a prompt, picture or seed is stored: only the model pack and input-cache folders, the size and +length, the planner's options and the card bytes the model took. +""" +import json +import os +from pathlib import Path +import time + +VERSION = 1 +NAME = 'last-video-model.json' +# The request fields a video model is built from (see worker.generate), none of them from a prompt, picture or seed. +KEPT = ('cache', 'input_cache_dir', 'engine_options', 'geometry', 'gpu_budget_bytes', 'gpu_reserve_bytes', + 'ram_budget_bytes', 'ram_budget_is_estimate', 'sampling_gpu_limit_bytes') +# Card room left beside a preloaded model: the allocator's own slack and another program's small growth. +CARD_SPARE_BYTES = 1 << 30 +CAPABILITY = 'engine-preload' + + +def path(root=None): + override = os.environ.get('FREEVIDEO_LAST_VIDEO_MODEL') + if override: + return Path(override) + if root is None: + from .system import install_root + root = install_root() + return Path(root) / '.freevideo' / NAME + + +def remember(request, card_bytes, allocator, root=None): + """Keep what the video model of a successful ``request`` was built from; ``card_bytes`` is what it took on the + card. A preview, an upscale, a continuation or a sound redo is kept like any other video: it is the last one.""" + if type(card_bytes) is not int or card_bytes <= 0 or not isinstance(request.get('engine_options'), dict): + return None + value = {name: request[name] for name in KEPT if name in request} + value.update(version=VERSION, card_bytes=card_bytes, allocator=allocator or '', saved_at=time.time()) + target = path(root) + target.parent.mkdir(parents=True, exist_ok=True) + temporary = target.with_name(target.name + '.tmp') + temporary.write_text(json.dumps(value), encoding='utf-8') + os.replace(temporary, target) + return value + + +def recall(root=None): + """The kept settings, or None when there are none or they cannot be read.""" + try: + value = json.loads(path(root).read_text(encoding='utf-8')) + except (OSError, ValueError): + return None + if (not isinstance(value, dict) or value.get('version') != VERSION or not isinstance(value.get('cache'), str) + or not isinstance(value.get('engine_options'), dict) or not isinstance(value.get('geometry'), dict) + or type(value.get('gpu_budget_bytes')) is not int or type(value.get('card_bytes')) is not int + or value['card_bytes'] <= 0): + return None + return value + + +def differences(before, after): + """What differs between two ``ModelBank.engine_parts``: 'cache', 'inputs', 'options.', 'geometry.'.""" + found = [] + for part in ('cache', 'inputs', 'options', 'geometry'): + old, new = before.get(part), after.get(part) + if isinstance(old, dict) and isinstance(new, dict) and part in ('options', 'geometry'): + found += ['%s.%s' % (part, name) for name in sorted(set(old) | set(new)) if old.get(name) != new.get(name)] + elif old != new: + found.append(part) + return found + + +def place(request, bank, factory, *, free_bytes, host_fits): + """In the resident worker: load the video model ``request`` describes into ``bank`` when it fits beside + everything held now. ``free_bytes`` is the card's free room (with the worker's own unused reserve) and + ``host_fits(bytes)`` whether host memory takes that much more beside the worker. Returns what happened.""" + from .resident_models import GiB, gpu_bytes + parts = bank.engine_parts(request) + identity = bank.engine_key(request) + entry = bank.entries.get('engine') + if entry is not None and entry['identity'] == identity: + bank.preloaded = dict(parts=parts, at=time.time()) + return dict(state='kept', reason='The video model with these settings is already loaded') + need = int(request['card_bytes']) + CARD_SPARE_BYTES + if entry is not None: + # The model loaded now was built for other settings: its room counts once it goes. + free_bytes += gpu_bytes(entry['model']) + if free_bytes < need: + return dict(state='skipped', reason='no_card_room', need_bytes=need, free_bytes=int(free_bytes)) + pinned = int(float(request['engine_options'].get('pin_host_gb') or 0) * 1e9) + # As settle keeps a model after a video: its host weights beside the next encoder's start. + if not host_fits(8 * GiB + pinned): + return dict(state='skipped', reason='no_host_room', pinned_bytes=pinned) + if entry is not None: + bank.drop('engine', 'Replaced by the video model of the last video settings') + started = time.perf_counter() + engine = factory() + bank.put('engine', identity, engine) + bank.preloaded = dict(parts=parts, at=time.time()) + return dict(state='loaded', seconds=round(time.perf_counter() - started, 2), gpu_bytes=gpu_bytes(engine)) + + +def worker_request(value, *, metrics, cancel): + """The resident worker's request for a preload of the kept ``value`` (from recall).""" + request = {name: value[name] for name in KEPT if name in value} + request.update(engine_preload=True, card_bytes=value['card_bytes'], metrics=str(metrics), cancel=str(cancel)) + return request diff --git a/freevideo_engine/failure_details.py b/freevideo_engine/failure_details.py index 55b6aed5..8b7e53a7 100644 --- a/freevideo_engine/failure_details.py +++ b/freevideo_engine/failure_details.py @@ -1203,6 +1203,20 @@ class names and errno, no text), when the message is that exception's str(); it _OWN_TYPES = {'ValueError', 'RuntimeError', 'TimeoutError'} +def raised_at(error): + """Where an exception was raised, for a log line that leaves out its message (which can carry paths or prompt + text): the innermost frame as file name, line and function, and FreeVideo's own innermost frame when that differs.""" + import traceback + frames = traceback.extract_tb(getattr(error, '__traceback__', None)) + if not frames: + return 'an unknown place' + + def place(frame): + return '%s:%s in %s' % (Path(frame.filename).name, frame.lineno, frame.name) + own = next((frame for frame in reversed(frames) if 'freevideo_engine' in Path(frame.filename).parts), None) + return place(frames[-1]) if own in (None, frames[-1]) else '%s (from %s)' % (place(frames[-1]), place(own)) + + def _raised_by_freevideo(exception): """The launcher's record says FreeVideo's own code raised this, in its own words: the first exception is one of the types it raises itself, carries no OS error number, and its innermost frame (when known) is FreeVideo's.""" diff --git a/freevideo_engine/hardware.py b/freevideo_engine/hardware.py index 78a52cb7..26fc668f 100644 --- a/freevideo_engine/hardware.py +++ b/freevideo_engine/hardware.py @@ -317,7 +317,10 @@ def detect(): from . import subprocess_output observed = _light_hardware() if observed is None: - code = 'import json; from freevideo_engine.hardware import _detect_local; print(json.dumps(_detect_local().to_dict()))' + # The probe finds this source itself: ComfyUI loads the engine by file location and starts without + # PYTHONPATH, and a portable Python's ._pth ignores it anyway. + code = ('import json, sys; sys.path.insert(0, %r); from freevideo_engine.hardware import _detect_local; ' + 'print(json.dumps(_detect_local().to_dict()))' % str(Path(__file__).resolve().parents[1])) result = subprocess_output.run_python([sys.executable, '-c', code], capture_output=True) if result.returncode: error = RuntimeError('Hardware detection failed: ' + result.stderr[-2000:]) diff --git a/freevideo_engine/idle_encoder.py b/freevideo_engine/idle_encoder.py index ededc56a..8eea26ee 100644 --- a/freevideo_engine/idle_encoder.py +++ b/freevideo_engine/idle_encoder.py @@ -55,6 +55,35 @@ class PreloadCancelled(Exception): # these seconds. One native transfer in flight cannot be interrupted, and on a # slow disk a single large weight takes longer than a second. YIELD_SECONDS = 6. +# The same while the worker keeps video models: stopping it then also drops them, and the video loads them again +# (about 30 s or more). The encoder's build is one native call that cannot stop midway (a few seconds). +KEPT_YIELD_SECONDS = 20. + + +def kept_models(endpoint): + """Roles and card bytes of the models other than the encoder that the resident worker at ``endpoint`` keeps.""" + from .resident_process import ENV, status + try: + held = status({ENV: str(endpoint)}) + return {str(row.get('role')): int(row.get('gpu_bytes') or 0) for row in held.get('models') or [] + if row.get('role') != 'encoder'} + except Exception: + return {} # Unknown: the usual yield time. + + +def stop_unyielding(worker, kept, result): + """Stop a worker whose cancelled request did not yield in time. The models it kept go with it: they are noted in + ``result`` and, in the process that owns the worker, recorded as a release.""" + try: + worker.stop_request(grace=.5) + except Exception: + pass # The caller stops it again and reports what failed. + if kept: + roles, released = sorted(kept), sum(kept.values()) + result.update(released_roles=roles, released_gpu_bytes=released) + from .resident_process import OWNER + if OWNER.process is not None: + OWNER.record(action='released', reason='preload_did_not_yield', roles=roles, released_gpu_bytes=released) @contextmanager @@ -134,7 +163,8 @@ def stop(self): if self.process is not None and self.process.poll() is None: processes.stop(self.process, grace=1.) if self.thread is not None: - self.thread.join(timeout=YIELD_SECONDS+2.) + # The controller's watch() gives the worker its yield time; this only bounds a controller that hangs. + self.thread.join(timeout=KEPT_YIELD_SECONDS+2.) if self.thread.is_alive(): # A blocked disk read/native copy is not indefinitely allowed # to delay the next prompt. The controller stops the real GPU @@ -212,33 +242,46 @@ def work(): def watch(endpoint, worker_request, environment, descriptor, result_path, cancelled, ram_budget_bytes, result, memory, - *, started=None, held=None, stop=None): + *, started=None, held=None, stop=None, module='freevideo_engine.encode_worker', + capability='encoder-weight-preload'): """Run one weights-only request in the resident worker under ``descriptor`` and watch it until it ends; the worker is appended to ``held`` as soon as it exists, so the caller can stop it. ``stop`` (an event) cancels it - like the cancel file. Returns its metrics.""" + like the cancel file. ``module`` and ``capability``: the encoder's placement, or the video model's preload + (freevideo_engine.worker, 'engine-preload'). + + Every speculative request in the resident worker is watched here, so this is the one place that decides how long + a cancelled request has to yield: KEPT_YIELD_SECONDS while the worker keeps video models, else YIELD_SECONDS, and + under live RAM pressure no more than YIELD_SECONDS. Past that the worker is stopped (stop_unyielding) and + PreloadCancelled raised. Returns its metrics.""" from .resident_process import RemoteProcess from .system import inference_headroom, inference_memory_sample, windows + # What the worker keeps before this request: the request only adds the encoder or the video model it loads. + kept = kept_models(endpoint) + patience = KEPT_YIELD_SECONDS if kept else YIELD_SECONDS worker = RemoteProcess(endpoint, - [sys.executable, '-B', '-m', 'freevideo_engine.encode_worker', '--request', str(worker_request)], + [sys.executable, '-B', '-m', module, '--request', str(worker_request)], environment, descriptor, result_path.with_name(result_path.stem+'-worker.log'), - required_capabilities=('encoder-weight-preload',)) + required_capabilities=(capability,)) if held is not None: held.append(worker) if started is not None: started(worker.pid) - cancel_started = None + cancel_started, pressed = None, False while worker.poll() is None: sample = memory.sample(worker.pid) used = inference_memory_sample(sample) if used is None or used > ram_budget_bytes or inference_headroom(sample) < (2 if windows() else 1)*2**30: cancelled.touch(exist_ok=True) result.update(state='released', reason='Live RAM pressure interrupted speculative loading') + pressed = True if stop is not None and stop.is_set() and not cancelled.exists(): cancelled.touch(exist_ok=True) result.update(state='released', reason='Another task took the card') if cancelled.exists(): cancel_started = cancel_started or time.monotonic() - if time.monotonic()-cancel_started > YIELD_SECONDS: + # Live RAM pressure never waits longer than the usual yield time. + if time.monotonic()-cancel_started > (min(patience, YIELD_SECONDS) if pressed else patience): + stop_unyielding(worker, kept, result) raise PreloadCancelled('Preload did not yield promptly; stop the worker before foreground work') try: worker.wait(timeout=.1) @@ -258,7 +301,7 @@ def place_now(endpoint, encoding, *, descriptor, environment, directory, gpu_bud ``encoding`` names the encoder recipe only (encoder, comfy_root, model_paths): no prompt or picture is sent. ``stop`` (set when a picture is asked for, or a video or another task takes the card) and live RAM pressure cancel it: a speculative placement does not page in its weights ahead and can take longer than the picture's own - load of the encoder, so a picture never waits for it.""" + load of the encoder, so a picture never waits for it. watch() decides how long it has to yield.""" from .ram import ProcessMemory from .resident_process import ENV directory = Path(directory) @@ -277,7 +320,8 @@ def place_now(endpoint, encoding, *, descriptor, environment, directory, gpu_bud return dict(result, reason='Another task took the card') try: result.update(watch(endpoint, worker_request, environment, descriptor, result_path, cancelled, - ram_budget_bytes, result, memory, held=held, stop=stop), resources=memory.result()) + ram_budget_bytes, result, memory, held=held, stop=stop), + resources=memory.result()) except BaseException as error: if held: try: diff --git a/freevideo_engine/image_gen/service.py b/freevideo_engine/image_gen/service.py index 9f9c0d78..fe7a62b8 100644 --- a/freevideo_engine/image_gen/service.py +++ b/freevideo_engine/image_gen/service.py @@ -24,12 +24,20 @@ from .. import server_mode from .loras import ERRORS as LORA_ERRORS, resolve_selection from ..disk_space import ran_out + + from ..download_settings import observed_speed from ..exit_diagnostics import clean_reading from ..monitoring import save from .failure import (Context, classify_exception, HOST_MESSAGE_ZH, host_memory_shortage, ERRORS, FailureError, MESSAGE_ZH, NO_REPORT, STAGES, UNIFIED_MESSAGE_ZH, classify_exception) +def write_refused(error): + """Whether an OSError says a folder or file cannot be written (no permission, read-only volume, in use).""" + import errno + return isinstance(error, PermissionError) or getattr(error, 'errno', None) in (errno.EACCES, errno.EPERM, errno.EROFS) + + BODY_LIMIT = 64 * 1024 CANCEL_GRACE = 5. MAX_IMAGES = 4 @@ -49,6 +57,8 @@ WARM_LEVELS = ('light', 'full') # How long after registration a server starts loading its models (ComfyUI finishes starting meanwhile). START_DELAY_SECONDS = 5. +# How often the host memory of a picture worker waiting between jobs is read. +HOST_READ_SECONDS = 5. # How long a step of a server-mode session (a trim of the video worker, an encoder placement) waits for the lease. LEASE_WAIT_SECONDS = 30. WARM_MODES = ('eager', 'conservative') @@ -772,7 +782,12 @@ def history_save(self, value): publish(temporary, target) finally: temporary.unlink(missing_ok=True) - except (OSError, Image.DecompressionBombError, SyntaxError): + except (OSError, Image.DecompressionBombError, SyntaxError) as error: + # A full disk or a folder that cannot be written is not a wrong picture: each has its own answer. + if isinstance(error, OSError) and ran_out(error): + raise ValueError('disk_full') from None + if isinstance(error, OSError) and write_refused(error): + raise ValueError('output_unwritable') from None raise ValueError('invalid_media') from None self.note_record(target, record) self.copy_to_output(target) @@ -1544,6 +1559,7 @@ def skipped(reason): self.loading_full = True if not alive: self.session_stop = threading.Event() + self.end_reason = None self.requests = queue.Queue() self.thread = threading.Thread(target=self.work, args=(root, machine), name='freevideo-image-gen', daemon=True) @@ -1617,7 +1633,9 @@ def place_encoder(self, root, machine, env, descriptor, stop=None): if endpoint is None: return dict(state='skipped', reason='no resident worker') hardware = detect() - policy = choose(hardware, available_backends=available_backends(hardware), allow_capacity_trial=True) + # From the saved kernel checks, never running them here: a check cannot be stopped for a video or a picture. + policy = choose(hardware, available_backends=available_backends(hardware, probe_missing=False), + allow_capacity_trial=True) directory = Path(endpoint).parent environment = dict(env, PYTHONPATH=str(source_root())) environment.pop(resident_process.ENV, None) @@ -1682,6 +1700,7 @@ def begin(self, key, root, machine, value, context): self._busy = True if self.thread is None or not self.thread.is_alive(): self.session_stop = threading.Event() + self.end_reason = None self.requests = queue.Queue() self.thread = threading.Thread(target=self.work, args=(root, machine), name='freevideo-image-gen', daemon=True) @@ -2068,7 +2087,10 @@ def stop_for_generation(self, only_idle=False, video=None): server_mode.note_keep('image', True, reason='video_start') return False self.yielding = True - self.end_reason = 'video_start' if not only_idle else 'lease_needed' + if self.thread is not None and self.thread.is_alive(): + # Only a session that is running ends for this; with none, a reason left here would be given to the + # next session's end, whatever ended it. + self.end_reason = 'video_start' if not only_idle else 'lease_needed' self.segment_stop.set() self.stop.set() self.session_stop.set() @@ -2253,6 +2275,8 @@ def work(self, root, machine): self.habit_root = root session = None started_resident = False + # The most host memory the worker tree took while it waited between jobs, for bringing it back (rewarm). + host_seen, host_read_at = 0, 0. failure = 'worker_exit' failure_error = None try: @@ -2340,6 +2364,10 @@ def respawn(): value = self.requests.get(timeout=.05) except queue.Empty: self.drain_warm(session) + if time.monotonic() - host_read_at >= HOST_READ_SECONDS: + host_read_at = time.monotonic() + host_seen = max(host_seen, resident_process.worker_memory( + session.process.pid).get('worker_rss_bytes') or 0) with self.mutex: if session.process.poll() is not None and self.requests.empty(): self.session_stop.set() @@ -2377,7 +2405,9 @@ def respawn(): if self._busy and placed.get('state') != 'ready': placed = dict(placed, state='stopped', reason='A picture was asked for') except Exception as error: # noqa: BLE001 - logging.warning('[FreeVideo] Encoder placement for the warm-up failed: %s', type(error).__name__) + from ..failure_details import raised_at + logging.warning('[FreeVideo] Encoder placement for the warm-up failed: %s at %s', + type(error).__name__, raised_at(error)) placed = dict(state='failed', reason='Encoder placement failed') with self.mutex: self.warm_placement = {k: placed.get(k) for k in ('state', 'reason', 'elapsed_seconds')} @@ -2439,7 +2469,8 @@ def respawn(): if session is not None and session.process.poll() == 0 else 'worker_exit') self.end_reason = None # The model it held comes back when the release only made room (rewarm). - server_mode.released('image', dict(action='released', reason=reason, held=self.loaded_model)) + server_mode.released('image', dict(action='released', reason=reason, held=self.loaded_model, + worker_rss_bytes=host_seen or None)) if started_resident and not resident_process.OWNER.active and not server_mode.coresident(): # The picture session started this worker only to hold the encoder between pictures # (with co-residency it stays: it is the video worker too). @@ -2813,11 +2844,12 @@ def clean_page_uploads(): from .. import video_warm videos = video_warm.warmer(installation, busy=lambda: video_busy() or service.busy()) token = secrets.token_urlsafe(24) - if server_mode.enabled(): - # A server loads its models as it starts, once ComfyUI has finished starting (its queue answers). + if server_mode.enabled() or server_mode.keeps_idle(): + # Models load as FreeVideo starts, once ComfyUI has finished starting (its queue answers): all of them on a + # server, the kinds used lately on a desktop. def load_at_start(): time.sleep(START_DELAY_SECONDS) - logging.info('[FreeVideo] Server mode: loading the models at start: %s', server_mode.warm()) + logging.info('[FreeVideo] Loading the models at start: %s', server_mode.warm_at_start()) threading.Thread(target=load_at_start, name='freevideo-server-start', daemon=True).start() @server.routes.get('/freevideo/image-gen') @@ -2832,6 +2864,10 @@ async def info(request): code = image_pack_error_code(error) return web.json_response(dict(error=code, message_en=image_pack_failure(code)['detail'], message_zh=image_pack_failure(code, zh=True)['detail']), status=409) + except Exception: + # A damaged model folder or pack record must not turn into a plain-text 500 that blocks every later action. + logging.getLogger(__name__).exception('image info failed') + return web.json_response(dict(error='model_unreadable', message_zh=MESSAGE_ZH['model_unreadable']), status=500) @server.routes.get('/freevideo/image-gen/report/{report_id}') async def report(request): @@ -2937,11 +2973,32 @@ async def action(request): code = str(error) if code in ('unknown_job', 'closed'): result = dict(error=code) - else: + elif isinstance(error, ValueError): code = code if code in ERRORS else 'invalid_request' result = dict(phase='failed', error=code, report_id=None, stage='start') if code in MESSAGE_ZH: result['message_zh'] = MESSAGE_ZH[code] + else: + # An OSError is not one of the request checks: a disk, a folder or a file went wrong, or something unexpected did. + # It says what it is and carries a report, instead of being called a wrong setting. + logging.getLogger(__name__).exception('image action failed') + if isinstance(error, OSError) and ran_out(error): + reason = 'disk_full' + elif isinstance(error, OSError) and write_refused(error): + reason = 'output_unwritable' + else: + reason = classify_exception(error) + try: + context = Context(request.match_info.get('action', ''), value if isinstance(value, dict) else {}) + result = service.failed(reason, context, error=error) + result.setdefault('error', reason) + if result['error'] in MESSAGE_ZH: + result.setdefault('message_zh', MESSAGE_ZH[result['error']]) + except Exception: + result = dict(phase='failed', error=reason, report_id=None, stage='start') + if reason in MESSAGE_ZH: + result['message_zh'] = MESSAGE_ZH[reason] + return web.json_response(result, status=500) return web.json_response(result, status=400) except Exception as error: # Any other fault still answers in JSON with a reason code, the stage and a report, so the page can show diff --git a/freevideo_engine/kernel_capabilities.py b/freevideo_engine/kernel_capabilities.py index d6b2e311..06118dc6 100644 --- a/freevideo_engine/kernel_capabilities.py +++ b/freevideo_engine/kernel_capabilities.py @@ -148,14 +148,14 @@ def withheld_without_receipt(hardware, discovered, receipt=None, expected=None): return withheld -def available_backends(hardware, *, discovered=None, probe_missing=True, evidence=None): +def available_backends(hardware, *, discovered=None, probe_missing=True, evidence=None, lease=None): """Reuse matching checks; re-probe after a GPU, driver or package/code change. Read-only planning may opt out of probing; it then offers the installed backends except those known not to run here (``withheld_without_receipt``). Execution callers never turn an unavailable requested backend into another backend or a math SDPA kernel. ``evidence``, a dict, receives which checks - the answer rests on. + the answer rests on. ``lease``: the GPU-work lease descriptor a caller already holds, for the probes. """ discovered = set(installed_backends() if discovered is None else discovered) saved = _saved_receipt() @@ -172,7 +172,7 @@ def available_backends(hardware, *, discovered=None, probe_missing=True, evidenc evidence.update(kernel_receipt='unmatched' if saved is not None else 'missing', withheld=withheld) return discovered - set(withheld) from .doctor import doctor - receipt = doctor(probe=True, hardware=hardware, backends=discovered) + receipt = doctor(probe=True, hardware=hardware, backends=discovered, lease=lease) checked = readiness(receipt['kernel_probes']) if not checked['ready']: raise RuntimeError('GPU kernel checks did not find a working linear and attention path. ' diff --git a/freevideo_engine/launcher/FComboBox.qml b/freevideo_engine/launcher/FComboBox.qml new file mode 100644 index 00000000..80157202 --- /dev/null +++ b/freevideo_engine/launcher/FComboBox.qml @@ -0,0 +1,43 @@ +import QtQuick +import QtQuick.Controls.Basic + +// A choice list in the app's own look: a field-like button and a popup in the sheet colour. +ComboBox { + id: control + implicitHeight: theme.heightSm + font.pixelSize: theme.micro + leftPadding: 12; rightPadding: 28 + contentItem: Text { + text: control.displayText; color: theme.text; font: control.font + verticalAlignment: Text.AlignVCenter; elide: Text.ElideRight + } + background: Rectangle { + radius: theme.radiusSm; color: theme.raised + border.width: control.visualFocus ? 2 : 1 + border.color: control.visualFocus ? theme.accent : control.hovered ? theme.sheen : theme.border + } + indicator: FIcon { kind: "chevron-down"; ink: theme.muted; x: control.width - width - 10; y: (control.height - height) / 2; width: 12; height: 12 } + delegate: ItemDelegate { + width: control.width; height: theme.heightSm + leftPadding: 12; rightPadding: 12 + highlighted: control.highlightedIndex === index + contentItem: Text { + text: control.textAt(index) + color: theme.text; font: control.font; verticalAlignment: Text.AlignVCenter; elide: Text.ElideRight + } + background: Rectangle { + radius: theme.radiusXs + color: parent.highlighted ? theme.accentSubtle : parent.hovered ? theme.surface : "transparent" + } + } + popup: Popup { + y: control.height + 4; width: control.width; padding: 4 + implicitHeight: Math.min(contentItem.implicitHeight + 8, 240) + contentItem: ListView { + clip: true; implicitHeight: contentHeight; model: control.popup.visible ? control.delegateModel : null + currentIndex: control.highlightedIndex + ScrollBar.vertical: FScrollBar {} + } + background: Rectangle { radius: theme.radiusSm; color: theme.canvas; border.color: theme.sheen } + } +} diff --git a/freevideo_engine/launcher/FIcon.qml b/freevideo_engine/launcher/FIcon.qml index 85668ba3..f0bf633b 100644 --- a/freevideo_engine/launcher/FIcon.qml +++ b/freevideo_engine/launcher/FIcon.qml @@ -12,6 +12,7 @@ Canvas { var c = getContext("2d"); c.reset(); c.scale(width/24, height/24) c.strokeStyle = ink; c.lineWidth = 1.6; c.lineCap = "round"; c.lineJoin = "round"; c.beginPath() if (kind === "folder") { c.moveTo(3,7); c.lineTo(3,19); c.lineTo(21,19); c.lineTo(21,7); c.lineTo(12,7); c.lineTo(10,4); c.lineTo(3,4); c.closePath() } + else if (kind === "chevron-down") { c.moveTo(5,9); c.lineTo(12,16); c.lineTo(19,9) } else if (kind === "play") { c.moveTo(8,4); c.lineTo(20,12); c.lineTo(8,20); c.closePath() } else if (kind === "terminal") { c.rect(2,4,20,16); c.moveTo(6,9); c.lineTo(9,12); c.lineTo(6,15); c.moveTo(12,15); c.lineTo(17,15) } else if (kind === "download") { c.moveTo(12,3); c.lineTo(12,15); c.moveTo(7,10); c.lineTo(12,15); c.lineTo(17,10); c.moveTo(4,16); c.lineTo(4,21); c.lineTo(20,21); c.lineTo(20,16) } diff --git a/freevideo_engine/launcher/FNav.qml b/freevideo_engine/launcher/FNav.qml index da72f17d..95bd65b6 100644 --- a/freevideo_engine/launcher/FNav.qml +++ b/freevideo_engine/launcher/FNav.qml @@ -36,9 +36,9 @@ Button { Rectangle { visible: control.selected; width: 3; height: 18; radius: 2; color: theme.accent; x: 0; anchors.verticalCenter: parent.verticalCenter } } Accessible.name: text - ToolTip { + FToolTip { objectName: "navToolTip" - visible: control.iconOnly && control.hovered + visible: control.iconOnly && control.hovered && !win.dialogShown text: control.text // Open into the content area instead of centring outside the left edge. x: control.width + 8 diff --git a/freevideo_engine/launcher/FScrollBar.qml b/freevideo_engine/launcher/FScrollBar.qml new file mode 100644 index 00000000..414253ba --- /dev/null +++ b/freevideo_engine/launcher/FScrollBar.qml @@ -0,0 +1,22 @@ +import QtQuick +import QtQuick.Controls.Basic + +// A thin rounded bar in the app's colours; it grows a little under the pointer. +ScrollBar { + id: bar + implicitWidth: 10; implicitHeight: 10 + padding: 2 + // The view's own bar sits along its edge; a replacement has to place itself the same way. + readonly property Item view: parent + readonly property bool upright: orientation === Qt.Vertical + x: !view ? 0 : upright ? (view.mirrored === true ? 0 : view.width - width) : (view.leftPadding || 0) + y: !view ? 0 : upright ? (view.topPadding || 0) : view.height - height + width: !view ? implicitWidth : upright ? implicitWidth : (view.availableWidth || view.width) + height: !view ? implicitHeight : upright ? (view.availableHeight || view.height) : implicitHeight + contentItem: Rectangle { + implicitWidth: 6; implicitHeight: 6; radius: 3 + color: bar.pressed ? theme.muted : bar.hovered ? theme.disabled : theme.border + opacity: bar.size < 1 && bar.policy !== ScrollBar.AlwaysOff ? 1 : 0 + } + background: null +} diff --git a/freevideo_engine/launcher/FToolTip.qml b/freevideo_engine/launcher/FToolTip.qml new file mode 100644 index 00000000..9b1bc7a1 --- /dev/null +++ b/freevideo_engine/launcher/FToolTip.qml @@ -0,0 +1,13 @@ +import QtQuick +import QtQuick.Controls.Basic + +// The launcher's hover tip: the sheet colour, a hairline edge and the app's own text, as the page tip in the editor. +ToolTip { + id: tip + delay: 400; padding: 8; leftPadding: 12; rightPadding: 12 + contentItem: Text { + text: tip.text; color: theme.text; font.pixelSize: theme.micro; wrapMode: Text.Wrap + width: Math.min(implicitWidth, 320) + } + background: Rectangle { radius: theme.radiusSm; color: theme.raised; border.color: theme.sheen } +} diff --git a/freevideo_engine/launcher/Main.qml b/freevideo_engine/launcher/Main.qml index 1dea3632..7b238167 100644 --- a/freevideo_engine/launcher/Main.qml +++ b/freevideo_engine/launcher/Main.qml @@ -14,6 +14,9 @@ ApplicationWindow { property var downloadExpanded: ({}) Connections { target: backend; function onChanged() { win.s = backend.state } } property bool settingsOpen: false + // Any dialog open: a hover tip of the page behind it is closed (the pointer stays on its control under the shade). + readonly property bool dialogShown: adalnDialog.visible || settings.visible || modelDialog.visible || archivesDialog.visible || updateDialog.visible + || releaseNotesPopup.visible || diskDialogOpen || licensesOpen || cleanupConfirm || releaseConfirm || closePending || closeChoice !== "" || !!s.notice property bool terminalOpen: false property bool lanPasswordEditing: false function firstLanLink() { return s.access_links && s.access_links.length ? s.access_links[0] : "" } @@ -454,10 +457,11 @@ ApplicationWindow { } } ScrollView { + ScrollBar.vertical: FScrollBar {} + ScrollBar.horizontal: FScrollBar { policy: ScrollBar.AlwaysOff } id: scroll; objectName: "pageScroll" anchors.top: header.bottom; anchors.bottom: footer.top; width: parent.width clip: true; contentWidth: availableWidth - ScrollBar.horizontal.policy: ScrollBar.AlwaysOff ColumnLayout { id: page width: Math.min(scroll.availableWidth - (win.narrow ? 24 : win.compact ? 36 : 64), 820) @@ -538,6 +542,8 @@ ApplicationWindow { } } ScrollView { + ScrollBar.vertical: FScrollBar {} + ScrollBar.horizontal: FScrollBar {} visible: errorDetailsOpen && !notAFault; Layout.fillWidth: true; Layout.preferredHeight: Math.min(160, errorText.implicitHeight+10); clip: true TextArea { id: errorText; objectName: "failureDetails"; text: s.error; readOnly: true; selectByMouse: true; wrapMode: Text.Wrap; color: theme.muted; font.family: theme.mono; font.pixelSize: theme.micro; background: null; textFormat: TextEdit.PlainText } } @@ -594,7 +600,8 @@ ApplicationWindow { Layout.fillWidth: true; spacing: 8 FField { objectName: "installationPath"; Layout.fillWidth: true; value: s.form.new_comfy ? s.form.destination : s.form.comfy; placeholderText: t("Choose a folder", "选择文件夹"); enabled: s.can_manage; onEditingFinished: backend.edit(s.form.new_comfy ? "destination" : "comfy", text) // Keep the recognizable end visible; hovering reveals the whole path. - hoverEnabled: true; ToolTip.text: text; ToolTip.delay: 500; ToolTip.visible: hovered && text.length > 0 } + hoverEnabled: true + FToolTip { objectName: "installationPathTooltip"; text: parent.text; delay: 500; visible: parent.hovered && parent.text.length > 0 && !win.dialogShown } } FButton { objectName: "installationBrowse"; text: t("Browse…", "浏览…"); enabled: s.can_manage; implicitHeight: theme.height + 4; onClicked: backend.browse(s.form.new_comfy ? "destination" : "comfy") } } FText { visible: !s.form.new_comfy; text: t("Uses your existing Python when available. A separate environment loads only FreeVideo.", "优先使用已有 Python;独立环境仅加载 FreeVideo。"); color: theme.muted; font.pixelSize: theme.micro; Layout.fillWidth: true } @@ -1203,11 +1210,8 @@ ApplicationWindow { Layout.fillWidth: true; spacing: 6 FIcon { kind: "terminal"; ink: theme.muted; Layout.preferredWidth: 16; Layout.preferredHeight: 16 } FText { text: t("Terminal", "终端"); font.pixelSize: theme.micro; font.weight: Font.DemiBold; color: theme.muted; Layout.rightMargin: 8 } - ComboBox { - visible: s.logs.length > 1; model: s.logs; textRole: "label"; Layout.fillWidth: true; Layout.maximumWidth: 260; implicitHeight: 30 - font.pixelSize: theme.micro - palette.button: theme.raised; palette.buttonText: theme.text; palette.window: theme.surface; palette.windowText: theme.text - palette.base: theme.surface; palette.text: theme.text; palette.highlight: theme.accentSubtle; palette.highlightedText: theme.text; palette.dark: theme.muted; palette.mid: theme.border; palette.light: theme.raised + FComboBox { + visible: s.logs.length > 1; model: s.logs; textRole: "label"; Layout.fillWidth: true; Layout.maximumWidth: 260 onActivated: backend.terminal(s.logs[currentIndex].path) } Item { Layout.fillWidth: true } @@ -1221,6 +1225,8 @@ ApplicationWindow { } FText { Layout.fillWidth: true; font.pixelSize: theme.micro; color: theme.muted; text: t("Copy or export the full log with private information hidden.", "可复制或导出完整日志,隐私信息已隐藏。") } ScrollView { + ScrollBar.vertical: FScrollBar {} + ScrollBar.horizontal: FScrollBar {} id: terminalScroll; Layout.fillWidth: true; Layout.fillHeight: true; clip: true TextArea { id: terminalText; objectName: "terminalText"; text: s.log || t("Activity will appear here after startup.", "启动后将在这里显示运行记录。"); textFormat: TextEdit.PlainText @@ -1262,12 +1268,13 @@ ApplicationWindow { options: [{value: "downloads", label: t("Downloads", "下载")}, {value: "general", label: t("Preferences", "偏好")}, {value: "advanced", label: t("Environment", "环境")}] } ScrollView { + ScrollBar.vertical: FScrollBar {} + ScrollBar.horizontal: FScrollBar { policy: ScrollBar.AlwaysOff } id: settingsScroll Layout.fillWidth: true; Layout.fillHeight: true; contentWidth: availableWidth; clip: true // The list never scrolls sideways; its hidden bar would take the clicks along the bottom edge. - ScrollBar.horizontal.policy: ScrollBar.AlwaysOff ColumnLayout { - width: settingsScroll.availableWidth; spacing: 18 + width: settingsScroll.availableWidth - settingsScroll.ScrollBar.vertical.width; spacing: 18 FText { objectName: "settingsActionNotice"; visible: !!s.action_notice && s.action_notice !== s.busy_reason; text: s.action_notice || ""; color: theme.muted; Layout.fillWidth: true } FText { objectName: "settingsBusyReason"; visible: (!s.can_manage || !s.can_cleanup) && (!s.action_notice || s.action_notice === s.busy_reason); text: s.busy_reason; color: theme.muted; Layout.fillWidth: true } ColumnLayout { @@ -1656,12 +1663,14 @@ ApplicationWindow { contentItem: ColumnLayout { id: modelContent; spacing: 12 ScrollView { + ScrollBar.vertical: FScrollBar {} + ScrollBar.horizontal: FScrollBar {} id: modelScroll; objectName: "downloadListScroll" Layout.fillWidth: true; Layout.fillHeight: true; Layout.minimumWidth: 0; Layout.minimumHeight: 0 implicitHeight: downloadBody.implicitHeight clip: true; contentWidth: availableWidth ColumnLayout { - id: downloadBody; width: modelScroll.availableWidth; spacing: 12 + id: downloadBody; width: modelScroll.availableWidth - modelScroll.ScrollBar.vertical.width; spacing: 12 FText { text: downloads.copy.title; font.pixelSize: theme.section + 2; font.weight: Font.DemiBold; Layout.fillWidth: true } FText { objectName: "downloadListTotal"; visible: downloads.available; text: downloads.total; font.weight: Font.DemiBold; color: theme.accent; Layout.fillWidth: true } FText { objectName: "videoModelGuide"; text: downloads.copy.guide; color: theme.muted; Layout.fillWidth: true; font.pixelSize: theme.micro + 1 } @@ -1779,9 +1788,11 @@ ApplicationWindow { contentItem: ColumnLayout { spacing: 14 ScrollView { + ScrollBar.vertical: FScrollBar {} + ScrollBar.horizontal: FScrollBar {} id: archivesScroll; Layout.fillWidth: true; Layout.fillHeight: true; clip: true; contentWidth: availableWidth ColumnLayout { - id: archivesContents; width: archivesScroll.availableWidth; spacing: 14 + id: archivesContents; width: archivesScroll.availableWidth - archivesScroll.ScrollBar.vertical.width; spacing: 14 FText { objectName: "archivesDialogTitle"; text: s.archives_dialog.title; font.pixelSize: theme.section + 2; font.weight: Font.DemiBold; Layout.fillWidth: true } FText { objectName: "archivesDialogText"; color: theme.muted; Layout.fillWidth: true @@ -1802,7 +1813,7 @@ ApplicationWindow { color: theme.muted; font.pixelSize: theme.micro; Layout.fillWidth: true wrapMode: Text.NoWrap; elide: Text.ElideMiddle; maximumLineCount: 1 MouseArea { id: folderHover; anchors.fill: parent; hoverEnabled: true; acceptedButtons: Qt.NoButton } - ToolTip { objectName: "archivesFolderTooltip-" + archiveGroup.index; text: archiveGroup.modelData.folder; visible: folderHover.containsMouse; delay: 300 } + FToolTip { objectName: "archivesFolderTooltip-" + archiveGroup.index; text: archiveGroup.modelData.folder; visible: folderHover.containsMouse && parent.truncated; delay: 300 } } Repeater { model: archiveGroup.modelData.files @@ -1852,6 +1863,8 @@ ApplicationWindow { zh: s.zh; radius: theme.radiusLg; maxHeight: Math.round(win.height * 0.4) } ScrollView { + ScrollBar.vertical: FScrollBar {} + ScrollBar.horizontal: FScrollBar {} id: updateScroll; Layout.fillWidth: true; Layout.fillHeight: true; clip: true; contentWidth: availableWidth ColumnLayout { // Clear of the scroll bar's strip whether or not the bar shows, so no line runs under it and the width never @@ -1903,10 +1916,11 @@ ApplicationWindow { contentItem: ColumnLayout { spacing: 14 ScrollView { + ScrollBar.vertical: FScrollBar { policy: licenseScroll.overflows ? ScrollBar.AlwaysOn : ScrollBar.AlwaysOff } + ScrollBar.horizontal: FScrollBar {} id: licenseScroll; objectName: "licensesScroll"; Layout.fillWidth: true; Layout.fillHeight: true; clip: true; contentWidth: availableWidth // Shown whenever the list runs past the window, so a row below the last divider is not missed. readonly property bool overflows: height > 0 && licenseContents.implicitHeight > height - ScrollBar.vertical.policy: overflows ? ScrollBar.AlwaysOn : ScrollBar.AlwaysOff ColumnLayout { // Clear of the scroll bar, so it never covers a link. id: licenseContents; width: licenseScroll.availableWidth - (licenseScroll.overflows ? 14 : 0); spacing: 12 @@ -1982,6 +1996,8 @@ ApplicationWindow { zh: s.zh; radius: theme.radiusLg; maxHeight: Math.round(win.height * 0.4) } ScrollView { + ScrollBar.vertical: FScrollBar {} + ScrollBar.horizontal: FScrollBar {} Layout.fillWidth: true; Layout.fillHeight: true id: releaseScroll; clip: true; contentWidth: availableWidth ColumnLayout { diff --git a/freevideo_engine/locking.py b/freevideo_engine/locking.py index 3cb0d13a..147e79bf 100644 --- a/freevideo_engine/locking.py +++ b/freevideo_engine/locking.py @@ -119,6 +119,18 @@ def _linux_holder(pid): return _holder_line(pid, executable, command, seconds) +def _windows_command(pid): + """The allowlisted words of a process's command line, or '' when it cannot be read.""" + try: + import psutil + arguments = psutil.Process(pid).cmdline() + except Exception: + return '' + if not arguments: + return '' + return _lock_command('\0'.join(arguments).encode('utf-8', errors='replace'))[1] + + def _windows_lock_holders(paths, deadline, lines): """Restart Manager is read-only here: never request a shutdown or restart.""" import ctypes @@ -200,6 +212,11 @@ class ProcessInfo(ctypes.Structure): size = c_uint32(len(image)) if kernel.QueryFullProcessImageNameW(handle, 0, image, ctypes.byref(size)): lines[position] = _holder_line(pid, image.value, seconds=seconds) + # The image is python.exe for every FreeVideo process; its -m module (allowlisted, as on + # Linux) tells a warm-up worker from a compile or a generation. + command = _windows_command(pid) if time.monotonic() < deadline else '' + if command: + lines[position] = _holder_line(pid, image.value, command, seconds) except Exception: pass finally: diff --git a/freevideo_engine/lora_check.py b/freevideo_engine/lora_check.py index 6e56c93a..6d0a466e 100644 --- a/freevideo_engine/lora_check.py +++ b/freevideo_engine/lora_check.py @@ -63,6 +63,12 @@ def _layout(): # Step-distillation adapters (for example parallel-decoding ones) ship a bank of # whole replacement output heads, one per stretch of the sampling schedule. HEADS = ('proj_out', 'audio_proj_out') +HEAD_SHAPES = {tuple(LAYOUT[name]) for name in HEADS} +# Conversions of the same adapters store that bank another way: flattened on the output head under a name no LoRA +# factor has (ComfyUI set_weight / reshape_weight, PTD orig_weight), and they say what they are in their metadata. +STEP_HEAD = re.compile(r'(?:^|\.)(?:proj_out|audio_proj_out|final_layer\.(?:video|audio)_out)\.(?:bias\.)?' + r'(?:set_weight|set_bias|reshape_weight|orig_weight|orig_bias)$') +STEP_METADATA = re.compile(r'(?:h3_)?p[dt]d_') _CACHE, _LOCK = {}, threading.Lock() @@ -108,11 +114,15 @@ def _find(target): ('sd', re.compile(r'down_blocks|up_blocks|input_blocks|lora_te|text_model'))) +# A language model (a prompt rewriter, a text encoder) also has self_attn layers; it is not a Wan model. +LANGUAGE_MODEL = re.compile(r'language_model\.|text_encoders?\.|(?:^|\.)layers\.\d+\.(?:mlp|self_attn|linear_attn)\.') + + def family(keys): """Which other model a file's layer names belong to, or None when they match none we know.""" for name, pattern in FAMILIES: if any(pattern.search(key) for key in keys): - return name + return 'llm' if name == 'wan' and any(LANGUAGE_MODEL.search(key) for key in keys) else name return None @@ -121,16 +131,25 @@ def _bad(reason, keys, **detail): def _head_bank(shapes): - """The first tensor that is a stack of whole output-head weights, or None.""" + """The first tensor that is a stack of whole output-head weights, under any name, or None. LoRA factors are + two-dimensional, so a three-dimensional tensor shaped like an output head is never one.""" for key, shape in shapes.items(): - if not key.endswith('.weight') or len(shape) != 3: - continue - name = _targets(key[:-7])[0][0] - if name in HEADS and list(shape[1:]) == list(LAYOUT[name]): + if len(shape) == 3 and tuple(shape[1:]) in HEAD_SHAPES: return key return None +def _step_adapter(shapes, metadata): + """For a file that is not a LoRA we can read: the tensor that marks it as a step-distillation adapter stored + another way (its output heads flattened, or its metadata saying so), or None.""" + marked = next((key for key in shapes if STEP_HEAD.search(key)), None) + if marked: + return marked + if metadata and any(STEP_METADATA.match(str(name)) for name in metadata): + return next((key for key in shapes if not supported(key)), None) or next(iter(shapes), None) + return None + + def _block(target): found = re.search(r'blocks\.(\d+)\.', target) return int(found[1]) + 1 if found else None @@ -150,22 +169,26 @@ def assess(shapes, *, int8_targets=None, skipped=None, metadata=None): heads = _head_bank(shapes) if heads: return _bad('acceleration', keys, layer=heads) + + def unreadable(layer): + step = _step_adapter(shapes, metadata) + return _bad('acceleration', keys, layer=step) if step else _bad('format', keys, layer=layer) try: pairs, full = adapter_keys(keys) except ValueError: if family(keys): return _bad('other-model', keys, layer=None) - return _bad('format', keys, layer=next((key for key in keys if not supported(key)), None)) + return unreadable(next((key for key in keys if not supported(key)), None)) if not any('A' in pair for pair in pairs.values()) and not full: - return _bad('format', keys, layer=None) + return unreadable(None) wrong, applied = [], set() skipped = [] if skipped is None else skipped for name, pair in pairs.items(): if not {'A', 'B'} <= pair.keys(): - return _bad('format', keys, layer=name) + return unreadable(name) a, b = shapes[pair['A']], shapes[pair['B']] if len(a) != 2 or len(b) != 2 or a[0] != b[1] or a[0] <= 0: - return _bad('format', keys, layer=name) + return unreadable(name) for target, split, swap in _targets(name): if int8_targets is not None: target = resolve_target(target, int8_targets) diff --git a/freevideo_engine/macos_generate.py b/freevideo_engine/macos_generate.py index 72003f6a..d78efc66 100644 --- a/freevideo_engine/macos_generate.py +++ b/freevideo_engine/macos_generate.py @@ -40,6 +40,10 @@ def floor(): return floor +MEMORY_BREAKDOWN = ('free_bytes', 'inactive_bytes', 'active_bytes', 'wired_bytes', 'compressor_physical_bytes', + 'compressor_logical_bytes', 'swap_total_bytes', 'swap_free_bytes') + + def policy(args, memory=None): from .system import system_memory memory = memory or system_memory() @@ -70,6 +74,10 @@ def amount(name, default): -down(-(reserve + 2 * GiB)))) # What the system reported at this moment, so the report shows whether the Mac is small or busy. error.memory_record = dict(total_bytes=memory['total_bytes'], available_bytes=memory['available_bytes'], reserve_bytes=reserve) + # How the Mac splits its memory (free, cached, in use, compressed, swap) separates a small Mac from a busy one. + for key in MEMORY_BREAKDOWN: + if type(memory.get(key)) is int and memory[key] >= 0: + error.memory_record[key] = memory[key] if getattr(args, 'ram_gib', None) is not None: error.memory_record['launcher_limit_bytes'] = amount('ram_gib', None) raise error @@ -398,6 +406,8 @@ def execute(value, name, module='freevideo_engine.macos_generate'): cancelled=isinstance(error, KeyboardInterrupt)) if getattr(error, 'memory_record', None): report['preflight_memory'] = error.memory_record + if 'runtime_hardware' not in report: + identify_refused(report, inventory, code_identity) raise finally: processes.restore_handlers(previous) @@ -406,6 +416,18 @@ def execute(value, name, module='freevideo_engine.macos_generate'): write_debug(output) +def identify_refused(report, inventory, code_identity): + """Name the chip, system and code of a request that stopped before its own record of them. + + Each lookup stands alone, so a failing one never hides the error being reported.""" + for key, lookup in (('runtime_hardware', lambda: inventory()['hardware']), ('runtime_code', code_identity), + ('runtime_software', runtime_software)): + try: + report[key] = lookup() + except Exception: + pass + + def runtime_software(): """The system and library versions a Metal failure depends on.""" versions = dict(macos=platform.mac_ver()[0]) diff --git a/freevideo_engine/managed.py b/freevideo_engine/managed.py index a19e17e8..5502e0f3 100644 --- a/freevideo_engine/managed.py +++ b/freevideo_engine/managed.py @@ -13,6 +13,10 @@ from . import processes from .system import windows +# A generation that finds the lease taken waits this long for it: a warm-up, a background compile or a kept +# picture model that is still letting go after the request stopped it. Past that the busy message names the holders. +GENERATE_LEASE_WAIT_SECONDS = 60. + def command_for(machine, command, arguments): defaults = {} @@ -119,7 +123,8 @@ def _main(argv=None, *, lock_paths=None): lock_path = os.environ.get('FREEVIDEO_LOCK_PATH', str(Path(snapshot['root']) / 'engine.lock')) if lock_paths is not None: lock_paths.append(lock_path) - with nullcontext() if readonly else runtime_lock(lock_path, wait_seconds=3 if command == 'generate' else 0) as descriptor: + wait = GENERATE_LEASE_WAIT_SECONDS if command == 'generate' else 0 + with nullcontext() if readonly else runtime_lock(lock_path, wait_seconds=wait) as descriptor: machine = json.loads(config.read_text(encoding='utf-8')) if machine != snapshot: raise ValueError('Installation changed while starting. Rerun the command.') diff --git a/freevideo_engine/precompile.py b/freevideo_engine/precompile.py index 6f48ee59..db4f6659 100644 --- a/freevideo_engine/precompile.py +++ b/freevideo_engine/precompile.py @@ -66,15 +66,53 @@ class GiveWay(BlockingIOError): """The user's other programs need memory/GPU: leave the cache receipt intact.""" +# The file whose presence stops a background run. Windows delivers Ctrl+Break +# only within one console, and a session started without one (a service, a +# scheduled task) never reaches the run that way; a file reaches it everywhere. +STOP_ENV = 'FREEVIDEO_PRECOMPILE_STOP' + # Set when the interactive session stops a background run. A signal can land # inside any handler that recovers from ordinary errors, so it only sets this; # the run gives way at its next checkpoint. CANCELLED = threading.Event() +def stop_requested(): + """True once the session stopped this run, by signal or by its stop file.""" + if not CANCELLED.is_set(): + path = os.environ.get(STOP_ENV) + try: + if path and os.path.exists(path): + CANCELLED.set() + except (OSError, ValueError): + pass + return CANCELLED.is_set() + + +# A stopped run that is still inside a step without a checkpoint (a kernel probe, a long compile) after this long +# exits with BUSY_EXIT itself. Its supervisor then ends every descendant, as for any give-way, and the next start +# reclaims its temporary folders; the session's own kill would come later and read as a failure. +STOP_EXIT_SECONDS = 3. + + +def watch_stop_file(interval=.1): + """Set CANCELLED within ``interval`` of a stop, also during steps without a checkpoint; leave if it lingers.""" + + def watch(): + while not stop_requested(): + time.sleep(interval) + time.sleep(STOP_EXIT_SECONDS) + try: + print(json.dumps(dict(event='give_way', reason='stopped by FreeVideo', at=time.time())), flush=True) + finally: + os._exit(BUSY_EXIT) + if os.environ.get(STOP_ENV): + threading.Thread(target=watch, name='precompile stop file', daemon=True).start() + + def checkpoint(room=None, sample=None): """GiveWay when the session stopped this run or the room is needed now.""" - if CANCELLED.is_set(): + if stop_requested(): raise GiveWay('stopped by FreeVideo') reason = room.run_reason(sample) if room is not None else None if reason: @@ -589,6 +627,7 @@ def stopped(signum, frame): # on the way out, leaving the cache receipt intact. CANCELLED.set() termination_handler(stopped) + watch_stop_file() try: from .testing import environment # A request's own variables: the installation, its caches and its GPU. diff --git a/freevideo_engine/prompt_vlm/rules.py b/freevideo_engine/prompt_vlm/rules.py index a9753671..6c41b237 100644 --- a/freevideo_engine/prompt_vlm/rules.py +++ b/freevideo_engine/prompt_vlm/rules.py @@ -1037,3 +1037,57 @@ def validate_parts(parts, value): SPLIT_RETRY = ('Answer again with exactly one "Shared:" line and the "Part N:" lines, every [L] marker exactly once ' 'and in order, and no marker in Shared. Shared holds no action, and every part has something of its ' 'own that no other part repeats.') + + +# Reverse prompt: describe a video from frames shown with their times, then ask for its camera movement. +# The description is plain text for the user (or the model rewrite that follows); spoken lines are never +# transcribed by the model: the caller gives them and the code writes them back as [Language] .... +REVERSE_FRAMES = (4, 32) +REVERSE_DEFAULT_FRAMES = 16 +REVERSE_INPUT_TOKENS = 6500 +REVERSE_OUTPUT_TOKENS = 450 +REVERSE_CAMERA_TOKENS = 80 +REVERSE_LINES = 12 +REVERSE_DESCRIBE = ("Describe this video so that a text-to-video model can recreate it as closely as possible. Cover the " + "subjects and their appearance; what each subject does, in order, with rough times in seconds; the " + "setting, lighting, colours and style; and any visible text exactly, inside double quotes. Write one " + "paragraph of plain description, with no lists and no preamble, about 120 to 220 words.") +REVERSE_CAMERA = ("Look only at how the camera moves between the first frame and the last frame. Compare the size and " + "position of the main subject and the background in the first and last frames: if the subject grows " + "larger the camera pushes in; if it shrinks the camera pulls out; if the background slides sideways " + "the camera pans or tracks; if the viewing angle around the subject changes the camera orbits; if " + "nothing changes it is static. Answer with one sentence naming the camera movement and its direction.") + + +def reverse_request(value): + """A file from ComfyUI's input folder, how many frames to look at, and the spoken lines the caller already has.""" + if not isinstance(value, dict) or set(value) - {'file', 'frames', 'lines', 'mode'} or value.get('mode', 'reverse') != 'reverse': + raise ValueError('invalid_request') + name, frames, lines = value.get('file'), value.get('frames', REVERSE_DEFAULT_FRAMES), value.get('lines', []) + if not isinstance(name, str) or not name or len(name) > 1024: + raise ValueError('unsupported_media') + if type(frames) is not int or not REVERSE_FRAMES[0] <= frames <= REVERSE_FRAMES[1]: + raise ValueError('invalid_request') + if (not isinstance(lines, list) or len(lines) > REVERSE_LINES + or any(not isinstance(line, str) or not plain(line) or len(line) > 400 for line in lines)): + raise ValueError('invalid_request') + return dict(mode='reverse', file=name, frames=frames, lines=[line.strip() for line in lines]) + + +def reverse_text(description, camera, lines): + """What the user sees: the description, the camera sentence, then each spoken line exactly as given.""" + parts = [description.strip(), camera.strip()] + spoken = ' '.join('[%s] %s' % (language(line), line) for line in lines) + if spoken: + parts.append(spoken) + return '\n\n'.join(part for part in parts if part) + + +def validate_reverse(text, value): + """Worker output for a reverse job: text of a sensible length that keeps every given spoken line verbatim.""" + if not isinstance(text, str) or not 40 <= len(text.strip()) <= 20000: + raise ValueError('invalid_output') + for line in value.get('lines', ()): + if line not in text: + raise ValueError('invalid_output') + return text diff --git a/freevideo_engine/prompt_vlm/service.py b/freevideo_engine/prompt_vlm/service.py index 4578cee3..078f9da6 100644 --- a/freevideo_engine/prompt_vlm/service.py +++ b/freevideo_engine/prompt_vlm/service.py @@ -13,6 +13,7 @@ import uuid from . import assets, rules +from ..disk_space import ran_out # How long a rewrite that does not fit waits for other programs to free the # GPU (the page names them) before it fails; the user can cancel meanwhile. @@ -302,7 +303,7 @@ def progress(self, row): def start(self, action, value): received_epoch = time.time() - if action not in ('install', 'rewrite', 'ask', 'split'): + if action not in ('install', 'rewrite', 'ask', 'split', 'reverse'): raise ValueError('invalid_request') if self.busy(): raise ValueError('busy') @@ -318,6 +319,16 @@ def start(self, action, value): if not assets.settle(root): raise ValueError('model_missing') value = rules.split_request(value) + elif action == 'reverse': + if not assets.settle(root): + raise ValueError('model_missing') + value = rules.reverse_request(value) + from ..comfy_assets import media_kind, resolve_assets + resolved = resolve_assets(json.dumps([dict(file=value['file'], role='reference')]), self.input_directory()) + path = resolved['references'][0]['path'] + if media_kind(path) != 'video': + raise ValueError('unsupported_media') + value['path'] = path else: if not assets.settle(root): raise ValueError('model_missing') @@ -452,6 +463,16 @@ def video_frames(self, value, folder): for row in value.get('media', ()): row.pop('optional', None) + def reverse_frames(self, value, folder): + """Evenly spaced frames of the video with their times; the worker picks how many fit its budget.""" + self.check() + try: + from ..agent.media import sample_frames + rows = sample_frames(value.pop('path'), folder, count=value['frames'], max_side=640) + except Exception: + raise ValueError('unreadable_video') from None + value['frame_files'] = [dict(path=row['path'], seconds=float(row['seconds'])) for row in rows] + def work(self, root, machine, action, value): from ..locking import runtime_lock from ..monitoring import save @@ -483,18 +504,24 @@ def work(self, root, machine, action, value): self.progress(dict(phase='complete')) else: with tempfile.TemporaryDirectory(prefix='freevideo-prompt-', ignore_cleanup_errors=True) as frames: - self.video_frames(value, frames) - self.infer(root, machine, descriptor, value, wait=action == 'rewrite') + if action == 'reverse': + self.reverse_frames(value, frames) + else: + self.video_frames(value, frames) + self.infer(root, machine, descriptor, value, wait=action in ('rewrite', 'reverse')) except InterruptedError: self.progress(dict(phase='cancelled')) except BlockingIOError: self.progress(dict(phase='failed', error='busy')) except Exception as error: known = {'disk_space', 'ram_space', 'unreadable_video', 'rewrite_failed', 'split_failed', 'worker_exit', 'timeout', 'worker_cleanup_failed'} + if str(error) not in known and not isinstance(error, rules.InvalidOutput): + logging.warning('[FreeVideo] Prompt model job %s failed: %s', action, type(error).__name__, exc_info=True) self.progress(dict(phase='failed', error='invalid_output' if isinstance(error, rules.InvalidOutput) else str(error) if str(error) in known + else 'disk_space' if isinstance(error, OSError) and ran_out(error) else 'download_failed' if action == 'install' - else 'ask_failed' if action == 'ask' else 'split_failed' if action == 'split' + else 'ask_failed' if action == 'ask' else 'split_failed' if action == 'split' else 'reverse_failed' if action == 'reverse' else 'rewrite_failed', exception=type(error).__name__, **({'output_rejection': error.details} if isinstance(error, rules.InvalidOutput) else {}))) @@ -760,6 +787,8 @@ def read_rows(): rules.validate_parts(result.get('parts'), value) elif value.get('mode') == 'image': rules.validate_image(result.get('text'), value) + elif value.get('mode') == 'reverse': + rules.validate_reverse(result.get('text'), value) else: try: rules.validate_output(result.get('text'), value) @@ -863,13 +892,15 @@ async def action(request): running, pending = server.prompt_queue.get_current_queue() if running or pending: raise ValueError('busy') - if name in ('ask', 'split', 'rewrite'): + if name in ('ask', 'split', 'rewrite', 'reverse'): # A moved modified time is checked by content here, off the event loop; # start() then finds the remembered answer. await asyncio.to_thread(assets.settle, service.installation()[0]) result = service.start(name, value) return web.json_response(result) except (ValueError, OSError) as error: + if isinstance(error, OSError): + logging.warning('[FreeVideo] Prompt model request failed: %s', type(error).__name__, exc_info=True) codes = {'invalid_request', 'invalid_prompt', 'invalid_duration', 'too_many_images', 'unsupported_media', 'mixed_media', 'busy', 'model_missing', 'consent_required', 'unknown_job'} return web.json_response(dict(error=str(error) if str(error) in codes else 'invalid_media'), status=400) diff --git a/freevideo_engine/prompt_vlm/worker.py b/freevideo_engine/prompt_vlm/worker.py index 4b44daef..11d6ba4e 100644 --- a/freevideo_engine/prompt_vlm/worker.py +++ b/freevideo_engine/prompt_vlm/worker.py @@ -273,7 +273,7 @@ def placement(weights, int8_saving, kv, allocator_budget): return 'bf16' if weights <= room else 'int8' if weights - int8_saving <= room else None -def gpu_plan(weights, stored, free, input_tokens, answer_tokens, text_only): +def gpu_plan(weights, stored, free, input_tokens, answer_tokens, text_only, extra=0, vision_gpu_only=False): """The GPU placement for `free` allocator bytes, or None when none fits. Best first: bf16 or int8 resident, then int8 with the later layers streamed @@ -286,7 +286,7 @@ def gpu_plan(weights, stored, free, input_tokens, answer_tokens, text_only): vision = sum(row['bytes'] for name, row in stored.items() if name.startswith('model.visual.')) saving = int8.saved_bytes(stored) def fit(answer, on_host): - kv = kv_bytes(stored, input_tokens, answer) + kv = kv_bytes(stored, input_tokens, answer) + extra size = weights - vision if on_host else weights plan = dict(kv=kv, positions=kv_positions(input_tokens, answer), vision_on_host=on_host, vision_bytes=vision if on_host else 0, keep=None, host_bytes=0) @@ -302,6 +302,9 @@ def fit(answer, on_host): if text_only: # The tower is never read: it takes neither GPU nor host memory. options = ((None, True), (answer_tokens, True)) + elif vision_gpu_only: + # Many frames through the tower on the CPU would take minutes: lower the frames instead (reverse prompt). + options = ((None, False),) else: options = ((None, False), (None, True)) for answer, on_host in dict.fromkeys(options): @@ -311,13 +314,13 @@ def fit(answer, on_host): return None -def gpu_needed(weights, stored, free, input_tokens, answer_tokens, text_only): +def gpu_needed(weights, stored, free, input_tokens, answer_tokens, text_only, extra=0, vision_gpu_only=False): """The fewest allocator bytes, to 32 MiB, for which gpu_plan finds a placement.""" step = 32 * 2**20 - low, high = free // step, -(-(weights + 2 * kv_bytes(stored, input_tokens) + WORKING_VRAM) // step) + low, high = free // step, -(-(weights + 2 * kv_bytes(stored, input_tokens) + extra + WORKING_VRAM) // step) while low + 1 < high: middle = (low + high) // 2 - if gpu_plan(weights, stored, middle * step, input_tokens, answer_tokens, text_only): + if gpu_plan(weights, stored, middle * step, input_tokens, answer_tokens, text_only, extra, vision_gpu_only): high = middle else: low = middle @@ -348,8 +351,9 @@ def load_model(folder, torch, stats, checkpoint): free = min(free, admission.get('effective_allocator_limit_bytes') or free) tokens = reserved_tokens(stats) answer = stats.get('answer_tokens', OUTPUT_TOKENS) + video = (stats.get('video_vram_bytes', 0), bool(stats.get('video_frames'))) def place(budget): - return gpu_plan(weights, shapes, budget, tokens, answer, not stats.get('image_count')) + return gpu_plan(weights, shapes, budget, tokens, answer, not stats.get('image_count'), *video) # Plan against what is left after the CUDA context and kernels, which the allocator's # limit does not cover; the Windows limit already leaves the 256 MiB growth reserve. extra = min(max(0, int(stats.get('extra_vram_reserve_bytes') or 0)), 4 * 2**30) @@ -389,12 +393,12 @@ def place(budget): # about 0.2 tokens/s and hit the request deadline, so say so at once. # The service waits for this much to become free before trying again. answer = stats.get('answer_tokens', OUTPUT_TOKENS) - stats['gpu_free_needed_bytes'] = gpu_needed(weights, shapes, free, tokens, answer, not stats.get('image_count')) + stats['gpu_free_needed_bytes'] = gpu_needed(weights, shapes, free, tokens, answer, not stats.get('image_count'), *video) # The report names the figure for a text-only request and for one with images; this # request's own kind may fit at the free memory shown, so these start from zero. stats.update(placement_refused='gpu_free_below_floor', gpu_free_needed_text_only_bytes=gpu_needed(weights, shapes, 0, tokens, answer, True), - gpu_free_needed_with_images_bytes=gpu_needed(weights, shapes, 0, tokens, answer, False)) + gpu_free_needed_with_images_bytes=gpu_needed(weights, shapes, 0, tokens, answer, False, *video)) raise ValueError('out_of_memory') stats['ram_required_bytes'] = (RESIDENT_RAM + host_bytes + vision_bytes) if resident else MAPPED_RAM available = stats['available_memory_at_start_bytes' if resident else 'available_memory_before_load_bytes'] @@ -475,6 +479,8 @@ def run(folder, value, *, stats=None): return split(folder, value, stats) if value.get('mode') == 'image': return image(folder, value, stats) + if value.get('mode') == 'reverse': + return reverse(folder, value, stats) return rewrite(folder, value, stats) @@ -529,6 +535,94 @@ def on_token(timing): emit(phase='complete', text=caption, diagnostics=dict(stats)) +# Peak graphics memory grew by about 0.04 GiB per 640 px frame (Qwen3-VL-4B, 8 to 32 frames, measured 11-19). +VIDEO_FRAME_VRAM = 48 * 2**20 +VIDEO_SIDES = (640, 480, 384) + + +def video_inputs(processor, frames, side, question): + """Frames shown with their times: Qwen3-VL turns each pair of frames into one group and prefixes its time.""" + import numpy as np + from PIL import Image + from transformers.video_utils import VideoMetadata + pictures = [] + for row in frames: + with Image.open(row['path']) as source: + picture = source.convert('RGB') + picture.thumbnail((side, side)) + pictures.append(np.asarray(picture)) + clip = np.stack(pictures) + times = [row['seconds'] for row in frames] + scale = 100 # indices at 100 per second reproduce the sampled times + metadata = VideoMetadata(total_num_frames=int(times[-1] * scale) + 1, fps=float(scale), duration=float(times[-1]), + frames_indices=[round(t * scale) for t in times], width=clip.shape[2], height=clip.shape[1]) + messages = [{'role': 'user', 'content': [{'type': 'video'}, {'type': 'text', 'text': question}]}] + text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True) + return processor(text=[text], videos=[clip], video_metadata=[metadata], do_sample_frames=False, return_tensors='pt') + + +def pick_frames(frames, build, budget): + """(frames, side, inputs) for the largest request that fits the token budget: fewer frames first (down to 8, always + spread over the whole clip), then smaller ones. None when even the smallest does not fit.""" + for side in VIDEO_SIDES: + count = len(frames) + while True: + picked = [frames[round(i * (len(frames) - 1) / max(1, count - 1))] for i in range(count)] + inputs = build(picked, side) + if inputs.input_ids.shape[-1] <= budget: + return picked, side, inputs + if count <= 8: + break + count = max(8, count - 4) + return None + + +def reverse(folder, value, stats): + """Describe a video from its frames, ask where the camera moves, and give both back with the caller's spoken lines.""" + from .rules import (REVERSE_CAMERA, REVERSE_CAMERA_TOKENS, REVERSE_DESCRIBE, REVERSE_INPUT_TOKENS, + REVERSE_OUTPUT_TOKENS, reverse_text) + stats.update(stage='imports', pid=os.getpid(), mode='reverse', frame_files=len(value['frame_files']), + answer_tokens=REVERSE_OUTPUT_TOKENS, dtype='bfloat16', attention='sdpa', kv_cache='dynamic', + backend='transformers', accelerations=[], persistent_model=False) + torch, checkpoint = begin(stats) + from transformers import AutoProcessor + checkpoint('preprocess') + preparing = time.monotonic() + processor = AutoProcessor.from_pretrained(folder, local_files_only=True, trust_remote_code=False) + # Frames and size are chosen before the model is placed, from the request's token budget: first fewer frames + # (down to 8), then smaller ones. The tower stays on the GPU for a video. + chosen = pick_frames(value['frame_files'], lambda rows, side: video_inputs(processor, rows, side, REVERSE_DESCRIBE), + REVERSE_INPUT_TOKENS) + if chosen is None: + raise ValueError('context_length') + picked, side, inputs = chosen + stats.update(input_tokens=int(inputs.input_ids.shape[-1]), video_frames=len(picked), video_side=side, + video_vram_bytes=len(picked) * VIDEO_FRAME_VRAM, image_count=len(picked), + preprocess_seconds=time.monotonic() - preparing) + model, device = load_model(folder, torch, stats, checkpoint) + loaded = time.monotonic() + checkpoint('prefill', 'describing') + shown = [0.] + def on_token(timing): + stats.update(output_tokens=timing['output_tokens'], decode_seconds=timing['decode_seconds'], + decode_tokens_per_second=timing['decode_tokens_per_second']) + stats['time_to_first_output_seconds'] = timing['first_output_seconds'] + stats.setdefault('first_output_epoch', timing['first_output_epoch']) + if time.monotonic() - shown[0] > .5: + checkpoint('decode', 'describing') + shown[0] = time.monotonic() + ids, _ = generate(torch, model, inputs.to(device), REVERSE_OUTPUT_TOKENS, loaded, on_token) + description = processor.decode(ids, skip_special_tokens=True).strip() + stats.update(describe_seconds=time.monotonic() - loaded, output_tokens=len(ids)) + checkpoint('decode', 'camera') + started = time.monotonic() + camera_inputs = video_inputs(processor, picked, side, REVERSE_CAMERA) + ids, _ = generate(torch, model, camera_inputs.to(device), REVERSE_CAMERA_TOKENS, started, lambda timing: None) + camera = processor.decode(ids, skip_special_tokens=True).strip() + stats.update(camera_seconds=time.monotonic() - started, stage='complete') + emit(phase='complete', text=reverse_text(description, camera, value['lines']), diagnostics=dict(stats)) + + def validate_rewrite(text, value, stats, retried=False): from .rules import InvalidOutput, validate_output try: diff --git a/freevideo_engine/release_notes.json b/freevideo_engine/release_notes.json index 23390b27..a1fe6873 100644 --- a/freevideo_engine/release_notes.json +++ b/freevideo_engine/release_notes.json @@ -1,42 +1,75 @@ { "schema": 1, - "product_version": "0.6.7", - "important": true, + "product_version": "0.6.8", "en": { - "summary": "0.6.7 improves prompt enhancement for MOSS-Image, lets merged videos be upscaled, offers lossless sound on export, gives videos, audio and dropdowns FreeVideo's own play bar and menu, makes the Edit view smoother, explains more failures, and cleans up more thoroughly when a work is deleted.", + "summary": "0.6.8 keeps models on the graphics card more often when pictures and videos alternate, has background preparation give the card back sooner when a generation starts, lets results be upscaled from their own menu, makes tutorial chapters searchable from the command palette, and explains more failures.", "changes": [ - "Prompt enhancement for MOSS-Image: with MOSS-Image, prompts are enhanced the way Qwen-Image's are; when the service refuses an enhancement request, the cause is named.", - "Prompt enhancement is steadier on smaller graphics cards: on cards with less video memory, such as 8 GB, enhancing a prompt no longer fails for lack of video memory.", - "Steadier use of Qwen-Image and MOSS-Image together: on a 12 GB card, making a picture with Qwen-Image and then switching to MOSS-Image no longer fails for lack of memory.", - "Upscale takes merged videos: a merged video can be upscaled to the largest size, and a video that cannot be enlarged says why.", - "Sound format on export: the export window adds a Sound option beside the frame rate, Compatible or Lossless. Lossless exports a .mov with uncompressed sound; it is not available with Audio only or for a range without sound.", - "One play bar and one menu: videos and audio use FreeVideo's own play bar, where a click plays or pauses a video and long audio and video can be dragged to any point; every dropdown in FreeVideo pages opens the FreeVideo menu instead of the system list.", - "A smoother Edit view: the preview has more room, the Media, LoRA and Advanced windows are no longer covered by the timeline, the buttons stay on one line in a narrow window, and Escape during a replace-audio step cancels only the replacement.", - "Over-long prompts are explained first: in the Image view and the Edit view, a prompt over the engine's limit says by how much before it is submitted, instead of being refused afterwards.", - "More failures explain what happened: a picture failure names the step where it failed, and a picture moved or deleted in the Edit view is named with a way to import it again.", - "More accurate graphics card notices: the laptop GeForce RTX 2050 is no longer listed as an unsupported card, and an old driver shows the driver update notice.", - "Steadier on a Mac with tight memory: when a Mac runs short of memory midway, generation retries once in a way that uses less memory instead of stopping.", - "Cleaner deletion: related traces in pictures, uploads, thumbnails and logs are removed, and deleted videos no longer appear in the finished-task record." + "Fewer reloads when pictures and videos alternate: when only system memory is short, models already on the graphics card are no longer cleared with it; after a picture, the video model returns to the card; when both cannot fit, the one used last stays.", + "A new generation gets the graphics card sooner: when Generate is clicked, background compiling and text-encoder preparation stop within seconds and give the card back instead of finishing first.", + "Less waiting in the second pass on 8 GB cards: on cards with less video memory, the second pass no longer waits for the processor to join intermediate results; the output is identical.", + "Upscale from the result menu: a result's \"⋯\" menu offers \"Upscale to W × H\", the same as the library's right-click menu.", + "Search the tutorial from the command palette: while text is typed in the command palette, matching tutorial chapters are listed after the related actions, and choosing one opens that chapter; Chinese and English chapter names and common terms can all be searched.", + "Launcher path tip: a folder's full path is shown as a tip only when the path is cut off.", + "More failures explain their cause: the prompt model and dubbing say when they fail for lack of disk space; a failure whose cause the engine has stated is no longer shown as an unexplained process exit and gets advice for that cause; on a Mac, using reference media together with first and last frames explains that one of the two has to be kept, and what to do next.", + "More accurate LoRA check: step-distillation acceleration LoRAs saved in other layouts are recognized as acceleration LoRAs, and language-model LoRAs are identified as such.", + "Edit view details: the title bar is no longer covered by the timeline's drag layers; at phone width the toolbar fits in one row; closing the Edit view clears the \"last edit not found\" notice; the slow-interface notice stays in the notification list until it is closed.", + "Reverse prompt: a video clip that yields a single frame can be reverse-prompted." ] }, "zh": { - "summary": "0.6.7 改进 MOSS-Image 的提示词增强,合并后的视频可以放大,导出可选无损声音;播放条和下拉菜单统一为 FreeVideo 自己的样式,剪辑视图更顺手,更多失败会说明原因,删除作品时清理得更干净。", + "summary": "0.6.8 让图片与视频交替使用时模型更多留在显卡上,开始生成时后台准备工作更快让出显卡;结果菜单可以直接放大,命令面板可以搜索教程章节,更多失败会说明原因。", "changes": [ - "提示词增强适配 MOSS-Image:使用 MOSS-Image 时,提示词按 Qwen-Image 的改写方式增强;改写请求被服务拒绝时,会说明原因。", - "提示词增强在显存较小的显卡上更稳:在 8 GB 等显存较小的显卡上,提示词增强不再因显存不足而失败。", - "先后使用 Qwen-Image 和 MOSS-Image 更稳:12 GB 显存的显卡上,先用 Qwen-Image 出图再换 MOSS-Image,不再因内存不足而失败。", - "视频放大支持合并后的视频:合并后的视频可以放大到最大尺寸;无法放大的视频会说明原因。", - "导出可选声音格式:导出窗口在帧率旁新增“声音”选项,可选“通用”或“无损”。选择“无损”时导出为 .mov 文件,声音不压缩;内容选“只声音”或所选范围没有声音时不可选。", - "播放条和下拉菜单统一:视频和音频使用 FreeVideo 自己的播放条,点击视频即可播放或暂停,长音频和视频可拖动进度;页面中的所有下拉选择都使用 FreeVideo 菜单,不再弹出系统列表。", - "剪辑视图更顺手:预览更宽敞,“素材”“LoRA”“高级选项”窗口不再被时间线遮住,窄窗口下按钮保持在一行,替换声音时按 Esc 只取消替换。", - "提示词过长时先说明:图像视图和剪辑视图中,超过引擎限制的提示词在提交前就会提示超出多少,不再提交后才被拒绝。", - "更多失败会说明原因:图片失败会指出出错的步骤;剪辑中的图片被移动或删除时,会说明并给出重新导入的办法。", - "显卡提示更准确:笔记本 GeForce RTX 2050 不再被列为不支持的显卡,驱动过旧时会显示更新驱动的提示。", - "Mac 内存紧张时更稳:Mac 生成中途内存不足时,会自动换一种更省内存的方式重试一次,不再直接停止。", - "删除作品清理更干净:图片、上传文件、缩略图和日志中的相关残留一并清除,已删除的视频不再出现在已完成任务记录中。" + "图片和视频交替使用时更少重复载入:只是电脑内存紧张时,已在显卡上的模型不再被一并清出;图片用完后,视频模型会重新回到显卡;两者放不下时,保留最近使用的一个。", + "开始生成更快接手显卡:点击生成时,后台的编译和文本编码器准备会在几秒内停下并让出显卡,不再等它们做完。", + "8 GB 显卡第二遍更少等待:显存较小时,第二遍不再等待处理器拼接中间结果,画面与之前完全一致。", + "结果菜单可以放大:生成结果的“⋯”菜单中可直接选择“放大到 宽 × 高”,与作品库右键菜单一致。", + "命令面板可以搜索教程:在命令面板中输入文字时,匹配的教程章节会列在相关操作之后,选择即可打开该章;中文、英文章节名和常用说法都可搜索。", + "启动器路径提示:文件夹路径只在显示不全时才出现完整路径提示。", + "更多失败会说明原因:提示词模型和配音因磁盘空间不足失败时会说明;引擎已写明原因的失败不再显示为原因不明的进程退出,并给出对应的处理建议;在 Mac 上同时使用参考素材和首尾帧时,会说明需要保留其中一种,以及下一步怎么做。", + "LoRA 检查更准确:以其他方式保存的步数蒸馏加速 LoRA 也能被识别为加速 LoRA;语言模型的 LoRA 会被如实指出。", + "剪辑视图细节:标题栏不再被时间线拖动层遮住;手机宽度下工具条完整放在一行;关闭剪辑视图后,“找不到上次的剪辑”提示随之清除;界面变慢的提示会保留在通知列表中,直到手动关闭。", + "反推提示词:只取到一帧的视频片段也能正常反推。" ] }, "history": [ + { + "product_version": "0.6.7", + "en": { + "summary": "0.6.7 improves prompt enhancement for MOSS-Image, lets merged videos be upscaled, offers lossless sound on export, gives videos, audio and dropdowns FreeVideo's own play bar and menu, makes the Edit view smoother, explains more failures, and cleans up more thoroughly when a work is deleted.", + "changes": [ + "Prompt enhancement for MOSS-Image: with MOSS-Image, prompts are enhanced the way Qwen-Image's are; when the service refuses an enhancement request, the cause is named.", + "Prompt enhancement is steadier on smaller graphics cards: on cards with less video memory, such as 8 GB, enhancing a prompt no longer fails for lack of video memory.", + "Steadier use of Qwen-Image and MOSS-Image together: on a 12 GB card, making a picture with Qwen-Image and then switching to MOSS-Image no longer fails for lack of memory.", + "Upscale takes merged videos: a merged video can be upscaled to the largest size, and a video that cannot be enlarged says why.", + "Sound format on export: the export window adds a Sound option beside the frame rate, Compatible or Lossless. Lossless exports a .mov with uncompressed sound; it is not available with Audio only or for a range without sound.", + "One play bar and one menu: videos and audio use FreeVideo's own play bar, where a click plays or pauses a video and long audio and video can be dragged to any point; every dropdown in FreeVideo pages opens the FreeVideo menu instead of the system list.", + "A smoother Edit view: the preview has more room, the Media, LoRA and Advanced windows are no longer covered by the timeline, the buttons stay on one line in a narrow window, and Escape during a replace-audio step cancels only the replacement.", + "Over-long prompts are explained first: in the Image view and the Edit view, a prompt over the engine's limit says by how much before it is submitted, instead of being refused afterwards.", + "More failures explain what happened: a picture failure names the step where it failed, and a picture moved or deleted in the Edit view is named with a way to import it again.", + "More accurate graphics card notices: the laptop GeForce RTX 2050 is no longer listed as an unsupported card, and an old driver shows the driver update notice.", + "Steadier on a Mac with tight memory: when a Mac runs short of memory midway, generation retries once in a way that uses less memory instead of stopping.", + "Cleaner deletion: related traces in pictures, uploads, thumbnails and logs are removed, and deleted videos no longer appear in the finished-task record." + ] + }, + "zh": { + "summary": "0.6.7 改进 MOSS-Image 的提示词增强,合并后的视频可以放大,导出可选无损声音;播放条和下拉菜单统一为 FreeVideo 自己的样式,剪辑视图更顺手,更多失败会说明原因,删除作品时清理得更干净。", + "changes": [ + "提示词增强适配 MOSS-Image:使用 MOSS-Image 时,提示词按 Qwen-Image 的改写方式增强;改写请求被服务拒绝时,会说明原因。", + "提示词增强在显存较小的显卡上更稳:在 8 GB 等显存较小的显卡上,提示词增强不再因显存不足而失败。", + "先后使用 Qwen-Image 和 MOSS-Image 更稳:12 GB 显存的显卡上,先用 Qwen-Image 出图再换 MOSS-Image,不再因内存不足而失败。", + "视频放大支持合并后的视频:合并后的视频可以放大到最大尺寸;无法放大的视频会说明原因。", + "导出可选声音格式:导出窗口在帧率旁新增“声音”选项,可选“通用”或“无损”。选择“无损”时导出为 .mov 文件,声音不压缩;内容选“只声音”或所选范围没有声音时不可选。", + "播放条和下拉菜单统一:视频和音频使用 FreeVideo 自己的播放条,点击视频即可播放或暂停,长音频和视频可拖动进度;页面中的所有下拉选择都使用 FreeVideo 菜单,不再弹出系统列表。", + "剪辑视图更顺手:预览更宽敞,“素材”“LoRA”“高级选项”窗口不再被时间线遮住,窄窗口下按钮保持在一行,替换声音时按 Esc 只取消替换。", + "提示词过长时先说明:图像视图和剪辑视图中,超过引擎限制的提示词在提交前就会提示超出多少,不再提交后才被拒绝。", + "更多失败会说明原因:图片失败会指出出错的步骤;剪辑中的图片被移动或删除时,会说明并给出重新导入的办法。", + "显卡提示更准确:笔记本 GeForce RTX 2050 不再被列为不支持的显卡,驱动过旧时会显示更新驱动的提示。", + "Mac 内存紧张时更稳:Mac 生成中途内存不足时,会自动换一种更省内存的方式重试一次,不再直接停止。", + "删除作品清理更干净:图片、上传文件、缩略图和日志中的相关残留一并清除,已删除的视频不再出现在已完成任务记录中。" + ] + }, + "important": true + }, { "product_version": "0.6.6", "en": { diff --git a/freevideo_engine/resident_models.py b/freevideo_engine/resident_models.py index 06a205a8..d2df067f 100644 --- a/freevideo_engine/resident_models.py +++ b/freevideo_engine/resident_models.py @@ -29,6 +29,8 @@ ENGINE_ARITHMETIC_OPTIONS = ('head_chunk', 'projection_chunk') # Resident blocks that a kept engine may lack against the plan and still be reused. RESIDENT_BLOCK_SHORTFALL = 2 +# Models given back by the bank itself, kept for the worker's status (decisions are cleared with each request). +EVICTIONS_KEPT = 20 def retention_order(history): @@ -158,6 +160,39 @@ def pinned_cpu_storages(model, *, committed=False): return storages +def host_bytes(model): + """Host bytes releasing ``model`` would give back: its CPU-side tensors, counted once per storage, plus a + parked engine's copy. None when they cannot be read (an object without parameters), so the caller treats the + model as one that may hold host memory.""" + total = parked_bytes(model) + if hasattr(model, 'transformer'): + model = model.transformer + elif hasattr(model, 'cond_stage_model'): + model = model.cond_stage_model + if model is None: + return total + if not callable(getattr(model, 'parameters', None)) or not callable(getattr(model, 'buffers', None)): + return None + storages = {} + for tensor in list(model.parameters()) + list(model.buffers()): + if tensor.device.type != 'cpu': + continue + try: + storage = tensor.untyped_storage() + storages[storage.data_ptr()] = storage.nbytes() + except (NotImplementedError, RuntimeError): + return None + return total + sum(storages.values()) + + +def gpu_only(model): + """Whether ``model`` sits wholly on the card: releasing it frees card memory and no host memory.""" + try: + return gpu_bytes(model) > 0 and host_bytes(model) == 0 + except (AttributeError, RuntimeError, TypeError): + return False + + def is_parked(model): """Whether an engine handed its GPU weights to host memory with park().""" return type(getattr(model, 'parked', None)) is list @@ -235,6 +270,14 @@ def __init__(self): # An automatic plan's RAM budget is an estimate (see system.ram_budget_is_estimate). self.ram_budget_is_estimate = False self.decisions = [] + self.evictions = [] + self.eviction_count = 0 + # The video model a warm-up loaded with the last video's settings (engine_preload), until a video takes it + # or it goes; and what each preload became (hit or miss), as the evictions. + self.preloaded = None + self.preloads = [] + self.engine_card_bytes = None + self.preload_count = 0 from .streamed_weights import ConvertedStore # Converted decoder layers streamed from the checkpoint; rebuilt on demand. self.converted_store = ConvertedStore() @@ -257,6 +300,7 @@ def configure(self, gpu_budget, ram_budget=None, *, gpu_reserve=0, ram_budget_is if ram_budget_is_estimate is not None: self.ram_budget_is_estimate = bool(ram_budget_is_estimate) self.decisions = [] + self.engine_card_bytes = None def take(self, role, identity): entry = self.entries.get(role) @@ -305,6 +349,22 @@ def drop(self, role, reason): encoder_discarded_without_cpu_copy=encoder_discarded, host_cache_released=host_cache_released, released_gpu_bytes=max(0, before - torch.cuda.memory_allocated()))) + self.eviction_count += 1 + self.evictions = (self.evictions + [dict(seq=self.eviction_count, role=role, reason=reason, at=time.time(), + released_gpu_bytes=self.decisions[-1]['released_gpu_bytes'])] + )[-EVICTIONS_KEPT:] + if role == 'engine' and self.preloaded is not None: + self.preload_outcome('dropped', reason=reason) + + def preload_outcome(self, outcome, **detail): + """What the preloaded video model became: 'hit', 'miss' (with what differed) or 'dropped' before any video.""" + row = dict(seq=self.preload_count + 1, outcome=outcome, at=time.time(), + waited_seconds=round(time.time() - self.preloaded['at'], 1), **detail) + self.preload_count += 1 + self.preloaded = None + self.preloads = (self.preloads + [row])[-EVICTIONS_KEPT:] + self.decisions.append(dict(action='preload_' + outcome, role='engine', **detail)) + print(json.dumps(dict(event='video_model_preload', **row)), flush=True) def park(self, role, reason, ram_need=2*GiB): """Release only an idle engine's GPU weights and keep its host side. @@ -338,6 +398,11 @@ def declined(why): released_gpu_bytes=released, seconds=time.perf_counter() - started)) return True + def keep_on_card(self, role, stage): + self.decisions.append(dict(action='keep', role=role, gpu_bytes=gpu_bytes(self.entries[role]['model']), + reason='Host memory is short for the %s, but this model holds only card memory' + % stage)) + def clear(self, reason='Request failed or session configuration changed'): self.converted_store.clear() for role in list(self.entries): @@ -393,6 +458,10 @@ def settle(self, pinned=0): if self.ram_fits(need): break if role in self.entries: + if gpu_only(self.entries[role]['model']): + # On the card only: releasing it gives the host nothing back. + self.keep_on_card(role, 'next request') + continue self.drop(role, 'Retained weights leave no host room for the next request') if role == 'engine': need = 8*GiB + int(pinned) @@ -536,6 +605,11 @@ def eviction_order(item): break if other == role: continue + if available() >= extra and gpu_only(self.entries[other]['model']): + # Only host memory is short, and this model holds none: releasing it would empty the card and + # give the host nothing back. + self.keep_on_card(other, role) + continue if is_parked(self.entries[other]['model']): # A parked engine holds no GPU memory; only RAM releases it. if fits(): @@ -574,7 +648,12 @@ def engine_peak_key(self, request): plan={name: options.get(name) for name in (*ENGINE_PASS_OPTIONS, 'resident_blocks')})) def engine_key(self, request): - """What a kept engine must share with a request to serve it, as opposed to engine_peak_key(). + """What a kept engine must share with a request to serve it (engine_parts), as opposed to engine_peak_key().""" + return key(ModelBank.engine_parts(request)) + + @staticmethod + def engine_parts(request): + """The parts of engine_key, by name. The tiling and pipelining of a pass (head, window, feed-forward and projection chunks, prefetch) change neither the weights nor where they live, and every request re-applies @@ -590,9 +669,9 @@ def engine_key(self, request): if request['engine_options'].get(name): options[name + '_on'] = True options.pop('resident_blocks', None) - return key(dict(cache=file_identity(Path(request['cache'])/'manifest.json'), - options=options, geometry=request.get('geometry'), - inputs=request.get('input_cache_dir'))) + return dict(cache=file_identity(Path(request['cache'])/'manifest.json'), + options=options, geometry=request.get('geometry'), + inputs=request.get('input_cache_dir')) @staticmethod def resident_blocks_serve(retained, wanted): @@ -606,6 +685,7 @@ def resident_blocks_serve(retained, wanted): return wanted - RESIDENT_BLOCK_SHORTFALL <= retained <= wanted def engine(self, request, factory): + preloaded = self.preloaded identity = self.engine_peak_key(request) options, canvas = request['engine_options'], request.get('geometry', {}) reuse_identity = self.engine_key(request) @@ -681,9 +761,27 @@ def engine(self, request, factory): moved = found.unpark() self.decisions.append(dict(action='unpark', role='engine', moved_bytes=moved, seconds=time.perf_counter() - started)) + if preloaded is not None: + # The preloaded model is the one held until a request takes or drops it. + if hit: + self.preload_outcome('hit') + else: + # Dropped just now for other settings, block count or host allowance: this request loads its own. + from .engine_preload import differences + changed = differences(preloaded['parts'], self.engine_parts(request)) + row = self.preloads[-1] if self.preloaded is None and self.preloads else None + if row is not None and row['outcome'] == 'dropped': + row.update(outcome='miss', differs=changed) + print(json.dumps(dict(event='video_model_preload', **row)), flush=True) + else: + self.preloaded = preloaded + self.preload_outcome('miss', differs=changed) if found is None: found = factory() self.put('engine', reuse_identity, found) + # What it takes on the card, kept for a later preload of the same settings (engine_preload) even when a later + # stage of this request releases it. + self.engine_card_bytes = gpu_bytes(found) memo = getattr(found, 'refined_text_memo', None) if isinstance(memo, dict): cached = self.take('conditioning', identity) @@ -772,7 +870,8 @@ def fit_observed_decoder(self, options, observed): def snapshot(self): if not torch.cuda.is_initialized(): - return dict(reclaimable_gpu_bytes=0, reclaimable_ram_bytes=0, gpu_uuid=None, models=[]) + return dict(reclaimable_gpu_bytes=0, reclaimable_ram_bytes=0, gpu_uuid=None, models=[], + evictions=list(self.evictions), preloads=list(self.preloads)) uuid = str(getattr(device_properties(torch), 'uuid', '')) if uuid and not uuid.startswith(('GPU-', 'MIG-')): uuid = 'GPU-' + uuid @@ -802,4 +901,5 @@ def snapshot(self): memory=memory, gpu_capacity=gpu_capacity, ram_credit_scope='Owned pinned model storage and parked engine weights; deduplicated, reclaimable on eviction. No mapped-page or swap credit; commit only for private storage.', gpu_uuid=uuid, models=[dict(role=role, gpu_bytes=gpu_bytes(entry['model'])) - for role, entry in self.entries.items()], decisions=self.decisions) + for role, entry in self.entries.items()], decisions=self.decisions, + evictions=list(self.evictions), preloads=list(self.preloads)) diff --git a/freevideo_engine/resident_process.py b/freevideo_engine/resident_process.py index a0994814..44f7494c 100644 --- a/freevideo_engine/resident_process.py +++ b/freevideo_engine/resident_process.py @@ -8,6 +8,7 @@ import atexit from dataclasses import replace import json +import logging import os from pathlib import Path import secrets @@ -30,9 +31,13 @@ # for the card back. A failed request without a queued part releases it as # before; a next part already on its way is held for HOLD_SECONDS. HOLD_SECONDS = 90. +# How often a held idle worker is asked what it gave back by itself. +STATUS_SECONDS = 10. AGENT_HOLD_SECONDS = 30. KEEP_IDLE_SECONDS = None OTHER_GPU_GROWTH = 512 * 2**20 +# How many of the programs that took the card a release record names. +OTHER_PROGRAMS_NAMED = 3 PRELOAD_CONTEXT_BYTES = 1536 * 2**20 # what the preload's process adds beside its weights (context, allocator, staging; measured 1.4 GiB) HOST_FLOOR = 4 * GiB # The host memory a kept idle worker leaves free, as a share of the memory this process may use (the cgroup limit @@ -51,6 +56,10 @@ class SessionBusy(RuntimeError): """A running request owns this worker; its allocations are not idle credit.""" +class StartStopped(RuntimeError): + """The caller asked to stop while the worker was still starting; it was stopped and nothing ran on it.""" + + def send(connection, value): connection.send_bytes(json.dumps(value, allow_nan=False).encode('utf-8')) @@ -396,21 +405,75 @@ def __init__(self): self.active = False self.prewarm = None self.gpu = self.baseline = self.own = self.foreign = None + self.others = {} # The other programs on the card when the hold began: {pid: bytes or None}. self.mutex = threading.RLock() self.generation = 0 self.idle_since = None self.decisions = [] + # (worker pid, last eviction number) already recorded from the worker's status. + self.evictions_seen = (None, 0) + self.preloads_seen = (None, 0) atexit.register(self.close) def record(self, **row): row.setdefault('at', time.time()) + # Who took the card goes to this machine's monitor only: the decisions reach the request's files, and those + # go into the diagnostic report and the feedback bundle, so they keep only each program's card bytes. + others = row.pop('other_programs', None) + if others is not None: + row['other_programs_gpu_bytes'] = [other.get('gpu_bytes') for other in others] with self.mutex: self.decisions = (self.decisions + [row])[-RELEASE_LOG:] if row.get('action') in ('released', 'trimmed'): from . import server_mode - server_mode.released('video', row) + server_mode.released('video', row if others is None else dict(row, other_programs=others)) return row + def note_evictions(self, answer): + """Record the models the worker gave back by itself (inside a request, to make room for a stage) from a + status ``answer``, as trims: without this only the worker knew the card had been emptied.""" + rows = answer.get('evictions') if isinstance(answer, dict) else None + if not isinstance(rows, list): + return [] + with self.mutex: + pid = self.process.pid if self.process is not None else None + seen = self.evictions_seen[1] if self.evictions_seen[0] == pid else 0 + new = [row for row in rows if isinstance(row, dict) and type(row.get('seq')) is int and row['seq'] > seen] + if new: + self.evictions_seen = (pid, max(row['seq'] for row in new)) + for row in new: + text = str(row.get('reason') or '') + self.record(action='trimmed', reason='host_memory_low' if 'host' in text.lower() else 'worker_made_room', + role=str(row.get('role')), detail=text[:200], pid=pid, + released_gpu_bytes=row.get('released_gpu_bytes'), + **({'at': row['at']} if isinstance(row.get('at'), (int, float)) else {})) + self.note_preloads(answer, pid) + return new + + def note_preloads(self, answer, pid): + """Log what each preloaded video model became (engine_preload): used by the next video, not used because it + asked for other settings, or released before any video.""" + rows = answer.get('preloads') + if not isinstance(rows, list): + return [] + with self.mutex: + seen = self.preloads_seen[1] if self.preloads_seen[0] == pid else 0 + new = [row for row in rows if isinstance(row, dict) and type(row.get('seq')) is int and row['seq'] > seen] + if new: + self.preloads_seen = (pid, max(row['seq'] for row in new)) + for row in new: + outcome = row.get('outcome') + if outcome == 'hit': + logging.info('[FreeVideo] Preloaded video model: hit, the video used it (loaded %.0f s before)', + float(row.get('waited_seconds') or 0)) + elif outcome == 'miss': + logging.info('[FreeVideo] Preloaded video model: miss, the video asked for other settings (%s)', + ', '.join(str(name) for name in row.get('differs') or []) or 'unknown') + else: + logging.info('[FreeVideo] Preloaded video model released before any video: %s', + str(row.get('reason') or '')[:200]) + return new + def take_decisions(self): """Keep or release decisions since the previous request, for its report.""" with self.mutex: @@ -446,6 +509,7 @@ def finished(self, *, next_part=None, agent=False, gpu=None, warm=False, decisio return self.release('gpu_unreadable') self.gpu, self.baseline = gpu, baseline self.own = gpu_own(gpu) if warm else None + self.others = card_others(gpu) if warm else {} # A server counts only programs outside it: the picture worker beside the video models is its own. from . import server_mode self.foreign = (baseline - self.own if warm and server_mode.coresident() and self.own is not None @@ -502,8 +566,18 @@ def placed_bytes(self): def _watch(self, generation, since, hold, gpu): placing = False + read_at = time.monotonic() while True: time.sleep(.5) + if time.monotonic() - read_at >= STATUS_SECONDS and not self.preloading(): + read_at = time.monotonic() + with self.mutex: + endpoint = self.endpoint if not self.active else None + if endpoint: + try: + self.note_evictions(status({ENV: str(endpoint)})) + except Exception: + logging.warning('[FreeVideo] Reading what the video worker gave back failed', exc_info=True) # Our own idle preload grows the card; only another program's growth counts, # so the reference is read again once placement has ended. unreadable = False @@ -529,39 +603,43 @@ def _watch(self, generation, since, hold, gpu): 'idle' if hold is not None and time.monotonic() - since >= hold else server_pressure(gpu, self.foreign) if self.foreign is not None else pressure(gpu, None if placing else self.baseline)) + # Who needs the card, read before taking the lock: the release record names them. + detail = dict(other_programs=other_programs(gpu, self.others)) if reason == 'other_program_gpu' else {} with self.mutex: if generation != self.generation or self.active or self.process is None: return if self.process.poll() is not None: return # The image or prompt model released it and recorded why. if reason: - self.release(reason) + self.release(reason, **detail) return - def release(self, reason): + def release(self, reason, **detail): with self.mutex: if self.process is None or self.process.poll() is not None: self.close() return None row = dict(action='released', reason=reason, pid=self.process.pid, idle_seconds=None if self.idle_since is None else round(time.monotonic() - self.idle_since, 1), - **worker_memory(self.process.pid)) + **worker_memory(self.process.pid), **detail) self.generation += 1 self.idle_since = None self.close() return self.record(**row) - def start(self, root, source, python, environment, busy=False): + def start(self, root, source, python, environment, busy=False, stop=None): + """``stop``, an Event: set while the worker is still starting, the start ends at once (StartStopped), so a + speculative start never keeps a video or a picture waiting for it.""" with self.mutex: self.generation += 1 self.idle_since = None - endpoint = self._start(root, source, python, environment) + endpoint = self._start(root, source, python, environment, stop) # Marked under the same lock, so a release cannot land between starting and using the worker. if busy: self.active = True return endpoint - def _start(self, root, source, python, environment): + def _start(self, root, source, python, environment, stop=None): import hashlib import psutil from .triton_compat import COMPILER_ENVIRONMENT_KEYS, environment as compiler_environment @@ -607,6 +685,9 @@ def _start(self, root, source, python, environment): raise RuntimeError('Resident worker could not start; see ' + str(directory/'session.log')) if (directory/'ready.json').exists(): return str(self.endpoint) + if stop is not None and stop.is_set(): + self.close() + raise StartStopped('Resident worker start stopped for another request') time.sleep(.05) self.close() raise TimeoutError('Resident worker startup timed out') @@ -688,6 +769,42 @@ def gpu_own(gpu): return None +def card_others(gpu): + """{pid: bytes or None} of the card's processes outside this process tree; {} when the driver cannot list them.""" + try: + from .background_room import Gpu, family + device = Gpu(gpu) + try: + rows = device.processes() + finally: + device.close() + ours = family(os.getpid()) + return {pid: size for pid, size in (rows or {}).items() if pid not in ours} + except (OSError, RuntimeError, AttributeError, ValueError, ImportError): + return {} + + +def other_programs(gpu, before, limit=OTHER_PROGRAMS_NAMED): + """The programs that came onto the card, or grew on it, since ``before`` ({pid: bytes or None}), most growth + first: [{'pid', 'name', 'gpu_bytes'}]. Where the driver gives no per-process bytes (WDDM) every newcomer is + listed with ``gpu_bytes`` None. The names reach only this machine's monitor (SessionOwner.record).""" + rows = [] + for pid, size in card_others(gpu).items(): + grown = None if size is None else size - (before.get(pid) or 0) + if pid not in before or (grown or 0) > 0: + rows.append((grown, pid, size)) + rows.sort(key=lambda row: -(row[0] or 0)) + return [dict(pid=pid, name=process_name(pid), gpu_bytes=size) for grown, pid, size in rows[:limit]] + + +def process_name(pid): + try: + import psutil + return psutil.Process(pid).name()[:80] or None + except Exception: + return None + + def host_margin(): """The host memory a kept idle worker leaves free: HOST_MARGIN_FRACTION of the cgroup limit, or of the machine's memory without one, and at least HOST_FLOOR.""" diff --git a/freevideo_engine/resident_worker.py b/freevideo_engine/resident_worker.py index 0f83415f..1f03d688 100644 --- a/freevideo_engine/resident_worker.py +++ b/freevideo_engine/resident_worker.py @@ -13,6 +13,31 @@ from .resident_process import serve +def preload(request, bank, torch): + """A warm-up's video model with the last video's settings (see engine_preload); nothing is sampled.""" + from .engine_preload import place + from .monitoring import save + from .runtime import Engine + bank.configure(request['gpu_budget_bytes'], request.get('ram_budget_bytes'), + ram_budget_is_estimate=request.get('ram_budget_is_estimate') is True) + allocation = request['gpu_budget_bytes'] + if request.get('sampling_gpu_limit_bytes'): + allocation = min(allocation, request['sampling_gpu_limit_bytes']) + factory = lambda: Engine(request['cache'], input_cache_dir=request.get('input_cache_dir'), + gpu_allocation_bytes=int(allocation), + **dict(request['engine_options'], canvas=request.get('geometry'))) + free = torch.cuda.mem_get_info()[0] + torch.cuda.memory_reserved() - torch.cuda.memory_allocated() + result = place(request, bank, factory, free_bytes=free, host_fits=bank.ram_fits) + print(json.dumps(dict(event='video_model_preload', **result)), flush=True) + save(Path(request['metrics']), dict(result, success=True)) + + +def remember(request, bank, allocator): + """After a whole video: what its video model was built from, for the next warm-up (engine_preload).""" + from .engine_preload import remember as keep + keep(request, bank.engine_card_bytes, allocator) + + def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--endpoint', type=Path, required=True) @@ -22,7 +47,7 @@ def main(): def snapshot(): result = bank.snapshot() if bank is not None else dict(reclaimable_gpu_bytes=0, reclaimable_ram_bytes=0, gpu_uuid=None, models=[]) - return dict(result, allocator_config=allocator, capabilities=['encoder-weight-preload']) + return dict(result, allocator_config=allocator, capabilities=['encoder-weight-preload', 'engine-preload']) def run(message): nonlocal bank, allocator @@ -73,12 +98,18 @@ def stage(name): stage('cuda_setup') from .processes import worker_signals with worker_signals(): - if module.endswith('.worker'): + if module.endswith('.worker') and request.get('engine_preload'): + preload(request, bank, torch) + elif module.endswith('.worker'): from .worker import generate stage('engine_import') bank.configure(request['gpu_budget_bytes'], request.get('ram_budget_bytes'), ram_budget_is_estimate=request.get('ram_budget_is_estimate') is True) generate(request, resident=bank) + try: + remember(request, bank, allocator) + except Exception: + pass # A preload that is not prepared only leaves the next video as before. # Only a fully returned video is a success, including its # final cleanup. Keep habit data inside this worker. try: diff --git a/freevideo_engine/rewarm.py b/freevideo_engine/rewarm.py index cb8a559f..adf77724 100644 --- a/freevideo_engine/rewarm.py +++ b/freevideo_engine/rewarm.py @@ -1,15 +1,20 @@ """Bringing a model back once the room it gave up is free again. Where idle models stay loaded (``server_mode.keeps_idle``: Linux and Windows), a model lets go when another program -needs the card or host memory runs short, and the picture model when a video needs its room. Without this, it stayed +needs the card or host memory runs short, the picture model when a video needs its room, and the video model when a +picture needs its room (the encoder stays). Where both do not fit, the one used last keeps the card: the other waits +for room beside it. Without this, it stayed unloaded until the next job asked for it and paid the whole load then. Now, once that room is free again and has stayed free for QUIET_SECONDS, the same model is loaded in the background as a warm-up would load it: - only into room that is free: the card holds the model's files and the picture reserve beside everything on it now, - and host memory keeps its margin; the other model is never trimmed to make room for it; + and host memory holds what the model's worker took the last time it held the model, plus the least host memory + that worker keeps free (below it the worker lets go again at once); the other model is never trimmed to make room + for it; - never while a video, a picture or a warm-up runs, or once the model is loaded again by other means; -- at most RELOADS_PER_HOUR times an hour per model, so a program that comes and goes does not make it load over and - over, and only for LIMIT_SECONDS after the release. +- after a quiet time that doubles with each return of the same model in the last hour (QUIET_SECONDS, then twice + that, up to QUIET_MOST_SECONDS), so a program that comes and goes does not make it load over and over, yet the + model still comes back; and only for LIMIT_SECONDS after the release. Each return is recorded beside the releases (``server_mode.releases``) with action 'reloaded'. Macs and FREEVIDEO_KEEP_MODELS=off keep the earlier behaviour. In server mode the picture model's return after a video stays @@ -23,11 +28,12 @@ POLL_SECONDS = 2. QUIET_SECONDS = 30. LIMIT_SECONDS = 6 * 3600. -RELOADS_PER_HOUR = 3 +# The longest quiet time, reached after several returns within the hour. +QUIET_MOST_SECONDS = 15 * 60. HOST_SPARE_BYTES = 1 << 30 # The releases that only made room: the model would have stayed. Others (closed, worker_exit, finished, a job's own # trim, an unreadable card) are not undone. -REASONS = dict(image=('crowded', 'video_start'), video=('other_program_gpu', 'host_memory_low')) +REASONS = dict(image=('crowded', 'video_start'), video=('other_program_gpu', 'host_memory_low', 'image_model')) # A warm-up that did not start because a job got there first: try again once it is done. BUSY = ('busy', 'video_busy') @@ -36,15 +42,16 @@ _reloads = {} -def after_release(model, reason, held=None): - """``model`` ('video' or 'image') was released for ``reason``; ``held`` is the picture model it held. Starts the - wait to bring it back and returns the thread, or None when this release is not one to undo.""" +def after_release(model, reason, held=None, host_bytes=None): + """``model`` ('video' or 'image') was released for ``reason``; ``held`` is the picture model it held and + ``host_bytes`` the host memory its worker took while it held it (None: not known). Starts the wait to bring it + back and returns the thread, or None when this release is not one to undo.""" from . import server_mode if reason not in REASONS.get(model, ()) or not server_mode.keeps_idle(): return None if model == 'image' and (not held or (reason == 'video_start' and server_mode.enabled())): return None - probe = Probe(model, held, reason) + probe = Probe(model, held, reason, host_bytes) if not probe.ready(): return None with _mutex: @@ -54,11 +61,13 @@ def after_release(model, reason, held=None): return thread -def _allowed(model, now): +def quiet_seconds(model, now): + """How long the room must stay free and still before ``model`` comes back: QUIET_SECONDS, doubled for each + return of it in the last hour, at most QUIET_MOST_SECONDS.""" with _mutex: recent = [at for at in _reloads.get(model, ()) if now - at < 3600.] _reloads[model] = recent - return len(recent) < RELOADS_PER_HOUR + return min(QUIET_SECONDS * 2 ** len(recent), QUIET_MOST_SECONDS) def _count(model, now): @@ -95,7 +104,7 @@ def watch(probe, generation, *, clock=time.monotonic, sleep=time.sleep): if since is None or abs(now_used - used) >= OTHER_GPU_GROWTH: since, used = now, now_used continue - if now - since < QUIET_SECONDS or not _allowed(model, now): + if now - since < quiet_seconds(model, now): continue try: answer = probe.load() or {} @@ -116,8 +125,9 @@ def watch(probe, generation, *, clock=time.monotonic, sleep=time.sleep): class Probe: """What the wait reads and does for one model; the tests replace it.""" - def __init__(self, model, held=None, reason=None): + def __init__(self, model, held=None, reason=None, host_bytes=None): self.model, self.held, self.reason = model, held, reason + self.host_bytes = host_bytes if type(host_bytes) is int and host_bytes > 0 else 0 def services(self): from . import server_mode @@ -144,10 +154,28 @@ def busy(self): def loaded(self): from .resident_process import OWNER if self.model == 'video': - return OWNER.process is not None and OWNER.process.poll() is None + if OWNER.process is None or OWNER.process.poll() is not None: + return False + # With settings to preload, the video model itself, not only the worker with its encoder. + return self.preload() is None or 'engine' in self.held_roles() _, images = self.services() return images.worker_alive() and images.loaded_model is not None + def preload(self): + if self.model != 'video': + return None + from . import engine_preload + return engine_preload.recall() + + def held_roles(self): + """The models the video worker holds; empty while it is busy or cannot be read.""" + from . import resident_process + try: + answer = resident_process.status({resident_process.ENV: str(resident_process.OWNER.endpoint)}) + except Exception: + return set() + return {row.get('role') for row in (answer or {}).get('models') or [] if isinstance(row, dict)} + def machine(self): videos, images = self.services() return (videos if self.model == 'video' else images).installation()[1] @@ -155,20 +183,40 @@ def machine(self): def need(self, machine): """Card bytes the model needs free: its files plus the picture reserve.""" from .image_gen import image_model, keep + extra = 0 if self.model == 'video': from .video_warm import encoder_file - files = encoder_file(machine) + files = [] if 'encoder' in self.held_roles() else encoder_file(machine) + value = self.preload() + extra = value['card_bytes'] if value else 0 else: _, images = self.services() files = images.model_files(machine, self.held) - size = sum(os.path.getsize(item) for item in files) + size = sum(os.path.getsize(item) for item in files) + extra return size + keep.RESERVE_BYTES if size > 0 else None + def host_least(self): + """Host memory the model's worker keeps free once it holds the model: below it, it lets go again.""" + from .resident_process import host_margin + if self.model == 'video': + value = self.preload() + if value: + from .resident_models import GiB + # The video model's host weights beside the next encoder's start, as the worker settles after a video. + pinned = int(float(value['engine_options'].get('pin_host_gb') or 0) * 1e9) + return max(host_margin(), 8 * GiB + pinned) + return host_margin() + from .image_gen import image_model, keep + if self.held == image_model.H3: + from .image_gen.h3_pipeline import host_floor + return max(host_margin(), host_floor()) + return max(host_margin(), keep.HOST_LEAST_BYTES) + def room(self): """The card's used bytes when the model fits now beside everything on it, else None.""" from .background_room import available_memory - from .resident_process import OWNER, gpu_memory, host_margin - if available_memory() < host_margin() + HOST_SPARE_BYTES: + from .resident_process import OWNER, gpu_memory + if available_memory() < self.host_bytes + self.host_least() + HOST_SPARE_BYTES: return None machine = self.machine() if self.model == 'image' and OWNER.process is not None and OWNER.process.poll() is None: diff --git a/freevideo_engine/server_mode.py b/freevideo_engine/server_mode.py index 89ec707c..6ad5bae7 100644 --- a/freevideo_engine/server_mode.py +++ b/freevideo_engine/server_mode.py @@ -10,7 +10,8 @@ Server mode (FREEVIDEO_SERVER_RESIDENT=1, Linux only; the desktop application never sets it) adds loading the video model's text encoder and the configured picture model as the server starts, and bringing the picture model back -after a video that needed its room. +after a video that needed its room. Where an idle picture worker keeps its model (``keeps_idle``), a desktop also +loads at start the kinds of model it used lately (``warm_at_start``), its picture model only into free room. Every release or trim is recorded with its reason (``releases``), for the running status. A model that only made room for another program, or the picture model for a video, comes back once the room is free again (``rewarm``). @@ -116,6 +117,9 @@ def released(model, row): global _last_release event = dict(model=model, action=row.get('action', 'released'), reason=str(row.get('reason') or 'unknown'), at=float(row.get('at') or time.time())) + if isinstance(row.get('other_programs'), list): + # Local only (this machine's monitor): who took the card, so it can be found while it still runs. + event['other_programs'] = [dict(item) for item in row['other_programs'] if isinstance(item, dict)] with _mutex: _last_release = event _releases[:] = (_releases + [event])[-RELEASES_KEPT:] @@ -123,10 +127,11 @@ def released(model, row): if model == 'image' and event['reason'] == 'video_start' and enabled(): # Until the picture worker can stay through a video, it comes back once the video is done. threading.Thread(target=_after_video, name='freevideo-server-rewarm', daemon=True).start() - if event['action'] == 'released': + # A trim keeps the worker but gives the video model back (a picture's room, host memory): it comes back as well. + if event['action'] == 'released' or (event['action'] == 'trimmed' and model == 'video'): try: from . import rewarm - rewarm.after_release(model, event['reason'], row.get('held')) + rewarm.after_release(model, event['reason'], row.get('held'), row.get('worker_rss_bytes')) except Exception: logging.warning('[FreeVideo] Could not wait to bring the %s model back', model, exc_info=True) for callback in listeners: @@ -204,6 +209,32 @@ def warm(models=('video', 'image'), policy='resident'): raise ValueError('invalid_request') if not enabled(): return dict(state='off', reason=None) + return _start(tuple(models), beside=False) + + +def recent_models(ops): + """The kinds of model to load at start from the last operations ('image' or 'video', oldest first): the kinds + used lately, the one used last first; the video side alone when nothing has been used yet.""" + order = [] + for kind in reversed(ops): + if kind in ('video', 'image') and kind not in order: + order.append(kind) + return tuple(order) or ('video',) + + +def warm_at_start(): + """Load at start what this computer used lately, as a server does: on Linux and Windows unless keeping models + is off (Macs keep loading on first use). A server loads both sides; a desktop loads the kinds of its last + operations, and its picture model only into room that is free, never in place of the video models.""" + if enabled(): + return warm() + if not keeps_idle(): + return dict(state='off', reason=None) + from . import usage_habit + return _start(recent_models(usage_habit.ops()), beside=True) + + +def _start(models, beside): with _mutex: thread = _warm['thread'] if thread is not None and thread.is_alive(): @@ -225,27 +256,44 @@ def warm(models=('video', 'image'), policy='resident'): return dict(state='skipped', reason='not_started') with _mutex: _warm.update(started=time.monotonic(), ready_seconds=None, models=tuple(models)) - _warm['thread'] = threading.Thread(target=_load, args=(tuple(models), videos, images), + _warm['thread'] = threading.Thread(target=_load, args=(tuple(models), videos, images, beside), name='freevideo-server-warm', daemon=True) _warm['thread'].start() return dict(state='loading', reason=None) -def _load(models, videos, images): +def _video_fits(): + """Whether the video side fits now beside what the card and host memory hold (as rewarm reads it).""" + try: + from .rewarm import Probe + return Probe('video').room() is not None + except Exception: + logging.warning('[FreeVideo] Reading the room for the video model failed', exc_info=True) + return False + + +def _load(models, videos, images, beside=False): + """Load ``models`` in their order; with ``beside`` (a desktop), each after the first only into room that is + free beside it, so where both do not fit the one used last keeps the card.""" try: - if 'video' in models: - answer = videos.warm(dict(level='full', mode='eager')) - if answer.get('warm') == 'loading' and videos.thread is not None: - videos.thread.join() - if 'image' in models and images is not None: - try: - info = images.installed_models() - except Exception: - info = () - model = image_model(info) - if model is not None: - images.warm(dict(model=model, level='full', mode='eager')) - images.wait_warm(600.) + for index, kind in enumerate(models): + later = beside and index > 0 + if kind == 'video': + if later and not _video_fits(): + continue + answer = videos.warm(dict(level='full', mode='eager')) + if answer.get('warm') == 'loading' and videos.thread is not None: + videos.thread.join() + elif kind == 'image' and images is not None: + try: + info = images.installed_models() + except Exception: + info = () + model = image_model(info) + if model is not None: + images.warm(dict(model=model, level='full', mode='eager', beside=True) if later + else dict(model=model, level='full', mode='eager')) + images.wait_warm(600.) except Exception: logging.warning('[FreeVideo] Server warm-up failed', exc_info=True) finally: @@ -275,6 +323,7 @@ def state(): alive = owner.process is not None and owner.process.poll() is None and owner.endpoint if alive and not owner.active: answer = resident_process.status({resident_process.ENV: str(owner.endpoint)}) + owner.note_evictions(answer) with _mutex: if isinstance(answer, dict): _held[:] = [(owner.process.pid, row) for row in answer.get('models') or [] if isinstance(row, dict)] diff --git a/freevideo_engine/support_report.py b/freevideo_engine/support_report.py index 2be71ac7..6f345ffd 100644 --- a/freevideo_engine/support_report.py +++ b/freevideo_engine/support_report.py @@ -4,6 +4,7 @@ import json import math from pathlib import Path +import re import statistics import sys import time @@ -329,6 +330,34 @@ def write_encoder_retry(output, encoding, *, index): return write(output, _retry=dict(stage='encoding', index=index, encoding=encoding)) +RESIDENT_ROWS = 20 +RESIDENT_NUMBERS = ('seconds', 'idle_seconds', 'released_gpu_bytes', 'worker_rss_bytes', 'worker_private_bytes') + + +def resident_releases(rows): + """What the kept video worker did since the last request, in fixed words and numbers only. Another program + that took the card is described by its card bytes; its name and pid are only on this machine's monitor.""" + found = [] + for row in rows if isinstance(rows, list) else []: + if not isinstance(row, dict): + continue + item = {key: row[key] for key in ('action', 'reason') + if isinstance(row.get(key), str) and re.fullmatch(r'[a-z_0-9]{1,40}', row[key])} + item.update({key: row[key] for key in RESIDENT_NUMBERS + if isinstance(row.get(key), (int, float)) and not isinstance(row.get(key), bool)}) + if isinstance(row.get('role'), str) and re.fullmatch(r'[a-z_0-9]{1,40}', row['role']): + item['role'] = row['role'] + for key in ('held', 'roles'): + if isinstance(row.get(key), list): + item[key] = [role for role in row[key] if isinstance(role, str) and re.fullmatch(r'[a-z_0-9]{1,40}', role)] + if isinstance(row.get('other_programs_gpu_bytes'), list): + item['other_programs_gpu_bytes'] = [size if type(size) is int else None + for size in row['other_programs_gpu_bytes']] + if item: + found.append(item) + return found[-RESIDENT_ROWS:] + + def write(output, report=None, bridge=None, *, _retry=None, live=False, restarted=False): """Bounded JSON/log reads only. Failure to write must not fail generation. @@ -507,6 +536,9 @@ def count(value): agent_poll.get('agent_generation_jobs')) if stalled: payload['agent_generation_stalls'] = stalled + releases = resident_releases(bridge.get('resident_since_last')) + if releases: + payload['bridge']['resident_since_last'] = releases try: from .comfy_host_stats import host_fields host = host_fields() diff --git a/freevideo_engine/video_warm.py b/freevideo_engine/video_warm.py index 2742219e..85f69dcf 100644 --- a/freevideo_engine/video_warm.py +++ b/freevideo_engine/video_warm.py @@ -2,8 +2,8 @@ 'light' (the panel was opened or touched) reads the text encoder and the video model's files into the OS file cache, as far as free memory goes. 'full' (a video is likely next: the prompt is being written, the tray was closed back to -the prompt) starts the resident worker, places the text encoder on the card under the installation lease and reads -the video model's files ahead. 'conservative' only keeps ready what the resident worker already holds. +the prompt) starts the resident worker, places the text encoder on the card under the installation lease, loads the +video model with the last video's settings where it fits (engine_preload) and reads the video model's files ahead. 'conservative' only keeps ready what the resident worker already holds. Never in the way: skipped while a video, a picture or another task runs; a video or a picture that starts stops it, and the encoder placement yields within the worker's own yield time. While the image worker holds the lease (a @@ -88,7 +88,8 @@ def run(self, level, root, machine, halt): self.last = (self.prepare(root, machine, halt) if level == 'full' else self.read_ahead(root, machine, encoder=True)) except Exception as error: - logging.warning('[FreeVideo] Video warm-up failed: %s', type(error).__name__) + from .failure_details import raised_at + logging.warning('[FreeVideo] Video warm-up failed: %s at %s', type(error).__name__, raised_at(error)) self.last = dict(state='failed', reason=type(error).__name__) def read_ahead(self, root, machine, *, encoder): @@ -117,11 +118,16 @@ def prepare(self, root, machine, halt): source = comfy_bridge.source_root() environment = comfy_bridge.engine_environment(root, source) environment.update(FREEVIDEO_HOME=str(root), PYTHONPATH=str(source)) - endpoint = owner.start(root, source, machine['python'], environment) + try: + endpoint = owner.start(root, source, machine['python'], environment, stop=halt) + except resident_process.StartStopped: + return dict(state='cancelled') if placed_encoder_bytes(endpoint) > 0: placed = dict(state='kept', reason='The encoder is already on the card') else: placed = self.place(endpoint, machine, environment, descriptor, halt) + if not halt.is_set(): + placed = dict(placed, video_model=self.place_engine(endpoint, environment, descriptor, halt)) finally: lease.__exit__(None, None, None) if halt.is_set(): @@ -138,7 +144,11 @@ def place(endpoint, machine, environment, descriptor, halt): from .kernel_capabilities import available_backends from .policy import choose hardware = detect() - policy = choose(hardware, available_backends=available_backends(hardware), allow_capacity_trial=True) + # Plans from the saved kernel checks and never runs them: a check cannot be stopped for a video, and this + # process (ComfyUI's own Python) is not the one the video runs in, so its checks never match the video's and + # would run again at every start. The video runs its checks in its own process. + policy = choose(hardware, available_backends=available_backends(hardware, probe_missing=False), + allow_capacity_trial=True) environment = dict(environment) environment.pop(resident_process.ENV, None) return place_now(endpoint, dict(encoder=machine.get('encoder'), comfy_root=machine.get('comfy_root'), @@ -147,6 +157,58 @@ def place(endpoint, machine, environment, descriptor, halt): gpu_budget_bytes=policy.gpu_budget_bytes, ram_budget_bytes=policy.ram_budget_bytes, allocator=policy.allocator_config, limits=dict(system=hardware.system), stop=halt) + @staticmethod + def place_engine(endpoint, environment, descriptor, halt): + """The video model with the last video's settings into the resident worker, under the caller's lease.""" + from . import engine_preload, resident_process + from .idle_encoder import PreloadCancelled, watch + from .monitoring import save + from .ram import ProcessMemory + value = engine_preload.recall() + if value is None: + return dict(state='skipped', reason='no_settings') + environment = dict(environment, **{resident_process.ENV: str(endpoint)}) + try: + held = resident_process.status(environment) + except Exception: + held = None + allocator = value.get('allocator') or '' + current = held.get('allocator_config') if isinstance(held, dict) else None + if current is not None and current != allocator: + # Another allocator restarts the worker and loses what it holds: the video loads its model as before. + result = dict(state='skipped', reason='allocator_changed') + logging.info('[FreeVideo] Video model not preloaded: the last video used other allocator settings') + return result + environment.update(PYTORCH_ALLOC_CONF=allocator, PYTORCH_CUDA_ALLOC_CONF=allocator) + directory = Path(endpoint).parent + result_path, cancelled = directory / 'engine-preload.json', directory / 'engine-preload.cancel' + request_path = directory / 'engine-preload-worker.json' + for item in (result_path, cancelled): + item.unlink(missing_ok=True) + save(request_path, engine_preload.worker_request(value, metrics=result_path, cancel=cancelled)) + result, memory, workers = dict(state='skipped'), ProcessMemory(), [] + try: + result.update(watch(endpoint, request_path, environment, descriptor, result_path, cancelled, + int(value.get('ram_budget_bytes') or 1 << 62), result, memory, held=workers, + stop=halt, module='freevideo_engine.worker', capability=engine_preload.CAPABILITY)) + except PreloadCancelled as error: + if workers: + try: + workers[0].stop_request(grace=.5) + except BaseException: + pass + result.update(state='cancelled', reason=str(error)) + except Exception as error: + result.update(state='cancelled' if halt.is_set() else 'failed', error_type=type(error).__name__, + reason=str(error)[-300:]) + result.pop('success', None) + geometry = value.get('geometry') or {} + logging.info('[FreeVideo] Video model preload with the last video settings (%sx%s, %s s): %s%s', + geometry.get('width'), geometry.get('height'), geometry.get('requested_seconds'), + result.get('state'), (' (%s)' % result['reason']) if result.get('reason') else + (' in %.1f s' % result['seconds']) if result.get('seconds') is not None else '') + return result + def cancel(self): """The page left the panel: the warm-up and its own file read stop; a kept worker stays to its idle hold.""" from .encoder_prewarm import IDLE @@ -157,11 +219,18 @@ def cancel(self): def stop(self, timeout=8.): """A video or a picture starts, or the page left: the warm-up stops; the file read stops with IDLE.stop().""" + from .idle_encoder import KEPT_YIELD_SECONDS with self.mutex: thread, halt = self.thread, self.halt halt.set() if thread is not None and thread is not threading.current_thread(): - thread.join(timeout=timeout) + # The placement's watch() decides its yield time (longer while the worker keeps video models); this + # only bounds a warm-up that hangs. + limit = max(timeout, KEPT_YIELD_SECONDS + 2.) + thread.join(timeout=limit) + if thread.is_alive(): + # The request then waits for the GPU lease on its own; this line names who kept it. + logging.warning('[FreeVideo] Video warm-up did not stop within %.0f s; it still holds the GPU.', limit) return dict(warm='cancelled') diff --git a/web/editor.css b/web/editor.css index c51cf340..738cfb2a 100644 --- a/web/editor.css +++ b/web/editor.css @@ -260,6 +260,7 @@ @media(min-width:681px) and (max-width:1279px){.fv-ed-notice{right:32px;max-width:min(560px,calc(100vw - 330px))}} .fv-ed-notice .fv-issue-button{margin-left:12px;vertical-align:middle;pointer-events:auto} @media(max-width:680px){ + .fv-studio.fv-editor .fv-ed-genbar{height:auto;align-self:stretch} .fv-studio.fv-editor{--fv-ed-generation-row:calc(96px + var(--fv-ed-description-growth,0px) + var(--fv-ed-note-growth,0px));grid-template-columns:minmax(0,1fr);grid-template-rows:auto var(--fv-ed-project-h) minmax(0,1fr) 40px minmax(var(--fv-ed-generation-row),auto) 40px 236px;overflow:hidden auto} .fv-editor .fv-header{overflow-x:auto} .fv-editor .fv-ed-name{font-size:13px;max-width:112px;flex:1;padding:0 2px} diff --git a/web/editor.js b/web/editor.js index ebc65c05..945c5aee 100644 --- a/web/editor.js +++ b/web/editor.js @@ -2362,6 +2362,8 @@ export function openEditor({api, app, from = null, panel = {}, components: given function hide() { closing = false; closePromise = null; handle.kept = true; player.pause(); player.stopPreview(); lineStop?.(); + // The "last edit not found" card belongs to that opening; closing the editor takes it away. + for (const card of notices.querySelectorAll('[data-lost-last]')) card.remove(); // The microphone is let go with the view: an open record bar closes, and a take in progress lands as Stop would. recording.hide(); detachBar?.(); @@ -2512,10 +2514,11 @@ export function openEditor({api, app, from = null, panel = {}, components: given if (lastMissing && !state.record.id) { // Point at the name menu only when it lists another edit to open. store.projects().catch(() => ({})).then(rows => { - if (closing || disposed) return; + if (closing || disposed || !element.open) return; const others = Array.isArray(rows) && rows.some(row => row.id !== state.record.id); notify(t('The last edit could not be found, so a blank edit is open.', '找不到上次的剪辑,已打开空白剪辑。') + (others ? t(' Click the edit name at the top to open another edit.', '点击顶部的剪⁠辑⁠名可打开其他剪辑。') : '')); + notices.lastElementChild?.setAttribute('data-lost-last', ''); }); } if (tracksFailure) throw tracksFailure; diff --git a/web/error_panel.js b/web/error_panel.js index bd5deff4..a967780d 100644 --- a/web/error_panel.js +++ b/web/error_panel.js @@ -49,8 +49,8 @@ const PLAIN_ERRORS = [ summary: ['Connect up to 3 pictures as references, and remove video, audio and pre-encoded inputs.', '最多接 3 张图片作为参考图,并移除视频、音频参考和预编码输入。']}, // Only the Mac engine still refuses keyframes next to references; elsewhere they become still guides. {key: 'media-mixed-layout', message: 'Reference and first/last keyframe layouts cannot be mixed in one request on this Mac; keep one of the two', - title: ['On this Mac, first and last frames cannot be used with references', '这台 Mac 上首尾帧不能与参考素材同时使用'], - summary: ['Turn off the media cards or inputs you are not using, then generate again.', '请关闭本次不用的素材卡片或输入,再重新生成。']}, + title: ['Use references or first and last frames', '参考素材与首尾帧请选其一'], + summary: ['On a Mac, keep one of the two: turn off the media cards or inputs you are not using, then generate again.', '在 Mac 上请保留其中一种:关闭本次不用的素材卡片或输入,再重新生成。']}, {key: 'audio-original-passes', prefixes: ['audio_original_passes:'], title: ['This audio needs two-pass acceleration', '这段音频需要二采加速'], summary: ['Turn on "Two-pass acceleration" or set the audio to "Reference".', '请打开“二采加速”,或把音频改选“参考”。']}, @@ -112,7 +112,11 @@ const PLAIN_ERRORS = [ function knownError(text) { const lines = String(text).slice(0, 65536).split(/\r?\n/).map(line => line.trim()).filter(Boolean); const index = /^FreeVideo generation failed(?: \(exit -?\d+\))?$/.test(lines[0] ?? '') ? 1 : 0; - const line = (lines[index] ?? '').replace(/^(?:[A-Za-z_][\w.]*(?:Error|Exception)|(?:[\w.]+\.)?SamplingTableUnavailable):\s*/, ''); + // Under the header the engine puts the child's last error first as "Cause: " (failure_details), + // so that line counts the same as the bare error; the same words as a first line stay typed text. + const first = lines[index] ?? ''; + const line = (index && /^Cause:\s/.test(first) ? first.replace(/^Cause:\s*/, '') : first) + .replace(/^(?:[A-Za-z_][\w.]*(?:Error|Exception)|(?:[\w.]+\.)?SamplingTableUnavailable):\s*/, ''); if (line.startsWith('SAMPLING_TABLE_UNAVAILABLE: ')) { try { const d = JSON.parse(line.slice('SAMPLING_TABLE_UNAVAILABLE: '.length)); @@ -588,7 +592,8 @@ export function failureAdvice(value, t, known = knownError(value)) { ['Restart FreeVideo and generate again.', '请重启 FreeVideo 后重新生成。']); // The generation process ended without a Python error: it crashed or was ended from outside. The code // names which (freevideo_engine/failure_details.py generation_failure prints "(exit N)"); the number stays in the details. - const exit = /FreeVideo generation failed \(exit (-?\d+)\)/.exec(text); + // A "Cause:" line means the process did report an error (a named one that no row above knows): it is not an unexplained exit. + const exit = /^Cause: /m.test(text) ? null : /FreeVideo generation failed \(exit (-?\d+)\)/.exec(text); if (exit) { const code = Number(exit[1]); const killed = code === 137 || code === -9 || code === 3221225786; diff --git a/web/library.js b/web/library.js index d0bfc312..1e3f4ea1 100644 --- a/web/library.js +++ b/web/library.js @@ -18,7 +18,7 @@ import { createMetaStore, promptOfRow } from './image_view_history.js'; import { attach as attachPlayerBar } from './glass/player_bar.js'; import { hasPictureThumbnail, mediaQueue, pictureThumbnailURL, watchCards } from './work_media.js'; import { zoomable } from './picture_zoom.js'; -import { createUpscaleOffer, upscale4kOffer } from './upscale_offer.js'; +import { createUpscaleOffer, upscaleChoices, UPSCALE_USE, UPSCALE_QUEUED, UPSCALE_FAILED } from './upscale_offer.js'; import { capabilityPoints } from './chain_support.js'; const style = document.createElement('link'); @@ -396,8 +396,9 @@ export function setDefaultUpscale(run) { defaultUpscale = typeof run === 'functi // ``upscaleWork`` makes a larger copy of a finished video; registered by the studio like the second pass. let defaultUpscaleWork = null; export function setDefaultUpscaleWork(run) { defaultUpscaleWork = typeof run === 'function' ? run : null; } -// The longest single request at a size, as the planner admits it now; null when it cannot be told. -async function admittedFrames(width, height) { +// The longest single request at a size, as the planner admits it now; null when it cannot be told. The studio asks the +// same for the result's "⋯". +export async function admittedFrames(width, height) { for (let tries = 0; tries < 5; tries++) { const response = await api.fetchApi('/freevideo/capabilities?' + new URLSearchParams({width, height})); if (!response.ok) return null; @@ -1485,15 +1486,11 @@ export function openLibrary(t, options = {}) { disabled: secondPassRunner() ? '' : ['Open the create view first, then run the second pass', '请先打开创作页,再继续二采'], run: () => secondPass(one).then(() => say(t('Queued. It appears in "Creations" when done.', '已加入队列,完成后在“作品”里。')), error => say(t('Could not start the second pass: ', '无法继续二采:') + error.message, true))}); // One 1.5× step where this computer can generate it (gap-04a), and the 4K size by a small model (gap-04b): - // each shown on its own, the same way. - for (const [id, larger, options] of [['upscale', defaultUpscaleWork && upscaleOffer.offer(one), {}], - ['upscale-4k', defaultUpscaleWork && upscale4kOffer(one), {to: '4k'}]]) { - if (!larger) continue; - const size = `${larger.width} × ${larger.height}`; - items.push({id, icon: 'upscale', label: [`Upscale to ${size}`, `放大到 ${size}`], - use: ['Make a larger copy as a new creation', '生成一个更大的新作品,原作品不变'], - run: () => defaultUpscaleWork(one, options).then(() => say(t('Queued. It appears in "Creations" when done.', '已加入队列,完成后在“作品”里。')), - error => say(t('Could not start upscaling: ', '无法开始放大:') + error.message, true))}); + // each shown on its own, the same rows as the result's "⋯" (upscaleChoices). + if (defaultUpscaleWork) for (const choice of upscaleChoices(one, upscaleOffer)) { + items.push({id: choice.id, icon: 'upscale', label: choice.label, use: UPSCALE_USE, + run: () => defaultUpscaleWork(one, choice.options).then(() => say(t(...UPSCALE_QUEUED)), + error => say(t(...UPSCALE_FAILED) + error.message, true))}); } items.push({id: 'reuse', icon: 'reuse', label: ['Reuse settings', '复用设置'], disabled: one.preview ? ['A first-pass preview: finish it first', '这是一采预览,先继续二采'] : '', diff --git a/web/lora_check.js b/web/lora_check.js index 6c3c1d9e..a6176801 100644 --- a/web/lora_check.js +++ b/web/lora_check.js @@ -1,5 +1,5 @@ // What the LoRA check found, as words for the row; the check itself is /freevideo/lora/check. -const FAMILIES = {wan: true, hunyuan: true, ltx: true, sd: true}; +const FAMILIES = {wan: true, hunyuan: true, ltx: true, sd: true, llm: true}; const size = shape => Array.isArray(shape) ? shape.join('×') : ''; /** Row notice: partial application has no details; unusable files keep their explanation. */ diff --git a/web/notifications.js b/web/notifications.js index e3add1e3..de7e6e8f 100644 --- a/web/notifications.js +++ b/web/notifications.js @@ -137,7 +137,7 @@ const ago = (at, cn = CN) => { }; export function noteWords(note, cn = CN) { const w = pair => words(pair, cn); - if (note.type === 'toast') return {title: note.title || w(['Notice', '提醒']), sub: note.reason || w(['Did not finish', '没有完成'])}; + if (note.type === 'toast') return {title: note.title || w(['Notice', '提醒']), sub: note.reason || (note.status === 'notice' ? '' : w(['Did not finish', '没有完成']))}; if (note.type === 'agent') return {title: note.title || w(['Assistant task', '助手任务']), sub: note.reason || w(['See why', '查看原因'])}; if (note.type === 'install') { return note.status === 'done' ? {title: w([`${note.label} is installed`, `${note.label} 已安装`]), sub: w(['Ready to use', '可以使用了'])} @@ -147,7 +147,7 @@ export function noteWords(note, cn = CN) { const head = note.status === 'done' ? w([`${kind} finished`, `${kind}生成完成`]) : note.status === 'failed' ? w([`${kind} failed`, `${kind}生成失败`]) : w([`${kind} stopped`, `${kind}生成中断`]); return {title: note.prompt || head, sub: note.prompt ? head : note.status === 'done' ? w(['In Creations', '已放进作品库']) : note.reason || w(['See why', '查看原因'])}; } -const ICON = {done: 'check', failed: 'alert', interrupted: 'alert'}; +const ICON = {done: 'check', failed: 'alert', interrupted: 'alert', notice: 'alert'}; // ── The page part ── let notes = null, panel = null, bells = new Set(), installs = {}, installTimer = 0, liveRows = []; @@ -201,7 +201,10 @@ async function openNote(note) { closeNotifications({focus: false}); store().markRead(note.id); // A notice of a page message has nowhere to go; reading it was the point. - if (note.type === 'toast') return; + if (note.type === 'toast') { + if (note.setup) { const {openSetup} = await import('./setup.js'); openSetup({section: note.setup}); } + return; + } if (note.type === 'install') { await globalThis.FreeVideoShell?.go?.('image').catch(() => {}); return; } if (note.type === 'agent') { try { if (globalThis.FreeVideoShell?.view?.() !== 'autopilot') await globalThis.FreeVideoShell?.go?.('autopilot'); } catch { /* The view did not open: stay. */ } @@ -399,7 +402,7 @@ export function mountNotices(element, options = {}) { } export function noticeState() { const rows = store().list(); - return {unread: rows.filter(row => !row.read).length, failed: rows.filter(row => !row.read && row.status !== 'done').length, running: jobs.active().length}; + return {unread: rows.filter(row => !row.read).length, failed: rows.filter(row => !row.read && row.status !== 'done' && row.status !== 'notice').length, running: jobs.active().length}; } const noticeListeners = new Set(); export function onNotices(fn) { noticeListeners.add(fn); fn(noticeState()); return () => noticeListeners.delete(fn); } @@ -433,7 +436,9 @@ async function checkInstalls() { function refreshLive() { liveRows = liveItems(); syncBells(); if (notificationsOpen()) drawPanel(); refreshMounts(); } // ── toast(): notices and undo bars (glob.css §9) ── -// toast(text, {tone, detail, icon, ms, sticky, action: {label, run, use, key}}) → {close()} +// toast(text, {tone, detail, icon, ms, sticky, keep: {id, setup, title, sub}, action: {label, run, use, key}}) → {close()} +// keep: a notice that must not be missed is also kept in the notification list until closed there; setup is the +// settings section its row opens; title and sub, when given, are the row's shorter words (the toast keeps its text). // tone: 'ok' | 'info' | 'caution' | 'warn' | 'fail'; detail: a second, quieter part of the line. // Lives 5 s, 8 s with an action (an undo); sticky ones (failures by default) stay until closed. // One shows at a time, in the top bar's right column (a bottom strip above the view's own bar under 720 px, at @@ -451,6 +456,7 @@ export function toastSpec(message, options = {}) { const long = tone === 'fail' || options.sticky === true; const given = Number.isFinite(options.ms) && options.ms > 0 ? options.ms : 0; return {text: words(message), detail: words(options.detail || ''), tone, icon: options.icon || TONE_ICON[tone] || 'check', action, + keep: options.keep && typeof options.keep === 'object' ? {id: String(options.keep.id || ''), setup: String(options.keep.setup || ''), title: String(options.keep.title || ''), sub: String(options.keep.sub || '')} : null, sticky: false, ms: long ? Math.max(given, UNDO_LIFE) : given || (action ? UNDO_LIFE : TOAST_LIFE)}; } // The queue, apart from the page: show(next) when the visible one goes; "+N" is the waiting count. @@ -554,6 +560,7 @@ function showToast(item, more) { runTimer(item); toastResized(); if (item.spec.tone === 'fail') store().add({id: `toast:${Date.now()}`, type: 'toast', status: 'failed', title: item.spec.text, reason: item.spec.detail, at: Date.now()}); + else if (item.spec.keep) store().add({id: item.spec.keep.id || `toast:${Date.now()}`, type: 'toast', status: 'notice', title: item.spec.keep.title || item.spec.text, reason: item.spec.keep.sub || item.spec.detail || (item.spec.action ? words(item.spec.action.label) : ''), setup: item.spec.keep.setup || null, at: Date.now()}); } // On a phone strip a message that wraps beside its controls takes its own row (notifications.css, is-stacked). function stackLong(el) { diff --git a/web/palette.js b/web/palette.js index a86157c7..db3635f5 100644 --- a/web/palette.js +++ b/web/palette.js @@ -57,18 +57,21 @@ export function fuzzyMatch(query, text) { } // One command against a query: every word of the query has to match the title (either language) or a keyword. -// The title in the language shown counts most; the ranges are for highlighting that title. +// The title in the language shown counts most; the ranges are for highlighting that title. A searchOnly command +// (a tutorial chapter) matches its title and its other names (aliases) only, each word as typed. export function scoreCommand(command, query, cn = CN) { const parts = fold(query).trim().split(/\s+/).filter(Boolean); if (!parts.length) return {score: 0, ranges: []}; const shown = words(command.title, cn), other = words(command.title, !cn); - const extra = [...(command.keywords || []), words(command.group || '', cn), words(command.group || '', !cn)].filter(Boolean); + const extra = command.searchOnly ? [...(command.aliases || [])] : [...(command.keywords || []), words(command.group || '', cn), words(command.group || '', !cn)].filter(Boolean); let total = 0; const ranges = []; for (const part of parts) { - const here = fuzzyMatch(part, shown), there = other !== shown ? fuzzyMatch(part, other) : null; + // A chapter title is long: its words have to appear as typed, not as scattered letters. + const allowed = text => !command.searchOnly || fold(text).includes(part); + const here = allowed(shown) ? fuzzyMatch(part, shown) : null, there = other !== shown && allowed(other) ? fuzzyMatch(part, other) : null; let best = here ? here.score : -Infinity; if (there) best = Math.max(best, there.score * 0.85); - for (const word of extra) { const hit = fuzzyMatch(part, word); if (hit) best = Math.max(best, hit.score * 0.7); } + for (const word of extra) { const hit = allowed(word) ? fuzzyMatch(part, word) : null; if (hit) best = Math.max(best, hit.score * 0.7); } if (best === -Infinity) return null; total += best; if (here) ranges.push(...here.ranges); @@ -83,8 +86,11 @@ export function mergeRanges(ranges) { // Ranks visible commands for a query. Without a query: recently used first (up to 5), then this view's commands, // then the rest in their groups. With one: best match first; a recent command gets a small lift. +// searchOnly commands (tutorial chapters) show only for a query, at most SEARCH_ONLY_LIMIT, after every matching command. +export const SEARCH_ONLY_LIMIT = 2; export function rankCommands(entries, query, {recent = [], cn = CN} = {}) { const q = String(query || '').trim(); + if (!q) entries = entries.filter(entry => !entry.command.searchOnly); const recentAt = id => { const at = recent.indexOf(id); return at < 0 ? Infinity : at; }; if (!q) { const recentRows = entries.filter(entry => recentAt(entry.command.id) < 5).sort((a, b) => recentAt(a.command.id) - recentAt(b.command.id)) @@ -104,7 +110,9 @@ export function rankCommands(entries, query, {recent = [], cn = CN} = {}) { const lift = recentAt(entry.command.id) < Infinity ? Math.max(0, 40 - recentAt(entry.command.id) * 5) : 0; out.push({...entry, section: 'match', ranges: hit.ranges, score: hit.score + lift + (entry.local ? 10 : 0)}); } - return out.sort((a, b) => b.score - a.score || a.order - b.order); + out.sort((a, b) => Number(Boolean(a.command.searchOnly)) - Number(Boolean(b.command.searchOnly)) || b.score - a.score || a.order - b.order); + let extra = 0; + return out.filter(entry => !entry.command.searchOnly || ++extra <= SEARCH_ONLY_LIMIT); } // ── Recently used ─────────────────────────────────────────────────────────────────────────────────────────────── @@ -281,6 +289,13 @@ export function builtinCommands() { ]; } +// Each finished tutorial chapter, found by its title or another name for it (either language) and opened at that chapter. +export const chapterCommands = (chapters, aliases = {}) => (chapters || []).filter(chapter => chapter?.id && chapter.title?.en && chapter.title?.zh).map(chapter => ({ + id: `tutorial.chapter.${chapter.id}`, searchOnly: true, group: G.help, icon: 'book', title: [chapter.title.en, chapter.title.zh], + aliases: [...(aliases[chapter.id]?.zh || []), ...(aliases[chapter.id]?.en || [])], + run: async () => (await import('./tutorial_book.js')).openTutorialBook({chapter: chapter.id}), +})); + // ── The palette ───────────────────────────────────────────────────────────────────────────────────────────────── // One surface with six scopes (Tab and Shift+Tab move between them): All, Actions, Creations, Prompts, Cast, Settings. // All without a query: recently used, this view's actions, the newest creations as a grid, then every action in its @@ -297,6 +312,8 @@ const SECTION_NAMES = {recent: ['Recently used', '最近使用'], match: ['Actio function build() { recent = createRecent((() => { try { return localStorage; } catch { return null; } })()); + // The tutorial's chapters, read when the palette first opens. + import('./tutorial_book_content.js').then(({TUTORIAL_CHAPTERS, TUTORIAL_ALIASES}) => registry.register('global', chapterCommands(TUTORIAL_CHAPTERS, TUTORIAL_ALIASES), {builtin: true}), () => {}); layer = createLayer({className: 'fv-palette', label: ['Search and commands', '搜索与命令'], onKey, onClose: () => { clearTimeout(searchTimer); searchRun++; }}); const d = layer.dialog; d.innerHTML = `
@@ -458,7 +475,9 @@ function draw() { const best = ranked[0]; const actionsFirst = best && scoreCommand(best.command, q).score >= 1150; // One group of actions: first when one of them starts with the query, else after what was found. - const actions = [...ranked.slice(0, actionsFirst ? 6 : 8), ...makeOfQuery(q)]; + // Chapters come after the actions, never in place of one. + const kept = new Set(ranked.filter(entry => !entry.command.searchOnly).slice(0, actionsFirst ? 6 : 8)); + const actions = [...ranked.filter(entry => entry.command.searchOnly || kept.has(entry)), ...makeOfQuery(q)]; if (actionsFirst) addCommands(actions, words(SECTION_NAMES.match)); addResults('works', {limit: 4}); addResults('prompt', {limit: 3}); diff --git a/web/result_actions.js b/web/result_actions.js index 7d09f8bd..2164c0d4 100644 --- a/web/result_actions.js +++ b/web/result_actions.js @@ -26,6 +26,7 @@ const ICONS = { trash: '', heart: '', reuse: '', + upscale: '', more: '', }; @@ -89,7 +90,8 @@ export function liftMenu(details, panel, {align = 'end', gap = 8} = {}) { function popover(menu, summary, onClose = () => {}) { const panel = menu.querySelector(':scope>.fv-menu'); - if (panel && menu.classList.contains('fv-action-more')) liftMenu(menu, panel); + // A lifted menu places itself when it opens; rows added while it is open call menu.fvPlace() to be placed again. + if (panel && menu.classList.contains('fv-action-more')) menu.fvPlace = liftMenu(menu, panel); const outside = event => { if (menu.open && !menu.contains(event.target)) menu.open = false; }; menu.addEventListener('toggle', () => { if (menu.open) document.addEventListener('pointerdown', outside, true); diff --git a/web/studio.js b/web/studio.js index 73c9c3ca..bcef69c4 100644 --- a/web/studio.js +++ b/web/studio.js @@ -22,7 +22,8 @@ import { skinSelect } from './fv_select.js'; import { loraMenu } from './lora_menu.js'; import { createPreviewScene } from './preview_scene.js?v=20261115-still'; import { animateDetails, closeDialog } from './motion.js'; -import { openLibrary, setDefaultUpscale, setDefaultUpscaleWork, videoThumbnailURL } from './library.js'; +import { openLibrary, setDefaultUpscale, setDefaultUpscaleWork, videoThumbnailURL, admittedFrames } from './library.js'; +import { createUpscaleOffer, upscaleChoices, UPSCALE_USE, UPSCALE_QUEUED, UPSCALE_FAILED } from './upscale_offer.js'; import { createRecentVideos } from './studio_recent.js'; import { createStudioQueue, randomSeed, turnNodeOn } from './studio_queue.js'; import { isNetworkTypeError, connectionLostText, wrappedFetchOnly } from './browser_extension.js'; @@ -1884,6 +1885,43 @@ export function openStudio(node, {extendFrom = null} = {}) { fault(shownMessage(error)); } const trimNote = el('div', '', 'fv-note fv-trim-note'); trimNote.hidden = true; trimNote.setAttribute('role', 'status'); + // The result's "⋯" offers the library's upscale rows (upscaleChoices, the same words and conditions): the 4K size at + // once, the 1.5× step once this computer's answer for that size is known. Asked again for each new video, since free + // memory may have changed; a row whose condition is not met is not shown. + const upscaleOffer = createUpscaleOffer(admittedFrames); + let upscaleAsked = null; + function upscaleItems(r) { + if (typeof node.freevideoUpscaleWork !== 'function') return []; + return upscaleChoices(r, upscaleOffer).map(choice => { + const item = el('button', null, 'fv-action fv-action-secondary fv-action-upscale fv-more-item'); + item.type = 'button'; item.dataset.upscale = choice.id; + item.append(icon('upscale'), el('span', t(...choice.label))); + item.dataset.fvTipName = t(...choice.label); item.dataset.fvTipUse = t(...UPSCALE_USE); + item.onclick = async () => { + const menu = item.closest('details'); if (menu) menu.open = false; + try { await node.freevideoUpscaleWork(r, choice.options); notify(t(...UPSCALE_QUEUED)); await syncQueue(); } + catch (error) { + if (extensionCause(error)) showQueueError(error); + else fault(t(...UPSCALE_FAILED) + shownMessage(error)); + } + }; + return item; + }); + } + function refreshUpscaleItems(r) { + if (upscaleAsked !== r.video) { upscaleAsked = r.video; upscaleOffer.forget(); } + void upscaleOffer.prepare([r]).then(() => { + const panel = links.querySelector('.fv-actions .fv-more-menu'); + if (disposed || result !== r || !panel) return; + const shown = [...panel.querySelectorAll('.fv-action-upscale')], fresh = upscaleItems(r); + if (shown.map(e => e.dataset.upscale).join() === fresh.map(e => e.dataset.upscale).join()) return; + shown.forEach(e => e.remove()); + const copy = panel.querySelector('.fv-action-copy'); + if (copy) copy.after(...fresh); else panel.prepend(...fresh); + // Open already: placed again for its new height, so it does not cover its button. + panel.closest('details')?.fvPlace?.(); + }); + } // Run second pass is the preview's primary action in the result bar. const secondPass = saved => async () => { try { await node.freevideoUpscaleResult(saved); await syncQueue(); } @@ -2118,7 +2156,8 @@ export function openStudio(node, {extendFrom = null} = {}) { links.replaceChildren(resultActions(r, t, {diagnostic: reported ? downloadReport : null, extend: saved => openExtendEditor(saved, node, {studio: dialog, isCurrent: () => dialog.open && dialog.dataset.closing !== 'true' && topDialog() === dialog && result === r}), - secondPass: r.preview ? secondPass(r) : null, reuse: r.preview ? null : reuse, layout: 'stage', more: [guideItem()]})); + secondPass: r.preview ? secondPass(r) : null, reuse: r.preview ? null : reuse, layout: 'stage', more: [...upscaleItems(r), guideItem()]})); + refreshUpscaleItems(r); if (runButtonReady) updateExtendButton(); stageBar.sync(); syncHistory(); // After a video finished just now, point at the report menu until the diff --git a/web/topbar.css b/web/topbar.css index aa471c89..bc38efea 100644 --- a/web/topbar.css +++ b/web/topbar.css @@ -12,6 +12,8 @@ html body .fv-topbar.fv-topbar.fv-topbar{ margin:0;padding:env(safe-area-inset-top,0px) var(--fv-tb-pad) 0!important;flex:none;overflow:visible; border:0!important;background:transparent!important;box-shadow:none!important; font:400 var(--fv-fs-2)/1.5 var(--fv-font);color:var(--fv-fg);-webkit-user-select:none;user-select:none} +/* The editor scrolls under its bar: keep it pinned and opaque. */ +html body .fv-editor .fv-header.fv-topbar.fv-topbar.fv-topbar{position:sticky;top:0;z-index:9;background:var(--fv-bg)!important} html body .fv-topbar.fv-topbar.fv-topbar:is([data-fv-fit="1"],[data-fv-fit="2"]){column-gap:var(--fv-sp-8)} html body .fv-topbar.fv-topbar.fv-topbar[data-fv-fit="3"]{--fv-tb-pad:calc(var(--fv-sp-12) + max(env(safe-area-inset-left,0px),env(safe-area-inset-right,0px)));column-gap:var(--fv-sp-8)} /* The node view: the toolbar is a full-width strip across the top of the window (moved here from shell.css), and the diff --git a/web/tutorial/beat-snap-1.webp b/web/tutorial/beat-snap-1.webp index a9c1b183..258977db 100644 Binary files a/web/tutorial/beat-snap-1.webp and b/web/tutorial/beat-snap-1.webp differ diff --git a/web/tutorial/beat-snap-2.webp b/web/tutorial/beat-snap-2.webp index 9eb099c3..c3eba510 100644 Binary files a/web/tutorial/beat-snap-2.webp and b/web/tutorial/beat-snap-2.webp differ diff --git a/web/tutorial/continue-or-new-shot-1.webp b/web/tutorial/continue-or-new-shot-1.webp index d8890606..81406e08 100644 Binary files a/web/tutorial/continue-or-new-shot-1.webp and b/web/tutorial/continue-or-new-shot-1.webp differ diff --git a/web/tutorial/continue-or-new-shot-2.webp b/web/tutorial/continue-or-new-shot-2.webp index 1d5fdd3b..49d2c9ee 100644 Binary files a/web/tutorial/continue-or-new-shot-2.webp and b/web/tutorial/continue-or-new-shot-2.webp differ diff --git a/web/tutorial/editor-1.webp b/web/tutorial/editor-1.webp index d75e3ecd..8dbed6ac 100644 Binary files a/web/tutorial/editor-1.webp and b/web/tutorial/editor-1.webp differ diff --git a/web/tutorial/editor-2.webp b/web/tutorial/editor-2.webp index 6494ad77..bbdc437c 100644 Binary files a/web/tutorial/editor-2.webp and b/web/tutorial/editor-2.webp differ diff --git a/web/tutorial/editor-extend-refs-1.webp b/web/tutorial/editor-extend-refs-1.webp index cbb1f755..64e5fec5 100644 Binary files a/web/tutorial/editor-extend-refs-1.webp and b/web/tutorial/editor-extend-refs-1.webp differ diff --git a/web/tutorial/editor-extend-refs-2.webp b/web/tutorial/editor-extend-refs-2.webp index 4db068a9..a4027a93 100644 Binary files a/web/tutorial/editor-extend-refs-2.webp and b/web/tutorial/editor-extend-refs-2.webp differ diff --git a/web/tutorial/extend-video-1.webp b/web/tutorial/extend-video-1.webp index 270a1866..0a94672e 100644 Binary files a/web/tutorial/extend-video-1.webp and b/web/tutorial/extend-video-1.webp differ diff --git a/web/tutorial/extend-video-2.webp b/web/tutorial/extend-video-2.webp index 883fb5ec..ebd76670 100644 Binary files a/web/tutorial/extend-video-2.webp and b/web/tutorial/extend-video-2.webp differ diff --git a/web/tutorial/film-project-1.webp b/web/tutorial/film-project-1.webp index 502c4c81..7e6225cc 100644 Binary files a/web/tutorial/film-project-1.webp and b/web/tutorial/film-project-1.webp differ diff --git a/web/tutorial/film-project-2.webp b/web/tutorial/film-project-2.webp index 09e37eac..b133e207 100644 Binary files a/web/tutorial/film-project-2.webp and b/web/tutorial/film-project-2.webp differ diff --git a/web/tutorial/library-export-1.webp b/web/tutorial/library-export-1.webp index f6b23c2a..4ae85187 100644 Binary files a/web/tutorial/library-export-1.webp and b/web/tutorial/library-export-1.webp differ diff --git a/web/tutorial/library-export-2.webp b/web/tutorial/library-export-2.webp index f6b23c2a..4ae85187 100644 Binary files a/web/tutorial/library-export-2.webp and b/web/tutorial/library-export-2.webp differ diff --git a/web/tutorial/lora-1.webp b/web/tutorial/lora-1.webp index c6780d8b..b64f580a 100644 Binary files a/web/tutorial/lora-1.webp and b/web/tutorial/lora-1.webp differ diff --git a/web/tutorial/lora-2.webp b/web/tutorial/lora-2.webp index 452ac6b8..a0dd702d 100644 Binary files a/web/tutorial/lora-2.webp and b/web/tutorial/lora-2.webp differ diff --git a/web/tutorial/narration-1.webp b/web/tutorial/narration-1.webp index 858e2200..01962b38 100644 Binary files a/web/tutorial/narration-1.webp and b/web/tutorial/narration-1.webp differ diff --git a/web/tutorial/narration-2.webp b/web/tutorial/narration-2.webp index 09dc8f6d..4f6b3479 100644 Binary files a/web/tutorial/narration-2.webp and b/web/tutorial/narration-2.webp differ diff --git a/web/tutorial/refine-1.webp b/web/tutorial/refine-1.webp index 8dc16cae..9e839932 100644 Binary files a/web/tutorial/refine-1.webp and b/web/tutorial/refine-1.webp differ diff --git a/web/tutorial/refine-2.webp b/web/tutorial/refine-2.webp index 58296c7f..2282a830 100644 Binary files a/web/tutorial/refine-2.webp and b/web/tutorial/refine-2.webp differ diff --git a/web/tutorial/replace-music-1.webp b/web/tutorial/replace-music-1.webp index f7e8f144..f4484572 100644 Binary files a/web/tutorial/replace-music-1.webp and b/web/tutorial/replace-music-1.webp differ diff --git a/web/tutorial/replace-music-2.webp b/web/tutorial/replace-music-2.webp index 6938ff41..64c28bce 100644 Binary files a/web/tutorial/replace-music-2.webp and b/web/tutorial/replace-music-2.webp differ diff --git a/web/tutorial/save-frame-1.webp b/web/tutorial/save-frame-1.webp index 74227785..ec72c023 100644 Binary files a/web/tutorial/save-frame-1.webp and b/web/tutorial/save-frame-1.webp differ diff --git a/web/tutorial/save-frame-2.webp b/web/tutorial/save-frame-2.webp index b9ad01a1..1333759c 100644 Binary files a/web/tutorial/save-frame-2.webp and b/web/tutorial/save-frame-2.webp differ diff --git a/web/tutorial/segment-prompt-1.webp b/web/tutorial/segment-prompt-1.webp index 6e16cf96..51f62b50 100644 Binary files a/web/tutorial/segment-prompt-1.webp and b/web/tutorial/segment-prompt-1.webp differ diff --git a/web/tutorial/segment-prompt-2.webp b/web/tutorial/segment-prompt-2.webp index e558ded0..1245a0e5 100644 Binary files a/web/tutorial/segment-prompt-2.webp and b/web/tutorial/segment-prompt-2.webp differ diff --git a/web/tutorial/separate-tracks-1.webp b/web/tutorial/separate-tracks-1.webp index 7c47ede2..737398fe 100644 Binary files a/web/tutorial/separate-tracks-1.webp and b/web/tutorial/separate-tracks-1.webp differ diff --git a/web/tutorial/separate-tracks-2.webp b/web/tutorial/separate-tracks-2.webp index 6fb6a246..d1800d64 100644 Binary files a/web/tutorial/separate-tracks-2.webp and b/web/tutorial/separate-tracks-2.webp differ diff --git a/web/tutorial/sound-to-picture-1.webp b/web/tutorial/sound-to-picture-1.webp index 303bb538..f82863cc 100644 Binary files a/web/tutorial/sound-to-picture-1.webp and b/web/tutorial/sound-to-picture-1.webp differ diff --git a/web/tutorial/sound-to-picture-2.webp b/web/tutorial/sound-to-picture-2.webp index c9cdb863..942aba53 100644 Binary files a/web/tutorial/sound-to-picture-2.webp and b/web/tutorial/sound-to-picture-2.webp differ diff --git a/web/tutorial/text-subtitles-1.webp b/web/tutorial/text-subtitles-1.webp index 9e384917..034fe698 100644 Binary files a/web/tutorial/text-subtitles-1.webp and b/web/tutorial/text-subtitles-1.webp differ diff --git a/web/tutorial/text-subtitles-2.webp b/web/tutorial/text-subtitles-2.webp index 45d9c1f1..a144e81c 100644 Binary files a/web/tutorial/text-subtitles-2.webp and b/web/tutorial/text-subtitles-2.webp differ diff --git a/web/tutorial/voice-recording-1.webp b/web/tutorial/voice-recording-1.webp index ee0de8c2..ad871292 100644 Binary files a/web/tutorial/voice-recording-1.webp and b/web/tutorial/voice-recording-1.webp differ diff --git a/web/tutorial/voice-recording-2.webp b/web/tutorial/voice-recording-2.webp index fac6b832..1a909ec7 100644 Binary files a/web/tutorial/voice-recording-2.webp and b/web/tutorial/voice-recording-2.webp differ diff --git a/web/tutorial_book.js b/web/tutorial_book.js index 6237e0b8..3a9f08ec 100644 --- a/web/tutorial_book.js +++ b/web/tutorial_book.js @@ -2,7 +2,7 @@ // steps with "Take me there" on the step that has a control, the limits, previous / next), an Examples page (the // feature examples: see one, fill it in, or be shown its control), and a follow-along card: "Follow along" folds the // booklet into a small card beside the work, step by step, so nothing is blocked while the person does it. -import {TUTORIAL_CHAPTERS} from './tutorial_book_content.js'; +import {TUTORIAL_CHAPTERS, TUTORIAL_ALIASES} from './tutorial_book_content.js'; import {FEATURE_TOUR, readyCards} from './feature_tour_content.js'; import {SHOWCASE_TEXT, SHOWCASE_ASSET} from './entry_showcase.js'; import {isolateDialogKeys, listenDialogKey, routeDialogKey} from './dialog_keys.js'; @@ -104,11 +104,11 @@ export function bookGroups(chapters = TUTORIAL_CHAPTERS) { return groups.filter(([, list]) => list.length); } export const bookOrder = (chapters = TUTORIAL_CHAPTERS) => bookGroups(chapters).flatMap(([, list]) => list); -// Search: every word must appear in the title, summary or steps (either language's own text). -export function searchChapters(query, lang, chapters = TUTORIAL_CHAPTERS) { +// Search: every word must appear in the title, summary, steps or another name for the chapter (either language's own text). +export function searchChapters(query, lang, chapters = TUTORIAL_CHAPTERS, aliases = TUTORIAL_ALIASES) { const words = String(query || '').toLowerCase().split(/\s+/).filter(Boolean); if (!words.length) return null; - return chapters.filter(c => { const hay = [c.title[lang], c.summary[lang], ...(c.steps[lang] || [])].join(' ').toLowerCase(); return words.every(word => hay.includes(word)); }).map(c => c.id); + return chapters.filter(c => { const hay = [c.title[lang], c.summary[lang], ...(c.steps[lang] || []), ...(aliases[c.id]?.[lang] || [])].join(' ').toLowerCase(); return words.every(word => hay.includes(word)); }).map(c => c.id); } function styles() { diff --git a/web/tutorial_book_content.js b/web/tutorial_book_content.js index 75c55712..fc5619d1 100644 --- a/web/tutorial_book_content.js +++ b/web/tutorial_book_content.js @@ -752,8 +752,8 @@ export const TUTORIAL_CHAPTERS = [ alt: {zh: '“作品库”:第一条作品已用红框标出。', en: 'Your creations, with the first video outlined in red.'}, }, steps: { - zh: ['点预览下方最近作品开头的“作品库”。', '选择一条视频,可播放,或点“接着生成”在剪辑视图中继续。', '在作品详情中点爱心图标收藏;列表上方选“收⁠藏”只看收藏的作品,选“全⁠部”看所有作品。', '需要成片时,在“剪辑视图”点“导⁠出”。', '在导出窗口选择范围、画质和内容;要更流畅的画面时,在“帧率”中选 48 或 60,中间的画面由显卡补出。再点“导⁠出”。'], - en: ['Choose "Creations" at the start of the recent videos below the preview.', 'Pick a video to play it, or choose "Continue" to continue it in the Edit view.', 'In a creation\'s details, choose the heart to add it to favorites. Above the list, choose "Favorites" to see only those, or "All" to see every creation.', 'For a finished file, choose "Export" in the Edit view.', 'In the export window choose the range, quality and content. For smoother motion, choose 48 or 60 under "Frame rate"; the graphics card makes the frames in between. Then choose "Export".'], + zh: ['点预览下方最近作品开头的“作品库”。', '选择一条视频,可播放,或点“接着生成”在剪辑视图中继续;要一次下载多个作品,点“选⁠择”选中它们,再点“下⁠载”,存成一个压缩包。', '在作品详情中点爱心图标收藏;列表上方选“收⁠藏”只看收藏的作品,选“全⁠部”看所有作品。', '需要成片时,在“剪辑视图”点“导⁠出”。', '在导出窗口选择范围、画质和内容;要更流畅的画面时,在“帧率”中选 48 或 60,中间的画面由显卡补出;要保留无损的声音,在“声音”中选“无损”。再点“导⁠出”。'], + en: ['Choose "Creations" at the start of the recent videos below the preview.', 'Pick a video to play it, or choose "Continue" to continue it in the Edit view. To download several at once, choose "Select", pick them, then choose "Download" to save them as one zip file.', 'In a creation\'s details, choose the heart to add it to favorites. Above the list, choose "Favorites" to see only those, or "All" to see every creation.', 'For a finished file, choose "Export" in the Edit view.', 'In the export window choose the range, quality and content. For smoother motion, choose 48 or 60 under "Frame rate"; the graphics card makes the frames in between. To keep the sound lossless, choose "Lossless" under "Sound". Then choose "Export".'], }, limits: { zh: ['删除作品前会确认;被剪辑使用的作品不能删除。', '导出窗口每次打开时,“内容”默认选“画面和声音”,“画质”默认选“高”;窗口里没有“帧率”时,这台电脑不支持 48 和 60 帧导出。', '导出过程中取消不会留下不完整的文件。'], @@ -833,3 +833,49 @@ export const TUTORIAL_CHAPTERS = [ }, }, ]; + +// Other names people use for a chapter (not words from its text): the command palette and the tutorial's own search +// find the chapter by these as well as by its title. +export const TUTORIAL_ALIASES = { + 'quick-start': {zh: ['入门', '新手', '第一次'], en: ['getting started', 'beginner', 'first time']}, + 'text-to-video': {zh: ['文生视频', '文字转视频'], en: ['text to video', 't2v']}, + 'timed-lines': {zh: ['台词', '分镜', '时间轴'], en: ['dialogue', 'storyboard', 'timestamps']}, + 'image-gen': {zh: ['文生图', '画图', '出图'], en: ['text to image', 'image generation']}, + 'image-references': {zh: ['图生图', '参考图出图'], en: ['image to image', 'img2img']}, + 'first-last-frame': {zh: ['首尾帧', '起始帧', '结束帧', '首帧', '尾帧'], en: ['start frame', 'end frame', 'first frame', 'last frame']}, + 'middle-frames': {zh: ['关键帧', '插帧'], en: ['keyframe', 'keyframes']}, + 'reference-video': {zh: ['图生视频', '参考生视频'], en: ['image to video', 'i2v']}, + 'cast-sheet': {zh: ['人物', '角色一致', '三视图', '人设'], en: ['character', 'consistent character', 'turnaround']}, + 'scenes-props': {zh: ['背景', '场景图', '道具图'], en: ['background', 'location', 'prop']}, + 'replace-person': {zh: ['换人', '换脸', '换角色'], en: ['swap person', 'face swap', 'swap character']}, + 'replace-two-people': {zh: ['双人替换', '换两个人'], en: ['two-person swap', 'swap two people']}, + 'edit-image': {zh: ['改图', '修图'], en: ['image edit', 'retouch']}, + 'local-image-edit': {zh: ['局部重绘', '涂抹', '蒙版'], en: ['inpaint', 'inpainting', 'mask']}, + 'new-image-shape': {zh: ['画板', '扩图', '画布'], en: ['canvas', 'outpaint', 'board']}, + 'lora': {zh: ['风格模型', '微调模型'], en: ['style model', 'fine-tuned model']}, + 'quality-tiers': {zh: ['画质', '档位', '清晰度', '速度'], en: ['quality', 'speed', 'resolution']}, + 'refine': {zh: ['预览', '二次采样', '精修'], en: ['preview', 'second pass', 'refine']}, + 'long-video': {zh: ['长视频', '多段', '连续生成'], en: ['long video', 'longer', 'multi-part']}, + 'extend-video': {zh: ['续写', '延长', '接着生成', '视频续写'], en: ['extend', 'continue video', 'make longer']}, + 'continue-or-new-shot': {zh: ['换镜头', '新镜头', '转场'], en: ['new shot', 'cut', 'transition']}, + 'editor': {zh: ['剪辑', '剪视频', '裁剪', '时间线'], en: ['edit', 'trim', 'timeline', 'crop']}, + 'save-frame': {zh: ['截图', '导出图片', '截帧'], en: ['screenshot', 'still', 'export frame']}, + 'editor-extend-refs': {zh: ['延长参考图', '续写参考图'], en: ['extend with reference', 'reference when extending']}, + 'segment-prompt': {zh: ['分段描述', '分段提示词'], en: ['per-part prompt', 'segment prompt']}, + 'separate-tracks': {zh: ['人声分离', '去背景音', '分离人声', '换声音'], en: ['vocal separation', 'remove music', 'stems']}, + 'replace-music': {zh: ['配乐', '背景音乐', 'BGM', '音乐'], en: ['music', 'soundtrack', 'background music', 'bgm']}, + 'beat-snap': {zh: ['卡点', '踩点', '节拍'], en: ['beat sync', 'beat', 'rhythm']}, + 'voice-recording': {zh: ['配音', '录音', '旁白', '解说'], en: ['voice-over', 'voiceover', 'dub', 'narrate', 'record']}, + 'narration': {zh: ['配音', '朗读', '文字转语音', '说话'], en: ['text to speech', 'tts', 'dub', 'speech']}, + 'sound-to-picture': {zh: ['对口型', '口型', '音频生视频', '数字人'], en: ['lip sync', 'lipsync', 'audio to video', 'talking head']}, + 'text-subtitles': {zh: ['字幕', '标题', '文字'], en: ['subtitles', 'captions', 'srt', 'title']}, + 'autopilot': {zh: ['自动', '一键成片', '助手', '智能体'], en: ['auto', 'one click', 'assistant', 'agent']}, + 'drama-outline': {zh: ['短剧', '剧本', '大纲'], en: ['short drama', 'script', 'outline']}, + 'film-project': {zh: ['成片', '短剧剪辑'], en: ['finished film', 'drama edit']}, + 'library-reuse': {zh: ['同款', '复用', '再生成一次'], en: ['reuse', 'same settings', 'remix']}, + 'library-export': {zh: ['导出', '下载', '保存视频', '收藏'], en: ['export', 'download', 'save video', 'favorites']}, + 'system-status': {zh: ['显存', '内存', '状态', '占用'], en: ['vram', 'memory', 'gpu', 'status']}, + 'launcher-close': {zh: ['后台', '退出', '关闭'], en: ['background', 'quit', 'exit']}, + 'troubleshoot': {zh: ['报错', '出错', '失败', '问题', '诊断报告'], en: ['error', 'failed', 'problem', 'diagnostic report']}, + 'offline-reimport': {zh: ['离线包', '修复模型', '模型损坏', '重新导入'], en: ['offline package', 'repair models', 'broken model', 'reimport']}, +}; diff --git a/web/ui_speed.js b/web/ui_speed.js index c151a52a..eaeb4afe 100644 --- a/web/ui_speed.js +++ b/web/ui_speed.js @@ -26,7 +26,9 @@ export function watchSpeed({now = () => performance.now(), notify, settle = SETT let measuring = false, done = false, frame = 0, wake = 0, away = false; const show = notify || (async () => { const [{toast}, {openSetup}] = await Promise.all([import('./notifications.js'), import('./setup.js')]); - toast(t('Interface is slow. Try Compatibility view.', '界面较卡,可在设置中开启兼容界面'), {tone: 'caution', + // Said once in the page's life, so it also stays in the notification list until closed there. + toast(t('Interface is slow. Try Compatibility view.', '界面较卡,可在设置中开启兼容界面'), {tone: 'caution', keep: {id: 'ui-speed:slow', setup: 'appearance', + title: t('Interface is slow', '界面较卡'), sub: t('Turn on Compatibility view', '开启兼容视图')}, action: {label: t('Open settings', '打开设置'), run: () => openSetup({section: 'appearance'})}}); }); const measure = () => { diff --git a/web/upscale_offer.js b/web/upscale_offer.js index e57f3f5a..961ab760 100644 --- a/web/upscale_offer.js +++ b/web/upscale_offer.js @@ -66,3 +66,18 @@ export function createUpscaleOffer(read) { const forget = () => answers.clear(); return {prepare, offer, forget}; } + +// The upscale rows of one finished video, the same wherever they are offered (the library's right-click menu, the +// result's "⋯"): one 1.5× step where this computer can make it (`offer`, from createUpscaleOffer), then the 4K size. +// A row whose condition is not met is left out, never shown disabled. +export const UPSCALE_USE = ['Make a larger copy as a new creation', '生成一个更大的新作品,原作品不变']; +export const UPSCALE_QUEUED = ['Queued. It appears in "Creations" when done.', '已加入队列,完成后在“作品”里。']; +export const UPSCALE_FAILED = ['Could not start upscaling: ', '无法开始放大:']; +export function upscaleChoices(row, offer) { + return [['upscale', offer?.offer(row), {}], ['upscale-4k', upscale4kOffer(row), {to: '4k'}]] + .filter(([, larger]) => larger) + .map(([id, larger, options]) => { + const size = `${larger.width} × ${larger.height}`; + return {id, width: larger.width, height: larger.height, options, label: [`Upscale to ${size}`, `放大到 ${size}`]}; + }); +}