-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathnodes.py
More file actions
1475 lines (1335 loc) · 53.9 KB
/
nodes.py
File metadata and controls
1475 lines (1335 loc) · 53.9 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 os
import json
import platform
import multiprocessing
import shutil
import subprocess
import tempfile
from typing import Any, Dict, List, Optional, Tuple, Union
import folder_paths
CONFIG_FILE = os.path.join(os.path.dirname(__file__), "config.json")
def load_config() -> Dict[str, Any]:
"""Load config from config.json; return empty dict if missing or invalid."""
try:
with open(CONFIG_FILE, "r") as f:
return json.load(f)
except (FileNotFoundError, json.JSONDecodeError):
return {}
def get_user_model_folders() -> List[str]:
"""Return user-specified model folders from config.json."""
return load_config().get("model_folders", [])
def get_merged_model_folders() -> List[str]:
"""Merge ComfyUI text_encoders folders with any user-configured folders."""
try:
comfy_folders = folder_paths.get_folder_paths("text_encoders")
except Exception:
comfy_folders = []
all_folders = comfy_folders + get_user_model_folders()
return [f for f in all_folders if os.path.isdir(f)]
def scan_gguf_models() -> List[str]:
"""Scan registered 'acestep_gguf' folder type for .gguf files.
Tries ComfyUI's folder_paths registry first (so the built-in model
manager can track the files), then falls back to manual scanning.
"""
try:
all_files = folder_paths.get_filename_list("acestep_gguf")
gguf_files = sorted(f for f in all_files if f.lower().endswith(".gguf"))
if gguf_files:
return gguf_files
except Exception:
pass
# Fallback: manual scan of text_encoders + user-configured folders
seen_models: set = set()
models: List[str] = []
for folder in get_merged_model_folders():
try:
for name in os.listdir(folder):
if name.lower().endswith(".gguf") and name not in seen_models:
models.append(name)
seen_models.add(name)
except OSError:
pass
return sorted(models)
def find_model_path(model_name: str) -> Optional[str]:
"""Return the full path to a model file, or None if not found."""
for folder in get_merged_model_folders():
path = os.path.join(folder, model_name)
if os.path.isfile(path):
return path
return None
def _coerce_float(value: Any, default: float) -> float:
"""Return *value* as a float, falling back to *default* for empty strings.
Older ComfyUI workflows may store optional FLOAT widget values as ``""``
instead of the numeric default when the field was not explicitly set.
"""
if isinstance(value, str):
return float(value) if value.strip() else default
return float(value)
def _coerce_int(value: Any, default: int) -> int:
"""Return *value* as an int, falling back to *default* for empty strings.
Older ComfyUI workflows may store optional INT widget values as ``""``
instead of the numeric default when the field was not explicitly set.
"""
if isinstance(value, str):
return int(value) if value.strip() else default
return int(value)
def _binary_in_build(build_dir: str, name: str) -> Optional[str]:
"""Return the path to *name* if it exists in *build_dir* or *build_dir*/bin.
ggml's CMakeLists.txt sets ``CMAKE_RUNTIME_OUTPUT_DIRECTORY`` to
``${CMAKE_BINARY_DIR}/bin`` when it is used as a cmake subdirectory (the
normal case for acestep.cpp). The cmake configure command now passes this
variable explicitly, but we still check *build_dir*/bin/ so that existing
installations built before this fix are found without a forced rebuild.
"""
for candidate in (
os.path.join(build_dir, name),
os.path.join(build_dir, "bin", name),
):
if os.path.isfile(candidate):
return candidate
return None
def get_binary_path(binary_name: str) -> Optional[str]:
"""
Locate an acestep.cpp binary.
Search order:
1. Explicit path from config.json ``binary_paths`` mapping.
2. System PATH (via shutil.which).
3. ``<node_dir>/acestep.cpp/build/<binary_name>`` (local build alongside the node).
4. ``<node_dir>/acestep.cpp/build/bin/<binary_name>`` (ggml's default output
directory when used as a cmake subdirectory).
"""
config = load_config()
explicit = config.get("binary_paths", {}).get(binary_name)
if explicit and os.path.isfile(explicit):
return explicit
on_path = shutil.which(binary_name)
if on_path:
return on_path
build_base = os.path.join(os.path.dirname(__file__), "acestep.cpp", "build")
return _binary_in_build(build_base, binary_name)
# ---------------------------------------------------------------------------
# Nodes
# ---------------------------------------------------------------------------
# HuggingFace repo that hosts all pre-quantized ACE-Step GGUFs
_HF_REPO = "Serveurperso/ACE-Step-1.5-GGUF"
# Quant resolution rules mirroring models.sh
_EMB_QUANTS = ["Q8_0", "BF16"]
_LM_SMALL_QUANTS = ["Q8_0", "BF16"]
_LM_4B_QUANTS = ["Q8_0", "Q6_K", "Q5_K_M", "BF16"]
_DIT_QUANTS = ["Q8_0", "Q6_K", "Q5_K_M", "Q4_K_M", "BF16"]
_DIT_VARIANTS = ["turbo", "sft", "base", "turbo-shift1", "turbo-shift3", "turbo-continuous"]
_LM_SIZES = ["4B", "1.7B", "0.6B"]
def _resolve_quant(requested: str, model_type: str) -> str:
"""Mirror the quant resolution logic from models.sh."""
if model_type in ("emb", "lm_small"):
return requested if requested == "BF16" else "Q8_0"
if model_type == "lm_4B":
if requested in ("Q4_K_M", "Q5_K_M"):
return "Q5_K_M"
return requested if requested in ("BF16", "Q8_0", "Q6_K") else "Q8_0"
return requested # dit: all quants available
class AcestepCPPModelDownloader:
"""
Download ACE-Step GGUF models from HuggingFace (``Serveurperso/ACE-Step-1.5-GGUF``)
directly into a local folder so they appear in the Model Loader dropdown.
"""
@classmethod
def INPUT_TYPES(cls):
try:
default_dir = folder_paths.get_folder_paths("text_encoders")[0]
except Exception:
default_dir = os.path.join(os.path.dirname(__file__), "models")
return {
"required": {
"save_dir": (
"STRING",
{
"default": default_dir,
"tooltip": "Directory to save downloaded GGUF files into",
},
),
"lm_size": (
_LM_SIZES,
{"default": "4B", "tooltip": "LM model size"},
),
"quant": (
_DIT_QUANTS,
{
"default": "Q8_0",
"tooltip": (
"Quantisation level. "
"Embedding/LM models fall back to the nearest available quant "
"automatically (mirroring models.sh logic)."
),
},
),
"dit_variant": (
_DIT_VARIANTS,
{"default": "turbo", "tooltip": "DiT model variant to download"},
),
},
"optional": {
"hf_token": (
"STRING",
{
"default": "",
"tooltip": "HuggingFace access token (leave empty for public repos)",
},
),
"overwrite": (
"BOOLEAN",
{
"default": False,
"tooltip": "Re-download even if the file already exists",
"label_on": "Overwrite",
"label_off": "Skip existing",
},
),
},
}
RETURN_TYPES = ("STRING",)
RETURN_NAMES = ("downloaded_files",)
FUNCTION = "download"
CATEGORY = "AcestepCPP"
OUTPUT_NODE = True
def download(
self,
save_dir: str,
lm_size: str = "4B",
quant: str = "Q8_0",
dit_variant: str = "turbo",
hf_token: str = "",
overwrite: bool = False,
):
try:
from huggingface_hub import hf_hub_download
except ImportError:
raise RuntimeError(
"huggingface_hub is required for model downloading. "
"Install it with: pip install huggingface_hub"
)
os.makedirs(save_dir, exist_ok=True)
token = hf_token.strip() or None
lm_type = "lm_4B" if lm_size == "4B" else "lm_small"
files_to_download = [
"vae-BF16.gguf",
f"Qwen3-Embedding-0.6B-{_resolve_quant(quant, 'emb')}.gguf",
f"acestep-5Hz-lm-{lm_size}-{_resolve_quant(quant, lm_type)}.gguf",
f"acestep-v15-{dit_variant}-{_resolve_quant(quant, 'dit')}.gguf",
]
downloaded: List[str] = []
skipped: List[str] = []
for filename in files_to_download:
dest = os.path.join(save_dir, filename)
if os.path.isfile(dest) and not overwrite:
print(f"[AcestepCPP] Skip (exists): {filename}")
skipped.append(filename)
continue
print(f"[AcestepCPP] Downloading: {filename} ...")
hf_hub_download(
repo_id=_HF_REPO,
filename=filename,
local_dir=save_dir,
token=token,
)
print(f"[AcestepCPP] Done: {filename}")
downloaded.append(filename)
summary_parts = []
if downloaded:
summary_parts.append(f"Downloaded: {', '.join(downloaded)}")
if skipped:
summary_parts.append(f"Skipped (already exist): {', '.join(skipped)}")
summary = "\n".join(summary_parts) if summary_parts else "Nothing to do."
return (summary,)
# The upstream source repository for the binaries
_ACESTEP_CPP_REPO = "https://github.com/audiohacking/acestep.cpp"
class AcestepCPPBuilder:
"""
Clone ``acestep.cpp`` from GitHub and build the ``ace-lm`` and
``ace-synth`` binaries via CMake.
The default clone directory (``<node_dir>/acestep.cpp``) is the same path
that ``get_binary_path()`` already searches, so the built binaries will be
found automatically by the Generate node without any extra configuration.
"""
BACKENDS = ["auto", "cuda", "metal", "blas", "cpu"]
@classmethod
def INPUT_TYPES(cls):
default_dir = os.path.join(os.path.dirname(__file__), "acestep.cpp")
return {
"required": {
"clone_dir": (
"STRING",
{
"default": default_dir,
"tooltip": (
"Directory to clone acestep.cpp into. "
"Defaults to <node_dir>/acestep.cpp so that the "
"Generate node finds the binaries automatically."
),
},
),
"backend": (
cls.BACKENDS,
{
"default": "auto",
"tooltip": (
"GPU/compute backend for CMake. "
"'auto' detects CUDA, Metal, or falls back to CPU."
),
},
),
},
"optional": {
"force_rebuild": (
"BOOLEAN",
{
"default": False,
"tooltip": (
"Delete the existing build directory and rebuild from scratch."
),
"label_on": "Force rebuild",
"label_off": "Incremental",
},
),
},
}
RETURN_TYPES = ("STRING",)
RETURN_NAMES = ("build_log",)
FUNCTION = "build"
CATEGORY = "AcestepCPP"
OUTPUT_NODE = True
# Maximum number of recent log lines included in error messages
_MAX_ERROR_LOG_LINES = 40
# Binaries produced by the cmake build
_BINARIES = ("ace-lm", "ace-synth")
# ------------------------------------------------------------------
# Helpers
# ------------------------------------------------------------------
@staticmethod
def _detect_backend() -> str:
"""Return the best available cmake backend flag value."""
# CUDA: look for nvcc or nvidia-smi on PATH
if shutil.which("nvcc") or shutil.which("nvidia-smi"):
return "cuda"
# Apple Metal: macOS always supports Metal through ggml
if platform.system() == "Darwin":
return "metal"
# OpenBLAS: check pkg-config first (cross-distro), then common header
# locations, then dpkg as a last resort on Debian-based systems
if shutil.which("pkg-config") and subprocess.run(
["pkg-config", "--exists", "openblas"],
capture_output=True,
).returncode == 0:
return "blas"
openblas_headers = [
"/usr/include/openblas/cblas.h",
"/usr/local/include/openblas/cblas.h",
"/opt/homebrew/include/openblas/cblas.h",
]
if any(os.path.isfile(h) for h in openblas_headers):
return "blas"
if shutil.which("dpkg") and subprocess.run(
["dpkg", "-l", "libopenblas-dev"],
capture_output=True,
).returncode == 0:
return "blas"
return "cpu"
@staticmethod
def _cmake_flags(backend: str) -> List[str]:
"""Translate backend name to CMake -D flags."""
mapping = {
"cuda": ["-DGGML_CUDA=ON"],
"metal": [], # Metal is auto-enabled on macOS by ggml
"blas": ["-DGGML_BLAS=ON"],
"cpu": [],
}
return mapping.get(backend, [])
@staticmethod
def _run(cmd: List[str], cwd: str, log_lines: List[str]) -> None:
"""Run a command, stream output to log_lines, raise on failure."""
label = " ".join(cmd)
log_lines.append(f"$ {label}")
result = subprocess.run(
cmd, cwd=cwd, capture_output=True, text=True
)
if result.stdout:
log_lines.extend(result.stdout.splitlines())
if result.stderr:
log_lines.extend(result.stderr.splitlines())
if result.returncode != 0:
raise RuntimeError(
f"Command failed (exit {result.returncode}): {label}\n"
+ "\n".join(log_lines[-AcestepCPPBuilder._MAX_ERROR_LOG_LINES:])
)
# ------------------------------------------------------------------
# Main entry point
# ------------------------------------------------------------------
def build(
self,
clone_dir: str,
backend: str = "auto",
force_rebuild: bool = False,
):
log: List[str] = []
# --- Resolve backend --------------------------------------------------
resolved = self._detect_backend() if backend == "auto" else backend
log.append(f"[AcestepCPP] Backend: {resolved} (requested: {backend})")
# --- Clone or update --------------------------------------------------
repo_dir = clone_dir
if not os.path.isdir(repo_dir):
log.append(f"[AcestepCPP] Cloning {_ACESTEP_CPP_REPO} -> {repo_dir}")
if not shutil.which("git"):
raise RuntimeError(
"git is not available on PATH. Please install git and retry."
)
self._run(
["git", "clone", "--recurse-submodules", _ACESTEP_CPP_REPO, repo_dir],
cwd=os.path.dirname(repo_dir),
log_lines=log,
)
else:
log.append(f"[AcestepCPP] Repo exists: {repo_dir} — updating submodules")
self._run(
["git", "submodule", "update", "--init", "--recursive"],
cwd=repo_dir,
log_lines=log,
)
# --- Prepare build directory ------------------------------------------
build_dir = os.path.join(repo_dir, "build")
if force_rebuild and os.path.isdir(build_dir):
log.append(f"[AcestepCPP] Removing existing build dir: {build_dir}")
shutil.rmtree(build_dir)
os.makedirs(build_dir, exist_ok=True)
# --- CMake configure --------------------------------------------------
# Pass CMAKE_RUNTIME_OUTPUT_DIRECTORY explicitly so that ggml's
# CMakeLists.txt (which defaults to ${CMAKE_BINARY_DIR}/bin when used
# as a subdirectory) does not redirect ace-lm and ace-synth into
# build/bin/ instead of build/.
cmake_cmd = [
"cmake", "..",
f"-DCMAKE_RUNTIME_OUTPUT_DIRECTORY={build_dir}",
] + self._cmake_flags(resolved)
log.append(f"[AcestepCPP] Configuring: {' '.join(cmake_cmd)}")
if not shutil.which("cmake"):
raise RuntimeError(
"cmake is not available on PATH. "
"Install cmake (e.g. apt install cmake) and retry."
)
self._run(cmake_cmd, cwd=build_dir, log_lines=log)
# --- CMake build ------------------------------------------------------
jobs = str(multiprocessing.cpu_count())
build_cmd = ["cmake", "--build", ".", "--config", "Release", f"-j{jobs}"]
log.append(f"[AcestepCPP] Building with {jobs} parallel jobs ...")
self._run(build_cmd, cwd=build_dir, log_lines=log)
# --- Verify outputs ---------------------------------------------------
# _binary_in_build checks both build/ (new cmake configure with explicit
# output dir) and build/bin/ (ggml's default when
# CMAKE_RUNTIME_OUTPUT_DIRECTORY is not set).
missing = [
binary for binary in self._BINARIES
if _binary_in_build(build_dir, binary) is None
]
if missing:
raise RuntimeError(
f"Build succeeded but expected binaries not found: {', '.join(missing)}. "
f"Check the build log above."
)
log.append(
f"[AcestepCPP] Build complete. Binaries in {build_dir}: "
+ ", ".join(self._BINARIES)
)
return ("\n".join(log),)
class AcestepCPPLoraLoader:
"""
Specify a LoRA adapter file for use with acestep.cpp.
Enter the full path to any ``.gguf`` or ``.safetensors`` LoRA file on
your filesystem. Outputs an ``ACESTEP_LORA`` dict consumed by the
generator node.
"""
_ALLOWED_EXTENSIONS = (".gguf", ".safetensors")
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"lora_path": (
"STRING",
{
"default": "",
"tooltip": (
"Full path to a LoRA adapter file (.gguf or .safetensors). "
"You can use any file location on your filesystem."
),
},
),
"lora_scale": (
"FLOAT",
{
"default": 1.0,
"min": 0.0,
"max": 2.0,
"step": 0.01,
"tooltip": "LoRA adapter scale",
},
),
}
}
RETURN_TYPES = ("ACESTEP_LORA",)
RETURN_NAMES = ("lora",)
FUNCTION = "load_lora"
CATEGORY = "AcestepCPP"
def load_lora(self, lora_path: str, lora_scale: float):
path = lora_path.strip()
if not path:
raise ValueError(
"lora_path is empty. Enter the full path to your LoRA file."
)
if not any(path.lower().endswith(ext) for ext in self._ALLOWED_EXTENSIONS):
raise ValueError(
f"Unsupported LoRA file type: {path!r}. "
f"Expected one of: {', '.join(self._ALLOWED_EXTENSIONS)}"
)
if not os.path.isfile(path):
raise FileNotFoundError(
f"LoRA file not found: {path}"
)
return ({"path": path, "scale": lora_scale},)
class AcestepCPPOptions:
"""
Advanced technical options for acestep.cpp generation.
Configures output format, VAE memory tiling, batch counts, and debug
flags that are typically set once and reused across multiple generations.
Connect the output to the **Acestep.cpp Generate** node's ``options``
input. All parameters are optional — unset fields fall back to their
acestep.cpp defaults.
"""
OUTPUT_FORMATS = ["mp3", "wav"]
@classmethod
def INPUT_TYPES(cls):
return {
"optional": {
# Output format
"output_format": (
cls.OUTPUT_FORMATS,
{
"default": "mp3",
"tooltip": "Audio output format: MP3 (smaller) or WAV (lossless)",
},
),
"mp3_bitrate": (
"INT",
{
"default": 128,
"min": 64,
"max": 320,
"tooltip": "MP3 bitrate in kbps (only used when output_format is 'mp3')",
},
),
# VAE memory control
"vae_chunk": (
"INT",
{
"default": 256,
"min": 16,
"max": 1024,
"tooltip": (
"VAE latent frames per tile (default: 256). "
"Reduce to lower VRAM usage at the cost of speed."
),
},
),
"vae_overlap": (
"INT",
{
"default": 64,
"min": 0,
"max": 256,
"tooltip": "VAE overlap frames per side (default: 64)",
},
),
# Batch generation
"lm_batch": (
"INT",
{
"default": 1,
"min": 1,
"max": 9,
"tooltip": (
"Number of LM (ace-lm) sequences to generate in parallel. "
"Each element produces a genuinely different song from a different seed."
),
},
),
"dit_batch": (
"INT",
{
"default": 1,
"min": 1,
"max": 9,
"tooltip": (
"Number of DiT (ace-synth) variations per LM output (max 9). "
"Variations share the same prompt but differ in initial noise."
),
},
),
# Advanced / debug
"no_flash_attn": (
"BOOLEAN",
{
"default": False,
"tooltip": "Disable flash attention in both ace-lm and ace-synth",
"label_on": "Disabled",
"label_off": "Enabled",
},
),
"lm_max_seq": (
"INT",
{
"default": 8192,
"min": 1024,
"max": 65536,
"tooltip": "ace-lm KV cache size in tokens (default: 8192)",
},
),
"lm_no_fsm": (
"BOOLEAN",
{
"default": False,
"tooltip": "Disable FSM constrained decoding in ace-lm",
"label_on": "Disabled",
"label_off": "Enabled",
},
),
}
}
RETURN_TYPES = ("ACESTEP_OPTIONS",)
RETURN_NAMES = ("options",)
FUNCTION = "get_options"
CATEGORY = "AcestepCPP"
def get_options(self, **kwargs) -> Tuple:
return (dict(kwargs),)
class AcestepCPPModelLoader:
"""
Select the four GGUF model files required by acestep.cpp.
Outputs an ``ACESTEP_MODELS`` dict consumed by the generator node.
"""
@classmethod
def INPUT_TYPES(cls):
model_list = scan_gguf_models()
options = model_list if model_list else ["No GGUF models found"]
return {
"required": {
"lm_model": (
options,
{
"tooltip": (
"LM (ace-lm) model GGUF, e.g. "
"acestep-5Hz-lm-4B-Q8_0.gguf"
)
},
),
"text_encoder_model": (
options,
{
"tooltip": (
"Text-encoder GGUF, e.g. "
"Qwen3-Embedding-0.6B-Q8_0.gguf"
)
},
),
"dit_model": (
options,
{
"tooltip": (
"DiT GGUF, e.g. "
"acestep-v15-turbo-Q8_0.gguf"
)
},
),
"vae_model": (
options,
{"tooltip": "VAE GGUF, e.g. vae-BF16.gguf"},
),
}
}
RETURN_TYPES = ("ACESTEP_MODELS",)
RETURN_NAMES = ("models",)
FUNCTION = "load_models"
CATEGORY = "AcestepCPP"
def load_models(
self,
lm_model: str,
text_encoder_model: str,
dit_model: str,
vae_model: str,
):
paths = {
"lm_model": find_model_path(lm_model),
"text_encoder": find_model_path(text_encoder_model),
"dit": find_model_path(dit_model),
"vae": find_model_path(vae_model),
}
missing = [
label
for label, path in [
("LM model", paths["lm_model"]),
("text encoder", paths["text_encoder"]),
("DiT model", paths["dit"]),
("VAE model", paths["vae"]),
]
if path is None
]
if missing:
raise FileNotFoundError(
f"Could not locate model file(s): {', '.join(missing)}. "
"Check your model folder configuration."
)
return (paths,)
class AcestepCPPGenerate:
"""
Generate music with acestep.cpp.
Runs ``ace-lm`` (LM) then ``ace-synth`` (DiT + VAE). The native MP3 or
WAV produced by the binary is copied as-is to ComfyUI's output directory
and an inline audio player is displayed on the node — no Python audio
decoding or re-encoding is performed. Connect an **AcestepCPPOptions**
node to the ``options`` input to control output format, batching, VAE
tiling, and advanced debug flags.
"""
VOCAL_LANGUAGES = [
"", "en", "zh", "fr", "de", "es", "ja", "ko", "pt", "ru", "it", "unknown",
]
LEGO_TRACKS = [
"", "vocals", "backing_vocals", "drums", "bass", "guitar",
"keyboard", "percussion", "strings", "synth", "fx", "brass", "woodwinds",
]
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"models": (
"ACESTEP_MODELS",
{"tooltip": "Model paths from the AcestepCPP Model Loader node"},
),
"caption": (
"STRING",
{
"multiline": True,
"default": "Upbeat pop rock with driving guitars and catchy hooks",
"tooltip": (
"Natural language description of the music style, mood, "
"instruments, etc. Fed to both the LM and the DiT text encoder."
),
},
),
},
"optional": {
# ---- Lyrics / vocal content ----
"lyrics": (
"STRING",
{
"multiline": True,
"default": "",
"tooltip": (
"Song lyrics. Leave empty for the LM to generate them. "
"Set to '[Instrumental]' (or enable the instrumental toggle) "
"for no vocals."
),
},
),
"instrumental": (
"BOOLEAN",
{
"default": False,
"tooltip": (
"Convenience toggle: when enabled and lyrics is empty, "
"sets lyrics to '[Instrumental]' so the DiT generates no vocals."
),
"label_on": "Instrumental",
"label_off": "Vocal",
},
),
# ---- Music metadata (LLM-filled when unset) ----
"vocal_language": (
cls.VOCAL_LANGUAGES,
{
"default": "",
"tooltip": (
"BCP-47 language code for lyrics (e.g. 'en', 'fr', 'ja'). "
"Leave empty for the LM to detect. "
"Set to 'unknown' for an explicit no-language signal."
),
},
),
"duration": (
"FLOAT",
{
"default": 0.0,
"min": 0.0,
"max": 600.0,
"step": 1.0,
"tooltip": (
"Target audio duration in seconds. "
"0 lets the LM decide (clamped to [1, 600] s after generation)."
),
},
),
"bpm": (
"INT",
{
"default": 0,
"min": 0,
"max": 300,
"tooltip": "Beats per minute (0 lets the LM decide)",
},
),
"keyscale": (
"STRING",
{
"default": "",
"tooltip": (
"Musical key and scale, e.g. 'C major' or 'F# minor'. "
"Leave empty for the LM to decide."
),
},
),
"timesignature": (
"STRING",
{
"default": "",
"tooltip": (
"Time signature numerator, e.g. '4' for 4/4, '3' for 3/4. "
"Leave empty for the LM to decide."
),
},
),
# ---- DiT flow-matching ----
"inference_steps": (
"INT",
{
"default": 8,
"min": 1,
"max": 200,
"tooltip": (
"Number of DiT denoising steps. "
"Turbo preset: 8. SFT preset: 50."
),
},
),
"guidance_scale": (
"FLOAT",
{
"default": 0.0,
"min": 0.0,
"max": 20.0,
"step": 0.1,
"tooltip": (
"CFG scale for the DiT. 0.0 is auto-resolved to 1.0 at runtime "
"(CFG disabled). Values > 1.0 on a turbo model are overridden to 1.0."
),
},
),
"shift": (
"FLOAT",
{
"default": 3.0,
"min": 0.0,
"max": 20.0,
"step": 0.1,
"tooltip": (
"Flow-matching schedule shift. "
"Turbo preset: 3.0. SFT preset: 1.0."
),
},
),
"seed": (
"INT",
{
"default": -1,
"min": -1,
"tooltip": "Random seed (-1 picks a random seed at runtime)",
},
),
# ---- LM sampling ----
"lm_temperature": (
"FLOAT",
{
"default": 0.85,
"min": 0.0,
"max": 2.0,
"step": 0.01,
"tooltip": (
"LM sampling temperature for both phase 1 (lyrics/metadata) "
"and phase 2 (audio codes). Lower = more deterministic."
),
},
),
"lm_cfg_scale": (
"FLOAT",
{
"default": 2.0,
"min": 0.0,
"max": 10.0,
"step": 0.1,
"tooltip": (
"LM classifier-free guidance scale. Active in phase 2 and in "
"phase 1 when lyrics are provided. 1.0 disables CFG."
),
},
),
"lm_top_p": (
"FLOAT",
{
"default": 0.9,
"min": 0.0,
"max": 1.0,
"step": 0.01,
"tooltip": "LM nucleus (top-p) sampling cutoff. 1.0 disables.",
},
),
"lm_top_k": (
"STRING",
{
"default": "0",
"tooltip": (
"LM top-k sampling. 0 disables hard top-k (top_p still applies). "
"Accepts integers. Leave empty to use the default (0)."
),
},
),
"lm_negative_prompt": (
"STRING",
{
"multiline": True,
"default": "",
"tooltip": (
"Negative caption for LM CFG in phase 2. "