-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathcdmf_pipeline_ace_step.py
More file actions
2404 lines (2180 loc) · 94.2 KB
/
cdmf_pipeline_ace_step.py
File metadata and controls
2404 lines (2180 loc) · 94.2 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
"""
ACE-Step: A Step Towards Music Generation Foundation Model
https://github.com/ace-step/ACE-Step
Apache 2.0 License
"""
import random
import time
import os
import re
import sys
# Store import errors for better diagnostics in frozen apps
_IMPORT_ERRORS = {}
# Basic imports that should always work (json, math are standard)
try:
import torch
except ImportError as e:
_IMPORT_ERRORS['torch'] = str(e)
# Create a minimal torch mock with no_grad context manager
class _NoGradContext:
"""Context manager fallback for torch.no_grad() when torch is not available."""
def __enter__(self):
return self
def __exit__(self, *args):
return False
def __call__(self, func):
"""Allow use as decorator."""
return func
class _TorchMock:
@staticmethod
def no_grad():
"""Fallback context manager when torch is not available."""
return _NoGradContext()
torch = _TorchMock()
try:
from loguru import logger
except ImportError as e:
_IMPORT_ERRORS['loguru'] = str(e)
logger = None
try:
from tqdm import tqdm
except ImportError as e:
_IMPORT_ERRORS['tqdm'] = str(e)
tqdm = None
import json
import math
try:
from cdmf_generation_job import GenerationCancelled
except ImportError:
GenerationCancelled = Exception # fallback if module not available
try:
from huggingface_hub import snapshot_download
except ImportError as e:
_IMPORT_ERRORS['huggingface_hub'] = str(e)
snapshot_download = None
# Try to import diffusers and transformers (should be bundled)
# Note: We're lenient about diffusers.loaders submodule issues (SD3LoraLoaderMixin, etc.)
# as those are patched by the shim in music_forge_ui.py before this module is imported
try:
from diffusers.pipelines.stable_diffusion_3.pipeline_stable_diffusion_3 import (
retrieve_timesteps,
)
from diffusers.utils.torch_utils import randn_tensor
from diffusers.utils.peft_utils import set_weights_and_activate_adapters
except ImportError as e:
error_msg = str(e)
# Check if this is a diffusers.loaders submodule issue that can be worked around
# The shim in music_forge_ui.py patches these mixins before imports happen
is_loaders_submodule_issue = (
'diffusers.loaders' in error_msg and
any(mixin in error_msg for mixin in [
'SD3LoraLoaderMixin', 'FromSingleFileMixin',
'SD3IPAdapterMixin', 'IPAdapterMixin'
])
)
if is_loaders_submodule_issue:
# This is a submodule issue that the shim handles - try individual imports
# as a fallback, but don't store as a fatal error
retrieve_timesteps = None
randn_tensor = None
set_weights_and_activate_adapters = None
try:
from diffusers.pipelines.stable_diffusion_3.pipeline_stable_diffusion_3 import (
retrieve_timesteps,
)
except ImportError:
pass
try:
from diffusers.utils.torch_utils import randn_tensor
except ImportError:
pass
try:
from diffusers.utils.peft_utils import set_weights_and_activate_adapters
except ImportError:
pass
# Don't store this as an error - _check_required_imports will filter it out
# if the individual imports also failed
else:
# Real import error, store it
_IMPORT_ERRORS['diffusers'] = error_msg
retrieve_timesteps = None
randn_tensor = None
set_weights_and_activate_adapters = None
try:
from transformers import UMT5EncoderModel, AutoTokenizer
except ImportError as e:
_IMPORT_ERRORS['transformers'] = str(e)
UMT5EncoderModel = None
AutoTokenizer = None
try:
import torchaudio
except ImportError as e:
_IMPORT_ERRORS['torchaudio'] = str(e)
torchaudio = None
# Import ACE-Step components with detailed error tracking
try:
from acestep.schedulers.scheduling_flow_match_euler_discrete import (
FlowMatchEulerDiscreteScheduler,
)
except ImportError as e:
_IMPORT_ERRORS['acestep.schedulers.euler'] = str(e)
FlowMatchEulerDiscreteScheduler = None
try:
from acestep.schedulers.scheduling_flow_match_heun_discrete import (
FlowMatchHeunDiscreteScheduler,
)
except ImportError as e:
_IMPORT_ERRORS['acestep.schedulers.heun'] = str(e)
FlowMatchHeunDiscreteScheduler = None
try:
from acestep.schedulers.scheduling_flow_match_pingpong import (
FlowMatchPingPongScheduler,
)
except ImportError as e:
_IMPORT_ERRORS['acestep.schedulers.pingpong'] = str(e)
FlowMatchPingPongScheduler = None
try:
from acestep.language_segmentation import LangSegment, language_filters
except ImportError as e:
_IMPORT_ERRORS['acestep.language_segmentation'] = str(e)
LangSegment = None
language_filters = None
try:
from acestep.music_dcae.music_dcae_pipeline import MusicDCAE
except ImportError as e:
_IMPORT_ERRORS['acestep.music_dcae'] = str(e)
MusicDCAE = None
try:
from acestep.models.ace_step_transformer import ACEStepTransformer2DModel
except ImportError as e:
_IMPORT_ERRORS['acestep.models.transformer'] = str(e)
ACEStepTransformer2DModel = None
try:
from acestep.models.lyrics_utils.lyric_tokenizer import VoiceBpeTokenizer
except ImportError as e:
_IMPORT_ERRORS['acestep.models.lyric_tokenizer'] = str(e)
VoiceBpeTokenizer = None
try:
from acestep.apg_guidance import (
apg_forward,
MomentumBuffer,
cfg_forward,
cfg_zero_star,
cfg_double_condition_forward,
)
except ImportError as e:
_IMPORT_ERRORS['acestep.apg_guidance'] = str(e)
apg_forward = None
MomentumBuffer = None
cfg_forward = None
cfg_zero_star = None
cfg_double_condition_forward = None
try:
from acestep.cpu_offload import cpu_offload
except ImportError as e:
_IMPORT_ERRORS['acestep.cpu_offload'] = str(e)
# Provide a no-op decorator fallback if cpu_offload import fails
def cpu_offload(model_name):
"""Fallback no-op decorator when acestep.cpu_offload is not available."""
def decorator(func):
return func
return decorator
# Configure CUDA backends if available (only if real torch is loaded)
if hasattr(torch, 'cuda') and hasattr(torch, 'backends'):
if torch.cuda.is_available():
torch.backends.cudnn.benchmark = False
torch.backends.cudnn.deterministic = True
torch.backends.cuda.matmul.allow_tf32 = True
torch.set_float32_matmul_precision("high")
os.environ["TOKENIZERS_PARALLELISM"] = "false"
SUPPORT_LANGUAGES = {
"en": 259,
"de": 260,
"fr": 262,
"es": 284,
"it": 285,
"pt": 286,
"pl": 294,
"tr": 295,
"ru": 267,
"cs": 293,
"nl": 297,
"ar": 5022,
"zh": 5023,
"ja": 5412,
"hu": 5753,
"ko": 6152,
"hi": 6680,
}
structure_pattern = re.compile(r"\[.*?\]")
def ensure_directory_exists(directory):
directory = str(directory)
if not os.path.exists(directory):
os.makedirs(directory)
REPO_ID = "ACE-Step/ACE-Step-v1-3.5B"
REPO_ID_QUANT = REPO_ID + "-q4-K-M" # ??? update this i guess
def _check_required_imports():
"""
Check if all required imports succeeded.
This is called at ACEStepPipeline initialization to provide detailed
error messages in case of import failures (especially in frozen apps).
Note: We're lenient about diffusers.loaders submodule issues, as those
can be patched by the shim in music_forge_ui.py (SD3LoraLoaderMixin, etc.)
Raises:
ImportError: If any required imports failed, with details about which ones.
"""
if not _IMPORT_ERRORS:
return # All imports succeeded
is_frozen = getattr(sys, 'frozen', False)
# Filter out diffusers.loaders submodule errors that can be worked around
# These are patched by the shim in music_forge_ui.py
filtered_errors = {}
for module_name, error_msg in _IMPORT_ERRORS.items():
# Skip diffusers.loaders submodule issues - these are handled by the shim
if module_name == 'diffusers' and 'diffusers.loaders' in error_msg:
if any(mixin in error_msg for mixin in ['SD3LoraLoaderMixin',
'FromSingleFileMixin',
'SD3IPAdapterMixin',
'IPAdapterMixin']):
# This is a submodule issue that the shim handles, skip it
continue
filtered_errors[module_name] = error_msg
# If all errors were filtered out, we're good
if not filtered_errors:
return
error_details = []
for module_name, error_msg in filtered_errors.items():
error_details.append(f" - {module_name}: {error_msg}")
if is_frozen:
error_message = (
"ACEStepPipeline cannot be initialized because some required modules "
"failed to import in the frozen app bundle.\n\n"
"This indicates the app was not built correctly or some dependencies "
"are missing from the bundle.\n\n"
"Failed imports:\n" + "\n".join(error_details) + "\n\n"
"Try downloading a fresh copy of AceForge from:\n"
" https://github.com/audiohacking/AceForge/releases\n\n"
"If the problem persists, this may be a build issue."
)
else:
error_message = (
"ACEStepPipeline cannot be initialized because some required modules "
"failed to import.\n\n"
"Failed imports:\n" + "\n".join(error_details) + "\n\n"
"Make sure ace-step is installed correctly:\n"
' pip install "git+https://github.com/ace-step/ACE-Step.git" --no-deps\n\n'
"And all dependencies are installed:\n"
" pip install -r requirements_ace_macos.txt"
)
raise ImportError(error_message)
def _refine_prompt_with_lm(
lm_checkpoint_path,
prompt,
lyrics,
use_cot_metas=True,
use_cot_caption=True,
use_cot_language=True,
lm_temperature=0.85,
lm_cfg_scale=2.0,
lm_top_k=0,
lm_top_p=0.9,
lm_negative_prompt="NO USER INPUT",
):
"""
Optionally refine prompt/lyrics using the bundled ACE-Step 5Hz LM (no external LLM).
Returns metadata dict or None if LM inference is not available.
"""
try:
# ACE-Step 1.5 primary layout
from acestep.llm_inference import LLMHandler
from acestep.inference import format_sample
except Exception:
try:
# Fallback layout used by some builds
from acestep.inference import LLMHandler, format_sample # type: ignore[attr-defined]
except Exception:
return None
try:
llm = LLMHandler()
device = "cuda" if os.environ.get("CUDA_VISIBLE_DEVICES") else "cpu"
lm_path = str(lm_checkpoint_path)
lm_parent = os.path.dirname(lm_path)
lm_name = os.path.basename(lm_path)
init_ok = False
init_attempts = [
{"checkpoint_dir": lm_parent, "lm_model_path": lm_name, "backend": "pytorch", "device": device},
{"checkpoint_dir": lm_parent, "lm_model_path": lm_name, "backend": "transformers", "device": device},
{"checkpoint_dir": lm_parent, "lm_model_path": lm_name, "backend": "hf", "device": device},
{"checkpoint_dir": lm_parent, "lm_model_path": lm_name, "device": device},
{"checkpoint_dir": lm_path, "device": device},
{"lm_model_path": lm_path, "device": device},
]
if device == "cuda":
init_attempts.append({"checkpoint_dir": lm_parent, "lm_model_path": lm_name, "backend": "vllm", "device": device})
for kwargs in init_attempts:
try:
llm.initialize(**kwargs)
init_ok = True
break
except Exception:
continue
if not init_ok:
return None
def _run_format():
return format_sample(
llm,
caption=prompt or "",
lyrics=lyrics or "",
temperature=lm_temperature,
top_k=lm_top_k if lm_top_k else None,
top_p=lm_top_p,
)
result = _run_format()
status_msg = str(getattr(result, "status_message", "") or "")
if "llm not initialized" in status_msg.lower():
retry_attempts = [
{"checkpoint_dir": lm_parent, "lm_model_path": lm_name, "backend": "pytorch", "device": device},
{"checkpoint_dir": lm_parent, "lm_model_path": lm_name, "backend": "transformers", "device": device},
{"checkpoint_dir": lm_parent, "lm_model_path": lm_name, "backend": "hf", "device": device},
]
for kwargs in retry_attempts:
try:
llm.initialize(**kwargs)
result = _run_format()
status_msg = str(getattr(result, "status_message", "") or "")
if "llm not initialized" not in status_msg.lower():
break
except Exception:
continue
if result and getattr(result, "caption", None) is not None:
new_caption = getattr(result, "caption", None) or prompt
new_lyrics = getattr(result, "lyrics", None) if hasattr(result, "lyrics") else lyrics
lm_duration = None
try:
if hasattr(result, "duration") and getattr(result, "duration") is not None:
lm_duration = float(getattr(result, "duration"))
elif hasattr(result, "cot_duration") and getattr(result, "cot_duration") is not None:
lm_duration = float(getattr(result, "cot_duration"))
except Exception:
lm_duration = None
return {
"caption": new_caption,
"lyrics": new_lyrics or lyrics,
"duration": lm_duration,
}
except Exception:
pass
return None
def _audio_duration_seconds(audio_path):
"""
Best-effort duration probe for local audio paths.
Returns duration in seconds or None when unavailable.
"""
if not audio_path:
return None
try:
from pydub import AudioSegment
seg = AudioSegment.from_file(str(audio_path))
sec = float(len(seg)) / 1000.0
return sec if sec > 0 else None
except Exception:
pass
try:
if torchaudio is not None:
wav, sr = torchaudio.load(str(audio_path))
if sr and getattr(wav, "shape", None) is not None and wav.shape[-1] > 0:
return float(wav.shape[-1]) / float(sr)
except Exception:
pass
return None
def _estimate_duration_from_lyrics(lyrics_text):
"""
Heuristic duration estimate from lyric content when LM metadata is unavailable.
Returns seconds or None.
"""
text = (lyrics_text or "").strip()
if not text:
return None
low = text.lower()
if low in ("[inst]", "[instrumental]", "instrumental"):
return None
lines = [ln.strip() for ln in text.splitlines()]
non_empty = [ln for ln in lines if ln]
if not non_empty:
return None
# Ignore section tags like [Verse], [Chorus], etc. for word counting.
section_pat = re.compile(r"^\s*\[[^\]]+\]\s*$")
lyric_lines = [ln for ln in non_empty if not section_pat.match(ln)]
if not lyric_lines:
return None
words = 0
for ln in lyric_lines:
words += len(re.findall(r"[A-Za-z0-9']+", ln))
# Two complementary estimates:
# 1) word-rate estimate (sung lyrics are often ~95-120 wpm; use ~0.58 s/word)
# 2) line-rate estimate (phrases + rests; ~4.3 s per lyric line)
word_est = words * 0.58
line_est = len(lyric_lines) * 4.3
# Take the larger estimate to reduce premature cutoffs.
est = max(word_est, line_est)
# Add a small arrangement buffer for intro/outro/transitions.
est += 12.0
# Keep in sane generation bounds.
est = max(30.0, min(360.0, est))
return float(est)
# class ACEStepPipeline(DiffusionPipeline):
class ACEStepPipeline:
def __init__(
self,
checkpoint_dir=None,
device_id=0,
dtype="bfloat16",
text_encoder_checkpoint_path=None,
persistent_storage_path=None,
torch_compile=False,
cpu_offload=False,
quantized=False,
overlapped_decode=False,
**kwargs,
):
# Check that all required imports succeeded before proceeding
_check_required_imports()
if not checkpoint_dir:
if persistent_storage_path is None:
checkpoint_dir = os.path.join(
os.path.expanduser("~"), ".cache/ace-step/checkpoints"
)
os.makedirs(checkpoint_dir, exist_ok=True)
else:
checkpoint_dir = os.path.join(persistent_storage_path, "checkpoints")
ensure_directory_exists(checkpoint_dir)
self.checkpoint_dir = checkpoint_dir
self.lora_path = "none"
self.lora_weight = 1
device = (
torch.device(f"cuda:{device_id}")
if torch.cuda.is_available()
else torch.device("cpu")
)
if device.type == "cpu" and torch.backends.mps.is_available():
device = torch.device("mps")
self.dtype = torch.bfloat16 if dtype == "bfloat16" else torch.float32
if device.type == "mps" and self.dtype == torch.bfloat16:
self.dtype = torch.float16
if device.type == "mps":
self.dtype = torch.float32
if 'ACE_PIPELINE_DTYPE' in os.environ and len(os.environ['ACE_PIPELINE_DTYPE']):
self.dtype = getattr(torch, os.environ['ACE_PIPELINE_DTYPE'])
self.device = device
self.loaded = False
self.torch_compile = torch_compile
self.cpu_offload = cpu_offload
self.quantized = quantized
self.overlapped_decode = overlapped_decode
def cleanup_memory(self):
"""Clean up GPU and CPU memory to prevent VRAM overflow during multiple generations."""
# Clear device cache based on device type
if torch.cuda.is_available() and self.device.type == "cuda":
torch.cuda.empty_cache()
# Log memory usage if in verbose mode
allocated = torch.cuda.memory_allocated() / (1024 ** 3)
reserved = torch.cuda.memory_reserved() / (1024 ** 3)
logger.info(f"GPU Memory: {allocated:.2f}GB allocated, {reserved:.2f}GB reserved")
elif hasattr(torch.backends, "mps") and torch.backends.mps.is_available() and self.device.type == "mps":
# MPS (Metal Performance Shaders) cache clearing
try:
torch.mps.empty_cache()
logger.info("MPS Memory cache cleared")
except Exception as e:
logger.debug(f"MPS cache clear not available: {e}")
# Collect Python garbage
import gc
gc.collect()
def get_checkpoint_path(self, checkpoint_dir, repo):
checkpoint_dir_models = None
if checkpoint_dir is not None:
required_dirs = ["music_dcae_f8c8", "music_vocoder", "ace_step_transformer", "umt5-base"]
all_dirs_exist = True
for dir_name in required_dirs:
dir_path = os.path.join(checkpoint_dir, dir_name)
if not os.path.exists(dir_path):
all_dirs_exist = False
break
if all_dirs_exist:
logger.info(f"Load models from: {checkpoint_dir}")
checkpoint_dir_models = checkpoint_dir
if checkpoint_dir_models is None:
if checkpoint_dir is None:
logger.info(f"Download models from Hugging Face: {repo}")
checkpoint_dir_models = snapshot_download(repo)
else:
logger.info(f"Download models from Hugging Face: {repo}, cache to: {checkpoint_dir}")
checkpoint_dir_models = snapshot_download(repo, cache_dir=checkpoint_dir)
return checkpoint_dir_models
def load_checkpoint(self, checkpoint_dir=None, export_quantized_weights=False):
checkpoint_dir = self.get_checkpoint_path(checkpoint_dir, REPO_ID)
dcae_checkpoint_path = os.path.join(checkpoint_dir, "music_dcae_f8c8")
vocoder_checkpoint_path = os.path.join(checkpoint_dir, "music_vocoder")
ace_step_checkpoint_path = os.path.join(checkpoint_dir, "ace_step_transformer")
text_encoder_checkpoint_path = os.path.join(checkpoint_dir, "umt5-base")
self.ace_step_transformer = ACEStepTransformer2DModel.from_pretrained(
ace_step_checkpoint_path, torch_dtype=self.dtype
)
# self.ace_step_transformer.to(self.device).eval().to(self.dtype)
if self.cpu_offload:
self.ace_step_transformer = (
self.ace_step_transformer.to("cpu").eval().to(self.dtype)
)
else:
self.ace_step_transformer = (
self.ace_step_transformer.to(self.device).eval().to(self.dtype)
)
if self.torch_compile:
self.ace_step_transformer = torch.compile(self.ace_step_transformer)
self.music_dcae = MusicDCAE(
dcae_checkpoint_path=dcae_checkpoint_path,
vocoder_checkpoint_path=vocoder_checkpoint_path,
)
# self.music_dcae.to(self.device).eval().to(self.dtype)
if self.cpu_offload: # might be redundant
self.music_dcae = self.music_dcae.to("cpu").eval().to(self.dtype)
else:
self.music_dcae = self.music_dcae.to(self.device).eval().to(self.dtype)
if self.torch_compile:
self.music_dcae = torch.compile(self.music_dcae)
# Initialize LangSegment with error handling for frozen app compatibility
# LangSegment uses py3langid which requires lzma for loading pickled models
try:
# Pre-import lzma to ensure it's available (helps with PyInstaller bundling)
try:
import lzma
import _lzma
# Quick test to ensure lzma is functional
test_compressed = lzma.compress(b"test")
lzma.decompress(test_compressed)
except Exception as lzma_err:
logger.warning(
f"lzma module test failed before LangSegment init: {lzma_err}. "
"LangSegment initialization may fail."
)
lang_segment = LangSegment()
lang_segment.setfilters(language_filters.default)
self.lang_segment = lang_segment
except Exception as lang_err:
error_msg = str(lang_err)
# Check if it's an lzma-related error
if 'lzma' in error_msg.lower() or '_lzma' in error_msg.lower():
logger.error(
f"Failed to initialize LangSegment due to lzma error: {error_msg}\n"
"This is likely a PyInstaller bundling issue. The _lzma C extension "
"may not be properly included in the frozen app bundle.\n"
"Language detection will be disabled."
)
else:
logger.warning(
f"Failed to initialize LangSegment: {error_msg}. "
"Language detection will be disabled."
)
# Create a dummy lang_segment that always returns 'en'
class DummyLangSegment:
def getTexts(self, text):
return []
def getCounts(self):
return [('en', 1)]
self.lang_segment = DummyLangSegment()
# Initialize VoiceBpeTokenizer with error handling for frozen app compatibility
try:
if VoiceBpeTokenizer is None:
raise RuntimeError("VoiceBpeTokenizer could not be imported")
self.lyric_tokenizer = VoiceBpeTokenizer()
except Exception as tokenizer_err:
error_msg = str(tokenizer_err)
logger.error(
f"Failed to initialize VoiceBpeTokenizer: {error_msg}\n"
"This is likely a PyInstaller bundling issue. The tokenizers library "
"or its dependencies may not be properly included in the frozen app bundle.\n"
"Generation will fail without the lyric tokenizer."
)
# Re-raise the error since we can't proceed without the tokenizer
raise RuntimeError(
f"VoiceBpeTokenizer initialization failed: {error_msg}\n"
"This is a critical component required for generation. "
"Please check the build logs and ensure all dependencies are bundled."
) from tokenizer_err
text_encoder_model = UMT5EncoderModel.from_pretrained(
text_encoder_checkpoint_path, torch_dtype=self.dtype
).eval()
# text_encoder_model = text_encoder_model.to(self.device).to(self.dtype)
if self.cpu_offload:
text_encoder_model = text_encoder_model.to("cpu").eval().to(self.dtype)
else:
text_encoder_model = text_encoder_model.to(self.device).eval().to(self.dtype)
text_encoder_model.requires_grad_(False)
self.text_encoder_model = text_encoder_model
if self.torch_compile:
self.text_encoder_model = torch.compile(self.text_encoder_model)
self.text_tokenizer = AutoTokenizer.from_pretrained(
text_encoder_checkpoint_path
)
self.loaded = True
# compile
if self.torch_compile:
if export_quantized_weights:
from torch.ao.quantization import (
quantize_,
Int4WeightOnlyConfig,
)
group_size = 128
use_hqq = True
quantize_(
self.ace_step_transformer,
Int4WeightOnlyConfig(group_size=group_size, use_hqq=use_hqq),
)
quantize_(
self.text_encoder_model,
Int4WeightOnlyConfig(group_size=group_size, use_hqq=use_hqq),
)
# save quantized weights
torch.save(
self.ace_step_transformer.state_dict(),
os.path.join(
ace_step_checkpoint_path, "diffusion_pytorch_model_int4wo.bin"
),
)
print(
"Quantized Weights Saved to: ",
os.path.join(
ace_step_checkpoint_path, "diffusion_pytorch_model_int4wo.bin"
),
)
torch.save(
self.text_encoder_model.state_dict(),
os.path.join(text_encoder_checkpoint_path, "pytorch_model_int4wo.bin"),
)
print(
"Quantized Weights Saved to: ",
os.path.join(text_encoder_checkpoint_path, "pytorch_model_int4wo.bin"),
)
def load_quantized_checkpoint(self, checkpoint_dir=None):
checkpoint_dir = self.get_checkpoint_path(checkpoint_dir, REPO_ID_QUANT)
dcae_checkpoint_path = os.path.join(checkpoint_dir, "music_dcae_f8c8")
vocoder_checkpoint_path = os.path.join(checkpoint_dir, "music_vocoder")
ace_step_checkpoint_path = os.path.join(checkpoint_dir, "ace_step_transformer")
text_encoder_checkpoint_path = os.path.join(checkpoint_dir, "umt5-base")
self.music_dcae = MusicDCAE(
dcae_checkpoint_path=dcae_checkpoint_path,
vocoder_checkpoint_path=vocoder_checkpoint_path,
)
if self.cpu_offload:
self.music_dcae.eval().to(self.dtype).to(self.device)
else:
self.music_dcae.eval().to(self.dtype).to('cpu')
self.music_dcae = torch.compile(self.music_dcae)
self.ace_step_transformer = ACEStepTransformer2DModel.from_pretrained(ace_step_checkpoint_path)
self.ace_step_transformer.eval().to(self.dtype).to('cpu')
self.ace_step_transformer = torch.compile(self.ace_step_transformer)
self.ace_step_transformer.load_state_dict(
torch.load(
os.path.join(ace_step_checkpoint_path, "diffusion_pytorch_model_int4wo.bin"),
map_location=self.device,
),assign=True
)
self.ace_step_transformer.torchao_quantized = True
self.text_encoder_model = UMT5EncoderModel.from_pretrained(text_encoder_checkpoint_path)
self.text_encoder_model.eval().to(self.dtype).to('cpu')
self.text_encoder_model = torch.compile(self.text_encoder_model)
self.text_encoder_model.load_state_dict(
torch.load(
os.path.join(text_encoder_checkpoint_path, "pytorch_model_int4wo.bin"),
map_location=self.device,
), assign=True
)
self.text_encoder_model.torchao_quantized = True
self.text_tokenizer = AutoTokenizer.from_pretrained(
text_encoder_checkpoint_path
)
# Initialize LangSegment with error handling (same as in load_checkpoint)
try:
# Pre-import lzma to ensure it's available
try:
import lzma
import _lzma
test_compressed = lzma.compress(b"test")
lzma.decompress(test_compressed)
except Exception as lzma_err:
logger.warning(
f"lzma module test failed before LangSegment init: {lzma_err}. "
"LangSegment initialization may fail."
)
lang_segment = LangSegment()
lang_segment.setfilters(language_filters.default)
self.lang_segment = lang_segment
except Exception as lang_err:
error_msg = str(lang_err)
if 'lzma' in error_msg.lower() or '_lzma' in error_msg.lower():
logger.error(
f"Failed to initialize LangSegment due to lzma error: {error_msg}\n"
"This is likely a PyInstaller bundling issue. The _lzma C extension "
"may not be properly included in the frozen app bundle.\n"
"Language detection will be disabled."
)
else:
logger.warning(
f"Failed to initialize LangSegment: {error_msg}. "
"Language detection will be disabled."
)
# Create a dummy lang_segment that always returns 'en'
class DummyLangSegment:
def getTexts(self, text):
return []
def getCounts(self):
return [('en', 1)]
self.lang_segment = DummyLangSegment()
# Initialize VoiceBpeTokenizer with error handling (same as in load_checkpoint)
try:
if VoiceBpeTokenizer is None:
raise RuntimeError("VoiceBpeTokenizer could not be imported")
self.lyric_tokenizer = VoiceBpeTokenizer()
except Exception as tokenizer_err:
error_msg = str(tokenizer_err)
logger.error(
f"Failed to initialize VoiceBpeTokenizer: {error_msg}\n"
"This is likely a PyInstaller bundling issue. The tokenizers library "
"or its dependencies may not be properly included in the frozen app bundle.\n"
"Generation will fail without the lyric tokenizer."
)
# Re-raise the error since we can't proceed without the tokenizer
raise RuntimeError(
f"VoiceBpeTokenizer initialization failed: {error_msg}\n"
"This is a critical component required for generation. "
"Please check the build logs and ensure all dependencies are bundled."
) from tokenizer_err
self.loaded = True
@cpu_offload("text_encoder_model")
def get_text_embeddings(self, texts, text_max_length=256):
inputs = self.text_tokenizer(
texts,
return_tensors="pt",
padding=True,
truncation=True,
max_length=text_max_length,
)
inputs = {key: value.to(self.device) for key, value in inputs.items()}
if self.text_encoder_model.device != self.device:
self.text_encoder_model.to(self.device)
with torch.no_grad():
outputs = self.text_encoder_model(**inputs)
last_hidden_states = outputs.last_hidden_state
attention_mask = inputs["attention_mask"]
return last_hidden_states, attention_mask
@cpu_offload("text_encoder_model")
def get_text_embeddings_null(
self, texts, text_max_length=256, tau=0.01, l_min=8, l_max=10
):
inputs = self.text_tokenizer(
texts,
return_tensors="pt",
padding=True,
truncation=True,
max_length=text_max_length,
)
inputs = {key: value.to(self.device) for key, value in inputs.items()}
if self.text_encoder_model.device != self.device:
self.text_encoder_model.to(self.device)
def forward_with_temperature(inputs, tau=0.01, l_min=8, l_max=10):
handlers = []
def hook(module, input, output):
output[:] *= tau
return output
for i in range(l_min, l_max):
handler = (
self.text_encoder_model.encoder.block[i]
.layer[0]
.SelfAttention.q.register_forward_hook(hook)
)
handlers.append(handler)
with torch.no_grad():
outputs = self.text_encoder_model(**inputs)
last_hidden_states = outputs.last_hidden_state
for hook in handlers:
hook.remove()
return last_hidden_states
last_hidden_states = forward_with_temperature(inputs, tau, l_min, l_max)
return last_hidden_states
def set_seeds(self, batch_size, manual_seeds=None):
processed_input_seeds = None
if manual_seeds is not None:
if isinstance(manual_seeds, str):
if "," in manual_seeds:
processed_input_seeds = list(map(int, manual_seeds.split(",")))
elif manual_seeds.isdigit():
processed_input_seeds = int(manual_seeds)
elif isinstance(manual_seeds, list) and all(
isinstance(s, int) for s in manual_seeds
):
if len(manual_seeds) > 0:
processed_input_seeds = list(manual_seeds)
elif isinstance(manual_seeds, int):
processed_input_seeds = manual_seeds
random_generators = [
torch.Generator(device=self.device) for _ in range(batch_size)
]
actual_seeds = []
for i in range(batch_size):
current_seed_for_generator = None
if processed_input_seeds is None:
current_seed_for_generator = torch.randint(0, 2**32, (1,)).item()
elif isinstance(processed_input_seeds, int):
current_seed_for_generator = processed_input_seeds
elif isinstance(processed_input_seeds, list):
if i < len(processed_input_seeds):
current_seed_for_generator = processed_input_seeds[i]
else:
current_seed_for_generator = processed_input_seeds[-1]
if current_seed_for_generator is None:
current_seed_for_generator = torch.randint(0, 2**32, (1,)).item()
random_generators[i].manual_seed(current_seed_for_generator)
actual_seeds.append(current_seed_for_generator)
return random_generators, actual_seeds
def get_lang(self, text):
language = "en"
try:
_ = self.lang_segment.getTexts(text)
langCounts = self.lang_segment.getCounts()
language = langCounts[0][0]
if len(langCounts) > 1 and language == "en":
language = langCounts[1][0]
except Exception as err:
language = "en"
return language
def tokenize_lyrics(self, lyrics, debug=False, vocal_language=None):
"""
Tokenize lyrics. When vocal_language is set (e.g. "en", "zh"), use it for all
lines instead of auto-detection, so user language choice is respected.
"""
lines = lyrics.split("\n")
lyric_token_idx = [261]
for line in lines:
line = line.strip()
if not line:
lyric_token_idx += [2]
continue
if vocal_language and vocal_language in SUPPORT_LANGUAGES:
lang = vocal_language
else:
lang = self.get_lang(line)
if lang not in SUPPORT_LANGUAGES:
lang = "en"
if "zh" in lang:
lang = "zh"
if "spa" in lang:
lang = "es"
try:
if structure_pattern.match(line):
token_idx = self.lyric_tokenizer.encode(line, "en")
else:
token_idx = self.lyric_tokenizer.encode(line, lang)
if debug:
toks = self.lyric_tokenizer.batch_decode(
[[tok_id] for tok_id in token_idx]
)
logger.info(f"debbug {line} --> {lang} --> {toks}")
lyric_token_idx = lyric_token_idx + token_idx + [2]
except Exception as e:
print("tokenize error", e, "for line", line, "major_language", lang)
return lyric_token_idx
@cpu_offload("ace_step_transformer")
def calc_v(
self,
zt_src,
zt_tar,
t,
encoder_text_hidden_states,
text_attention_mask,
target_encoder_text_hidden_states,
target_text_attention_mask,
speaker_embds,