KingNish commited on
Commit
15059e3
·
verified ·
1 Parent(s): fa7e403

By deepseek prev was stable

Browse files
Files changed (1) hide show
  1. app.py +215 -156
app.py CHANGED
@@ -1,11 +1,11 @@
1
  import gradio as gr
2
  import subprocess
3
- import os
4
  import shutil
5
  import tempfile
6
  import spaces
7
  import torch
8
- import os
9
  import sys
10
 
11
  print("Installing flash-attn...")
@@ -16,7 +16,7 @@ subprocess.run(
16
  shell=True,
17
  )
18
 
19
- from huggingface_hub import snapshot_download
20
 
21
  # Create xcodec_mini_infer folder
22
  folder_path = './xcodec_mini_infer'
@@ -29,8 +29,8 @@ else:
29
  print(f"Folder already exists at: {folder_path}")
30
 
31
  snapshot_download(
32
- repo_id = "m-a-p/xcodec_mini_infer",
33
- local_dir = "./xcodec_mini_infer"
34
  )
35
 
36
  # Change to the "inference" directory
@@ -69,11 +69,12 @@ from models.soundstream_hubert_new import SoundStream
69
  from vocoder import build_codec_model, process_audio
70
  from post_process_audio import replace_low_freq_with_energy_matched
71
  import re
 
72
 
73
  def empty_output_folder(output_dir):
74
  # List all files in the output directory
75
  files = os.listdir(output_dir)
76
-
77
  # Iterate over the files and remove them
78
  for file in files:
79
  file_path = os.path.join(output_dir, file)
@@ -87,37 +88,27 @@ def empty_output_folder(output_dir):
87
  except Exception as e:
88
  print(f"Error deleting file {file_path}: {e}")
89
 
90
- # Function to create a temporary file with string content
91
- def create_temp_file(content, prefix, suffix=".txt"):
92
- temp_file = tempfile.NamedTemporaryFile(delete=False, mode="w", prefix=prefix, suffix=suffix)
93
- # Ensure content ends with newline and normalize line endings
94
- content = content.strip() + "\n\n" # Add extra newline at end
95
- content = content.replace("\r\n", "\n").replace("\r", "\n")
96
- temp_file.write(content)
97
- temp_file.close()
98
-
99
- # Debug: Print file contents
100
- print(f"\nContent written to {prefix}{suffix}:")
101
- print(content)
102
- print("---")
103
-
104
- return temp_file.name
105
-
106
  device = "cuda:0"
107
 
 
108
  model = AutoModelForCausalLM.from_pretrained(
109
- "m-a-p/YuE-s1-7B-anneal-en-cot",
110
  torch_dtype=torch.float16,
111
- attn_implementation="flash_attention_2", # To enable flashattn, you have to install flash-attn
112
- )
113
  model.to(device)
114
  model.eval()
115
 
116
- basic_model_config='./xcodec_mini_infer/final_ckpt/config.yaml'
117
- resume_path='./xcodec_mini_infer/final_ckpt/ckpt_00360000.pth'
118
- config_path='./xcodec_mini_infer/decoders/config.yaml'
119
- vocal_decoder_path='./xcodec_mini_infer/decoders/decoder_131000.pth'
120
- inst_decoder_path='./xcodec_mini_infer/decoders/decoder_151000.pth'
 
 
 
 
 
121
 
122
  mmtokenizer = _MMSentencePieceTokenizer("./mm_tokenizer_v0.2_hf/tokenizer.model")
123
 
@@ -129,26 +120,53 @@ codec_model.load_state_dict(parameter_dict['codec_model'])
129
  codec_model.to(device)
130
  codec_model.eval()
131
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
132
  def generate_music(
133
- max_new_tokens=5,
134
- run_n_segments=2,
135
- genre_txt=None,
136
- lyrics_txt=None,
137
- use_audio_prompt=False,
138
- audio_prompt_path="",
139
- prompt_start_time=0.0,
140
- prompt_end_time=30.0,
141
- output_dir="./output",
142
- cuda_idx=0,
143
- rescale=False,
 
 
 
144
  ):
145
  if use_audio_prompt and not audio_prompt_path:
146
- raise FileNotFoundError("Please offer audio prompt filepath using '--audio_prompt_path', when you enable 'use_audio_prompt'!")
147
- cuda_idx = cuda_idx
148
- max_new_tokens = max_new_tokens*100
149
  stage1_output_dir = os.path.join(output_dir, f"stage1")
150
  os.makedirs(stage1_output_dir, exist_ok=True)
151
-
152
  class BlockTokenRangeProcessor(LogitsProcessor):
153
  def __init__(self, start_id, end_id):
154
  self.blocked_token_ids = list(range(start_id, end_id))
@@ -177,109 +195,158 @@ def generate_music(
177
  stage1_output_set = []
178
 
179
  genres = genre_txt.strip()
180
- lyrics = split_lyrics(lyrics_txt+"\n")
181
  # intruction
182
  full_lyrics = "\n".join(lyrics)
183
  prompt_texts = [f"Generate music from the given lyrics segment by segment.\n[Genre] {genres}\n{full_lyrics}"]
184
  prompt_texts += lyrics
185
 
186
-
187
  random_id = uuid.uuid4()
188
  output_seq = None
189
  # Here is suggested decoding config
190
  top_p = 0.93
191
  temperature = 1.0
192
- repetition_penalty = 1.2
193
  # special tokens
194
  start_of_segment = mmtokenizer.tokenize('[start_of_segment]')
195
  end_of_segment = mmtokenizer.tokenize('[end_of_segment]')
196
 
197
  raw_output = None
 
198
 
199
  # Format text prompt
200
- run_n_segments = min(run_n_segments+1, len(lyrics))
201
 
202
  print(list(enumerate(tqdm(prompt_texts[:run_n_segments]))))
203
 
204
- for i, p in enumerate(tqdm(prompt_texts[:run_n_segments])):
205
- section_text = p.replace('[start_of_segment]', '').replace('[end_of_segment]', '')
206
- guidance_scale = 1.5 if i <=1 else 1.2
207
- if i==0:
208
- continue
209
- if i==1:
210
- if use_audio_prompt:
211
- audio_prompt = load_audio_mono(audio_prompt_path)
212
- audio_prompt.unsqueeze_(0)
213
- with torch.no_grad():
214
- raw_codes = codec_model.encode(audio_prompt.to(device), target_bw=0.5)
215
- raw_codes = raw_codes.transpose(0, 1)
216
- raw_codes = raw_codes.cpu().numpy().astype(np.int16)
217
- # Format audio prompt
218
- code_ids = codectool.npy2ids(raw_codes[0])
219
- audio_prompt_codec = code_ids[int(prompt_start_time *50): int(prompt_end_time *50)] # 50 is tps of xcodec
220
- audio_prompt_codec_ids = [mmtokenizer.soa] + codectool.sep_ids + audio_prompt_codec + [mmtokenizer.eoa]
221
- sentence_ids = mmtokenizer.tokenize("[start_of_reference]") + audio_prompt_codec_ids + mmtokenizer.tokenize("[end_of_reference]")
222
- head_id = mmtokenizer.tokenize(prompt_texts[0]) + sentence_ids
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
223
  else:
224
- head_id = mmtokenizer.tokenize(prompt_texts[0])
225
- prompt_ids = head_id + start_of_segment + mmtokenizer.tokenize(section_text) + [mmtokenizer.soa] + codectool.sep_ids
226
- else:
227
- prompt_ids = end_of_segment + start_of_segment + mmtokenizer.tokenize(section_text) + [mmtokenizer.soa] + codectool.sep_ids
228
-
229
- prompt_ids = torch.as_tensor(prompt_ids).unsqueeze(0).to(device)
230
- input_ids = torch.cat([raw_output, prompt_ids], dim=1) if i > 1 else prompt_ids
231
- # Use window slicing in case output sequence exceeds the context of model
232
- max_context = 16384-max_new_tokens-1
233
- if input_ids.shape[-1] > max_context:
234
- print(f'Section {i}: output length {input_ids.shape[-1]} exceeding context length {max_context}, now using the last {max_context} tokens.')
235
- input_ids = input_ids[:, -(max_context):]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
236
  with torch.no_grad():
237
- output_seq = model.generate(
238
- input_ids=input_ids,
239
- max_new_tokens=max_new_tokens,
240
- min_new_tokens=100,
241
- do_sample=True,
242
  top_p=top_p,
243
- temperature=temperature,
244
- repetition_penalty=repetition_penalty,
245
  eos_token_id=mmtokenizer.eoa,
246
  pad_token_id=mmtokenizer.eoa,
247
- logits_processor=LogitsProcessorList([BlockTokenRangeProcessor(0, 32002), BlockTokenRangeProcessor(32016, 32016)]),
 
248
  guidance_scale=guidance_scale,
249
  use_cache=True,
250
- )
 
 
 
 
 
251
  if output_seq[0][-1].item() != mmtokenizer.eoa:
252
  tensor_eoa = torch.as_tensor([[mmtokenizer.eoa]]).to(model.device)
253
  output_seq = torch.cat((output_seq, tensor_eoa), dim=1)
254
- if i > 1:
255
- raw_output = torch.cat([raw_output, prompt_ids, output_seq[:, input_ids.shape[-1]:]], dim=1)
256
- else:
257
- raw_output = output_seq
258
- print(len(raw_output))
 
 
 
 
259
 
260
  # save raw output and check sanity
261
  ids = raw_output[0].cpu().numpy()
262
  soa_idx = np.where(ids == mmtokenizer.soa)[0].tolist()
263
  eoa_idx = np.where(ids == mmtokenizer.eoa)[0].tolist()
264
- if len(soa_idx)!=len(eoa_idx):
265
  raise ValueError(f'invalid pairs of soa and eoa, Num of soa: {len(soa_idx)}, Num of eoa: {len(eoa_idx)}')
266
 
267
  vocals = []
268
  instrumentals = []
269
  range_begin = 1 if use_audio_prompt else 0
270
  for i in range(range_begin, len(soa_idx)):
271
- codec_ids = ids[soa_idx[i]+1:eoa_idx[i]]
272
  if codec_ids[0] == 32016:
273
  codec_ids = codec_ids[1:]
274
  codec_ids = codec_ids[:2 * (codec_ids.shape[0] // 2)]
275
- vocals_ids = codectool.ids2npy(rearrange(codec_ids,"(n b) -> b n", b=2)[0])
276
  vocals.append(vocals_ids)
277
- instrumentals_ids = codectool.ids2npy(rearrange(codec_ids,"(n b) -> b n", b=2)[1])
278
  instrumentals.append(instrumentals_ids)
279
  vocals = np.concatenate(vocals, axis=1)
280
  instrumentals = np.concatenate(instrumentals, axis=1)
281
- vocal_save_path = os.path.join(stage1_output_dir, f"cot_{genres.replace(' ', '-')}_tp{top_p}_T{temperature}_rp{repetition_penalty}_maxtk{max_new_tokens}_vocal_{random_id}".replace('.', '@')+'.npy')
282
- inst_save_path = os.path.join(stage1_output_dir, f"cot_{genres.replace(' ', '-')}_tp{top_p}_T{temperature}_rp{repetition_penalty}_maxtk{max_new_tokens}_instrumental_{random_id}".replace('.', '@')+'.npy')
 
 
 
 
283
  np.save(vocal_save_path, vocals)
284
  np.save(inst_save_path, instrumentals)
285
  stage1_output_set.append(vocal_save_path)
@@ -296,6 +363,7 @@ def generate_music(
296
  max_val = wav.abs().max()
297
  wav = wav * min(limit / max_val, 1) if rescale else wav.clamp(-limit, limit)
298
  torchaudio.save(str(path), wav, sample_rate=sample_rate, encoding='PCM_S', bits_per_sample=16)
 
299
  # reconstruct tracks
300
  recons_output_dir = os.path.join(output_dir, "recons")
301
  recons_mix_dir = os.path.join(recons_output_dir, 'mix')
@@ -303,9 +371,11 @@ def generate_music(
303
  tracks = []
304
  for npy in stage1_output_set:
305
  codec_result = np.load(npy)
306
- decodec_rlt=[]
307
  with torch.no_grad():
308
- decoded_waveform = codec_model.decode(torch.as_tensor(codec_result.astype(np.int16), dtype=torch.long).unsqueeze(0).permute(1, 0, 2).to(device))
 
 
309
  decoded_waveform = decoded_waveform.cpu().squeeze(0)
310
  decodec_rlt.append(torch.as_tensor(decoded_waveform))
311
  decodec_rlt = torch.cat(decodec_rlt, dim=-1)
@@ -316,7 +386,7 @@ def generate_music(
316
  for inst_path in tracks:
317
  try:
318
  if (inst_path.endswith('.wav') or inst_path.endswith('.mp3')) \
319
- and 'instrumental' in inst_path:
320
  # find pair
321
  vocal_path = inst_path.replace('instrumental', 'vocal')
322
  if not os.path.exists(vocal_path):
@@ -329,7 +399,6 @@ def generate_music(
329
  sf.write(recons_mix, mix_stem, sr)
330
  except Exception as e:
331
  print(e)
332
-
333
 
334
  # vocoder to upsample audios
335
  vocal_decoder, inst_decoder = build_codec_model(config_path, vocal_decoder_path, inst_decoder_path)
@@ -338,53 +407,41 @@ def generate_music(
338
  vocoder_mix_dir = os.path.join(vocoder_output_dir, 'mix')
339
  os.makedirs(vocoder_mix_dir, exist_ok=True)
340
  os.makedirs(vocoder_stems_dir, exist_ok=True)
341
- instrumental_output = None
342
- vocal_output = None
343
- for npy in stage1_output_set:
344
- if 'instrumental' in npy:
345
- # Process instrumental
346
- instrumental_output = process_audio(
347
- npy,
348
- os.path.join(vocoder_stems_dir, 'instrumental.mp3'),
349
- rescale,
350
- argparse.Namespace(**locals()), # Convert local variables to argparse.Namespace
351
- inst_decoder,
352
- codec_model
353
- )
354
- else:
355
- # Process vocal
356
- vocal_output = process_audio(
357
- npy,
358
- os.path.join(vocoder_stems_dir, 'vocal.mp3'),
359
- rescale,
360
- argparse.Namespace(**locals()), # Convert local variables to argparse.Namespace
361
- vocal_decoder,
362
- codec_model
363
- )
364
- # mix tracks
365
- try:
366
- mix_output = instrumental_output + vocal_output
367
- vocoder_mix = os.path.join(vocoder_mix_dir, os.path.basename(recons_mix))
368
- save_audio(mix_output, vocoder_mix, 44100, rescale)
369
- print(f"Created mix: {vocoder_mix}")
370
- except RuntimeError as e:
371
- print(e)
372
- print(f"mix {vocoder_mix} failed! inst: {instrumental_output.shape}, vocal: {vocal_output.shape}")
373
 
374
  # Post process
375
  replace_low_freq_with_energy_matched(
376
- a_file=recons_mix, # 16kHz
377
- b_file=vocoder_mix, # 48kHz
378
  c_file=os.path.join(output_dir, os.path.basename(recons_mix)),
379
  cutoff_freq=5500.0
380
  )
381
  print("All process Done")
382
  return recons_mix
383
 
384
-
385
  @spaces.GPU(duration=120)
386
- def infer(genre_txt_content, lyrics_txt_content, num_segments=2, max_new_tokens=10):
387
-
388
  # Ensure the output folder exists
389
  output_dir = "./output"
390
  os.makedirs(output_dir, exist_ok=True)
@@ -394,15 +451,16 @@ def infer(genre_txt_content, lyrics_txt_content, num_segments=2, max_new_tokens=
394
 
395
  # Execute the command
396
  try:
397
- music = generate_music(genre_txt=genre_txt_content, lyrics_txt=lyrics_txt_content, run_n_segments=num_segments, output_dir=output_dir, cuda_idx=0, max_new_tokens=max_new_tokens)
 
398
  return music
399
  except Exception as e:
400
  gr.Warning("An Error Occured: " + str(e))
401
- return none
402
  finally:
403
  print("Temporary files deleted.")
404
 
405
- # Gradio
406
 
407
  with gr.Blocks() as demo:
408
  with gr.Column():
@@ -424,15 +482,16 @@ with gr.Blocks() as demo:
424
  with gr.Column():
425
  genre_txt = gr.Textbox(label="Genre")
426
  lyrics_txt = gr.Textbox(label="Lyrics")
427
-
428
  with gr.Column():
429
  num_segments = gr.Number(label="Number of Segments", value=2, interactive=True)
430
- max_new_tokens = gr.Slider(label="Duration of song", minimum=1, maximum=30, step=1, value=5, interactive=True)
 
431
  submit_btn = gr.Button("Submit")
432
  music_out = gr.Audio(label="Audio Result")
433
 
434
  gr.Examples(
435
- examples = [
436
  [
437
  "female blues airy vocal bright vocal piano sad romantic guitar jazz",
438
  """[verse]
@@ -467,17 +526,17 @@ Through the highs and lows, I'mma keep it real
467
  Living out my dreams with this mic and a deal
468
  """
469
  ]
470
- ],
471
- inputs = [genre_txt, lyrics_txt],
472
- outputs = [music_out],
473
- cache_examples = True,
474
  cache_mode="eager",
475
  fn=infer
476
  )
477
-
478
  submit_btn.click(
479
- fn = infer,
480
- inputs = [genre_txt, lyrics_txt, num_segments, max_new_tokens],
481
- outputs = [music_out]
482
  )
483
- demo.queue().launch(show_error=True)
 
1
  import gradio as gr
2
  import subprocess
3
+ import os
4
  import shutil
5
  import tempfile
6
  import spaces
7
  import torch
8
+ import torch.nn.functional as F
9
  import sys
10
 
11
  print("Installing flash-attn...")
 
16
  shell=True,
17
  )
18
 
19
+ from huggingface_hub import snapshot_download
20
 
21
  # Create xcodec_mini_infer folder
22
  folder_path = './xcodec_mini_infer'
 
29
  print(f"Folder already exists at: {folder_path}")
30
 
31
  snapshot_download(
32
+ repo_id="m-a-p/xcodec_mini_infer",
33
+ local_dir="./xcodec_mini_infer"
34
  )
35
 
36
  # Change to the "inference" directory
 
69
  from vocoder import build_codec_model, process_audio
70
  from post_process_audio import replace_low_freq_with_energy_matched
71
  import re
72
+ import multiprocessing
73
 
74
  def empty_output_folder(output_dir):
75
  # List all files in the output directory
76
  files = os.listdir(output_dir)
77
+
78
  # Iterate over the files and remove them
79
  for file in files:
80
  file_path = os.path.join(output_dir, file)
 
88
  except Exception as e:
89
  print(f"Error deleting file {file_path}: {e}")
90
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91
  device = "cuda:0"
92
 
93
+ # --- Model Loading and Quantization ---
94
  model = AutoModelForCausalLM.from_pretrained(
95
+ "m-a-p/YuE-s1-7B-anneal-en-cot",
96
  torch_dtype=torch.float16,
97
+ attn_implementation="flash_attention_2", # To enable flashattn, you have to install flash-attn
98
+ )
99
  model.to(device)
100
  model.eval()
101
 
102
+ # Apply dynamic quantization
103
+ model = torch.quantization.quantize_dynamic(
104
+ model, {torch.nn.Linear}, dtype=torch.qint8
105
+ )
106
+
107
+ basic_model_config = './xcodec_mini_infer/final_ckpt/config.yaml'
108
+ resume_path = './xcodec_mini_infer/final_ckpt/ckpt_00360000.pth'
109
+ config_path = './xcodec_mini_infer/decoders/config.yaml'
110
+ vocal_decoder_path = './xcodec_mini_infer/decoders/decoder_131000.pth'
111
+ inst_decoder_path = './xcodec_mini_infer/decoders/decoder_151000.pth'
112
 
113
  mmtokenizer = _MMSentencePieceTokenizer("./mm_tokenizer_v0.2_hf/tokenizer.model")
114
 
 
120
  codec_model.to(device)
121
  codec_model.eval()
122
 
123
+ # --- Parallel Audio Processing ---
124
+ def process_audio_wrapper(args):
125
+ # Unpack arguments and call the original process_audio function
126
+ npy, output_path, rescale, other_args, decoder, codec_model = args
127
+ return process_audio(npy, output_path, rescale, other_args, decoder, codec_model)
128
+
129
+ def parallel_process_audio(stage1_output_set, vocoder_stems_dir, rescale, other_args, vocal_decoder, inst_decoder,
130
+ codec_model, num_processes=4):
131
+ with multiprocessing.Pool(processes=num_processes) as pool:
132
+ tasks = []
133
+ for npy in stage1_output_set:
134
+ if 'instrumental' in npy:
135
+ output_path = os.path.join(vocoder_stems_dir, 'instrumental.mp3')
136
+ decoder = inst_decoder
137
+ else:
138
+ output_path = os.path.join(vocoder_stems_dir, 'vocal.mp3')
139
+ decoder = vocal_decoder
140
+ tasks.append((npy, output_path, rescale, other_args, decoder, codec_model))
141
+
142
+ results = pool.map(process_audio_wrapper, tasks)
143
+
144
+ return results
145
+
146
+ # --- Optimized Music Generation ---
147
  def generate_music(
148
+ max_new_tokens=5,
149
+ run_n_segments=2,
150
+ genre_txt=None,
151
+ lyrics_txt=None,
152
+ use_audio_prompt=False,
153
+ audio_prompt_path="",
154
+ prompt_start_time=0.0,
155
+ prompt_end_time=30.0,
156
+ output_dir="./output",
157
+ rescale=False,
158
+ beam_width=3, # Add beam search
159
+ length_penalty=1.0, # Add length penalty
160
+ repetition_penalty=1.5, # Add repetition penalty
161
+ batch_size=2
162
  ):
163
  if use_audio_prompt and not audio_prompt_path:
164
+ raise FileNotFoundError(
165
+ "Please offer audio prompt filepath using '--audio_prompt_path', when you enable 'use_audio_prompt'!")
166
+ max_new_tokens = max_new_tokens * 100
167
  stage1_output_dir = os.path.join(output_dir, f"stage1")
168
  os.makedirs(stage1_output_dir, exist_ok=True)
169
+
170
  class BlockTokenRangeProcessor(LogitsProcessor):
171
  def __init__(self, start_id, end_id):
172
  self.blocked_token_ids = list(range(start_id, end_id))
 
195
  stage1_output_set = []
196
 
197
  genres = genre_txt.strip()
198
+ lyrics = split_lyrics(lyrics_txt + "\n")
199
  # intruction
200
  full_lyrics = "\n".join(lyrics)
201
  prompt_texts = [f"Generate music from the given lyrics segment by segment.\n[Genre] {genres}\n{full_lyrics}"]
202
  prompt_texts += lyrics
203
 
 
204
  random_id = uuid.uuid4()
205
  output_seq = None
206
  # Here is suggested decoding config
207
  top_p = 0.93
208
  temperature = 1.0
 
209
  # special tokens
210
  start_of_segment = mmtokenizer.tokenize('[start_of_segment]')
211
  end_of_segment = mmtokenizer.tokenize('[end_of_segment]')
212
 
213
  raw_output = None
214
+ segment_cache = {} # Cache for repeated segments
215
 
216
  # Format text prompt
217
+ run_n_segments = min(run_n_segments + 1, len(lyrics))
218
 
219
  print(list(enumerate(tqdm(prompt_texts[:run_n_segments]))))
220
 
221
+ # Modified loop for batching and caching
222
+ for i in range(1, run_n_segments, batch_size):
223
+ batch_segments = []
224
+ batch_prompts = []
225
+ for j in range(i, min(i + batch_size, run_n_segments)):
226
+ section_text = prompt_texts[j].replace('[start_of_segment]', '').replace('[end_of_segment]', '')
227
+
228
+ # Check cache
229
+ if section_text in segment_cache:
230
+ cached_output = segment_cache[section_text]
231
+ if j > 1:
232
+ raw_output = torch.cat([raw_output, cached_output], dim=1)
233
+ else:
234
+ raw_output = cached_output
235
+ continue
236
+
237
+ batch_segments.append(section_text)
238
+ guidance_scale = 1.5 if j <= 1 else 1.2
239
+
240
+ if j == 1:
241
+ if use_audio_prompt:
242
+ audio_prompt = load_audio_mono(audio_prompt_path)
243
+ audio_prompt.unsqueeze_(0)
244
+ with torch.no_grad():
245
+ raw_codes = codec_model.encode(audio_prompt.to(device), target_bw=0.5)
246
+ raw_codes = raw_codes.transpose(0, 1)
247
+ raw_codes = raw_codes.cpu().numpy().astype(np.int16)
248
+ # Format audio prompt
249
+ code_ids = codectool.npy2ids(raw_codes[0])
250
+ audio_prompt_codec = code_ids[
251
+ int(prompt_start_time * 50): int(prompt_end_time * 50)] # 50 is tps of xcodec
252
+ audio_prompt_codec_ids = [mmtokenizer.soa] + codectool.sep_ids + audio_prompt_codec + [
253
+ mmtokenizer.eoa]
254
+ sentence_ids = mmtokenizer.tokenize("[start_of_reference]") + audio_prompt_codec_ids + mmtokenizer.tokenize(
255
+ "[end_of_reference]")
256
+ head_id = mmtokenizer.tokenize(prompt_texts[0]) + sentence_ids
257
+ else:
258
+ head_id = mmtokenizer.tokenize(prompt_texts[0])
259
+ prompt_ids = head_id + start_of_segment + mmtokenizer.tokenize(section_text) + [mmtokenizer.soa] + codectool.sep_ids
260
  else:
261
+ prompt_ids = end_of_segment + start_of_segment + mmtokenizer.tokenize(section_text) + [
262
+ mmtokenizer.soa] + codectool.sep_ids
263
+
264
+ prompt_ids = torch.as_tensor(prompt_ids).unsqueeze(0).to(device)
265
+ input_ids = torch.cat([raw_output, prompt_ids], dim=1) if j > 1 else prompt_ids
266
+
267
+ # Use window slicing in case output sequence exceeds the context of model
268
+ max_context = 16384 - max_new_tokens - 1
269
+ if input_ids.shape[-1] > max_context:
270
+ print(
271
+ f'Section {j}: output length {input_ids.shape[-1]} exceeding context length {max_context}, now using the last {max_context} tokens.')
272
+ input_ids = input_ids[:, -(max_context):]
273
+
274
+ batch_prompts.append(input_ids)
275
+
276
+ if not batch_prompts:
277
+ continue # All segments in the batch were cached
278
+
279
+ # Pad prompts in the batch to the same length
280
+ max_len = max(p.size(1) for p in batch_prompts)
281
+ padded_prompts = []
282
+ for p in batch_prompts:
283
+ pad_len = max_len - p.size(1)
284
+ padded_prompt = F.pad(p, (0, pad_len), value=mmtokenizer.eoa)
285
+ padded_prompts.append(padded_prompt)
286
+
287
+ batch_input_ids = torch.cat(padded_prompts, dim=0)
288
+
289
  with torch.no_grad():
290
+ output_seqs = model.generate(
291
+ input_ids=batch_input_ids,
292
+ max_new_tokens=max_new_tokens,
293
+ min_new_tokens=100,
294
+ do_sample=True,
295
  top_p=top_p,
296
+ temperature=temperature,
297
+ repetition_penalty=repetition_penalty,
298
  eos_token_id=mmtokenizer.eoa,
299
  pad_token_id=mmtokenizer.eoa,
300
+ logits_processor=LogitsProcessorList(
301
+ [BlockTokenRangeProcessor(0, 32002), BlockTokenRangeProcessor(32016, 32016)]),
302
  guidance_scale=guidance_scale,
303
  use_cache=True,
304
+ num_beams=beam_width, # Use beam search
305
+ length_penalty=length_penalty, # Apply length penalty
306
+ )
307
+
308
+ # Process each output in the batch
309
+ for k, output_seq in enumerate(output_seqs):
310
  if output_seq[0][-1].item() != mmtokenizer.eoa:
311
  tensor_eoa = torch.as_tensor([[mmtokenizer.eoa]]).to(model.device)
312
  output_seq = torch.cat((output_seq, tensor_eoa), dim=1)
313
+ if i > 1:
314
+ raw_output = torch.cat([raw_output, batch_prompts[k][:, :batch_input_ids.shape[-1]],
315
+ output_seq[:, batch_input_ids.shape[-1]:]], dim=1)
316
+ else:
317
+ raw_output = output_seq
318
+
319
+ # Cache the generated output if not already cached
320
+ if batch_segments[k] not in segment_cache:
321
+ segment_cache[batch_segments[k]] = output_seq[:, batch_input_ids.shape[-1]:].cpu()
322
 
323
  # save raw output and check sanity
324
  ids = raw_output[0].cpu().numpy()
325
  soa_idx = np.where(ids == mmtokenizer.soa)[0].tolist()
326
  eoa_idx = np.where(ids == mmtokenizer.eoa)[0].tolist()
327
+ if len(soa_idx) != len(eoa_idx):
328
  raise ValueError(f'invalid pairs of soa and eoa, Num of soa: {len(soa_idx)}, Num of eoa: {len(eoa_idx)}')
329
 
330
  vocals = []
331
  instrumentals = []
332
  range_begin = 1 if use_audio_prompt else 0
333
  for i in range(range_begin, len(soa_idx)):
334
+ codec_ids = ids[soa_idx[i] + 1:eoa_idx[i]]
335
  if codec_ids[0] == 32016:
336
  codec_ids = codec_ids[1:]
337
  codec_ids = codec_ids[:2 * (codec_ids.shape[0] // 2)]
338
+ vocals_ids = codectool.ids2npy(rearrange(codec_ids, "(n b) -> b n", b=2)[0])
339
  vocals.append(vocals_ids)
340
+ instrumentals_ids = codectool.ids2npy(rearrange(codec_ids, "(n b) -> b n", b=2)[1])
341
  instrumentals.append(instrumentals_ids)
342
  vocals = np.concatenate(vocals, axis=1)
343
  instrumentals = np.concatenate(instrumentals, axis=1)
344
+ vocal_save_path = os.path.join(stage1_output_dir,
345
+ f"cot_{genres.replace(' ', '-')}_tp{top_p}_T{temperature}_rp{repetition_penalty}_maxtk{max_new_tokens}_vocal_{random_id}".replace(
346
+ '.', '@') + '.npy')
347
+ inst_save_path = os.path.join(stage1_output_dir,
348
+ f"cot_{genres.replace(' ', '-')}_tp{top_p}_T{temperature}_rp{repetition_penalty}_maxtk{max_new_tokens}_instrumental_{random_id}".replace(
349
+ '.', '@') + '.npy')
350
  np.save(vocal_save_path, vocals)
351
  np.save(inst_save_path, instrumentals)
352
  stage1_output_set.append(vocal_save_path)
 
363
  max_val = wav.abs().max()
364
  wav = wav * min(limit / max_val, 1) if rescale else wav.clamp(-limit, limit)
365
  torchaudio.save(str(path), wav, sample_rate=sample_rate, encoding='PCM_S', bits_per_sample=16)
366
+
367
  # reconstruct tracks
368
  recons_output_dir = os.path.join(output_dir, "recons")
369
  recons_mix_dir = os.path.join(recons_output_dir, 'mix')
 
371
  tracks = []
372
  for npy in stage1_output_set:
373
  codec_result = np.load(npy)
374
+ decodec_rlt = []
375
  with torch.no_grad():
376
+ decoded_waveform = codec_model.decode(
377
+ torch.as_tensor(codec_result.astype(np.int16), dtype=torch.long).unsqueeze(0).permute(1, 0, 2).to(
378
+ device))
379
  decoded_waveform = decoded_waveform.cpu().squeeze(0)
380
  decodec_rlt.append(torch.as_tensor(decoded_waveform))
381
  decodec_rlt = torch.cat(decodec_rlt, dim=-1)
 
386
  for inst_path in tracks:
387
  try:
388
  if (inst_path.endswith('.wav') or inst_path.endswith('.mp3')) \
389
+ and 'instrumental' in inst_path:
390
  # find pair
391
  vocal_path = inst_path.replace('instrumental', 'vocal')
392
  if not os.path.exists(vocal_path):
 
399
  sf.write(recons_mix, mix_stem, sr)
400
  except Exception as e:
401
  print(e)
 
402
 
403
  # vocoder to upsample audios
404
  vocal_decoder, inst_decoder = build_codec_model(config_path, vocal_decoder_path, inst_decoder_path)
 
407
  vocoder_mix_dir = os.path.join(vocoder_output_dir, 'mix')
408
  os.makedirs(vocoder_mix_dir, exist_ok=True)
409
  os.makedirs(vocoder_stems_dir, exist_ok=True)
410
+
411
+ # Use parallel processing for vocoding
412
+ parallel_process_audio(stage1_output_set, vocoder_stems_dir, rescale, argparse.Namespace(**locals()), vocal_decoder,
413
+ inst_decoder, codec_model)
414
+
415
+ # mix tracks after parallel processing
416
+ instrumental_output_path = os.path.join(vocoder_stems_dir, 'instrumental.mp3')
417
+ vocal_output_path = os.path.join(vocoder_stems_dir, 'vocal.mp3')
418
+
419
+ if os.path.exists(instrumental_output_path) and os.path.exists(vocal_output_path):
420
+ instrumental_output, sr = torchaudio.load(instrumental_output_path)
421
+ vocal_output, _ = torchaudio.load(vocal_output_path)
422
+ try:
423
+ mix_output = instrumental_output + vocal_output
424
+ vocoder_mix = os.path.join(vocoder_mix_dir, os.path.basename(recons_mix))
425
+ save_audio(mix_output, vocoder_mix, 44100, rescale)
426
+ print(f"Created mix: {vocoder_mix}")
427
+ except RuntimeError as e:
428
+ print(e)
429
+ print(f"mix {vocoder_mix} failed! inst: {instrumental_output.shape}, vocal: {vocal_output.shape}")
430
+ else:
431
+ print("Skipping mix creation, instrumental or vocal output missing.")
 
 
 
 
 
 
 
 
 
 
432
 
433
  # Post process
434
  replace_low_freq_with_energy_matched(
435
+ a_file=recons_mix, # 16kHz
436
+ b_file=vocoder_mix, # 48kHz
437
  c_file=os.path.join(output_dir, os.path.basename(recons_mix)),
438
  cutoff_freq=5500.0
439
  )
440
  print("All process Done")
441
  return recons_mix
442
 
 
443
  @spaces.GPU(duration=120)
444
+ def infer(genre_txt_content, lyrics_txt_content, num_segments=2, max_new_tokens=5):
 
445
  # Ensure the output folder exists
446
  output_dir = "./output"
447
  os.makedirs(output_dir, exist_ok=True)
 
451
 
452
  # Execute the command
453
  try:
454
+ music = generate_music(genre_txt=genre_txt_content, lyrics_txt=lyrics_txt_content, run_n_segments=num_segments,
455
+ output_dir=output_dir, cuda_idx=0, max_new_tokens=max_new_tokens)
456
  return music
457
  except Exception as e:
458
  gr.Warning("An Error Occured: " + str(e))
459
+ return None
460
  finally:
461
  print("Temporary files deleted.")
462
 
463
+ # Gradio
464
 
465
  with gr.Blocks() as demo:
466
  with gr.Column():
 
482
  with gr.Column():
483
  genre_txt = gr.Textbox(label="Genre")
484
  lyrics_txt = gr.Textbox(label="Lyrics")
485
+
486
  with gr.Column():
487
  num_segments = gr.Number(label="Number of Segments", value=2, interactive=True)
488
+ max_new_tokens = gr.Slider(label="Duration of song", minimum=1, maximum=30, step=1, value=5,
489
+ interactive=True)
490
  submit_btn = gr.Button("Submit")
491
  music_out = gr.Audio(label="Audio Result")
492
 
493
  gr.Examples(
494
+ examples=[
495
  [
496
  "female blues airy vocal bright vocal piano sad romantic guitar jazz",
497
  """[verse]
 
526
  Living out my dreams with this mic and a deal
527
  """
528
  ]
529
+ ],
530
+ inputs=[genre_txt, lyrics_txt],
531
+ outputs=[music_out],
532
+ cache_examples=True,
533
  cache_mode="eager",
534
  fn=infer
535
  )
536
+
537
  submit_btn.click(
538
+ fn=infer,
539
+ inputs=[genre_txt, lyrics_txt, num_segments, max_new_tokens],
540
+ outputs=[music_out]
541
  )
542
+ demo.queue().launch(show_error=True)