Skip to content

Make videos on the computer you already own. FreeVideo runs MiniMax H3 in as little as 8 GB of VRAM and 16 GB of RAM, and adapts its acceleration path to your hardware.

Warn when other programs worsen generation memory placement

Bowen Xue34a8f1cf32e1
diff --git a/freevideo_engine/agent/comfy.py b/freevideo_engine/agent/comfy.py
index d9afb86..b27f631 100644
--- a/freevideo_engine/agent/comfy.py
+++ b/freevideo_engine/agent/comfy.py
@@ -354,7 +354,8 @@ class ComfyPort:
code = getattr(error, 'code', str(error))
code = code if code in IMAGE_ERRORS else 'invalid_request'
raise JobError(code, IMAGE_ERRORS[code], retryable=code in IMAGE_WAIT_ERRORS,
- kind='image', report_id=getattr(error, 'report_id', None)) from None
+ kind='image', report_id=getattr(error, 'report_id', None),
+ other_usage=getattr(error, 'status', {}).get('other_usage')) from None
def image_status(self, key):
return self.image.status(key)
diff --git a/freevideo_engine/agent/errors.py b/freevideo_engine/agent/errors.py
index 97d362e..6c03fe6 100644
--- a/freevideo_engine/agent/errors.py
+++ b/freevideo_engine/agent/errors.py
@@ -12,6 +12,7 @@ from ..image_gen.loras import ERRORS as LORA_ERRORS, MESSAGE_EN as LORA_MESSAGE_
REQUEST_ID = ContextVar('agent_request_id', default=None)
# The work session a token request belongs to (sessions.py); jobs and productions record it.
SESSION = ContextVar('agent_session', default=None)
+_UNREAD_USAGE = object()
# The operation digest a confirmation approves: method, route, path values and body without ref.
CONFIRM = ContextVar('agent_confirm', default=None)
# code: HTTP status, retryable, public message, concrete recovery action
@@ -128,6 +129,8 @@ ERRORS.update({
# Static bilingual image reasons; backend exception strings never enter the API.
IMAGE_REASONS = {
+ 'small_memory': ('This Mac has less than 16 GB of memory and cannot generate pictures.',
+ '这台 Mac 的内存不足 16 GB,无法生成图片。'),
'no_memory': ('Not enough GPU memory, even at the smallest size. Close other apps using the GPU, then try again.',
'显存不够,最小尺寸也没能生成。关掉其他占用显卡的程序后再试。'),
'busy_video': ('A video is generating. Try again when it finishes.', '视频正在生成,完成后再试。'),
@@ -164,6 +167,7 @@ def image_failure(code, report_id=None):
# Recovery is a function of the committed task and phase, not just an error code.
IMAGE_ERRORS = {
**LORA_MESSAGE_EN,
+ 'small_memory': IMAGE_REASONS['small_memory'][0],
'invalid_request': 'The picture request contains invalid fields.',
'invalid_prompt': 'The picture prompt must contain text and be at most 2000 characters.',
'invalid_dimensions': 'Picture width and height must be integers from 256 to 2048.',
@@ -413,7 +417,26 @@ def failure_reason_en(error):
def reasons(error):
- return dict(error_zh=failure_reason(error), error_en=failure_reason_en(error))
+ from ..other_usage import fact, join
+ result = dict(error_zh=failure_reason(error), error_en=failure_reason_en(error))
+ for key, zh in (('error_zh', True), ('error_en', False)):
+ suffix = fact(error.get('other_usage'), zh=zh)
+ if suffix and suffix not in result[key]:
+ result[key] = join(result[key], suffix, zh=zh)
+ return result
+
+
+def capture_other_usage(error):
+ from ..other_usage import at_failure, fact, join, MEMORY_ERRORS
+ if error and error.get('code') in MEMORY_ERRORS and 'other_usage' not in error:
+ error = dict(error, other_usage=at_failure(error['code']))
+ if error and error.get('other_usage') and error.get('reason'):
+ error = dict(error, reason=dict(error['reason']))
+ for lang in ('en', 'zh'):
+ suffix = fact(error['other_usage'], zh=lang == 'zh')
+ if suffix and suffix not in error['reason'].get(lang, ''):
+ error['reason'][lang] = join(error['reason'].get(lang, ''), suffix, zh=lang == 'zh')
+ return error
def with_reason(error):
@@ -422,7 +445,7 @@ def with_reason(error):
def build(code, *, details=None, request=None, validation=False, message=None, next_action=None,
action_required=True, retry_after_seconds=None, owner=None, kind=None, stage='request', resumable=True,
- report_id=None, memory=None):
+ report_id=None, memory=None, other_usage=_UNREAD_USAGE):
code = code if code in ERRORS else 'internal_error'
_, retryable, default_message, _ = ERRORS[code]
action = recovery(code, kind=kind, stage=stage, resumable=resumable)
@@ -438,6 +461,9 @@ def build(code, *, details=None, request=None, validation=False, message=None, n
result.update(image_failure(code, report_id))
if code == 'no_memory' and memory == 'host':
result['memory'] = 'host'
+ if other_usage is not _UNREAD_USAGE:
+ result['other_usage'] = other_usage
+ result = capture_other_usage(result)
if action_required:
result['next'] = next_action if validation and next_action else action
if code == 'busy':
diff --git a/freevideo_engine/agent/jobs.py b/freevideo_engine/agent/jobs.py
index 51648bb..9cd7488 100644
--- a/freevideo_engine/agent/jobs.py
+++ b/freevideo_engine/agent/jobs.py
@@ -88,7 +88,8 @@ class JobError(Exception):
return errors.build(self.code, details=self.details.get('details'),
owner=self.details.get('owner'),
retry_after_seconds=self.details.get('retry_after_seconds'),
- kind=self.details.get('kind'), report_id=self.details.get('report_id'))
+ kind=self.details.get('kind'), report_id=self.details.get('report_id'),
+ **({'other_usage': self.details['other_usage']} if 'other_usage' in self.details else {}))
class ManagedByProduction(JobError):
@@ -681,16 +682,19 @@ class Jobs:
def finish(self, row, status, *, result=None, error=None, save=True):
if error is not None:
+ error = errors.capture_other_usage(error)
code = error.get('code', 'internal_error')
report_id = error.get('report_id')
if code == 'invalid_json' and row['kind'] in ('vlm', 'enhance'):
code = 'vlm_invalid_json'
- reason_zh, reason_en = errors.failure_reason(dict(error, code=code)), errors.failure_reason_en(dict(error, code=code))
+ failure_reasons = errors.reasons(dict(error, code=code))
+ reason_zh, reason_en = failure_reasons['error_zh'], failure_reasons['error_en']
if code != error.get('code') or not error.get('request_id') or row['kind'] == 'image':
error = errors.build(code, details=error.get('details'),
request=row.get('request_id'), action_required=code != 'cancelled',
kind=row['kind'], stage='terminal', resumable=not row['spec'].get('refine_from'),
- report_id=error.get('report_id'), memory=error.get('memory'))
+ report_id=error.get('report_id'), memory=error.get('memory'),
+ other_usage=error.get('other_usage'))
if row['kind'] == 'image':
reason_zh, reason_en = error['error_zh'], error['error_en']
if error is not None:
@@ -1235,7 +1239,8 @@ class Jobs:
if row['kind'] == 'image':
result['error'] = errors.build(result['error']['code'], kind='image', stage='terminal',
details=result['error'].get('details'), request=row.get('request_id'),
- action_required=result['error']['code'] != 'cancelled', report_id=row['error'].get('report_id'))
+ action_required=result['error']['code'] != 'cancelled', report_id=row['error'].get('report_id'),
+ other_usage=row['error'].get('other_usage'))
else:
result['error'] = dict(result['error'], **errors.reasons(row['error']))
report_id = row['error'].get('report_id')
@@ -2098,7 +2103,8 @@ class Jobs:
code = failure.get('code') if isinstance(failure, dict) else failure
code = code or 'generation_failed'
if not self.wait_image(row, code):
- self.finish(row, 'failed', error=dict(code=code, report_id=state.get('report_id'), memory=state.get('memory')))
+ self.finish(row, 'failed', error=dict(code=code, report_id=state.get('report_id'), memory=state.get('memory'),
+ other_usage=state.get('other_usage')))
# Local VLM -----------------------------------------------------------------------------------------
def start_vlm(self, row):
diff --git a/freevideo_engine/agent/schema.py b/freevideo_engine/agent/schema.py
index 57fa1ab..905a4d0 100644
--- a/freevideo_engine/agent/schema.py
+++ b/freevideo_engine/agent/schema.py
@@ -1538,6 +1538,9 @@ def openapi():
'description': 'Image diagnostic report ID, or null when no report exists.'},
request_id=string(), docs=string(), retry_after_seconds=number(0), card={'type': 'object'}, job=JOB,
project={'type': 'object'}, current_revision=number(1, integer=True),
+ other_usage=nullable(obj(dict(vram_gib=number(0), ram_gib=number(0),
+ kinds={'type': 'array', 'items': enum(('gpu', 'ram'))}, signature=string()),
+ ('vram_gib', 'ram_gib', 'kinds', 'signature'))),
error_zh=string(), error_en=string()),
('code', 'message', 'details', 'retryable', 'request_id', 'docs'))}))
diff --git a/freevideo_engine/comfy_capabilities.py b/freevideo_engine/comfy_capabilities.py
index 4ad9c07..677c7b1 100644
--- a/freevideo_engine/comfy_capabilities.py
+++ b/freevideo_engine/comfy_capabilities.py
@@ -27,7 +27,7 @@ def _hash(value):
ensure_ascii=False, allow_nan=False).encode()).hexdigest()[:12]
-def _context(output_directory):
+def _machine_context():
from .background_compile import compile_owed
from .comfy_bridge import installation
root, machine = installation()
@@ -52,6 +52,12 @@ def _context(output_directory):
machine['hardware'] = observed
# Receipt read only: tells the page the first run still compiles.
machine['compile_owed'] = compile_owed(root)
+ return machine
+
+
+def _context(output_directory):
+ machine = _machine_context()
+ device = machine.get('device_identity') if machine.get('device_backend') == 'mps' else machine.get('gpu_uuid')
# Do not inherit the sampling-estimate route's 15-second history cache:
# reopening the grid after a generation must notice the new timing record.
rows = local_records(output_directory, device, system=machine.get('system'), stage_details=True, refresh=True)
@@ -270,6 +276,56 @@ def _query(query):
return aspect, size, task, query.get('adapters') == '1', normalize_references(task, references)
+def _usage_query(query):
+ """Same canvas/material fields as capabilities, plus this request's duration/profile."""
+ from .geometry import geometry
+ from .tiers import TIERS, STEP_CACHES
+ kind = query.get('kind', 'video')
+ if kind not in ('video', 'image'):
+ raise ValueError('Unsupported generation kind.')
+ if kind == 'image':
+ width, height = int(query.get('width', 1024)), int(query.get('height', 1024))
+ if not 256 <= width <= 2048 or not 256 <= height <= 2048:
+ raise ValueError('Use image dimensions from 256 to 2048.')
+ count = int(query.get('image_references', '0'))
+ if not 0 <= count <= 4:
+ raise ValueError('Use at most four image references.')
+ # Image preflight normalizes each reference to 1024**2 pixels.
+ return dict(kind=kind, width=width, height=height, reference_pixels=count * 1024**2)
+ _, size, task, _, references = _query(query)
+ width, height = size or (1344, 768)
+ tier = query.get('tier', 'light')
+ if tier not in (*TIERS, 'custom'):
+ raise ValueError('Unsupported tier.')
+ defaults = TIERS.get(tier, TIERS['light'])
+ flag = query.get('two_pass', '1' if defaults['two_pass'] else '0')
+ if flag not in ('0', '1'):
+ raise ValueError('Use a boolean two_pass flag.')
+ steps, refine = int(query.get('base_steps', defaults['steps'])), int(query.get('refine_steps', 3))
+ cache = query.get('step_cache', defaults['step_cache'])
+ cache = None if cache in (None, 'none', '') else cache
+ upscale = float(query.get('upscale_factor', defaults['upscale']))
+ if not 1 <= steps <= 32 or not 0 <= refine <= 31 or cache not in STEP_CACHES or upscale not in (1.2, 1.5, 2):
+ raise ValueError('Unsupported sampling profile.')
+ if 'frames' in query and 'seconds' in query:
+ raise ValueError('Specify frames or seconds, not both.')
+ shape = geometry(width, height, frames=int(query['frames'])) if 'frames' in query else geometry(
+ width, height, seconds=float(query.get('seconds', 10.125)))
+ return dict(kind=kind, width=width, height=height, frames=shape['frames'], steps=steps,
+ two_pass=flag == '1', task=task, refine=refine, references=reference_parameters(references),
+ step_cache=cache, upscale=upscale)
+
+
+def _other_usage(params, failure=False):
+ from . import other_usage
+ try:
+ machine = _machine_context()
+ usage = other_usage.read(machine)
+ return other_usage.notice(other_usage.net(usage, machine)) if failure else other_usage.for_request(machine, usage, **params)
+ except Exception:
+ return None
+
+
def register():
from aiohttp import web
import folder_paths
@@ -281,6 +337,17 @@ def register():
cache = None if mac else CapabilityCache(folder_paths.get_output_directory(), server)
server._freevideo_capabilities = cache if cache is not None else True
+ @server.routes.get('/freevideo/other-usage')
+ async def other_usage(request):
+ result = None
+ if not mac:
+ try:
+ params = _usage_query(request.query)
+ except (ValueError, TypeError, OverflowError, RecursionError) as error:
+ raise web.HTTPBadRequest(text=str(error)) from error
+ result = await asyncio.to_thread(_other_usage, params, request.query.get('failure') == '1')
+ return web.json_response(dict(status='ok', notice=result), headers={'Cache-Control': 'no-store'})
+
@server.routes.get('/freevideo/capabilities')
async def capabilities(request):
if mac:
diff --git a/freevideo_engine/image_gen/failure.py b/freevideo_engine/image_gen/failure.py
index 0882327..35c23c2 100644
--- a/freevideo_engine/image_gen/failure.py
+++ b/freevideo_engine/image_gen/failure.py
@@ -66,6 +66,15 @@ def host_memory_shortage(error):
return commit_exhausted(error)
+def append_other_usage(result, machine):
+ from ..other_usage import at_failure, fact, join
+ value = at_failure(result.get('error'), machine)
+ result['other_usage'] = value
+ if value and result.get('message_zh'):
+ result['message_zh'] = join(result['message_zh'], fact(value, zh=True), zh=True)
+ return result
+
+
class FailureError(ValueError):
"""Admission rejection with the same safe status as the HTTP reply."""
def __init__(self, status):
diff --git a/freevideo_engine/image_gen/service.py b/freevideo_engine/image_gen/service.py
index 36d1cd2..7014276 100644
--- a/freevideo_engine/image_gen/service.py
+++ b/freevideo_engine/image_gen/service.py
@@ -763,6 +763,9 @@ class Service:
if code == 'no_memory' and (isinstance(row, dict) and row.get('memory') == 'host'
or error is not None and host_memory_shortage(error)):
result.update(memory='host', message_zh=HOST_MESSAGE_ZH)
+ if code in ('no_memory', 'small_memory'):
+ from .failure import append_other_usage
+ append_other_usage(result, context.machine)
if code not in NO_REPORT:
if video_busy is None:
try:
@@ -1287,7 +1290,7 @@ def register():
raise ValueError('invalid_request')
result = await asyncio.to_thread(service.history_open)
else:
- result = service.start(name, value)
+ result = await asyncio.to_thread(service.start, name, value)
return web.json_response(result)
except FailureError as error:
return web.json_response(error.status, status=400)
diff --git a/freevideo_engine/other_usage.py b/freevideo_engine/other_usage.py
new file mode 100644
index 0000000..ca39cae
--- /dev/null
+++ b/freevideo_engine/other_usage.py
@@ -0,0 +1,238 @@
+"""Best-effort, anonymous occupancy and its effect on this request's placement.
+
+No process names, model loads or CUDA initialization. Call readings off the
+event loop; an incomplete reading never becomes a claim about other programs.
+"""
+import os
+import platform
+import sys
+
+from .background_room import Gpu, available_memory, family
+from .capabilities import IDLE_IN_USE, _admit, _machine
+from .hardware import GiB
+from .system import system_memory
+
+THRESHOLD = GiB
+CONTEXT_BYTES = GiB // 2
+# What the system and desktop use with no other program running. Readings are
+# whole-machine use minus this program's own, so they include it; only the part
+# above it counts as other programs. Host memory gets a generous allowance so
+# the notice stays quiet unless something else is clearly running.
+SYSTEM_RAM = {'Windows': 6 * GiB, 'Linux': 2 * GiB}
+MEMORY_ERRORS = frozenset(('no_memory', 'small_memory', 'insufficient_memory',
+ 'out_of_memory', 'ram_space'))
+
+
+def _mac(machine):
+ return (platform.system() == 'Darwin' or machine.get('device_backend') == 'mps'
+ or (machine.get('device_identity') or {}).get('backend') == 'mps'
+ or (machine.get('hardware') or {}).get('system') == 'Darwin')
+
+
+def _running():
+ """Unknown activity is unsafe for the WDDM allocator approximation."""
+ from .resident_process import OWNER
+ from .background_compile import COMPILE
+ if OWNER.active or COMPILE.process is not None and COMPILE.process.poll() is None:
+ return True
+ module = sys.modules.get('server')
+ server = module.PromptServer.instance if module is not None else None
+ if server is not None:
+ service = getattr(server, '_freevideo_image_gen', None)
+ if service is not None and service.busy():
+ return True
+ queue = getattr(server, 'prompt_queue', None)
+ if queue is not None and queue.get_current_queue()[0]:
+ return True
+ return False
+
+
+def _allocator_credit(pids):
+ """WDDM has no per-process bytes. Only trust idle, already loaded allocators.
+
+ A child with a persistent pool cannot be accounted for by the parent's
+ torch allocator. Suppress the approximation while such a worker lives.
+ """
+ if _running():
+ return None
+ from .resident_process import OWNER
+ module = sys.modules.get('server')
+ server = module.PromptServer.instance if module is not None else None
+ service = getattr(server, '_freevideo_image_gen', None)
+ for process in (OWNER.process, getattr(service, 'process', None)):
+ if process is not None and process.poll() is None:
+ return None
+ torch = sys.modules.get('torch')
+ if torch is None or not torch.cuda.is_initialized():
+ return None
+ return int(torch.cuda.memory_reserved()) + CONTEXT_BYTES
+
+
+def _rss(pids):
+ import psutil
+ total = 0
+ for pid in pids:
+ try:
+ total += psutil.Process(pid).memory_info().rss
+ except psutil.NoSuchProcess:
+ continue # A child that exited holds no memory now.
+ return total
+
+
+def read(machine=None):
+ """{'vram': bytes, 'ram': bytes}, or None if either cannot be established."""
+ gpu = None
+ try:
+ if platform.system() == 'Darwin':
+ return None
+ if machine is None:
+ from .comfy_bridge import installation
+ _, machine = installation()
+ if (_mac(machine) or machine.get('device_backend', 'cuda') != 'cuda'
+ or machine.get('gpu_uuid') is None):
+ return None
+ pids = family(os.getpid())
+ gpu = Gpu(machine.get('gpu_uuid'))
+ memory = gpu.memory()
+ if memory is None:
+ return None
+ used, total = memory
+ if not total or not 0 <= used <= total:
+ return None
+ rows = gpu.processes()
+ if rows is None or any(size is None for size in rows.values()):
+ if platform.system() != 'Windows':
+ return None
+ own = _allocator_credit(pids)
+ if own is None:
+ return None
+ else:
+ own = sum(size for pid, size in rows.items() if pid in pids)
+ host_total, available = system_memory()['total_bytes'], available_memory()
+ if host_total <= 0 or not 0 <= available <= host_total:
+ return None
+ return dict(vram=max(0, used - own), ram=max(0, host_total - available - _rss(pids)))
+ except Exception:
+ return None
+ finally:
+ if gpu is not None:
+ try:
+ gpu.close()
+ except Exception:
+ pass
+
+
+def net(usage, machine):
+ """The reading above what the system and desktop use by themselves."""
+ if not isinstance(usage, dict) or not isinstance(machine, dict):
+ return None
+ hardware = machine.get('hardware') or {}
+ system = hardware.get('system') or machine.get('system')
+ if system not in SYSTEM_RAM or any(type(usage.get(k)) is not int or usage[k] < 0 for k in ('vram', 'ram')):
+ return None
+ return dict(vram=max(0, usage['vram'] - IDLE_IN_USE[system]['vram']),
+ ram=max(0, usage['ram'] - SYSTEM_RAM[system]))
+
+
+def notice(usage):
+ """Only anonymous numbers cross the UI boundary; sub-GiB noise stays quiet."""
+ if not isinstance(usage, dict) or any(type(usage.get(k)) is not int or usage[k] < 0
+ for k in ('vram', 'ram')):
+ return None
+ kinds = [kind for key, kind in (('vram', 'gpu'), ('ram', 'ram')) if usage[key] >= THRESHOLD]
+ if not kinds:
+ return None
+ return dict(vram_gib=usage['vram'] / GiB, ram_gib=usage['ram'] / GiB,
+ kinds=kinds, signature='%d:%d' % (usage['vram'] // GiB, usage['ram'] // GiB))
+
+
+def _worse(current, idle):
+ request, code, _ = current
+ baseline, base_code, _ = idle
+ if baseline is None:
+ return False # Closing other programs cannot admit this request either.
+ if request is None:
+ return False # A refused request is reported by the failure card, not as slower.
+ return (code > base_code
+ or any(request[key] < baseline[key] for key in (
+ 'pass1_resident_blocks', 'pass2_resident_blocks', 'decoder_resident_blocks'))
+ or request['decoder_offload'] != baseline['decoder_offload'])
+
+
+def placements(machine, usage, *, kind='video', width=1344, height=768, frames=243,
+ steps=8, two_pass=True, task='t2va', refine=3, references=None,
+ step_cache=None, upscale=2, reference_pixels=0):
+ """Identical request and reserves, with and without the measured other usage."""
+ idle = _machine(machine)
+ usage = net(usage, machine)
+ if idle is None or idle['mac'] or _mac(machine) or notice(usage) is None:
+ return None
+ current = dict(idle, vram_free=max(0, idle['vram_free'] - usage['vram']),
+ ram_available=max(0, idle['ram_available'] - usage['ram']))
+ if kind == 'image':
+ from .image_gen.image_policy import plan_image
+ def plan(value):
+ return plan_image(gpu_budget_bytes=value['vram_free'], host_available_bytes=value['ram_available'],
+ width=width, height=height, reference_pixels=reference_pixels).to_dict()
+ base, occupied = plan(idle), plan(current)
+ worse = base['feasible'] and occupied['feasible'] and (any(
+ occupied[key] < base[key] for key in ('dit_resident_layers', 'te_resident_layers',
+ 'dit_kept_layers', 'vae_tile_size'))
+ or occupied['vae_tiling'] != base['vae_tiling']
+ or occupied['host_mode'] != base['host_mode'])
+ else:
+ params = dict(width=width, height=height, frames=frames, steps=steps, two_pass=two_pass,
+ task=task, refine=refine, references=references, step_cache=step_cache, upscale=upscale)
+ base, occupied = _admit(idle, **params), _admit(current, **params)
+ worse = _worse(occupied, base)
+ return dict(idle=base, occupied=occupied, worse=bool(worse))
+
+
+def for_request(machine, usage, **request):
+ try:
+ comparison = placements(machine, usage, **request)
+ return notice(net(usage, machine)) if comparison and comparison['worse'] else None
+ except Exception:
+ return None
+
+
+def at_failure(code, machine=None):
+ """Fresh reading at failure, independent of session deduplication/admission."""
+ if code not in MEMORY_ERRORS:
+ return None
+ try:
+ if machine is None:
+ from .comfy_bridge import installation
+ _, machine = installation()
+ return notice(net(read(machine), machine))
+ except Exception:
+ return None
+
+
+FACTS = {
+ 'gpu': ('Other programs are using {vram_gib} GB of GPU memory.', '其他程序占用了 {vram_gib} GB 显存。'),
+ 'ram': ('Other programs are using {ram_gib} GB of RAM.', '其他程序占用了 {ram_gib} GB 内存。'),
+ 'both': ('Other programs are using {vram_gib} GB of GPU memory and {ram_gib} GB of RAM.',
+ '其他程序占用了 {vram_gib} GB 显存和 {ram_gib} GB 内存。'),
+}
+
+
+def join(text, suffix, zh=False):
+ """Append the fact as its own sentence: no space in Chinese, one in English."""
+ text = (text or '').rstrip()
+ if not text:
+ return suffix
+ if text[-1] not in ('。!?' if zh else '.!?'):
+ text += '。' if zh else '.'
+ return text + suffix if zh else text + ' ' + suffix
+
+
+def fact(value, zh=False):
+ if not isinstance(value, dict):
+ return ''
+ kinds = value.get('kinds')
+ key = 'both' if kinds == ['gpu', 'ram'] else 'gpu' if kinds == ['gpu'] else 'ram' if kinds == ['ram'] else None
+ try:
+ return FACTS[key][int(zh)].format(**{k: format(value[k], '.1f') for k in ('vram_gib', 'ram_gib')}) if key else ''
+ except (KeyError, TypeError, ValueError):
+ return ''
diff --git a/web/cast_generate.css b/web/cast_generate.css
index 2dac44d..65fc980 100644
--- a/web/cast_generate.css
+++ b/web/cast_generate.css
@@ -13,6 +13,7 @@
.fv-cg-text:read-only{opacity:.7}
.fv-cg-text::placeholder{color:var(--fv-muted,#7d8794)}
.fv-cg-note{grid-column:1/-1;font-size:12px;line-height:1.6;color:var(--fv-muted,#aaaeb9)}
+.fv-cg-side>.fv-other-usage{color:var(--fv-muted,#aaaeb9);line-height:1.6}
/* A failure is the reason on one line, then the report button left and the retry right on the next. */
.fv-cg-note[data-failed=true],.fv-cg-note[data-failed=true] .fv-result-links,.fv-cg-note[data-failed=true] .fv-actions{display:contents}
.fv-cg-note .fv-image-failure-reason{grid-column:1/-1}
diff --git a/web/cast_generate.js b/web/cast_generate.js
index 07238c7..ecb0fd4 100644
--- a/web/cast_generate.js
+++ b/web/cast_generate.js
@@ -5,6 +5,7 @@
import {createImageGenClient, imageGenProgress, imagePackUnavailableMessage, renderImageFailure,
IMAGE_GEN_POLL_MS, IMAGE_GEN_INFO_POLL_MS} from './image_generation.js';
import {createImageLoras} from './image_lora.js';
+import {createOtherUsageNotice} from './other_usage.js';
export {imageGenerationSupported as castGenerateSupported} from './image_generation.js';
@@ -18,11 +19,11 @@ const VIEW_TITLES = Object.freeze({
function el(tag, cls, text) { const e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; }
const failureOf = error => ({error: error?.code || 'generation_failed', report_id: error?.report_id || null,
- stage: error?.stage || '', fitted: error?.fitted || null, memory: error?.memory || ''});
+ stage: error?.stage || '', fitted: error?.fitted || null, memory: error?.memory || '', other_usage: error?.other_usage || null});
const randomSeed = () => crypto.getRandomValues(new Uint32Array(1))[0] >>> 1;
// The five pictures of one description. No DOM: the page below draws its state.
-export function createCastGenerator({client, kind = 'character', onChange = () => {}, schedule = setTimeout, unschedule = clearTimeout}) {
+export function createCastGenerator({client, kind = 'character', onChange = () => {}, beforeGenerate = async () => {}, schedule = setTimeout, unschedule = clearTimeout}) {
const scene = kind === 'setting', names = scene ? SCENE_CANDIDATES : CAST_VIEWS;
const fresh = () => names.map(view => ({view, file: '', fraction: 0}));
let state = {pictures: fresh(), running: false, current: -1, error: '', report_id: null, waiting: '', description: ''};
@@ -34,6 +35,8 @@ export function createCastGenerator({client, kind = 'character', onChange = () =
async function runOne(index, alive) {
const view = plan[index], front = state.pictures[0].file;
+ await beforeGenerate({kind: 'image', width: view.width, height: view.height, image_references: view.from_front ? 1 : 0});
+ if (!alive()) return null;
const row = await client.generate({prompt: view.prompt, width: view.width, height: view.height, seed: scene ? seed + index : seed,
images: view.from_front ? [front] : [], ...(view.view === 'back' ? {cast_view: 'back'} : {}),
...(loras === undefined ? {} : {loras})});
@@ -47,7 +50,7 @@ export function createCastGenerator({client, kind = 'character', onChange = () =
if (!alive()) return null;
if (status.state === 'error') {
throw Object.assign(new Error(status.error), {code: status.error, report_id: status.report_id,
- stage: status.stage, fitted: status.fitted, memory: status.memory});
+ stage: status.stage, fitted: status.fitted, memory: status.memory, other_usage: status.other_usage});
}
if (status.state === 'done') {
if (!status.file) throw new Error('generation_failed');
@@ -168,7 +171,8 @@ export function mountCastGenerate({container, api, text, t = text, viewURL, onSt
container.append(root);
let chosen = 0, picked = '', info = null, infoTimer = null, disposed = false, failureKey = null, attention = null;
- const generator = createCastGenerator({client, kind, onChange: render});
+ const otherUsage = createOtherUsageNotice(side, tr, fetcher);
+ const generator = createCastGenerator({client, kind, onChange: render, beforeGenerate: query => otherUsage.check(query)});
let last = '';
function missing() { return info && !info.installed && !info.ready; }
@@ -262,7 +266,7 @@ export function mountCastGenerate({container, api, text, t = text, viewURL, onSt
: generator.state().pictures.map(row => ({file: row.file, label: row.view})),
isBusy: () => generator.state().running,
cancel: () => generator.stop(),
- destroy() { disposed = true; picker?.dispose(); clearTimeout(infoTimer); void generator.dispose(); root.remove(); },
+ destroy() { disposed = true; picker?.dispose(); clearTimeout(infoTimer); otherUsage.dispose(); void generator.dispose(); root.remove(); },
element: root,
};
}
diff --git a/web/error_panel.js b/web/error_panel.js
index 7910e1f..e05c0ba 100644
--- a/web/error_panel.js
+++ b/web/error_panel.js
@@ -1,4 +1,5 @@
// Shared by the Studio and graph view. Text only; never render exception HTML.
+import {readOtherUsage, otherUsageText} from './other_usage.js';
import {repairAction} from './repair_hint.js';
import {detectBrowserExtension, browserExtensionAdvice, extensionSteps, isNetworkTypeError, connectionLostText} from './browser_extension.js';
import {SAMPLING_EFFORTS, STEP_CACHES, UPSCALE_FACTORS, tableLevel} from './sampling_effort.js';
@@ -632,10 +633,19 @@ export function createErrorPanel(t, route = null) {
}
};
disclosure.append(summary, detailLocation, detailCause, details, copyInside, privacyInside);
- head.append(title, actions); element.append(head, explanation, location, cause, action, disclosure, privacy, downloadStatus);
+ const occupancy = document.createElement('p'); occupancy.className = 'fv-muted fv-other-usage-failure'; occupancy.hidden = true;
+ head.append(title, actions); element.append(head, explanation, location, cause, action, occupancy, disclosure, privacy, downloadStatus);
return {element, show(value, popup = true, context = {}) {
const report = createErrorReport(value, context); currentReport = report;
const {advice, generated} = adviceFor(report, t, value);
+ occupancy.hidden = true; occupancy.textContent = '';
+ if (['vram', 'ram', 'commit', 'resources'].includes(advice.kind)) {
+ void readOtherUsage({failure: '1'}).then(notice => {
+ if (currentReport !== report) return;
+ occupancy.textContent = otherUsageText(notice, t, true);
+ occupancy.hidden = !occupancy.textContent;
+ });
+ }
title.textContent = advice.title; explanation.textContent = advice.summary; explanation.hidden = !advice.summary; action.textContent = advice.action;
element.querySelector('.fv-extension-steps')?.remove();
if (advice.kind === 'browser-extension') action.after(extensionSteps(advice));
diff --git a/web/image_editor.css b/web/image_editor.css
index 5207ca6..50b21fd 100644
--- a/web/image_editor.css
+++ b/web/image_editor.css
@@ -115,6 +115,7 @@ button.fv-ie-size:hover{background:var(--fv-hover);color:var(--fv-ink)}
.fv-ie-generation[data-failed=true]>.fv-ie-gen-note{grid-column:1/-1;grid-row:2;max-width:none}
.fv-ie-generation[data-failed=true]>.fv-ie-button{grid-row:1}
.fv-ie-gen-note>.fv-result-links{display:grid;gap:8px}
+.fv-ie-generation>.fv-other-usage{grid-column:1/-1;font-size:var(--fv-micro);color:var(--fv-muted);line-height:1.5}
.fv-ie-gen-note .fv-image-failure-reason{color:var(--fv-danger)}
.fv-ie-gen-note>.fv-result-links>.fv-actions{justify-content:flex-start}
/* Same accent ramp and easing as the shared generation progress meters. */
diff --git a/web/image_generation.js b/web/image_generation.js
index 2358116..e7a18ba 100644
--- a/web/image_generation.js
+++ b/web/image_generation.js
@@ -6,6 +6,7 @@ import {saveReport, reportIssue, showReportTip, focusReportTip} from './report_i
import {issueButton} from './issue_button.js';
import {about} from './request_assets.js';
import {createImageLoras} from './image_lora.js';
+import {createOtherUsageNotice, otherUsageText} from './other_usage.js';
export const IMAGE_GEN_PROTOCOL = Object.freeze({
root: '/freevideo/image-gen', header: 'X-FreeVideo-Image', upload: '/upload/image',
@@ -51,6 +52,7 @@ export function blankCanvasSize(ratio, sizes = null, tier = 'standard') {
const failure = (code, info = {}) => Object.assign(new Error(code || 'generation_failed'), {
code: code || 'generation_failed', report_id: info.report_id || null, stage: info.stage || '',
fitted: info.fitted || null, memory: info.memory || '',
+ other_usage: info.other_usage || null,
});
export function createImageGenClient(fetchImpl = globalThis.fetch.bind(globalThis)) {
@@ -181,7 +183,8 @@ export function imageGenError(code, info, t) {
small_memory: ['This Mac has less than 16 GB of memory and cannot generate pictures.',
'这台 Mac 的内存不足 16 GB,无法生成图片。'],
};
- const say = (en, zh) => t(...memoryWords([en, zh], info?.unified));
+ const fact = ['no_memory', 'small_memory'].includes(code) ? otherUsageText(info?.other_usage, t, true) : '';
+ const say = (en, zh) => t(...memoryWords([en, zh], info?.unified)) + (fact ? t(' ', '') + fact : '');
if (code === 'pack_missing') return imagePackUnavailableMessage(info, t);
if (code === 'no_memory' && info?.memory === 'host')
return t('Not enough virtual memory to load the image model. Close other apps, or increase virtual memory in system settings, then try again.',
@@ -221,7 +224,7 @@ export const REPORT_LABELS = Object.freeze({
// Shared by the editor and the other image entry points. Only the opaque report
// ID goes in the request; raw service messages are never shown in the page.
-export function renderImageFailure(host, {error, report_id, stage, fitted, info, memory} = {}, t,
+export function renderImageFailure(host, {error, report_id, stage, fitted, info, memory, other_usage} = {}, t,
{productVersion = () => null, fetchApi = globalThis.fetch.bind(globalThis)} = {}) {
host.replaceChildren();
if (!error || error === 'cancelled') return null;
@@ -232,7 +235,7 @@ export function renderImageFailure(host, {error, report_id, stage, fitted, info,
}
const card = doc.createElement('div'); card.className = 'fv-result-links';
const reason = doc.createElement('div'); reason.className = 'fv-image-failure-reason';
- reason.setAttribute('role', 'status'); reason.textContent = imageGenError(error, {stage, fitted, memory, unified: info?.unified_memory}, t);
+ reason.setAttribute('role', 'status'); reason.textContent = imageGenError(error, {stage, fitted, memory, unified: info?.unified_memory, other_usage}, t);
card.append(reason); host.append(card);
if (!report_id) return card;
const fetchReport = async () => {
@@ -411,6 +414,7 @@ export function imageGenProgress(stage, fraction, withImages = false) {
// An epoch rejects late uploads/status/results. A generate response arriving
// after Stop still has to be cancelled, even though its job was not known yet.
export function createImageGenSession({client, prepare, apply, onChange = () => {},
+ beforeGenerate = async () => {},
schedule = setTimeout, unschedule = clearTimeout, store = null,
visible = () => globalThis.document?.visibilityState !== 'hidden'}) {
let epoch = 0, timer = null, infoTimer = null, disposed = false, checking = null;
@@ -419,7 +423,7 @@ export function createImageGenSession({client, prepare, apply, onChange = () =>
const emit = patch => { state = {...state, ...patch}; if (!disposed) onChange(state); };
const failed = error => error.code === 'cancelled' ? {error: '', report_id: null, stage: '', memory: ''}
: {error: error.code || 'generation_failed', report_id: error.report_id || null, stage: error.stage || '',
- memory: error.memory || '', ...(error.fitted ? {fitted: error.fitted} : {})};
+ memory: error.memory || '', other_usage: error.other_usage || null, ...(error.fitted ? {fitted: error.fitted} : {})};
const cancelJob = job => Promise.resolve().then(() => client.cancel(job)).catch(() => {});
const forget = () => { try { store?.clear(); } catch { /* the job is only not resumed after a reload */ } };
function scheduleInfo() {
@@ -483,6 +487,8 @@ export function createImageGenSession({client, prepare, apply, onChange = () =>
if (!alive()) return;
if (state.stage === 'upload') emit({stage: ''});
const withImages = images.length > 0;
+ await beforeGenerate({kind: 'image', width: context.width, height: context.height, image_references: images.length});
+ if (!alive()) return;
const row = await client.generate({prompt: request.prompt, width: context.width, height: context.height, images, mask,
...(request.seed === undefined ? {} : {seed: request.seed}),
...(request.loras === undefined ? {} : {loras: request.loras})});
@@ -571,6 +577,7 @@ export function createImageGeneration({client, renderer, t, getDoc, getSelection
let store = null;
try { if (resumeKey != null && globalThis.sessionStorage) store = imageJobStore(resumeKey); } catch { /* no storage */ }
const session = createImageGenSession({client, store,
+ beforeGenerate: query => mounted?.otherUsage.check(query),
prepare: async (request, alive) => {
const context = generationContext(getDoc(), getSelection(), request.mode);
const images = request.mode === 'edit' ? [await uploadGenerationReference(renderer, client, context, alive),
@@ -872,6 +879,7 @@ export function createImageGeneration({client, renderer, t, getDoc, getSelection
bar.append(group);
if (shape) bar.append(shape);
bar.append(field, note, action, meter);
+ const otherUsage = createOtherUsageNotice(bar, t, fetchApi);
const grow = () => {
input.style.height = '0px';
input.style.height = (prompt.trim() ? Math.min(80, Math.max(32, input.scrollHeight + 2)) : 32) + 'px';
@@ -887,13 +895,13 @@ export function createImageGeneration({client, renderer, t, getDoc, getSelection
event.preventDefault(); void start();
}
};
- mounted = {bar, input, action, note, meter, fill, group, refs, ratio, size, grow};
+ mounted = {bar, input, action, note, meter, fill, group, refs, ratio, size, otherUsage, grow};
grow(); update();
}
- return {mount, drawsSelection: () => mode === 'edit' && getDoc().layers.length > 0, unmount() { clearAttention(); promptRequired = false; mounted = null; },
+ return {mount, drawsSelection: () => mode === 'edit' && getDoc().layers.length > 0, unmount() { clearAttention(); promptRequired = false; mounted?.otherUsage.dispose(); mounted = null; },
selected: () => session.check(), cancel: session.cancel,
// The blank canvas a reloaded generation was started on, to be set again by the editor.
resumedCanvas: resumed?.context?.mode === 'new'
? {width: resumed.context.doc.width, height: resumed.context.doc.height} : null,
- dispose() { clearAttention(); loras?.dispose(); return session.dispose(); }, state: session.state};
+ dispose() { clearAttention(); loras?.dispose(); mounted?.otherUsage.dispose(); return session.dispose(); }, state: session.state};
}
diff --git a/web/other_usage.js b/web/other_usage.js
new file mode 100644
index 0000000..ffa9404
--- /dev/null
+++ b/web/other_usage.js
@@ -0,0 +1,66 @@
+// All occupancy sentences shown by the page live here; numbers join GB with a no-break space.
+export const OTHER_USAGE_COPY = Object.freeze({
+ gpu: ['Other programs are using {vram_gib}\u00a0GB of GPU memory, so this generation will be slower. Closing them speeds up generation.',
+ '其他程序占用了 {vram_gib}\u00a0GB 显存,这次生成会变慢。关闭这些程序可加快生成。'],
+ ram: ['Other programs are using {ram_gib}\u00a0GB of RAM, so this generation will be slower. Closing them speeds up generation.',
+ '其他程序占用了 {ram_gib}\u00a0GB 内存,这次生成会变慢。关闭这些程序可加快生成。'],
+ both: ['Other programs are using {vram_gib}\u00a0GB of GPU memory and {ram_gib}\u00a0GB of RAM, so this generation will be slower. Closing them speeds up generation.',
+ '其他程序占用了 {vram_gib}\u00a0GB 显存和 {ram_gib}\u00a0GB 内存,这次生成会变慢。关闭这些程序可加快生成。'],
+ gpuFact: ['Other programs are using {vram_gib} GB of GPU memory.', '其他程序占用了 {vram_gib} GB 显存。'],
+ ramFact: ['Other programs are using {ram_gib} GB of RAM.', '其他程序占用了 {ram_gib} GB 内存。'],
+ bothFact: ['Other programs are using {vram_gib} GB of GPU memory and {ram_gib} GB of RAM.',
+ '其他程序占用了 {vram_gib} GB 显存和 {ram_gib} GB 内存。'],
+});
+export const OTHER_USAGE_STORAGE = 'freevideo.otherUsage.lastNotice';
+export function otherUsageText(notice, t, fact = false) {
+ if (!notice || !['vram_gib', 'ram_gib'].every(k => Number.isFinite(notice[k]) && notice[k] >= 0)) return '';
+ const gpu = notice.kinds?.includes('gpu'), ram = notice.kinds?.includes('ram');
+ if (!gpu && !ram) return '';
+ const key = (gpu && ram ? 'both' : gpu ? 'gpu' : 'ram') + (fact ? 'Fact' : '');
+ return t(...OTHER_USAGE_COPY[key]).replaceAll('{vram_gib}', notice.vram_gib.toFixed(1))
+ .replaceAll('{ram_gib}', notice.ram_gib.toFixed(1));
+}
+export function claimOtherUsage(notice, storage) {
+ try {
+ storage ??= globalThis.sessionStorage;
+ const previous = JSON.parse(storage.getItem(OTHER_USAGE_STORAGE) || 'null');
+ if (!notice?.signature || previous?.signature === notice.signature) return false;
+ // A floor-bucket boundary alone can be less than 1 GiB of actual change.
+ if (previous && Math.abs(previous.vram_gib - notice.vram_gib) < 1
+ && Math.abs(previous.ram_gib - notice.ram_gib) < 1) return false;
+ storage.setItem(OTHER_USAGE_STORAGE, JSON.stringify(notice));
+ return true;
+ } catch { return false; } // Cannot persist the once-only rule: stay quiet.
+}
+export async function readOtherUsage(query, fetchApi = globalThis.fetch.bind(globalThis)) {
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), 750);
+ try {
+ // Race also bounds adapters that ignore AbortSignal. No advisory can hold submission.
+ return await Promise.race([
+ (async () => {
+ const response = await fetchApi('/freevideo/other-usage?' + new URLSearchParams(query),
+ {cache: 'no-store', signal: controller.signal});
+ const value = response.ok ? await response.json() : null;
+ return value?.status === 'ok' ? value.notice : null;
+ })(),
+ new Promise(resolve => controller.signal.addEventListener('abort', () => resolve(null), {once: true})),
+ ]);
+ } catch { return null; }
+ finally { clearTimeout(timeout); }
+}
+export function createOtherUsageNotice(host, t, fetchApi) {
+ const element = (host.ownerDocument || document).createElement('div');
+ element.className = 'fv-muted fv-other-usage'; element.hidden = true; element.setAttribute('role', 'status');
+ host.append(element);
+ let revision = 0;
+ return {element, async check(query) {
+ const current = ++revision;
+ element.hidden = true; element.textContent = '';
+ if (!query) return;
+ const notice = await readOtherUsage(query, fetchApi);
+ if (current !== revision || !element.isConnected) return;
+ const text = otherUsageText(notice, t);
+ if (text && claimOtherUsage(notice)) { element.textContent = text; element.hidden = false; }
+ }, dispose() { revision++; element.remove?.(); }};
+}
diff --git a/web/studio.css b/web/studio.css
index ed8cf5f..648fd68 100644
--- a/web/studio.css
+++ b/web/studio.css
@@ -117,6 +117,7 @@
.fv-studio .fv-stats[data-count="3"]{grid-template-columns:repeat(3,minmax(0,1fr))}
.fv-studio .fv-result-links{animation:fv-panel-enter .35s ease;display:flex;align-items:center;justify-content:center;gap:9px;flex-wrap:wrap}
.fv-studio .fv-runbar{position:sticky;bottom:0;padding:16px 0 22px;background:linear-gradient(transparent,var(--fv-bg) 12%);z-index:2}
+.fv-studio .fv-runbar>.fv-other-usage{margin-bottom:8px}
.fv-studio .fv-runbar .fv-primary{width:100%;min-height:var(--fv-h-lg);font-size:14px}
.fv-studio .fv-runrow{display:flex;gap:6px;align-items:stretch}
.fv-studio .fv-runrow>.fv-primary{flex:1;min-width:0}
diff --git a/web/studio.js b/web/studio.js
index 0e0c136..fbf9283 100644
--- a/web/studio.js
+++ b/web/studio.js
@@ -38,7 +38,8 @@ import { requestText, shownRewrite } from './prompt_sections.js';
import { createRequestAssets, enabledLoras, referenceFiles } from './request_assets.js';
import { promptDraftTrouble, rememberPromptDraft, restorePromptDraft, savePromptDraft, trackPromptDraft, watchPromptDraftTrouble } from './prompt_draft.js';
import { canvasDimensions, imageSizeSelection } from './studio_size.js';
-import { createCapabilityView } from './capability_view.js';
+import { createCapabilityView, capabilityContext } from './capability_view.js';
+import { createOtherUsageNotice } from './other_usage.js';
import { openEditorView } from './editor_loader.js';
import { frameShapes, frameSize } from './frame_sizes.js';
import { createFirstRunGuide, createFirstStart } from './first_run_guide.js';
@@ -1678,6 +1679,8 @@ export function openStudio(node, {extendFrom = null} = {}) {
resumeChain.hidden = !['cancelled', 'failed', 'interrupted'].includes(chainController?.state?.state) || partList.resumes();
queueActions.hidden = !chainController?.active && !busy && !queueState?.looping && resumeChain.hidden;
};
+ const otherUsage = createOtherUsageNotice(runbar, t, api.fetchApi.bind(api));
+ cleanup.push(() => otherUsage.dispose());
runbar.append(requestAssets.element, runrow, queueActions); controls.append(runbar);
const queueError = error => ({
queue_unavailable: t('Could not read the queue. The loop has stopped; videos already added stay queued.', '暂时读不到队列,循环已停止;已加入的视频还在队列中。'),
@@ -1931,6 +1934,17 @@ export function openStudio(node, {extendFrom = null} = {}) {
if (lengthControl.absent && !seconds.reportValidity()) return;
if (lengthPlan?.count > 1 && chosenMode !== 'single') { status.textContent = t('Videos made in parts cannot use batch or loop.', '分段视频不能批量或循环生成。'); return; }
const lengthOptions = lengthControl.options();
+ const usageContext = capabilityContext(node, {custom: true});
+ const usageQuery = usageContext && !extension.source && !seconds.disabled ? new URLSearchParams(usageContext) : null;
+ // Missing material dimensions or linked settings cannot describe the same request reliably.
+ if (usageQuery && (!usageQuery.get('task').startsWith('ref2va') || usageQuery.has('references'))) {
+ for (const [key, val] of Object.entries({width: value(node, 'width'), height: value(node, 'height'),
+ seconds: lengthPlan?.partSeconds?.[0] ?? Number(seconds.value), base_steps: baseSteps.value,
+ refine_steps: refineSteps.value, two_pass: twoPass.checked ? '1' : '0',
+ step_cache: stepCacheNow(), upscale_factor: upscaleNow()})) usageQuery.set(key, val);
+ await otherUsage.check(usageQuery);
+ } else await otherUsage.check(null);
+ if (disposed) return;
const source = extension.source;
const sourceState = source ? await extendSourceState(api, source) : 'ok';
if (sourceState !== 'ok') throw new Error(extendSourceProblem(t, sourceState));