Spaces:
Runtime error
Runtime error
Merge branch 'longgen' into our_hf2
Browse filesFiles changed (5)
12 unmodified lines131415161718192012 unmodified lines
More options when launching Gradio app locally (thanks @ashleykleynhans).
Testing out PyTorch 2.0 memory efficient attention.
## [0.0.1] - 2023-06-09
Initial release, with model evaluation only.14 unmodified lines151617181819202114 unmodified linesfrom audiocraft.data.audio import audio_write
MODEL = NoneIS_SHARED_SPACE = "musicgen/MusicGen" in os.environ['SPACE_ID']IS_SHARED_SPACE = "musicgen/MusicGen" in os.environ.get('SPACE_ID', '')
def load_model(version):5 unmodified lines678910111213141516173 unmodified lines21222324252627282930313233343536373839404142434445464748496 unmodified lines56575859606162336364653566676821 unmodified lines90919293946364656667686970717273747576777879808182838485868788899091929394959697989910095969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461021031041051061071081091101111121131141151161471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102111181191201211221231241251262121281291302132141322152162172182192202212225 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 lines
MODEL = None
_old_call = sp.call
def _call_nostderr(*args, **kwargs): # Avoid ffmpeg vomitting on the logs. kwargs['stderr'] = sp.DEVNULL kwargs['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 out
def load_model(): print("Loading model")6 unmodified lines MODEL = load_model()
duration = 12 max_text_length = 512 texts = [text[:max_text_length] for text in texts] MODEL.set_generation_params(duration=duration)
print(texts, melodies) 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 = 32000 target_ac = 1 for melody in melodies:21 unmodified lines 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]] waveform_video = gr.make_waveform(file.name) out_files.append(waveform_video) return [out_files]
with gr.Blocks() as demo: gr.Markdown( """ # MusicGen
This is the demo for [MusicGen](https://github.com/facebookresearch/audiocraft), a simple and controllable model for music generation presented 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", print("batch finished", len(texts), time.time() - be) return res
def ui(**kwargs): with gr.Blocks() as demo: gr.Markdown( """ # MusicGen
This is the demo for [MusicGen](https://github.com/facebookresearch/audiocraft), a simple and controllable model for music generation presented 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, ], ], [ "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] inputs=[text, melody], outputs=[output] ) gr.Markdown(""" ### More details
The 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 interface launch_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_name
if username and password: launch_kwargs['auth'] = (username, password) if server_port > 0: launch_kwargs['server_port'] = server_port if inbrowser: launch_kwargs['inbrowser'] = inbrowser if share: launch_kwargs['share'] = share demo.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' ) gr.Markdown(""" ### More details
The 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. """) args = parser.parse_args()
demo.queue(max_size=60).launch() ui( username=args.username, password=args.password, inbrowser=args.inbrowser, server_port=args.server_port, share=args.share, listen=args.listen )95 unmodified lines96979899991001011026 unmodified lines10911011111211311411511311611711811912012195 unmodified lines def 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): two_step_cfg: bool = False, extend_stride: float = 15): """Set the generation parameters for MusicGen.
Args:6 unmodified lines two_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 things are padded but seems to have little impact in practice. extend_stride: when doing extended generation (i.e. more than 30 seconds), by how much should we extend the audio each time. Larger values will mean less context is preserved, and shorter value will require extra computations. """ assert duration <= 30, "The MusicGen cannot generate more than 30 seconds" # 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_stride self.generation_params = { 'max_gen_len': int(duration * self.frame_rate), 'use_sampling': use_sampling,246 unmodified lines2472482492502502512522532542552552562572582592602602612622632632642652664 unmodified lines27127227327427527627748 unmodified lines3263273283283293303313321 unmodified line33433533633633733833934015 unmodified lines3563573583593603613623 unmodified lines36636736836736937037137237314 unmodified lines388389390388391392393394246 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) nk = torch.cat([pk, k], dim=2) if v is k: nv = nk else: pv = self._streaming_state['past_values'] nv = torch.cat([pv, v], dim=1) nv = torch.cat([pv, v], dim=2) else: nk = k nv = v
assert nk.shape[1] == nv.shape[1] assert nk.shape[2] == nv.shape[2] offset = 0 if self.past_context is not None: offset = max(0, nk.shape[1] - self.past_context) 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 lines self._streaming_state['offset'] = torch.tensor(0) return nk, nv
def _apply_rope(self, query: torch.Tensor, key: torch.Tensor): # Apply rope embeddings to query and key tensors. assert self.rope is not None48 unmodified lines 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 t h 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 line assert 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) 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 lines 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 lines q, k, v = [x.float() for x in [q, k, v]] if self.memory_efficient: p = self.dropout if self.training else 0 x = ops.memory_efficient_attention(q, k, v, attn_mask, p=p) x = 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 lines 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 t h d -> b t (h d)", h=self.num_heads) 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