Spaces:
Runtime error
Runtime error
Merge branch 'main' into our_hf2
Browse filesFiles changed (9)
- README.md+11-5
- app.py+2-2
- app_batched.py+2-2
- 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")```
8 unmodified lines91011121314153 unmodified lines192021222324258 unmodified linesfrom tempfile import NamedTemporaryFileimport torchimport gradio as grfrom hf_loading import get_pretrainedfrom audiocraft.data.audio import audio_write3 unmodified linesdef load_model(version):print("Loading model", version)return get_pretrained(version)def predict(model, text, melody, duration, topk, topp, temperature, cfg_coef):8 unmodified lines91011121314153 unmodified lines192021222324258 unmodified linesfrom tempfile import NamedTemporaryFileimport torchimport gradio as grfrom audiocraft.models import MusicGenfrom audiocraft.data.audio import audio_write3 unmodified linesdef load_model(version):print("Loading model", version)return MusicGen.get_pretrained(version)def predict(model, text, melody, duration, topk, topp, temperature, cfg_coef):
10 unmodified lines111213141516171 unmodified line1920212223242510 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):10 unmodified lines111213141516171 unmodified line1920212223242510 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):
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+2-2
app_batched.py+2-2
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