Spaces:
Paused
Paused
Merge branch 'main' into our_hf
Browse filesFiles changed (9)
- README.md+11-5
- app.py+32-23
- app_batched.py+24-25
- audiocraft/models/loaders.py+37-10
- audiocraft/models/musicgen.py+15-20
- audiocraft/utils/utils.py+1-1
- hf_loading.pyDeleted-61
- mypy.ini+1-1
- requirements.txt+1
55 unmodified lines56575859606162636465666768697013 unmodified lines8485868788899055 unmodified lines## APIWe provide a simple API and 4 pre-trained models. The pre trained models are:- `small`: 300M model, text to music only,- `medium`: 1.5B model, text to music only,- `melody`: 1.5B model, text to music and text+melody to music,- `large`: 3.3B model, text to music only.We observe the best trade-off between quality and compute with the `medium` or `melody` model.In order to use MusicGen locally **you must have a GPU**. We recommend 16GB of memory, but smallerGPUs will be able to generate short sequences, or longer sequences with the `small` model.See after a quick example for using the API.```python13 unmodified linesfor idx, one_wav in enumerate(wav):# Will save under {idx}.wav, with loudness normalization at -14 db LUFS.audio_write(f'{idx}', one_wav, model.sample_rate, strategy="loudness")```55 unmodified lines56575859606162636465666768697071727374757613 unmodified lines9091929394959655 unmodified lines## APIWe provide a simple API and 4 pre-trained models. The pre trained models are:- `small`: 300M model, text to music only - [🤗 Hub](https://huggingface.co/facebook/musicgen-small)- `medium`: 1.5B model, text to music only - [🤗 Hub](https://huggingface.co/facebook/musicgen-medium)- `melody`: 1.5B model, text to music and text+melody to music - [🤗 Hub](https://huggingface.co/facebook/musicgen-melody)- `large`: 3.3B model, text to music only - [🤗 Hub](https://huggingface.co/facebook/musicgen-large)We observe the best trade-off between quality and compute with the `medium` or `melody` model.In order to use MusicGen locally **you must have a GPU**. We recommend 16GB of memory, but smallerGPUs will be able to generate short sequences, or longer sequences with the `small` model.**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 ffmpeg```See after a quick example for using the API.```python13 unmodified linesfor 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")```
5 unmodified lines678910111213141 unmodified line1617181920212228 unmodified lines51525354555657581 unmodified line6061626364656667686970717273747576777879808182838413 unmodified lines989910010110210310427 unmodified lines1321331341351365 unmodified linesLICENSE file in the root directory of this source tree."""import torchimport gradio as grfrom hf_loading import get_pretrainedMODEL = None1 unmodified linedef load_model(version):print("Loading model", version)return get_pretrained(version)def predict(model, text, melody, duration, topk, topp, temperature, cfg_coef):28 unmodified lineselse:output = MODEL.generate(descriptions=[text], progress=False)output = output.detach().cpu().numpy()return MODEL.sample_rate, outputwith gr.Blocks() as demo:1 unmodified line"""# MusicGenThis is the demo for MusicGen, a simple and controllable model for music generation presented at: "Simple and Controllable Music Generation".Below we present 3 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 the optional melody conditioning wav is provided, the model will extracta broad melody and try to follow it in the generated samples.For skipping queue, you can duplicate this space, and upgrade to GPU in the settings.<br/><a href="https://huggingface.co/spaces/musicgen/MusicGen?duplicate=true"><img style="margin-top: 0em; margin-bottom: 0em" src="https://bit.ly/3gLdBN6" alt="Duplicate Space"></a></p>See [github.com/facebookresearch/audiocraft](https://github.com/facebookresearch/audiocraft)for more details.""")with gr.Row():13 unmodified linestemperature = 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.Audio(label="Generated Music", type="numpy")submit.click(predict, inputs=[model, text, melody, duration, topk, topp, temperature, cfg_coef], outputs=[output])gr.Examples(fn=predict,27 unmodified linesinputs=[text, melody, model],outputs=[output])demo.launch()5 unmodified lines678910111213141516171 unmodified line1920212223242528 unmodified lines54555657585960616263641 unmodified line66676869707172737475767713 unmodified lines9192939495969727 unmodified lines1251261271281291301311321331341351361371381391401411421431441455 unmodified linesLICENSE file in the root directory of this source tree."""from tempfile import NamedTemporaryFileimport torchimport gradio as grfrom audiocraft.models import MusicGenfrom audiocraft.data.audio import audio_writeMODEL = None1 unmodified linedef load_model(version):print("Loading model", version)return MusicGen.get_pretrained(version)def predict(model, text, melody, duration, topk, topp, temperature, cfg_coef):28 unmodified lineselse: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", add_suffix=False)waveform_video = gr.make_waveform(file.name)return waveform_videowith gr.Blocks() as demo:1 unmodified line"""# 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():13 unmodified linestemperature = 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,27 unmodified linesinputs=[text, melody, model],outputs=[output])gr.Markdown("""### More detailsBy typing a description of the music you want and an optional audio used for melody conditioning,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 the optional melody conditioning wav is provided, the model will extracta broad melody and try to follow it in the generated samples.""")demo.launch()
10 unmodified lines111213141516171 unmodified line1920212223242532 unmodified lines58596061626364651 unmodified line67686970717273747576777879808182838485868788899091929394959697989910010122 unmodified lines12412512612712810 unmodified linesimport gradio as grfrom audiocraft.data.audio_utils import convert_audiofrom audiocraft.data.audio import audio_writefrom hf_loading import get_pretrainedMODEL = None1 unmodified linedef load_model():print("Loading model")return get_pretrained("melody")def predict(texts, melodies):32 unmodified linesfor 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)out_files.append([file.name])return out_fileswith gr.Blocks() as demo:1 unmodified line"""# MusicGenThis is the demo for MusicGen, a simple and controllable model for music generationpresented at: "Simple and Controllable Music Generation".Enter the description of the music you want and an optional audio used for melody conditioning.The model will extract the broad melody from the uploaded wav if provided.This will generate a 12s extract with the `melody` model.For generating longer sequences (up to 30 seconds) and skipping queue, you can duplicateto full demo space, which contains more control and upgrade to GPU in the settings.<br/><a href="https://huggingface.co/spaces/musicgen/MusicGen?duplicate=true"><img style="margin-top: 0em; margin-bottom: 0em" src="https://bit.ly/3gLdBN6" alt="Duplicate Space"></a></p>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.""")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.Column():output = gr.Audio(label="Generated Music", type="filepath", format="wav")submit.click(predict, inputs=[text, melody], outputs=[output], batch=True, max_batch_size=12)gr.Examples(fn=predict,22 unmodified linesinputs=[text, melody],outputs=[output])demo.queue(max_size=15).launch()10 unmodified lines111213141516171 unmodified line1920212223242532 unmodified lines5859606162636465661 unmodified line686970717273747576777879808182838485868788899022 unmodified lines11311411511611711811912012112212312412512612710 unmodified linesimport gradio as grfrom audiocraft.data.audio_utils import convert_audiofrom audiocraft.data.audio import audio_writefrom audiocraft.models import MusicGenMODEL = None1 unmodified linedef load_model():print("Loading model")return MusicGen.get_pretrained("melody")def predict(texts, melodies):32 unmodified linesfor 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)waveform_video = gr.make_waveform(file.name)out_files.append(waveform_video)return [out_files]with gr.Blocks() as demo:1 unmodified line"""# 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,22 unmodified linesinputs=[text, melody],outputs=[output])gr.Markdown("""### More detailsBy typing a description of the music you want and an optional audio used for melody conditioning,the model will extract the broad melody from the uploaded wav if provided and generate a 12s extract 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=15).launch()
19 unmodified lines202122232425261 unmodified line2829303132333435363738394041424344452 unmodified lines484950515253545519 unmodified lines"""from pathlib import Pathimport typing as tpfrom omegaconf import OmegaConfimport torch1 unmodified linefrom . import buildersdef _get_state_dict(file_or_url: tp.Union[Path, str], device='cpu'):# Return the state dict either from a file or urlfile_or_url = str(file_or_url)assert isinstance(file_or_url, str)if file_or_url.startswith('https://'):return torch.hub.load_state_dict_from_url(file_or_url, map_location=device, check_hash=True)else:return torch.load(file_or_url, device)def load_compression_model(file_or_url: tp.Union[Path, str], device='cpu'):pkg = _get_state_dict(file_or_url)cfg = OmegaConf.create(pkg['xp.cfg'])cfg.device = str(device)model = builders.get_compression_model(cfg)2 unmodified linesreturn modeldef load_lm_model(file_or_url: tp.Union[Path, str], device='cpu'):pkg = _get_state_dict(file_or_url)cfg = OmegaConf.create(pkg['xp.cfg'])cfg.device = str(device)if cfg.device == 'cpu':19 unmodified lines2021222324252627281 unmodified line303132333435363738394041424344454647484950515253545556575859606162636465666768697071722 unmodified lines757677787980818219 unmodified lines"""from pathlib import Pathfrom huggingface_hub import hf_hub_downloadimport typing as tpimport osfrom omegaconf import OmegaConfimport torch1 unmodified linefrom . import buildersHF_MODEL_CHECKPOINTS_MAP = {"small": "facebook/musicgen-small","medium": "facebook/musicgen-medium","large": "facebook/musicgen-large","melody": "facebook/musicgen-melody",}def _get_state_dict(file_or_url_or_id: tp.Union[Path, str],filename: tp.Optional[str] = None,device='cpu',cache_dir: tp.Optional[str] = None,):# Return the state dict either from a file or urlfile_or_url_or_id = str(file_or_url_or_id)assert isinstance(file_or_url_or_id, str)if os.path.isfile(file_or_url_or_id):return torch.load(file_or_url_or_id, map_location=device)elif file_or_url_or_id.startswith('https://'):return torch.hub.load_state_dict_from_url(file_or_url_or_id, map_location=device, check_hash=True)elif file_or_url_or_id in HF_MODEL_CHECKPOINTS_MAP:assert filename is not None, "filename needs to be defined if using HF checkpoints"repo_id = HF_MODEL_CHECKPOINTS_MAP[file_or_url_or_id]file = hf_hub_download(repo_id=repo_id, filename=filename, cache_dir=cache_dir)return torch.load(file, map_location=device)else:raise ValueError(f"{file_or_url_or_id} is not a valid name, path or link that can be loaded.")def load_compression_model(file_or_url_or_id: tp.Union[Path, str], device='cpu', cache_dir: tp.Optional[str] = None):pkg = _get_state_dict(file_or_url_or_id, filename="compression_state_dict.bin", cache_dir=cache_dir)cfg = OmegaConf.create(pkg['xp.cfg'])cfg.device = str(device)model = builders.get_compression_model(cfg)2 unmodified linesreturn modeldef load_lm_model(file_or_url_or_id: tp.Union[Path, str], device='cpu', cache_dir: tp.Optional[str] = None):pkg = _get_state_dict(file_or_url_or_id, filename="state_dict.bin", cache_dir=cache_dir)cfg = OmegaConf.create(pkg['xp.cfg'])cfg.device = str(device)if cfg.device == 'cpu':
16 unmodified lines1718192021222343 unmodified lines676869707172737475762 unmodified lines79808182838485868788899091929394959697989916 unmodified linesfrom .encodec import CompressionModelfrom .lm import LMModelfrom .builders import get_debug_compression_model, get_debug_lm_modelfrom .loaders import load_compression_model, load_lm_modelfrom ..data.audio_utils import convert_audiofrom ..modules.conditioners import ConditioningAttributes, WavConditionfrom ..utils.autocast import TorchAutocast43 unmodified lines@staticmethoddef get_pretrained(name: str = 'melody', device='cuda'):"""Return pretrained model, we provide four models:- small (300M), text to music,- medium (1.5B), text to music,- melody (1.5B) text to music and text+melody to music,- large (3.3B), text to music."""if name == 'debug':2 unmodified lineslm = get_debug_lm_model(device)return MusicGen(name, compression_model, lm)if 'MUSICGEN_ROOT' in os.environ:ROOT = os.environ['MUSICGEN_ROOT']if not ROOT.endswith('/'):ROOT += '/'else:ROOT = 'https://dl.fbaipublicfiles.com/audiocraft/musicgen/v0/'compression_model = load_compression_model(ROOT + 'b0dbef54-37d256b525.th', device=device)names = {'small': 'ba7a97ba-830fe5771e','medium': 'aa73ae27-fbc9f401db','large': '9b6e835c-1f0cf17b5e','melody': 'f79af192-61305ffc49',}sig = names[name]lm = load_lm_model(ROOT + f'{sig}.th', device=device)return MusicGen(name, compression_model, lm)def set_generation_params(self, use_sampling: bool = True, top_k: int = 250,16 unmodified lines1718192021222343 unmodified lines676869707172737475762 unmodified lines7980818283848586878889909192939416 unmodified linesfrom .encodec import CompressionModelfrom .lm import LMModelfrom .builders import get_debug_compression_model, get_debug_lm_modelfrom .loaders import load_compression_model, load_lm_model, HF_MODEL_CHECKPOINTS_MAPfrom ..data.audio_utils import convert_audiofrom ..modules.conditioners import ConditioningAttributes, WavConditionfrom ..utils.autocast import TorchAutocast43 unmodified lines@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-medium- melody (1.5B) text to music and text+melody to music, # see: https://huggingface.co/facebook/musicgen-melody- large (3.3B), text to music, # see: https://huggingface.co/facebook/musicgen-large"""if name == 'debug':2 unmodified lineslm = get_debug_lm_model(device)return MusicGen(name, compression_model, lm)if name not in HF_MODEL_CHECKPOINTS_MAP:raise ValueError(f"{name} is not a valid checkpoint name. "f"Choose one of {', '.join(HF_MODEL_CHECKPOINTS_MAP.keys())}")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)return MusicGen(name, compression_model, lm)def set_generation_params(self, use_sampling: bool = True, top_k: int = 250,
121 unmodified lines122123124125126127128121 unmodified linesprobs_sort, probs_idx = torch.sort(probs, dim=-1, descending=True)probs_sum = torch.cumsum(probs_sort, dim=-1)mask = probs_sum - probs_sort > pprobs_sort *= (~mask).float(0)probs_sort.div_(probs_sort.sum(dim=-1, keepdim=True))next_token = multinomial(probs_sort, num_samples=1)next_token = torch.gather(probs_idx, -1, next_token)121 unmodified lines122123124125126127128121 unmodified linesprobs_sort, probs_idx = torch.sort(probs, dim=-1, descending=True)probs_sum = torch.cumsum(probs_sort, dim=-1)mask = probs_sum - probs_sort > pprobs_sort *= (~mask).float()probs_sort.div_(probs_sort.sum(dim=-1, keepdim=True))next_token = multinomial(probs_sort, num_samples=1)next_token = torch.gather(probs_idx, -1, next_token)
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061"""Utility for loading the models from HF."""from pathlib import Pathimport typing as tp
from omegaconf import OmegaConffrom huggingface_hub import hf_hub_downloadimport torch
from audiocraft.models import builders, MusicGen
MODEL_CHECKPOINTS_MAP = { "small": "facebook/musicgen-small", "medium": "facebook/musicgen-medium", "large": "facebook/musicgen-large", "melody": "facebook/musicgen-melody",}
def _get_state_dict(file_or_url: tp.Union[Path, str], filename="state_dict.bin", device='cpu'): # Return the state dict either from a file or url print("loading", file_or_url, filename) file_or_url = str(file_or_url) assert isinstance(file_or_url, str) return torch.load( hf_hub_download(repo_id=file_or_url, filename=filename), map_location=device)
def load_compression_model(file_or_url: tp.Union[Path, str], device='cpu'): pkg = _get_state_dict(file_or_url, filename="compression_state_dict.bin") cfg = OmegaConf.create(pkg['xp.cfg']) cfg.device = str(device) model = builders.get_compression_model(cfg) model.load_state_dict(pkg['best_state']) model.eval() model.cfg = cfg return model
def load_lm_model(file_or_url: tp.Union[Path, str], device='cpu'): pkg = _get_state_dict(file_or_url) 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' model = builders.get_lm_model(cfg) model.load_state_dict(pkg['best_state']) model.eval() model.cfg = cfg return model
def get_pretrained(name: str = 'small', device='cuda'): model_id = MODEL_CHECKPOINTS_MAP[name] compression_model = load_compression_model(model_id, device=device) lm = load_lm_model(model_id, device=device) return MusicGen(name, compression_model, lm)1234[mypy][mypy-treetable,torchaudio.*,soundfile,einops.*,av.*,tqdm.*,num2words.*,spacy,xformers.*,scipy]ignore_missing_imports = True1234[mypy][mypy-treetable,torchaudio.*,soundfile,einops.*,av.*,tqdm.*,num2words.*,spacy,xformers.*,scipy,huggingface_hub]ignore_missing_imports = True
10 unmodified lines11121314151610 unmodified linesspacy==3.5.2torch>=2.0.0torchaudio>=2.0.0tqdmtransformersxformers10 unmodified lines1112131415161710 unmodified linesspacy==3.5.2torch>=2.0.0torchaudio>=2.0.0huggingface_hubtqdmtransformersxformers
README.md+11-5
app.py+32-23
app_batched.py+24-25
audiocraft/models/loaders.py+37-10
audiocraft/models/musicgen.py+15-20
audiocraft/utils/utils.py+1-1
hf_loading.pyDeleted-61
mypy.ini+1-1
requirements.txt+1