Merge branch 'longgen' into our_hf2
Browse filesFiles changed (8)
4 unmodified lines56789101142 unmodified lines54555657585960616263644 unmodified lines- "music generation"- "language models"- "LLMs"app_file: "app_batched.py"emoji: 🎵colorFrom: whitecolorTo: blue42 unmodified lines## UsageWe offer a number of way to interact with MusicGen:1. You can play with MusicGen by running the jupyter notebook at [`demo.ipynb`](./demo.ipynb) locally, or use the provided [colab notebook](https://colab.research.google.com/drive/1fxGqfg96RBUvGxZ1XXN07s3DthrKUl4-?usp=sharing).2. You can use the gradio demo locally by running `python app.py`.3. A demo is also available on the [`facebook/MusicGen` HuggingFace Space](https://huggingface.co/spaces/facebook/MusicGen) (huge thanks to all the HF team for their support).4. Finally, you can run the [Gradio demo with a Colab GPU](https://colab.research.google.com/drive/1-Xe9NCdIs2sCUbiSmwHXozK6AAhMm7_i?usp=sharing),as adapted from [@camenduru Colab](https://github.com/camenduru/MusicGen-colab).## API4 unmodified lines56789101142 unmodified lines5455565758596061626364654 unmodified lines- "music generation"- "language models"- "LLMs"app_file: "app.py"emoji: 🎵colorFrom: whitecolorTo: blue42 unmodified lines## UsageWe offer a number of way to interact with MusicGen:1. A demo is also available on the [`facebook/MusicGen` HuggingFace Space](https://huggingface.co/spaces/facebook/MusicGen) (huge thanks to all the HF team for their support).2. You can run the extended demo on a Colab: [colab notebook](https://colab.research.google.com/drive/1fxGqfg96RBUvGxZ1XXN07s3DthrKUl4-?usp=sharing).3. You can use the gradio demo locally by running `python app.py`.4. You can play with MusicGen by running the jupyter notebook at [`demo.ipynb`](./demo.ipynb) locally (if you have a GPU).5. Finally, checkout [@camenduru Colab page](https://github.com/camenduru/MusicGen-colab) which is regularlyupdated with contributions from @camenduru and the community.## API
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869702 unmodified lines73747576777879808182838485861 unmodified line888990919293949596971 unmodified line9910010110210310410510610729 unmodified lines13713813914014114214310 unmodified lines1541551561571581591601611621631641651661671681691701711721731741751761771781791801 unmodified line18218318418518618718817 unmodified lines206207208209210211212213214215216"""Copyright (c) Meta Platforms, Inc. and affiliates.All rights reserved.This source code is licensed under the license found in theLICENSE file in the root directory of this source tree."""from tempfile import NamedTemporaryFileimport argparseimport torchimport gradio as grimport osfrom audiocraft.models import MusicGenfrom audiocraft.data.audio import audio_writeMODEL = NoneIS_SHARED_SPACE = "musicgen/MusicGen" in os.environ.get('SPACE_ID', '')def load_model(version):print("Loading model", version)return MusicGen.get_pretrained(version)def predict(model, text, melody, duration, topk, topp, temperature, cfg_coef):global MODELtopk = int(topk)if MODEL is None or MODEL.name != model:MODEL = load_model(model)if duration > MODEL.lm.cfg.dataset.segment_duration:raise gr.Error("MusicGen currently supports durations of up to 30 seconds!")MODEL.set_generation_params(use_sampling=True,top_k=topk,top_p=topp,temperature=temperature,cfg_coef=cfg_coef,duration=duration,)if melody:sr, melody = melody[0], torch.from_numpy(melody[1]).to(MODEL.device).float().t().unsqueeze(0)print(melody.shape)if melody.dim() == 2:melody = melody[None]melody = melody[..., :int(sr * MODEL.lm.cfg.dataset.segment_duration)]output = MODEL.generate_with_chroma(descriptions=[text],melody_wavs=melody,melody_sample_rate=sr,progress=False)else:output = MODEL.generate(descriptions=[text], progress=False)output = output.detach().cpu().float()[0]with NamedTemporaryFile("wb", suffix=".wav", delete=False) as file:audio_write(file.name, output, MODEL.sample_rate, strategy="loudness",loudness_headroom_db=16, loudness_compressor=True, add_suffix=False)waveform_video = gr.make_waveform(file.name)return waveform_videodef ui(**kwargs):with gr.Blocks() as interface:gr.Markdown("""2 unmodified linespresented at: ["Simple and Controllable Music Generation"](https://huggingface.co/papers/2306.05284)""")if IS_SHARED_SPACE:gr.Markdown("""⚠ This Space doesn't work in this shared UI ⚠<a href="https://huggingface.co/spaces/musicgen/MusicGen?duplicate=true" style="display: inline-block;margin-top: .5em;margin-right: .25em;" target="_blank"><img style="margin-bottom: 0em;display: inline;margin-top: -.25em;" src="https://bit.ly/3gLdBN6" alt="Duplicate Space"></a>to use it privately, or use the <a href="https://huggingface.co/spaces/facebook/MusicGen">public demo</a>""")with gr.Row():with gr.Column():with gr.Row():1 unmodified linemelody = gr.Audio(source="upload", type="numpy", label="Melody Condition (optional)", interactive=True)with gr.Row():submit = gr.Button("Submit")with gr.Row():model = gr.Radio(["melody", "medium", "small", "large"], label="Model", value="melody", interactive=True)with gr.Row():duration = gr.Slider(minimum=1, maximum=30, value=10, label="Duration", interactive=True)with gr.Row():topk = gr.Number(label="Top-k", value=250, interactive=True)topp = gr.Number(label="Top-p", value=0, interactive=True)1 unmodified linecfg_coef = gr.Number(label="Classifier Free Guidance", value=3.0, interactive=True)with gr.Column():output = gr.Video(label="Generated Music")submit.click(predict, inputs=[model, text, melody, duration, topk, topp, temperature, cfg_coef], outputs=[output])gr.Examples(fn=predict,examples=[["An 80s driving pop song with heavy drums and synth pads in the background",29 unmodified lines### More detailsThe model will generate a short music extract based on the description you provided.You can generate up to 30 seconds of audio.We present 4 model variations:1. Melody -- a music generation model capable of generating music condition on text and melody inputs. **Note**, you can also use text only.10 unmodified lines""")# Show the interfacelaunch_kwargs = {}username = kwargs.get('username')password = kwargs.get('password')server_port = kwargs.get('server_port', 0)inbrowser = kwargs.get('inbrowser', False)share = kwargs.get('share', False)server_name = kwargs.get('listen')launch_kwargs['server_name'] = server_nameif username and password:launch_kwargs['auth'] = (username, password)if server_port > 0:launch_kwargs['server_port'] = server_portif inbrowser:launch_kwargs['inbrowser'] = inbrowserif share:launch_kwargs['share'] = shareinterface.queue().launch(**launch_kwargs, max_threads=1)if __name__ == "__main__":1 unmodified lineparser.add_argument('--listen',type=str,default='0.0.0.0',help='IP to listen on for connections to Gradio',)parser.add_argument(17 unmodified linesargs = parser.parse_args()ui(username=args.username,password=args.password,inbrowser=args.inbrowser,server_port=args.server_port,share=args.share,listen=args.listen)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381392 unmodified lines1421431441451461471 unmodified line1491501511521531541551561571581591601 unmodified line16216316416516616716816917029 unmodified lines20020120220320420520620720820921021121210 unmodified lines2232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962971 unmodified line29930030130230330430530630730830917 unmodified lines327328329330331332333334335336337338339340341342343344# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.# This source code is licensed under the license found in the# LICENSE file in the root directory of this source tree.# Updated to account for UI changes from https://github.com/rkfg/audiocraft/blob/long/app.py# also released under the MIT license.import argparsefrom concurrent.futures import ProcessPoolExecutorimport osimport subprocess as spfrom tempfile import NamedTemporaryFileimport timeimport warningsimport torchimport gradio as grfrom audiocraft.data.audio_utils import convert_audiofrom audiocraft.data.audio import audio_writefrom audiocraft.models import MusicGenMODEL = None # Last used modelIS_BATCHED = "facebook/MusicGen" in os.environ.get('SPACE_ID', '')MAX_BATCH_SIZE = 12BATCHED_DURATION = 15INTERRUPTING = False# We have to wrap subprocess call to clean a bit the log when using gr.make_waveform_old_call = sp.calldef _call_nostderr(*args, **kwargs):# Avoid ffmpeg vomitting on the logs.kwargs['stderr'] = sp.DEVNULLkwargs['stdout'] = sp.DEVNULL_old_call(*args, **kwargs)sp.call = _call_nostderr# Preallocating the pool of processes.pool = ProcessPoolExecutor(4)pool.__enter__()def interrupt():global INTERRUPTINGINTERRUPTING = Truedef make_waveform(*args, **kwargs):# Further remove some warnings.be = time.time()with warnings.catch_warnings():warnings.simplefilter('ignore')out = gr.make_waveform(*args, **kwargs)print("Make a video took", time.time() - be)return outdef load_model(version='melody'):global MODELprint("Loading model", version)if MODEL is None or MODEL.name != version:MODEL = MusicGen.get_pretrained(version)def _do_predictions(texts, melodies, duration, **gen_kwargs):MODEL.set_generation_params(duration=duration, **gen_kwargs)print("new batch", len(texts), texts, [None if m is None else (m[0], m[1].shape) for m in melodies])be = time.time()processed_melodies = []target_sr = 32000target_ac = 1for melody in melodies:if melody is None:processed_melodies.append(None)else:sr, melody = melody[0], torch.from_numpy(melody[1]).to(MODEL.device).float().t()if melody.dim() == 1:melody = melody[None]melody = melody[..., :int(sr * duration)]melody = convert_audio(melody, sr, target_sr, target_ac)processed_melodies.append(melody)if any(m is not None for m in processed_melodies):outputs = MODEL.generate_with_chroma(descriptions=texts,melody_wavs=processed_melodies,melody_sample_rate=target_sr,progress=True)else:outputs = MODEL.generate(texts, progress=True)outputs = outputs.detach().cpu().float()out_files = []for output in outputs:with NamedTemporaryFile("wb", suffix=".wav", delete=False) as file:audio_write(file.name, output, MODEL.sample_rate, strategy="loudness",loudness_headroom_db=16, loudness_compressor=True, add_suffix=False)out_files.append(pool.submit(make_waveform, file.name))res = [out_file.result() for out_file in out_files]print("batch finished", len(texts), time.time() - be)return resdef predict_batched(texts, melodies):max_text_length = 512texts = [text[:max_text_length] for text in texts]load_model('melody')res = _do_predictions(texts, melodies, BATCHED_DURATION)return [res]def predict_full(model, text, melody, duration, topk, topp, temperature, cfg_coef, progress=gr.Progress()):global INTERRUPTINGINTERRUPTING = Falsetopk = int(topk)load_model(model)def _progress(generated, to_generate):progress((generated, to_generate))if INTERRUPTING:raise gr.Error("Interrupted.")MODEL.set_custom_progress_callback(_progress)outs = _do_predictions([text], [melody], duration,top_k=topk, top_p=topp, temperature=temperature, cfg_coef=cfg_coef)return outs[0]def ui_full(launch_kwargs):with gr.Blocks() as interface:gr.Markdown("""2 unmodified linespresented at: ["Simple and Controllable Music Generation"](https://huggingface.co/papers/2306.05284)""")with gr.Row():with gr.Column():with gr.Row():1 unmodified linemelody = gr.Audio(source="upload", type="numpy", label="Melody Condition (optional)", interactive=True)with gr.Row():submit = gr.Button("Submit")# Adapted from https://github.com/rkfg/audiocraft/blob/long/app.py, MIT license._ = gr.Button("Interrupt").click(fn=interrupt, queue=False)with gr.Row():model = gr.Radio(["melody", "medium", "small", "large"], label="Model", value="melody", interactive=True)with gr.Row():duration = gr.Slider(minimum=1, maximum=120, value=10, label="Duration", interactive=True)with gr.Row():topk = gr.Number(label="Top-k", value=250, interactive=True)topp = gr.Number(label="Top-p", value=0, interactive=True)1 unmodified linecfg_coef = gr.Number(label="Classifier Free Guidance", value=3.0, interactive=True)with gr.Column():output = gr.Video(label="Generated Music")submit.click(predict_full, inputs=[model, text, melody, duration, topk, topp, temperature, cfg_coef], outputs=[output])gr.Examples(fn=predict_full,examples=[["An 80s driving pop song with heavy drums and synth pads in the background",29 unmodified lines### More detailsThe model will generate a short music extract based on the description you provided.The model can generate up to 30 seconds of audio in one pass. It is now possibleto extend the generation by feeding back the end of the previous chunk of audio.This can take a long time, and the model might lose consistency. The model might alsodecide at arbitrary positions that the song ends.**WARNING:** Choosing long durations will take a long time to generate (2min might take ~10min). An overlap of 12 secondsis kept with the previously generated chunk, and 18 "new" seconds are generated each time.We present 4 model variations:1. Melody -- a music generation model capable of generating music condition on text and melody inputs. **Note**, you can also use text only.10 unmodified lines""")interface.queue().launch(**launch_kwargs)def ui_batched(launch_kwargs):with gr.Blocks() as demo:gr.Markdown("""# MusicGenThis is the demo for [MusicGen](https://github.com/facebookresearch/audiocraft), a simple and controllable model for music generationpresented at: ["Simple and Controllable Music Generation"](https://huggingface.co/papers/2306.05284).<br/><a href="https://huggingface.co/spaces/facebook/MusicGen?duplicate=true" style="display: inline-block;margin-top: .5em;margin-right: .25em;" target="_blank"><img style="margin-bottom: 0em;display: inline;margin-top: -.25em;" src="https://bit.ly/3gLdBN6" alt="Duplicate Space"></a>for longer sequences, more control and no queue.</p>""")with gr.Row():with gr.Column():with gr.Row():text = gr.Text(label="Describe your music", lines=2, interactive=True)melody = gr.Audio(source="upload", type="numpy", label="Condition on a melody (optional)", interactive=True)with gr.Row():submit = gr.Button("Generate")with gr.Column():output = gr.Video(label="Generated Music")submit.click(predict_batched, inputs=[text, melody], outputs=[output], batch=True, max_batch_size=MAX_BATCH_SIZE)gr.Examples(fn=predict_batched,examples=[["An 80s driving pop song with heavy drums and synth pads in the background","./assets/bach.mp3",],["A cheerful country song with acoustic guitars","./assets/bolero_ravel.mp3",],["90s rock song with electric guitar and heavy drums",None,],["a light and cheerly EDM track, with syncopated drums, aery pads, and strong emotions bpm: 130","./assets/bach.mp3",],["lofi slow bpm electro chill with organic samples",None,],],inputs=[text, melody],outputs=[output])gr.Markdown("""### More detailsThe model will generate 12 seconds of audio based on the description you provided.You can optionaly provide a reference audio from which a broad melody will be extracted.The model will then try to follow both the description and melody provided.All samples are generated with the `melody` model.You can also use your own GPU or a Google Colab by following the instructions on our repo.See [github.com/facebookresearch/audiocraft](https://github.com/facebookresearch/audiocraft)for more details.""")demo.queue(max_size=8 * 4).launch(**launch_kwargs)if __name__ == "__main__":1 unmodified lineparser.add_argument('--listen',type=str,<<<<<<< HEADdefault='0.0.0.0',=======default='0.0.0.0' if 'SPACE_ID' in os.environ else '127.0.0.1',>>>>>>> longgenhelp='IP to listen on for connections to Gradio',)parser.add_argument(17 unmodified linesargs = parser.parse_args()launch_kwargs = {}if args.username and args.password:launch_kwargs['auth'] = (args.username, args.password)if args.server_port:launch_kwargs['server_port'] = args.server_portif args.inbrowser:launch_kwargs['inbrowser'] = args.inbrowserif args.share:launch_kwargs['share'] = args.share# Show the interfaceif IS_BATCHED:ui_batched(launch_kwargs)else:ui_full(launch_kwargs)
79 unmodified lines808182838485868779 unmodified linescfg = OmegaConf.create(pkg['xp.cfg'])cfg.device = str(device)if cfg.device == 'cpu':cfg.transformer_lm.memory_efficient = Falsecfg.transformer_lm.custom = Truecfg.dtype = 'float32'else:cfg.dtype = 'float16'79 unmodified lines80818283848579 unmodified linescfg = OmegaConf.create(pkg['xp.cfg'])cfg.device = str(device)if cfg.device == 'cpu':cfg.dtype = 'float32'else:cfg.dtype = 'float16'
35 unmodified lines3637383940414243444546474816 unmodified lines656667686970711 unmodified line73747576777817 unmodified lines9697989910010110210 unmodified lines1131141151161171181191201211221232 unmodified lines126127128129130131136 unmodified lines26826927027127227327427527627727827928028128228328428528628735 unmodified linesused to map audio to invertible discrete representations.lm (LMModel): Language model over discrete representations."""def __init__(self, name: str, compression_model: CompressionModel, lm: LMModel):self.name = nameself.compression_model = compression_modelself.lm = lmself.device = next(iter(lm.parameters())).deviceself.generation_params: dict = {}self.set_generation_params(duration=15) # 15 seconds by defaultif self.device.type == 'cpu':self.autocast = TorchAutocast(enabled=False)else:16 unmodified linesreturn self.compression_model.channels@staticmethoddef get_pretrained(name: str = 'melody', device='cuda'):"""Return pretrained model, we provide four models:- small (300M), text to music, # see: https://huggingface.co/facebook/musicgen-small- medium (1.5B), text to music, # see: https://huggingface.co/facebook/musicgen-medium1 unmodified line- large (3.3B), text to music, # see: https://huggingface.co/facebook/musicgen-large"""if name == 'debug':# used only for unit testscompression_model = get_debug_compression_model(device)17 unmodified linesdef set_generation_params(self, use_sampling: bool = True, top_k: int = 250,top_p: float = 0.0, temperature: float = 1.0,duration: float = 30.0, cfg_coef: float = 3.0,two_step_cfg: bool = False, extend_stride: float = 15):"""Set the generation parameters for MusicGen.Args:10 unmodified linesshould we extend the audio each time. Larger values will mean less context ispreserved, and shorter value will require extra computations."""# assert duration <= 30, "The MusicGen cannot generate more than 30 seconds"assert extend_stride <= 25, "Keep at least 5 seconds of overlap!"self.extend_stride = extend_strideself.generation_params = {'max_gen_len': int(duration * self.frame_rate),'use_sampling': use_sampling,'temp': temperature,'top_k': top_k,2 unmodified lines'two_step_cfg': two_step_cfg,}def generate_unconditional(self, num_samples: int, progress: bool = False) -> torch.Tensor:"""Generate samples in an unconditional manner.136 unmodified linesReturns:torch.Tensor: Generated audio, of shape [B, C, T], T is defined by the generation params."""def _progress_callback(generated_tokens: int, tokens_to_generate: int):print(f'{generated_tokens: 6d} / {tokens_to_generate: 6d}', end='\r')if prompt_tokens is not None:assert self.generation_params['max_gen_len'] > prompt_tokens.shape[-1], \"Prompt is longer than audio to generate"callback = Noneif progress:callback = _progress_callback# generate by sampling from LMwith self.autocast:gen_tokens = self.lm.generate(prompt_tokens, attributes, callback=callback, **self.generation_params)# generate audioassert gen_tokens.dim() == 335 unmodified lines3637383940414243444546474849505116 unmodified lines686970717273741 unmodified line76777879808182838485868717 unmodified lines10510610710810911011110 unmodified lines1221231241251261271281291301312 unmodified lines134135136137138139140141142143136 unmodified lines28028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835 unmodified linesused to map audio to invertible discrete representations.lm (LMModel): Language model over discrete representations."""def __init__(self, name: str, compression_model: CompressionModel, lm: LMModel,max_duration: float = 30):self.name = nameself.compression_model = compression_modelself.lm = lmself.max_duration = max_durationself.device = next(iter(lm.parameters())).deviceself.generation_params: dict = {}self.set_generation_params(duration=15) # 15 seconds by defaultself._progress_callback: tp.Optional[tp.Callable[[int, int], None]] = Noneif self.device.type == 'cpu':self.autocast = TorchAutocast(enabled=False)else:16 unmodified linesreturn self.compression_model.channels@staticmethoddef get_pretrained(name: str = 'melody', device=None):"""Return pretrained model, we provide four models:- small (300M), text to music, # see: https://huggingface.co/facebook/musicgen-small- medium (1.5B), text to music, # see: https://huggingface.co/facebook/musicgen-medium1 unmodified line- large (3.3B), text to music, # see: https://huggingface.co/facebook/musicgen-large"""if device is None:if torch.cuda.device_count():device = 'cuda'else:device = 'cpu'if name == 'debug':# used only for unit testscompression_model = get_debug_compression_model(device)17 unmodified linesdef set_generation_params(self, use_sampling: bool = True, top_k: int = 250,top_p: float = 0.0, temperature: float = 1.0,duration: float = 30.0, cfg_coef: float = 3.0,two_step_cfg: bool = False, extend_stride: float = 18):"""Set the generation parameters for MusicGen.Args:10 unmodified linesshould we extend the audio each time. Larger values will mean less context ispreserved, and shorter value will require extra computations."""assert extend_stride < self.max_duration, "Cannot stride by more than max generation duration."self.extend_stride = extend_strideself.duration = durationself.generation_params = {'use_sampling': use_sampling,'temp': temperature,'top_k': top_k,2 unmodified lines'two_step_cfg': two_step_cfg,}def set_custom_progress_callback(self, progress_callback: tp.Optional[tp.Callable[[int, int], None]] = None):"""Override the default progress callback."""self._progress_callback = progress_callbackdef generate_unconditional(self, num_samples: int, progress: bool = False) -> torch.Tensor:"""Generate samples in an unconditional manner.136 unmodified linesReturns:torch.Tensor: Generated audio, of shape [B, C, T], T is defined by the generation params."""total_gen_len = int(self.duration * self.frame_rate)max_prompt_len = int(min(self.duration, self.max_duration) * self.frame_rate)current_gen_offset: int = 0def _progress_callback(generated_tokens: int, tokens_to_generate: int):generated_tokens += current_gen_offsetif self._progress_callback is not None:# Note that total_gen_len might be quite wrong depending on the# codebook pattern used, but with delay it is almost accurate.self._progress_callback(generated_tokens, total_gen_len)else:print(f'{generated_tokens: 6d} / {total_gen_len: 6d}', end='\r')if prompt_tokens is not None:assert max_prompt_len >= prompt_tokens.shape[-1], \"Prompt is longer than audio to generate"callback = Noneif progress:callback = _progress_callbackif self.duration <= self.max_duration:# generate by sampling from LM, simple case.with self.autocast:gen_tokens = self.lm.generate(prompt_tokens, attributes,callback=callback, max_gen_len=total_gen_len, **self.generation_params)else:# now this gets a bit messier, we need to handle prompts,# melody conditioning etc.ref_wavs = [attr.wav['self_wav'] for attr in attributes]all_tokens = []if prompt_tokens is None:prompt_length = 0else:all_tokens.append(prompt_tokens)prompt_length = prompt_tokens.shape[-1]stride_tokens = int(self.frame_rate * self.extend_stride)while current_gen_offset + prompt_length < total_gen_len:time_offset = current_gen_offset / self.frame_ratechunk_duration = min(self.duration - time_offset, self.max_duration)max_gen_len = int(chunk_duration * self.frame_rate)for attr, ref_wav in zip(attributes, ref_wavs):wav_length = ref_wav.length.item()if wav_length == 0:continue# We will extend the wav periodically if it not long enough.# we have to do it here rather than in conditioners.py as otherwise# we wouldn't have the full wav.initial_position = int(time_offset * self.sample_rate)wav_target_length = int(self.max_duration * self.sample_rate)print(initial_position / self.sample_rate, wav_target_length / self.sample_rate)positions = torch.arange(initial_position,initial_position + wav_target_length, device=self.device)attr.wav['self_wav'] = WavCondition(ref_wav[0][:, positions % wav_length],torch.full_like(ref_wav[1], wav_target_length))with self.autocast:gen_tokens = self.lm.generate(prompt_tokens, attributes,callback=callback, max_gen_len=max_gen_len, **self.generation_params)if prompt_tokens is None:all_tokens.append(gen_tokens)else:all_tokens.append(gen_tokens[:, :, prompt_tokens.shape[-1]:])prompt_tokens = gen_tokens[:, :, stride_tokens:]prompt_length = prompt_tokens.shape[-1]current_gen_offset += stride_tokensgen_tokens = torch.cat(all_tokens, dim=-1)# generate audioassert gen_tokens.dim() == 3
24 unmodified lines25262728293044 unmodified lines7576777879808182838485868788121 unmodified lines2102112122132142156 unmodified lines22222322422522622722810 unmodified lines2392402412422432442 unmodified lines2472482492502512522532542552562572582592602612622632642652664 unmodified lines27127227327427527627727814 unmodified lines29329429529629729826 unmodified lines3253263273283293303313321 unmodified line3343353363373383393404 unmodified lines3453463473483493503513523533543553563573583593603613623 unmodified lines3663673683693703713723733 unmodified lines37737837938038138238338438538638738838939039139239339424 unmodified linesfrom .rope import RotaryEmbeddingfrom .streaming import StreamingModuledef _is_profiled() -> bool:# Return true if we are currently running with a xformers profiler activated.44 unmodified linesdef expand_repeated_kv(x: torch.Tensor, n_rep: int) -> torch.Tensor:"""torch.repeat_interleave(x, dim=2, repeats=n_rep) from xlformers"""bs, slen, n_kv_heads, head_dim = x.shapeif n_rep == 1:return xreturn (x[:, :, :, None, :].expand(bs, slen, n_kv_heads, n_rep, head_dim).reshape(bs, slen, n_kv_heads * n_rep, head_dim))class LayerScale(nn.Module):121 unmodified lines# Return a causal mask, accounting for potentially stored past keys/values# We actually return a bias for the attention score, as this has the same# convention both in the builtin MHA in Pytorch, and Xformers functions.if self.memory_efficient:from xformers.ops import LowerTriangularMaskif current_steps == 1:6 unmodified linesreturn LowerTriangularMask()if self._streaming_state:past_keys = self._streaming_state['past_keys']past_steps = past_keys.shape[1]else:past_steps = 010 unmodified linestorch.full([], float('-inf'), device=device, dtype=dtype))def _complete_kv(self, k, v):if self.cross_attention:# With cross attention we assume all keys and values# are already available, and streaming is with respect2 unmodified lines# Complete the key/value pair using the streaming state.if self._streaming_state:pk = self._streaming_state['past_keys']nk = torch.cat([pk, k], dim=2)if v is k:nv = nkelse:pv = self._streaming_state['past_values']nv = torch.cat([pv, v], dim=2)else:nk = knv = vassert nk.shape[2] == nv.shape[2]offset = 0if self.past_context is not None:offset = max(0, nk.shape[2] - self.past_context)if self._is_streaming:self._streaming_state['past_keys'] = nk[:, offset:]if v is not k:4 unmodified linesself._streaming_state['offset'] = torch.tensor(0)return nk, nvdef _apply_rope(self, query: torch.Tensor, key: torch.Tensor):# Apply rope embeddings to query and key tensors.assert self.rope is not Noneif 'past_keys' in self._streaming_state:14 unmodified linesassert not is_causal, ("new param added in torch 2.0.1 not supported, ""use the causal args in the constructor.")dtype = query.dtypeif self._is_streaming:assert self.causal or self.cross_attention, \26 unmodified linesif self.qk_layer_norm is True:q = self.q_layer_norm(q)k = self.k_layer_norm(k)# q, k, v = [rearrange(x, "b t (h d) -> (b h) t d", h=self.num_heads) for x in [q, k, v]]q, k, v = [rearrange(x, "b t (h d) -> b h t d", h=self.num_heads) for x in [q, k, v]]else:if not _is_profiled():# profiling breaks that propertysomehow.1 unmodified lineassert value is key, "specialized implementation"projected = nn.functional.linear(query, self.in_proj_weight, self.in_proj_bias)if self.kv_repeat == 1:packed = rearrange(projected, "b t (p h d) -> b h p t d", p=3, h=self.num_heads)q, k, v = ops.unbind(packed, dim=2)else:embed_dim = self.embed_dim4 unmodified linesend = start + per_head_dim * kv_headsk = projected[:, :, start: end]v = projected[:, :, end:]q = rearrange(q, "b t (h d) -> b t h d", h=self.num_heads)k = rearrange(k, "b t (h d) -> b t h d", h=kv_heads)v = rearrange(v, "b t (h d) -> b t h d", h=kv_heads)if self.qk_layer_norm is True:assert self.kv_repeat == 1q, k = [rearrange(x, "b t h d -> b t (h d)") for x in [q, k]]q = self.q_layer_norm(q)k = self.k_layer_norm(k)q, k = [rearrange(x, "b t (h d) -> b t h d", h=self.num_heads) for x in [q, k]]if self.rope:assert False, "Not supported for now"q, k = self._apply_rope(q, k)k, v = self._complete_kv(k, v)if self.kv_repeat > 1:3 unmodified linesq, k, v = [x.float() for x in [q, k, v]]if self.memory_efficient:p = self.dropout if self.training else 0x = torch.nn.functional.scaled_dot_product_attention(q, k, v, is_causal=attn_mask is not None, dropout_p=p)else:# We include the dot product as float32, for consistency# with the other implementations that include that step3 unmodified lines# extend a bit the range of operations done in float32,# although this should make no difference.q = q / q.shape[-1] ** 0.5if self._is_streaming and self.safe_streaming and q.device.type == 'cuda':with torch.autocast(device_type=q.device.type, dtype=torch.float32):pre_w = torch.einsum("bqhc,bkhc->bhqk", q, k)else:pre_w = torch.einsum("bqhc,bkhc->bhqk", q, k)if attn_mask is not None:pre_w = pre_w + attn_maskw = torch.softmax(pre_w, dim=-1)w = F.dropout(w, self.dropout, training=self.training).to(v)x = torch.einsum("bhqk,bkhc->bqhc", w, v)x = x.to(dtype)x = rearrange(x, "b h t d -> b t (h d)", h=self.num_heads)x = self.out_proj(x)else:key, value = self._complete_kv(key, value)24 unmodified lines2526272829303132333435363738394041424344454644 unmodified lines919293949596979899100101102103104105106107108109110111112121 unmodified lines2342352362372382392406 unmodified lines24724824925025125225310 unmodified lines2642652662672682692702 unmodified lines2732742752762772782792802812822832842852862872882892902912924 unmodified lines29729829930030130230330430514 unmodified lines32032132232332432532632732832933026 unmodified lines3573583593603613623631 unmodified line3653663673683693703713723733743754 unmodified lines3803813823833843853863873883893903913923933943953963 unmodified lines4004014024034044054064074084094103 unmodified lines41441541641741841942042142242342442542642742842943043143243343424 unmodified linesfrom .rope import RotaryEmbeddingfrom .streaming import StreamingModule_efficient_attention_backend: str = 'torch'def set_efficient_attention_backend(backend: str = 'torch'):# Using torch by default, it seems a bit faster on older P100 GPUs (~20% faster).global _efficient_attention_backendassert _efficient_attention_backend in ['xformers', 'torch']_efficient_attention_backend = backenddef _get_attention_time_dimension() -> int:if _efficient_attention_backend == 'torch':return 2else:return 1def _is_profiled() -> bool:# Return true if we are currently running with a xformers profiler activated.44 unmodified linesdef expand_repeated_kv(x: torch.Tensor, n_rep: int) -> torch.Tensor:"""torch.repeat_interleave(x, dim=2, repeats=n_rep) from xlformers"""if n_rep == 1:return xif _efficient_attention_backend == 'torch':bs, n_kv_heads, slen, head_dim = x.shapereturn (x[:, :, None, :, :].expand(bs, n_kv_heads, n_rep, slen, head_dim).reshape(bs, n_kv_heads * n_rep, slen, head_dim))else:bs, slen, n_kv_heads, head_dim = x.shapereturn (x[:, :, :, None, :].expand(bs, slen, n_kv_heads, n_rep, head_dim).reshape(bs, slen, n_kv_heads * n_rep, head_dim))class LayerScale(nn.Module):121 unmodified lines# Return a causal mask, accounting for potentially stored past keys/values# We actually return a bias for the attention score, as this has the same# convention both in the builtin MHA in Pytorch, and Xformers functions.time_dim = _get_attention_time_dimension()if self.memory_efficient:from xformers.ops import LowerTriangularMaskif current_steps == 1:6 unmodified linesreturn LowerTriangularMask()if self._streaming_state:past_keys = self._streaming_state['past_keys']past_steps = past_keys.shape[time_dim]else:past_steps = 010 unmodified linestorch.full([], float('-inf'), device=device, dtype=dtype))def _complete_kv(self, k, v):time_dim = _get_attention_time_dimension()if self.cross_attention:# With cross attention we assume all keys and values# are already available, and streaming is with respect2 unmodified lines# Complete the key/value pair using the streaming state.if self._streaming_state:pk = self._streaming_state['past_keys']nk = torch.cat([pk, k], dim=time_dim)if v is k:nv = nkelse:pv = self._streaming_state['past_values']nv = torch.cat([pv, v], dim=time_dim)else:nk = knv = vassert nk.shape[time_dim] == nv.shape[time_dim]offset = 0if self.past_context is not None:offset = max(0, nk.shape[time_dim] - self.past_context)if self._is_streaming:self._streaming_state['past_keys'] = nk[:, offset:]if v is not k:4 unmodified linesself._streaming_state['offset'] = torch.tensor(0)return nk, nvdef _apply_rope(self, query: torch.Tensor, key: torch.Tensor):# TODO: fix and verify layout.assert _efficient_attention_backend == 'xformers', 'Rope not supported with torch attn.'# Apply rope embeddings to query and key tensors.assert self.rope is not Noneif 'past_keys' in self._streaming_state:14 unmodified linesassert not is_causal, ("new param added in torch 2.0.1 not supported, ""use the causal args in the constructor.")time_dim = _get_attention_time_dimension()if time_dim == 2:layout = "b h t d"else:layout = "b t h d"dtype = query.dtypeif self._is_streaming:assert self.causal or self.cross_attention, \26 unmodified linesif self.qk_layer_norm is True:q = self.q_layer_norm(q)k = self.k_layer_norm(k)q, k, v = [rearrange(x, f"b t (h d) -> {layout}", h=self.num_heads) for x in [q, k, v]]else:if not _is_profiled():# profiling breaks that propertysomehow.1 unmodified lineassert value is key, "specialized implementation"projected = nn.functional.linear(query, self.in_proj_weight, self.in_proj_bias)if self.kv_repeat == 1:if time_dim == 2:bound_layout = "b h p t d"else:bound_layout = "b t p h d"packed = rearrange(projected, f"b t (p h d) -> {bound_layout}", p=3, h=self.num_heads)q, k, v = ops.unbind(packed, dim=2)else:embed_dim = self.embed_dim4 unmodified linesend = start + per_head_dim * kv_headsk = projected[:, :, start: end]v = projected[:, :, end:]q = rearrange(q, f"b t (h d) -> {layout}", h=self.num_heads)k = rearrange(k, f"b t (h d) -> {layout}", h=kv_heads)v = rearrange(v, f"b t (h d) -> {layout}", h=kv_heads)if self.qk_layer_norm is True:assert self.kv_repeat == 1q, k = [rearrange(x, f"{layout} -> b t (h d)") for x in [q, k]]q = self.q_layer_norm(q)k = self.k_layer_norm(k)q, k = [rearrange(x, f"b t (h d) -> {layout}", h=self.num_heads) for x in [q, k]]if self.rope:q, k = self._apply_rope(q, k)k, v = self._complete_kv(k, v)if self.kv_repeat > 1:3 unmodified linesq, k, v = [x.float() for x in [q, k, v]]if self.memory_efficient:p = self.dropout if self.training else 0if _efficient_attention_backend == 'torch':x = torch.nn.functional.scaled_dot_product_attention(q, k, v, is_causal=attn_mask is not None, dropout_p=p)else:x = ops.memory_efficient_attention(q, k, v, attn_mask, p=p)else:# We include the dot product as float32, for consistency# with the other implementations that include that step3 unmodified lines# extend a bit the range of operations done in float32,# although this should make no difference.q = q / q.shape[-1] ** 0.5key_layout = layout.replace('t', 'k')query_layout = layoutif self._is_streaming and self.safe_streaming and q.device.type == 'cuda':with torch.autocast(device_type=q.device.type, dtype=torch.float32):pre_w = torch.einsum(f"{query_layout},{key_layout}-> b h t k", q, k)else:pre_w = torch.einsum(f"{query_layout},{key_layout}-> b h t k", q, k)if attn_mask is not None:pre_w = pre_w + attn_maskw = torch.softmax(pre_w, dim=-1)w = F.dropout(w, self.dropout, training=self.training).to(v)# Key and value have the same format.x = torch.einsum(f"b h t k, {key_layout} -> {layout}", w, v)x = x.to(dtype)x = rearrange(x, f"{layout} -> b t (h d)", h=self.num_heads)x = self.out_proj(x)else:key, value = self._complete_kv(key, value)
12 unmodified lines1314151617181928 unmodified lines48495012 unmodified linesclass TestSEANetModel:def get_musicgen(self):mg = MusicGen.get_pretrained(name='debug', device='cpu')mg.set_generation_params(duration=2.0)return mgdef test_base(self):28 unmodified lineswav = mg.generate(['youpi', 'lapin dort'])assert list(wav.shape) == [2, 1, 64000]12 unmodified lines1314151617181928 unmodified lines484950515253545556575812 unmodified linesclass TestSEANetModel:def get_musicgen(self):mg = MusicGen.get_pretrained(name='debug', device='cpu')mg.set_generation_params(duration=2.0, extend_stride=2.)return mgdef test_base(self):28 unmodified lineswav = mg.generate(['youpi', 'lapin dort'])assert list(wav.shape) == [2, 1, 64000]def test_generate_long(self):mg = self.get_musicgen()mg.max_duration = 3.mg.set_generation_params(duration=4., extend_stride=2.)wav = mg.generate(['youpi', 'lapin dort'])assert list(wav.shape) == [2, 1, 32000 * 4]
6 unmodified lines789101112131415166 unmodified lines23242526272817 unmodified lines4647484950519 unmodified lines61626364656621 unmodified lines88899091929323 unmodified lines11711811912012112214 unmodified lines1371381391401411426 unmodified lines1491501511521531546 unmodified linesimport torchfrom audiocraft.modules.rope import RotaryEmbeddingfrom audiocraft.modules.transformer import StreamingTransformerdef test_rope():B, T, H, C = 8, 75, 16, 128rope = RotaryEmbedding(dim=C)6 unmodified linesdef test_rope_io_dtypes():B, T, H, C = 8, 75, 16, 128rope_32 = RotaryEmbedding(dim=C, dtype=torch.float32)17 unmodified linesdef test_transformer_with_rope():torch.manual_seed(1234)for pos in ['rope', 'sin_rope']:tr = StreamingTransformer(9 unmodified lines@torch.no_grad()def test_rope_streaming():torch.manual_seed(1234)tr = StreamingTransformer(16, 4, 2, causal=True, dropout=0.,21 unmodified lines@torch.no_grad()def test_rope_streaming_past_context():torch.manual_seed(1234)for context in [None, 10]:23 unmodified linesdef test_rope_memory_efficient():torch.manual_seed(1234)tr = StreamingTransformer(16, 4, 2, custom=True, dropout=0., layer_scale=0.1,14 unmodified linesdef test_rope_with_xpos():B, T, H, C = 8, 75, 16, 128rope = RotaryEmbedding(dim=C, xpos=True)6 unmodified linesdef test_positional_scale():B, T, H, C = 8, 75, 16, 128rope = RotaryEmbedding(dim=C, xpos=True, scale=0.0)6 unmodified lines78910111213141516176 unmodified lines2425262728293017 unmodified lines484950515253549 unmodified lines6465666768697021 unmodified lines9293949596979823 unmodified lines12212312412512612712814 unmodified lines1431441451461471481496 unmodified lines1561571581591601611626 unmodified linesimport torchfrom audiocraft.modules.rope import RotaryEmbeddingfrom audiocraft.modules.transformer import StreamingTransformer, set_efficient_attention_backenddef test_rope():set_efficient_attention_backend('xformers')B, T, H, C = 8, 75, 16, 128rope = RotaryEmbedding(dim=C)6 unmodified linesdef test_rope_io_dtypes():set_efficient_attention_backend('xformers')B, T, H, C = 8, 75, 16, 128rope_32 = RotaryEmbedding(dim=C, dtype=torch.float32)17 unmodified linesdef test_transformer_with_rope():set_efficient_attention_backend('xformers')torch.manual_seed(1234)for pos in ['rope', 'sin_rope']:tr = StreamingTransformer(9 unmodified lines@torch.no_grad()def test_rope_streaming():set_efficient_attention_backend('xformers')torch.manual_seed(1234)tr = StreamingTransformer(16, 4, 2, causal=True, dropout=0.,21 unmodified lines@torch.no_grad()def test_rope_streaming_past_context():set_efficient_attention_backend('xformers')torch.manual_seed(1234)for context in [None, 10]:23 unmodified linesdef test_rope_memory_efficient():set_efficient_attention_backend('xformers')torch.manual_seed(1234)tr = StreamingTransformer(16, 4, 2, custom=True, dropout=0., layer_scale=0.1,14 unmodified linesdef test_rope_with_xpos():set_efficient_attention_backend('xformers')B, T, H, C = 8, 75, 16, 128rope = RotaryEmbedding(dim=C, xpos=True)6 unmodified linesdef test_positional_scale():set_efficient_attention_backend('xformers')B, T, H, C = 8, 75, 16, 128rope = RotaryEmbedding(dim=C, xpos=True, scale=0.0)
8 unmodified lines910111213141570 unmodified lines868788899091929394959697989910010110210310424 unmodified lines12913013113213313413513613713813914014114214314414514614714814915015115215315415515615715845 unmodified lines2042052062072082092108 unmodified linesimport pytestimport torchfrom audiocraft.modules.transformer import StreamingMultiheadAttention, StreamingTransformerdef test_transformer_causal_streaming():70 unmodified linesdef test_memory_efficient():torch.manual_seed(1234)tr = StreamingTransformer(16, 4, 2, custom=True, dropout=0., layer_scale=0.1)tr_mem_efficient = StreamingTransformer(16, 4, 2, dropout=0., memory_efficient=True, layer_scale=0.1)tr_mem_efficient.load_state_dict(tr.state_dict())tr.eval()steps = 12x = torch.randn(3, steps, 16)with torch.no_grad():y = tr(x)y2 = tr_mem_efficient(x)assert torch.allclose(y, y2), (y - y2).norm()def test_attention_as_float32():24 unmodified lines@torch.no_grad()def test_streaming_memory_efficient():torch.manual_seed(1234)tr = StreamingTransformer(16, 4, 2, causal=True, dropout=0., custom=True)tr_mem_efficient = StreamingTransformer(16, 4, 2, dropout=0., memory_efficient=True, causal=True)tr.load_state_dict(tr_mem_efficient.state_dict())tr.eval()tr_mem_efficient.eval()steps = 12x = torch.randn(3, steps, 16)ref = tr(x)with tr_mem_efficient.streaming():outs = []# frame_sizes = [2] + [1] * (steps - 2)frame_sizes = [1] * stepsfor frame_size in frame_sizes:frame = x[:, :frame_size]x = x[:, frame_size:]outs.append(tr_mem_efficient(frame))out = torch.cat(outs, dim=1)delta = torch.norm(out - ref) / torch.norm(out)assert delta < 1e-6, deltadef test_cross_attention():45 unmodified linesy = cross_attn(queries, keys, values)[0]y_ref = ref_attn(queries, keys, values)[0]assert torch.allclose(y, y_ref, atol=1e-7)# Now let's check that streaming is working properly.with cross_attn.streaming():8 unmodified lines91011121314151670 unmodified lines8788899091929394959697989910010110210310410510610710824 unmodified lines13313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316445 unmodified lines2102112122132142152168 unmodified linesimport pytestimport torchfrom audiocraft.modules.transformer import (StreamingMultiheadAttention, StreamingTransformer, set_efficient_attention_backend)def test_transformer_causal_streaming():70 unmodified linesdef test_memory_efficient():torch.manual_seed(1234)for backend in ['torch', 'xformers']:set_efficient_attention_backend(backend)tr = StreamingTransformer(16, 4, 2, custom=True, dropout=0., layer_scale=0.1)tr_mem_efficient = StreamingTransformer(16, 4, 2, dropout=0., memory_efficient=True, layer_scale=0.1)tr_mem_efficient.load_state_dict(tr.state_dict())tr.eval()steps = 12x = torch.randn(3, steps, 16)with torch.no_grad():y = tr(x)y2 = tr_mem_efficient(x)assert torch.allclose(y, y2), ((y - y2).norm(), backend)def test_attention_as_float32():24 unmodified lines@torch.no_grad()def test_streaming_memory_efficient():torch.manual_seed(1234)for backend in ['torch', 'xformers']:set_efficient_attention_backend(backend)tr = StreamingTransformer(16, 4, 2, causal=True, dropout=0., custom=True)tr_mem_efficient = StreamingTransformer(16, 4, 2, dropout=0., memory_efficient=True, causal=True)tr.load_state_dict(tr_mem_efficient.state_dict())tr.eval()tr_mem_efficient.eval()steps = 12x = torch.randn(3, steps, 16)ref = tr(x)with tr_mem_efficient.streaming():outs = []# frame_sizes = [2] + [1] * (steps - 2)frame_sizes = [1] * stepsfor frame_size in frame_sizes:frame = x[:, :frame_size]x = x[:, frame_size:]outs.append(tr_mem_efficient(frame))out = torch.cat(outs, dim=1)delta = torch.norm(out - ref) / torch.norm(out)assert delta < 1e-6, deltadef test_cross_attention():45 unmodified linesy = cross_attn(queries, keys, values)[0]y_ref = ref_attn(queries, keys, values)[0]assert torch.allclose(y, y_ref, atol=1e-7), (y - y_ref).norm() / y_ref.norm()# Now let's check that streaming is working properly.with cross_attn.streaming():
README.md+7-6
app.py+215-87
audiocraft/models/loaders.py-2
audiocraft/models/musicgen.py+82-11
audiocraft/modules/transformer.py+67-27
tests/models/test_musicgen.py+9-1
tests/modules/test_rope.py+9-1
tests/modules/test_transformer.py+40-34