Download ComfyUI-H3-LongForge-NodePack/cache.py from p3cyc/minimax: direct link, hf CLI and curl.
- Browser
- Download file 43.9 kB
-
https://huggingface.co/p3cyc/minimax/resolve/main/ComfyUI-H3-LongForge-NodePack/cache.py
- Command line
-
hf download hf://p3cyc/minimax/ComfyUI-H3-LongForge-NodePack/cache.py
-
curl -L -o cache.py https://huggingface.co/p3cyc/minimax/resolve/main/ComfyUI-H3-LongForge-NodePack/cache.py
43.9 kB
| """Adaptive native-step cache for MiniMax H3 audio-video diffusion. | |
| Version 2.4 keeps the small-memory full-output cache used by LongForge | |
| and the v2 input-stability controller: | |
| * video and audio are measured independently and either stream can veto reuse; | |
| * an anchor metric catches cumulative drift while a local metric catches sudden | |
| step-to-step changes; | |
| * sketches are bounded to a few thousand values regardless of latent size; | |
| * large input spikes trigger a short automatic cooldown; | |
| * warmup, end-of-schedule refreshes and consecutive-reuse limits remain hard | |
| constraints rather than estimates. | |
| 2.2 additions (same controller, safer packaging): | |
| * cloned cached outputs so later in-place writes cannot poison reuse; | |
| * semantic profiles VOICE / ACTION, draft PREVIEW, and DRAFT10 (~10 reused steps on a 20-step native path); | |
| * CUSTOM overrides for thresholds, budgets, warmup, consecutive reuse and window; | |
| * explicit LongForge preflight before reuse; the designated Turbo loader must | |
| be bypassed in the full workflow and absent from the execution graph; | |
| * per-step reasons and estimated wall-time saved. | |
| 2.3 added an opt-in AUTO controller without changing any manual profile: | |
| * three full calibration observations choose QUALITY / VOICE / ACTION / | |
| BALANCED / FAST for the current scene; | |
| 2.4 tightens AUTO and render preflight: | |
| * the first eligible reuse in each selected profile is calculated in full to | |
| prove that profile on the actual scene before any output is reused; | |
| * subsequent periodic full control steps compare the actually calculated | |
| output with the value that would have been reused at that same sigma; | |
| * a failed control step backs off to a safer profile, and repeated failures | |
| disable reuse for the remainder of that scene while sampling stays native. | |
| The controller is deliberately unavailable for short/Turbo schedules. Mutable | |
| state lives in the selected ModelPatcher branch, is reset for every scene, and | |
| is never present on the clean HQ refiner branch. | |
| """ | |
| from __future__ import annotations | |
| from contextlib import nullcontext | |
| import logging | |
| import math | |
| import time | |
| import types | |
| from dataclasses import dataclass, field | |
| import torch | |
| from .cache_guard import turbo_bypass_reason | |
| LOG = logging.getLogger("LongForge.cache") | |
| MARKER = "longforge_h3_native_cache_v2" | |
| LEGACY_MARKER = "longforge_h3_native_cache_v1" | |
| AGSOFT_MARKER = "agsoft_cache_state" | |
| MIN_NATIVE_STEPS = 16 | |
| EPS = 1e-6 | |
| MAX_SKETCH_VALUES = 4096 | |
| UNPREPARED = "LongForge preflight has not confirmed 07 路 Turbo LoRA bypass; Native Cache stays disabled" | |
| MANUAL_PROFILES = ("QUALITY", "VOICE", "ACTION", "BALANCED", "FAST", "PREVIEW", "DRAFT10") | |
| NAMED_PROFILES = ("AUTO",) + MANUAL_PROFILES | |
| PROFILE_CHOICES = NAMED_PROFILES + ("CUSTOM",) | |
| AUTO_VERIFY_INTERVAL = 3 | |
| AUTO_VERIFY_VIDEO_LIMIT = 0.100 | |
| AUTO_VERIFY_AUDIO_LIMIT = 0.075 | |
| AUTO_MAX_FAILURES = 3 | |
| # ComfyUI's standard KSamplerSelect uses the samplers' default noise settings. | |
| # Fresh noise between steps defeats reuse of a previous model output: the input | |
| # deltas then look like repeated spikes and the cache spends time in cooldown. | |
| # This is a cache compatibility check; it does not change the selected sampler. | |
| STOCHASTIC_SAMPLERS = frozenset({"ddpm", "lcm", "sa_solver", "sa_solver_pece"}) | |
| def stochastic_sampler_reason(sampler): | |
| name = str(sampler or "").strip().lower() | |
| if name and ("ancestral" in name or "_sde" in name or name in STOCHASTIC_SAMPLERS): | |
| return (f"sampler {sampler} injects fresh noise between steps; " | |
| "LongForge output cache is bypassed for this run. The sampler still runs normally.") | |
| return None | |
| PROFILES = { | |
| # AUTO begins with BALANCED sampling/measurement geometry. Reuse stays | |
| # locked until scene-local calibration selects an effective manual profile. | |
| "AUTO": { | |
| "video_threshold": 0.075, "audio_threshold": 0.050, | |
| "start": 0.15, "end": 0.84, "warmup": 3, "max_consecutive": 1, | |
| "video_budget": 0.075, "audio_budget": 0.050, | |
| "video_stride": 12, "audio_stride": 6, | |
| "spike_multiplier": 3.0, "cooldown": 1, | |
| }, | |
| # Reuse counts remain data dependent. These are limits, not fixed skip maps. | |
| "QUALITY": { | |
| "video_threshold": 0.055, "audio_threshold": 0.035, | |
| "start": 0.20, "end": 0.76, "warmup": 3, "max_consecutive": 1, | |
| "video_budget": 0.055, "audio_budget": 0.035, | |
| "video_stride": 12, "audio_stride": 6, | |
| "spike_multiplier": 2.5, "cooldown": 2, | |
| }, | |
| "VOICE": { | |
| "video_threshold": 0.055, "audio_threshold": 0.028, | |
| "start": 0.20, "end": 0.74, "warmup": 3, "max_consecutive": 1, | |
| "video_budget": 0.055, "audio_budget": 0.028, | |
| "video_stride": 12, "audio_stride": 4, | |
| "spike_multiplier": 2.2, "cooldown": 2, | |
| }, | |
| "ACTION": { | |
| "video_threshold": 0.068, "audio_threshold": 0.040, | |
| "start": 0.18, "end": 0.80, "warmup": 3, "max_consecutive": 1, | |
| "video_budget": 0.068, "audio_budget": 0.040, | |
| "video_stride": 12, "audio_stride": 6, | |
| "spike_multiplier": 2.5, "cooldown": 2, | |
| }, | |
| "BALANCED": { | |
| "video_threshold": 0.075, "audio_threshold": 0.050, | |
| "start": 0.15, "end": 0.84, "warmup": 3, "max_consecutive": 1, | |
| "video_budget": 0.075, "audio_budget": 0.050, | |
| "video_stride": 12, "audio_stride": 6, | |
| "spike_multiplier": 3.0, "cooldown": 1, | |
| }, | |
| "FAST": { | |
| "video_threshold": 0.100, "audio_threshold": 0.065, | |
| "start": 0.12, "end": 0.88, "warmup": 2, "max_consecutive": 2, | |
| "video_budget": 0.150, "audio_budget": 0.090, | |
| "video_stride": 16, "audio_stride": 8, | |
| "spike_multiplier": 4.0, "cooldown": 1, | |
| }, | |
| "PREVIEW": { | |
| "video_threshold": 0.125, "audio_threshold": 0.085, | |
| "start": 0.10, "end": 0.90, "warmup": 2, "max_consecutive": 3, | |
| "video_budget": 0.200, "audio_budget": 0.130, | |
| "video_stride": 16, "audio_stride": 8, | |
| "spike_multiplier": 4.5, "cooldown": 1, | |
| }, | |
| "DRAFT10": { | |
| "video_threshold": 0.160, "audio_threshold": 0.150, | |
| "start": 0.06, "end": 0.94, "warmup": 3, "max_consecutive": 4, | |
| "video_budget": 0.240, "audio_budget": 0.220, | |
| "video_stride": 16, "audio_stride": 8, | |
| "spike_multiplier": 4.0, "cooldown": 1, | |
| }, | |
| "CUSTOM": { | |
| "video_threshold": 0.075, "audio_threshold": 0.050, | |
| "start": 0.15, "end": 0.84, "warmup": 3, "max_consecutive": 1, | |
| "video_budget": 0.075, "audio_budget": 0.050, | |
| "video_stride": 12, "audio_stride": 6, | |
| "spike_multiplier": 3.0, "cooldown": 1, | |
| }, | |
| } | |
| CUSTOM_KEYS = ( | |
| "video_threshold", "audio_threshold", "video_budget", "audio_budget", | |
| "warmup", "max_consecutive", "start", "end", | |
| ) | |
| def _finite(value, default=math.inf): | |
| try: | |
| number = float(value) | |
| except (TypeError, ValueError): | |
| return default | |
| return number if math.isfinite(number) else default | |
| def _offsets(stride): | |
| stride = max(1, int(stride)) | |
| return (0,) if stride == 1 else (0, stride // 2) | |
| def _effective_stride(numel, requested): | |
| """Bound both phase samples together to MAX_SKETCH_VALUES.""" | |
| requested = max(1, int(requested)) | |
| # Reserve half the cap for each phase. If stride resolves to 1, _offsets | |
| # returns one phase and the sketch is smaller, never larger, than the cap. | |
| per_phase = max(1, MAX_SKETCH_VALUES // 2) | |
| return max(requested, int(math.ceil(max(1, int(numel)) / per_phase))) | |
| def _sample_stream(value, requested_stride): | |
| flat = value.detach().reshape(-1) | |
| stride = _effective_stride(flat.numel(), requested_stride) | |
| samples = [] | |
| for offset in _offsets(stride): | |
| if offset < flat.numel(): | |
| # Bounded CPU sketch: one sync per stream, later deltas stay off-GPU. | |
| samples.append(flat[offset::stride].float().to(device="cpu")) | |
| return tuple(samples) | |
| def _stream_snapshot(value, stride): | |
| """Bounded two-phase fp32 sketch, resistant to single-stride aliasing.""" | |
| return tuple(sample.clone() for sample in _sample_stream(value, stride)) | |
| def _snapshot_samples(samples): | |
| return tuple(sample.clone() for sample in samples) | |
| def _sample_delta(current_samples, snapshot): | |
| deltas = [] | |
| for current, previous in zip(current_samples, snapshot or ()): | |
| if current.shape != previous.shape: | |
| return math.inf | |
| if current.device != previous.device: | |
| previous = previous.to(current.device) | |
| numerator = (current - previous).abs().mean() | |
| denominator = previous.abs().mean() + EPS | |
| deltas.append(_finite((numerator / denominator).item())) | |
| return max(deltas) if deltas else math.inf | |
| def _relative_delta(value, snapshot, stride): | |
| return _sample_delta(_sample_stream(value, stride), snapshot) | |
| def _schedule(timestep, transformer_options): | |
| """Return video sigma, index, real step count, progress and last-step flag.""" | |
| sigmas = (transformer_options or {}).get("sample_sigmas") | |
| if not torch.is_tensor(sigmas) or sigmas.numel() == 0: | |
| return None, None, None, None, False | |
| values = sigmas.detach().flatten().to(device="cpu", dtype=torch.float32) | |
| if not torch.isfinite(values).all(): | |
| return None, None, None, None, False | |
| real_steps = int(values.numel()) | |
| if real_steps > 1 and abs(float(values[-1])) <= 1e-7: | |
| real_steps -= 1 | |
| if real_steps <= 0: | |
| return None, None, None, None, False | |
| try: | |
| raw = float(timestep.detach().flatten()[0]) if torch.is_tensor(timestep) else float(timestep) | |
| except (TypeError, ValueError, IndexError): | |
| return None, None, real_steps, None, False | |
| # Native H3 uses timestep = sigma * 1000 even in the low-sigma tail. | |
| # A magnitude heuristic mislabels those late calls as early steps. | |
| sigma = raw / 1000.0 | |
| if not math.isfinite(sigma): | |
| return None, None, real_steps, None, False | |
| index = int((values[:real_steps] - sigma).abs().argmin()) | |
| if abs(float(values[index]) - sigma) > max(1e-6, abs(sigma) * 1e-4): | |
| return None, None, real_steps, None, False | |
| progress = index / max(1, real_steps - 1) | |
| return sigma, index, real_steps, progress, index >= real_steps - 1 | |
| def _streams(value): | |
| if not isinstance(value, (list, tuple)) or len(value) < 2: | |
| return None, None | |
| if not torch.is_tensor(value[0]) or not torch.is_tensor(value[1]): | |
| return None, None | |
| return value[0], value[1] | |
| def _clone_item(item): | |
| if torch.is_tensor(item): | |
| return item.detach().clone() | |
| if isinstance(item, list): | |
| return [_clone_item(value) for value in item] | |
| if isinstance(item, tuple): | |
| return tuple(_clone_item(value) for value in item) | |
| if isinstance(item, dict): | |
| return {key: _clone_item(value) for key, value in item.items()} | |
| return item | |
| def _remember_output(output): | |
| """Keep isolated tensor storage; H3 forward() rebinds the returned list.""" | |
| # These tensors outlive this forward. They must not belong to the | |
| # compiler's temporary allocation graph, which can recycle their storage. | |
| try: | |
| from comfy.model_prefetch import pause_malloc_graph | |
| except ImportError: | |
| pause_malloc_graph = nullcontext | |
| with pause_malloc_graph(): | |
| if isinstance(output, list): | |
| return "list", tuple(_clone_item(item) for item in output) | |
| if isinstance(output, tuple): | |
| return "tuple", tuple(_clone_item(item) for item in output) | |
| return "value", _clone_item(output) | |
| def competing_cache_reason(transformer, options=None): | |
| competing = [key for key in (AGSOFT_MARKER, LEGACY_MARKER, 'easycache', | |
| 'minimax_h3_block_cache_t8', 'spectrum_h3_binding') | |
| if transformer.get(key) is not None] | |
| if (options or {}).get('spectrum_h3_binding') is not None and 'spectrum_h3_binding' not in competing: | |
| competing.append('spectrum_h3_binding') | |
| if competing: | |
| return ('another approximation cache is active on this branch ' | |
| f"({', '.join(competing)}); LongForge cache disabled to prevent double approximation") | |
| return None | |
| def _fresh_output(kind, value): | |
| """Return isolated storage while keeping the cached copy immutable. | |
| ComfyUI normally consumes H3 outputs without mutating them, but custom | |
| samplers and model patches are allowed to perform in-place operations. A | |
| shallow container copy would let such a consumer alter the tensors retained | |
| for the next reused step. Clone on every reuse so the cache remains the | |
| authoritative private copy. | |
| """ | |
| if kind == "list": | |
| return [_clone_item(item) for item in value] | |
| if kind == "tuple": | |
| return tuple(_clone_item(item) for item in value) | |
| return _clone_item(value) | |
| def _clamp_custom(overrides): | |
| cleaned = {} | |
| if not overrides: | |
| return cleaned | |
| if "video_threshold" in overrides: | |
| cleaned["video_threshold"] = min(1.0, max(0.0, float(overrides["video_threshold"]))) | |
| if "audio_threshold" in overrides: | |
| cleaned["audio_threshold"] = min(1.0, max(0.0, float(overrides["audio_threshold"]))) | |
| if "max_consecutive" in overrides: | |
| cleaned["max_consecutive"] = min(8, max(0, int(overrides["max_consecutive"]))) | |
| if "warmup" in overrides: | |
| cleaned["warmup"] = min(8, max(0, int(overrides["warmup"]))) | |
| if "video_budget" in overrides: | |
| cleaned["video_budget"] = min(1.0, max(0.0, float(overrides["video_budget"]))) | |
| if "audio_budget" in overrides: | |
| cleaned["audio_budget"] = min(1.0, max(0.0, float(overrides["audio_budget"]))) | |
| start = overrides.get("start", overrides.get("start_percent")) | |
| end = overrides.get("end", overrides.get("end_percent")) | |
| if start is not None: | |
| cleaned["start"] = min(1.0, max(0.0, float(start))) | |
| if end is not None: | |
| cleaned["end"] = min(1.0, max(0.0, float(end))) | |
| if "start" in cleaned or "end" in cleaned: | |
| lo = cleaned.get("start", 0.0) | |
| hi = cleaned.get("end", 1.0) | |
| cleaned["start"], cleaned["end"] = (lo, hi) if lo <= hi else (hi, lo) | |
| return cleaned | |
| def build_config(profile, overrides=None): | |
| if profile not in PROFILES: | |
| raise ValueError(f"Unknown native cache profile: {profile}") | |
| config = dict(PROFILES[profile]) | |
| if profile == "CUSTOM": | |
| config.update(_clamp_custom(overrides)) | |
| # Budgets may be raised above the thresholds. They must never fall | |
| # below them: an old graph only stored thresholds, and the new budget | |
| # widgets default to BALANCED values. | |
| config["video_budget"] = max( | |
| float(config["video_threshold"]), | |
| float(config.get("video_budget", config["video_threshold"])), | |
| ) | |
| config["audio_budget"] = max( | |
| float(config["audio_threshold"]), | |
| float(config.get("audio_budget", config["audio_threshold"])), | |
| ) | |
| return config | |
| class CacheState: | |
| profile: str | |
| console_report: bool = True | |
| overrides: dict | None = None | |
| config: dict = field(init=False) | |
| effective_profile: str = field(init=False) | |
| run_token: str | None = None | |
| prepared_steps: int | None = None | |
| active: bool = False | |
| disabled_reason: str | None = None | |
| armed_mode: str | None = None | |
| last_step: int | None = None | |
| last_sigma: float | None = None | |
| anchor_video: tuple | None = None | |
| anchor_audio: tuple | None = None | |
| recent_video: tuple | None = None | |
| recent_audio: tuple | None = None | |
| cached_kind: str | None = None | |
| cached_output: object = None | |
| consecutive: int = 0 | |
| cooldown: int = 0 | |
| video_budget_used: float = 0.0 | |
| audio_budget_used: float = 0.0 | |
| total_calls: int = 0 | |
| full_calls: int = 0 | |
| reused_calls: int = 0 | |
| repeated_step_calls: int = 0 | |
| video_vetoes: int = 0 | |
| audio_vetoes: int = 0 | |
| cooldown_vetoes: int = 0 | |
| spike_events: int = 0 | |
| max_video_delta: float = 0.0 | |
| max_audio_delta: float = 0.0 | |
| full_time_total: float = 0.0 | |
| time_saved: float = 0.0 | |
| last_reason: str | None = None | |
| executed_steps: list[int] = field(default_factory=list) | |
| reused_steps: list[int] = field(default_factory=list) | |
| last_report: dict | None = None | |
| auto_classified: bool = False | |
| auto_reuse_disabled: bool = False | |
| auto_video_observations: list[float] = field(default_factory=list) | |
| auto_audio_observations: list[float] = field(default_factory=list) | |
| auto_candidates_since_check: int = 0 | |
| auto_verification_checks: int = 0 | |
| auto_verification_passes: int = 0 | |
| auto_verification_failures: int = 0 | |
| auto_profile_verified: bool = False | |
| auto_backoffs: list[str] = field(default_factory=list) | |
| auto_max_video_error: float = 0.0 | |
| auto_max_audio_error: float = 0.0 | |
| def __post_init__(self): | |
| self.config = build_config(self.profile, self.overrides) | |
| self.effective_profile = "CALIBRATING" if self.profile == "AUTO" else self.profile | |
| def __deepcopy__(self, memo): | |
| return self | |
| def avg_full_step(self): | |
| return self.full_time_total / max(1, self.full_calls) | |
| def prepare(self, token, steps, cfg=1.0, armed_mode="preflight", block_reason=None): | |
| self.release_runtime() | |
| self.run_token = str(token) | |
| self.prepared_steps = int(steps) | |
| self.armed_mode = armed_mode | |
| if block_reason: | |
| self.active = False | |
| self.disabled_reason = str(block_reason) | |
| elif self.prepared_steps < MIN_NATIVE_STEPS: | |
| self.active = False | |
| self.disabled_reason = ( | |
| f"adaptive native cache requires at least {MIN_NATIVE_STEPS} sampling steps; " | |
| f"received {self.prepared_steps}. Turbo/short schedules are intentionally uncached." | |
| ) | |
| elif abs(float(cfg) - 1.0) > 1e-7: | |
| self.active = False | |
| self.disabled_reason = ( | |
| f"adaptive native cache requires CFG 1 for conditioning-safe single evaluation; received CFG {cfg}." | |
| ) | |
| else: | |
| self.active = True | |
| self.disabled_reason = None | |
| self.total_calls = self.full_calls = self.reused_calls = 0 | |
| self.repeated_step_calls = self.video_vetoes = self.audio_vetoes = 0 | |
| self.cooldown_vetoes = self.spike_events = 0 | |
| self.max_video_delta = self.max_audio_delta = 0.0 | |
| self.full_time_total = self.time_saved = 0.0 | |
| self.last_reason = None | |
| self.executed_steps = [] | |
| self.reused_steps = [] | |
| self.last_report = None | |
| self.effective_profile = "CALIBRATING" if self.profile == "AUTO" else self.profile | |
| self.auto_classified = False | |
| self.auto_reuse_disabled = False | |
| self.auto_video_observations = [] | |
| self.auto_audio_observations = [] | |
| self.auto_candidates_since_check = 0 | |
| self.auto_verification_checks = 0 | |
| self.auto_verification_passes = 0 | |
| self.auto_verification_failures = 0 | |
| self.auto_profile_verified = False | |
| self.auto_backoffs = [] | |
| self.auto_max_video_error = self.auto_max_audio_error = 0.0 | |
| self.config = build_config(self.profile, self.overrides) | |
| return self.report(aborted=False) | |
| def release_runtime(self): | |
| self.last_step = None | |
| self.last_sigma = None | |
| self.anchor_video = self.anchor_audio = None | |
| self.recent_video = self.recent_audio = None | |
| self.cached_kind = None | |
| self.cached_output = None | |
| self.consecutive = self.cooldown = 0 | |
| self.video_budget_used = self.audio_budget_used = 0.0 | |
| def report(self, aborted=False): | |
| possible = (self.total_calls / self.full_calls) if self.full_calls else 1.0 | |
| return { | |
| "algorithm": "adaptive-dual-stream-v2.4", "profile": self.profile, | |
| "effective_profile": self.effective_profile, | |
| "active": bool(self.active), "reason": self.disabled_reason, | |
| "armed": self.armed_mode, | |
| "steps": self.prepared_steps, "calls": self.total_calls, | |
| "executed": self.full_calls, "reused": self.reused_calls, | |
| "reuse_percent": round(100 * self.reused_calls / max(1, self.total_calls), 1), | |
| "compute_reduction_upper_bound": round(possible, 3), | |
| "avg_full_step_seconds": round(self.avg_full_step, 3) if self.full_calls else 0.0, | |
| "time_saved_seconds": round(self.time_saved, 2), | |
| "video_vetoes": self.video_vetoes, "audio_vetoes": self.audio_vetoes, | |
| "cooldown_vetoes": self.cooldown_vetoes, "spike_events": self.spike_events, | |
| "repeated_step_calls": self.repeated_step_calls, | |
| "max_video_delta": round(self.max_video_delta, 6), | |
| "max_audio_delta": round(self.max_audio_delta, 6), | |
| "executed_steps": list(self.executed_steps), "reused_steps": list(self.reused_steps), | |
| "auto": { | |
| "classified": bool(self.auto_classified), | |
| "reuse_disabled": bool(self.auto_reuse_disabled), | |
| "video_observations": [round(value, 6) for value in self.auto_video_observations], | |
| "audio_observations": [round(value, 6) for value in self.auto_audio_observations], | |
| "verification_checks": self.auto_verification_checks, | |
| "verification_passes": self.auto_verification_passes, | |
| "verification_failures": self.auto_verification_failures, | |
| "profile_verified": bool(self.auto_profile_verified), | |
| "backoffs": list(self.auto_backoffs), | |
| "max_video_error": round(self.auto_max_video_error, 6), | |
| "max_audio_error": round(self.auto_max_audio_error, 6), | |
| } if self.profile == "AUTO" else None, | |
| "aborted": bool(aborted), | |
| } | |
| def _clean_transformer_options(options): | |
| clean = dict(options or {}) | |
| clean.pop(MARKER, None) | |
| return clean | |
| def _original(self, args, kwargs): | |
| """Call H3 without exposing Python cache state to the compiled graph.""" | |
| call_args = list(args) | |
| call_kwargs = dict(kwargs) | |
| if isinstance(call_kwargs.get("transformer_options"), dict): | |
| call_kwargs["transformer_options"] = _clean_transformer_options(call_kwargs["transformer_options"]) | |
| elif len(call_args) >= 4 and isinstance(call_args[3], dict): | |
| call_args[3] = _clean_transformer_options(call_args[3]) | |
| return self._longforge_cache_original_forward(*call_args, **call_kwargs) | |
| def _reject_detail(cfg, anchor_v, local_v, anchor_a, local_a, v_used, a_used): | |
| reasons = [] | |
| if not (anchor_v < cfg["video_threshold"] and local_v < cfg["video_threshold"]): | |
| if not (anchor_v < cfg["video_threshold"]): | |
| reasons.append(f"anchor_video {anchor_v:.4f}>={cfg['video_threshold']:.4f}") | |
| if not (local_v < cfg["video_threshold"]): | |
| reasons.append(f"local_video {local_v:.4f}>={cfg['video_threshold']:.4f}") | |
| if v_used + local_v > cfg["video_budget"]: | |
| reasons.append(f"video_budget {v_used + local_v:.4f}>{cfg['video_budget']:.4f}") | |
| if not (anchor_a < cfg["audio_threshold"] and local_a < cfg["audio_threshold"]): | |
| if not (anchor_a < cfg["audio_threshold"]): | |
| reasons.append(f"anchor_audio {anchor_a:.4f}>={cfg['audio_threshold']:.4f}") | |
| if not (local_a < cfg["audio_threshold"]): | |
| reasons.append(f"local_audio {local_a:.4f}>={cfg['audio_threshold']:.4f}") | |
| if a_used + local_a > cfg["audio_budget"]: | |
| reasons.append(f"audio_budget {a_used + local_a:.4f}>{cfg['audio_budget']:.4f}") | |
| return ", ".join(reasons) if reasons else "stability veto" | |
| def _median(values): | |
| finite = sorted(float(value) for value in values if math.isfinite(float(value))) | |
| if not finite: | |
| return math.inf | |
| middle = len(finite) // 2 | |
| return finite[middle] if len(finite) % 2 else (finite[middle - 1] + finite[middle]) / 2 | |
| def _auto_observe_and_classify(state, local_video, local_audio): | |
| """Choose one existing manual profile from scene-local input movement.""" | |
| if state.profile != "AUTO" or state.auto_classified: | |
| return | |
| if math.isfinite(local_video): | |
| state.auto_video_observations.append(float(local_video)) | |
| if math.isfinite(local_audio): | |
| state.auto_audio_observations.append(float(local_audio)) | |
| if min(len(state.auto_video_observations), len(state.auto_audio_observations)) < 3: | |
| return | |
| video = _median(state.auto_video_observations[-4:]) | |
| audio = _median(state.auto_audio_observations[-4:]) | |
| if max(video, audio) >= 0.140: | |
| selected = "QUALITY" | |
| elif audio >= 0.055 and audio > video * 1.15: | |
| selected = "VOICE" | |
| elif video >= 0.080 and video > audio * 1.20: | |
| selected = "ACTION" | |
| elif video <= 0.045 and audio <= 0.032: | |
| selected = "FAST" | |
| else: | |
| selected = "BALANCED" | |
| video_stride = state.config["video_stride"] | |
| audio_stride = state.config["audio_stride"] | |
| state.config = dict(PROFILES[selected]) | |
| state.config["video_stride"] = video_stride | |
| state.config["audio_stride"] = audio_stride | |
| state.effective_profile = selected | |
| state.auto_classified = True | |
| state.auto_profile_verified = False | |
| if state.console_report: | |
| LOG.info( | |
| "Adaptive Cache AUTO calibrated 路 video %.4f 路 audio %.4f 路 selected %s", | |
| video, audio, selected, | |
| ) | |
| def _cached_stream_errors(output, cached_value, cfg): | |
| fresh_video, fresh_audio = _streams(output) | |
| cached_video, cached_audio = _streams(cached_value) | |
| if any(value is None for value in (fresh_video, fresh_audio, cached_video, cached_audio)): | |
| return math.inf, math.inf | |
| video_error = _sample_delta( | |
| _sample_stream(fresh_video, cfg["video_stride"]), | |
| _sample_stream(cached_video, cfg["video_stride"]), | |
| ) | |
| audio_error = _sample_delta( | |
| _sample_stream(fresh_audio, cfg["audio_stride"]), | |
| _sample_stream(cached_audio, cfg["audio_stride"]), | |
| ) | |
| return video_error, audio_error | |
| def _auto_verify(state, output, cached_value): | |
| """Validate a real would-be reuse, then back off without corrupting output.""" | |
| video_error, audio_error = _cached_stream_errors(output, cached_value, state.config) | |
| state.auto_verification_checks += 1 | |
| if math.isfinite(video_error): | |
| state.auto_max_video_error = max(state.auto_max_video_error, video_error) | |
| if math.isfinite(audio_error): | |
| state.auto_max_audio_error = max(state.auto_max_audio_error, audio_error) | |
| passed = video_error <= AUTO_VERIFY_VIDEO_LIMIT and audio_error <= AUTO_VERIFY_AUDIO_LIMIT | |
| if passed: | |
| state.auto_verification_passes += 1 | |
| state.auto_profile_verified = True | |
| return ( | |
| f"AUTO verification passed 路 output v {video_error:.4f}/{AUTO_VERIFY_VIDEO_LIMIT:.4f} " | |
| f"a {audio_error:.4f}/{AUTO_VERIFY_AUDIO_LIMIT:.4f}" | |
| ) | |
| state.auto_verification_failures += 1 | |
| state.auto_profile_verified = False | |
| current = state.effective_profile | |
| safer = { | |
| "FAST": "BALANCED", | |
| "ACTION": "BALANCED", | |
| "BALANCED": "QUALITY", | |
| "VOICE": "QUALITY", | |
| }.get(current) | |
| if safer is not None: | |
| video_stride = state.config["video_stride"] | |
| audio_stride = state.config["audio_stride"] | |
| state.config = dict(PROFILES[safer]) | |
| state.config["video_stride"] = video_stride | |
| state.config["audio_stride"] = audio_stride | |
| state.effective_profile = safer | |
| state.auto_backoffs.append(f"{current}->{safer}") | |
| elif state.auto_verification_failures >= AUTO_MAX_FAILURES: | |
| state.auto_reuse_disabled = True | |
| state.effective_profile = "FULL" | |
| state.auto_backoffs.append(f"{current}->FULL") | |
| else: | |
| state.auto_backoffs.append(f"{current}->HOLD") | |
| state.cooldown = max(state.cooldown, 2) | |
| return ( | |
| f"AUTO verification failed 路 output v {video_error:.4f}/{AUTO_VERIFY_VIDEO_LIMIT:.4f} " | |
| f"a {audio_error:.4f}/{AUTO_VERIFY_AUDIO_LIMIT:.4f} 路 " | |
| f"effective {state.effective_profile}{' 路 reuse disabled' if state.auto_reuse_disabled else ''}" | |
| ) | |
| def _log_step(state, step, reused, reason, dt=None): | |
| if not state.console_report: | |
| return | |
| label = "SKIP" if reused else "RUN " | |
| timing = f" in {dt:.2f}s" if dt is not None else "" | |
| LOG.info("Adaptive Cache step %s %s 路 %s%s", step + 1, label, reason, timing) | |
| def _cached_forward(self, *args, **kwargs): | |
| transformer_options = kwargs.get("transformer_options") | |
| if transformer_options is None and len(args) >= 4 and isinstance(args[3], dict): | |
| transformer_options = args[3] | |
| state = (transformer_options or {}).get(MARKER) | |
| if not isinstance(state, CacheState): | |
| return _original(self, args, kwargs) | |
| # Never arm from the sampling schedule alone: it cannot prove that the | |
| # designated Turbo loader is bypassed. Only LongForge preflight may arm. | |
| if state.prepared_steps is None: | |
| state.active = False | |
| if state.disabled_reason != UNPREPARED and state.console_report: | |
| LOG.info("Adaptive Native Cache bypassed 路 %s", UNPREPARED) | |
| state.disabled_reason = UNPREPARED | |
| return _original(self, args, kwargs) | |
| # Applying another full-output cache after LongForge can reintroduce its | |
| # marker downstream. Never let two approximation policies control the same | |
| # model call: preserve the later patch and safely retire this controller. | |
| competing = competing_cache_reason(transformer_options or {}) | |
| if competing: | |
| state.active = False | |
| state.disabled_reason = competing | |
| return _original(self, args, kwargs) | |
| x = kwargs.get("x", args[0] if len(args) > 0 else None) | |
| timestep = kwargs.get("timestep", args[1] if len(args) > 1 else None) | |
| video, audio = _streams(x) | |
| sigma, step, real_steps, progress, is_last = _schedule(timestep, transformer_options) | |
| if video is None or audio is None or step is None or progress is None or sigma is None: | |
| state.active = False | |
| state.disabled_reason = "unexpected model input or sigma schedule; adaptive dual-stream cache disabled safely" | |
| return _original(self, args, kwargs) | |
| if real_steps < MIN_NATIVE_STEPS: | |
| state.active = False | |
| state.disabled_reason = ( | |
| f"runtime schedule has {real_steps} steps; Native Cache is disabled below " | |
| f"{MIN_NATIVE_STEPS} steps and must not be combined with Turbo generation." | |
| ) | |
| return _original(self, args, kwargs) | |
| if not state.active: | |
| return _original(self, args, kwargs) | |
| if state.last_step is not None and step < state.last_step: | |
| state.prepare(f"fallback-{id(transformer_options)}", real_steps, armed_mode=state.armed_mode or "auto") | |
| repeated = state.last_step is not None and step == state.last_step | |
| state.total_calls += 1 | |
| if repeated: | |
| state.repeated_step_calls += 1 | |
| state.active = False | |
| state.disabled_reason = "multiple model evaluations at one sigma; cache disabled for conditioning safety" | |
| output = _original(self, args, kwargs) | |
| state.full_calls += 1 | |
| state.executed_steps.append(step + 1) | |
| return output | |
| cfg = state.config | |
| current_video = _sample_stream(video, cfg["video_stride"]) | |
| current_audio = _sample_stream(audio, cfg["audio_stride"]) | |
| anchor_video_delta = (_sample_delta(current_video, state.anchor_video) | |
| if state.anchor_video is not None else math.inf) | |
| anchor_audio_delta = (_sample_delta(current_audio, state.anchor_audio) | |
| if state.anchor_audio is not None else math.inf) | |
| local_video_delta = (_sample_delta(current_video, state.recent_video) | |
| if state.recent_video is not None else math.inf) | |
| local_audio_delta = (_sample_delta(current_audio, state.recent_audio) | |
| if state.recent_audio is not None else math.inf) | |
| # AUTO observes real sampler inputs and stays locked until three finite | |
| # scene-local movements select one of the unchanged manual controllers. | |
| _auto_observe_and_classify(state, local_video_delta, local_audio_delta) | |
| cfg = state.config | |
| for value, attr in ((anchor_video_delta, "max_video_delta"), | |
| (anchor_audio_delta, "max_audio_delta")): | |
| if math.isfinite(value): | |
| setattr(state, attr, max(getattr(state, attr), value)) | |
| in_window = cfg["start"] <= progress <= cfg["end"] | |
| base_candidate = ( | |
| not is_last and in_window and step >= cfg["warmup"] | |
| and state.cached_output is not None | |
| and state.consecutive < cfg["max_consecutive"] | |
| and (state.profile != "AUTO" or state.auto_classified) | |
| and not state.auto_reuse_disabled | |
| ) | |
| video_ok = audio_ok = False | |
| reject_reason = None | |
| verify_cached = None | |
| if not base_candidate: | |
| if is_last: | |
| reject_reason = "last step" | |
| elif state.profile == "AUTO" and not state.auto_classified: | |
| reject_reason = "AUTO calibration" | |
| elif state.auto_reuse_disabled: | |
| reject_reason = "AUTO safety backoff 路 reuse disabled" | |
| elif not in_window: | |
| reject_reason = "outside cache window" | |
| elif step < cfg["warmup"]: | |
| reject_reason = f"warmup ({step + 1}/{cfg['warmup']})" | |
| elif state.cached_output is None: | |
| reject_reason = "initial step" | |
| else: | |
| reject_reason = f"max consecutive skips ({cfg['max_consecutive']})" | |
| elif state.cooldown > 0: | |
| reject_reason = f"cooldown ({state.cooldown})" | |
| state.cooldown_vetoes += 1 | |
| else: | |
| video_ok = ( | |
| anchor_video_delta < cfg["video_threshold"] | |
| and local_video_delta < cfg["video_threshold"] | |
| and state.video_budget_used + local_video_delta <= cfg["video_budget"] | |
| ) | |
| audio_ok = ( | |
| anchor_audio_delta < cfg["audio_threshold"] | |
| and local_audio_delta < cfg["audio_threshold"] | |
| and state.audio_budget_used + local_audio_delta <= cfg["audio_budget"] | |
| ) | |
| if video_ok and audio_ok: | |
| if state.profile == "AUTO": | |
| if not state.auto_profile_verified: | |
| # A low input delta cannot prove that a cached H3 output | |
| # is safe at the next sigma. Check the first candidate in | |
| # full before any output from this profile is reused. | |
| verify_cached = state.cached_output | |
| state.auto_candidates_since_check = 0 | |
| reject_reason = "AUTO initial profile control step" | |
| else: | |
| state.auto_candidates_since_check += 1 | |
| if verify_cached is None and state.auto_candidates_since_check >= AUTO_VERIFY_INTERVAL: | |
| # Execute this candidate for real and compare it with the | |
| # value that would have been reused. Fresh output is kept. | |
| verify_cached = state.cached_output | |
| state.auto_candidates_since_check = 0 | |
| reject_reason = "AUTO full control step" | |
| if verify_cached is None: | |
| state.consecutive += 1 | |
| state.reused_calls += 1 | |
| state.reused_steps.append(step + 1) | |
| state.video_budget_used += local_video_delta | |
| state.audio_budget_used += local_audio_delta | |
| state.recent_video = _snapshot_samples(current_video) | |
| state.recent_audio = _snapshot_samples(current_audio) | |
| state.last_step = step | |
| state.last_sigma = sigma | |
| state.time_saved += state.avg_full_step | |
| reason = ( | |
| f"reuse v {local_video_delta:.4f}/{anchor_video_delta:.4f} " | |
| f"a {local_audio_delta:.4f}/{anchor_audio_delta:.4f} " | |
| f"{state.consecutive}/{cfg['max_consecutive']}" | |
| ) | |
| state.last_reason = reason | |
| _log_step(state, step, True, reason) | |
| return _fresh_output(state.cached_kind, state.cached_output) | |
| else: | |
| reject_reason = _reject_detail( | |
| cfg, anchor_video_delta, local_video_delta, | |
| anchor_audio_delta, local_audio_delta, | |
| state.video_budget_used, state.audio_budget_used, | |
| ) | |
| if not video_ok: | |
| state.video_vetoes += 1 | |
| if not audio_ok: | |
| state.audio_vetoes += 1 | |
| # A sudden change is not treated as an ordinary rejected step: force a | |
| # short sequence of full refreshes before reuse is considered again. | |
| spike = False | |
| if in_window and state.cached_output is not None: | |
| spike = any(( | |
| math.isfinite(delta) | |
| and delta > threshold * cfg["spike_multiplier"] | |
| ) for delta, threshold in ( | |
| (anchor_video_delta, cfg["video_threshold"]), | |
| (local_video_delta, cfg["video_threshold"]), | |
| (anchor_audio_delta, cfg["audio_threshold"]), | |
| (local_audio_delta, cfg["audio_threshold"]), | |
| )) | |
| if spike: | |
| state.spike_events += 1 | |
| state.cooldown = max(state.cooldown, cfg["cooldown"]) | |
| reject_reason = f"input spike 路 {reject_reason}" | |
| elif state.cooldown > 0: | |
| state.cooldown -= 1 | |
| started = time.perf_counter() | |
| output = _original(self, args, kwargs) | |
| dt = time.perf_counter() - started | |
| if verify_cached is not None: | |
| reject_reason = _auto_verify(state, output, verify_cached) | |
| state.full_calls += 1 | |
| state.full_time_total += dt | |
| state.executed_steps.append(step + 1) | |
| state.last_reason = reject_reason | |
| _log_step(state, step, False, reject_reason or "full step", dt) | |
| state.consecutive = 0 | |
| state.video_budget_used = state.audio_budget_used = 0.0 | |
| state.anchor_video = _snapshot_samples(current_video) | |
| state.anchor_audio = _snapshot_samples(current_audio) | |
| state.recent_video = state.anchor_video | |
| state.recent_audio = state.anchor_audio | |
| state.cached_kind, state.cached_output = _remember_output(output) | |
| state.last_step = step | |
| state.last_sigma = sigma | |
| return output | |
| def _keep_cache_control_outside_compiler(function): | |
| """Keep Python cache decisions eager while allowing the called H3 forward to compile.""" | |
| compiler = getattr(torch, "compiler", None) | |
| disable = getattr(compiler, "disable", None) | |
| if not callable(disable): | |
| return function | |
| try: | |
| return disable(function, recursive=False, | |
| reason="LongForge adaptive cache policy uses data-dependent Python control flow") | |
| except TypeError: | |
| return disable(function, recursive=False) | |
| _cached_forward = _keep_cache_control_outside_compiler(_cached_forward) | |
| def _state(model): | |
| options = getattr(model, "model_options", {}) or {} | |
| return (options.get("transformer_options") or {}).get(MARKER) | |
| def apply(model, profile="BALANCED", console_report=True, custom=None): | |
| """Return an isolated adaptive-cache ModelPatcher branch.""" | |
| if profile == "OFF": | |
| return model | |
| if profile not in PROFILES: | |
| raise ValueError(f"Unknown native cache profile: {profile}") | |
| patched = model.clone() | |
| diffusion = patched.model.diffusion_model | |
| if not callable(getattr(diffusion, "_forward", None)): | |
| raise ValueError("LongForge H3 Native Cache requires a MiniMax H3 model with a callable _forward method.") | |
| # A hot reload from cache v1 can otherwise nest wrappers. A normal ComfyUI | |
| # restart never enters this path, but unwrapping makes development safer. | |
| if (getattr(diffusion, "_longforge_cache_installed", False) | |
| and not getattr(diffusion, "_longforge_cache_v2_installed", False) | |
| and callable(getattr(diffusion, "_longforge_cache_original_forward", None))): | |
| diffusion._forward = diffusion._longforge_cache_original_forward | |
| if not getattr(diffusion, "_longforge_cache_v2_installed", False): | |
| diffusion._longforge_cache_original_forward = diffusion._forward | |
| diffusion._forward = types.MethodType(_cached_forward, diffusion) | |
| diffusion._longforge_cache_installed = True | |
| diffusion._longforge_cache_v2_installed = True | |
| LOG.info("LongForge Adaptive Native Cache v2.4 wrapper installed") | |
| patched.model_options = dict(getattr(patched, "model_options", {}) or {}) | |
| transformer = dict(patched.model_options.get("transformer_options", {}) or {}) | |
| transformer.pop(LEGACY_MARKER, None) | |
| transformer[MARKER] = CacheState( | |
| profile=profile, | |
| console_report=bool(console_report), | |
| overrides=custom if profile == "CUSTOM" else None, | |
| ) | |
| patched.model_options["transformer_options"] = transformer | |
| return patched | |
| def prepare_run(model, token, settings, prompt=None, render_node_id=None, block_reason=None, workflow=None): | |
| options = getattr(model, "model_options", {}) or {} | |
| transformer = options.get("transformer_options") or {} | |
| transformer.pop(LEGACY_MARKER, None) | |
| state = _state(model) | |
| if not isinstance(state, CacheState): | |
| return None | |
| values = settings or {} | |
| reason = (block_reason or turbo_bypass_reason(prompt, render_node_id, workflow) | |
| or competing_cache_reason(transformer, options) | |
| or stochastic_sampler_reason(values.get("sampler"))) | |
| report = state.prepare(token, int(values.get("steps", 0)), float(values.get("cfg", 1.0)), | |
| armed_mode="preflight", block_reason=reason) | |
| if not report["active"] and state.console_report: | |
| LOG.info("Adaptive Native Cache bypassed 路 %s", report["reason"]) | |
| return report | |
| def finish_run(model, aborted=False): | |
| state = _state(model) | |
| if not isinstance(state, CacheState): | |
| return None | |
| report = state.report(aborted=aborted) | |
| state.last_report = dict(report) | |
| if state.console_report: | |
| if report["active"]: | |
| LOG.info( | |
| "Adaptive Native Cache %s 路 executed %s/%s 路 reused %s (%.1f%%) 路 " | |
| "compute reduction upper bound %.2fx 路 ~%.1fs potential forward time avoided (estimate)", | |
| report["profile"], report["executed"], report["calls"], report["reused"], | |
| report["reuse_percent"], report["compute_reduction_upper_bound"], | |
| report["time_saved_seconds"], | |
| ) | |
| LOG.info("Adaptive Cache reused sampler steps: %s", report["reused_steps"] or "none") | |
| LOG.info( | |
| "Adaptive Cache safety 路 video vetoes %s 路 audio vetoes %s 路 input spikes %s 路 cooldown vetoes %s", | |
| report["video_vetoes"], report["audio_vetoes"], | |
| report["spike_events"], report["cooldown_vetoes"], | |
| ) | |
| if report["profile"] == "AUTO": | |
| auto = report["auto"] or {} | |
| LOG.info( | |
| "Adaptive Cache AUTO 路 effective %s 路 verification %s pass / %s fail 路 backoffs %s", | |
| report["effective_profile"], auto.get("verification_passes", 0), | |
| auto.get("verification_failures", 0), auto.get("backoffs") or "none", | |
| ) | |
| else: | |
| LOG.info("Adaptive Native Cache bypassed 路 %s", report["reason"]) | |
| state.release_runtime() | |
| # A cached model object may be reused elsewhere in the graph. Require the | |
| # explicit LongForge preflight for every new sampler run rather than | |
| # leaving a finished controller armed with stale counters/token data. | |
| state.active = False | |
| state.disabled_reason = UNPREPARED | |
| state.run_token = None | |
| state.prepared_steps = None | |
| state.armed_mode = None | |
| return report | |