forked from Jasonzzt/ComfyUI-CacheDiT
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnodes_wan.py
More file actions
512 lines (424 loc) ยท 18.8 KB
/
nodes_wan.py
File metadata and controls
512 lines (424 loc) ยท 18.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
"""
ComfyUI-CacheDiT: Wan2.2 Specialized Node
==========================================
Dedicated node for Wan2.2 DiT model with MoE architecture.
Wan2.2 has High-Noise and Low-Noise expert models that can be used
in separate node instances within the same workflow.
Key Features:
- Per-transformer cache isolation (multiple instances supported)
- Lightweight cache strategy (warmup + skip interval)
- Memory-efficient caching (detach-only, no clone)
- Automatic state reset per sampling run
- Support for Tensor and Tuple outputs
"""
from __future__ import annotations
import logging
import traceback
import torch
import comfy.model_patcher
import comfy.patcher_extension
from typing import TYPE_CHECKING, Any, Dict, Optional, Tuple
if TYPE_CHECKING:
from comfy.model_patcher import ModelPatcher
logger = logging.getLogger("ComfyUI-CacheDiT-Wan")
# === Per-transformer cache state registry ===
# Key: id(transformer), Value: cache state dict
_wan_cache_registry: Dict[int, Dict[str, Any]] = {}
def _get_or_create_cache_state(transformer_id: int) -> Dict[str, Any]:
"""
Get or create cache state for a specific transformer instance.
This ensures High-Noise and Low-Noise models have independent caches.
"""
if transformer_id not in _wan_cache_registry:
_wan_cache_registry[transformer_id] = {
"enabled": False,
"transformer_id": transformer_id,
"call_count": 0,
"skip_count": 0,
"compute_count": 0,
"last_result": None,
"config": None,
"compute_times": [],
}
return _wan_cache_registry[transformer_id]
class WanCacheConfig:
"""Configuration for Wan2.2 cache optimization."""
def __init__(
self,
warmup_steps: int = 4,
skip_interval: int = 2,
verbose: bool = False,
print_summary: bool = True,
):
self.warmup_steps = warmup_steps
self.skip_interval = skip_interval
self.verbose = verbose
self.print_summary = print_summary
# Runtime state
self.is_enabled = False
self.num_inference_steps: Optional[int] = None
self.current_step: int = 0
def clone(self) -> "WanCacheConfig":
"""Create a copy for cloned models."""
new_config = WanCacheConfig(
warmup_steps=self.warmup_steps,
skip_interval=self.skip_interval,
verbose=self.verbose,
print_summary=self.print_summary,
)
new_config.is_enabled = self.is_enabled
new_config.num_inference_steps = self.num_inference_steps
return new_config
def reset(self):
"""Reset runtime state for new generation."""
self.current_step = 0
def _enable_wan_cache(transformer, config: WanCacheConfig):
"""Enable lightweight cache for Wan2.2 transformer"""
transformer_id = id(transformer)
state = _get_or_create_cache_state(transformer_id)
if hasattr(transformer, '_original_forward_wan'):
if state.get("transformer_id") == transformer_id:
logger.info("[Wan-Cache] Already enabled, resetting state")
state.update({
"call_count": 0,
"skip_count": 0,
"compute_count": 0,
"last_result": None,
"compute_times": [],
})
return
# Save original forward
transformer._original_forward_wan = transformer.forward
# Initialize state
state.update({
"enabled": True,
"transformer_id": transformer_id,
"call_count": 0,
"skip_count": 0,
"compute_count": 0,
"last_result": None,
"config": config,
"compute_times": [],
})
def cached_forward(*args, **kwargs):
state = _get_or_create_cache_state(transformer_id)
state["call_count"] += 1
call_id = state["call_count"]
cache_config = state.get("config")
warmup_steps = cache_config.warmup_steps if cache_config else 4
skip_interval = cache_config.skip_interval if cache_config else 2
# Debug logging for first few calls
if call_id <= 5 and cache_config and cache_config.verbose:
logger.info(
f"[Wan-Cache] Call #{call_id} (transformer {transformer_id}), "
f"warmup={warmup_steps}, skip={skip_interval}"
)
# Phase 1: Warmup - always compute
if call_id <= warmup_steps:
import time
start = time.time()
result = transformer._original_forward_wan(*args, **kwargs)
elapsed = time.time() - start
state["compute_count"] += 1
state["compute_times"].append(elapsed)
# Cache result - CRITICAL: use detach() only, NO clone()
if isinstance(result, torch.Tensor):
state["last_result"] = result.detach()
elif isinstance(result, tuple):
# Handle tuple of tensors (Wan model may return tuples)
state["last_result"] = tuple(
r.detach() if isinstance(r, torch.Tensor) else r
for r in result
)
else:
state["last_result"] = result
if call_id <= 3 and cache_config and cache_config.verbose:
logger.info(f"[Wan-Cache] Warmup step {call_id}/{warmup_steps}, cached result")
return result
# Phase 2: Post-warmup - selective compute
steps_after_warmup = call_id - warmup_steps
should_compute = (steps_after_warmup % skip_interval == 0)
cache_valid = state["last_result"] is not None
if not should_compute and cache_valid:
# Use cached result
state["skip_count"] += 1
cached_result = state["last_result"]
if call_id <= 10 and cache_config and cache_config.verbose:
logger.info(
f"[Wan-Cache] Step {call_id}: using cache "
f"(skip {state['skip_count']}/{call_id})"
)
return cached_result
else:
# Compute and update cache
import time
start = time.time()
result = transformer._original_forward_wan(*args, **kwargs)
elapsed = time.time() - start
state["compute_count"] += 1
state["compute_times"].append(elapsed)
# Update cache - CRITICAL: use detach() only
if isinstance(result, torch.Tensor):
state["last_result"] = result.detach()
elif isinstance(result, tuple):
state["last_result"] = tuple(
r.detach() if isinstance(r, torch.Tensor) else r
for r in result
)
else:
state["last_result"] = result
if call_id <= 10 and cache_config and cache_config.verbose:
logger.info(
f"[Wan-Cache] Step {call_id}: computed "
f"({state['compute_count']}/{call_id}, {elapsed:.3f}s)"
)
return result
# Replace forward method
transformer.forward = cached_forward
logger.info(
f"[Wan-Cache] Enabled for transformer {transformer_id}: "
f"warmup={config.warmup_steps}, skip_interval={config.skip_interval}"
)
def _refresh_wan_cache(transformer, config: WanCacheConfig):
"""
Refresh Wan cache for new sampling run.
CRITICAL: This is called at the start of each sampling task (KSampler run).
We MUST reset call_count and last_result to prevent reusing data from
previous generations, which would cause artifacts.
"""
transformer_id = id(transformer)
state = _get_or_create_cache_state(transformer_id)
try:
# Reset ALL runtime state (critical for multi-generation workflows)
state["call_count"] = 0
state["skip_count"] = 0
state["compute_count"] = 0
state["last_result"] = None
state["compute_times"] = []
state["config"] = config
if config.verbose:
logger.info(
f"[Wan-Cache] โป๏ธ Reset for new sampling: transformer {transformer_id}, "
f"{config.num_inference_steps} steps"
)
except Exception as e:
logger.error(f"[Wan-Cache] Refresh failed: {e}")
traceback.print_exc()
def _get_wan_cache_stats(transformer_id: int):
"""Get statistics from Wan cache for a specific transformer."""
if transformer_id not in _wan_cache_registry:
return None
state = _wan_cache_registry[transformer_id]
if not state.get("enabled"):
return None
total_calls = state["call_count"]
cache_hits = state["skip_count"]
compute_count = state["compute_count"]
if total_calls == 0:
return None
cache_hit_rate = (cache_hits / total_calls) * 100
avg_time = sum(state["compute_times"]) / max(len(state["compute_times"]), 1)
estimated_speedup = total_calls / max(compute_count, 1)
return {
"transformer_id": transformer_id,
"total_calls": total_calls,
"computed_calls": compute_count,
"cached_calls": cache_hits,
"cache_hit_rate": cache_hit_rate,
"estimated_speedup": estimated_speedup,
"avg_compute_time": avg_time,
}
def _wan_outer_sample_wrapper(executor, *args, **kwargs):
"""
OUTER_SAMPLE wrapper for Wan2.2.
This is called at the CFGGuider.sample level BEFORE each sampling task.
It ensures cache state is properly reset for each generation, preventing
cross-contamination between multiple generations.
Arguments:
- executor: the original CFGGuider.sample method
- executor.class_obj: the CFGGuider instance
- args[0]: noise
- args[1]: latent_image
- args[2]: sampler (KSAMPLER)
- args[3]: sigmas
"""
guider = executor.class_obj
orig_model_options = guider.model_options
transformer = None
config = None
try:
# Clone model options (standard ComfyUI pattern)
guider.model_options = comfy.model_patcher.create_model_options_clone(orig_model_options)
# Get config
config: WanCacheConfig = guider.model_options.get("transformer_options", {}).get("wan_cache")
if config is None:
return executor(*args, **kwargs)
# Clone and reset config
config = config.clone()
config.reset()
guider.model_options["transformer_options"]["wan_cache"] = config
# Extract num_inference_steps from sigmas (4th positional arg)
sigmas = args[3] if len(args) > 3 else kwargs.get("sigmas")
if sigmas is not None:
num_steps = len(sigmas) - 1
config.num_inference_steps = num_steps
# Get transformer
model_patcher = guider.model_patcher
if hasattr(model_patcher, 'model') and hasattr(model_patcher.model, 'diffusion_model'):
transformer = model_patcher.model.diffusion_model
transformer_id = id(transformer)
# Check if cache already enabled for this transformer
cache_already_enabled = hasattr(transformer, '_original_forward_wan')
if config.num_inference_steps is not None:
if not cache_already_enabled:
# First time: enable cache
logger.info(
f"[Wan-Cache] ๐ Enabling for transformer {transformer_id}: "
f"{config.num_inference_steps} steps"
)
_enable_wan_cache(transformer, config)
config.is_enabled = True
else:
# Subsequent runs: REFRESH (reset state)
logger.info(
f"[Wan-Cache] โป๏ธ Refreshing for transformer {transformer_id}: "
f"{config.num_inference_steps} steps"
)
_refresh_wan_cache(transformer, config)
config.is_enabled = True
# Execute sampling
result = executor(*args, **kwargs)
# Print summary
if config.print_summary and transformer is not None:
transformer_id = id(transformer)
stats = _get_wan_cache_stats(transformer_id)
if stats:
logger.info(
f"\nโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ\n"
f"โ Wan Cache Optimizer - Performance Summary โ\n"
f"โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฃ\n"
f"โ Transformer ID: {transformer_id:>10} โ\n"
f"โ Total Calls: {stats['total_calls']:>4} forward passes โ\n"
f"โ Computed: {stats['computed_calls']:>4} ({100*stats['computed_calls']/stats['total_calls']:>5.1f}%) โ\n"
f"โ Cached: {stats['cached_calls']:>4} ({stats['cache_hit_rate']:>5.1f}%) โ\n"
f"โ Estimated Speedup: {stats['estimated_speedup']:>5.2f}x โ\n"
f"โ Avg Compute Time: {stats['avg_compute_time']:>6.3f}s โ\n"
f"โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ"
)
return result
except Exception as e:
logger.error(f"[Wan-Cache] OUTER_SAMPLE wrapper failed: {e}")
traceback.print_exc()
return executor(*args, **kwargs)
finally:
# Restore original model options
guider.model_options = orig_model_options
# =============================================================================
# Node Definition
# =============================================================================
class WanCacheOptimizer:
"""
Wan2.2 Cache Optimizer Node
Accelerates Wan2.2 (DiT + MoE) inference using lightweight cache strategy.
Supports multiple instances (High-Noise + Low-Noise experts) in same workflow.
Features:
- Per-transformer cache isolation (id-based registry)
- Warmup + skip interval strategy
- Memory-efficient (detach-only, no clone)
- Auto-reset per sampling run (OUTER_SAMPLE wrapper)
"""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"model": ("MODEL",),
"warmup_steps": ("INT", {
"default": 4,
"min": 1,
"max": 20,
"step": 1,
"tooltip": "Number of initial steps to always compute (build cache baseline)\n"
"้ข็ญๆญฅๆฐ๏ผๅNๆญฅๅฟ
้กป่ฎก็ฎ๏ผๅปบ็ซ็ผๅญๅบ็บฟ๏ผ\n"
"Recommended: 3-6 for balanced quality/speed"
}),
"skip_interval": ("INT", {
"default": 2,
"min": 2,
"max": 10,
"step": 1,
"tooltip": "Compute every Nth step after warmup (others use cache)\n"
"่ทณๆญฅ้ด้๏ผ้ข็ญๅๆฏNๆญฅ่ฎก็ฎไธๆฌก๏ผๅ
ถไฝ็จ็ผๅญ๏ผ\n"
"Recommended: 2-3 for ~40-50% cache rate"
}),
"print_summary": ("BOOLEAN", {
"default": True,
"tooltip": "Print performance statistics after generation\n"
"็ๆๅๆๅฐๆง่ฝ็ป่ฎก"
}),
},
}
RETURN_TYPES = ("MODEL",)
RETURN_NAMES = ("optimized_model",)
FUNCTION = "optimize"
CATEGORY = "โก CacheDiT"
DESCRIPTION = (
"Wan2.2 ไธ็จ็ผๅญๅ ้ๅจ / Wan2.2 Cache Accelerator\n\n"
"โจ Features:\n"
"โข Lightweight cache (warmup + skip interval)\n"
"โข Multi-instance support (High-Noise + Low-Noise)\n"
"โข Memory-efficient (detach-only, prevents VAE OOM)\n"
"โข Auto-reset per sampling (clean slate each generation)\n\n"
"๐ Performance (warmup=4, skip=2, 20 steps):\n"
"โข Compute: 12 steps (4 warmup + 8 selective)\n"
"โข Cache: 8 steps (40% cache rate)\n"
"โข Speedup: ~1.7x\n\n"
"๐ง Recommended Settings:\n"
"โข Speed: warmup=3, skip=2 (50% cache, ~2.0x)\n"
"โข Balanced โญ: warmup=4, skip=2 (40% cache, ~1.7x)\n"
"โข Quality: warmup=6, skip=3 (30% cache, ~1.4x)"
)
def optimize(
self,
model,
warmup_steps: int = 4,
skip_interval: int = 2,
print_summary: bool = True,
):
"""Apply Wan2.2 specific cache optimization."""
# Clone model (standard ComfyUI pattern)
model = model.clone()
# Create config
config = WanCacheConfig(
warmup_steps=warmup_steps,
skip_interval=skip_interval,
verbose=False,
print_summary=print_summary,
)
# Store config in transformer_options
if "transformer_options" not in model.model_options:
model.model_options["transformer_options"] = {}
model.model_options["transformer_options"]["wan_cache"] = config
# Register wrapper using ComfyUI's patcher_extension system
# This ensures cache state is reset at the start of each sampling task
try:
model.add_wrapper_with_key(
comfy.patcher_extension.WrappersMP.OUTER_SAMPLE,
"wan_cache",
_wan_outer_sample_wrapper
)
logger.info(
f"[Wan-Cache] โ Node configured: warmup={warmup_steps}, skip={skip_interval}"
)
except Exception as e:
logger.error(f"[Wan-Cache] Failed to register wrapper: {e}")
traceback.print_exc()
return (model,)
# =============================================================================
# Node Registration
# =============================================================================
NODE_CLASS_MAPPINGS = {
"WanCacheOptimizer": WanCacheOptimizer,
}
NODE_DISPLAY_NAME_MAPPINGS = {
"WanCacheOptimizer": "โก Wan Cache Optimizer",
}