-
-
Notifications
You must be signed in to change notification settings - Fork 78
Expand file tree
/
Copy pathinstaller.py
More file actions
1860 lines (1695 loc) · 89.3 KB
/
Copy pathinstaller.py
File metadata and controls
1860 lines (1695 loc) · 89.3 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
#!/usr/bin/env python3
import os
import sys
import argparse
import subprocess
import requests
import glob
import re
import shutil
from pathlib import Path
from typing import Dict, List, Set, Any
try:
from tqdm.auto import tqdm
TQDM_AVAILABLE = True
except ImportError:
TQDM_AVAILABLE = False
# --- Compatibility Patches ---
# Polyfill for Path.is_junction() which requires Python 3.12+.
# comfy_env uses it but many ComfyUI installs still run Python 3.10/3.11.
_PATCH_PY310_IS_JUNCTION = (
"# -- StableGen patch: Path.is_junction polyfill for Python < 3.12 --\n"
"import pathlib as _pathlib\n"
"if not hasattr(_pathlib.Path, 'is_junction'):\n"
" import os as _os, stat as _stat\n"
" def _is_junction(self):\n"
" try:\n"
" return bool(\n"
" _os.lstat(str(self)).st_file_attributes\n"
" & _stat.FILE_ATTRIBUTE_REPARSE_POINT\n"
" )\n"
" except (OSError, AttributeError):\n"
" return False\n"
" _pathlib.Path.is_junction = _is_junction\n"
"# -- End StableGen patch --\n\n"
)
_PATCH_TRELLIS_PRESTARTUP = (
"# -- StableGen patch: Path.is_junction polyfill for Python < 3.12 --\n"
"import pathlib as _pathlib\n"
"if not hasattr(_pathlib.Path, 'is_junction'):\n"
" import os as _os, stat as _stat\n"
" def _is_junction(self):\n"
" try:\n"
" return bool(\n"
" _os.lstat(str(self)).st_file_attributes\n"
" & _stat.FILE_ATTRIBUTE_REPARSE_POINT\n"
" )\n"
" except (OSError, AttributeError):\n"
" return False\n"
" _pathlib.Path.is_junction = _is_junction\n"
"# -- End StableGen patch --\n\n"
"# -- StableGen patch: Auto-heal comfy-env site-packages isolation at startup --\n"
"try:\n"
" import importlib.util as _u, os as _os, sys as _sys\n"
" _s = _u.find_spec('comfy_env')\n"
" if _s and _s.origin:\n"
" _wrap_py = _os.path.join(_os.path.dirname(_s.origin), 'isolation', 'wrap.py')\n"
" if _os.path.exists(_wrap_py):\n"
" with open(_wrap_py, 'r', encoding='utf-8') as _f:\n"
" _code = _f.read()\n"
" if 'PYTHONNOUSERSITE' not in _code:\n"
" _anchor = ' env[\"COMFYUI_ISOLATION_WORKER\"] = \"1\"'\n"
" if _anchor in _code:\n"
" _code = _code.replace(_anchor, _anchor + '\\n env[\"PYTHONNOUSERSITE\"] = \"1\"')\n"
" with open(_wrap_py, 'w', encoding='utf-8') as _f:\n"
" _f.write(_code)\n"
" print('[StableGen] Auto-applied comfy-env user site-packages isolation patch at boot', file=_sys.stderr)\n"
"except Exception:\n"
" pass\n"
"# -- End StableGen patch --\n\n"
)
# Patch for lazy_manager.py: Add attn_backend to config comparison.
# Without this, switching attention backend (e.g. xformers -> flash_attn)
# doesn't recreate the model manager, leaving stale config.
_PATCH_TRELLIS_ATTN_CMP_ANCHOR = (
" elif (_LAZY_MANAGER.model_name != model_name or\n"
" _LAZY_MANAGER.resolution != resolution or\n"
" _LAZY_MANAGER.vram_mode != vram_mode):\n"
" # Config changed, recreate manager\n"
" _LAZY_MANAGER.cleanup()\n"
)
_PATCH_TRELLIS_ATTN_CMP_REPLACE = (
" elif (_LAZY_MANAGER.model_name != model_name or\n"
" _LAZY_MANAGER.resolution != resolution or\n"
" _LAZY_MANAGER.vram_mode != vram_mode or\n"
" _LAZY_MANAGER.attn_backend != attn_backend):\n"
" # Config changed, recreate manager\n"
" print(f\"[TRELLIS2] Config changed, recreating model manager...\", file=sys.stderr)\n"
" _LAZY_MANAGER.cleanup()\n"
)
# Patch for stages.py: Wrap DinoV3 feature extraction in torch.no_grad().
# Without this, autograd retains ViT-L intermediate activations on GPU,
# leaking ~5-9 GB between runs in the persistent comfy-env worker.
_PATCH_TRELLIS_NOGRAD_ANCHOR = (
" # Load DinoV3 and extract features\n"
" model = manager.get_dinov3(device)\n"
"\n"
" # Get 512px conditioning\n"
" model.image_size = 512\n"
" cond_512 = model([pil_image])\n"
"\n"
" # Get 1024px conditioning if requested\n"
" cond_1024 = None\n"
" if include_1024:\n"
" model.image_size = 1024\n"
" cond_1024 = model([pil_image])\n"
"\n"
" # Unload DinoV3 immediately\n"
" manager.unload_dinov3()\n"
"\n"
" # Create negative conditioning\n"
" neg_cond = torch.zeros_like(cond_512)\n"
"\n"
" conditioning = {\n"
" 'cond_512': cond_512.cpu(),\n"
" 'neg_cond': neg_cond.cpu(),\n"
" }\n"
" if cond_1024 is not None:\n"
" conditioning['cond_1024'] = cond_1024.cpu()\n"
)
_PATCH_TRELLIS_NOGRAD_REPLACE = (
" # Load DinoV3 and extract features\n"
" model = manager.get_dinov3(device)\n"
"\n"
" # Use no_grad to prevent autograd from retaining intermediate activations\n"
" # on GPU. Without this, the computation graph keeps ViT-L activations alive\n"
" # in the comfy-env worker, leaking ~5-9 GB between runs.\n"
" with torch.no_grad():\n"
" # Get 512px conditioning\n"
" model.image_size = 512\n"
" cond_512 = model([pil_image])\n"
"\n"
" # Get 1024px conditioning if requested\n"
" cond_1024 = None\n"
" if include_1024:\n"
" model.image_size = 1024\n"
" cond_1024 = model([pil_image])\n"
"\n"
" # Unload DinoV3 immediately\n"
" manager.unload_dinov3()\n"
"\n"
" # Create negative conditioning\n"
" neg_cond = torch.zeros_like(cond_512)\n"
"\n"
" # .detach() breaks any remaining graph references before moving to CPU\n"
" conditioning = {\n"
" 'cond_512': cond_512.detach().cpu(),\n"
" 'neg_cond': neg_cond.detach().cpu(),\n"
" }\n"
" if cond_1024 is not None:\n"
" conditioning['cond_1024'] = cond_1024.detach().cpu()\n"
"\n"
" # Free the GPU originals immediately\n"
" del cond_512, cond_1024, neg_cond\n"
" gc.collect()\n"
" torch.cuda.empty_cache()\n"
)
# ---------------------------------------------------------------------------
# comfy-env VRAM leak fix patches
# ---------------------------------------------------------------------------
# comfy-env hooks torch.nn.Module.to() and .cuda() to auto-register every
# model that lands on CUDA in a permanent _model_registry (with no unregister
# API). Between ComfyUI node calls the model manager issues
# "Requested to load SubprocessModel" which calls model_to_device("cuda"),
# moving ALL registered models back to GPU. This leaks ~7 GB of model
# weights between runs. The fix: unregister from the registry before
# moving models to CPU / deleting them.
# ---------------------------------------------------------------------------
# -- base.py _unload_model: unregister from comfy-env + model.cpu() before del
_PATCH_TRELLIS_UNLOAD_CPU_ANCHOR = (
" # Delete the model entirely\n"
" self.models[model_key] = None\n"
" del model\n"
)
_PATCH_TRELLIS_UNLOAD_CPU_REPLACE = (
" # Unregister from comfy-env's model registry BEFORE moving to CPU.\n"
" # comfy-env auto-registers every nn.Module that lands on CUDA via\n"
" # hooked Module.to(). Without unregistering, the registry keeps a\n"
" # permanent reference and ComfyUI's model manager re-loads the model\n"
" # to GPU between calls, leaking the full model weights per run.\n"
" # Replace with zero-param dummy so host's model_to_device succeeds\n"
" # but consumes 0 VRAM. Registry accessed via closure on\n"
" # sys.modules['comfy_worker'].register_model.\n"
" try:\n"
" _cw = sys.modules.get('comfy_worker')\n"
" if _cw is not None:\n"
" _reg_fn = getattr(_cw, 'register_model', None)\n"
" if _reg_fn is not None and hasattr(_reg_fn, '__closure__'):\n"
" _fv = _reg_fn.__code__.co_freevars\n"
" _cl = _reg_fn.__closure__\n"
" _by_obj = _cl[_fv.index('_model_id_by_obj')].cell_contents\n"
" _registry = _cl[_fv.index('_model_registry')].cell_contents\n"
" _meta = _cl[_fv.index('_model_registry_meta')].cell_contents\n"
" obj_id = id(model)\n"
" if obj_id in _by_obj:\n"
" ce_model_id = _by_obj.pop(obj_id)\n"
" dummy = torch.nn.Module()\n"
" _registry[ce_model_id] = dummy\n"
" _meta[ce_model_id] = {'size': 0, 'kind': 'other'}\n"
" _by_obj[id(dummy)] = ce_model_id\n"
' print(f"[TRELLIS2] Unregistered {model_key} from comfy-env registry (id={ce_model_id})", file=sys.stderr, flush=True)\n'
" except Exception:\n"
" pass\n"
" # Force all parameters and buffers off GPU.\n"
" try:\n"
" model.cpu()\n"
" except Exception:\n"
" pass\n"
" # Delete the model entirely\n"
" self.models[model_key] = None\n"
" del model\n"
)
# -- lazy_manager.py: insert _unregister_from_comfy_env helper function
_PATCH_TRELLIS_COMFY_HELPER_ANCHOR = (
"# Global model manager instance\n"
'_LAZY_MANAGER: Optional["LazyModelManager"] = None\n'
)
_PATCH_TRELLIS_COMFY_HELPER_REPLACE = (
"\n"
"def _unregister_from_comfy_env(model, label: str = \"\"):\n"
' """Remove an nn.Module from comfy-env\'s worker-side model registry.\n'
"\n"
" comfy-env hooks Module.to() to auto-register every model that lands on\n"
" CUDA. The registry keeps a permanent reference, and ComfyUI's model\n"
" manager will re-load the model to GPU between calls via\n"
" 'Requested to load SubprocessModel'. We replace the model with a\n"
" zero-param dummy so the host's model_to_device succeeds (no-op) but\n"
" no VRAM is consumed. Registry accessed via closure on\n"
" sys.modules['comfy_worker'].register_model.\n"
' """\n'
" try:\n"
" _cw = sys.modules.get('comfy_worker')\n"
" if _cw is None:\n"
" return\n"
" _reg_fn = getattr(_cw, 'register_model', None)\n"
" if _reg_fn is None or not hasattr(_reg_fn, '__closure__'):\n"
" return\n"
" _fv = _reg_fn.__code__.co_freevars\n"
" _cl = _reg_fn.__closure__\n"
" _by_obj = _cl[_fv.index('_model_id_by_obj')].cell_contents\n"
" _registry = _cl[_fv.index('_model_registry')].cell_contents\n"
" _meta = _cl[_fv.index('_model_registry_meta')].cell_contents\n"
" obj_id = id(model)\n"
" if obj_id in _by_obj:\n"
" model_id = _by_obj.pop(obj_id)\n"
" dummy = torch.nn.Module()\n"
" _registry[model_id] = dummy\n"
" _meta[model_id] = {'size': 0, 'kind': 'other'}\n"
" _by_obj[id(dummy)] = model_id\n"
' print(f"[TRELLIS2] Unregistered {label} from comfy-env registry (id={model_id})", file=sys.stderr)\n'
" except Exception:\n"
" pass\n"
"\n"
"\n"
"# Global model manager instance\n"
'_LAZY_MANAGER: Optional["LazyModelManager"] = None\n'
)
# -- lazy_manager.py unload_dinov3: add comfy-env unregistration
_PATCH_TRELLIS_UNLOAD_DINOV3_ANCHOR = (
" def unload_dinov3(self):\n"
' """Unload DinoV3 to free VRAM."""\n'
" if self.dinov3_model is not None:\n"
" self.dinov3_model.cpu()\n"
" self.dinov3_model = None\n"
" gc.collect()\n"
" torch.cuda.empty_cache()\n"
' print(f"[TRELLIS2] DinoV3 offloaded", file=sys.stderr)\n'
)
_PATCH_TRELLIS_UNLOAD_DINOV3_REPLACE = (
" def unload_dinov3(self):\n"
' """Unload DinoV3 to free VRAM."""\n'
" if self.dinov3_model is not None:\n"
" # Unregister the inner nn.Module (DINOv3ViTModel) from comfy-env.\n"
" # DinoV3FeatureExtractor is a plain class; comfy-env hooks on the\n"
" # inner .model which is the actual nn.Module that got .to(cuda).\n"
" inner = getattr(self.dinov3_model, 'model', self.dinov3_model)\n"
' _unregister_from_comfy_env(inner, "dinov3")\n'
" self.dinov3_model.cpu()\n"
" self.dinov3_model = None\n"
" gc.collect()\n"
" torch.cuda.empty_cache()\n"
' print(f"[TRELLIS2] DinoV3 offloaded", file=sys.stderr)\n'
)
# -- lazy_manager.py unload_shape_pipeline: iterate models + comfy-env unreg
_PATCH_TRELLIS_UNLOAD_SHAPE_ANCHOR = (
" def unload_shape_pipeline(self):\n"
' """Unload shape pipeline to free VRAM."""\n'
" if self.shape_pipeline is not None:\n"
" self.shape_pipeline = None\n"
" gc.collect()\n"
" torch.cuda.empty_cache()\n"
' print(f"[TRELLIS2] Shape pipeline offloaded", file=sys.stderr)\n'
)
_PATCH_TRELLIS_UNLOAD_SHAPE_REPLACE = (
" def unload_shape_pipeline(self):\n"
' """Unload shape pipeline to free VRAM."""\n'
" if self.shape_pipeline is not None:\n"
" # Force any remaining models off GPU before dropping pipeline\n"
" if hasattr(self.shape_pipeline, 'models'):\n"
" for key in list(self.shape_pipeline.models.keys()):\n"
" model = self.shape_pipeline.models[key]\n"
" if model is not None:\n"
' _unregister_from_comfy_env(model, f"shape/{key}")\n'
" try:\n"
" model.cpu()\n"
" except Exception:\n"
" pass\n"
" self.shape_pipeline.models[key] = None\n"
" del model\n"
" self.shape_pipeline.models.clear()\n"
" self.shape_pipeline = None\n"
" gc.collect()\n"
" torch.cuda.empty_cache()\n"
' print(f"[TRELLIS2] Shape pipeline offloaded", file=sys.stderr)\n'
)
# -- lazy_manager.py unload_texture_pipeline: iterate models + comfy-env unreg
_PATCH_TRELLIS_UNLOAD_TEX_ANCHOR = (
" def unload_texture_pipeline(self):\n"
' """Unload texture pipeline to free VRAM."""\n'
" if self.texture_pipeline is not None:\n"
" self.texture_pipeline = None\n"
" gc.collect()\n"
" torch.cuda.empty_cache()\n"
' print(f"[TRELLIS2] Texture pipeline offloaded", file=sys.stderr)\n'
)
_PATCH_TRELLIS_UNLOAD_TEX_REPLACE = (
" def unload_texture_pipeline(self):\n"
' """Unload texture pipeline to free VRAM."""\n'
" if self.texture_pipeline is not None:\n"
" # Force any remaining models off GPU before dropping pipeline\n"
" if hasattr(self.texture_pipeline, 'models'):\n"
" for key in list(self.texture_pipeline.models.keys()):\n"
" model = self.texture_pipeline.models[key]\n"
" if model is not None:\n"
' _unregister_from_comfy_env(model, f"texture/{key}")\n'
" try:\n"
" model.cpu()\n"
" except Exception:\n"
" pass\n"
" self.texture_pipeline.models[key] = None\n"
" del model\n"
" self.texture_pipeline.models.clear()\n"
" self.texture_pipeline = None\n"
" gc.collect()\n"
" torch.cuda.empty_cache()\n"
' print(f"[TRELLIS2] Texture pipeline offloaded", file=sys.stderr)\n'
)
# Patch for stages.py: clean up IPC tensor files from previous generations
# inside _save_to_disk so they don't accumulate and fill the disk.
_PATCH_TRELLIS_TEMP_CLEANUP_ANCHOR = (
"def _save_to_disk(data, prefix):\n"
" path = os.path.join(_get_temp_dir(), f'{prefix}_{uuid.uuid4().hex[:8]}.pt')\n"
" torch.save(data, path)\n"
" return {'_tensor_file': path}"
)
_PATCH_TRELLIS_TEMP_CLEANUP_REPLACE = (
"def _save_to_disk(data, prefix):\n"
" import glob as _glob\n"
" temp_dir = _get_temp_dir()\n"
" # StableGen patch: clean up files from previous generations\n"
" for _old in _glob.glob(os.path.join(temp_dir, f'{prefix}_*.pt')):\n"
" try:\n"
" os.remove(_old)\n"
" except OSError:\n"
" pass\n"
" path = os.path.join(temp_dir, f'{prefix}_{uuid.uuid4().hex[:8]}.pt')\n"
" torch.save(data, path)\n"
" return {'_tensor_file': path}"
)
# --- Configuration: Dependencies Data ---
# Sizes are in MB.
DEPENDENCIES: Dict[str, Dict[str, Any]] = {
# --- Custom Nodes ---
"cn_ipadapter_plus": {
"id": "cn_ipadapter_plus", "type": "node", "name": "ComfyUI IPAdapter Plus",
"git_url": "https://github.com/cubiq/ComfyUI_IPAdapter_plus.git",
"target_dir_relative": "custom_nodes",
"repo_name": "ComfyUI_IPAdapter_plus",
"license": "GPL-3.0", "packages": ["core"]
},
# --- Models ---
# Core Models
"model_ipadapter_plus_sdxl_vit_h": {
"id": "model_ipadapter_plus_sdxl_vit_h", "type": "model", "name": "IPAdapter Plus SDXL ViT-H",
"url": "https://huggingface.co/h94/IP-Adapter/resolve/main/sdxl_models/ip-adapter-plus_sdxl_vit-h.safetensors?download=true",
"target_path_relative": "models/ipadapter", "filename": "ip-adapter-plus_sdxl_vit-h.safetensors",
"license": "Apache 2.0", "size_mb": 850, "packages": ["core"]
},
"model_clip_vision_h": {
"id": "model_clip_vision_h", "type": "model", "name": "IPAdapter CLIP Vision ViT-H",
"url": "https://huggingface.co/h94/IP-Adapter/resolve/main/models/image_encoder/model.safetensors",
"target_path_relative": "models/clip_vision", "filename": "CLIP-ViT-H-14-laion2B-s32B-b79K.safetensors",
"rename_from": "model.safetensors", "license": "Apache 2.0", "size_mb": 2500, "packages": ["core"]
},
"model_clip_vision_g": {
"id": "model_clip_vision_g", "type": "model", "name": "IPAdapter CLIP Vision ViT-G",
"url": "https://huggingface.co/h94/IP-Adapter/resolve/main/sdxl_models/image_encoder/model.safetensors",
"target_path_relative": "models/clip_vision", "filename": "CLIP-ViT-bigG-14-laion2B-39B-b160k.safetensors",
"rename_from": "model.safetensors", "license": "Apache 2.0", "size_mb": 3500, "packages": ["core"]
},
"lora_sdxl_lightning_8step": {
"id": "lora_sdxl_lightning_8step", "type": "model", "name": "SDXL Lightning 8-Step LoRA",
"url": "https://huggingface.co/ByteDance/SDXL-Lightning/resolve/main/sdxl_lightning_8step_lora.safetensors?download=true",
"target_path_relative": "models/loras", "filename": "sdxl_lightning_8step_lora.safetensors",
"license": "OpenRAIL++", "size_mb": 400, "packages": ["core"]
},
# Preset Essentials
"controlnet_depth_sdxl_preset": {
"id": "controlnet_depth_sdxl_preset", "type": "model", "name": "ControlNet Depth SDXL (for presets)",
"url": "https://huggingface.co/xinsir/controlnet-depth-sdxl-1.0/resolve/main/diffusion_pytorch_model.safetensors?download=true",
"target_path_relative": "models/controlnet", "filename": "controlnet_depth_sdxl.safetensors",
"rename_from": "diffusion_pytorch_model.safetensors", "license": "Apache 2.0", "size_mb": 2500, "packages": ["preset_essentials"]
},
# Extended SDXL Optional Models
"lora_sdxl_lightning_4step": {
"id": "lora_sdxl_lightning_4step", "type": "model", "name": "SDXL Lightning 4-Step LoRA",
"url": "https://huggingface.co/ByteDance/SDXL-Lightning/resolve/main/sdxl_lightning_4step_lora.safetensors?download=true",
"target_path_relative": "models/loras", "filename": "sdxl_lightning_4step_lora.safetensors",
"license": "OpenRAIL++", "size_mb": 400, "packages": ["extended_optional"]
},
"lora_sdxl_lightning_2step": {
"id": "lora_sdxl_lightning_2step", "type": "model", "name": "SDXL Lightning 2-Step LoRA",
"url": "https://huggingface.co/ByteDance/SDXL-Lightning/resolve/main/sdxl_lightning_2step_lora.safetensors?download=true",
"target_path_relative": "models/loras", "filename": "sdxl_lightning_2step_lora.safetensors",
"license": "OpenRAIL++", "size_mb": 400, "packages": ["extended_optional"]
},
"lora_hyper_sdxl_8step": {
"id": "lora_hyper_sdxl_8step", "type": "model", "name": "Hyper-SDXL 8-Steps LoRA",
"url": "https://huggingface.co/ByteDance/Hyper-SD/resolve/main/Hyper-SDXL-8steps-lora.safetensors?download=true",
"target_path_relative": "models/loras", "filename": "Hyper-SDXL-8steps-lora.safetensors",
"license": "Unknown (User to verify)", "size_mb": 800, "packages": ["extended_optional"]
},
"lora_hyper_sdxl_4step": {
"id": "lora_hyper_sdxl_4step", "type": "model", "name": "Hyper-SDXL 4-Steps LoRA",
"url": "https://huggingface.co/ByteDance/Hyper-SD/resolve/main/Hyper-SDXL-4steps-lora.safetensors?download=true",
"target_path_relative": "models/loras", "filename": "Hyper-SDXL-4steps-lora.safetensors",
"license": "Unknown (User to verify)", "size_mb": 800, "packages": ["extended_optional"]
},
"lora_hyper_sdxl_1step": {
"id": "lora_hyper_sdxl_1step", "type": "model", "name": "Hyper-SDXL 1-Step LoRA",
"url": "https://huggingface.co/ByteDance/Hyper-SD/resolve/main/Hyper-SDXL-1step-lora.safetensors?download=true",
"target_path_relative": "models/loras", "filename": "Hyper-SDXL-1step-lora.safetensors",
"license": "Unknown (User to verify)", "size_mb": 800, "packages": ["extended_optional"]
},
"controlnet_depth_sdxl_fp16_alt": {
"id": "controlnet_depth_sdxl_fp16_alt", "type": "model", "name": "ControlNet Depth SDXL fp16 (alternative)",
"url": "https://huggingface.co/diffusers/controlnet-depth-sdxl-1.0/resolve/main/diffusion_pytorch_model.fp16.safetensors?download=true",
"target_path_relative": "models/controlnet", "filename": "diffusion_pytorch_model.fp16.safetensors",
"license": "OpenRAIL++", "size_mb": 2500, "packages": ["extended_optional"]
},
"controlnet_union_promax": {
"id": "controlnet_union_promax", "type": "model", "name": "ControlNet Union SDXL ProMax",
"url": "https://huggingface.co/brad-twinkl/controlnet-union-sdxl-1.0-promax/resolve/main/diffusion_pytorch_model.safetensors?download=true",
"target_path_relative": "models/controlnet", "filename": "sdxl_promax.safetensors",
"rename_from": "diffusion_pytorch_model.safetensors", "license": "Apache 2.0", "size_mb": 2500, "packages": ["extended_optional"]
},
# Checkpoints
"checkpoint_realvis_v5": {
"id": "checkpoint_realvis_v5", "type": "model", "name": "RealVisXL V5.0 fp16 Checkpoint",
"url": "https://huggingface.co/SG161222/RealVisXL_V5.0/resolve/main/RealVisXL_V5.0_fp16.safetensors?download=true",
"target_path_relative": "models/checkpoints", "filename": "RealVisXL_V5.0_fp16.safetensors",
"license": "OpenRAIL++", "size_mb": 6500, "packages": ["checkpoint_realvis"]
},
# Qwen Core
"cn_comfyui_gguf": {
"id": "cn_comfyui_gguf", "type": "node", "name": "ComfyUI GGUF Loader",
"git_url": "https://github.com/city96/ComfyUI-GGUF.git",
"target_dir_relative": "custom_nodes",
"repo_name": "ComfyUI-GGUF",
"license": "Apache 2.0", "packages": ["qwen_core"],
"pip_packages": ["gguf"]
},
"model_qwen_unet_q3_k_m": {
"id": "model_qwen_unet_q3_k_m", "type": "model", "name": "Qwen Image Edit 2509 UNet (Q3_K_M)",
"url": "https://huggingface.co/QuantStack/Qwen-Image-Edit-2509-GGUF/resolve/main/Qwen-Image-Edit-2509-Q3_K_M.gguf?download=true",
"target_path_relative": "models/unet", "filename": "Qwen-Image-Edit-2509-Q3_K_M.gguf",
"license": "Apache 2.0", "size_mb": 9760, "packages": ["qwen_core"]
},
"model_qwen_vae": {
"id": "model_qwen_vae", "type": "model", "name": "Qwen Image VAE",
"url": "https://huggingface.co/Comfy-Org/Qwen-Image_ComfyUI/resolve/main/split_files/vae/qwen_image_vae.safetensors?download=true",
"target_path_relative": "models/vae", "filename": "qwen_image_vae.safetensors",
"license": "Apache 2.0", "size_mb": 254, "packages": ["qwen_core"]
},
"model_qwen_text_encoder_fp8": {
"id": "model_qwen_text_encoder_fp8", "type": "model", "name": "Qwen 2.5 VL 7B Text Encoder (FP8)",
"url": "https://huggingface.co/Comfy-Org/Qwen-Image_ComfyUI/resolve/main/split_files/text_encoders/qwen_2.5_vl_7b_fp8_scaled.safetensors?download=true",
"target_path_relative": "models/clip", "filename": "qwen_2.5_vl_7b_fp8_scaled.safetensors",
"license": "Apache 2.0", "size_mb": 9380, "packages": ["qwen_core"]
},
"lora_qwen_lightning_4step_edit": {
"id": "lora_qwen_lightning_4step_edit", "type": "model", "name": "Qwen Image Edit Lightning 4-Step LoRA (bf16)",
"url": "https://huggingface.co/lightx2v/Qwen-Image-Lightning/resolve/main/Qwen-Image-Edit-2509/Qwen-Image-Edit-2509-Lightning-4steps-V1.0-bf16.safetensors?download=true",
"target_path_relative": "models/loras", "filename": "Qwen-Image-Edit-2509-Lightning-4steps-V1.0-bf16.safetensors",
"license": "Apache 2.0", "size_mb": 850, "packages": ["qwen_core"]
},
# Qwen Extras
"lora_qwen_lightning_8step": {
"id": "lora_qwen_lightning_8step", "type": "model", "name": "Qwen Image Edit Lightning 8-Step LoRA (bf16)",
"url": "https://huggingface.co/lightx2v/Qwen-Image-Lightning/resolve/main/Qwen-Image-Edit-2509/Qwen-Image-Edit-2509-Lightning-8steps-V1.0-bf16.safetensors?download=true",
"target_path_relative": "models/loras", "filename": "Qwen-Image-Edit-2509-Lightning-8steps-V1.0-bf16.safetensors",
"license": "Apache 2.0", "size_mb": 850, "packages": ["qwen_extras"]
},
"lora_qwen_lightning_4step": {
"id": "lora_qwen_lightning_4step", "type": "model", "name": "Qwen Image Lightning 4-Step LoRA (bf16)",
"url": "https://huggingface.co/lightx2v/Qwen-Image-Lightning/resolve/main/Qwen-Image-Lightning-4steps-V1.0-bf16.safetensors?download=true",
"target_path_relative": "models/loras", "filename": "Qwen-Image-Lightning-4steps-V1.0-bf16.safetensors",
"license": "Apache 2.0", "size_mb": 850, "packages": ["qwen_extras"]
},
# Nunchaku Qwen
"cn_nunchaku": {
"id": "cn_nunchaku", "type": "node", "name": "ComfyUI Nunchaku",
"git_url": "https://github.com/nunchaku-tech/ComfyUI-nunchaku.git",
"target_dir_relative": "custom_nodes",
"repo_name": "ComfyUI-nunchaku",
"license": "Apache 2.0", "packages": ["qwen_nunchaku"],
"pip_packages": ["nunchaku"]
},
"cn_qwen_lora_loader": {
"id": "cn_qwen_lora_loader", "type": "node", "name": "ComfyUI Qwen Image LoRA Loader",
"git_url": "https://github.com/ussoewwin/ComfyUI-QwenImageLoraLoader.git",
"target_dir_relative": "custom_nodes",
"repo_name": "ComfyUI-QwenImageLoraLoader",
"license": "Apache 2.0", "packages": ["qwen_nunchaku"]
},
"model_nunchaku_qwen": {
"id": "model_nunchaku_qwen", "type": "model", "name": "Nunchaku Qwen Image Edit 2509 (Int4)",
"url": "https://huggingface.co/nunchaku-tech/nunchaku-qwen-image-edit-2509/resolve/main/lightning-251115/svdq-int4_r128-qwen-image-edit-2509-lightning-4steps-251115.safetensors?download=true",
"target_path_relative": "models/diffusion_models", "filename": "svdq-int4_r128-qwen-image-edit-2509-lightning-4steps-251115.safetensors",
"license": "Apache 2.0", "size_mb": 12700, "packages": ["qwen_nunchaku"]
},
# --- PBR Decomposition (Marigold IID) ---
"cn_comfyui_marigold": {
"id": "cn_comfyui_marigold", "type": "node", "name": "ComfyUI-Marigold (IID/Depth/Normal)",
"git_url": "https://github.com/kijai/ComfyUI-Marigold.git",
"target_dir_relative": "custom_nodes",
"repo_name": "ComfyUI-Marigold",
"license": "GPL-3.0", "packages": ["pbr_marigold"],
"pip_packages": ["diffusers>=0.28", "accelerate", "matplotlib"] + (["triton-windows"] if sys.platform == "win32" else []),
"run_install_script": True,
},
# --- StableDelight (specular-free albedo) ---
"cn_comfyui_stabledelight": {
"id": "cn_comfyui_stabledelight", "type": "node", "name": "ComfyUI StableDelight (Delighting)",
"git_url": "https://github.com/lldacing/ComfyUI_StableDelight_ll.git",
"target_dir_relative": "custom_nodes",
"repo_name": "ComfyUI_StableDelight_ll",
"license": "Apache-2.0", "packages": ["pbr_stabledelight"],
"pip_packages": ["diffusers>=0.28", "accelerate", "matplotlib"] + (["triton-windows"] if sys.platform == "win32" else []),
"post_clone_patches": [
{
"file": "nodes/BaseNode.py",
"marker": "local_files_only=False",
"anchor": "local_files_only=True",
"patch": "local_files_only=False",
"mode": "replace",
},
],
},
"model_stabledelight": {
"id": "model_stabledelight", "type": "hf_model",
"name": "StableDelight Model (yoso-delight-v0-4-base)",
"hf_repo": "Stable-X/yoso-delight-v0-4-base",
"local_dir": "Stable-X--yoso-delight-v0-4-base",
"license": "Apache-2.0", "size_mb": 3300,
"packages": ["pbr_stabledelight"],
},
# --- TRELLIS.2 ---
"cn_trellis2": {
"id": "cn_trellis2", "type": "node", "name": "ComfyUI TRELLIS.2",
"git_url": "https://github.com/PozzettiAndrea/ComfyUI-TRELLIS2.git",
"target_dir_relative": "custom_nodes",
"repo_name": "ComfyUI-TRELLIS2",
"license": "MIT (Note: textured pipeline uses NVIDIA non-commercial libs)", "packages": ["trellis2"],
"pip_packages": ["comfy-env", "comfy-sparse-attn", "comfy-3d-viewers"],
"clean_envs": True,
"run_install_script": True,
"post_clone_patches": [
{
"file": "__init__.py",
"marker": "StableGen patch: Path.is_junction",
"anchor": "from comfy_env import",
"patch": _PATCH_PY310_IS_JUNCTION,
},
{
"file": "prestartup_script.py",
"marker": "StableGen patch: Auto-heal comfy-env",
"anchor": "from comfy_env import",
"patch": _PATCH_TRELLIS_PRESTARTUP,
},
{
"file": "nodes/trellis_utils/lazy_manager.py",
"marker": "_LAZY_MANAGER.attn_backend != attn_backend",
"anchor": _PATCH_TRELLIS_ATTN_CMP_ANCHOR,
"patch": _PATCH_TRELLIS_ATTN_CMP_REPLACE,
"mode": "replace",
},
{
"file": "nodes/trellis_utils/stages.py",
"marker": "# Use no_grad to prevent autograd",
"anchor": _PATCH_TRELLIS_NOGRAD_ANCHOR,
"patch": _PATCH_TRELLIS_NOGRAD_REPLACE,
"mode": "replace",
},
{
"file": "nodes/trellis2/pipelines/base.py",
"marker": "_model_id_by_obj",
"anchor": _PATCH_TRELLIS_UNLOAD_CPU_ANCHOR,
"patch": _PATCH_TRELLIS_UNLOAD_CPU_REPLACE,
"mode": "replace",
},
{
"file": "nodes/trellis_utils/lazy_manager.py",
"marker": "_unregister_from_comfy_env",
"anchor": _PATCH_TRELLIS_COMFY_HELPER_ANCHOR,
"patch": _PATCH_TRELLIS_COMFY_HELPER_REPLACE,
"mode": "replace",
},
{
"file": "nodes/trellis_utils/lazy_manager.py",
"marker": '_unregister_from_comfy_env(self.dinov3_model',
"anchor": _PATCH_TRELLIS_UNLOAD_DINOV3_ANCHOR,
"patch": _PATCH_TRELLIS_UNLOAD_DINOV3_REPLACE,
"mode": "replace",
},
{
"file": "nodes/trellis_utils/lazy_manager.py",
"marker": '_unregister_from_comfy_env(model, f"shape/',
"anchor": _PATCH_TRELLIS_UNLOAD_SHAPE_ANCHOR,
"patch": _PATCH_TRELLIS_UNLOAD_SHAPE_REPLACE,
"mode": "replace",
},
{
"file": "nodes/trellis_utils/lazy_manager.py",
"marker": '_unregister_from_comfy_env(model, f"texture/',
"anchor": _PATCH_TRELLIS_UNLOAD_TEX_ANCHOR,
"patch": _PATCH_TRELLIS_UNLOAD_TEX_REPLACE,
"mode": "replace",
},
{
"file": "nodes/trellis_utils/stages.py",
"marker": "# StableGen patch: clean up files from previous generations",
"anchor": _PATCH_TRELLIS_TEMP_CLEANUP_ANCHOR,
"patch": _PATCH_TRELLIS_TEMP_CLEANUP_REPLACE,
"mode": "replace",
},
{
"file": "nodes/rembg/BiRefNet.py",
"marker": "StableGen patch: BiRefNet fp32",
"anchor": "self.model.eval()",
"patch": "self.model.eval()\n self.model.float() # StableGen patch: BiRefNet fp32 — avoid fp16/fp32 dtype mismatch",
"mode": "replace",
},
{
"file": "nodes/trellis2/pipelines/rembg/BiRefNet.py",
"marker": "StableGen patch: timm.layers compat",
"anchor": "import torch",
"patch": (
"import torch\n"
"import sys as _sys # StableGen patch: timm.layers compat\n"
"if 'timm.layers' not in _sys.modules:\n"
" try:\n"
" import timm.models.layers as _tl; _sys.modules['timm.layers'] = _tl # timm<0.9 compat for BiRefNet\n"
" except ImportError: pass\n"
),
"mode": "replace",
},
]
},
# --- FLUX.2 Klein 4B ---
"model_flux2_klein_4b": {
"id": "model_flux2_klein_4b", "type": "model",
"name": "FLUX.2 Klein 4B Diffusion Model (FP8)",
"url": "https://huggingface.co/black-forest-labs/FLUX.2-klein-base-4b-fp8/resolve/main/flux-2-klein-base-4b-fp8.safetensors?download=true",
"target_path_relative": "models/diffusion_models",
"filename": "flux-2-klein-base-4b-fp8.safetensors",
"license": "Apache 2.0", "size_mb": 4070, "packages": ["flux2_klein"],
},
"model_flux2_text_encoder": {
"id": "model_flux2_text_encoder", "type": "model",
"name": "FLUX.2 Klein Qwen 3 4B Text Encoder (bf16)",
"url": "https://huggingface.co/Comfy-Org/z_image_turbo/resolve/main/split_files/text_encoders/qwen_3_4b.safetensors?download=true",
"target_path_relative": "models/text_encoders",
"filename": "qwen_3_4b.safetensors",
"license": "Apache 2.0", "size_mb": 8050, "packages": ["flux2_klein"],
},
"model_flux2_vae": {
"id": "model_flux2_vae", "type": "model",
"name": "FLUX.2 Klein VAE",
"url": "https://huggingface.co/Comfy-Org/flux2-dev/resolve/main/split_files/vae/flux2-vae.safetensors?download=true",
"target_path_relative": "models/vae",
"filename": "flux2-vae.safetensors",
"license": "Apache 2.0", "size_mb": 321, "packages": ["flux2_klein"],
},
}
# Define what items each menu option entails by listing package tags
# The script will collect all unique items based on the selected package tags.
MENU_PACKAGES: Dict[str, Dict[str, Any]] = {
'1': {"name": "[MINIMAL CORE] Basic Requirements",
"tags": ["core"],
"size_gb": 7.3,
"description_suffix": "*You will still need to manually download your own SDXL checkpoint(s) and all ControlNet models for full functionality and preset usage.*"},
'2': {"name": "[ESSENTIAL] Core + Preset Essentials",
"tags": ["core", "preset_essentials"],
"size_gb": 9.8,
"description_suffix": "*All models for preset functionality. You will still need to manually download your own SDXL checkpoint(s).*"},
'3': {"name": "[RECOMMENDED] Full SDXL Setup (No Checkpoints)",
"tags": ["core", "preset_essentials", "extended_optional", "pbr_marigold", "pbr_stabledelight"],
"size_gb": 19.3,
"description_suffix": "*Downloads optional ControlNet and LoRA models + PBR decomposition nodes. You will still need to manually download your own SDXL checkpoint(s).*"},
'4': {"name": "[COMPLETE SDXL] Full SDXL Setup + RealVisXL V5.0 Checkpoint",
"tags": ["core", "preset_essentials", "extended_optional", "pbr_marigold", "pbr_stabledelight", "checkpoint_realvis"],
"size_gb": 26.3,
"description_suffix": ""},
'5': {"name": "[QWEN CORE] Models + GGUF Node",
"tags": ["qwen_core"],
"size_gb": 20.3,
"description_suffix": "*Installs Qwen Image Edit UNet, VAE, text encoder, core LoRA, and GGUF ComfyUI node.*"},
'6': {"name": "[QWEN EXTRAS] Core + Lightning LoRAs",
"tags": ["qwen_core", "qwen_extras"],
"size_gb": 22.6,
"description_suffix": "*Adds additional Qwen Lightning LoRAs on top of the Qwen core install.*"},
'7': {"name": "[QWEN NUNCHAKU] Nunchaku Nodes + Model",
"tags": ["qwen_core", "qwen_nunchaku"],
"size_gb": 33.0,
"description_suffix": "*Installs Qwen Core components plus Nunchaku nodes and the Int4 quantized model (12.7GB).*"},
'8': {"name": "[TRELLIS.2] Image-to-3D Node",
"tags": ["trellis2"],
"size_gb": 20.4,
"description_suffix": "*Installs ComfyUI-TRELLIS2 custom node + isolated Python environment (~5 GB).*\n"
" *TRELLIS.2 models (~15.4 GB) are downloaded automatically from HuggingFace on first use.*\n"
" *LICENSE NOTICE: Only the 'Native (TRELLIS.2)' texture mode uses nvdiffrast/nvdiffrec*\n"
" *(NVIDIA Source Code License — non-commercial use only). See README.md for full details.*",
},
'9': {"name": "[PBR DECOMPOSITION] Marigold IID Node",
"tags": ["pbr_marigold"],
"size_gb": 0.01,
"description_suffix": "*Installs ComfyUI-Marigold custom node for PBR decomposition (albedo, roughness, metallic).*\n"
" *IID models (~2GB each) are downloaded automatically from HuggingFace on first use.*",
},
'10': {"name": "[PBR DECOMPOSITION] StableDelight Node + Model",
"tags": ["pbr_marigold", "pbr_stabledelight"],
"size_gb": 3.3,
"description_suffix": "*Installs ComfyUI_StableDelight_ll custom node + downloads the*\n"
" *Stable-X/yoso-delight-v0-4-base model (~3.3GB fp16) for specular-free albedo.*",
},
'11': {"name": "[FLUX.2 KLEIN] Klein 4B FP8 + Qwen 3 Text Encoder + VAE",
"tags": ["flux2_klein"],
"size_gb": 12.4,
"description_suffix": "*Downloads FLUX.2 Klein 4B FP8 diffusion model (~4.1GB), Qwen 3 4B text encoder bf16 (~8.0GB),*\n"
" *and FLUX.2 VAE (~0.3GB). All ComfyUI nodes are built-in (no custom nodes needed).*\n"
" *Apache 2.0 license. Requires ~13GB VRAM.*",
},
}
# --- Helper Functions ---
def print_header(title: str):
print(f"\n{'='*10} {title} {'='*10}")
def print_separator(char='-', length=70):
print(char * length)
def get_comfyui_path_from_args() -> Path:
parser = argparse.ArgumentParser(description="StableGen Dependency Installer Script.")
parser.add_argument("comfyuipath", nargs='?', default=None,
help="Full path to your ComfyUI installation directory. If not provided, will be prompted.")
args = parser.parse_args()
comfyui_path_str = args.comfyuipath
while not comfyui_path_str:
comfyui_path_str = input("Please enter the full path to your ComfyUI installation directory: ").strip()
comfyui_path = Path(comfyui_path_str).resolve() # Get absolute path
if not comfyui_path.is_dir():
print(f"Error: ComfyUI path '{comfyui_path}' not found or not a directory.")
sys.exit(1)
if not (comfyui_path / "models").is_dir() or not (comfyui_path / "custom_nodes").is_dir():
print(f"Error: '{comfyui_path}' does not look like a valid ComfyUI directory (missing 'models' or 'custom_nodes' subfolder).")
sys.exit(1)
return comfyui_path
def find_comfyui_python(comfyui_path: Path) -> str:
"""Detect the Python executable used by ComfyUI.
Checks (in order):
1. Windows portable: python_embedded/python.exe
2. Virtual-env: venv/Scripts/python.exe or venv/bin/python
3. Fallback: the Python running this script (sys.executable)
"""
# Windows portable build
embedded = comfyui_path / "python_embedded" / "python.exe"
if embedded.is_file():
return str(embedded)
# venv (Windows)
venv_win = comfyui_path / "venv" / "Scripts" / "python.exe"
if venv_win.is_file():
return str(venv_win)
# venv (Linux / macOS)
venv_unix = comfyui_path / "venv" / "bin" / "python"
if venv_unix.is_file():
return str(venv_unix)
# Fallback
return sys.executable
def install_pip_packages(pip_packages: List[str], comfyui_path: Path, force_reinstall: bool = False):
"""Install pip packages into ComfyUI's Python environment."""
python_exe = find_comfyui_python(comfyui_path)
print(f" Installing pip packages into ComfyUI Python: {python_exe}")
for pkg in pip_packages:
print(f" pip install {pkg} ...")
try:
subprocess.run(
[python_exe, "-m", "pip", "install"] + (["--force-reinstall", "--no-deps"] if force_reinstall else []) + [pkg],
check=True,
)
print(f" Successfully installed '{pkg}'.")
except subprocess.CalledProcessError as e:
print(f" ERROR: Failed to install '{pkg}' (exit code {e.returncode}).")
print(f" You may need to install it manually: pip install {pkg}")
except FileNotFoundError:
print(f" ERROR: Python executable not found at '{python_exe}'.")
print(f" Please install '{pkg}' manually into your ComfyUI Python environment.")
break
def _apply_all_comfy_env_patches(comfyui_path: Path):
"""Apply all comfy-env patches (platform tag, wheel fallback, site isolation, dist-info, validator)."""
_patch_comfy_env_platform_tag(comfyui_path)
_patch_comfy_env_wheel_fallback(comfyui_path)
_patch_comfy_env_user_site_isolation(comfyui_path)
_patch_comfy_env_distinfo_normalize(comfyui_path)
_patch_comfy_env_validator(comfyui_path)
def _patch_comfy_env_validator(comfyui_path: Path):
"""Patch comfy-env's _validate_node_config to strip torch/torchvision instead of crashing."""
python_exe = find_comfyui_python(comfyui_path)
result = subprocess.run(
[python_exe, "-c",
"import importlib.util as u, os; s=u.find_spec('comfy_env'); print(os.path.join(os.path.dirname(s.origin), 'packages', 'toml_generator.py') if s and s.origin else '')"],
capture_output=True, text=True,
)
if result.returncode != 0:
print(" WARNING: Could not locate comfy_env toml_generator.py, skipping validator patch")
return
toml_gen_path = Path(result.stdout.strip().splitlines()[-1])
if not toml_gen_path.is_file():
print(f" WARNING: {toml_gen_path} not found, skipping validator patch")
return
content = toml_gen_path.read_text(encoding="utf-8")
marker = "# StableGen patch: bypass toml validation crash by stripping torch/torchvision"
if marker in content:
print(" comfy-env validator patch already applied")
return
old = (
"def _validate_node_config(name: str, cfg: ComfyEnvConfig) -> None:\n"
" \"\"\"Reject node configs that try to redefine the workspace torch pin.\"\"\"\n"
" bad = [p for p in cfg.cuda_packages if p in _TORCH_PKGS]\n"
" if bad:\n"
" raise ValueError(\n"
" f\"[{name}] comfy-env.toml has {bad} under [cuda] packages. \"\n"
" \"Plain torch/torchvision/torchaudio are pinned workspace-wide \"\n"
" \"(replicated into every feature so the rattler cache dedupes). \"\n"
" \"Remove them from [cuda] packages -- keep only CUDA-only wheels there \"\n"
" \"(cumesh, flash-attn, cc_torch, nvdiffrast, etc.).\"\n"
" )"
)
if old not in content:
old_alt = (
"def _validate_node_config(name: str, cfg: ComfyEnvConfig) -> None:\n"
" \"\"\"Reject node configs that try to redefine the workspace torch pin.\"\"\"\n"
" bad = [p for p in cfg.cuda_packages if p in _TORCH_PKGS]\n"
" if bad:\n"
" raise ValueError(\n"
" f\"[{name}] comfy-env.toml has {bad} under [cuda] packages. \"\n"
" \"Plain torch/torchvision/torchaudio are pinned workspace-wide \"\n"
" \"(replicated into every feature so the rattler cache dedupes). \"\n"
" \"Remove them from [cuda] packages -- keep only CUDA-only wheels there \"\n"
" \"(cumesh, flash-attn, cc_torch, nvdiffrast, etc.).\"\n"
" )\n"
)
if old_alt in content:
old = old_alt
else:
print(" WARNING: Could not find validator anchor in toml_generator.py (already modified?)")
return
new = (
"def _validate_node_config(name: str, cfg: ComfyEnvConfig) -> None:\n"
" " + marker + "\n"
" bad = [p for p in cfg.cuda_packages if p in _TORCH_PKGS]\n"
" if bad:\n"
" for p in bad:\n"
" try:\n"
" cfg.cuda_packages.remove(p)\n"
" except ValueError:\n"
" pass\n"
" print(f'[comfy-env] [{name}] stripped plain torch/torchvision from [cuda] packages list', file=sys.stderr)\n"
)
content = content.replace(old, new)
toml_gen_path.write_text(content, encoding="utf-8")
print(" Patched comfy-env _validate_node_config() to bypass invalid torch/torchvision declarations")
def _patch_comfy_env_platform_tag(comfyui_path: Path):
"""Fix comfy-env 0.2.0 Linux platform tag matching bug.
comfy-env's _platform_tag() returns "linux_x86_64" but pre-built CUDA
wheels use "manylinux_2_34_x86_64" filenames. The substring check
``"linux_x86_64" in "manylinux_2_34_x86_64"`` fails because the glibc
version sits between "linux_" and "x86_64".
Fix: return "linux" instead, which IS a substring of "manylinux_*".
"""
python_exe = find_comfyui_python(comfyui_path)
result = subprocess.run(
[python_exe, "-c",
"import importlib.util as u, os; s=u.find_spec('comfy_env'); print(os.path.join(os.path.dirname(s.origin), 'packages', 'cuda_wheels.py') if s and s.origin else '')"],
capture_output=True, text=True,
)
if result.returncode != 0:
print(" WARNING: Could not locate comfy_env cuda_wheels.py, "
"skipping platform tag patch")
return
cuda_wheels_path = Path(result.stdout.strip())
if not cuda_wheels_path.is_file():
print(f" WARNING: {cuda_wheels_path} not found, "
"skipping platform tag patch")
return
content = cuda_wheels_path.read_text(encoding="utf-8")
marker = "# StableGen patch: linux platform tag"
if marker in content:
print(" comfy-env platform tag patch already applied")
return
old = 'return "linux_x86_64"'
if old not in content:
print(" WARNING: Could not find platform tag to patch in "
"cuda_wheels.py (already fixed upstream?)")
return
content = content.replace(old, f'return "linux" {marker}')
cuda_wheels_path.write_text(content, encoding="utf-8")
print(" Patched comfy-env _platform_tag() for Linux manylinux matching")
def _patch_comfy_env_wheel_fallback(comfyui_path: Path):
"""Fix comfy-env get_wheel_url missing torch version fallback.
Some packages (e.g. flash-attn) lack wheels for the exact torch version
comfy-env pins (e.g. torch 2.4 on Linux, though torch 2.5+ exist).
Patch get_wheel_url to try higher torch versions when exact match fails.
"""
python_exe = find_comfyui_python(comfyui_path)
result = subprocess.run(
[python_exe, "-c",
"import importlib.util as u, os; s=u.find_spec('comfy_env'); print(os.path.join(os.path.dirname(s.origin), 'packages', 'cuda_wheels.py') if s and s.origin else '')"],
capture_output=True, text=True,
)
if result.returncode != 0:
print(" WARNING: Could not locate comfy_env cuda_wheels.py, "
"skipping wheel fallback patch")
return
cuda_wheels_path = Path(result.stdout.strip())
if not cuda_wheels_path.is_file():
print(f" WARNING: {cuda_wheels_path} not found, "
"skipping wheel fallback patch")
return