-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathgeneration_orchestrator.py
More file actions
3514 lines (3105 loc) · 177 KB
/
Copy pathgeneration_orchestrator.py
File metadata and controls
3514 lines (3105 loc) · 177 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
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Generation Orchestrator - Main Entry Point
Coordinates the entire grid generation workflow
"""
import os
import json
import time
import re
import gc
import threading
import torch
import hashlib
import folder_paths
import comfy.sd # Required for async workers
from comfy.model_management import InterruptProcessingException
from .trigger_words import collect_unique_prompts_with_triggers, build_prompt_with_triggers, clear_trigger_caches
from .batch_encoding import batch_encode_prompts, encode_prompt_with_combinators
from .manifest_utils import load_existing_manifest, save_manifest
from .model_loader import (
load_checkpoint, load_loras, cleanup_model_references,
get_latent_channels, load_loras_for_preencoding,
print_incompatible_loras_summary, load_diffusion_model_and_clip,
load_vae_by_name
)
from .lora_utils import expand_lora_folder
from .image_generation import (
generate_image, flush_batch_with_vae, flush_batch_with_remote_vae,
create_image_metadata, decode_latent_with_vae, calculate_eta, print_generation_progress
)
from .config_utils import sanitize_session_name
from .html_generator import get_html_template
from .conditioning_cache import ConditioningCache
from .remote_vae import RemoteVAEDecodeWorker, is_remote_vae_available, get_endpoint_names, INSTALL_INSTRUCTIONS
from . import distribution
try:
from server import PromptServer
except ImportError:
PromptServer = None
def setup_session_directories(session_name):
"""Create session directories and return paths."""
base_dir = os.path.join(folder_paths.get_output_directory(), "benchmarks", session_name)
img_dir = os.path.join(base_dir, "images")
manifest_path = os.path.join(base_dir, "manifest.json")
os.makedirs(base_dir, exist_ok=True)
os.makedirs(img_dir, exist_ok=True)
return {
"base": base_dir,
"images": img_dir,
"manifest": manifest_path
}
def initialize_remote_vae(remote_vae_endpoint, img_dir, manifest_path, existing_data, session_name, unique_id, image_format="webp"):
"""Initialize remote VAE worker if enabled."""
if not remote_vae_endpoint or remote_vae_endpoint == "None":
return None
if remote_vae_endpoint in ["SD", "SDXL", "Flux", "HunyuanVideo"]:
# Pass the endpoint NAME through to the worker; the companion plugin
# (ComfyUI-USCG-RemoteVAE) resolves the name to the actual URL.
actual_endpoint = remote_vae_endpoint
print(f"[GridTester] 🌐 Using {remote_vae_endpoint} remote VAE (resolved by companion plugin)")
elif remote_vae_endpoint == "Auto (Experimental)":
print(f"[GridTester] 🌐 Auto mode selected - worker will initialize on first flush")
return None
else:
actual_endpoint = remote_vae_endpoint
print(f"[GridTester] 🌐 Using custom endpoint: {actual_endpoint}")
worker = RemoteVAEDecodeWorker(
endpoint=actual_endpoint,
img_dir=img_dir,
manifest_path=manifest_path,
existing_data=existing_data,
session_name=session_name,
unique_id=unique_id,
image_format=image_format
)
print(f"[GridTester] 🌐 Remote VAE worker started")
return worker
REMOTE_VAE_PREFIX = "remote:"
def is_remote_vae(vae_string):
"""Check if a VAE value is a per-config remote URL (e.g. 'remote:http://...')."""
return isinstance(vae_string, str) and vae_string.startswith(REMOTE_VAE_PREFIX)
def extract_remote_vae_url(vae_string):
"""Extract the URL from a remote VAE string like 'remote:http://...'.
If the URL is empty:
- When the companion plugin is NOT installed, raise RuntimeError with
install instructions (the most likely user state — Builder UI shows
install card so URL field is empty).
- When the companion IS installed, raise ValueError asking the user to
pick a preset or enter a URL.
"""
url = vae_string[len(REMOTE_VAE_PREFIX):]
if not url:
if not is_remote_vae_available():
raise RuntimeError(INSTALL_INSTRUCTIONS)
raise ValueError(
"[GridTester] Per-config remote VAE URL is empty.\n"
"Please provide a valid endpoint URL in the config builder's VAE section."
)
return url
def _flush_pending_batch(pending_batch, current_vae_is_remote, current_remote_vae_url,
per_config_remote_workers, use_remote_vae, remote_vae_worker,
loaded_vae, paths, existing_data, session_name, manifest_path, unique_id,
config_overrides_vae=False, image_format="webp"):
"""Flush pending batch using the appropriate VAE decode method.
Handles three-way dispatch:
1. Per-config remote VAE (current_vae_is_remote) — uses per-config worker
2. Global remote VAE (use_remote_vae) — uses global remote_vae_worker
ONLY when config_overrides_vae is False (config VAE is "Default")
3. Local VAE — uses loaded_vae for local decode
Config Builder VAE settings take priority over the sampler node's
remote_vae_endpoint when a config explicitly sets a non-Default VAE.
"""
if not pending_batch:
return
if current_vae_is_remote and current_remote_vae_url:
worker = per_config_remote_workers.get(current_remote_vae_url)
if worker:
flush_batch_with_remote_vae(pending_batch, worker, existing_data, session_name)
else:
print(f"[GridTester] ⚠️ No remote worker for {current_remote_vae_url}, falling back to local VAE")
flush_batch_with_vae(pending_batch, loaded_vae, paths["images"], existing_data, session_name, manifest_path, unique_id, image_format=image_format)
elif not config_overrides_vae and use_remote_vae and remote_vae_worker:
flush_batch_with_remote_vae(pending_batch, remote_vae_worker, existing_data, session_name)
else:
flush_batch_with_vae(pending_batch, loaded_vae, paths["images"], existing_data, session_name, manifest_path, unique_id, image_format=image_format)
def _cleanup_per_config_remote_workers(per_config_remote_workers):
"""Shut down all per-config remote VAE workers."""
for url, worker in per_config_remote_workers.items():
try:
print(f"[GridTester] 🌐 Waiting for per-config remote VAE ({url})...")
worker.wait_completion()
worker.stop()
except Exception as e:
print(f"[GridTester] ⚠️ Error stopping per-config remote worker ({url}): {e}")
def calculate_clip_hash(clip_model):
"""Calculate a hash of the CLIP model for cache validation."""
try:
if hasattr(clip_model, 'state_dict'):
state_dict = clip_model.state_dict()
model_signature = str([(k, tuple(v.shape)) for k, v in list(state_dict.items())[:10]])
elif hasattr(clip_model, 'cond_stage_model'):
model_signature = str(type(clip_model.cond_stage_model))
else:
model_signature = str(type(clip_model))
return hashlib.md5(model_signature.encode()).hexdigest()[:16]
except:
return "unknown"
def check_if_job_completed(existing_items, conf, seed, width, height, batch_idx, positive_prompt, negative_prompt, has_optional_inputs=False):
"""Independent check to see if a specific generation job already exists.
When has_optional_inputs is True, we cannot reliably detect changes from
upstream nodes (models, LoRAs, conditionings, latents), so we disable
skip detection entirely and return -1 (no match) to force re-generation.
"""
# When optional inputs are connected, we can't reliably match on model,
# lora, prompts, or latents because those may come from upstream nodes
# whose changes we can't detect. Disable skip detection entirely.
if has_optional_inputs:
return -1
FLOAT_TOLERANCE = 0.0001
for idx, item in enumerate(existing_items):
if item.get("seed") != seed: continue
if item.get("width") != width: continue
if item.get("height") != height: continue
if item.get("batch_idx", 0) != batch_idx: continue
if item.get("sampler") != conf["sampler"]: continue
if item.get("scheduler") != conf["scheduler"]: continue
# Check attention mode (default = no attention_mode key or "default")
item_attn = item.get("attention_mode", "default")
conf_attn = conf.get("attention_mode", "default")
if item_attn != conf_attn: continue
try:
if abs(float(item.get("steps")) - float(conf["steps"])) > FLOAT_TOLERANCE: continue
if abs(float(item.get("cfg")) - float(conf["cfg"])) > FLOAT_TOLERANCE: continue
if abs(float(item.get("denoise")) - float(conf["denoise"])) > FLOAT_TOLERANCE: continue
except (ValueError, TypeError):
continue
# Standard matching - check model, lora, and prompts
if item.get("model") != conf["model"]: continue
if item.get("positive", "").strip() != positive_prompt.strip(): continue
if item.get("negative", "").strip() != negative_prompt.strip(): continue
item_lora = item.get("lora", "None")
conf_lora = conf.get("lora_expanded", "None")
if item_lora != conf_lora: continue
# Check model_type and text_encoders — different text encoders produce
# different conditioning even with the same model file, so they must
# NOT be considered duplicate jobs
item_model_type = item.get("model_type", "checkpoint")
conf_model_type = conf.get("model_type", "checkpoint")
if item_model_type != conf_model_type: continue
item_te = item.get("text_encoders", [])
conf_te = conf.get("text_encoders", [])
if item_te != conf_te: continue
# Check clip_type — different clip types produce different conditioning
item_clip_type = item.get("clip_type", "stable_diffusion")
conf_clip_type = conf.get("clip_type", "stable_diffusion")
if item_clip_type != conf_clip_type: continue
# Check clip_skip — different clip_skip values produce different conditioning
item_clip_skip = item.get("clip_skip", 0)
conf_clip_skip = conf.get("clip_skip", 0)
if item_clip_skip != conf_clip_skip: continue
# Check VAE — different VAEs produce different decoded images.
# Normalize "None"/empty to "Default" so legacy configs that emit
# "vae": "None" don't appear distinct from configs that omit the
# key entirely.
def _norm_vae(v):
if not v or str(v) in ("None", "none"):
return "Default"
return v
item_vae = _norm_vae(item.get("vae", "Default"))
conf_vae = _norm_vae(conf.get("vae", "Default"))
if item_vae != conf_vae: continue
return idx
return -1
def _ltx_sort_components(x):
"""Return tuple of LTX-specific sort components (None for non-LTX entries)."""
if x.get('model_type') != 'ltx_video':
return (None, None, None, None)
cm = x.get('clip_models') or []
return (
tuple(cm),
x.get('vae_video', ''),
x.get('vae_audio', ''),
x.get('latent_upscaler', ''),
)
def get_model_cache_key(conf):
"""Generate a cache key that uniquely identifies the model+clip combination."""
model_type = conf.get("model_type", "checkpoint")
if model_type == "checkpoint":
return conf["model"]
elif model_type == "ltx_video":
clip_models = conf.get("clip_models", ["", ""])
clip_a = clip_models[0] if len(clip_models) > 0 else ""
clip_b = clip_models[1] if len(clip_models) > 1 else ""
return (
"ltx::" + conf["model"] + "::" + clip_a + "::" + clip_b + "::" +
conf.get("vae_video", "") + "::" + conf.get("vae_audio", "") + "::" +
conf.get("latent_upscaler", "")
)
else:
te_key = "|".join(sorted(conf.get("text_encoders", [])))
return f"{conf['model']}::{model_type}::{te_key}"
def _build_ltx_manifest_entry(conf, gen_result, output_filename, gen_index=None, session_name=""):
"""Build a manifest entry for an LTX video. Mirrors image-gen entry shape
but with media_type='video' and LTX-specific fields.
The `file` key is the ComfyUI /view? URL the dashboard uses to fetch the mp4
via Comfy's standard view endpoint — same format the image-gen path uses
(see image_generation.py:844)."""
import random
mp4_filename = output_filename + ".mp4"
file_url = f"/view?filename={mp4_filename}&type=output&subfolder=benchmarks/{session_name}/images"
# Unique timestamp-based id (matches image_generation.py:828 pattern). Used by
# the dashboard for sorting, position tracking, and DOM identity.
item_id = int(time.time() * 100000) + random.randint(0, 1000)
return {
"id": item_id,
"gen_index": gen_index,
"media_type": "video",
# The dashboard's loader reads `file` (ComfyUI /view? URL) for the actual
# video src. image_path/video_path stored as duplicates for any code that
# needs the absolute disk path.
"file": file_url,
"image_path": gen_result["video_path"],
"video_path": gen_result["video_path"],
"preview_path": gen_result.get("preview_path"),
"width": gen_result["width"],
"height": gen_result["height"],
"duration_seconds": gen_result["duration_seconds"],
"frame_rate": gen_result["fps"],
"frames": gen_result["frames"],
"model_type": "ltx_video",
"model": conf["model"],
"clip_models": conf.get("clip_models", []),
"vae_video": conf.get("vae_video", ""),
"vae_audio": conf.get("vae_audio", ""),
"latent_upscaler": conf.get("latent_upscaler", ""),
"sampler_stage1": conf.get("sampler_stage1", ""),
"sigmas_stage1": conf.get("sigmas_stage1", ""),
"sampler_stage2": conf.get("sampler_stage2", ""),
"sigmas_stage2": conf.get("sigmas_stage2", ""),
"image_strength_stage1": conf.get("image_strength_stage1", 0.8),
"image_strength_stage2": conf.get("image_strength_stage2", 1.0),
"img_compression": conf.get("img_compression", 18),
"input_image": conf.get("input_image"),
"audio_mode": conf.get("audio_mode", "on"),
"cfg": conf.get("cfg", 1.0),
"seed": conf.get("seed"),
"positive": conf.get("positive", ""),
"negative": conf.get("negative", ""),
"lora": conf.get("lora", "None"),
"duration": gen_result.get("duration", 0),
"favorited": False,
"rejected": False,
"note": "",
}
def load_model_by_type(conf, ckpt_name, use_remote_vae, optional_model, optional_clip, optional_vae,
optional_positive, optional_negative, loaded_clip, loaded_vae, model_cache):
"""Dispatch to correct loader based on model_type in config."""
model_type = conf.get("model_type", "checkpoint")
target = conf["model"]
if model_type == "checkpoint":
return load_checkpoint(
target, ckpt_name, use_remote_vae,
optional_model, optional_clip, optional_vae,
optional_positive, optional_negative,
loaded_clip, loaded_vae, model_cache=model_cache
)
else:
# diffusion_model or gguf
return load_diffusion_model_and_clip(
model_name=target,
model_type=model_type,
text_encoder_paths=conf.get("text_encoders", []),
clip_type_str=conf.get("clip_type", "stable_diffusion"),
gguf_options=conf.get("gguf_options"),
use_remote_vae=use_remote_vae,
optional_model=optional_model,
optional_clip=optional_clip,
optional_vae=optional_vae,
model_cache=model_cache
)
def run_deferred_upscales(
deferred_queue, upscale_settings, session_settings,
loaded_vae, patched_model, patched_clip, conditioning_cache,
paths, existing_data, session_name, unique_id,
PromptServer, config_overrides_vae=None
):
"""
Process deferred upscale jobs after generation completes.
Runs all pipeline chains for each queued image.
Called BEFORE finalization cleanup so VAE/model/CLIP are still loaded.
"""
if not deferred_queue:
return
from .image_generation import upscale_image, decode_latent_with_vae, create_image_metadata
import itertools as up_itertools
import random as up_random
from PIL import Image as PILImage
import comfy.model_management as mm
import numpy as np
import torch
pipelines = upscale_settings.get("pipelines", [])
if not pipelines:
return
total_jobs = len(deferred_queue)
print(f"\n[GridTester] 🔄 Starting deferred upscale phase: {total_jobs} images")
upscale_durations = []
for job_idx, job in enumerate(deferred_queue):
# Check for interrupt
if mm.processing_interrupted():
print(f"\n[GridTester] 🛑 INTERRUPTED during deferred upscaling")
break
conf = job["config"]
pipe_w = job["width"]
pipe_h = job["height"]
current_seed = job["seed"]
actual_positive_prompt = job["actual_positive_prompt"]
actual_negative_prompt = job["actual_negative_prompt"]
# Find the base image in the manifest by matching identity
base_item = None
for item in existing_data.get("items", []):
if (item.get("seed") == current_seed and
item.get("width") == pipe_w and
item.get("height") == pipe_h and
not item.get("upscaled") and
item.get("positive") == actual_positive_prompt):
base_item = item
break
if not base_item:
print(f"[GridTester] ⚠️ Deferred upscale #{job_idx+1}: base image not found in manifest, skipping")
continue
base_filename = base_item.get("filename")
if not base_filename:
print(f"[GridTester] ⚠️ Deferred upscale #{job_idx+1}: no filename in manifest, skipping")
continue
base_image_path = os.path.join(paths["images"], base_filename)
if not os.path.exists(base_image_path):
print(f"[GridTester] ⚠️ Deferred upscale #{job_idx+1}: file not found: {base_filename}, skipping")
continue
# Check if already upscaled (resume support)
already_upscaled = False
for item in existing_data.get("items", []):
if (item.get("upscaled") and
item.get("seed") == current_seed and
item.get("positive") == actual_positive_prompt and
item.get("width") != pipe_w):
already_upscaled = True
break
if already_upscaled:
print(f"[GridTester] ⏭️ Deferred upscale #{job_idx+1}: already upscaled, skipping")
continue
# Load base image from disk and VAE-encode back to latent
try:
pil_image = PILImage.open(base_image_path).convert("RGB")
img_array = np.array(pil_image).astype(np.float32) / 255.0
img_tensor = torch.from_numpy(img_array).unsqueeze(0)
encoded = loaded_vae.encode(img_tensor[:, :, :, :3])
result_latent = {"samples": encoded}
except Exception as e:
print(f"[GridTester] ⚠️ Deferred upscale #{job_idx+1}: failed to load/encode: {e}")
continue
# Look up conditioning from cache
final_positive = conditioning_cache["positive"].get(actual_positive_prompt)
final_negative = conditioning_cache["negative"].get(actual_negative_prompt)
if final_positive is None or final_negative is None:
print(f"[GridTester] ⚠️ Deferred upscale #{job_idx+1}: conditioning not in cache, re-encoding")
try:
clip_skip = conf.get("clip_skip", 0)
if final_positive is None:
final_positive = encode_prompt_with_combinators(patched_clip, actual_positive_prompt, clip_skip)
conditioning_cache["positive"][actual_positive_prompt] = final_positive
if final_negative is None:
final_negative = encode_prompt_with_combinators(patched_clip, actual_negative_prompt, clip_skip)
conditioning_cache["negative"][actual_negative_prompt] = final_negative
except Exception as e:
print(f"[GridTester] ⚠️ Deferred upscale #{job_idx+1}: re-encode failed: {e}, skipping")
continue
# HiRes prompt adjustment
hires_positive_cond = final_positive
hires_prompt_active = False
hires_prompt_behavior_rt = ""
hires_prompt_text_rt = ""
if upscale_settings.get("hires_prompt_adjust") and upscale_settings.get("hires_prompt_text", "").strip():
hires_prompt_behavior_rt = upscale_settings.get("hires_prompt_behavior", "append_end")
hires_prompt_text_rt = upscale_settings["hires_prompt_text"].strip()
if hires_prompt_behavior_rt == "prepend":
adjusted_prompt = hires_prompt_text_rt + " " + actual_positive_prompt
elif hires_prompt_behavior_rt == "append_end":
adjusted_prompt = actual_positive_prompt + " " + hires_prompt_text_rt
elif hires_prompt_behavior_rt == "replace":
adjusted_prompt = hires_prompt_text_rt
else:
adjusted_prompt = actual_positive_prompt
hires_cond = conditioning_cache["positive"].get(adjusted_prompt)
if hires_cond is not None:
hires_positive_cond = hires_cond
hires_prompt_active = True
job_start_time = time.time()
upscale_combo_idx = 0
for pipeline_idx, pipeline in enumerate(pipelines):
if pipeline.get("active", True) is False:
continue
pipeline_name = pipeline.get("name", f"Pipeline {pipeline_idx + 1}")
pipeline_steps = pipeline.get("steps", [])
if not pipeline_steps:
continue
pipe_latent = result_latent
pipe_w_current = pipe_w
pipe_h_current = pipe_h
expanded_steps = []
for step in pipeline_steps:
if step.get("active", True) is False:
continue
repeat = max(1, int(step.get("repeat", 1)))
for _ in range(repeat):
expanded_steps.append(step)
for step_idx, ucfg in enumerate(expanded_steps):
mode = ucfg.get("mode", "hires_only")
show_hires = mode in ("hires_only", "model_then_hires")
show_model = mode in ("model_only", "model_then_hires")
raw_ratios = str(ucfg.get("upscale_ratios", "1.5"))
ratios = [float(r.strip()) for r in raw_ratios.split(",") if r.strip()] or [1.5]
raw_denoise = str(ucfg.get("hires_denoise", "0.3"))
denoises = [float(d.strip()) for d in raw_denoise.split(",") if d.strip()] or [0.3]
models = ucfg.get("upscale_models", []) or [""]
if show_hires and show_model:
combos = list(up_itertools.product(models, ratios, denoises))
elif show_hires:
combos = list(up_itertools.product([""], ratios, denoises))
elif show_model:
combos = list(up_itertools.product(models, [1.0], [0.0]))
else:
combos = []
for combo in combos:
up_model, up_ratio, up_denoise = combo
single_config = {
"mode": mode,
"upscale_model": up_model,
"upscale_ratio": up_ratio,
"hires_denoise": up_denoise,
"hires_steps": ucfg.get("hires_steps", 0),
"tiled_vae": ucfg.get("tiled_vae", False),
"tile_size": ucfg.get("tile_size", 512),
"upscale_size": ucfg.get("upscale_size", "2.0"),
"resize_method": ucfg.get("resize_method", "bilinear"),
"hires_tiled_sampling": ucfg.get("hires_tiled_sampling", False),
"hires_tile_width": ucfg.get("hires_tile_width", 512),
"hires_tile_height": ucfg.get("hires_tile_height", 512),
"hires_mask_blur": ucfg.get("hires_mask_blur", 8),
"hires_tile_padding": ucfg.get("hires_tile_padding", 32),
"hires_force_uniform_tiles": ucfg.get("hires_force_uniform_tiles", False)
}
up_positive = hires_positive_cond if (show_hires and hires_prompt_active) else final_positive
upscale_result, upscale_duration = upscale_image(
pipe_latent, loaded_vae, patched_model, single_config,
conf, up_positive, final_negative, pipe_w_current, pipe_h_current
)
is_last_step = step_idx == len(expanded_steps) - 1
is_last_combo = combo == combos[-1]
is_final_output = is_last_step and is_last_combo
if isinstance(upscale_result, dict) and "samples" in upscale_result:
upscaled_pil = decode_latent_with_vae(loaded_vae, upscale_result["samples"])
up_w, up_h = upscaled_pil.size
if is_final_output:
upscale_id = int(time.time() * 100000) + up_random.randint(0, 1000)
upscaled_filename = f"img_{upscale_id}_upscaled.webp"
upscaled_pil.save(
os.path.join(paths["images"], upscaled_filename),
format="WEBP", quality=95
)
elif isinstance(upscale_result, PILImage.Image):
up_w, up_h = upscale_result.size
if is_final_output:
upscale_id = int(time.time() * 100000) + up_random.randint(0, 1000)
upscaled_filename = f"img_{upscale_id}_upscaled.webp"
upscale_result.save(
os.path.join(paths["images"], upscaled_filename),
format="WEBP", quality=95
)
else:
continue
if not is_final_output:
if isinstance(upscale_result, dict) and "samples" in upscale_result:
pipe_latent = upscale_result
pipe_w_current = up_w
pipe_h_current = up_h
continue
# Final output: create manifest entry
upscaled_meta = create_image_metadata(
conf, up_w, up_h, upscale_duration, current_seed, job.get("batch_idx", 0),
actual_positive_prompt, actual_negative_prompt,
gen_index=job.get("gen_index", 0)
)
upscaled_meta["id"] = upscale_id
upscaled_meta["filename"] = upscaled_filename
upscaled_meta["upscaled"] = True
upscaled_meta["upscale_pipeline"] = pipeline_name
upscaled_meta["upscale_mode"] = mode
upscaled_meta["upscale_ratio"] = up_ratio
upscaled_meta["upscale_denoise"] = up_denoise
if up_model:
upscaled_meta["upscale_model"] = up_model
if hires_prompt_active:
upscaled_meta["hires_prompt_behavior"] = hires_prompt_behavior_rt
upscaled_meta["hires_prompt_text"] = hires_prompt_text_rt
existing_data["items"].append(upscaled_meta)
upscale_combo_idx += 1
if upscale_combo_idx > 0:
save_manifest(paths["manifest"], existing_data)
if PromptServer is not None:
try:
PromptServer.instance.send_sync("ultimate_grid.update_data", {
"node": unique_id,
"session_name": session_name,
"new_items": [existing_data["items"][-1]]
})
except Exception:
pass
job_duration = time.time() - job_start_time
upscale_durations.append(job_duration)
# Progress reporting
if PromptServer is not None:
try:
avg_dur = sum(upscale_durations) / len(upscale_durations)
remaining = (total_jobs - (job_idx + 1)) * avg_dur
mins = int(remaining // 60)
secs = int(remaining % 60)
eta_str = f"{mins}m {secs}s" if mins > 0 else f"{secs}s"
PromptServer.instance.send_sync("ultimate_grid.progress", {
"node": unique_id,
"session_name": session_name,
"current_job": job_idx + 1,
"total_jobs": total_jobs,
"progress_pct": int(((job_idx + 1) / total_jobs) * 100),
"eta_str": eta_str,
"avg_duration": round(avg_dur, 1),
"last_duration": round(job_duration, 1),
"phase": "upscaling",
})
except Exception:
pass
print(f"[GridTester] 🔄 Deferred upscale {job_idx+1}/{total_jobs} complete ({job_duration:.1f}s)")
print(f"[GridTester] ✅ Deferred upscale phase complete: {len(upscale_durations)}/{total_jobs} images upscaled")
def _expand_lora_weight_arrays(expanded_configs):
"""
Expand LoRA weight array bracket notation into Cartesian product of configs.
Input format per lora part: "name:[0.5, 0.8]:1.0" or "name:0.5:[0.7, 1.0]"
Weight arrays use brackets in the STRENGTH fields (after first colon),
while folder random syntax uses brackets in the NAME field (before first colon).
If multiple loras in the same config have weight arrays, produces a Cartesian
product of all combinations:
lora1:[0.5, 1.0] + lora2:[0.7, 1.0] → 4 configs
"""
import re
from itertools import product as itertools_product
result = []
weight_array_pattern = re.compile(r'\[([^\]]+)\]')
for conf in expanded_configs:
lora_str = conf.get("lora", "None")
if lora_str == "None" or ":" not in lora_str:
result.append(conf)
continue
lora_parts = lora_str.split(" + ")
# Check each part for weight arrays (brackets in strength fields, not name field)
parts_with_arrays = []
has_weight_arrays = False
for part in lora_parts:
part = part.strip()
colon_idx = part.find(":")
if colon_idx < 0:
# No strength specified — plain lora name
parts_with_arrays.append([(part, None, None)])
continue
name = part[:colon_idx]
strength_str = part[colon_idx + 1:]
# If brackets are in the name portion, it's folder syntax — skip
if "[" in name:
parts_with_arrays.append([(part, None, None)])
continue
# Parse strength fields for bracket arrays
# Format: "model_str:clip_str" where either can be "[val1, val2]"
strength_parts = strength_str.split(":")
model_strs = strength_parts[0] if len(strength_parts) > 0 else "1.0"
clip_strs = strength_parts[1] if len(strength_parts) > 1 else model_strs
# Extract arrays from model strength
model_match = weight_array_pattern.search(model_strs)
if model_match:
model_vals = [v.strip() for v in model_match.group(1).split(",")]
has_weight_arrays = True
else:
model_vals = [model_strs.strip()]
# Extract arrays from clip strength
clip_match = weight_array_pattern.search(clip_strs)
if clip_match:
clip_vals = [v.strip() for v in clip_match.group(1).split(",")]
has_weight_arrays = True
else:
clip_vals = [clip_strs.strip()]
# Build all combinations for this lora part
combos = []
for mv in model_vals:
for cv in clip_vals:
combos.append((name, mv, cv))
parts_with_arrays.append(combos)
if not has_weight_arrays:
result.append(conf)
continue
# Cartesian product across all lora parts
for combo in itertools_product(*parts_with_arrays):
new_lora_parts = []
for item in combo:
name, mv, cv = item
if mv is None:
# Passthrough (folder syntax or plain name)
new_lora_parts.append(name)
else:
new_lora_parts.append(f"{name}:{mv}:{cv}")
new_conf = conf.copy()
new_conf["lora"] = " + ".join(new_lora_parts)
result.append(new_conf)
if len(result) != len(expanded_configs):
print(f"[GridTester] 🎯 LoRA weight arrays expanded: {len(expanded_configs)} → {len(result)} configs")
return result
def run_generation_loop(
self,
ckpt_name, positive_text, negative_text, seed, denoise, vae_batch_size,
overwrite_existing, flush_batch_every, configs_json, resolutions_json,
session_name, unique_id, add_random_seeds_to_gens, lora_triggerwords_mode,
remote_vae_endpoint, save_conditioning_cache_to_file, enable_model_cache,
optional_model, optional_clip, optional_vae,
optional_positive, optional_negative, optional_latent,
distribution_config=None,
session_settings=None
):
"""Main generation loop orchestrator."""
# Clear stale trigger word caches from previous runs (within same ComfyUI session).
# Without this, @lru_cache and _build_prompt_cache can serve outdated results
# if loras_tags.json was updated by a CivitAI fetch in a prior run.
clear_trigger_caches()
from .model_cache import ModelCache
# Initialize Model Cache (or disable completely if user requested)
if enable_model_cache:
model_cache = ModelCache(
max_models=1, # Adjust for your VRAM
max_lora_sets=2, # Adjust for your VRAM
max_lora_files=30, # Adjust for your VRAM
enable_preload=True, # Preloading enabled when cache is on
async_preload=True, # Always async when preloading
cache_device='cpu',
verbose=True
)
else:
# Completely disable entire cache system
print("[GridTester] ⚠️ Model cache DISABLED - all models will load from disk (slower but saves RAM/VRAM)")
model_cache = None
# ==== SETUP ====
session_name = sanitize_session_name(session_name)
paths = setup_session_directories(session_name)
existing_data = load_existing_manifest(paths["manifest"])
existing_data["session_name"] = session_name
from .config_utils import (
parse_json_with_error, parse_float_input, parse_prompt_input_nested,
expand_configs, prepare_input_jobs
)
raw_configs = parse_json_with_error(configs_json, "configs")
denoise_values = parse_float_input(denoise)
resolutions = parse_json_with_error(resolutions_json, "resolutions")
pos_prompts = parse_prompt_input_nested(positive_text)
neg_prompts = parse_prompt_input_nested(negative_text)
extra_seeds = []
if add_random_seeds_to_gens > 0:
import random
extra_seeds = [random.randint(0, 2**32 - 1) for _ in range(add_random_seeds_to_gens)]
expanded = expand_configs(raw_configs, pos_prompts, neg_prompts, denoise_values, seed, extra_seeds, ckpt_name)
expanded.sort(key=lambda x: (
x.get('model_type', 'checkpoint'),
x['model'],
*_ltx_sort_components(x),
tuple(x.get('text_encoders', [])),
x.get('vae', 'Default'),
x['lora'],
x.get('attention_mode', 'default'),
x['positive'],
x['negative'],
))
# ==== EXPAND LORA WEIGHT ARRAYS (Cartesian product) ====
# Format: "lora:[0.5, 0.8]:1.0" → expand into separate configs per strength combo
expanded = _expand_lora_weight_arrays(expanded)
# ==== EXPAND LORA FOLDERS ====
print(f"[GridTester] 🎲 Expanding LoRA folders and random selections...")
for conf in expanded:
if conf["lora"] != "None":
lora_parts = conf["lora"].split(" + ")
expanded_parts = []
for part in lora_parts:
part = part.strip()
if "[" in part and "]" in part:
expanded_lora = expand_lora_folder(part, seed=conf.get("seed"))
if expanded_lora:
if isinstance(expanded_lora, list):
expanded_parts.extend(expanded_lora)
else:
expanded_parts.append(expanded_lora)
else:
expanded_parts.append(part)
conf["lora_expanded"] = " + ".join(expanded_parts) if expanded_parts else "None"
conf["lora"] = conf["lora_expanded"]
else:
conf["lora_expanded"] = "None"
print(f"[GridTester] ✅ LoRA expansion complete")
# ==== VAE VALIDATION FOR NON-CHECKPOINT MODELS ====
# Only error if non-checkpoint model has no VAE source (no optional_vae AND no per-config VAE).
# LTX video configs are exempt — they declare vae_video and vae_audio in their own LTX
# block, validated separately by preflight_ltx() at gen time.
use_remote_vae = remote_vae_endpoint and remote_vae_endpoint != "None"
needs_vae = any(
c.get("model_type", "checkpoint") not in ("checkpoint", "ltx_video")
and c.get("vae", "Default") == "Default"
for c in expanded
)
if needs_vae and not use_remote_vae and optional_vae is None:
raise ValueError(
"GGUF and diffusion models do not include a bundled VAE.\n"
"You must either:\n"
" 1. Connect a VAE to the optional_vae input on the sampler node, or\n"
" 2. Enable remote VAE decoding via remote_vae_endpoint, or\n"
" 3. Set a specific VAE in the config builder for those configs\n"
)
# ==== REGISTER SMART CACHE SCHEDULE ====
if model_cache:
model_cache.register_schedule(expanded)
input_jobs = prepare_input_jobs(optional_latent, resolutions)
# Count total jobs: configs with per-config resolutions provide their own
# width/height and don't multiply with the global input_jobs.
configs_with_res = sum(1 for c in expanded if c.get("resolution") is not None)
configs_without_res = len(expanded) - configs_with_res
total_jobs = configs_with_res + (configs_without_res * len(input_jobs))
print(f"{'='*80}")
print(f"[GridTester] 🚀 GENERATION START")
if configs_with_res > 0:
print(f"[GridTester] 📋 {configs_with_res} configs with per-config resolutions + "
f"{configs_without_res} configs × {len(input_jobs)} resolutions = {total_jobs} total jobs")
else:
print(f"[GridTester] 📋 {len(expanded)} configs × {len(input_jobs)} resolutions = {total_jobs} total jobs")
print(f"{'='*80}")
# ==== OPTIONAL INPUT DETECTION ====
# Track whether any optional inputs are connected - this affects skip/resume logic
has_optional_inputs = any([
optional_model is not None,
optional_clip is not None,
optional_vae is not None,
optional_positive is not None,
optional_negative is not None,
optional_latent is not None
])
if has_optional_inputs and not overwrite_existing:
print(f"[GridTester] ⚠️ Optional inputs connected — job skip/resume DISABLED.")
print(f"[GridTester] ⚠️ Changes to upstream nodes (models, LoRAs, prompts, latents) connected via optional inputs")
print(f"[GridTester] ⚠️ cannot be automatically detected, so all jobs will be re-generated.")
print(f"[GridTester] ⚠️ To use resume mode, disconnect optional inputs and use the built-in config fields instead.")
# ==== DISTRIBUTED PROCESSING BRANCH ====
# If distribution_config is provided and enabled, delegate to distributed processing
# which handles the generation loop, then jump to finalization
dist_enabled = (
distribution_config
and isinstance(distribution_config, dict)
and distribution_config.get("enabled")
and distribution_config.get("worker_urls")
)
if distribution_config:
print(f"[GridTester] 🌐 Distribution check: type={type(distribution_config).__name__}, "
f"enabled={distribution_config.get('enabled') if isinstance(distribution_config, dict) else 'N/A'}, "
f"workers={len(distribution_config.get('worker_urls', [])) if isinstance(distribution_config, dict) else 'N/A'}, "
f"dist_enabled={dist_enabled}")
else:
print(f"[GridTester] ℹ️ distribution_config is None/empty, running normal generation")
if dist_enabled:
print(f"[GridTester] 🌐 ENTERING DISTRIBUTED MODE with {len(distribution_config.get('worker_urls', []))} worker(s)")
# Upscaling in distributed mode: workers generate base images, master runs upscales after collection
if session_settings and session_settings.get("upscaling", {}).get("enabled", False):
print(f"[GridTester] ℹ️ Upscaling enabled — workers will generate base images, master will run upscales after all generation completes.")
return _run_distributed_generation(
self, distribution_config, expanded, input_jobs, existing_data,
overwrite_existing, has_optional_inputs, lora_triggerwords_mode,
session_name, paths, unique_id, total_jobs, seed, ckpt_name,
positive_text, negative_text, vae_batch_size, configs_json,
resolutions_json, flush_batch_every, use_remote_vae,
remote_vae_endpoint, save_conditioning_cache_to_file,
enable_model_cache, optional_model, optional_clip, optional_vae,
optional_positive, optional_negative, optional_latent, model_cache,
session_settings=session_settings
)
# ==== OPTIONAL CONDITIONING SETUP ====
if optional_positive or optional_negative:
pos_hash = hashlib.md5(str(optional_positive).encode()).hexdigest()[:16] if optional_positive else None
neg_hash = hashlib.md5(str(optional_negative).encode()).hexdigest()[:16] if optional_negative else None
else:
pos_hash, neg_hash = None, None
# ==== REMOTE VAE SETUP (use_remote_vae already defined above for VAE validation) ====
try:
if PromptServer is not None:
pbar = PromptServer.instance.progress_bar_pool.get_progress_bar(unique_id)
else:
pbar = None
except:
pbar = None
# ==== STATE VARIABLES ====
loaded_model, loaded_clip, loaded_vae = None, None, None
patched_model, patched_clip = None, None
cached_model_key = None
cached_lora_key = None
cached_lora_cache_key = None
cached_vae_key = None # Track which VAE is currently loaded
default_model_vae = None # Track the model's bundled/default VAE for reverting
conditioning_cache = {"positive": {}, "negative": {}}
incompatible_loras = {}
pending_batch = []
current_job = 0
new_completed = 0 # New generations completed in this run (excludes pre-existing skips)
total_generated = 0
gen_index_offset = len(existing_data.get("items", [])) # Sequential index for deterministic sort ordering
skipped_count = 0
start_at_job = int(session_settings.get("start_at_job", 0)) if session_settings else 0
if start_at_job > 0:
print(f"[GridTester] ⏭️ Start At Job #{start_at_job} — skipping earlier jobs")
image_format = session_settings.get("image_format", "webp") if session_settings else "webp"
if image_format != "webp":
print(f"[GridTester] 🖼️ Image save format: {image_format}")
job_durations = []
deferred_upscale_queue = []