Spaces:
Runtime error
Runtime error
Merge branch 'longgen' into our_hf2
Browse filesFiles changed (5)
12 unmodified lines13141516171812 unmodified linesMore options when launching Gradio app locally (thanks @ashleykleynhans).## [0.0.1] - 2023-06-09Initial release, with model evaluation only.12 unmodified lines131415161718192012 unmodified linesMore options when launching Gradio app locally (thanks @ashleykleynhans).Testing out PyTorch 2.0 memory efficient attention.## [0.0.1] - 2023-06-09Initial release, with model evaluation only.
14 unmodified lines1516171819202114 unmodified linesfrom audiocraft.data.audio import audio_writeMODEL = NoneIS_SHARED_SPACE = "musicgen/MusicGen" in os.environ['SPACE_ID']def load_model(version):14 unmodified lines1516171819202114 unmodified linesfrom audiocraft.data.audio import audio_writeMODEL = NoneIS_SHARED_SPACE = "musicgen/MusicGen" in os.environ.get('SPACE_ID', '')def load_model(version):
5 unmodified lines67891011123 unmodified lines1617181920216 unmodified lines282930313233343536373821 unmodified lines606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311325 unmodified linesLICENSE file in the root directory of this source tree."""from tempfile import NamedTemporaryFileimport torchimport gradio as grfrom audiocraft.data.audio_utils import convert_audio3 unmodified linesMODEL = Nonedef load_model():print("Loading model")6 unmodified linesMODEL = load_model()duration = 12MODEL.set_generation_params(duration=duration)print(texts, melodies)processed_melodies = []target_sr = 32000target_ac = 1for melody in melodies:21 unmodified linesaudio_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)out_files.append(waveform_video)return [out_files]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/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>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, inputs=[text, melody], outputs=[output], batch=True, max_batch_size=12)gr.Examples(fn=predict,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=60).launch()5 unmodified lines678910111213141516173 unmodified lines21222324252627282930313233343536373839404142434445464748496 unmodified lines5657585960616263646566676821 unmodified lines909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212225 unmodified linesLICENSE file in the root directory of this source tree."""import argparsefrom concurrent.futures import ProcessPoolExecutorimport subprocess as spfrom tempfile import NamedTemporaryFileimport timeimport warningsimport torchimport gradio as grfrom audiocraft.data.audio_utils import convert_audio3 unmodified linesMODEL = None_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_nostderrpool = ProcessPoolExecutor(3)pool.__enter__()def make_waveform(*args, **kwargs):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():print("Loading model")6 unmodified linesMODEL = load_model()duration = 12max_text_length = 512texts = [text[:max_text_length] for text in texts]MODEL.set_generation_params(duration=duration)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:21 unmodified linesaudio_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 ui(**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/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>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, inputs=[text, melody], outputs=[output], batch=True, max_batch_size=8)gr.Examples(fn=predict,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.""")# 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'] = sharedemo.queue(max_size=8 * 4).launch(**launch_kwargs)if __name__ == "__main__":parser = argparse.ArgumentParser()parser.add_argument('--listen',type=str,default='127.0.0.1',help='IP to listen on for connections to Gradio',)parser.add_argument('--username', type=str, default='', help='Username for authentication')parser.add_argument('--password', type=str, default='', help='Password for authentication')parser.add_argument('--server_port',type=int,default=0,help='Port to run the server listener on',)parser.add_argument('--inbrowser', action='store_true', help='Open in browser')parser.add_argument('--share', action='store_true', help='Share the gradio UI')args = parser.parse_args()ui(username=args.username,password=args.password,inbrowser=args.inbrowser,server_port=args.server_port,share=args.share,listen=args.listen)
95 unmodified lines969798991001011026 unmodified lines10911011111211311411511695 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):"""Set the generation parameters for MusicGen.Args:6 unmodified linestwo_step_cfg (bool, optional): If True, performs 2 forward for Classifier Free Guidance,instead of batching together the two. This has some impact on how thingsare padded but seems to have little impact in practice."""assert duration <= 30, "The MusicGen cannot generate more than 30 seconds"self.generation_params = {'max_gen_len': int(duration * self.frame_rate),'use_sampling': use_sampling,95 unmodified lines969798991001011026 unmodified lines10911011111211311411511611711811912012195 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:6 unmodified linestwo_step_cfg (bool, optional): If True, performs 2 forward for Classifier Free Guidance,instead of batching together the two. This has some impact on how thingsare padded but seems to have little impact in practice.extend_stride: when doing extended generation (i.e. more than 30 seconds), by how muchshould 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,
246 unmodified lines2472482492502512522532542552562572582592602612622632642652664 unmodified lines27127227327427527648 unmodified lines3253263273283293303311 unmodified line33333433533633733833915 unmodified lines3553563573583593603 unmodified lines36436536636736836937014 unmodified lines385386387388389390391246 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=1)if v is k:nv = nkelse:pv = self._streaming_state['past_values']nv = torch.cat([pv, v], dim=1)else:nk = knv = vassert nk.shape[1] == nv.shape[1]offset = 0if self.past_context is not None:offset = max(0, nk.shape[1] - 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 None48 unmodified linesq = 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 t h 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 t p h d", p=3, h=self.num_heads)q, k, v = ops.unbind(packed, dim=2)else:embed_dim = self.embed_dim15 unmodified linesk = 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: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 = 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 step14 unmodified linesw = 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 t h d -> b t (h d)", h=self.num_heads)x = self.out_proj(x)else:key, value = self._complete_kv(key, value)246 unmodified lines2472482492502512522532542552562572582592602612622632642652664 unmodified lines27127227327427527627748 unmodified lines3263273283293303313321 unmodified line33433533633733833934015 unmodified lines3563573583593603613623 unmodified lines36636736836937037137237314 unmodified lines388389390391392393394246 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 None48 unmodified linesq = 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_dim15 unmodified linesk = 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 step14 unmodified linesw = 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)
CHANGELOG.md+2
app.py+1-1
app_batched.py+158-68
audiocraft/models/musicgen.py+7-2
audiocraft/modules/transformer.py+11-8