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.
Switch every entry to the new quality levels
Bowen Xue8f3af7efb216
diff --git a/freevideo_engine/adaptive.py b/freevideo_engine/adaptive.pyindex 37d9a9b..ddd3dfb 100644--- a/freevideo_engine/adaptive.py+++ b/freevideo_engine/adaptive.py@@ -434,7 +434,12 @@ def next_placement(profile, failure, phase, canvas=None, *, previous_ram_retrieshost_pins = failure['kind'] == 'gpu_oom' and nonlocal_exhausted(failure)compute = Noneif failure['kind'] == 'gpu_oom':- if host_pins and phase in ('load', 'sample') and (engine.get('pin_host_gb', 0.) > 0 or engine.get('pin_host_weights')):+ if phase == 'sample' and engine.get('step_cache') == 'fbcache' and not host_pins:+ # Its two packed residuals are the newest GPU allocation in the+ # pass; sample every step in full before moving any weights.+ changes['engine.step_cache'] = {'from': 'fbcache', 'to': None}+ del engine['step_cache']+ elif host_pins and phase in ('load', 'sample') and (engine.get('pin_host_gb', 0.) > 0 or engine.get('pin_host_weights')):# Page-locked memory ran out, not VRAM: return pinned weights and# keep every GPU setting. Halve once, then pin nothing.change('engine', 'pin_host_gb', 0. if previous_gpu_retries else round(engine.get('pin_host_gb', 0.) / 2, 3))diff --git a/freevideo_engine/agent/editor_runtime.py b/freevideo_engine/agent/editor_runtime.pyindex e247014..b8bbf75 100644--- a/freevideo_engine/agent/editor_runtime.py+++ b/freevideo_engine/agent/editor_runtime.py@@ -17,8 +17,8 @@ WEB = Path(__file__).resolve().parents[2] / 'web'# import does. editor_model and editor_text_model import each other: the# module still loading is reached only through a namespace import.MODULES = ('editor_picture_fields', 'editor_transport_model', 'editor_audio_model', 'editor_speed_model',- 'editor_text_model', 'editor_model', 'editor_room', 'editor_actions', 'editor_generation', 'chain_support',- 'editor_store')+ 'editor_text_model', 'editor_model', 'editor_room', 'editor_actions', 'editor_generation', 'sampling_effort',+ 'chain_support', 'editor_store')TIME_LIMIT = 5.0MEMORY_LIMIT = 256 * 2**20STACK_LIMIT = 4 * 2**20diff --git a/freevideo_engine/agent/guide.py b/freevideo_engine/agent/guide.pyindex 2cf848f..6a6a068 100644--- a/freevideo_engine/agent/guide.py+++ b/freevideo_engine/agent/guide.py@@ -71,8 +71,10 @@ GUIDE = {'the draft and looks plainer than a direct generation, so keep the direct one when the user prefers its look.',],'quality': [- 'Steps per quality: "light" = 8 first-pass steps + 3 refine steps, two-pass (default); "medium" = 12 steps, '- '"high" = 16 steps, "max" = 20 steps, each in one pass.',+ 'Steps per quality: "light" = 8 first-pass steps + 3 refine steps, two-pass (default); "medium" = 8 steps, '+ '"high" = 20 steps with a step cache, "max" = 20 steps with a step cache that skips less work, each in one pass. '+ '"max" runs plain 20 steps when the GPU has no room for its cache. On a Mac, "high" is 16 steps and '+ '"max" 20 steps, without a cache.','Two-pass generation runs only with 8 first-pass steps. Any other base_steps (for example 20 with ''two_pass=true) runs in one pass of that many steps; the job notice says so. A preview is always two-pass ''with 8 steps.',diff --git a/freevideo_engine/agent/length.py b/freevideo_engine/agent/length.pyindex adacee8..a44e149 100644--- a/freevideo_engine/agent/length.py+++ b/freevideo_engine/agent/length.py@@ -41,9 +41,14 @@ def single_frame_limit(spec, *, port=None, table=None):tiers = table.get('tiers', {})tier = tiers.get(spec['quality'])if tier is None:- tier = next((row for row in tiers.values()- if row.get('steps') == spec['base_steps'] and row.get('two_pass') == spec['two_pass']- and (not spec['two_pass'] or spec['refine_steps'] == 3)), {})+ # The same plan with the same step cache first. A cache keeps the length a+ # card fits (the planner drops a first-block cache that does not fit),+ # so the same plan with another cache is the next best row.+ same = [row for row in tiers.values()+ if row.get('steps') == spec['base_steps'] and row.get('two_pass') == spec['two_pass']+ and (not spec['two_pass'] or spec['refine_steps'] == 3)]+ tier = next((row for row in same if row.get('step_cache') == spec.get('step_cache')),+ same[0] if same else {})index = next((i for i, row in enumerate(table.get('sizes', []))if (row['width'], row['height']) == (spec['width'], spec['height'])), None)if index is None:diff --git a/freevideo_engine/agent/productions.py b/freevideo_engine/agent/productions.pyindex df88866..64bcb6d 100644--- a/freevideo_engine/agent/productions.py+++ b/freevideo_engine/agent/productions.py@@ -1012,9 +1012,12 @@ class Productions:tiers = table.get('tiers', {})tier = tiers.get(normalized['quality'])if tier is None:- tier = next((row for row in tiers.values()- if row.get('steps') == normalized['base_steps'] and row.get('two_pass') == normalized['two_pass']- and (not normalized['two_pass'] or normalized['refine_steps'] == 3)), None)+ # Same plan and step cache first, then the same plan (see length.single_frame_limit).+ same = [row for row in tiers.values()+ if row.get('steps') == normalized['base_steps'] and row.get('two_pass') == normalized['two_pass']+ and (not normalized['two_pass'] or normalized['refine_steps'] == 3)]+ tier = next((row for row in same if row.get('step_cache') == normalized.get('step_cache')),+ same[0] if same else None)maxima = tier.get('max_frames') if tier else Noneif index is None or not isinstance(maxima, list) or index >= len(maxima):return Falsediff --git a/freevideo_engine/agent/routes.py b/freevideo_engine/agent/routes.pyindex 040c525..69534e6 100644--- a/freevideo_engine/agent/routes.py+++ b/freevideo_engine/agent/routes.py@@ -25,6 +25,7 @@ from . import API_VERSION, enabledfrom . import assetsfrom . import private_filefrom . import spec as specs+from .. import tiers as quality_tiersfrom . import schema as contract, errors, accessfrom .jobs import ACTIVE, DONE, JobError, Jobs, chain_error, library_view@@ -213,7 +214,8 @@ def capabilities(port, jobs):seconds_tested=[4, 15],fps=24, base_steps=[1, 32], refine_steps=[1, 31], references=32, loras=32, lora_strength=[-4, 4],upload_bytes=2 * 1024 ** 3, vlm_images=24, takes=8, batch_jobs=64),- quality={name: dict(two_pass=plan[0], base_steps=plan[1], refine_steps=plan[2])+ quality={name: dict(two_pass=plan[0], base_steps=plan[1], refine_steps=plan[2],+ step_cache=quality_tiers.step_cache(name, quality_tiers.on_mac()))for name, plan in specs.QUALITY.items()},aspects=sorted(specs.ASPECTS), native_megapixels=.98,tasks=GUIDE['tasks'], media_extensions={k: sorted(v) for k, v in EXTENSIONS.items()},diff --git a/freevideo_engine/agent/schema.py b/freevideo_engine/agent/schema.pyindex df65bb3..bad26ed 100644--- a/freevideo_engine/agent/schema.py+++ b/freevideo_engine/agent/schema.py@@ -9,10 +9,13 @@ import mathimport refrom . import API_VERSION+from .. import tiersS = 'https://json-schema.org/draft/2020-12/schema'PREFIX = '/freevideo/agent/v1'-QUALITY = {'light': (True, 8, 3), 'medium': (False, 12, 3), 'high': (False, 16, 3), 'max': (False, 20, 3)}+# (two_pass, base_steps, refine_steps) of each level on this platform; the step+# cache a level adds is tiers.step_cache(name, mac) (none on Mac).+QUALITY = {name: tiers.plan(name, mac=tiers.on_mac()) for name in tiers.TIERS}ASPECTS = {'16:9': (16, 9), '9:16': (9, 16), '1:1': (1, 1), '4:3': (4, 3), '3:4': (3, 4),'21:9': (21, 9), '2:3': (2, 3), '3:2': (3, 2)}IMAGE_ASPECTS = {'1:1': (1024, 1024), '16:9': (1344, 768), '9:16': (768, 1344),@@ -191,7 +194,7 @@ def generate(*, local=False):{'required': ['sampling', 'quality'], 'properties': {'sampling': {'required': ['two_pass'], 'not': {'required': ['base_steps']},'properties': {'two_pass': {'const': True}}},- 'quality': {'enum': ['medium', 'high', 'max']}}}]}}}],+ 'quality': {'enum': [name for name, plan in QUALITY.items() if plan[1] != 8]}}}]}}}],description='x-job-kind selects normalization and checks derived geometry and sampling step comparisons; these calculations are not JSON Schema constraints.',**{'x-job-kind': 'generate'})diff --git a/freevideo_engine/agent/spec.py b/freevideo_engine/agent/spec.pyindex 1a932ae..75ee140 100644--- a/freevideo_engine/agent/spec.py+++ b/freevideo_engine/agent/spec.py@@ -126,6 +126,8 @@ def canvas_size(value):def sampling(value):+ from .. import tiers+ mac = tiers.on_mac()quality = value.get('quality', contract.generate()['properties']['quality']['default'])two, base, refine = QUALITY[quality]custom = value.get('sampling', {})@@ -136,10 +138,13 @@ def sampling(value):# Only the 8-step first pass goes two-pass; any other count is one pass, said once in the answer.note = one_pass_note(base)two = two and note is None+ # A level's step cache stays only with that level's own plan; custom sampling runs every step.+ cache = tiers.step_cache(quality, mac) if QUALITY[quality] == (two, base, refine) else Noneif custom:- quality = next((k for k, v in QUALITY.items() if v == (two, base, refine)), 'custom')+ quality = next((k for k, v in QUALITY.items() if v == (two, base, refine)+ and tiers.step_cache(k, mac) == cache), 'custom')return dict(quality=quality, two_pass=two, base_steps=base, refine_steps=refine,- **({'sampling_note': note} if note else {}))+ **({'step_cache': cache} if cache else {}), **({'sampling_note': note} if note else {}))def generation_media(value):@@ -276,6 +281,8 @@ def comfy_prompt(spec, node, *, prompt, assets, refine_from=''):if spec.get('first_frame_reference'):# Every part of the video carries it; the part that continues nothing ignores it.inputs['first_frame_reference'] = True+ if spec.get('step_cache'):+ inputs['step_cache'] = spec['step_cache']graph = {node: {'class_type': 'FreeVideoGenerate', 'inputs': inputs,'_meta': {'title': 'FreeVideo · ' + (spec.get('label') or 'Agent job')}}}if assets:diff --git a/freevideo_engine/capabilities.py b/freevideo_engine/capabilities.pyindex 9daddfb..bf9ea16 100644--- a/freevideo_engine/capabilities.py+++ b/freevideo_engine/capabilities.py@@ -18,12 +18,12 @@ from .media_request import TASKSfrom .policy import BLOCK_BYTES, ResourceBudgetError, choosefrom .stage_estimate import STAGES, _params, gpu_key, predict_priorfrom .two_pass import first_pass_policy, plan as sampling_plan+from . import tiers as quality_tiers# Shared by all queries, including the default summary; parity with the editor# is checked in test_capabilities (JS uses positive Math.round, not bankers' rounding).SIZE_PRESETS = (.5, .75, .98, 1., 1.5, 2.)-TIERS = {'light': (8, True), 'medium': (12, False),- 'high': (16, False), 'max': (20, False)}+TIERS = {name: (tier['steps'], tier['two_pass']) for name, tier in quality_tiers.TIERS.items()}PLAN_NAMES = {'-1': 'refused', '0': 'normal', '1': 'slower_streaming','2': 'admitted_tight_memory'}# WholeVideoProgress.for_request starts an ordinary new-prompt request with@@ -242,7 +242,12 @@ def _request(width, height, frames, steps, two_pass, task='t2va', refine=3,def _admit(machine, width, height, frames, steps, two_pass, task='t2va', refine=3,- references=None, reference_rows=None):+ references=None, reference_rows=None, step_cache=None):+ """Admission of one request; `step_cache` asks the planner for a first-pass cache.++ The request carries the cache the planner keeps (never one on Mac), so its+ estimate and history follow what the engine will actually run.+ """canvas, sampling, request = _request(width, height, frames, steps, two_pass, task, refine,references, reference_rows)rows = dict(video=canvas.get('reference_video_tokens', 0), audio=canvas.get('reference_audio_tokens', 0))@@ -269,7 +274,9 @@ def _admit(machine, width, height, frames, steps, two_pass, task='t2va', refine=machine['ram'], machine['ram_available'], system=machine['system'])options = dict(precision=machine['precision'], attention='sage2/sage2', available_backends={'sage2'})choose(hardware, canvas=canvas, stage='encoding', **options)- final = choose(hardware, canvas=canvas, **options)+ final = choose(hardware, canvas=dict(canvas, step_cache=step_cache) if step_cache else canvas, **options)+ if final.engine.get('step_cache'):+ request['step_cache'] = final.engine['step_cache']first = first_pass_policy(final.legacy_profile(), canvas, sampling)engines = [first['profile']['engine'] if first else final.engine, final.engine]request.update(pass1_resident_blocks=engines[0]['resident_blocks'],@@ -327,7 +334,7 @@ def _calibration(machine, hardware, records, params, version):request, _, _ = _admit(machine, shape['width'], shape['height'], shape['frames'],row['base_steps'], row['two_pass'], row['task'],row['refine_steps'] if row['two_pass'] else 3,- reference_rows=refs)+ reference_rows=refs, step_cache=row.get('step_cache'))if request is None:continuerequest['lora_count'] = int(bool(row.get('adapters')))@@ -355,6 +362,7 @@ def _whole_records(records, request, adapters):and r.get('flow', 'full') == 'full' and r.get('task') == request['task']and r.get('adapters', False) == adapters and r.get('two_pass') == request['two_pass']and r.get('base_steps') == request['base_steps'] and r.get('refine_steps') == request['refine_steps']+ and r.get('step_cache') == request.get('step_cache')and ((request['task'] == 't2va' and r.get('reference_rows') is None)or (valid_reference_rows(r.get('reference_rows')) and r['reference_rows'] == rows))]@@ -407,11 +415,12 @@ def build(machine, records, *, aspect='16:9', size=None, task='t2va', adapters=Freturn local.get('seconds', prior['total']['seconds'] * ratio)tiers = {}- for name, (steps, two_pass) in TIERS.items():+ for name, tier in quality_tiers.table(machine['mac']).items():+ steps, two_pass, step_cache = tier['steps'], tier['two_pass'], tier['step_cache']times, codes, maxima, frame_maxima, limits = [], [], [], [], []for size_row in sizes:admitted = {f: _admit(machine, size_row['width'], size_row['height'], f, steps, two_pass, task,- references=references)+ references=references, step_cache=step_cache)for f in range(39, lengths[-1]['frames'] + 1, 17)}estimates = {}for f, (request, _, _) in admitted.items():@@ -437,7 +446,7 @@ def build(machine, records, *, aspect='16:9', size=None, task='t2va', adapters=Frow_codes.append(code)times.append(row_times)codes.append(row_codes)- tiers[name] = dict(steps=steps, two_pass=two_pass, estimate_seconds=times,+ tiers[name] = dict(steps=steps, two_pass=two_pass, step_cache=step_cache, estimate_seconds=times,max_seconds=maxima, max_frames=frame_maxima, limit=limits, plan=codes)default = next((i for i, s in enumerate(sizes) if s['pixels'] == .98), 0)result = dict(version=1, status='ready',diff --git a/freevideo_engine/cli.py b/freevideo_engine/cli.pyindex cdc8690..acbda45 100644--- a/freevideo_engine/cli.py+++ b/freevideo_engine/cli.py@@ -113,6 +113,8 @@ def main():generate.add_argument('--seed', type=int, default=2026090901)generate.add_argument('--two-pass', action=argparse.BooleanOptionalAction, default=True,help='Sample a smaller canvas, upscale latents and refine (default: on; 8 + 3 steps)')+ generate.add_argument('--step-cache', choices=('easycache-av', 'fbcache'),+ help='Approximate reuse between sampling steps (disabled by default)')generate.add_argument('--base-steps', type=int, choices=range(1, 33), metavar='1..32',help='First-pass steps (default: 8, or explicit profile). Changes may reduce quality.')generate.add_argument('--refine-steps', type=int, choices=range(1, 32), default=3, metavar='1..31',diff --git a/freevideo_engine/comfy_assets.py b/freevideo_engine/comfy_assets.pyindex 19545ba..f1d0e61 100644--- a/freevideo_engine/comfy_assets.py+++ b/freevideo_engine/comfy_assets.py@@ -156,6 +156,13 @@ def connect_assets(assets, *, first=None, last=None, reference=None, reference_areturn result+def sampling_plan(report):+ """The report's sampling plan, with the step cache its first pass used (names High and Max)."""+ from .effort_forecast import report_step_cache+ plan, cache = report.get('sampling_plan'), report_step_cache(report)+ return dict(plan, step_cache=cache) if isinstance(plan, dict) and cache else plan++def output_summary(report, relative_video):video = report.get('video', {})encoding = report.get('encoding', {})@@ -175,7 +182,7 @@ def output_summary(report, relative_video):gpu_total_bytes=report.get('profile', {}).get('policy', {}).get('hardware', {}).get('vram_total'),# A small size is sampled larger and scaled back; people see the size they asked for.geometry=dict(report.get('geometry', {}), **(report.get('output_size') or {})),- sampling_plan=report.get('sampling_plan'),+ sampling_plan=sampling_plan(report),low_memory=bool(report.get('low_memory_mode')),thermal=thermal_slowdown(worker_gpu(report)),shared_gpu=shared_gpu_note(worker_gpu(report)),diff --git a/freevideo_engine/comfy_bridge.py b/freevideo_engine/comfy_bridge.pyindex 6b5b750..606784d 100644--- a/freevideo_engine/comfy_bridge.py+++ b/freevideo_engine/comfy_bridge.py@@ -4,6 +4,7 @@ The installed engine owns resource policy, input caches, retries and history.This bridge only retains a request, supervises that CLI and forwards progress."""import json+import loggingimport mathimport osfrom pathlib import Path@@ -208,7 +209,7 @@ class WholeVideoProgress:@classmethoddef for_request(cls, machine, canvas, output_directory, *, base_steps=8,refine_steps=3, two_pass=True, preview=False, upscale=False,- encoder_prewarm=None, options=None):+ encoder_prewarm=None, options=None, step_cache=None):import platformfrom .effort_forecast import start_contextstarted, opened = time.perf_counter(), time.monotonic()@@ -222,7 +223,8 @@ class WholeVideoProgress:flags['encoder_cold'] = Falsetracker = cls(hardware=hardware, records=records, cold_flags=flags, started=started,request=dict(canvas, base_steps=base_steps, refine_steps=refine_steps,- two_pass=two_pass, flow='upscale' if upscale else 'preview' if preview else 'full'),+ two_pass=two_pass, flow='upscale' if upscale else 'preview' if preview else 'full',+ step_cache=step_cache),**(options or {}))tracker.history = (output_directory, machine, opened)return tracker@@ -300,6 +302,13 @@ class WholeVideoProgress:self.request['decoder_resident_blocks'] = blocksif type(decoder.get('offload')) is bool:self.request['decoder_offload'] = decoder['offload']+ if self.request.get('step_cache') is not None:+ # The planner keeps the first-block cache only where it fits; the+ # estimate follows the cache this placement actually uses.+ if engine.get('step_cache') is None:+ self.request.pop('step_cache')+ else:+ self.request['step_cache'] = engine['step_cache']if media is not None:self.request.update(task=task_for(media), lora_count=len(media.get('loras') or []),reference_count=len(media.get('references') or []) +@@ -1170,7 +1179,13 @@ def generate(prompt, width, height, seconds, seed, output_directory, *,release_models=None, export_inputs=None, two_pass=True, encoder_prewarm=None,force_regenerate=False, base_steps=8, refine_steps=3, comfy_metadata=None,prompt_rewrite_report=None, preview=False, refine_from=None, report_extra=None,- continue_from=None, frames=None, first_frame_reference=False, voice_reference=False, hide_tail=False):+ continue_from=None, frames=None, first_frame_reference=False, voice_reference=False, hide_tail=False,+ step_cache=None):+ from .tiers import STEP_CACHES+ if step_cache == 'none':+ step_cache = None+ if step_cache not in STEP_CACHES:+ raise ValueError('Step cache must be none, ' + ', '.join(c for c in STEP_CACHES if c))if type(first_frame_reference) is not bool:raise ValueError('First-frame reference must be a boolean')if type(voice_reference) is not bool:@@ -1202,6 +1217,8 @@ def generate(prompt, width, height, seconds, seed, output_directory, *,two_pass, preview = True, Falsebase_steps = int(argument(arguments, '--base-steps', 8))refine_steps = int(argument(arguments, '--refine-steps', 3))+ # The second pass never uses a step cache; the preview's own command keeps its flag.+ step_cache = argument(arguments, '--step-cache')from .preview import validate_flagsvalidate_flags(preview, upscale, two_pass, base_steps)from .two_pass import validate_steps@@ -1216,6 +1233,11 @@ def generate(prompt, width, height, seconds, seed, output_directory, *,from .two_pass import sampling_canvascheck(continue_from, sampling_canvas(canvas)[0])+ if step_cache is not None and machine.get('device_backend') == 'mps':+ # The step caches are not ported to Mac yet: the request samples every step,+ # and its identity is that of the same request without a cache.+ logging.warning('[FreeVideo] Step caches are not available on Mac yet; sampling every step.')+ step_cache = Noneif continue_from is not None:validate_route(backend=machine.get('device_backend', 'cuda'))from .continuation import MISSING, prepare, summary@@ -1263,6 +1285,8 @@ def generate(prompt, width, height, seconds, seed, output_directory, *,'--width', str(width), '--height', str(height), '--seconds', str(seconds), '--seed', str(seed),'--two-pass' if two_pass else '--no-two-pass','--base-steps', str(base_steps), '--refine-steps', str(refine_steps)]+ if step_cache is not None:+ command += ['--step-cache', step_cache]if frames is not None:position = command.index('--seconds')command[position:position + 2] = ['--frames', str(frames)]@@ -1300,7 +1324,8 @@ def generate(prompt, width, height, seconds, seed, output_directory, *,try:whole_progress = WholeVideoProgress.for_request(machine, canvas, output_directory,base_steps=base_steps, refine_steps=refine_steps, two_pass=two_pass,- preview=preview, upscale=bool(upscale), encoder_prewarm=state['encoder_prewarm'])+ preview=preview, upscale=bool(upscale), encoder_prewarm=state['encoder_prewarm'],+ step_cache=None if upscale else step_cache)except Exception:# A progress estimate cannot prevent generation, even without its parameters.try:@@ -1414,6 +1439,9 @@ def generate(prompt, width, height, seconds, seed, output_directory, *,new_frames=sampled['frames'] - hide_tail_frames - OVERLAP_FRAMES, encoded=True)# A preview is its own result; an upscale is always run from its preview.keyed = dict(planned, preview=True) if preview else planned+ if step_cache is not None:+ # A cache changes the arithmetic; without one the identity stays that of earlier versions.+ keyed = dict(keyed, step_cache=step_cache)if hide_tail_frames:keyed = dict(keyed, hide_tail_frames=hide_tail_frames)identify = lambda check: request_key(prompt, seed, canvas, keyed, extra, machine,@@ -1448,7 +1476,9 @@ def generate(prompt, width, height, seconds, seed, output_directory, *,# Reference audio selects its own tables; match the encoder's choice.asset_task = ((ANCHOR_ADALN_TASK if anchored or pictured else ADALN_TASK) if continue_from is not Noneelse engine_task(extra.get('media', {}), media_base))- preparation = prepare_sampling_assets(root, machine, planned, asset_task,+ # The cache only names the level of a missing table (high or max at 20 steps).+ preparation = prepare_sampling_assets(root, machine, dict(planned, step_cache=step_cache) if step_cache else planned,+ asset_task,progress=asset_progress, interrupted=interrupted, environ=environment)except BaseException:elapsed = time.monotonic() - preparation_starteddiff --git a/freevideo_engine/comfy_library.py b/freevideo_engine/comfy_library.pyindex 42b4da7..3d8c511 100644--- a/freevideo_engine/comfy_library.py+++ b/freevideo_engine/comfy_library.py@@ -1084,11 +1084,18 @@ def register():device = machine.get('device_identity') if machine.get('device_backend') == 'mps' else machine.get('gpu_uuid')rows = await asyncio.to_thread(local_records, folder_paths.get_output_directory(), device)adapters = request.query.get('adapters') == '1'- # A small canvas runs in one pass whatever the switch says.- result = {name: {str(steps): estimate(rows, canvas, base_steps=steps,- two_pass=plan(canvas, enabled, task, base_steps=steps)['enabled'],- task=task, adapters=adapters)- for steps in ((8,) if enabled else (8, 12, 16, 20))}+ # A small canvas runs in one pass whatever the switch says. A cached+ # level is keyed "<steps>:<cache>". Without a run of it, plain runs+ # stand in: the first-block cache is counted at full time, since the+ # planner may not keep it on this card.+ share = {'fbcache': 1.}+ result = {name: {(str(steps) + (':' + cache if cache else '')):+ estimate(rows, canvas, base_steps=steps,+ two_pass=plan(canvas, enabled, task, base_steps=steps)['enabled'],+ task=task, adapters=adapters, step_cache=cache, cache_share=share.get(cache))+ for steps, cache in (((8, None),) if enabled else+ ((8, None), (12, None), (16, None), (20, None),+ (20, 'easycache-av'), (20, 'fbcache')))}for name, enabled in (('single', False), ('two_pass', True))}return web.json_response(result, headers={'Cache-Control': 'no-store'})except (OSError, ValueError, TypeError, KeyError):diff --git a/freevideo_engine/comfy_nodes.py b/freevideo_engine/comfy_nodes.pyindex 725e62f..7232ac2 100644--- a/freevideo_engine/comfy_nodes.py+++ b/freevideo_engine/comfy_nodes.py@@ -12,6 +12,13 @@ References = io.Custom('FREEVIDEO_REFERENCES')LoRAs = io.Custom('FREEVIDEO_LORAS')Media = io.Custom('FREEVIDEO_MEDIA')NO_LORA = 'None'+STEP_CACHE_OPTIONS = ('none', 'easycache-av', 'fbcache')+++def step_cache_option(value):+ """Bridge keyword for the Step cache widget; a workflow without it, or with 'none', adds nothing."""+ return {} if value in (None, 'none') else {'step_cache': value}+class FreeVideoGenerate(io.ComfyNode):@classmethod@@ -69,6 +76,11 @@ class FreeVideoGenerate(io.ComfyNode):optional=True, advanced=True, tooltip='Keeps the opening voice consistent in continued dialogue.'),io.Boolean.Input('hide_tail', display_name='Hide dialogue tail', default=False,optional=True, advanced=True, tooltip='Generates and discards 17 extra frames to keep dialogue moving between parts.'),+ # Last, so the widget values of saved workflows keep their positions.+ io.Combo.Input('step_cache', display_name='Step cache', options=list(STEP_CACHE_OPTIONS), default='none',+ optional=True, advanced=True,+ tooltip='Reuses work between similar sampling steps to finish sooner, with a small change to the result. '+ 'High uses easycache-av; Max uses fbcache.'),],outputs=[io.Video.Output('video'), io.String.Output('report', display_name='Report JSON')],hidden=[io.Hidden.unique_id, io.Hidden.prompt, io.Hidden.extra_pnginfo],@@ -114,7 +126,8 @@ class FreeVideoGenerate(io.ComfyNode):def execute(cls, text, width, height, seconds, seed, first=None, last=None,references=None, loras=None, conditioning=None, media=None, two_pass=True,force_regenerate=False, base_steps=8, refine_steps=3, preview=False, refine_from='',- continue_from='', frames=0, first_frame_reference=False, voice_reference=False, hide_tail=False):+ continue_from='', frames=0, first_frame_reference=False, voice_reference=False, hide_tail=False,+ step_cache='none'):from server import PromptServerfrom .comfy_chain import block_context, block_finished, report_fieldsrefine_from, continue_from = optional_text(refine_from), optional_text(continue_from)@@ -257,6 +270,7 @@ class FreeVideoGenerate(io.ComfyNode):**({'first_frame_reference': True} if first_frame_reference is True and options.get('continue_from') else {}),**({'voice_reference': True} if voice_reference is True and options.get('continue_from') else {}),**({'hide_tail': True} if hide_tail is True else {}),+ **step_cache_option(step_cache),**({'report_extra': {'chain': report_fields(chain)}} if chain is not None else {}))relative = output.relative_to(output_root)report = output.with_suffix('.request.json').read_text(encoding='utf-8')diff --git a/freevideo_engine/comfy_share.py b/freevideo_engine/comfy_share.pyindex 0dd387a..3421d24 100644--- a/freevideo_engine/comfy_share.py+++ b/freevideo_engine/comfy_share.py@@ -60,6 +60,9 @@ def details(root, identity):plan = summary.get('sampling_plan') or {}result['sampling_plan'] = {k: v for k, v in plan.items() if k in ('enabled', 'base_steps', 'refine_steps')and type(v) in (int, bool)}+ from .tiers import STEP_CACHES+ if plan.get('step_cache') in STEP_CACHES[1:]:+ result['sampling_plan']['step_cache'] = plan['step_cache']result['id'] = identityresult['graph'] = saved_graph(path)return resultdiff --git a/freevideo_engine/effort_forecast.py b/freevideo_engine/effort_forecast.pyindex 3183906..159734b 100644--- a/freevideo_engine/effort_forecast.py+++ b/freevideo_engine/effort_forecast.py@@ -70,6 +70,7 @@ def timing_record(report, gpu_uuid, system, *, stage_details=True):refine = plan.get('refine_steps', 0) if plan.get('enabled') and not preview else 0if measured[0]['steps'] != base or (refine and measured[1]['steps'] != refine):return None+ cache = effective_step_cache(passes[0])encoding = report.get('encoding') or {}cached = bool(encoding.get('cache_hit') or report.get('input_cache', {}).get('conditioning_hit')or report.get('tuning', {}).get('conditioning_cache_hit'))@@ -82,6 +83,9 @@ def timing_record(report, gpu_uuid, system, *, stage_details=True):task=video.get('config', {}).get('task', 't2va'),adapters=bool(report.get('profile', {}).get('engine', {}).get('loras') orreport.get('lora') or video.get('config', {}).get('online_lora')))+ if cache is not None:+ # Rows without the key are plain runs, as every run before the caches was.+ record['step_cache'] = cacheif not stage_details:return recordupscale = video.get('latent_upscale') or {}@@ -131,14 +135,42 @@ def timing_record(report, gpu_uuid, system, *, stage_details=True):return record-def estimate(records, canvas, *, base_steps=8, refine_steps=3, two_pass=True, task='t2va', adapters=False):+def effective_step_cache(part):+ """The step cache a first pass actually used, from its report; None for a plain pass."""+ from .tiers import STEP_CACHES+ stats = part.get('step_cache') if isinstance(part, dict) else None+ if not isinstance(stats, dict) or stats.get('disabled_reason') or stats.get('kind') not in STEP_CACHES:+ return None+ return stats['kind']+++def report_step_cache(report):+ """The first-pass step cache a finished request used, from its report."""+ video = report.get('video') or {} if isinstance(report, dict) else {}+ passes = video.get('sampling_passes')+ return effective_step_cache(passes[0] if isinstance(passes, list) and passes else video)+++def estimate(records, canvas, *, base_steps=8, refine_steps=3, two_pass=True, task='t2va', adapters=False,+ step_cache=None, cache_share=None):+ """Whole-request seconds from local runs of this shape.++ Runs with the requested step cache come first. Without one, plain runs stand+ in with their first pass scaled by `cache_share` (tiers.sampling_share by+ default) and a wider range; a cached run never stands in for a plain request.+ """from .two_pass import validate_steps+ from .tiers import sampling_sharevalidate_steps(base_steps, refine_steps, two_pass)+ share = sampling_share(step_cache) if cache_share is None else cache_sharecandidates = []for row in records:if (row.get('flow', 'full') != 'full' or row['task'] != task or row['adapters'] != adaptersor row['shape'] != {k: canvas[k] for k in ('width', 'height', 'frames')}):continue+ cache = row.get('step_cache')+ if cache != step_cache and (cache is not None or row['two_pass'] != two_pass):+ continue# Both passes retain their own resolution costs. Never multiply the# entire generation by a step ratio or confuse eight low-res steps# with eight full-res steps. Existing first-step warmup stays intact.@@ -152,7 +184,12 @@ def estimate(records, canvas, *, base_steps=8, refine_steps=3, two_pass=True, taseconds = row['request_seconds'] - row['sampling_seconds'] + last['seconds'] + (base_steps - last['steps']) * last['incremental']else:seconds = row['request_seconds'] + (base_steps - row['base_steps']) * row['passes'][0]['incremental']- if two_pass and not switched:+ if cache != step_cache:+ # A plain run of the same plan: only its first pass changes with a cache.+ first = row['passes'][0]['seconds'] + (base_steps - row['base_steps']) * row['passes'][0]['incremental']+ seconds -= (1 - share) * first+ switched = True+ if two_pass and row['two_pass'] == two_pass:seconds += (refine_steps - row['refine_steps']) * row['passes'][1]['incremental']if positive(seconds):candidates.append((seconds, row, switched))@@ -255,10 +292,13 @@ def _stage_forecast(records, request, cold_flags, prior):if positive(stages.get('decode_save')):found.append(('decode_save', stages['decode_save']))similar_passes = row['two_pass'] == request.get('two_pass', True)+ # A step cache changes the first pass only; its steps and totals stay with their own cache.+ same_cache = row.get('step_cache') == request.get('step_cache')for i, (target, observed, count) in enumerate(zip((first, second), (r1, r2), counts), 1):near = _near(token_count(target), token_count(observed))similar_passes = similar_passes and (near or not count)- if not (count and same_task and same_lora and near and i <= len(row['passes'])):+ if not (count and same_task and same_lora and near and i <= len(row['passes'])+ and (same_cache or i == 2)):continuepart = row['passes'][i-1]seconds = part['seconds'] + (count-part['steps']) * part['incremental']@@ -271,7 +311,7 @@ def _stage_forecast(records, request, cold_flags, prior):if similar_passes and same_task and same_lora and positive(stages.get('upscale')):found.append(('upscale', stages['upscale']))if (request.get('flow', 'full') == row.get('flow', 'full') and similar_passes and same_task and same_lora- and same_refs):+ and same_refs and same_cache):total = row['request_seconds'] + (counts[0] - row['base_steps']) * row['passes'][0]['incremental']if counts[1]:total += (counts[1] - row['refine_steps']) * row['passes'][1]['incremental']diff --git a/freevideo_engine/execution_config.py b/freevideo_engine/execution_config.pyindex 864d139..77a326f 100644--- a/freevideo_engine/execution_config.py+++ b/freevideo_engine/execution_config.py@@ -18,7 +18,7 @@ ENGINE_DEFAULTS = MappingProxyType({'window_batch': 1, 'linear_compute': 'native-fp8', 'fp8_gemm': 'auto','window_varlen': False, 'varlen_smooth_k': True, 'task': 't2va','stream_weights': False, 'head_parallelism': 1, 'residual_offload': False,- 'adaln_task': None,+ 'adaln_task': None, 'step_cache': None,})DECODER_DEFAULTS = MappingProxyType({'offload': False, 'prefetch': True, 'tile_group': False,diff --git a/freevideo_engine/failure_details.py b/freevideo_engine/failure_details.pyindex ed856ca..13bc523 100644--- a/freevideo_engine/failure_details.py+++ b/freevideo_engine/failure_details.py@@ -7,10 +7,11 @@ import sysfrom .long_paths import io_path, plain_textfrom .diagnostics import Redactor+from .tiers import STEP_CACHES, TIERS, on_mac, table_levelSTEP_OUTPUT = '\n\nFull step output:\n'-QUALITY_LEVELS = (('Light', '轻量'), ('Medium', '标准'), ('High', '精细'), ('Max', '极致'))+QUALITY_LEVELS = (('Light', '轻量'), ('Medium', '标准'), ('High', '精细'), ('Max', '极致')) # tiers.TIERS orderIMAGE_PACK_FAILURES = {@@ -69,9 +70,11 @@ def sampling_table_details(value):and type(details['refine_steps']) is int and 0 <= details['refine_steps'] <= 31and type(details['missing_bytes']) is int and details['missing_bytes'] > 0and type(details['decimal_sizes']) is bool and isinstance(details['available'], list)- and all(type(i) is int and 0 <= i <= 3 for i in details['available'])):+ and all(type(i) is int and 0 <= i <= 3 for i in details['available'])+ and details.get('step_cache') in STEP_CACHES):return {key: details[key] for key in- ('base_steps', 'two_pass', 'refine_steps', 'missing_bytes', 'available', 'decimal_sizes')}+ ('base_steps', 'two_pass', 'refine_steps', 'missing_bytes', 'available', 'decimal_sizes', 'step_cache')+ if key in details}except (ValueError, KeyError, TypeError):passreturn None@@ -83,9 +86,10 @@ def sampling_table_failure(value, *, zh=False):return Nonefrom .launcher_copy import size_textlanguage = 1 if zh else 0- index = next((i for i, steps in enumerate((8, 12, 16, 20))- if details['base_steps'] == steps and details['two_pass'] == (i == 0)- and (i != 0 or details['refine_steps'] == 3)), None)+ # Tables follow the step count; the cache tells high from max at 20 steps.+ level = table_level(details['base_steps'], details['two_pass'], details['refine_steps'],+ details.get('step_cache'), on_mac())+ index = list(TIERS).index(level) if level else Nonenames = [('“%s”' if zh else '%s') % QUALITY_LEVELS[i][language] for i in sorted(set(details['available']))]available = ''if names:diff --git a/freevideo_engine/generate.py b/freevideo_engine/generate.pyindex 3d03c7d..910120c 100644--- a/freevideo_engine/generate.py+++ b/freevideo_engine/generate.py@@ -180,6 +180,9 @@ def automatic_profile(args, canvas, *, stage, evidence, descriptor=None, environplanning_canvas = dict(canvas)if getattr(args, 'task', None):planning_canvas['task'] = args.task+ if getattr(args, 'step_cache', None):+ # The planner keeps the first-block cache only where it fits.+ planning_canvas['step_cache'] = args.step_cacheoptions.update(available_backends=available_backends(hardware, probe_missing=False), canvas=planning_canvas,demonstrated_ram_bytes=demonstrated_local_ram(hardware, args, canvas))cache = getattr(args, 'cache', None)@@ -548,6 +551,8 @@ def _run(args):base_steps = requested_steps if requested_steps is not None else profile['engine'].get('steps', 8)validate_steps(base_steps, refine_steps, two_pass)profile['engine']['steps'] = base_steps+ if args.profile and getattr(args, 'step_cache', None):+ profile['engine']['step_cache'] = args.step_cacheif 'engine' in profile.get('policy', {}):profile['policy']['engine']['steps'] = base_stepsif base_steps != 8:diff --git a/freevideo_engine/offload.py b/freevideo_engine/offload.pyindex 123217f..085db76 100644--- a/freevideo_engine/offload.py+++ b/freevideo_engine/offload.py@@ -519,6 +519,36 @@ class LayerOffloader:"""No layer pass is open, so the next pass can start; False after a failure inside one."""return not (self.expected or self.pending or self.host_pending)+ def end_pass_early(self):+ """Finish a successful partial traversal after its last forward hook.++ Indices belong to this offloaded subset, not the transformer's blocks.+ Block zero may be resident, so an already idle traversal is valid too.+ Keep admitted weight caches and live reader pools for the next step.+ """+ if self.closed:+ raise RuntimeError('Cannot finish a closed offloader')+ # _stage may still be submitting copies or filling an admitted cache.+ # Join producers before waiting on the final events they recorded.+ for future in self.pending.values():+ future.result()+ for read in self.host_pending.values():+ if not read.future.cancel():+ read.future.result()+ # A skipped prefetch has copy_done but no new compute_done. Likewise,+ # the first block's compute may still read its slot after Python returns.+ # Never reset/reuse either plane until both operations have completed.+ for slot in [*self.slots, *self.cached.values(), *self.host_slots]:+ for event in (slot.copy_done, slot.compute_done):+ if event is not None:+ event.synchronize()+ if self.read_ahead is not None:+ self.read_ahead.end_pass_early()+ self.pending.clear()+ self.host_pending.clear()+ self.host_cursor = 0+ self.expected = 0+def cache_between_steps(self, max_bytes, *, max_layers=None, allow_growth=True):"""Retain affordable device planes until this sampling pass closes.diff --git a/freevideo_engine/packing.py b/freevideo_engine/packing.pyindex 236f4e2..816e4a5 100644--- a/freevideo_engine/packing.py+++ b/freevideo_engine/packing.py@@ -37,12 +37,25 @@ def install_streamed_forward(model, chunk=1024, residual_offload=False):def blocks(self, value, length, temb, adaln_indices, rotary):first = length not in collectedcollected.add(length)+ cache = getattr(self, '_freevideo_step_cache', None)+ cache = cache if cache is not None and not cache.disabled_reason and cache.block_level else None+ if cache is not None and not isinstance(value, torch.Tensor):+ cache.disabled_reason = 'residual_offload'+ cache = Nonefor index, block in enumerate(self.transformer_blocks):if first and index in (1, 2) and hasattr(value, 'collect_after_store'):value.collect_after_store = True+ if cache is not None and index == 0:+ cache.before_first_block(value)value = block(value, temb, adaln_indices, rotary)if first and index == 0 and not hasattr(value, 'collect_after_store'):gc.collect()+ if cache is not None and index == 0 and cache.after_first_block(value):+ if cache.offloader is not None:+ cache.offloader.end_pass_early()+ return value+ if cache is not None:+ cache.after_last_block(value)return valuedef forward(self, hidden_states, audio_hidden_states, encoder_hidden_states,@@ -55,6 +68,24 @@ def install_streamed_forward(model, chunk=1024, residual_offload=False):length = position_ids.shape[0]if position_ids.shape != (length, 3) or token_tags.shape != (length,) or timestep_indices.shape != (length,):raise ValueError('Invalid packed sequence geometry')+ cache = getattr(self, '_freevideo_step_cache', None)+ if cache is not None and residual_offload and cache.block_level:+ # The first-block cache keeps packed residuals on the GPU; reusing+ # a whole step (EasyCache) does not touch them.+ cache.disabled_reason = 'residual_offload'+ cache = cache if cache is not None and not cache.disabled_reason else None+ sigmas = None+ if cache is not None:+ cache.begin(video_indices, audio_indices)+ if not cache.block_level:+ # H3 time is t = 1 - sigma; generated video rows come last.+ sigmas = (1. - float(timestep[timestep_indices[video_indices[-1]]]),+ 1. - float(timestep[timestep_indices[audio_indices[0]]]))+ cached = cache.skip_forward(hidden_states[0], audio_hidden_states[0], sigmas)+ if cached is not None:+ video = cached[0][None].to(self.proj_out.weight.dtype)+ audio = cached[1][None].to(self.audio_proj_out.weight.dtype)+ return MiniMaxH3TransformerOutput(sample=video, audio_sample=audio) if return_dict else (video, audio)rotary = self.rope(position_ids)text = getattr(self, '_freevideo_refined_text', None)if text is None:@@ -95,6 +126,8 @@ def install_streamed_forward(model, chunk=1024, residual_offload=False):audio_all[:, start:start + chunk] = self.audio_proj_out(normalized)video = video_all.index_select(1, video_indices)audio = audio_all.index_select(1, audio_indices)+ if sigmas is not None:+ cache.record_forward(hidden_states[0], audio_hidden_states[0], sigmas, video[0], audio[0])return MiniMaxH3TransformerOutput(sample=video, audio_sample=audio) if return_dict else (video, audio)model.forward = types.MethodType(forward, model)diff --git a/freevideo_engine/policy.py b/freevideo_engine/policy.pyindex 8636924..faa7239 100644--- a/freevideo_engine/policy.py+++ b/freevideo_engine/policy.py@@ -767,10 +767,74 @@ def adaln_extra_bytes(canvas=None):return max(0, steps - 8) * times_per_step * 50 * 3 * 6 * 5376 * 2-def choose(hardware: Hardware, *, vram_gib=None, ram_gib=None, attention='auto',- gpu_reserve_gib=None, ram_reserve_gib=None, available_backends=None, canvas=None,- demonstrated_ram_bytes=None, allow_capacity_trial=False, stage='generation',- lora_max_block_bytes=0, lora_root_bytes=0, precision='fp8'):+STEP_CACHES = ('easycache-av', 'fbcache')+# Engine choices the first-block cache may change. B200 at 24 GiB, 20 steps with the+# cache against without: 8 resident blocks given up 297 s vs 396 s sampling (20 s),+# head chunk 16 -> 8 368 s vs 439 s, 28 -> 16 149-166 s vs 184-200 s (10 s). Host pins+# follow the GPU placement. Anything else (prefetch, attention outputs on the CPU, ...)+# costs more than the skipped steps save, and the request runs every step instead.+FIRST_BLOCK_CACHE_MAY_CHANGE = ('pin_host_gb', 'resident_blocks', 'head_chunk')+# Reserved growth over the counted video rows: 3.34 GiB measured / 2.87 GiB counted (B200, 20 s 1344x768).+FIRST_BLOCK_CACHE_RESERVED_SCALE = 1.17+++def first_block_cache_bytes(canvas):+ """GPU storage the first-block cache keeps through a sampling pass.++ It holds two packed residuals of the last full step: block 0's output and+ the remaining blocks' contribution, BF16 rows of 5376 channels. At 20 s of+ 1344x768 the video rows are 2 x 1.43 GiB; B200 measured 2.98 GiB more+ allocated and 3.34 GiB more reserved than the same request without it (text+ and audio rows, allocator rounding), so the rows are scaled to the reserved+ growth.+ """+ from .two_pass import placement_tokens+ return math.ceil(2 * placement_tokens(canvas) * 5376 * 2 * FIRST_BLOCK_CACHE_RESERVED_SCALE)+++def choose(hardware: Hardware, *, canvas=None, stage='generation', **options):+ """Placement for a request; canvas['step_cache'] asks for a step cache.++ The first-block cache is kept when reserving its storage only gives up+ resident blocks or at most halves the head chunk; otherwise the request+ samples every step in full. EasyCache keeps only latent-sized tensors and+ is always kept.+ """+ wanted = (canvas or {}).get('step_cache') if stage == 'generation' else None+ if wanted is None:+ plain = canvas if canvas is None or 'step_cache' not in canvas else {+ key: value for key, value in canvas.items() if key != 'step_cache'}+ return _choose(hardware, canvas=plain, stage=stage, **options)+ if wanted not in STEP_CACHES:+ raise ValueError('Step cache must be one of ' + ', '.join(STEP_CACHES))+ from dataclasses import replace+ plain = {key: value for key, value in canvas.items() if key != 'step_cache'}+ base = _choose(hardware, canvas=plain, stage=stage, **options)+ kept, note = True, None+ if wanted == 'fbcache':+ try:+ cached = _choose(hardware, canvas=plain, stage=stage, step_cache_bytes=first_block_cache_bytes(plain), **options)+ except ResourceBudgetError:+ cached = None+ route = lambda engine: {key: value for key, value in engine.items() if key not in FIRST_BLOCK_CACHE_MAY_CHANGE}+ kept = (cached is not None and route(cached.engine) == route(base.engine)+ and 2 * (cached.engine.get('head_chunk') or 0) >= (base.engine.get('head_chunk') or 0))+ note = ('First-block cache keeps %.2f GiB of residuals in free GPU memory.' if kept else+ 'First-block cache needs %.2f GiB the placement does not leave free; every step runs in full.'+ ) % (first_block_cache_bytes(plain) / GiB)+ if kept:+ # Decoding starts after the pass has released the cache.+ base = replace(base, engine=cached.engine)+ # Without a cache the engine options stay exactly those of a plain request,+ # so its history and identities still match.+ return replace(base, engine=dict(base.engine, step_cache=wanted) if kept else base.engine,+ notes=list(base.notes) + ([note] if note else []))+++def _choose(hardware: Hardware, *, vram_gib=None, ram_gib=None, attention='auto',+ gpu_reserve_gib=None, ram_reserve_gib=None, available_backends=None, canvas=None,+ demonstrated_ram_bytes=None, allow_capacity_trial=False, stage='generation',+ lora_max_block_bytes=0, lora_root_bytes=0, precision='fp8', step_cache_bytes=0):"""precision is the prepared cache's: int8 caches run int8 projections."""from .geometry import geometryif stage not in ('encoding', 'generation'):@@ -791,7 +855,7 @@ def choose(hardware: Hardware, *, vram_gib=None, ram_gib=None, attention='auto',lora_workspace = (128 * 2**20 + 2 * lora_max_block_bytes + lora_root_bytesif lora_max_block_bytes or lora_root_bytes else 0)table_workspace = adaln_extra_bytes(canvas) if stage == 'generation' else 0- placement_workspace = lora_workspace + table_workspace+ placement_workspace = lora_workspace + table_workspace + step_cache_bytesif canvas is not None:checked = geometry(canvas['width'], canvas['height'], frames=canvas['frames'])if any(canvas.get(k) != checked[k] for k in ('width', 'height', 'frames', 'video_tokens')):diff --git a/freevideo_engine/resource_history.py b/freevideo_engine/resource_history.pyindex 62ca498..831f7b2 100644--- a/freevideo_engine/resource_history.py+++ b/freevideo_engine/resource_history.py@@ -89,6 +89,9 @@ def _canonical_config(config, purpose):# The ordinary task's schedule has the same historical computation identity.if resolved_engine.get('adaln_task') in (None, engine.get('task', 't2va')):resolved_engine.pop('adaln_task', None)+ # Runs without a step cache keep their historical identity; a cache changes the arithmetic.+ if resolved_engine.get('step_cache') is None:+ resolved_engine.pop('step_cache', None)if resolved_decoder.get('continuation') is None:resolved_decoder.pop('continuation', None)normalized_engine = _computation(resolved_engine)diff --git a/freevideo_engine/runtime.py b/freevideo_engine/runtime.pyindex 6bc3298..26ea87a 100644--- a/freevideo_engine/runtime.py+++ b/freevideo_engine/runtime.py@@ -62,7 +62,9 @@ class Engine:fp8_gemm='auto', window_varlen=False, varlen_smooth_k=True,task='t2va', stream_weights=False, canvas=None, head_parallelism=1,residual_offload=False, device_backend=None, gpu_allocation_bytes=None,- fetch_tables=True, adaln_task=None):+ fetch_tables=True, adaln_task=None, step_cache=None):+ from .step_cache import requested+ requested(step_cache) # Validate the effective selection before loading weights.self.device_backend = device_backend if device_backend is not None else get_backend()if gpu_allocation_bytes is not None and (type(gpu_allocation_bytes) is not int or gpu_allocation_bytes < 0):raise ValueError('GPU allocation limit must be a nonnegative byte count')@@ -519,6 +521,8 @@ class Engine:'window_varlen': window_varlen,'varlen_smooth_k': varlen_smooth_k if window_varlen else None,'steps': steps, 'source_id': manifest['source_id']}+ if step_cache is not None:+ self.config['step_cache'] = step_cacheif self.adaln_task != self.task:self.config['adaln_task'] = self.adaln_task@@ -833,9 +837,18 @@ class Engine:frame_preview.observing(latent_frames=canvas.get('latent_frames'), frame_h=height // 32,frame_w=width // 32, step_offset=progress_offset,total=progress_total if progress_total is not None else active_steps):- latents, audio = generate_latents(self.transformer, prompt, tags, frames,- self.steps, seed, self.device_backend.device, step_seconds=step_seconds,- conditions=conditions, **sampling_kwargs)+ from .step_cache import begin_pass, end_pass+ if not refining:+ disabled = ('residual_offload' if self.config.get('residual_offload') and self.config.get('step_cache') == 'fbcache' else+ 'streamed_forward_unavailable' if not self.config.get('projection_chunk') else None)+ begin_pass(self.transformer, active_steps, self.config.get('step_cache'),+ offloader=offloader if self.offload_layers else None, disabled_reason=disabled)+ try:+ latents, audio = generate_latents(self.transformer, prompt, tags, frames,+ self.steps, seed, self.device_backend.device, step_seconds=step_seconds,+ conditions=conditions, **sampling_kwargs)+ finally:+ step_cache = end_pass(self.transformer)if prefix is not None:latents, audio = prefix.finish(latents, audio)stats = offloader.stats()@@ -858,7 +871,7 @@ class Engine:'head_execution': dict(requested_parallelism=self.config.get('head_parallelism', 1),**{name: getattr(self.attention, name, 0) - countfor name, count in parallel_before.items()}),- 'text_refinement': refinement,+ 'text_refinement': refinement, 'step_cache': step_cache,'torch_peak_allocated_bytes': self.device_backend.max_memory_allocated(),'torch_peak_reserved_bytes': self.device_backend.max_memory_reserved()}if watch is not None:diff --git a/freevideo_engine/sampling_assets.py b/freevideo_engine/sampling_assets.pyindex 2298857..c860988 100644--- a/freevideo_engine/sampling_assets.py+++ b/freevideo_engine/sampling_assets.py@@ -80,7 +80,9 @@ def available_levels(cache, shared, manifest, kind, catalog):not refinement(t) and len(t['identity']['timesteps']) == steps and ready(t) for t in task_tables)refine_ready = any(refinement(t) and ready(t) for t in task_tables)- return [i for i, steps in enumerate((8, 12, 16, 20)) if base_ready(steps) and (i != 0 or refine_ready)]+ from .tiers import table+ return [i for i, tier in enumerate(table(sys.platform == 'darwin').values())+ if base_ready(tier['steps']) and (not tier['two_pass'] or refine_ready)]@plain_errors@@ -380,7 +382,8 @@ def prepare(root, machine, sampling, task, *, progress, interrupted=None, envirodetails = dict(base_steps=sampling['base_steps'], two_pass=bool(sampling.get('enabled')),refine_steps=sampling.get('refine_steps', 0), missing_bytes=total,available=available_levels(cache, shared, manifest, kind, catalog),- decimal_sizes=sys.platform == 'darwin')+ decimal_sizes=sys.platform == 'darwin',+ **({'step_cache': sampling['step_cache']} if sampling.get('step_cache') else {}))raise SamplingTableUnavailable(details, failure.cause) from failure.causeif failure is not None:raise failurediff --git a/freevideo_engine/stage_estimate.py b/freevideo_engine/stage_estimate.pyindex 5b5dded..c3f2853 100644--- a/freevideo_engine/stage_estimate.py+++ b/freevideo_engine/stage_estimate.py@@ -435,12 +435,19 @@ def predict_prior(hardware, request, cold_flags, params=None):video_decode is a diagnostic SUBSET of decode: never add it to total.Input hardware RAM/VRAM use GiB. pcie_bandwidth_gbs is decimal GB/s.- request uses schema names plus optional pass1_resident_blocks, reference_seconds.+ request uses schema names plus optional pass1_resident_blocks, reference_seconds,+ step_cache (the effective first-pass cache).Cold flags may include pass1/2_canvas_compiled and pass1/2_compile_cold.Unknown flags must be None, never inferred from future observed first steps."""p=_params(params)v,d=_raw(hardware,request,cold_flags or {},p)+ if request.get('step_cache'):+ # The fit has only plain passes; a step cache shortens the first pass alone.+ from .tiers import sampling_share+ d['step_cache_share']=sampling_share(request['step_cache'])+ v['pass1']*=d['step_cache_share']+ _sum_total(v)wide=_apple(hardware) or _gpu_item(hardware,p) is Nonereturn _decode_save({'stages':{k:_interval(k,x,p,wide=wide) for k,x in v.items() if k!='total'},'total':_interval('total',v['total'],p,wide=wide), 'diagnostics':d,diff --git a/freevideo_engine/step_cache.py b/freevideo_engine/step_cache.pynew file mode 100644index 0000000..2ea6463--- /dev/null+++ b/freevideo_engine/step_cache.py@@ -0,0 +1,196 @@+"""Step-skipping caches for MiniMax H3 sampling, ported from the ComfyUI community.++Both approximate an earlier step of the same pass (one forward per step, no CFG).+Only explicit step_cache configuration or FREEVIDEO_STEP_CACHE=<kind>[:<threshold>]+enables them. Numerical operations follow the FreeVideo H200 experiment snapshot+fb7786481cd10f0908c646667ff0e41e23b81dcfbaae656cb9b0622e73d579fd.++fbcache: MiniMax H3 FirstBlockCache by duckyshell (MIT), Fast preset, upstream+f7a27128e73e1859f2295e64698164203799029d. Compare the video rows' first-block+residual with the last full step (relative mean absolute difference, row/channel+stride 8, threshold 0.10, window 10-95%, at most two consecutive hits). Audio+is sampled for diagnostics only. A hit adds the last full step's cached tail.++easycache-av: ComfyUI EasyCache, reimplemented from the paper/node behaviour+(ComfyUI #15326; original snapshot SHA-256+746fd299918efff7f2abe919fb8a0c20abd384be1e28a0f122c0d321a69ce174).+The last full step's rate k = |d out| / |d in| predicts k |d in| / |out|.+The H3 AV adaptation accumulates the larger audio/video prediction; below 0.2+in the 15-95% window, reuse each modality's output-minus-input difference.+As in the H200 snapshot, this method has no consecutive-hit cap.++FirstBlockCache attribution and MIT permission notice:+MIT License++Copyright (c) 2026 duckyshell++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.+"""+import os++DEFAULTS = {'easycache-av': 0.2, 'fbcache': 0.10}+WINDOWS = {'easycache-av': (0.15, 0.95), 'fbcache': (0.10, 0.95)}+BLOCK_LEVEL = ('fbcache',)+STRIDE = 8+++def requested(config=None):+ """Resolve (kind, threshold, source); a nonempty experiment overrides config."""+ value = os.environ.get('FREEVIDEO_STEP_CACHE', '').strip()+ if value:+ kind, _, threshold = value.partition(':')+ if kind not in DEFAULTS:+ raise ValueError('Unknown FREEVIDEO_STEP_CACHE kind %r; use one of %s' % (kind, ', '.join(DEFAULTS)))+ return kind, float(threshold) if threshold else DEFAULTS[kind], 'environment'+ if config is None:+ return None+ if config not in DEFAULTS:+ raise ValueError('Unknown step_cache %r; use one of %s' % (config, ', '.join(DEFAULTS)))+ return config, DEFAULTS[config], 'config'+++def _relative(current, previous):+ return float((current - previous).abs().mean() / previous.abs().mean().clamp_min(1e-6))+++class StepCache:+ def __init__(self, kind, threshold, steps, *, source=None, offloader=None, disabled_reason=None):+ self.kind, self.threshold, self.steps = kind, threshold, steps+ self.source, self.offloader = source, offloader+ self.disabled_reason = disabled_reason+ self.block_level = kind in BLOCK_LEVEL+ self.step = -1+ self.hits, self.decisions = [], []+ self.consecutive = 0+ # block level+ self.previous = None # (audio, video) block-0 residual samples of the last full step+ self.tail = None # packed: last block output - block 0 output, last full step+ self.indices = None+ # model level+ self.prev_input = None+ self.prev_diff = None+ self.prev_out = None+ self.rate = None+ self.accumulated = 0.++ # ---- shared ------------------------------------------------------------------------------------+ def in_window(self):+ start, end = WINDOWS.get(self.kind, (0., 1.))+ progress = self.step / self.steps+ return start <= progress < end++ def begin(self, video_indices, audio_indices):+ """Called at the start of every transformer forward (one per step)."""+ self.step += 1+ self.indices = (video_indices, audio_indices)++ def stats(self):+ full = self.steps - len(self.hits)+ return dict(kind=self.kind, threshold=self.threshold, steps=self.steps, cached_steps=list(self.hits),+ full_forwards=full, decisions=self.decisions, source=self.source,+ disabled_reason=self.disabled_reason)++ # ---- block level: fbcache -----------------------------------------------------------------+ def _samples(self, residual):+ video, audio = self.indices+ rows = residual[0]+ return (rows.index_select(0, audio[::STRIDE])[:, ::STRIDE].float(),+ rows.index_select(0, video[::STRIDE])[:, ::STRIDE].float())++ def before_first_block(self, value):+ self.before = self._samples(value)++ def after_first_block(self, after):+ """Whether to skip the remaining blocks; on a hit `after` becomes the cached output."""+ audio, video = (now - then for now, then in zip(self._samples(after), self.before))+ self.before = None+ hit, scores = False, None+ if self.previous is not None and self.tail is not None and self.in_window() and self.consecutive < 2:+ scores = (_relative(audio, self.previous[0]), _relative(video, self.previous[1]))+ decisive = scores[1]+ hit = decisive <= self.threshold+ self.decisions.append(dict(step=self.step, audio=scores and round(scores[0], 5),+ video=scores and round(scores[1], 5), hit=hit))+ if hit:+ self.consecutive += 1+ self.hits.append(self.step)+ after.add_(self.tail)+ return True+ self.consecutive = 0+ self.previous = (audio, video)+ self.anchor = after.clone()+ return False++ def after_last_block(self, output):+ self.tail = output - self.anchor+ self.anchor = None++ # ---- model level: easycache-av --------------------------------------------------------+ def skip_forward(self, video_in, audio_in, sigmas):+ """Cached (video, audio) velocities for this step, or None to run the model."""+ return self._easycache(video_in, audio_in)++ def record_forward(self, video_in, audio_in, sigmas, video_out, audio_out):+ stride = (slice(None), slice(None, None, STRIDE))+ current_in = (video_in[stride].float(), audio_in[stride].float())+ current_out = (video_out[stride].float(), audio_out[stride].float())+ if self.prev_input is not None and self.prev_out is not None:+ rates = []+ for i in range(2):+ change_in = (current_in[i] - self.prev_input[i]).abs().mean()+ change_out = (current_out[i] - self.prev_out[i]).abs().mean()+ rates.append(float(change_out / change_in.clamp_min(1e-8)))+ self.rate = rates+ self.prev_input, self.prev_out = current_in, current_out+ self.prev_norm = [float(o.abs().mean()) for o in current_out]+ self.prev_diff = (video_out.float() - video_in.float(), audio_out.float() - audio_in.float())++ def _easycache(self, video_in, audio_in):+ reuse = False+ if self.rate is not None and self.prev_diff is not None and self.in_window():+ stride = (slice(None), slice(None, None, STRIDE))+ current = (video_in[stride].float(), audio_in[stride].float())+ predicted = [self.rate[i] * float((current[i] - self.prev_input[i]).abs().mean()) / max(self.prev_norm[i], 1e-8)+ for i in range(2)]+ self.accumulated += max(predicted)+ reuse = self.accumulated < self.threshold+ if not reuse:+ self.accumulated = 0.+ self.decisions.append(dict(step=self.step, accumulated=round(self.accumulated, 5), hit=reuse))+ if not reuse:+ return None+ self.hits.append(self.step)+ return (video_in.float() + self.prev_diff[0], audio_in.float() + self.prev_diff[1])+++def begin_pass(transformer, steps, config=None, *, offloader=None, disabled_reason=None):+ """Attach fresh state for this sampling pass; refinement never calls this."""+ wanted = requested(config)+ transformer._freevideo_step_cache = (StepCache(wanted[0], wanted[1], steps, source=wanted[2],+ offloader=offloader, disabled_reason=disabled_reason) if wanted else None)+ return transformer._freevideo_step_cache+++def end_pass(transformer):+ cache = getattr(transformer, '_freevideo_step_cache', None)+ transformer._freevideo_step_cache = None+ if cache is None:+ return None+ cache.offloader = None+ return cache.stats()diff --git a/freevideo_engine/streamed_weights.py b/freevideo_engine/streamed_weights.pyindex 87ed257..af23e44 100644--- a/freevideo_engine/streamed_weights.py+++ b/freevideo_engine/streamed_weights.py@@ -251,6 +251,24 @@ class LayerReadAhead:self.cursor = 0self._fill()+ def end_pass_early(self):+ """Cancel the unread window and rewind without reading the skipped layers."""+ self.stop.set()+ for _, future in self.pending.values():+ future.cancel()+ for _, future in self.pending.values():+ if not future.cancelled():+ try:+ future.result()+ except Exception as error:+ self.failed = self.failed or type(error).__name__ + ': ' + str(error)+ self.pending.clear()+ self.pending_bytes = 0+ self.cursor = 0+ if not self.failed and not self.closed:+ self.stop.clear()+ # before() will refill on demand; cached steps need no speculative I/O.+def stats(self):with self.lock:return dict(self.counters, enabled=True, failure=self.failed,diff --git a/freevideo_engine/tiers.py b/freevideo_engine/tiers.pynew file mode 100644index 0000000..af1131b--- /dev/null+++ b/freevideo_engine/tiers.py@@ -0,0 +1,94 @@+"""The quality levels, defined once.++Every entry (editor, Agent API, ComfyUI capabilities, estimates, docs) reads+its level -> plan mapping from here; tests/test_tiers.py checks the entries+that cannot import it (web JS, prose docs) against this table.++- light: two-pass, 8 + 3 steps.+- medium: one pass of 8 steps.+- high: one pass of 20 steps with the audio-video EasyCache.+- max: one pass of 20 steps with the first-block cache. The planner keeps that+ cache only where the card has room for it; otherwise the request samples all+ 20 steps in full (engine.json/debug record the cache actually used).++Only a two-pass level samples a second time. Single-pass levels carry+REFINE_STEPS only as the neutral value the `refine_steps` field needs; it is+never run for them. `step_cache` is the engine's cache key: None,+'easycache-av' (audio-video EasyCache) or 'fbcache' (first-block cache).++The caches are not ported to Mac (MPS) yet: there high is one pass of 16+steps and max one pass of 20, both without a cache (TIERS_MAC).+"""+import sys++REFINE_STEPS = 3+STEP_CACHES = (None, 'easycache-av', 'fbcache')++TIERS = {+ 'light': dict(steps=8, two_pass=True, step_cache=None),+ 'medium': dict(steps=8, two_pass=False, step_cache=None),+ 'high': dict(steps=20, two_pass=False, step_cache='easycache-av'),+ 'max': dict(steps=20, two_pass=False, step_cache='fbcache'),+}+TIERS_MAC = dict(TIERS, high=dict(steps=16, two_pass=False, step_cache=None),+ max=dict(steps=20, two_pass=False, step_cache=None))++# Sampling time of a cached pass as a share of the same pass without a cache,+# for estimates that have no run with that cache yet. B200, 20 s clips+# (/mnt/fvbench/eng5/tiers/RESULTS-b200.md): EasyCache-AV sampled 1.8-1.9x and+# the first-block cache 1.4-1.5x faster than plain 20 steps. 10 s clips with the+# GPU held to 8-48 GiB (/mnt/fvbench/remy/tiers-v2/REPORT.md): EasyCache-AV+# 0.48-0.75 of plain 20 steps (median about 0.6); a first-block cache kept at+# 32-48 GiB 0.71-0.82. Under the current keep rule at 8-24 GiB+# (review/quality-tiers-v2/linux-evidence.md) it is kept at 12 and 24 GiB,+# 0.81-1.28 (median 0.87), and dropped at 8 and 16 GiB. The shares are not+# fitted to the median: EasyCache-AV is slightly conservative, the first-block+# cache near the 8-24 GiB median. A first-block cache the planner did not keep+# is plain 20 steps.+SAMPLING_SHARE = {None: 1., 'easycache-av': .64, 'fbcache': .9}+++def on_mac():+ """FreeVideo runs on Apple's MPS backend on every Mac."""+ return sys.platform == 'darwin'+++def table(mac=False):+ return TIERS_MAC if mac else TIERS+++def plan(name, mac=False):+ """(two_pass, base_steps, refine_steps) of a level."""+ tier = table(mac)[name]+ return tier['two_pass'], tier['steps'], REFINE_STEPS+++def step_cache(name, mac=False):+ return table(mac)[name]['step_cache']+++def name_for(steps, two_pass, refine_steps=REFINE_STEPS, step_cache=None, mac=False):+ """The level with exactly this plan, or None for custom sampling."""+ return next((name for name, tier in table(mac).items()+ if tier['steps'] == steps and tier['two_pass'] == two_pass+ and (not two_pass or refine_steps == REFINE_STEPS) and tier['step_cache'] == step_cache), None)+++def table_level(steps, two_pass, refine_steps=REFINE_STEPS, step_cache=None, mac=False):+ """The level whose sampling table a plan needs, for naming a missing download.++ Tables follow the step count only. Prefer the exact level (the cache tells+ high from max at 20 steps), then the other platform's table (20 steps+ without a cache is "max", as on Mac; 16 steps is "high"), then the first+ level with that step count.+ """+ found = name_for(steps, two_pass, refine_steps, step_cache, mac) or name_for(+ steps, two_pass, refine_steps, step_cache, not mac)+ return found or next((name for name, tier in TIERS.items()+ if tier['steps'] == steps and tier['two_pass'] == two_pass+ and (not two_pass or refine_steps == REFINE_STEPS)), None)+++def sampling_share(cache):+ """Estimated sampling time with this effective cache, as a share of the plain pass."""+ return SAMPLING_SHARE.get(cache, 1.)diff --git a/scripts/test_freevideo_entry.mjs b/scripts/test_freevideo_entry.mjsindex 35d9e85..bf0ca41 100644--- a/scripts/test_freevideo_entry.mjs+++ b/scripts/test_freevideo_entry.mjs@@ -185,6 +185,8 @@ test('main browser entry registers both views and preserves node hooks', async t['continue_from', 'Continue from video', '接着生成', 'previous.mp4'],['frames', 'Total frames', '帧数', 141],['first_frame_reference', 'First-frame reference', '首帧参考', true, '减小漂移'],+ ['step_cache', 'Step cache', '步间缓存', 'none',+ '复用相近采样步之间的计算,更快完成,结果会有细微变化。精细档用 easycache-av,极致档用 fbcache。'],['voice_reference', 'Voice reference', 'Voice reference', true],['hide_tail', 'Hide dialogue tail', 'Hide dialogue tail', true],];diff --git a/web/capability_view.js b/web/capability_view.jsindex 9df6df1..ec2e6b8 100644--- a/web/capability_view.js+++ b/web/capability_view.js@@ -1,4 +1,5 @@import { referenceItems } from './prompt_references.js';+import { stepCacheOf } from './sampling_effort.js';const PRESETS = [.5, .75, .98, 1.5, 2];const COLUMN_SPACING = 'equal'; // 'equal' or 'width'@@ -44,7 +45,7 @@ export function aboutTime(seconds, t) {// documented task fallback, rather than pretending the known subset is all of it.export function capabilityContext(node, state) {if (linked(node, 'conditioning') || linked(node, 'width') || linked(node, 'height')- || ['base_steps', 'refine_steps', 'two_pass'].some(name => linked(node, name))) return null;+ || ['base_steps', 'refine_steps', 'two_pass', 'step_cache'].some(name => linked(node, name))) return null;let items, assets;try { items = referenceItems(node); assets = JSON.parse(value(upstream(node, 'media'), 'assets') || '[]'); }catch { return null; }@@ -76,12 +77,15 @@ export function capabilityContext(node, state) {return query.toString();}+// The grid's level with exactly this plan; a step cache tells High from Max at 20 steps.+const gridTier = (grid, steps, twoPass, refine, stepCache) => Object.values(grid.tiers || {}).find(v => v.steps === steps+ && v.two_pass === twoPass && (!v.two_pass || refine === 3) && stepCacheOf(v.step_cache) === stepCacheOf(stepCache));+export function capabilitySurface(grid, state) {if (grid?.version !== 1 || grid.status !== 'ready' || typeof grid.revision !== 'string' || !grid.machine?.system|| /darwin|mac|apple/i.test(grid.machine.system)|| !Array.isArray(grid.sizes) || !grid.sizes.length || !Array.isArray(grid.lengths)) return null;- const tier = Object.values(grid.tiers || {}).find(v => v.steps === state.steps && v.two_pass === state.twoPass- && (!v.two_pass || state.refine === 3));+ const tier = gridTier(grid, state.steps, state.twoPass, state.refine, state.stepCache);if (!tier || !Array.isArray(tier.estimate_seconds) || !Array.isArray(tier.max_seconds)) return null;const lengths = grid.lengths.map(l => l.seconds);if (!lengths.length || lengths.some((s, i) => !Number.isInteger(s) || s < 2 || (i && s <= lengths[i - 1]))) return null;@@ -171,7 +175,7 @@ export function surfacePixels(surface, width, height) {}let serial = 0;-export function createCapabilityView({node, api, t, getState, onPick, onEstimate}) {+export function createCapabilityView({node, api, t, getState, onPick, onEstimate, onGrid}) {if (!document.querySelector('link[data-fv-capability]')) {const css = el('link', ''); css.rel = 'stylesheet'; css.dataset.fvCapability = '';css.href = new URL('./capability_view.css', import.meta.url).href; document.head.append(css);@@ -241,7 +245,7 @@ export function createCapabilityView({node, api, t, getState, onPick, onEstimatefunction paint(animate = false) {if (!surface || !opened || element.hidden || !plot.clientWidth) return;const dpr = Math.max(1, window.devicePixelRatio || 1), width = Math.round(plot.clientWidth * dpr), height = Math.round(plot.clientHeight * dpr);- const key = `${grid.revision}:${getState().steps}:${getState().twoPass}:${width}:${height}:${query}`;+ const key = `${grid.revision}:${getState().steps}:${getState().twoPass}:${stepCacheOf(getState().stepCache)}:${width}:${height}:${query}`;if (key === drawn) { current(); return; }drawn = key;if (animate && canvas.width && !matchMedia('(prefers-reduced-motion: reduce)').matches) {@@ -266,6 +270,7 @@ export function createCapabilityView({node, api, t, getState, onPick, onEstimatecurrent(); hideHover();}function applyGrid(animate = false) {+ if (grid?.version === 1 && grid.status === 'ready') onGrid?.(grid);surface = capabilitySurface(grid, getState()); element.hidden = !surface;onEstimate?.();if (!surface) { hideHover(); return; }@@ -370,9 +375,9 @@ export function createCapabilityView({node, api, t, getState, onPick, onEstimateapi.addEventListener('freevideo_capabilities', changed);const outside = event => { if (!plot.contains(event.target)) hideHover(); };node && window.addEventListener('pointerdown', outside);- return {element, update, estimate(steps, twoPass, refine) {+ return {element, update, estimate(steps, twoPass, refine, stepCache = null) {if (!grid || !surface) return '';- const tier = Object.values(grid.tiers || {}).find(v => v.steps === steps && v.two_pass === twoPass && (!twoPass || refine === 3));+ const tier = gridTier(grid, steps, twoPass, refine, stepCache);const i = grid.sizes.findIndex(s => s.width === Number(value(node, 'width')) && s.height === Number(value(node, 'height')));const j = grid.lengths.findIndex(l => l.seconds === Number(value(node, 'seconds')));const seconds = tier?.estimate_seconds?.[i]?.[j];diff --git a/web/chain_support.js b/web/chain_support.jsindex 9471f2a..94ab4f2 100644--- a/web/chain_support.js+++ b/web/chain_support.js@@ -1,5 +1,6 @@// Pure helpers the creative panel's long-video planning shares with the editor store; kept out of// editor_store.js so the panel does not load the editing implementation.+import { stepCacheOf } from './sampling_effort.js';const clockDefault = {now: () => Date.now(), setTimeout: (fn, ms) => setTimeout(fn, ms), clearTimeout: id => clearTimeout(id)};export const chainRoute = (id, action) => '/freevideo/chain' + (id ? '/' + encodeURIComponent(id) : '') + (action ? '/' + action : '');@@ -37,9 +38,9 @@ function capabilityTier(reply, settings) {const tiers = reply.tiers;if (!tiers || typeof tiers !== 'object') return reply;if (tiers[settings?.tier]) return tiers[settings.tier];- const steps = Number(settings?.base_steps), twoPass = !!settings?.two_pass;+ const steps = Number(settings?.base_steps), twoPass = !!settings?.two_pass, cache = stepCacheOf(settings?.step_cache);return Object.values(tiers).find(tier => tier.steps === steps && tier.two_pass === twoPass- && (!twoPass || Number(settings?.refine_steps) === 3)) || {};+ && (!twoPass || Number(settings?.refine_steps) === 3) && stepCacheOf(tier.step_cache) === cache) || {};}export function capabilityPoints(reply, {width, height, settings = {}}) {const tier = capabilityTier(reply, settings);diff --git a/web/editor_entry.js b/web/editor_entry.jsindex 9966774..2c9aab2 100644--- a/web/editor_entry.js+++ b/web/editor_entry.js@@ -11,7 +11,7 @@ function editorPanel(node) {const values = Object.fromEntries((node.widgets || []).filter(widget => widget.name).map(widget => [widget.name, widget.value]));return {node: node.id, width: values.width, height: values.height, text: values.text || '', settings: Object.fromEntries(Object.entries({two_pass: values.two_pass, base_steps: values.base_steps, refine_steps: values.refine_steps,- seed: values.seed, sampling_effort: values.sampling_effort}).filter(([, value]) => value !== undefined)),+ step_cache: values.step_cache, seed: values.seed, sampling_effort: values.sampling_effort}).filter(([, value]) => value !== undefined)),references: mediaReferences(node),async snapshot() {if (node.freevideoEditorLooping?.()) throw new Error('loop_active');diff --git a/web/error_panel.js b/web/error_panel.jsindex c9d38de..2c23dad 100644--- a/web/error_panel.js+++ b/web/error_panel.js@@ -1,5 +1,6 @@// Shared by the Studio and graph view. Text only; never render exception HTML.import {detectBrowserExtension, browserExtensionAdvice, extensionSteps} from './browser_extension.js';+import {SAMPLING_EFFORTS, STEP_CACHES, tableLevel} from './sampling_effort.js';const reports = new WeakSet();const captured = new WeakMap();const diagnosticReports = new WeakSet();@@ -72,9 +73,11 @@ function knownError(text) {if (Number.isInteger(d.base_steps) && d.base_steps >= 1 && d.base_steps <= 32&& typeof d.two_pass === 'boolean' && Number.isInteger(d.refine_steps) && d.refine_steps >= 0 && d.refine_steps <= 31&& Number.isSafeInteger(d.missing_bytes) && d.missing_bytes > 0 && typeof d.decimal_sizes === 'boolean'- && Array.isArray(d.available) && d.available.every(i => Number.isInteger(i) && i >= 0 && i <= 3))+ && Array.isArray(d.available) && d.available.every(i => Number.isInteger(i) && i >= 0 && i <= 3)+ && (d.step_cache === undefined || STEP_CACHES.includes(d.step_cache)))return {kind: 'sampling-table', base_steps: d.base_steps, two_pass: d.two_pass, refine_steps: d.refine_steps,- missing_bytes: d.missing_bytes, decimal_sizes: d.decimal_sizes, available: [...new Set(d.available)].sort()};+ missing_bytes: d.missing_bytes, decimal_sizes: d.decimal_sizes, available: [...new Set(d.available)].sort(),+ ...(d.step_cache ? {step_cache: d.step_cache} : {})};} catch { /* Malformed metadata stays in technical details. */ }}return PLAIN_ERRORS.find(error => line === error.message || error.aliases?.includes(line))?.key ?? null;@@ -214,6 +217,8 @@ export function createErrorReport(detail, context = {}) {const value = Array.isArray(inputs?.[key]) && inputs[key].length === 1 ? inputs[key][0] : inputs?.[key];if (typeof value === 'boolean' || typeof value === 'number' && Number.isFinite(value)) settings[key] = value;}+ const cache = Array.isArray(inputs?.step_cache) && inputs.step_cache.length === 1 ? inputs.step_cache[0] : inputs?.step_cache;+ if (typeof cache === 'string' && (cache === 'none' || STEP_CACHES.includes(cache))) settings.step_cache = cache;const progress = {};for (const key of ['phase', 'stage']) if (typeof context.progress?.[key] === 'string') progress[key] = clean(context.progress[key]);for (const key of ['done', 'total']) if (Number.isFinite(context.progress?.[key])) progress[key] = context.progress[key];@@ -258,9 +263,9 @@ export function failureAdvice(value, t, known = knownError(value)) {const row = (kind, title, summary, action) => ({kind, title: t(...title), summary: t(...summary), action: t(...action)});if (known?.kind === 'sampling-table') {// Names and plan matching follow sampling_effort.js; metadata carries no user text.- const levels = [['Light', '轻量'], ['Medium', '标准'], ['High', '精细'], ['Max', '极致']];- const index = [8, 12, 16, 20].findIndex((steps, i) => known.base_steps === steps- && known.two_pass === (i === 0) && (i !== 0 || known.refine_steps === 3));+ const levels = SAMPLING_EFFORTS.map(tier => [tier.name, tier.zh]);+ const level = tableLevel(known.base_steps, known.two_pass, known.refine_steps, known.step_cache ?? null);+ const index = SAMPLING_EFFORTS.findIndex(tier => tier.name === level?.name);const custom = index < 0;// Iris: a level name and its 档 never break apart. The summary is set as text,// so word joiners (U+2060) keep each group on one line instead of markup.diff --git a/web/freevideo.js b/web/freevideo.jsindex bb1dfaa..ad369b7 100644--- a/web/freevideo.js+++ b/web/freevideo.js@@ -751,6 +751,7 @@ app.registerExtension({['continue_from', '接着生成'],['frames', '帧数'],['first_frame_reference', '首帧参考', '减小漂移'],+ ['step_cache', '步间缓存', '复用相近采样步之间的计算,更快完成,结果会有细微变化。精细档用 easycache-av,极致档用 fbcache。'],]) {const widget = this.widgets?.find(w => w.name === name);if (widget) {diff --git a/web/prompt_draft.js b/web/prompt_draft.jsindex 7fa30fa..9b8e419 100644--- a/web/prompt_draft.js+++ b/web/prompt_draft.js@@ -2,9 +2,12 @@// alongside the existing schema-1 prompt draft; ordinary reloads keep their graph.const FILE = '/userdata/' + encodeURIComponent('freevideo/prompt-draft.json');const WIDGETS = ['text', 'width', 'height', 'seconds', 'seed', 'control_after_generate', 'two_pass',- 'base_steps', 'refine_steps', 'force_regenerate', 'preview', 'refine_from', 'continue_from', 'frames', 'first_frame_reference'];-const DEFAULTS = ['', 1344, 768, 10, 2026090903, 'randomize', true, 8, 3, false, false, '', '', 0, false];-const SAVED_WIDGETS = WIDGETS.filter(name => !['text', 'force_regenerate', 'refine_from', 'continue_from', 'frames'].includes(name));+ 'base_steps', 'refine_steps', 'force_regenerate', 'preview', 'refine_from', 'continue_from', 'frames', 'first_frame_reference',+ 'voice_reference', 'hide_tail', 'step_cache'];+const DEFAULTS = ['', 1344, 768, 10, 2026090903, 'randomize', true, 8, 3, false, false, '', '', 0, false, false, false, 'none'];+const SAVED_WIDGETS = WIDGETS.filter(name => !['text', 'force_regenerate', 'refine_from', 'continue_from', 'frames',+ 'voice_reference', 'hide_tail'].includes(name));+const STEP_CACHE_OPTIONS = ['none', 'easycache-av', 'fbcache'];const PROPERTIES = ['freevideo_aspect', 'freevideo_pixels', 'freevideo_seconds', 'freevideo_single','freevideo_block_seconds', 'freevideo_run_mode', 'freevideo_batch_count'];const OUTBOX = 'freevideo.prompt-pending';@@ -46,7 +49,8 @@ export function applyPromptDraft(workflow, draft) {for (const name of SAVED_WIDGETS) {const value = draft.widgets?.[name], index = WIDGETS.indexOf(name);if (value === undefined || typeof value !== typeof DEFAULTS[index]- || (typeof value === 'number' && !Number.isFinite(value))) continue;+ || (typeof value === 'number' && !Number.isFinite(value))+ || (name === 'step_cache' && !STEP_CACHE_OPTIONS.includes(value))) continue;while (node.widgets_values.length <= index) node.widgets_values.push(DEFAULTS[node.widgets_values.length]);node.widgets_values[index] = value;}diff --git a/web/sampling_effort.js b/web/sampling_effort.jsindex 40ffcd9..966b2df 100644--- a/web/sampling_effort.js+++ b/web/sampling_effort.js@@ -1,20 +1,54 @@// One editor control. The queued request remains an immutable graph snapshot.-// Each level is a complete plan: Light is two-pass 8 + 3; the others sample once.-export const SAMPLING_EFFORTS = Object.freeze([- {name: 'Light', zh: '轻量', steps: 8, twoPass: true, color: '#3dd6b5'},- {name: 'Medium', zh: '标准', steps: 12, twoPass: false, color: '#4ea8ff'},- {name: 'High', zh: '精细', steps: 16, twoPass: false, color: '#9d7bff'},- {name: 'Max', zh: '极致', steps: 20, twoPass: false, color: '#ffa94d'},-].map(Object.freeze));+// Each level is a complete plan (freevideo_engine/tiers.py): Light is two-pass 8 + 3;+// the others sample once, High and Max with a step cache.+const frozen = rows => Object.freeze(rows.map(row => Object.freeze({...row})));+export const SAMPLING_EFFORTS = frozen([+ {name: 'Light', zh: '轻量', steps: 8, twoPass: true, stepCache: null, color: '#3dd6b5'},+ {name: 'Medium', zh: '标准', steps: 8, twoPass: false, stepCache: null, color: '#4ea8ff'},+ {name: 'High', zh: '精细', steps: 20, twoPass: false, stepCache: 'easycache-av', color: '#9d7bff'},+ {name: 'Max', zh: '极致', steps: 20, twoPass: false, stepCache: 'fbcache', color: '#ffa94d'},+]);+// Mac (MPS) has no step caches yet: High samples 16 steps and Max 20, both in full.+const MAC = {High: {steps: 16, stepCache: null}, Max: {stepCache: null}};+export const SAMPLING_EFFORTS_MAC = frozen(SAMPLING_EFFORTS.map(tier => ({...tier, ...MAC[tier.name]})));export const effortName = (t, tier) => t(tier.name, tier.zh);+export const STEP_CACHES = Object.freeze([null, 'easycache-av', 'fbcache']);++// The cache a `step_cache` value names; 'none', '' and a missing value sample in full.+export const stepCacheOf = value => (typeof value === 'string' && value && value !== 'none' ? value : null);++// The levels of the machine a capability grid describes: its own table when the+// grid lists one, else the Mac table on a Mac, else the default table.+export function effortsFrom(grid) {+ const base = grid?.machine?.system === 'Darwin' ? SAMPLING_EFFORTS_MAC : SAMPLING_EFFORTS;+ const tiers = grid?.tiers;+ if (!tiers || typeof tiers !== 'object') return base;+ return frozen(base.map(tier => {+ const row = tiers[tier.name.toLowerCase()];+ if (!row || !Number.isInteger(row.steps) || typeof row.two_pass !== 'boolean') return tier;+ return {...tier, steps: row.steps, twoPass: row.two_pass,+ stepCache: 'step_cache' in row ? stepCacheOf(row.step_cache) : tier.stepCache};+ }));+}// The level a plan matches, or undefined for custom steps.-export function effortFor(steps, twoPass, refine) {- return SAMPLING_EFFORTS.find(tier => tier.steps === steps && tier.twoPass === twoPass && (!twoPass || refine === 3));+export function effortFor(steps, twoPass, refine, stepCache = null, levels = SAMPLING_EFFORTS) {+ const cache = stepCacheOf(stepCache);+ return levels.find(tier => tier.steps === steps && tier.twoPass === twoPass && (!twoPass || refine === 3)+ && tier.stepCache === cache);}-export function createSamplingEffort(t, {onChange, onPreview = () => {}}) {+// The level whose sampling table a plan needs, for naming a missing download (tiers.table_level):+// the exact level of either table (the cache tells High from Max at 20 steps; 20 steps+// without a cache is Max and 16 steps High, as on Mac), else the first level with those steps.+export function tableLevel(steps, twoPass, refine, stepCache = null) {+ return effortFor(steps, twoPass, refine, stepCache) || effortFor(steps, twoPass, refine, stepCache, SAMPLING_EFFORTS_MAC)+ || SAMPLING_EFFORTS.find(tier => tier.steps === steps && tier.twoPass === twoPass && (!twoPass || refine === 3));+}++export function createSamplingEffort(t, {onChange, onPreview = () => {}, levels = SAMPLING_EFFORTS}) {+ let efforts = levels;const el = (tag, cls, text) => { const e = document.createElement(tag); e.className = cls; if (text) e.textContent = text; return e; };const element = el('div', 'fv-effort');const header = el('div', 'fv-effort-heading');@@ -33,7 +67,7 @@ export function createSamplingEffort(t, {onChange, onPreview = () => {}}) {const knob = el('span', 'fv-effort-knob'); track.append(knob); rail.append(track);knob.addEventListener('animationend', () => knob.classList.remove('fv-effort-pop'));const names = el('div', 'fv-effort-names');- const nameButtons = SAMPLING_EFFORTS.map((tier, i) => {+ const nameButtons = efforts.map((tier, i) => {const b = el('button', 'fv-effort-name', effortName(t, tier)); b.type = 'button'; b.tabIndex = -1;b.style.setProperty('--fv-stop', i / 3);b.onclick = () => { if (!disabled && pointer === null) commit(i); };@@ -41,10 +75,10 @@ export function createSamplingEffort(t, {onChange, onPreview = () => {}}) {});const custom = el('span', 'fv-effort-custom', t('Custom steps', '自定义步数')); custom.hidden = true;element.append(header, rail, names, custom);- let selected = 0, disabled = false, pointer = null, draft = 0, currentSteps = 8, currentRefine = 3, twoPass = true;+ let selected = 0, disabled = false, pointer = null, draft = 0, currentSteps = 8, currentRefine = 3, twoPass = true, stepCache = null, reason = '';function paint(position) {element.style.setProperty('--fv-position', position / 3);- const index = Math.round(position), tier = SAMPLING_EFFORTS[index];+ const index = Math.round(position), tier = efforts[index];nameButtons.forEach((b, i) => b.toggleAttribute('data-active', i === index));stops.forEach((stop, i) => stop.toggleAttribute('data-filled', i <= position + .01));rail.setAttribute('aria-valuenow', String(index));@@ -57,13 +91,13 @@ export function createSamplingEffort(t, {onChange, onPreview = () => {}}) {}function commit(index) {selected = index; custom.hidden = true; delete element.dataset.custom;- paint(index); onChange(SAMPLING_EFFORTS[index]);+ paint(index); onChange(efforts[index]);knob.classList.remove('fv-effort-pop'); void knob.offsetWidth; knob.classList.add('fv-effort-pop');}function cancel() {const id = pointer; pointer = null; delete rail.dataset.dragging;if (id !== null && rail.hasPointerCapture(id)) rail.releasePointerCapture(id);- update({baseSteps: currentSteps, refineSteps: currentRefine, twoPass, disabled});+ update({baseSteps: currentSteps, refineSteps: currentRefine, twoPass, stepCache, disabled, reason});onPreview(null);}rail.onpointerdown = event => {@@ -71,11 +105,11 @@ export function createSamplingEffort(t, {onChange, onPreview = () => {}}) {if (disabled || event.button !== 0 || pointer !== null) return;event.preventDefault(); rail.focus({preventScroll: true, focusVisible: false}); pointer = event.pointerId;rail.setPointerCapture(pointer); rail.dataset.dragging = 'true';- draft = position(event); paint(draft); onPreview(SAMPLING_EFFORTS[Math.round(draft)]);+ draft = position(event); paint(draft); onPreview(efforts[Math.round(draft)]);};rail.onpointermove = event => {if (event.pointerId !== pointer) return;- draft = position(event); paint(draft); onPreview(SAMPLING_EFFORTS[Math.round(draft)]);+ draft = position(event); paint(draft); onPreview(efforts[Math.round(draft)]);};rail.onpointerup = event => {if (event.pointerId !== pointer) return;@@ -95,21 +129,30 @@ export function createSamplingEffort(t, {onChange, onPreview = () => {}}) {};function update(state) {currentSteps = Number(state.baseSteps); currentRefine = Number(state.refineSteps);- twoPass = state.twoPass; disabled = state.disabled;+ twoPass = state.twoPass; stepCache = stepCacheOf(state.stepCache); disabled = state.disabled; reason = state.reason || '';rail.tabIndex = disabled ? -1 : 0; rail.setAttribute('aria-disabled', String(disabled));element.dataset.disabled = String(disabled);if (pointer !== null) return;- const exact = SAMPLING_EFFORTS.findIndex(v => v.steps === currentSteps);- selected = exact < 0 ? SAMPLING_EFFORTS.reduce((best, v, i) => Math.abs(v.steps - currentSteps) < Math.abs(SAMPLING_EFFORTS[best].steps - currentSteps) ? i : best, 0) : exact;- const isCustom = !effortFor(currentSteps, twoPass, currentRefine);+ const level = effortFor(currentSteps, twoPass, currentRefine, stepCache, efforts);+ // Custom steps sit at the nearest level, preferring one with the same pass count.+ const distance = v => Math.abs(v.steps - currentSteps) * 2 + (v.twoPass !== twoPass);+ selected = level ? efforts.indexOf(level) : efforts.reduce((best, v, i) => distance(v) < distance(efforts[best]) ? i : best, 0);+ const isCustom = !level;element.dataset.custom = String(isCustom); custom.hidden = !isCustom;const unit = currentSteps === 1 && !twoPass ? t('step', '步') : t('steps', '步');custom.textContent = `${t('Custom', '自定义')} · ${currentSteps}${twoPass ? ' + ' + currentRefine : ''} ${unit}`;paint(selected);if (isCustom) rail.setAttribute('aria-valuetext', custom.textContent);- rail.title = disabled ? state.reason || t('Controlled by connected nodes.', '由连接的节点控制。')+ rail.title = disabled ? reason || t('Controlled by connected nodes.', '由连接的节点控制。'): t('Same model. Higher effort uses more sampling steps; results vary by scene.', '使用同一模型,提高档位会增加采样步数;效果因场景而异。');for (const name of nameButtons) { name.disabled = disabled; name.title = ''; }}- return {element, update, setEstimate(text, title = '') { estimate.textContent = text; if (title) estimate.title = title; else estimate.removeAttribute('title'); }, dispose: cancel};+ // The machine's own table (effortsFrom); the names stay, the plans follow the machine.+ function setLevels(next) {+ const same = (a, b) => a.steps === b.steps && a.twoPass === b.twoPass && a.stepCache === b.stepCache;+ if (!next || next.length !== efforts.length || next.every((tier, i) => same(tier, efforts[i]))) return;+ efforts = next;+ update({baseSteps: currentSteps, refineSteps: currentRefine, twoPass, stepCache, disabled, reason});+ }+ return {element, update, setLevels, levels: () => efforts, setEstimate(text, title = '') { estimate.textContent = text; if (title) estimate.title = title; else estimate.removeAttribute('title'); }, dispose: cancel};}diff --git a/web/share.js b/web/share.jsindex ddc034a..f0aea76 100644--- a/web/share.js+++ b/web/share.js@@ -1,6 +1,6 @@import {api} from '../../scripts/api.js';import {closeDialog} from './motion.js';-import {effortFor, effortName} from './sampling_effort.js';+import {SAMPLING_EFFORTS_MAC, effortFor, effortName} from './sampling_effort.js';import {fontCSS as bundledFontCSS, fontLoaded, loadFont} from './fonts.js';import {shareLayout} from './share_layout.js';import {videoUnavailableText} from './studio_extend.js';@@ -38,7 +38,9 @@ export function drawShareCard(canvas,frame,logo,record,t) {const ctx=canvas.getContext('2d'),w=shape.width,y=shape.rect[3],H=shape.footer,pad=44,wide=w>=1000;const p=record.sampling_plan||{},steps=p.base_steps,refine=p.enabled?p.refine_steps:0;// Results made with the earlier 8 + 2 default count as Light.- const tier=effortFor(steps,!!p.enabled,p.enabled&&steps===8&&refine===2?3:refine), accent=tier?.color||'#8fa3bb';+ // A Mac result names its level from the Mac table (High 16 steps, Max 20 without a cache).+ const plan=[steps,!!p.enabled,p.enabled&&steps===8&&refine===2?3:refine,p.step_cache??null];+ const tier=effortFor(...plan)||effortFor(...plan,SAMPLING_EFFORTS_MAC), accent=tier?.color||'#8fa3bb';ctx.fillStyle='#0b1016';ctx.fillRect(0,0,w,shape.height);ctx.clearRect(...shape.rect);const bg=ctx.createLinearGradient(0,y,0,y+H);bg.addColorStop(0,'#131b26');bg.addColorStop(1,'#0b1016');ctx.fillStyle=bg;ctx.fillRect(0,y,w,H);diff --git a/web/studio.js b/web/studio.jsindex 2816d03..ce44606 100644--- a/web/studio.js+++ b/web/studio.js@@ -25,7 +25,7 @@ import { attachMentionOverlay } from './cast_overlay.js';import { openCastLibrary } from './cast_source.js';import { uploadMedia } from './media_upload.js';import { reconcileLoraTriggers } from './lora_triggers.js';-import { createSamplingEffort } from './sampling_effort.js';+import { createSamplingEffort, effortFor, effortsFrom, stepCacheOf } from './sampling_effort.js';import { resultActions, previewBadge, icon, actionsUnavailable } from './result_actions.js';import { createPromptEnhancer } from './prompt_enhance.js';import { createRequestAssets, enabledLoras, referenceFiles } from './request_assets.js';@@ -672,6 +672,9 @@ export function openStudio(node, {extendFrom = null} = {}) {});twoPassLabel.append(el('span', t('Two-pass', '二次采样')), twoPassStatus, passMode);let effortEstimate = {}, effortEstimateKey = '', effortEstimateTimer = null, effortEstimateRequest = null, lengthControl = null, chainController = null;+ // A level's step cache; custom steps and workflows without the input sample every step.+ const stepCacheNow = () => stepCacheOf(value(node, 'step_cache'));+ const clearStepCache = () => { if (stepCacheNow()) set(node, 'step_cache', 'none'); };const effort = createSamplingEffort(t, {onChange: tier => {baseSteps.value = tier.steps;refineSteps.value = 3;@@ -679,14 +682,15 @@ export function openStudio(node, {extendFrom = null} = {}) {autoSinglePass = false;set(node, 'two_pass', twoPass.checked);set(node, 'refine_steps', 3);+ set(node, 'step_cache', tier.stepCache || 'none');syncSamplingSteps();- }, onPreview: tier => tier ? showEffortEstimate(tier.steps, tier.twoPass) : showEffortEstimate()});+ }, onPreview: tier => tier ? showEffortEstimate(tier.steps, tier.twoPass, tier.stepCache) : showEffortEstimate()});const samplingSettings = el('div', null, 'fv-sampling-settings');const previewFirst = el('input'); previewFirst.type = 'checkbox'; previewFirst.checked = value(node, 'preview') === true;function choosePassMode(mode) {if (extension.source) return;const wantsTwoPass = mode !== 'off', wantsPreview = mode === 'preview';- if (twoPass.checked !== wantsTwoPass) { twoPass.checked = wantsTwoPass; autoSinglePass = false; set(node, 'two_pass', wantsTwoPass); }+ if (twoPass.checked !== wantsTwoPass) { twoPass.checked = wantsTwoPass; autoSinglePass = false; set(node, 'two_pass', wantsTwoPass); clearStepCache(); }if (previewFirst.checked !== wantsPreview) { previewFirst.checked = wantsPreview; set(node, 'preview', wantsPreview); }syncSamplingSteps(); updateRunButton();}@@ -775,6 +779,8 @@ export function openStudio(node, {extendFrom = null} = {}) {input.onchange = () => input.reportValidity();samplingFields.append(field(label, input));}+ // Typed steps are custom sampling, which has no step cache.+ baseSteps.oninput = () => { clearStepCache(); syncSamplingSteps(); };// Apply the two-pass rule to committed values, never while typing.baseSteps.onchange = () => {// Before validation: one step is valid only once two-pass is off.@@ -790,7 +796,7 @@ export function openStudio(node, {extendFrom = null} = {}) {// The run button exists only further down; until then its label is set there.let runButtonReady = false;function syncSamplingSteps() {- if (extension.source) { baseSteps.value = '8'; refineSteps.value = '3'; twoPass.checked = true; set(node, 'two_pass', true); autoSinglePass = false; }+ if (extension.source) { baseSteps.value = '8'; refineSteps.value = '3'; twoPass.checked = true; set(node, 'two_pass', true); clearStepCache(); autoSinglePass = false; }const baseLinked = linked(node, 'base_steps');// Two-pass is offered at 8 first-pass steps. A saved workflow that already// uses it with other steps is shown as custom and left unchanged.@@ -819,13 +825,14 @@ export function openStudio(node, {extendFrom = null} = {}) {}}effort.update({baseSteps: Number(baseSteps.value), refineSteps: Number(refineSteps.value),- twoPass: twoPass.checked, disabled: baseSteps.disabled || linked(node, 'two_pass') || linked(node, 'refine_steps'),+ twoPass: twoPass.checked, stepCache: stepCacheNow(),+ disabled: baseSteps.disabled || linked(node, 'two_pass') || linked(node, 'refine_steps') || linked(node, 'step_cache'),reason: extension.source ? t('A continuation uses the Light level.', '接着生成使用轻量档。') : ''});refreshEffortEstimate();}syncSamplingSteps();advanced.append(samplingFields, samplingWarning);- function showEffortEstimate(steps = Number(baseSteps.value), twoPassPlan = twoPass.checked) {+ function showEffortEstimate(steps = Number(baseSteps.value), twoPassPlan = twoPass.checked, cache = stepCacheNow()) {const parts = lengthControl.plan?.count > 1 ? t(`${lengthControl.plan.count} parts`, `分 ${lengthControl.plan.count} 段`) : '';// A request that fits one run keeps its own estimate while the longest run is unknown.if ((lengthControl.capabilityState === 'pending' || lengthControl.capabilityState === 'unavailable')@@ -838,16 +845,16 @@ export function openStudio(node, {extendFrom = null} = {}) {if (lengthControl.needsPlan && !lengthControl.plan) { effort.setEstimate(''); return; }if (lengthControl.plan?.count > 1) {const plan = lengthControl.plan;- const seconds = steps === Number(baseSteps.value) && twoPassPlan === twoPass.checked+ const seconds = steps === Number(baseSteps.value) && twoPassPlan === twoPass.checked && cache === stepCacheNow()? sumPartEstimates(plan, lengthControl.estimate) : null;effort.setEstimate(seconds > 0 ? t(`${plan.count} parts · about ${Math.ceil(seconds / 60)} min`, `分 ${plan.count} 段 · 约 ${Math.ceil(seconds / 60)} 分钟`): t(`${plan.count} parts`, `分 ${plan.count} 段`));return;}- const rangeEstimate = capabilityView?.estimate(steps, twoPassPlan, arguments.length ? 3 : Number(refineSteps.value));+ const rangeEstimate = capabilityView?.estimate(steps, twoPassPlan, arguments.length ? 3 : Number(refineSteps.value), cache);if (rangeEstimate) { effort.setEstimate(rangeEstimate); return; }const mode = twoPassPlan ? 'two_pass' : 'single';- const estimate = effortEstimate[mode]?.[steps];+ const estimate = effortEstimate[mode]?.[cache ? `${steps}:${cache}` : String(steps)];// A previewed level always refines three steps; the current plan may not.if (estimate?.status !== 'estimated' || (mode === 'two_pass' && !arguments.length && Number(refineSteps.value) !== 3)) {effort.setEstimate('', t('No estimate is available for these settings.', '当前设置暂无预计用时。'));@@ -880,8 +887,9 @@ export function openStudio(node, {extendFrom = null} = {}) {const requestWidth = extension.source?.geometry.width ?? value(node, 'width');const requestHeight = extension.source?.geometry.height ?? value(node, 'height');lengthControl?.refresh({width: requestWidth, height: requestHeight, task, adapters,- settings: {tier: twoPass.checked ? 'light' : ({12: 'medium', 16: 'high', 20: 'max'}[Number(baseSteps.value)] || 'custom'),- base_steps: Number(baseSteps.value), refine_steps: Number(refineSteps.value), two_pass: twoPass.checked}}, force);+ settings: {tier: effortFor(Number(baseSteps.value), twoPass.checked, Number(refineSteps.value), stepCacheNow(), effort.levels())?.name.toLowerCase() || 'custom',+ base_steps: Number(baseSteps.value), refine_steps: Number(refineSteps.value), two_pass: twoPass.checked,+ step_cache: stepCacheNow()}}, force);requestAssetsQuery = () => {const query = new URLSearchParams({width: requestWidth, height: requestHeight, seconds: value(node, 'seconds'), task,base_steps: baseSteps.value, refine_steps: refineSteps.value, two_pass: twoPass.checked ? '1' : '0',@@ -1581,7 +1589,8 @@ export function openStudio(node, {extendFrom = null} = {}) {dialog.onclose = () => { disposed = true; for (const f of cleanup) f(); stage.querySelector('video')?.pause(); dialog.remove(); if (current?.dialog === dialog) { current = null; viewChanged('nodes', node); } };capabilityView = createCapabilityView({node, api, t, getState: () => ({ratio,custom: selected === 'custom', steps: Number(baseSteps.value), twoPass: twoPass.checked,- refine: Number(refineSteps.value), disabled: Boolean(extension.source) || dimensionsLinked || seconds.disabled}), onEstimate: () => showEffortEstimate(), onPick: point => {+ refine: Number(refineSteps.value), stepCache: stepCacheNow(), disabled: Boolean(extension.source) || dimensionsLinked || seconds.disabled}),+ onEstimate: () => showEffortEstimate(), onGrid: grid => effort.setLevels(effortsFrom(grid)), onPick: point => {pixels = point.pixels; mp.value = String(pixels);set(node, 'width', point.width); set(node, 'height', point.height);node.properties.freevideo_pixels = pixels;diff --git a/web/studio_extend.js b/web/studio_extend.jsindex 31c4c03..a5453ac 100644--- a/web/studio_extend.js+++ b/web/studio_extend.js@@ -56,7 +56,7 @@ export async function readExtendRecord(api, record) {}export function createExtendState(node, read, write) {- const keys = ['width', 'height', 'seconds', 'two_pass', 'preview', 'base_steps', 'refine_steps'];+ const keys = ['width', 'height', 'seconds', 'two_pass', 'preview', 'base_steps', 'refine_steps', 'step_cache'];return {get source() { return node.properties?.[EXTEND_PROPERTY]?.source || null; },enter(record) {@@ -76,8 +76,8 @@ export function createExtendState(node, read, write) {node.properties[EXTEND_PROPERTY] = {source, previous};for (const [key, value] of Object.entries({width: g.width, height: g.height,seconds: Math.min(60, seconds), text: '', preview: false,- // A continuation always runs the Light plan: two passes, 8 + 3 steps.- two_pass: true, base_steps: 8, refine_steps: 3})) write(key, value);+ // A continuation always runs the Light plan: two passes, 8 + 3 steps, no step cache.+ two_pass: true, base_steps: 8, refine_steps: 3, step_cache: 'none'})) write(key, value);node.properties.freevideo_seconds = seconds;node.properties.freevideo_aspect = 'custom';node.properties.freevideo_pixels = g.width * g.height / 1024 ** 2;@@ -101,7 +101,7 @@ export function extendSnapshot(snapshot, node, source, {multiple = false} = {})const copy = structuredClone(snapshot), inputs = copy.output[String(node)].inputs;inputs.width = source.geometry.width; inputs.height = source.geometry.height;inputs.preview = false; inputs.refine_from = ''; inputs.two_pass = true;- for (const [key, value] of [['base_steps', 8], ['refine_steps', 3]]) if (key in inputs) inputs[key] = value;+ for (const [key, value] of [['base_steps', 8], ['refine_steps', 3], ['step_cache', 'none']]) if (key in inputs) inputs[key] = value;// A continuation takes no first or last frame and no pre-encoded conditioning.for (const key of ['first', 'last', 'conditioning']) delete inputs[key];if (multiple) delete inputs.continue_from; else inputs.continue_from = source.video;