forked from robertvoy/ComfyUI-Distributed
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdistributed_upscale_video.py
More file actions
4297 lines (3715 loc) · 191 KB
/
distributed_upscale_video.py
File metadata and controls
4297 lines (3715 loc) · 191 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
# Import statements (original + new)
import torch
from PIL import Image, ImageFilter, ImageDraw
import json
import asyncio, sys
if sys.platform.startswith("win"):
try:
# If a loop is already running, policy change may not take effect.
try:
asyncio.get_running_loop()
print("[USDU] Warning: an event loop is already running; "
"policy change may not fully apply.")
except RuntimeError:
pass # No running loop yet; safe to switch policy.
current = asyncio.get_event_loop_policy()
# Switch only if not already Selector
if not isinstance(current, asyncio.WindowsSelectorEventLoopPolicy):
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
print("[USDU] Applied WindowsSelectorEventLoopPolicy")
except Exception as e:
print(f"[USDU] Failed to set WindowsSelectorEventLoopPolicy: {e}")
# ---- Quiet Windows 10054 noise in asyncio ----
import logging
def _is_win_conn_reset(exc: BaseException) -> bool:
# True for Windows-specific connection reset noise
if not sys.platform.startswith("win"):
return False
if isinstance(exc, ConnectionResetError):
return True
if isinstance(exc, OSError) and getattr(exc, "winerror", None) == 10054:
return True
# Fallback: textual match (defensive)
return "10054" in str(exc)
def _install_win_connreset_filter():
# Install a loop exception handler that ignores benign 10054 during shutdown
try:
loop = asyncio.get_event_loop()
except RuntimeError:
return # no loop yet; safe to skip
default_handler = loop.get_exception_handler()
def _handler(loop, context):
exc = context.get("exception")
if exc and _is_win_conn_reset(exc):
# Swallow ConnectionResetError(10054) noise
return
# Delegate to default handler
if default_handler is not None:
default_handler(loop, context)
else:
loop.default_exception_handler(context)
try:
loop.set_exception_handler(_handler)
# Optional: keep asyncio logger quiet in INFO for less noise
logging.getLogger("asyncio").setLevel(logging.WARNING)
except Exception:
pass
_install_win_connreset_filter()
# ---- End of quieting block ----
from contextlib import contextmanager
import aiohttp
import io
import base64
import math
import time
import torch.nn as nn
from typing import List, Tuple, Dict
from functools import wraps
import os
from concurrent.futures import ThreadPoolExecutor
import torch.nn.functional as F
import numpy as np
from typing import Optional
from comfy.utils import ProgressBar # ComfyUI progress bar
from comfy import model_management
import gc
from tqdm.auto import tqdm
# Import ComfyUI modules
import comfy.samplers
import comfy.model_management
# Import shared utilities
from .utils.logging import debug_log, log
from .utils.image import tensor_to_pil, pil_to_tensor
from .utils.network import get_client_session
from .utils.async_helpers import run_async_in_server_loop
from .utils.config import get_worker_timeout_seconds
from .utils.constants import (
TILE_COLLECTION_TIMEOUT, TILE_WAIT_TIMEOUT,
TILE_SEND_TIMEOUT, MAX_BATCH
)
# Import for controller support
from .utils.usdu_utils import (
crop_cond,
get_crop_region,
expand_crop,
)
from .utils.usdu_managment import (
clone_conditioning, ensure_tile_jobs_initialized,
# Job management functions
_drain_results_queue,
_check_and_requeue_timed_out_workers, _get_completed_count, _mark_task_completed,
_send_heartbeat_to_master, _cleanup_job,
# Constants
JOB_COMPLETED_TASKS, JOB_WORKER_STATUS, JOB_PENDING_TASKS,
MAX_PAYLOAD_SIZE,
register_final_frames
)
from .utils.usdu_managment import init_dynamic_job, init_static_job_batched
# -----------------------------------------------------------------------------
# JPEG encoding/decoding multiprocess/thread utilities
#
# The following configuration and helper functions implement multi-threaded
# JPEG encoding and decoding. A global thread pool is initialized using a
# fraction of the available CPU cores, controlled by `JPEG_THREAD_FRACTION`.
# The helper functions `_encode_tile_data`, `_encode_np_to_jpeg` and
# `_decode_base64_to_np` are used to perform JPEG operations in parallel
# without blocking the main thread. These functions should be used whenever
# large numbers of tiles or frames need to be encoded or decoded. Because
# PIL's JPEG implementation releases the GIL during compression, using a
# ThreadPoolExecutor can take advantage of multiple cores effectively.
# Fraction of CPU cores to dedicate to JPEG tasks. Can be overridden via
# the environment variable JPEG_THREAD_FRACTION (e.g., "0.75" for 75%).
JPEG_THREAD_FRACTION = float(os.environ.get("JPEG_THREAD_FRACTION", "0.5"))
# Internal ThreadPoolExecutor instance for JPEG encoding/decoding. It is lazily
# instantiated on first use to avoid unnecessary thread creation when JPEG
# operations are not performed. See `get_jpeg_executor()` below.
_JPEG_EXECUTOR: Optional[ThreadPoolExecutor] = None
def get_jpeg_executor() -> ThreadPoolExecutor:
"""
Return a shared ThreadPoolExecutor configured for JPEG operations.
The number of worker threads is determined by the available CPU cores
multiplied by JPEG_THREAD_FRACTION. At least one thread is always
allocated. This executor is reused across calls to avoid repeatedly
creating and destroying threads.
"""
global _JPEG_EXECUTOR
if _JPEG_EXECUTOR is None:
# Determine available CPU cores; fallback to 1 if unknown
try:
cpu_count = os.cpu_count() or 1
except Exception:
cpu_count = 1
# Compute number of threads based on the configured fraction
num_workers = max(1, int(cpu_count * JPEG_THREAD_FRACTION))
_JPEG_EXECUTOR = ThreadPoolExecutor(max_workers=num_workers, thread_name_prefix="jpeg")
return _JPEG_EXECUTOR
def _encode_tile_data(tile_data: dict) -> dict:
"""
Encode a single tile into JPEG bytes with associated metadata.
The input `tile_data` dictionary must contain the keys 'tile_idx', 'x',
'y', 'extracted_width', 'extracted_height' and optionally 'batch_idx' and
'global_idx'. It may also contain a pre-rendered PIL image under the key
'image'. If no 'image' is present, the function falls back to converting
the provided torch tensor under 'tile' into a PIL image via `tensor_to_pil`.
The output is a dictionary with keys 'bytes' (JPEG-compressed data) and
'meta' (original metadata for reconstruction on the master).
"""
# Prefer the prepared PIL image when available to avoid redundant
# conversions. If not present, use tensor_to_pil to convert the tensor.
img = tile_data.get('image')
if img is None:
img = tensor_to_pil(tile_data['tile'], 0)
# Perform JPEG encoding into a byte buffer. High quality is retained to
# minimize compression artefacts; subsampling and optimize flags mirror the
# original behaviour in the codebase.
bio = io.BytesIO()
img.save(bio, format='JPEG', quality=100, subsampling=0, optimize=False)
raw = bio.getvalue()
# Collect metadata for the tile for later reassembly
meta = {
'tile_idx': tile_data['tile_idx'],
'x': tile_data['x'],
'y': tile_data['y'],
'extracted_width': tile_data['extracted_width'],
'extracted_height': tile_data['extracted_height']
}
if 'batch_idx' in tile_data:
meta['batch_idx'] = tile_data['batch_idx']
if 'global_idx' in tile_data:
meta['global_idx'] = tile_data['global_idx']
return {'bytes': raw, 'meta': meta}
def _encode_np_to_jpeg(arr: np.ndarray) -> bytes:
"""
Encode a numpy array (H×W×3, uint8 [0,255]) into JPEG-compressed bytes.
"""
bio = io.BytesIO()
Image.fromarray(arr).save(bio, format='JPEG', quality=100, subsampling=0, optimize=False)
return bio.getvalue()
def _decode_base64_to_np(fb64: str) -> np.ndarray:
"""
Decode a base64-encoded JPEG image into a numpy array of shape H×W×3
with dtype=uint8 in [0,255]. No scaling is performed here to avoid
forcing float32; scaling happens later only if the target dtype is float.
"""
pil_img = Image.open(io.BytesIO(base64.b64decode(fb64))).convert('RGB')
# Keep uint8 to avoid unnecessary FP32 memory usage
return np.array(pil_img, dtype=np.uint8)
# Note: MAX_BATCH and HEARTBEAT_TIMEOUT are imported from utils.constants
# They can be overridden via environment variables:
# - COMFYUI_MAX_BATCH (default: 20)
# - COMFYUI_HEARTBEAT_TIMEOUT (default: 90)
# Sync wrapper decorator for async methods
def sync_wrapper(async_func):
"""Decorator to wrap async methods for synchronous execution."""
@wraps(async_func)
def sync_func(self, *args, **kwargs):
# Use run_async_in_server_loop for ComfyUI compatibility
return run_async_in_server_loop(
async_func(self, *args, **kwargs),
timeout=600.0 # 10 minute timeout for long operations
)
return sync_func
@torch.no_grad()
def upscale_with_model_batched(
upscale_model,
images, # <- accepts torch.Tensor OR PIL.Image OR list[PIL.Image]
per_batch: int = 16,
clear_cuda_each_batch: bool = False,
show_tqdm: bool = True,
tqdm_desc: str = "[UpscalingWithModel]",
verbose: bool = False,
log_every_batches: int = 1,
time_unit: str = "s", # "s" or "ms"
prefer_tiled: bool = False, # start in tiled mode
sticky_tiled_after_oom: bool = True, # once OOM happens -> always tiled
auto_tiled_vram_threshold: float = 0.90, # if util>=threshold -> tiled
direct_clear_cuda_each_batch: Optional[bool] = None, # default False
init_tile: int = 512,
min_tile: int = 128,
overlap: int = 32,
remember_tile_across_batches: bool = True, # remember tile size
return_pil: bool = True, # default True since downstream uses PIL
pil_autoswitch_bytes: int = 1_000_000_000, # auto-switch to PIL if est. output > ~1GB
):
"""
Batched upscaling with sticky tiled mode and tile-size memory.
Input:
- torch.Tensor [B,H,W,C] in 0..1
- PIL.Image or list[PIL.Image] (RGB)
If return_pil=True:
- Do NOT pre-allocate a giant CPU tensor.
- Convert each processed batch directly to uint8 PIL frames and append to a list.
If return_pil=False:
- Collect CPU BHWC chunks in a list and concatenate at the end.
"""
# -------- helpers --------
def _fmt_b(x: int) -> str:
for u in ["B","KB","MB","GB","TB"]:
if x < 1024 or u == "TB": return f"{x:.1f}{u}"
x /= 1024.0
def _cuda_stats(dev: torch.device):
try:
if dev.type == "cuda":
idx = dev.index or 0
free_b, total_b = torch.cuda.mem_get_info(idx)
alloc = torch.cuda.memory_allocated(idx)
reserv = torch.cuda.memory_reserved(idx)
used = total_b - free_b
util = used / float(total_b) if total_b else 0.0
return {"alloc":alloc,"reserv":reserv,"free":free_b,"total":total_b,"used":used,"util":util}
except Exception:
pass
return None
def _stats_str(s) -> str:
if not s: return "n/a"
return (f"alloc={_fmt_b(s['alloc'])}, reserv={_fmt_b(s['reserv'])}, "
f"free={_fmt_b(s['free'])}, total={_fmt_b(s['total'])}, util={s['util']*100:.1f}%")
def _now(): return time.perf_counter()
def _dt(dt): return dt * (1000.0 if time_unit=="ms" else 1.0)
def _log(msg):
if verbose: print(msg, flush=True)
# -------- normalize/ingest input to BHWC tensor (no forced float32) --------
model_dtype = None
try:
# Prefer the model's parameter dtype to respect current ComfyUI precision (fp16/bf16/etc.)
p = next(upscale_model.parameters()) if hasattr(upscale_model, "parameters") else None
if p is not None:
model_dtype = p.dtype
except Exception:
pass
if model_dtype is None:
# Fallback to torch.get_default_dtype() if parameters() not available
model_dtype = torch.get_default_dtype()
# Convert PIL inputs to a BHWC tensor with model_dtype in 0..1
pil_in = False
if isinstance(images, Image.Image):
pil_in = True
images = [images]
if isinstance(images, list) and len(images) > 0 and isinstance(images[0], Image.Image):
pil_in = True
# Build a minimal, contiguous BHWC tensor in the model's dtype
np_list = []
for im in images:
if im.mode != "RGB":
im = im.convert("RGB")
arr = np.asarray(im, dtype=np.uint8) # HWC uint8
np_list.append(arr)
# Stack as BHWC uint8 then scale to 0..1 in model_dtype
arr_bhwc = np.stack(np_list, axis=0) # [B,H,W,C], uint8
t = torch.from_numpy(arr_bhwc) # uint8 CPU
images = t.to(dtype=torch.float32).mul_(1.0/255.0) # temporary float32 for safe scaling math
# Cast to model dtype only once, to avoid keeping two copies
images = images.to(dtype=model_dtype, copy=False)
del np_list, arr_bhwc, t
# -------- validate --------
if not (isinstance(images, torch.Tensor) and images.ndim == 4 and images.shape[-1] == 3):
raise ValueError("Expected BHWC tensor or PIL.Image/list[PIL.Image] (RGB).")
if per_batch < 1:
raise ValueError("per_batch must be >= 1.")
# -------- setup --------
dev = model_management.get_torch_device()
is_cuda = (dev.type == "cuda")
in_dtype = images.dtype # keep the current dtype; do not force float32
x = images.movedim(-1, -3).contiguous() # BHWC -> BCHW
B, C, H, W = x.shape
scale = float(getattr(upscale_model, "scale", 1.0))
outW, outH = int(W * scale), int(H * scale)
# Auto-switch to PIL path if the final dense tensor would be huge
try:
est_bytes = int(B) * int(outH) * int(outW) * int(C) * int(torch.tensor([], dtype=in_dtype).element_size())
if est_bytes >= pil_autoswitch_bytes:
return_pil = True
except Exception:
pass
_log("="*70)
_log(f"{tqdm_desc} starting")
_log(f"device={dev}, dtype={x.dtype}, cuda={is_cuda}")
_log(f"B={B}, per_batch={per_batch}, in={W}x{H}, scale={scale} -> out≈{outW}x{outH}")
if is_cuda: _log(f"VRAM before: {_stats_str(_cuda_stats(dev))}")
if clear_cuda_each_batch: _log("clear_cuda_each_batch=True (tiled cleanup).")
_log(f"direct_clear_cuda_each_batch={bool(direct_clear_cuda_each_batch or False)}")
pbar = ProgressBar(B)
total_batches = max(1, math.ceil(B / per_batch))
tbar = tqdm(total=total_batches, desc=tqdm_desc, unit="it", dynamic_ncols=True, leave=True) if show_tqdm else None
# Try to free some VRAM before moving model
t0 = _now()
try:
elem_size = images.element_size()
mem_required = model_management.module_size(getattr(upscale_model, "model", upscale_model))
mem_required += (512 * 512 * 3) * elem_size * max(scale, 1.0) * 384.0
mem_required += images.nelement() * elem_size
model_management.free_memory(mem_required, dev)
_log(f"reserved/free_memory heuristic={_fmt_b(int(mem_required))} on {dev} (t={_dt(_now()-t0):.1f}{time_unit})")
if is_cuda: _log(f"VRAM after reserve: {_stats_str(_cuda_stats(dev))}")
except Exception as e:
_log(f"reserve/free_memory skipped: {e!r}")
# Move model
t1 = _now()
upscale_model.to(dev)
if hasattr(upscale_model, "eval"): upscale_model.eval()
_log(f"model.to({dev}) + eval (t={_dt(_now()-t1):.1f}{time_unit})")
# -------- mode state --------
use_tiled = bool(prefer_tiled)
sticky_tripped = False
tile_state = int(init_tile) # last successful tile size
have_tile_state = False # becomes True after first successful tiled pass
batch_times = []
start_t, done_frames = _now(), 0
# Output accumulators (no giant pre-allocation)
out_cpu_chunks: list[torch.Tensor] = [] # used when return_pil=False
out_pil_frames: list = [] # used when return_pil=True
try:
for batch_idx, s in enumerate(range(0, B, per_batch), start=1):
b_t0 = _now()
chunk = x[s:s + per_batch]
n = int(chunk.shape[0])
if n == 0:
if tbar: tbar.update(1)
continue
_log("-"*70)
_log(f"Batch {batch_idx}/{total_batches} frames={s}..{s+n-1} shape={list(chunk.shape)}")
# Auto-tiling by VRAM
if is_cuda and auto_tiled_vram_threshold is not None:
st = _cuda_stats(dev)
if st and st["util"] >= auto_tiled_vram_threshold and not use_tiled:
use_tiled = True
_log(f"auto-tiling engaged (VRAM util {st['util']*100:.1f}% >= {auto_tiled_vram_threshold*100:.0f}%)")
if is_cuda and verbose:
torch.cuda.synchronize()
_log(f"VRAM pre-pass: {_stats_str(_cuda_stats(dev))}")
# Cleanup policy for this batch
do_cleanup_after = clear_cuda_each_batch if use_tiled else bool(direct_clear_cuda_each_batch or False)
# Direct path unless already in tiled mode
if not use_tiled:
try:
d_t0 = _now()
y = upscale_model(chunk.to(dev, non_blocking=True))
if is_cuda and verbose: torch.cuda.synchronize()
_log(f"direct pass ok (t={_dt(_now()-d_t0):.1f}{time_unit})")
except model_management.OOM_EXCEPTION:
_log("direct pass OOM -> switch to tiled (sticky)")
use_tiled = True
sticky_tripped = True
if use_tiled:
tile = tile_state if (remember_tile_across_batches and have_tile_state) else int(init_tile)
in_img = chunk.to(dev, non_blocking=True)
while True:
try:
if is_cuda and verbose: torch.cuda.synchronize()
t_t0 = _now()
y = comfy.utils.tiled_scale(
in_img,
lambda a: upscale_model(a),
tile_x=tile, tile_y=tile,
overlap=overlap,
upscale_amount=scale,
pbar=None
)
if is_cuda and verbose: torch.cuda.synchronize()
_log(f"tiled pass ok tile={tile} overlap={overlap} (t={_dt(_now()-t_t0):.1f}{time_unit})")
tile_state = tile
have_tile_state = True
break
except model_management.OOM_EXCEPTION as e:
tile //= 2
_log(f"tiled pass OOM -> reduce tile to {tile}")
if tile < int(min_tile):
_log("tile < min_tile -> re-raise OOM")
raise e
if is_cuda:
torch.cuda.synchronize()
torch.cuda.empty_cache()
torch.cuda.ipc_collect()
gc.collect()
del in_img
# ---- collect results without giant allocation ----
y_bhwc = y.permute(0, 2, 3, 1)
if return_pil:
y_u8 = (y_bhwc.clamp_(0.0, 1.0) * 255.0 + 0.5).to(torch.uint8).to("cpu", non_blocking=False)
for i in range(y_u8.shape[0]):
arr = y_u8[i].numpy().copy() # HWC uint8
out_pil_frames.append(Image.fromarray(arr, mode="RGB"))
del y_u8
else:
y_cpu = y_bhwc.to("cpu", dtype=in_dtype, non_blocking=False).contiguous()
y_cpu.clamp_(0.0, 1.0)
out_cpu_chunks.append(y_cpu)
pbar.update(n)
if tbar: tbar.update(1)
del y, y_bhwc, chunk
if is_cuda and do_cleanup_after:
torch.cuda.synchronize()
torch.cuda.empty_cache()
torch.cuda.ipc_collect()
gc.collect()
b_dt = _now() - b_t0
batch_times.append(b_dt)
done_frames += n
elapsed = _now() - start_t
fps = done_frames / elapsed if elapsed > 0 else float("inf")
mpix_done = (W * H * done_frames) / 1e6
mpix_s = mpix_done / elapsed if elapsed > 0 else float("inf")
avg_bt = sum(batch_times) / len(batch_times)
eta = (total_batches - batch_idx) * avg_bt
_log(f"batch time={_dt(b_dt):.1f}{time_unit} avg/batch={_dt(avg_bt):.1f}{time_unit} ETA≈{_dt(eta):.0f}{time_unit}")
_log(f"throughput: {fps:.2f} fps, {mpix_s:.2f} MPix/s (done {done_frames}/{B})")
if is_cuda and verbose and (batch_idx % max(1, log_every_batches) == 0):
_log(f"VRAM post-batch: {_stats_str(_cuda_stats(dev))}")
if sticky_tripped and sticky_tiled_after_oom:
use_tiled = True # keep tiled for all subsequent batches
total_t = _now() - start_t
_log("="*70)
_log(f"{tqdm_desc} done total={_dt(total_t):.1f}{time_unit} avg/batch={_dt(sum(batch_times)/max(1,len(batch_times))):.1f}{time_unit}")
if is_cuda: _log(f"VRAM final: {_stats_str(_cuda_stats(dev))}")
if return_pil:
return out_pil_frames # list[PIL.Image]
else:
if len(out_cpu_chunks) == 1:
return out_cpu_chunks[0]
return torch.cat(out_cpu_chunks, dim=0)
finally:
if tbar:
try: tbar.close()
except Exception: pass
try: upscale_model.cpu()
except Exception: pass
del x
gc.collect()
if is_cuda:
torch.cuda.synchronize()
torch.cuda.empty_cache()
torch.cuda.ipc_collect()
@torch.no_grad()
def auto_morph_align_batch_bhwc(
clean: torch.Tensor,
image: torch.Tensor,
blur: int = 0,
max_disp_px: float = 160.0, # max displacement clamp at full-res
lk_win_rad: int = 15, # LK box window radius
pyramid_levels: int = 4, # kept for API compatibility; ignored
iters_per_level: int = 6, # iterations at half-res
stop_at_fine_levels: int = 0, # kept for API compatibility; ignored
pre_smooth_rad: int = 0, # low-pass before gradients
min_eig_rel: float = 0.001, # confidence gate on λ_min
inc_smooth_rad: int = 0 # optional blur of incremental flow
) -> torch.Tensor:
"""
Dense optical-flow alignment (GPU-only), computed at half resolution:
1) Downscale (area) to 1/2.
2) Iteratively estimate flow at half-res.
3) Upscale flow to full-res (proper vector scaling).
4) Single inverse warp at full-res.
Inputs/outputs: BHWC, floating point in [0,1] with the SAME dtype as input.
"""
# ---- sanity checks ----
if clean.ndim != 4 or image.ndim != 4:
raise ValueError("Expected BHWC tensors.")
if clean.shape != image.shape:
raise ValueError(f"Shape mismatch: clean {clean.shape} vs image {image.shape}.")
if not (torch.is_floating_point(clean) and torch.is_floating_point(image)):
raise TypeError("Expected floating point tensors in [0,1].")
if not torch.cuda.is_available():
raise RuntimeError("CUDA is not available.")
# Preserve original device and dtype
orig_device, in_dtype = image.device, image.dtype
# Move to CUDA without changing dtype
clean = clean.to("cuda", non_blocking=True)
image = image.to("cuda", non_blocking=True)
B, H, W, C = image.shape
blur = int(max(0, int(blur)))
# Use machine epsilon scaled for numerical safety in the current dtype
EPS = torch.finfo(in_dtype).eps * 16.0
# ----------------- small helpers -----------------
def _to_gray_bhwc(x: torch.Tensor) -> torch.Tensor:
# simple luma (keeps dtype)
r, g, b = x[..., 0:1], x[..., 1:2], x[..., 2:3]
return (0.2989 * r + 0.5870 * g + 0.1140 * b).clamp(0.0, 1.0)
def _bhwc_to_nchw(x: torch.Tensor) -> torch.Tensor:
return x.permute(0, 3, 1, 2).contiguous()
def _nchw_to_bhwc(x: torch.Tensor) -> torch.Tensor:
return x.permute(0, 2, 3, 1).contiguous()
def _resize_bhwc(x: torch.Tensor, oh: int, ow: int, mode: str = "area") -> torch.Tensor:
# Use area for downscale; bilinear for upscale
nchw = _bhwc_to_nchw(x)
out = F.interpolate(nchw, size=(oh, ow), mode=("area" if mode == "area" else "bilinear"),
align_corners=False if mode != "area" else None)
return _nchw_to_bhwc(out)
def _avg_blur_1ch_nchw(x: torch.Tensor, rad: int) -> torch.Tensor:
if rad <= 0:
return x
k = 2 * rad + 1
x = F.pad(x, (rad, rad, rad, rad), mode="replicate")
return F.avg_pool2d(x, kernel_size=k, stride=1)
def _sobel_conv_1ch_nchw(x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
gx = torch.tensor([[-1, 0, 1],
[-2, 0, 2],
[-1, 0, 1]], dtype=x.dtype, device=x.device).view(1, 1, 3, 3) / 8.0
gy = torch.tensor([[-1, -2, -1],
[ 0, 0, 0],
[ 1, 2, 1]], dtype=x.dtype, device=x.device).view(1, 1, 3, 3) / 8.0
xp = F.pad(x, (1, 1, 1, 1), mode="replicate")
return F.conv2d(xp, gx), F.conv2d(xp, gy)
def _box_sum_1ch_nchw(x: torch.Tensor, rad: int) -> torch.Tensor:
if rad <= 0:
return x
k = 2 * rad + 1
w = torch.ones((1, 1, k, k), dtype=x.dtype, device=x.device)
xp = F.pad(x, (rad, rad, rad, rad), mode="replicate")
return F.conv2d(xp, w)
def _box_blur_flow_gpu(flow_nchw: torch.Tensor, rad: int) -> torch.Tensor:
if rad <= 0:
return flow_nchw
k = 2 * rad + 1
c = flow_nchw.shape[1]
w = torch.ones((c, 1, k, k), dtype=flow_nchw.dtype, device=flow_nchw.device) / float(k * k)
x = F.pad(flow_nchw, (rad, rad, rad, rad), mode="replicate")
return F.conv2d(x, w, groups=c)
def _warp_by_flow_bhwc(img_bhwc: torch.Tensor, flow_bhwc: torch.Tensor) -> torch.Tensor:
# Inverse warp: output(x) = img(x - flow)
N, Hh, Ww, _ = img_bhwc.shape
img_nchw = _bhwc_to_nchw(img_bhwc)
ys = torch.linspace(-1.0, 1.0, Hh, device=img_bhwc.device, dtype=img_bhwc.dtype)
xs = torch.linspace(-1.0, 1.0, Ww, device=img_bhwc.device, dtype=img_bhwc.dtype)
yy, xx = torch.meshgrid(ys, xs, indexing="ij")
base = torch.stack((xx, yy), dim=-1).unsqueeze(0)
fx = flow_bhwc[..., 0] * (2.0 / max(1, (Ww - 1)))
fy = flow_bhwc[..., 1] * (2.0 / max(1, (Hh - 1)))
grid = base + torch.stack((-fx, -fy), dim=-1)
out = F.grid_sample(img_nchw, grid, mode="bilinear", padding_mode="border", align_corners=False)
return _nchw_to_bhwc(out)
def _lk_dense_increment(
img_bhwc: torch.Tensor,
ref_bhwc: torch.Tensor,
win_rad: int,
eps: float,
clamp_px: float,
pre_blur_rad: int,
min_eig_rel_thr: float,
inc_blur_rad: int
) -> torch.Tensor:
# One-step Lucas–Kanade increment at current scale
img_g = _to_gray_bhwc(img_bhwc)
ref_g = _to_gray_bhwc(ref_bhwc)
img_n = _bhwc_to_nchw(img_g)
ref_n = _bhwc_to_nchw(ref_g)
if pre_blur_rad > 0:
img_n = _avg_blur_1ch_nchw(img_n, pre_blur_rad)
ref_n = _avg_blur_1ch_nchw(ref_n, pre_blur_rad)
Ix, Iy = _sobel_conv_1ch_nchw(img_n)
It = ref_n - img_n
Sxx = _box_sum_1ch_nchw(Ix * Ix, win_rad)
Syy = _box_sum_1ch_nchw(Iy * Iy, win_rad)
Sxy = _box_sum_1ch_nchw(Ix * Iy, win_rad)
Sxt = _box_sum_1ch_nchw(Ix * It, win_rad)
Syt = _box_sum_1ch_nchw(Iy * It, win_rad)
det = (Sxx * Syy - Sxy * Sxy)
u = (-(Syy * Sxt) + (Sxy * Syt)) / (det + eps)
v = ((Sxy * Sxt) - (Sxx * Syt)) / (det + eps)
trace = Sxx + Syy
sqrt_term = torch.sqrt((Sxx - Syy) * (Sxx - Syy) + 4.0 * Sxy * Sxy + eps)
lam_min = 0.5 * (trace - sqrt_term)
k = (2 * win_rad + 1) ** 2
lam_min_rel = lam_min / max(1.0, float(k))
mask = (lam_min_rel >= float(min_eig_rel_thr)).to(u.dtype)
u = (u * mask).clamp(-clamp_px, clamp_px)
v = (v * mask).clamp(-clamp_px, clamp_px)
inc = _nchw_to_bhwc(torch.cat([u, v], dim=1)) # [B,H,W,2]
if inc_blur_rad > 0:
inc = _nchw_to_bhwc(_box_blur_flow_gpu(_bhwc_to_nchw(inc), inc_blur_rad))
return inc
# ----------------- half-res flow, then upscale -----------------
t0 = time.perf_counter()
#pbar = ProgressBar(B)
out_frames = []
# per-level clamp at half-res so that full-res magnitude <= max_disp_px
clamp_half = float(max_disp_px) / 2.0
for i in range(B):
src_full = image[i:i+1]
ref_full = clean[i:i+1]
# build half-res pair (area downscale)
Hh = max(1, H // 2)
Wh = max(1, W // 2)
src_half = _resize_bhwc(src_full, Hh, Wh, mode="area")
ref_half = _resize_bhwc(ref_full, Hh, Wh, mode="area")
# initialize zero flow at half-res with input dtype
flow_h = torch.zeros((1, Hh, Wh, 2), dtype=in_dtype, device=src_half.device)
# iterative LK at half-res (warp -> increment -> accumulate)
for _ in range(max(1, int(iters_per_level))):
warped_h = _warp_by_flow_bhwc(src_half, flow_h)
inc_h = _lk_dense_increment(
warped_h, ref_half,
win_rad=lk_win_rad,
eps=EPS,
clamp_px=clamp_half,
pre_blur_rad=pre_smooth_rad,
min_eig_rel_thr=min_eig_rel,
inc_blur_rad=inc_smooth_rad
)
flow_h = (flow_h + inc_h).clamp(min=-clamp_half, max=clamp_half)
# optional smoothing of final half-res flow (legacy 'blur' knob)
with torch.cuda.amp.autocast(enabled=True):
flow_h = _nchw_to_bhwc(_box_blur_flow_gpu(_bhwc_to_nchw(flow_h), blur))
# upscale flow to full-res and scale vector magnitudes
flow_full = _nchw_to_bhwc(
F.interpolate(_bhwc_to_nchw(flow_h), size=(H, W), mode="bilinear", align_corners=False)
)
flow_full[..., 0] *= (W / max(1.0, float(Wh)))
flow_full[..., 1] *= (H / max(1.0, float(Hh)))
flow_full = flow_full.clamp(min=-max_disp_px, max=max_disp_px)
# single inverse warp at full-res
aligned = _warp_by_flow_bhwc(src_full, flow_full).clamp(0.0, 1.0)
out_frames.append(aligned)
#pbar.update(i + 1)
# cleanup
del src_full, ref_full, src_half, ref_half, flow_h, flow_full, aligned
torch.cuda.synchronize()
dt = time.perf_counter() - t0
print(f"[AutoMorph] {B} frame(s), {dt:.3f} s, {dt/max(1,B):.4f} s/frame", flush=True)
# Preserve dtype and move back to original device
result_cuda = torch.cat(out_frames, dim=0).contiguous()
return result_cuda.to(orig_device, dtype=in_dtype, non_blocking=True)
def sharpen_tiny(
image: torch.Tensor,
sharpen_radius: int = 1, # will be 1
sigma_x: float = 0.5,
sigma_y: float = 0.5,
alpha: float = 1.0,
) -> torch.Tensor:
"""
Ultra-fast unsharp mask for BHWC float tensors in [0,1] with OOM safety.
- Uses a single depthwise 3x3 Gaussian conv (separable kernel fused via outer product).
- Vectorized across batch; dynamically downsizes chunk if CUDA OOM is encountered.
- Preserves input dtype/device and returns BHWC.
"""
# Fast exits
if sharpen_radius <= 0 or alpha == 0.0:
return image
if image.ndim != 4 or image.shape[-1] not in (1, 2, 3, 4):
raise ValueError("Expected BHWC image with 1..4 channels.")
t0 = time.perf_counter()
B, H, W, C = image.shape
dev = image.device
dt = image.dtype
is_cuda = dev.type == "cuda"
# Enable fast CuDNN kernels where applicable
if is_cuda:
torch.backends.cudnn.benchmark = True # safe for inference with varying sizes
# --- Build 3x3 depthwise Gaussian kernel on the same device/dtype ---
# For radius=1 we need K=3; keep sigma_x/sigma_y for anisotropic cases.
k = 2 * sharpen_radius + 1 # -> 3
# 1D grids: [-1, 0, 1]
xs = torch.linspace(-sharpen_radius, sharpen_radius, k, device=dev, dtype=dt)
gx = torch.exp(-(xs**2) / (2.0 * (sigma_x * sigma_x) + 1e-12))
gy = torch.exp(-(xs**2) / (2.0 * (sigma_y * sigma_y) + 1e-12))
gx = gx / (gx.sum() + 1e-12) # [3]
gy = gy / (gy.sum() + 1e-12) # [3]
# Outer product -> 2D kernel [3,3]
g2d = torch.outer(gy, gx)
# Depthwise weights: [C, 1, 3, 3] (same kernel per channel)
weight = g2d.view(1, 1, k, k).expand(C, 1, k, k).contiguous()
# Pre-allocate output tensor
out = torch.empty_like(image)
# Heuristic to choose batch chunk size (in frames) to avoid OOM
# We estimate activation footprint conservatively and leave a safety margin.
def estimate_safe_chunk():
# bytes per element for current dtype
if dt == torch.float32:
bpe = 4
elif dt in (torch.float16, torch.bfloat16):
bpe = 2
else:
# default conservative
bpe = max(2, torch.finfo(dt).bits // 8)
# Approx per-frame working set in bytes:
# input + padded input (~+8%), output, and conv work buffers.
# Use a conservative multiplier.
per_frame_bytes = C * H * W * bpe
conservative_factor = 6.0 # generous headroom for conv workspace
frame_budget = per_frame_bytes * conservative_factor
if is_cuda:
try:
free_bytes, total_bytes = torch.cuda.mem_get_info(dev)
# Keep only 60% of currently free memory for safety
budget = max(128 * 1024 * 1024, int(free_bytes * 0.60))
chunk = max(1, min(B, budget // max(1, int(frame_budget))))
return chunk
except Exception:
pass
# CPU or mem_get_info unavailable: fallback to megapixels heuristic
# Aim ~8 MP per chunk (safe on most systems)
mp_target = 8_000_000
per_frame_mp = max(1, H * W)
chunk = max(1, min(B, mp_target // per_frame_mp))
return chunk
alpha_t = torch.as_tensor(alpha, dtype=dt, device=dev)
# Process in chunks with automatic backoff on OOM
remaining = B
start = 0
chunk = estimate_safe_chunk()
# Single-pass depthwise conv; reflect padding keeps edges clean.
# Use channels_last on CUDA for better throughput.
while remaining > 0:
# Make sure chunk is at least 1
chunk = max(1, min(chunk, remaining))
try:
x_bhwc = image[start:start + chunk] # [N,H,W,C]
x = x_bhwc.permute(0, 3, 1, 2) # [N,C,H,W]
if is_cuda:
x = x.contiguous(memory_format=torch.channels_last)
# Reflect pad by 1 pixel and run depthwise conv
x_pad = F.pad(x, (1, 1, 1, 1), mode="reflect")
if is_cuda:
x_pad = x_pad.contiguous(memory_format=torch.channels_last)
blur = F.conv2d(
x_pad, weight, bias=None, stride=1, padding=0, groups=C
)
# Unsharp mask: sharp = (1+alpha)*x - alpha*blur
sharp = torch.add(x, x, alpha=alpha_t) # (1+alpha)*x
sharp.add_(blur, alpha=-alpha_t) # subtract alpha*blur
sharp.clamp_(0.0, 1.0)
# Write back as BHWC
out[start:start + chunk].copy_(sharp.permute(0, 2, 3, 1))
# Advance window
start += chunk
remaining -= chunk
# Try to grow chunk opportunistically to reduce loop overhead
if is_cuda and remaining > 0:
chunk = min(B - start, chunk * 2)
# Explicitly drop large temporaries
del x_bhwc, x, x_pad, blur, sharp
except RuntimeError as e:
# Robust OOM handling: shrink chunk and retry
if "out of memory" in str(e).lower() and is_cuda:
torch.cuda.empty_cache()
# Halve the chunk; if already at 1, re-raise
if chunk > 1:
chunk = max(1, chunk // 2)
continue
raise
dt_s = time.perf_counter() - t0
print(f"[SharpenTiny] {B} frame(s), {dt_s:.3f} s, {dt_s / max(1, B):.4f} s/frame", flush=True)
return out
class UltimateSDUpscaleDistributed:
"""
Distributed version of Ultimate SD Upscale (No Upscale).
Now expects and returns: list of RGB PIL frames.
Supports three processing modes:
1. Single GPU: No workers available, process everything locally
2. Static Mode: Small batches, distributes tiles across workers (flattened)
3. Dynamic Mode: Large batches, assigns whole images to workers dynamically
Features:
- Multi-mode batch handling for efficient video/image upscaling
- Tiled VAE support for memory efficiency
- Dynamic load balancing for large batches
- Backward compatible with single-image workflows
Environment Variables:
- COMFYUI_MAX_BATCH: Chunk size for tile sending (default 20)
- COMFYUI_MAX_PAYLOAD_SIZE: Max API payload bytes (default 50MB)
Threshold: dynamic_threshold input controls mode switch (default 8)
"""
def __init__(self):
"""Initialize the node and ensure persistent storage exists."""
ensure_tile_jobs_initialized()
debug_log("UltimateSDUpscaleDistributed - Node initialized (PIL I/O)")
self._progress = None
self._progress_keepalive = False
@classmethod
def IS_CHANGED(cls, **kwargs):
"""Force re-execution."""
return float("nan") # Always re-execute
# ------------ small helpers (PIL-first) ------------
def _infer_batch_and_size_from_pil(self, images_list):
"""Return (batch, H, W) from list of RGB PIL images."""
if not isinstance(images_list, list) or len(images_list) == 0:
raise ValueError("Expected a non-empty list of RGB PIL images")
w, h = images_list[0].size
return len(images_list), h, w
def _ensure_rgb_copies(self, images_list):
"""Ensure every image is RGB and detached from any shared buffer."""
out = []
for img in images_list:
if img.mode != "RGB":
img = img.convert("RGB")
out.append(img.copy())
return out
# ---------------------------------------------------
def run(self, upscaled_image, model, positive, negative, vae, seed, steps, cfg,
sampler_name, scheduler, denoise, tile_width, tile_height, padding,
mask_blur, mask_expand, force_uniform_tiles, tiled_decode,
multi_job_id="", is_worker=False, master_url="", enabled_worker_ids="[]",
worker_id="", tile_indices="", dynamic_threshold=8, auto_morph_output=False, auto_morph_blur=8,
# Optional high-pass and gradient-preserve blending parameters
highpass_blend=False, hp_blur_size=100, hp_opacity=0.85, hp_device="auto", hp_store_result_on="cpu", hp_contrast=1.0,
preserve_gradients_blend=False, pg_highpass_radius=15, pg_downscale_by=0.25, pg_strength=10.0,
pg_expand=5, pg_mask_blur=25, pg_clamp_blacks=0.05, pg_clamp_whites=0.9,
pg_temporal_deflicker=False, pg_device="auto", post_sharpen=0.0, pre_sharpen=0.0):
"""Entry point (synchronous). Now expects a list of RGB PIL frames and returns the same."""
if not isinstance(upscaled_image, list):
raise TypeError("UltimateSDUpscaleDistributed now expects a list of RGB PIL frames as input")
batch_size, height, width = self._infer_batch_and_size_from_pil(upscaled_image)
# Enforce 4n+1 batches globally when batch > 1 (master only)
if not is_worker and batch_size != 1 and (batch_size % 4 != 1):
raise ValueError(
f"Batch size {batch_size} is not of the form 4n+1. "