Spaces:
Build error
Build error
Merge branch 'longgen' into our_hf2
Browse filesFiles changed (8)
4 unmodified lines567889101142 unmodified lines54555657585960615758596061626364654 unmodified lines - "music generation" - "language models" - "LLMs"app_file: "app_batched.py"app_file: "app.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).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 regularly updated with contributions from @camenduru and the community.
## API
12312356745678991011121314151617181913142021222324171825262728293031323334353637383940414243444546212223474849505126525354555657585960616263282930313233343536373839404164656667686970717273747576777879808182838485864344454647484950515253878889909192939456959697989910010110210310410510610710810911011111211311411511611711811912012112212358596061626364124125126127128129130131132133134671351361371381392 unmodified lines14214314476777879808182831451461471 unmodified line149150151152153154155156941571581591601 unmodified line16216316410216516610416716816917029 unmodified lines20020120214020320420520620720820921021121210 unmodified lines2232242251571581591601611621631642262271662281681691701711721731741752292302312322332341772352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962971 unmodified line29930030130230330430530630730830917 unmodified lines327328329209210211212213214215216330331332333334335336337338339340341342343344"""Copyright (c) Meta Platforms, Inc. and affiliates.All rights reserved.# 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."""# 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.
from tempfile import NamedTemporaryFileimport argparsefrom concurrent.futures import ProcessPoolExecutorimport osimport subprocess as spfrom tempfile import NamedTemporaryFileimport timeimport warnings
import torchimport gradio as grimport osfrom audiocraft.models import MusicGen
from audiocraft.data.audio_utils import convert_audiofrom audiocraft.data.audio import audio_writefrom audiocraft.models import MusicGen
MODEL = NoneIS_SHARED_SPACE = "musicgen/MusicGen" in os.environ.get('SPACE_ID', '')
MODEL = 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.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_nostderr# Preallocating the pool of processes.pool = ProcessPoolExecutor(4)pool.__enter__()
def load_model(version): print("Loading model", version) return MusicGen.get_pretrained(version)
def interrupt(): global INTERRUPTING INTERRUPTING = True
def predict(model, text, melody, duration, topk, topp, temperature, cfg_coef):def 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 out
def load_model(version='melody'): global MODEL topk = 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, ) print("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 = 32000 target_ac = 1 for 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 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 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: output = MODEL.generate(descriptions=[text], progress=False) 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 res
def predict_batched(texts, melodies): max_text_length = 512 texts = [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 INTERRUPTING INTERRUPTING = False topk = int(topk) load_model(model)
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_video 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(**kwargs):
def ui_full(launch_kwargs): with gr.Blocks() as interface: gr.Markdown( """2 unmodified lines presented 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 line melody = 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=30, value=10, label="Duration", interactive=True) 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 line cfg_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]) submit.click(predict_full, inputs=[model, text, melody, duration, topk, topp, temperature, cfg_coef], outputs=[output]) gr.Examples( fn=predict, fn=predict_full, examples=[ [ "An 80s driving pop song with heavy drums and synth pads in the background",29 unmodified lines ### More details
The model will generate a short music extract based on the description you provided. You can generate up to 30 seconds of audio. The model can generate up to 30 seconds of audio in one pass. It is now possible to 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 also decide 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 seconds is 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 """ )
# 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') interface.queue().launch(**launch_kwargs)
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'] = sharedef ui_batched(launch_kwargs): with gr.Blocks() as demo: gr.Markdown( """ # MusicGen
interface.queue().launch(**launch_kwargs, max_threads=1) 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/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 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. """)
demo.queue(max_size=8 * 4).launch(**launch_kwargs)
if __name__ == "__main__":1 unmodified line parser.add_argument( '--listen', type=str,<<<<<<< HEAD default='0.0.0.0',======= default='0.0.0.0' if 'SPACE_ID' in os.environ else '127.0.0.1',>>>>>>> longgen help='IP to listen on for connections to Gradio', ) parser.add_argument(17 unmodified lines
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 ) 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_port if args.inbrowser: launch_kwargs['inbrowser'] = args.inbrowser if args.share: launch_kwargs['share'] = args.share
# Show the interface if IS_BATCHED: ui_batched(launch_kwargs) else: ui_full(launch_kwargs)79 unmodified lines808182838483848579 unmodified lines cfg = OmegaConf.create(pkg['xp.cfg']) cfg.device = str(device) if cfg.device == 'cpu': cfg.transformer_lm.memory_efficient = False cfg.transformer_lm.custom = True cfg.dtype = 'float32' else: cfg.dtype = 'float16'35 unmodified lines363738393940414243444546474849505116 unmodified lines68697068717273741 unmodified line76777879808182838485868717 unmodified lines1051061079910810911011110 unmodified lines1221231241161171251261271281201291301312 unmodified lines134135136137138139140141142143136 unmodified lines28028128228328428528628728828929029129229327229429529627529729829930030130230330428228328430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835 unmodified lines used to map audio to invertible discrete representations. lm (LMModel): Language model over discrete representations. """ def __init__(self, name: str, compression_model: CompressionModel, lm: LMModel): def __init__(self, name: str, compression_model: CompressionModel, lm: LMModel, max_duration: float = 30): self.name = name self.compression_model = compression_model self.lm = lm self.max_duration = max_duration self.device = next(iter(lm.parameters())).device self.generation_params: dict = {} self.set_generation_params(duration=15) # 15 seconds by default self._progress_callback: tp.Optional[tp.Callable[[int, int], None]] = None if self.device.type == 'cpu': self.autocast = TorchAutocast(enabled=False) else:16 unmodified lines return self.compression_model.channels
@staticmethod def get_pretrained(name: str = 'melody', device='cuda'): def 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 tests compression_model = get_debug_compression_model(device)17 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, extend_stride: float = 15): two_step_cfg: bool = False, extend_stride: float = 18): """Set the generation parameters for MusicGen.
Args:10 unmodified lines 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 extend_stride <= 25, "Keep at least 5 seconds of overlap!" assert extend_stride < self.max_duration, "Cannot stride by more than max generation duration." self.extend_stride = extend_stride self.duration = duration self.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 set_custom_progress_callback(self, progress_callback: tp.Optional[tp.Callable[[int, int], None]] = None): """Override the default progress callback.""" self._progress_callback = progress_callback
def generate_unconditional(self, num_samples: int, progress: bool = False) -> torch.Tensor: """Generate samples in an unconditional manner.
136 unmodified lines Returns: 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 = 0
def _progress_callback(generated_tokens: int, tokens_to_generate: int): generated_tokens += current_gen_offset if 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} / {tokens_to_generate: 6d}', end='\r') print(f'{generated_tokens: 6d} / {total_gen_len: 6d}', end='\r')
if prompt_tokens is not None: assert self.generation_params['max_gen_len'] > prompt_tokens.shape[-1], \ assert max_prompt_len >= prompt_tokens.shape[-1], \ "Prompt is longer than audio to generate"
callback = None if progress: callback = _progress_callback
if self.duration <= self.max_duration: # generate by sampling from LM with self.autocast: gen_tokens = self.lm.generate(prompt_tokens, attributes, callback=callback, **self.generation_params) # 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 = 0 else: 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_rate chunk_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_tokens
gen_tokens = torch.cat(all_tokens, dim=-1)
# generate audio assert gen_tokens.dim() == 324 unmodified lines2526272829303132333435363738394041424344454644 unmodified lines919293789495969798991001011021031048182838485105106107108109110111112121 unmodified lines2342352362372382392406 unmodified lines24724824922525025125225310 unmodified lines2642652662672682692702 unmodified lines2732742752502762772782792802552812822832842852602862872882632892902912924 unmodified lines29729829927430030130230330430514 unmodified lines32032132232332432532632732832933026 unmodified lines3573583593283293603613623631 unmodified line3653663673683693703713373723733743754 unmodified lines3803813823483493503833843853863873883543893903913573923933593943953963 unmodified lines4004014024033693704044054064074084094103 unmodified lines41441541641741841942038242142238442342442542642738942842943039143143243343424 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_backend assert _efficient_attention_backend in ['xformers', 'torch'] _efficient_attention_backend = backend
def _get_attention_time_dimension() -> int: if _efficient_attention_backend == 'torch': return 2 else: return 1
def _is_profiled() -> bool: # Return true if we are currently running with a xformers profiler activated.44 unmodified lines
def 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.shape if n_rep == 1: return x if _efficient_attention_backend == 'torch': bs, n_kv_heads, slen, head_dim = x.shape return ( 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.shape return ( x[:, :, :, None, :] .expand(bs, slen, n_kv_heads, n_rep, head_dim) .reshape(bs, slen, n_kv_heads * n_rep, head_dim) ) return ( 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 LowerTriangularMask if current_steps == 1:6 unmodified lines return LowerTriangularMask() if self._streaming_state: past_keys = self._streaming_state['past_keys'] past_steps = past_keys.shape[1] past_steps = past_keys.shape[time_dim] else: past_steps = 0
10 unmodified lines torch.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=2) nk = torch.cat([pk, k], dim=time_dim) if v is k: nv = nk else: pv = self._streaming_state['past_values'] nv = torch.cat([pv, v], dim=2) nv = torch.cat([pv, v], dim=time_dim) else: nk = k nv = v
assert nk.shape[2] == nv.shape[2] assert nk.shape[time_dim] == nv.shape[time_dim] offset = 0 if self.past_context is not None: offset = max(0, nk.shape[2] - self.past_context) 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 lines self._streaming_state['offset'] = torch.tensor(0) return nk, nv
def _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 None if 'past_keys' in self._streaming_state:14 unmodified lines assert 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.dtype if self._is_streaming: assert self.causal or self.cross_attention, \26 unmodified lines if 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]] 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 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: if time_dim == 2: bound_layout = "b h p t d" else: bound_layout = "b t p h d" packed = rearrange(projected, "b t (p h d) -> b h p t d", p=3, h=self.num_heads) 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 lines end = start + per_head_dim * kv_heads k = 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) 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 == 1 q, k = [rearrange(x, "b t h d -> b t (h d)") for x in [q, k]] q, 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, "b t (h d) -> b t h d", h=self.num_heads) for x in [q, k]] q, k = [rearrange(x, f"b t (h d) -> {layout}", 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 if _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) 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.5 key_layout = layout.replace('t', 'k') query_layout = layout if 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) pre_w = torch.einsum(f"{query_layout},{key_layout}-> b h t k", q, k) else: pre_w = torch.einsum("bqhc,bkhc->bhqk", q, k) 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_mask w = 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) # 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, "b h t d -> b t (h d)", h=self.num_heads) 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 lines131415161617181928 unmodified lines484950515253545556575812 unmodified linesclass TestSEANetModel: def get_musicgen(self): mg = MusicGen.get_pretrained(name='debug', device='cpu') mg.set_generation_params(duration=2.0) mg.set_generation_params(duration=2.0, extend_stride=2.) return mg
def test_base(self):28 unmodified lines wav = 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 lines7891010111213141516176 unmodified lines2425262728293017 unmodified lines484950515253549 unmodified lines6465666768697021 unmodified lines9293949596979823 unmodified lines12212312412512612712814 unmodified lines1431441451461471481496 unmodified lines1561571581591601611626 unmodified linesimport torch
from audiocraft.modules.rope import RotaryEmbeddingfrom audiocraft.modules.transformer import StreamingTransformerfrom audiocraft.modules.transformer import StreamingTransformer, set_efficient_attention_backend
def test_rope(): set_efficient_attention_backend('xformers') B, T, H, C = 8, 75, 16, 128
rope = RotaryEmbedding(dim=C)6 unmodified lines
def test_rope_io_dtypes(): set_efficient_attention_backend('xformers') B, T, H, C = 8, 75, 16, 128
rope_32 = RotaryEmbedding(dim=C, dtype=torch.float32)17 unmodified lines
def 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 lines
def 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 lines
def test_rope_with_xpos(): set_efficient_attention_backend('xformers') B, T, H, C = 8, 75, 16, 128
rope = RotaryEmbedding(dim=C, xpos=True)6 unmodified lines
def test_positional_scale(): set_efficient_attention_backend('xformers') B, T, H, C = 8, 75, 16, 128
rope = RotaryEmbedding(dim=C, xpos=True, scale=0.0)8 unmodified lines9101112121314151670 unmodified lines878889899091929394959690919293949596979899100101989910010110210310410510610710824 unmodified lines13313413513613713213313413513613713813913813914014114214314414514614114714814314414514614915015115215314814915015115415515615715815315415515916016116216316445 unmodified lines2102112122072132142152168 unmodified linesimport pytestimport torch
from audiocraft.modules.transformer import StreamingMultiheadAttention, StreamingTransformerfrom audiocraft.modules.transformer import ( StreamingMultiheadAttention, StreamingTransformer, set_efficient_attention_backend)
def test_transformer_causal_streaming():70 unmodified lines
def 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 = 12 x = torch.randn(3, steps, 16) 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 = 12 x = 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() 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 = 12 x = torch.randn(3, steps, 16) 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 = 12 x = torch.randn(3, steps, 16)
ref = tr(x) ref = tr(x)
with tr_mem_efficient.streaming(): outs = [] # frame_sizes = [2] + [1] * (steps - 2) frame_sizes = [1] * steps with tr_mem_efficient.streaming(): outs = [] # frame_sizes = [2] + [1] * (steps - 2) frame_sizes = [1] * steps
for frame_size in frame_sizes: frame = x[:, :frame_size] x = x[:, frame_size:] outs.append(tr_mem_efficient(frame)) for 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, delta out = torch.cat(outs, dim=1) delta = torch.norm(out - ref) / torch.norm(out) assert delta < 1e-6, delta
def test_cross_attention():45 unmodified lines
y = cross_attn(queries, keys, values)[0] y_ref = ref_attn(queries, keys, values)[0] assert torch.allclose(y, y_ref, atol=1e-7) 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