Spaces:
Runtime error
Runtime error
Merge branch 'main' into our_hf2
Browse filesFiles changed (11)
3 unmodified lines456778910111213141516179183 unmodified lines
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [0.0.1a] - TBD## [0.0.2a] - TBD
Improved demo, fixed top p (thanks @jnordberg).
Compressor tanh on output to avoid clipping with some style (especially piano).Now repeating the conditioning periodically if it is too short.
More options when launching Gradio app locally (thanks @ashleykleynhans).
## [0.0.1] - 2023-06-09
Initial release, with model evaluation only.Initial release, with model evaluation only.51 unmodified lines52535455555657583 unmodified lines626364656566676851 unmodified lines
## Training datasets
The model was trained using the following sources: the [Meta Music Initiative Sound Collection](https://www.fb.com/sound), [Shutterstock music collection](https://www.shutterstock.com/music) and the [Pond5 music collection](https://www.pond5.com/). See the paper for more details about the training set and corresponding preprocessing.The model was trained on licensed data using the following sources: the [Meta Music Initiative Sound Collection](https://www.fb.com/sound), [Shutterstock music collection](https://www.shutterstock.com/music) and the [Pond5 music collection](https://www.pond5.com/). See the paper for more details about the training set and corresponding preprocessing.
## Quantitative analysis
3 unmodified lines
**Data:** The data sources used to train the model are created by music professionals and covered by legal agreements with the right holders. The model is trained on 20K hours of data, we believe that scaling the model on larger datasets can further improve the performance of the model.
**Mitigations:** All vocals have been removed from the data source using a state-of-the-art music source separation method, namely using the open source [Hybrid Transformer for Music Source Separation](https://github.com/facebookresearch/demucs) (HT-Demucs). The model is therefore not able to produce vocals.**Mitigations:** Vocals have been removed from the data source using corresponding tags, and then using using a state-of-the-art music source separation method, namely using the open source [Hybrid Transformer for Music Source Separation](https://github.com/facebookresearch/demucs) (HT-Demucs).
**Limitations:**
23 unmodified lines24252627272829303132323334351 unmodified line37383940414243448 unmodified lines5354555456575859606162636410 unmodified lines757677717879808115 unmodified lines979899931001011021038 unmodified lines11211311411511611711811912012112223 unmodified lines## MusicGen
Audiocraft provides the code and models for MusicGen, [a simple and controllable model for music generation][arxiv]. MusicGen is a single stage auto-regressiveTransformer model trained over a 32kHz <a href="https://github.com/facebookresearch/encodec">EnCodec tokenizer</a> with 4 codebooks sampled at 50 Hz. Unlike existing methods like [MusicLM](https://arxiv.org/abs/2301.11325), MusicGen doesn't not require a self-supervised semantic representation, and it generatesTransformer model trained over a 32kHz <a href="https://github.com/facebookresearch/encodec">EnCodec tokenizer</a> with 4 codebooks sampled at 50 Hz. Unlike existing methods like [MusicLM](https://arxiv.org/abs/2301.11325), MusicGen doesn't require a self-supervised semantic representation, and it generatesall 4 codebooks in one pass. By introducing a small delay between the codebooks, we show we can predictthem in parallel, thus having only 50 auto-regressive steps per second of audio.Check out our [sample page][musicgen_samples] or test the available demo!
<a target="_blank" href="https://colab.research.google.com/drive/1fxGqfg96RBUvGxZ1XXN07s3DthrKUl4-?usp=sharing"><a target="_blank" href="https://colab.research.google.com/drive/1-Xe9NCdIs2sCUbiSmwHXozK6AAhMm7_i?usp=sharing"> <img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a><a target="_blank" href="https://huggingface.co/spaces/facebook/MusicGen">1 unmodified line</a><br>
We use 20K hours of licensed music to train MusicGen. Specifically, we rely on an internal dataset of 10K high-quality music tracks, and on the ShutterStock and Pond5 music data.
## InstallationAudiocraft requires Python 3.9, PyTorch 2.0.0, and a GPU with at least 16 GB of memory (for the medium-sized model). To install Audiocraft, you can run the following:
8 unmodified lines```
## UsageYou 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). Finally, a demo is also available on the [`facebook/MusiGen` HugginFace Space](https://huggingface.co/spaces/facebook/MusicGen) (huge thanks to all the HF team for their support).We 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).
## API
10 unmodified lines**Note**: Please make sure to have [ffmpeg](https://ffmpeg.org/download.html) installed when using newer version of `torchaudio`.You can install it with:```apt get install ffmpegapt-get install ffmpeg```
See after a quick example for using the API.15 unmodified lines
for idx, one_wav in enumerate(wav): # Will save under {idx}.wav, with loudness normalization at -14 db LUFS. audio_write(f'{idx}', one_wav.cpu(), model.sample_rate, strategy="loudness") audio_write(f'{idx}', one_wav.cpu(), model.sample_rate, strategy="loudness", loudness_compressor=True)```
8 unmodified linesYes. We will soon release the training code for MusicGen and EnCodec.
#### I need help on Windows
@FurkanGozukara made a complete tutorial for [Audiocraft/MusicGen on Windows](https://youtu.be/v-YpvPkhdO4)
## Citation```@article{copet2023simple,6 unmodified lines789101112131413151616171819202135 unmodified lines5758595960616263646566676465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551566970717273747515715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618777787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261881891901911921931281291301311321331341351361371381391401411421431441451461471941951961971981992002012022032042052061502072082092102112122132142152166 unmodified lines"""
from tempfile import NamedTemporaryFileimport argparseimport torchimport gradio as grimport osfrom audiocraft.models import MusicGen
from audiocraft.data.audio import audio_write
MODEL = NoneIS_SHARED_SPACE = "musicgen/MusicGen" in os.environ['SPACE_ID']
def load_model(version):35 unmodified lines
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", add_suffix=False) 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 ui(**kwargs):with gr.Blocks() as demo: gr.Markdown( """ # MusicGen with gr.Blocks() as interface: gr.Markdown( """ # MusicGen This is your private 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) """ ) 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(): text = gr.Text(label="Input Text", interactive=True) melody = 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) temperature = gr.Number(label="Temperature", value=1.0, interactive=True) 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]) gr.Examples( fn=predict, examples=[ [ "An 80s driving pop song with heavy drums and synth pads in the background", "./assets/bach.mp3", "melody" ], [ "A cheerful country song with acoustic guitars", "./assets/bolero_ravel.mp3", "melody" ], [ "90s rock song with electric guitar and heavy drums", None, "medium" ], [ "a light and cheerly EDM track, with syncopated drums, aery pads, and strong emotions", "./assets/bach.mp3", "melody" ], [ "lofi slow bpm electro chill with organic samples", None, "medium", ], ], inputs=[text, melody, model], outputs=[output] ) gr.Markdown( """ ### 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.
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. 2. Small -- a 300M transformer decoder conditioned on text only. 3. Medium -- a 1.5B transformer decoder conditioned on text only. 4. Large -- a 3.3B transformer decoder conditioned on text only (might OOM for the longest sequences.)
When using `melody`, ou 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.
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. """ )
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> """ # 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
interface.queue().launch(**launch_kwargs, max_threads=1)
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', ) with gr.Row(): with gr.Column(): with gr.Row(): text = gr.Text(label="Input Text", interactive=True) melody = 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) temperature = gr.Number(label="Temperature", value=1.0, interactive=True) 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]) gr.Examples( fn=predict, examples=[ [ "An 80s driving pop song with heavy drums and synth pads in the background", "./assets/bach.mp3", "melody" ], [ "A cheerful country song with acoustic guitars", "./assets/bolero_ravel.mp3", "melody" ], [ "90s rock song with electric guitar and heavy drums", None, "medium" ], [ "a light and cheerly EDM track, with syncopated drums, aery pads, and strong emotions", "./assets/bach.mp3", "melody" ], [ "lofi slow bpm electro chill with organic samples", None, "medium", ], ], inputs=[text, melody, model], outputs=[output] parser.add_argument( '--username', type=str, default='', help='Username for authentication' ) parser.add_argument( '--password', type=str, default='', help='Password for authentication' ) gr.Markdown( """ ### 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.
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. 2. Small -- a 300M transformer decoder conditioned on text only. 3. Medium -- a 1.5B transformer decoder conditioned on text only. 4. Large -- a 3.3B transformer decoder conditioned on text only (might OOM for the longest sequences.)
When using `melody`, ou 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.
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. """ 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' )
demo.launch() 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 )56 unmodified lines5758596060616263646556 unmodified lines 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", add_suffix=False) 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) out_files.append(waveform_video) return [out_files]6 unmodified lines78910106 unmodified lines# flake8: noqafrom . import data, modules, models
__version__ = '0.0.1'__version__ = '0.0.2a1'154 unmodified lines15515615715815916016112 unmodified lines174175176177176178179180181154 unmodified lines format: str = 'wav', mp3_rate: int = 320, normalize: bool = True, strategy: str = 'peak', peak_clip_headroom_db: float = 1, rms_headroom_db: float = 18, loudness_headroom_db: float = 14, loudness_compressor: bool = False, log_clipping: bool = True, make_parent_dir: bool = True, add_suffix: bool = True) -> Path: """Convenience function for saving audio to disk. Returns the filename the audio was written to.12 unmodified lines rms_headroom_db (float): Headroom in dB when doing 'rms' strategy. This must be much larger than the `peak_clip` one to avoid further clipping. loudness_headroom_db (float): Target loudness for loudness normalization. loudness_compressor (bool): Uses tanh for soft clipping when strategy is 'loudness'. log_clipping (bool): If True, basic logging on stderr when clipping still when strategy is 'loudness'log_clipping (bool): If True, basic logging on stderr when clipping still occurs despite strategy (only for 'rms'). make_parent_dir (bool): Make parent directory if it doesn't exist. Returns:53 unmodified lines545556575857585960611 unmodified line636465666768697 unmodified lines777879808182838411 unmodified lines96979899961001011021039 unmodified lines11311411511611711811917 unmodified lines13713813913514014114214353 unmodified lines return wav
def normalize_loudness(wav: torch.Tensor, sample_rate: int, loudness_headroom_db: float = 12, energy_floor: float = 2e-3):def normalize_loudness(wav: torch.Tensor, sample_rate: int, loudness_headroom_db: float = 14, loudness_compressor: bool = False, energy_floor: float = 2e-3): """Normalize an input signal to a user loudness in dB LKFS. Audio loudness is defined according to the ITU-R BS.1770-4 recommendation.
1 unmodified line wav (torch.Tensor): Input multichannel audio data. sample_rate (int): Sample rate. loudness_headroom_db (float): Target loudness of the output in dB LUFS. loudness_compressor (bool): Uses tanh for soft clipping. energy_floor (float): anything below that RMS level will not be rescaled. Returns: output (torch.Tensor): Loudness normalized output data.7 unmodified lines delta_loudness = -loudness_headroom_db - input_loudness_db gain = 10.0 ** (delta_loudness / 20.0) output = gain * wav if loudness_compressor: output = torch.tanh(output) assert output.isfinite().all(), (input_loudness_db, wav.pow(2).mean().sqrt()) return output
11 unmodified linesdef normalize_audio(wav: torch.Tensor, normalize: bool = True, strategy: str = 'peak', peak_clip_headroom_db: float = 1, rms_headroom_db: float = 18, loudness_headroom_db: float = 14, loudness_compressor: bool = False, log_clipping: bool = False, log_clipping: bool = False, sample_rate: tp.Optional[int] = None, sample_rate: tp.Optional[int] = None, stem_name: tp.Optional[str] = None) -> torch.Tensor: """Normalize the audio according to the prescribed strategy (see after).
9 unmodified lines rms_headroom_db (float): Headroom in dB when doing 'rms' strategy. This must be much larger than the `peak_clip` one to avoid further clipping. loudness_headroom_db (float): Target loudness for loudness normalization. loudness_compressor (bool): If True, uses tanh based soft clipping. log_clipping (bool): If True, basic logging on stderr when clipping still occurs despite strategy (only for 'rms'). sample_rate (int): Sample rate for the audio data (required for loudness).17 unmodified lines _clip_wav(wav, log_clipping=log_clipping, stem_name=stem_name) elif strategy == 'loudness': assert sample_rate is not None, "Loudness normalization requires sample rate." wav = normalize_loudness(wav, sample_rate, loudness_headroom_db) wav = normalize_loudness(wav, sample_rate, loudness_headroom_db, loudness_compressor) _clip_wav(wav, log_clipping=log_clipping, stem_name=stem_name) else: assert wav.abs().max() < 187 unmodified lines888990919293949587 unmodified lines cache_dir = os.environ.get('MUSICGEN_ROOT', None) compression_model = load_compression_model(name, device=device, cache_dir=cache_dir) lm = load_lm_model(name, device=device, cache_dir=cache_dir) if name == 'melody': lm.condition_provider.conditioners['self_wav'].match_len_on_eval = True
return MusicGen(name, compression_model, lm)
8 unmodified lines9101112131415469 unmodified lines48548648748748848949049144 unmodified lines5365375385385395405415425435445458 unmodified linesfrom dataclasses import dataclass, fieldfrom itertools import chainimport loggingimport mathimport randomimport reimport typing as tp469 unmodified lines **kwargs: Additional parameters for the chroma extractor. """ def __init__(self, output_dim: int, sample_rate: int, n_chroma: int, radix2_exp: int, duration: float, match_len_on_eval: bool = False, eval_wavs: tp.Optional[str] = None, duration: float, match_len_on_eval: bool = True, eval_wavs: tp.Optional[str] = None, n_eval_wavs: int = 0, device: tp.Union[torch.device, str] = "cpu", **kwargs): from demucs import pretrained super().__init__(dim=n_chroma, output_dim=output_dim, device=device)44 unmodified lines chroma = chroma[:, :self.chroma_len] logger.debug(f'chroma was truncated! ({t} -> {chroma.shape[1]})') elif t < self.chroma_len: chroma = F.pad(chroma, (0, 0, 0, self.chroma_len - t)) # chroma = F.pad(chroma, (0, 0, 0, self.chroma_len - t)) n_repeat = int(math.ceil(self.chroma_len / t)) chroma = chroma.repeat(1, n_repeat, 1) chroma = chroma[:, :self.chroma_len] logger.debug(f'chroma was zero-padded! ({t} -> {chroma.shape[1]})') return chroma
16 unmodified lines1718192016 unmodified linesxformersdemucslibrosagradioCHANGELOG.md+11-2
MODEL_CARD.md+2-2
README.md+17-5
app.py+151-85
app_batched.py+3-1
audiocraft/__init__.py+1-1
audiocraft/data/audio.py+3-1
audiocraft/data/audio_utils.py+9-4
audiocraft/models/musicgen.py+2
audiocraft/modules/conditioners.py+6-2
requirements.txt+1