Spaces:
Running on Zero
Running on Zero
Uplaod files
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .ipynb_checkpoints/README-checkpoint.mdAdded+13
- .ipynb_checkpoints/app-checkpoint.pyAdded+260
- .ipynb_checkpoints/modelling_deberta_v2-checkpoint.pyAdded+1750
- .ipynb_checkpoints/models-checkpoint.pyAdded+738
- app.pyAdded+260
- audioldm/__init__.pyAdded+8
- audioldm/__main__.pyAdded+183
- audioldm/__pycache__/__init__.cpython-311.pycAdded
- audioldm/__pycache__/__init__.cpython-37.pycAdded
- audioldm/__pycache__/__init__.cpython-39.pycAdded
- audioldm/__pycache__/ldm.cpython-311.pycAdded
- audioldm/__pycache__/ldm.cpython-37.pycAdded
- audioldm/__pycache__/ldm.cpython-39.pycAdded
- audioldm/__pycache__/pipeline.cpython-311.pycAdded
- audioldm/__pycache__/pipeline.cpython-37.pycAdded
- audioldm/__pycache__/pipeline.cpython-39.pycAdded
- audioldm/__pycache__/utils.cpython-311.pycAdded
- audioldm/__pycache__/utils.cpython-37.pycAdded
- audioldm/__pycache__/utils.cpython-39.pycAdded
- audioldm/audio/__init__.pyAdded+2
- audioldm/audio/__pycache__/__init__.cpython-311.pycAdded
- audioldm/audio/__pycache__/__init__.cpython-37.pycAdded
- audioldm/audio/__pycache__/__init__.cpython-39.pycAdded
- audioldm/audio/__pycache__/audio_processing.cpython-311.pycAdded
- audioldm/audio/__pycache__/audio_processing.cpython-37.pycAdded
- audioldm/audio/__pycache__/audio_processing.cpython-39.pycAdded
- audioldm/audio/__pycache__/mix.cpython-39.pycAdded
- audioldm/audio/__pycache__/stft.cpython-311.pycAdded
- audioldm/audio/__pycache__/stft.cpython-37.pycAdded
- audioldm/audio/__pycache__/stft.cpython-39.pycAdded
- audioldm/audio/__pycache__/tools.cpython-311.pycAdded
- audioldm/audio/__pycache__/tools.cpython-37.pycAdded
- audioldm/audio/__pycache__/tools.cpython-39.pycAdded
- audioldm/audio/__pycache__/torch_tools.cpython-39.pycAdded
- audioldm/audio/audio_processing.pyAdded+100
- audioldm/audio/stft.pyAdded+186
- audioldm/audio/tools.pyAdded+85
- audioldm/clap/__init__.pyAdded
- audioldm/clap/__pycache__/__init__.cpython-39.pycAdded
- audioldm/clap/__pycache__/encoders.cpython-39.pycAdded
- audioldm/clap/encoders.pyAdded+170
- audioldm/clap/open_clip/__init__.pyAdded+25
- audioldm/clap/open_clip/__pycache__/__init__.cpython-39.pycAdded
- audioldm/clap/open_clip/__pycache__/factory.cpython-39.pycAdded
- audioldm/clap/open_clip/__pycache__/feature_fusion.cpython-39.pycAdded
- audioldm/clap/open_clip/__pycache__/htsat.cpython-39.pycAdded
- audioldm/clap/open_clip/__pycache__/loss.cpython-39.pycAdded
- audioldm/clap/open_clip/__pycache__/model.cpython-39.pycAdded
- audioldm/clap/open_clip/__pycache__/openai.cpython-39.pycAdded
- audioldm/clap/open_clip/__pycache__/pann_model.cpython-39.pycAdded
12345678910111213---title: Mustangoemoji: 🐢colorFrom: indigocolorTo: greensdk: gradiosdk_version: 4.3.0app_file: app.pypinned: falselicense: apache-2.0---
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260import gradio as grimport jsonimport torchimport waviofrom tqdm import tqdmfrom huggingface_hub import snapshot_download
from audioldm.audio.stft import TacotronSTFTfrom audioldm.variational_autoencoder import AutoencoderKL
from transformers import AutoTokenizer, T5ForConditionalGenerationfrom modelling_deberta_v2 import DebertaV2ForTokenClassificationRegression
from diffusers import DDPMSchedulerfrom models import MusicAudioDiffusion
from gradio import Markdown
class MusicFeaturePredictor: def __init__(self, path, device="cuda:0", cache_dir=None, local_files_only=False): self.beats_tokenizer = AutoTokenizer.from_pretrained( "microsoft/deberta-v3-large", cache_dir=cache_dir, local_files_only=local_files_only, ) self.beats_model = DebertaV2ForTokenClassificationRegression.from_pretrained( "microsoft/deberta-v3-large", cache_dir=cache_dir, local_files_only=local_files_only, ) self.beats_model.eval() self.beats_model.to(device)
beats_ckpt = f"{path}/beats/microsoft-deberta-v3-large.pt" beats_weight = torch.load(beats_ckpt, map_location="cpu") self.beats_model.load_state_dict(beats_weight)
self.chords_tokenizer = AutoTokenizer.from_pretrained( "google/flan-t5-large", cache_dir=cache_dir, local_files_only=local_files_only, ) self.chords_model = T5ForConditionalGeneration.from_pretrained( "google/flan-t5-large", cache_dir=cache_dir, local_files_only=local_files_only, ) self.chords_model.eval() self.chords_model.to(device)
chords_ckpt = f"{path}/chords/flan-t5-large.bin" chords_weight = torch.load(chords_ckpt, map_location="cpu") self.chords_model.load_state_dict(chords_weight)
def generate_beats(self, prompt): tokenized = self.beats_tokenizer( prompt, max_length=512, padding=True, truncation=True, return_tensors="pt" ) tokenized = {k: v.to(self.beats_model.device) for k, v in tokenized.items()}
with torch.no_grad(): out = self.beats_model(**tokenized)
max_beat = ( 1 + torch.argmax(out["logits"][:, 0, :], -1).detach().cpu().numpy() ).tolist()[0] intervals = ( out["values"][:, :, 0] .detach() .cpu() .numpy() .astype("float32") .round(4) .tolist() )
intervals = np.cumsum(intervals) predicted_beats_times = [] for t in intervals: if t < 10: predicted_beats_times.append(round(t, 2)) else: break predicted_beats_times = list(np.array(predicted_beats_times)[:50])
if len(predicted_beats_times) == 0: predicted_beats = [[], []] else: beat_counts = [] for i in range(len(predicted_beats_times)): beat_counts.append(float(1.0 + np.mod(i, max_beat))) predicted_beats = [[predicted_beats_times, beat_counts]]
return max_beat, predicted_beats_times, predicted_beats
def generate(self, prompt): max_beat, predicted_beats_times, predicted_beats = self.generate_beats(prompt)
chords_prompt = "Caption: {} \\n Timestamps: {} \\n Max Beat: {}".format( prompt, " , ".join([str(round(t, 2)) for t in predicted_beats_times]), max_beat, )
tokenized = self.chords_tokenizer( chords_prompt, max_length=512, padding=True, truncation=True, return_tensors="pt", ) tokenized = {k: v.to(self.chords_model.device) for k, v in tokenized.items()}
generated_chords = self.chords_model.generate( input_ids=tokenized["input_ids"], attention_mask=tokenized["attention_mask"], min_length=8, max_length=128, num_beams=5, early_stopping=True, num_return_sequences=1, )
generated_chords = self.chords_tokenizer.decode( generated_chords[0], skip_special_tokens=True, clean_up_tokenization_spaces=True, ).split(" n ")
predicted_chords, predicted_chords_times = [], [] for item in generated_chords: c, ct = item.split(" at ") predicted_chords.append(c) predicted_chords_times.append(float(ct))
return predicted_beats, predicted_chords, predicted_chords_times
class Mustango: def __init__( self, name="declare-lab/mustango", device="cuda:0", cache_dir=None, local_files_only=False, ): path = snapshot_download(repo_id=name, cache_dir=cache_dir)
self.music_model = MusicFeaturePredictor( path, device, cache_dir=cache_dir, local_files_only=local_files_only )
vae_config = json.load(open(f"{path}/configs/vae_config.json")) stft_config = json.load(open(f"{path}/configs/stft_config.json")) main_config = json.load(open(f"{path}/configs/main_config.json"))
self.vae = AutoencoderKL(**vae_config).to(device) self.stft = TacotronSTFT(**stft_config).to(device) self.model = MusicAudioDiffusion( main_config["text_encoder_name"], main_config["scheduler_name"], unet_model_config_path=f"{path}/configs/music_diffusion_model_config.json", ).to(device)
vae_weights = torch.load( f"{path}/vae/pytorch_model_vae.bin", map_location=device ) stft_weights = torch.load( f"{path}/stft/pytorch_model_stft.bin", map_location=device ) main_weights = torch.load( f"{path}/ldm/pytorch_model_ldm.bin", map_location=device )
self.vae.load_state_dict(vae_weights) self.stft.load_state_dict(stft_weights) self.model.load_state_dict(main_weights)
print("Successfully loaded checkpoint from:", name)
self.vae.eval() self.stft.eval() self.model.eval()
self.scheduler = DDPMScheduler.from_pretrained( main_config["scheduler_name"], subfolder="scheduler" )
def generate(self, prompt, steps=100, guidance=3, samples=1, disable_progress=True): """Genrate music for a single prompt string."""
with torch.no_grad(): beats, chords, chords_times = self.music_model.generate(prompt) latents = self.model.inference( [prompt], beats, [chords], [chords_times], self.scheduler, steps, guidance, samples, disable_progress, ) mel = self.vae.decode_first_stage(latents) wave = self.vae.decode_to_waveform(mel)
return wave[0]
# Initialize Mustangoif torch.cuda.is_available(): mustango = Mustango()else: mustango = Mustango(device="cpu")
def gradio_generate(prompt, steps, guidance): output_wave = mustango.generate(prompt, steps, guidance) # output_filename = f"{prompt.replace(' ', '_')}_{steps}_{guidance}"[:250] + ".wav" output_filename = "temp.wav" wavio.write(output_filename, output_wave, rate=16000, sampwidth=2) return output_filename
# description_text = """# <p><a href="https://huggingface.co/spaces/declare-lab/mustango/blob/main/app.py?duplicate=true"> <img style="margin-top: 0em; margin-bottom: 0em" src="https://bit.ly/3gLdBN6" alt="Duplicate Space"></a> For faster inference without waiting in queue, you may duplicate the space and upgrade to a GPU in the settings. <br/><br/># Generate music using Mustango by providing a text prompt.# <br/><br/> Meet Mustango, an exciting addition to the vibrant landscape of Multimodal Large Language Models \# designed for controlled music generation. Mustango leverages Latent Diffusion Model (LDM), Flan-T5, and \# musical features to do the magic! \# <p/># """description_text = ""# Gradio input and output componentsinput_text = gr.inputs.Textbox(lines=2, label="Prompt")output_audio = gr.outputs.Audio(label="Generated Music", type="filepath")denoising_steps = gr.Slider(minimum=100, maximum=200, value=100, step=1, label="Steps", interactive=True)guidance_scale = gr.Slider(minimum=1, maximum=10, value=3, step=0.1, label="Guidance Scale", interactive=True)
# Gradio interfacegr_interface = gr.Interface( fn=gradio_generate, inputs=[input_text, denoising_steps, guidance_scale], outputs=[output_audio], title="Mustango: Toward Controllable Text-to-Music Generation", description=description_text, allow_flagging=False, examples=[ ["This techno song features a synth lead playing the main melody. This is accompanied by programmed percussion playing a simple kick focused beat. The hi-hat is accented in an open position on the 3-and count of every bar. The synth plays the bass part with a voicing that sounds like a cello. This techno song can be played in a club. The chord sequence is Gm, A7, Eb, Bb, C, F, Gm. The beat counts to 2. The tempo of this song is 128.0 beats per minute. The key of this song is G minor."], ["This is a new age piece. There is a flute playing the main melody with a lot of staccato notes. The rhythmic background consists of a medium tempo electronic drum beat with percussive elements all over the spectrum. There is a playful atmosphere to the piece. This piece can be used in the soundtrack of a children's TV show or an advertisement jingle."], ["The song is an instrumental. The song is in medium tempo with a classical guitar playing a lilting melody in accompaniment style. The song is emotional and romantic. The song is a romantic instrumental song. The chord sequence is Gm, F6, Ebm. The time signature is 4/4. This song is in Adagio. The key of this song is G minor."], ["This folk song features a female voice singing the main melody. This is accompanied by a tabla playing the percussion. A guitar strums chords. For most parts of the song, only one chord is played. At the last bar, a different chord is played. This song has minimal instruments. This song has a story-telling mood. This song can be played in a village scene in an Indian movie. The chord sequence is Bbm, Ab. The beat is 3. The tempo of this song is Allegro. The key of this song is Bb minor."], ["This is a live performance of a classical music piece. There is an orchestra performing the piece with a violin lead playing the main melody. The atmosphere is sentimental and heart-touching. This piece could be playing in the background at a classy restaurant. The chord progression in this song is Am7, Gm, Dm, A7, Dm. The beat is 3. This song is in Largo. The key of this song is D minor."], ["This is a techno piece with drums and beats and a leading melody. A synth plays chords. The music kicks off with a powerful and relentless drumbeat. Over the pounding beats, a leading melody emerges. In the middle of the song, a flock of seagulls flies over the venue and make loud bird sounds. It has strong danceability and can be played in a club. The tempo is 120 bpm. The chords played by the synth are Am, Cm, Dm, Gm."], ], cache_examples=False,)
# Launch Gradio appgr_interface.launch()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750# coding=utf-8# Copyright 2020 Microsoft and the Hugging Face Inc. team.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.""" PyTorch DeBERTa-v2 model."""
from collections.abc import Sequencefrom typing import Optional, Tuple, Union
import torchimport torch.utils.checkpointfrom torch import nnfrom torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, LayerNorm, MSELoss
from transformers.activations import ACT2FNfrom transformers.modeling_outputs import ( ModelOutput, BaseModelOutput, MaskedLMOutput, MultipleChoiceModelOutput, QuestionAnsweringModelOutput, SequenceClassifierOutput, TokenClassifierOutput,)from transformers.modeling_utils import PreTrainedModelfrom transformers.pytorch_utils import softmax_backward_datafrom transformers.utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, loggingfrom transformers.models.deberta_v2.configuration_deberta_v2 import DebertaV2Config
logger = logging.get_logger(__name__)
_CONFIG_FOR_DOC = "DebertaV2Config"_CHECKPOINT_FOR_DOC = "microsoft/deberta-v2-xlarge"_QA_TARGET_START_INDEX = 2_QA_TARGET_END_INDEX = 9
DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST = [ "microsoft/deberta-v2-xlarge", "microsoft/deberta-v2-xxlarge", "microsoft/deberta-v2-xlarge-mnli", "microsoft/deberta-v2-xxlarge-mnli",]
# Copied from transformers.models.deberta.modeling_deberta.ContextPoolerclass ContextPooler(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.pooler_hidden_size, config.pooler_hidden_size) self.dropout = StableDropout(config.pooler_dropout) self.config = config
def forward(self, hidden_states): # We "pool" the model by simply taking the hidden state corresponding # to the first token.
context_token = hidden_states[:, 0] context_token = self.dropout(context_token) pooled_output = self.dense(context_token) pooled_output = ACT2FN[self.config.pooler_hidden_act](pooled_output) return pooled_output
@property def output_dim(self): return self.config.hidden_size
# Copied from transformers.models.deberta.modeling_deberta.XSoftmax with deberta->deberta_v2class XSoftmax(torch.autograd.Function): """ Masked Softmax which is optimized for saving memory
Args: input (`torch.tensor`): The input tensor that will apply softmax. mask (`torch.IntTensor`): The mask matrix where 0 indicate that element will be ignored in the softmax calculation. dim (int): The dimension that will apply softmax
Example:
```python >>> import torch >>> from transformers.models.deberta_v2.modeling_deberta_v2 import XSoftmax
>>> # Make a tensor >>> x = torch.randn([4, 20, 100])
>>> # Create a mask >>> mask = (x > 0).int()
>>> # Specify the dimension to apply softmax >>> dim = -1
>>> y = XSoftmax.apply(x, mask, dim) ```"""
@staticmethod def forward(self, input, mask, dim): self.dim = dim rmask = ~(mask.to(torch.bool))
output = input.masked_fill(rmask, torch.tensor(torch.finfo(input.dtype).min)) output = torch.softmax(output, self.dim) output.masked_fill_(rmask, 0) self.save_for_backward(output) return output
@staticmethod def backward(self, grad_output): (output,) = self.saved_tensors inputGrad = softmax_backward_data(self, grad_output, output, self.dim, output) return inputGrad, None, None
@staticmethod def symbolic(g, self, mask, dim): import torch.onnx.symbolic_helper as sym_help from torch.onnx.symbolic_opset9 import masked_fill, softmax
mask_cast_value = g.op("Cast", mask, to_i=sym_help.cast_pytorch_to_onnx["Long"]) r_mask = g.op( "Cast", g.op("Sub", g.op("Constant", value_t=torch.tensor(1, dtype=torch.int64)), mask_cast_value), to_i=sym_help.cast_pytorch_to_onnx["Bool"], ) output = masked_fill( g, self, r_mask, g.op("Constant", value_t=torch.tensor(torch.finfo(self.type().dtype()).min)) ) output = softmax(g, output, dim) return masked_fill(g, output, r_mask, g.op("Constant", value_t=torch.tensor(0, dtype=torch.bool)))
# Copied from transformers.models.deberta.modeling_deberta.DropoutContextclass DropoutContext(object): def __init__(self): self.dropout = 0 self.mask = None self.scale = 1 self.reuse_mask = True
# Copied from transformers.models.deberta.modeling_deberta.get_maskdef get_mask(input, local_context): if not isinstance(local_context, DropoutContext): dropout = local_context mask = None else: dropout = local_context.dropout dropout *= local_context.scale mask = local_context.mask if local_context.reuse_mask else None
if dropout > 0 and mask is None: mask = (1 - torch.empty_like(input).bernoulli_(1 - dropout)).to(torch.bool)
if isinstance(local_context, DropoutContext): if local_context.mask is None: local_context.mask = mask
return mask, dropout
# Copied from transformers.models.deberta.modeling_deberta.XDropoutclass XDropout(torch.autograd.Function): """Optimized dropout function to save computation and memory by using mask operation instead of multiplication."""
@staticmethod def forward(ctx, input, local_ctx): mask, dropout = get_mask(input, local_ctx) ctx.scale = 1.0 / (1 - dropout) if dropout > 0: ctx.save_for_backward(mask) return input.masked_fill(mask, 0) * ctx.scale else: return input
@staticmethod def backward(ctx, grad_output): if ctx.scale > 1: (mask,) = ctx.saved_tensors return grad_output.masked_fill(mask, 0) * ctx.scale, None else: return grad_output, None
@staticmethod def symbolic(g: torch._C.Graph, input: torch._C.Value, local_ctx: Union[float, DropoutContext]) -> torch._C.Value: from torch.onnx import symbolic_opset12
dropout_p = local_ctx if isinstance(local_ctx, DropoutContext): dropout_p = local_ctx.dropout # StableDropout only calls this function when training. train = True # TODO: We should check if the opset_version being used to export # is > 12 here, but there's no good way to do that. As-is, if the # opset_version < 12, export will fail with a CheckerError. # Once https://github.com/pytorch/pytorch/issues/78391 is fixed, do something like: # if opset_version < 12: # return torch.onnx.symbolic_opset9.dropout(g, input, dropout_p, train) return symbolic_opset12.dropout(g, input, dropout_p, train)
# Copied from transformers.models.deberta.modeling_deberta.StableDropoutclass StableDropout(nn.Module): """ Optimized dropout module for stabilizing the training
Args: drop_prob (float): the dropout probabilities """
def __init__(self, drop_prob): super().__init__() self.drop_prob = drop_prob self.count = 0 self.context_stack = None
def forward(self, x): """ Call the module
Args: x (`torch.tensor`): The input tensor to apply dropout """ if self.training and self.drop_prob > 0: return XDropout.apply(x, self.get_context()) return x
def clear_context(self): self.count = 0 self.context_stack = None
def init_context(self, reuse_mask=True, scale=1): if self.context_stack is None: self.context_stack = [] self.count = 0 for c in self.context_stack: c.reuse_mask = reuse_mask c.scale = scale
def get_context(self): if self.context_stack is not None: if self.count >= len(self.context_stack): self.context_stack.append(DropoutContext()) ctx = self.context_stack[self.count] ctx.dropout = self.drop_prob self.count += 1 return ctx else: return self.drop_prob
# Copied from transformers.models.deberta.modeling_deberta.DebertaSelfOutput with DebertaLayerNorm->LayerNormclass DebertaV2SelfOutput(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) self.LayerNorm = LayerNorm(config.hidden_size, config.layer_norm_eps) self.dropout = StableDropout(config.hidden_dropout_prob)
def forward(self, hidden_states, input_tensor): hidden_states = self.dense(hidden_states) hidden_states = self.dropout(hidden_states) hidden_states = self.LayerNorm(hidden_states + input_tensor) return hidden_states
# Copied from transformers.models.deberta.modeling_deberta.DebertaAttention with Deberta->DebertaV2class DebertaV2Attention(nn.Module): def __init__(self, config): super().__init__() self.self = DisentangledSelfAttention(config) self.output = DebertaV2SelfOutput(config) self.config = config
def forward( self, hidden_states, attention_mask, output_attentions=False, query_states=None, relative_pos=None, rel_embeddings=None, ): self_output = self.self( hidden_states, attention_mask, output_attentions, query_states=query_states, relative_pos=relative_pos, rel_embeddings=rel_embeddings, ) if output_attentions: self_output, att_matrix = self_output if query_states is None: query_states = hidden_states attention_output = self.output(self_output, query_states)
if output_attentions: return (attention_output, att_matrix) else: return attention_output
# Copied from transformers.models.bert.modeling_bert.BertIntermediate with Bert->DebertaV2class DebertaV2Intermediate(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.intermediate_size) if isinstance(config.hidden_act, str): self.intermediate_act_fn = ACT2FN[config.hidden_act] else: self.intermediate_act_fn = config.hidden_act
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: hidden_states = self.dense(hidden_states) hidden_states = self.intermediate_act_fn(hidden_states) return hidden_states
# Copied from transformers.models.deberta.modeling_deberta.DebertaOutput with DebertaLayerNorm->LayerNormclass DebertaV2Output(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.intermediate_size, config.hidden_size) self.LayerNorm = LayerNorm(config.hidden_size, config.layer_norm_eps) self.dropout = StableDropout(config.hidden_dropout_prob) self.config = config
def forward(self, hidden_states, input_tensor): hidden_states = self.dense(hidden_states) hidden_states = self.dropout(hidden_states) hidden_states = self.LayerNorm(hidden_states + input_tensor) return hidden_states
# Copied from transformers.models.deberta.modeling_deberta.DebertaLayer with Deberta->DebertaV2class DebertaV2Layer(nn.Module): def __init__(self, config): super().__init__() self.attention = DebertaV2Attention(config) self.intermediate = DebertaV2Intermediate(config) self.output = DebertaV2Output(config)
def forward( self, hidden_states, attention_mask, query_states=None, relative_pos=None, rel_embeddings=None, output_attentions=False, ): attention_output = self.attention( hidden_states, attention_mask, output_attentions=output_attentions, query_states=query_states, relative_pos=relative_pos, rel_embeddings=rel_embeddings, ) if output_attentions: attention_output, att_matrix = attention_output intermediate_output = self.intermediate(attention_output) layer_output = self.output(intermediate_output, attention_output) if output_attentions: return (layer_output, att_matrix) else: return layer_output
class ConvLayer(nn.Module): def __init__(self, config): super().__init__() kernel_size = getattr(config, "conv_kernel_size", 3) groups = getattr(config, "conv_groups", 1) self.conv_act = getattr(config, "conv_act", "tanh") self.conv = nn.Conv1d( config.hidden_size, config.hidden_size, kernel_size, padding=(kernel_size - 1) // 2, groups=groups ) self.LayerNorm = LayerNorm(config.hidden_size, config.layer_norm_eps) self.dropout = StableDropout(config.hidden_dropout_prob) self.config = config
def forward(self, hidden_states, residual_states, input_mask): out = self.conv(hidden_states.permute(0, 2, 1).contiguous()).permute(0, 2, 1).contiguous() rmask = (1 - input_mask).bool() out.masked_fill_(rmask.unsqueeze(-1).expand(out.size()), 0) out = ACT2FN[self.conv_act](self.dropout(out))
layer_norm_input = residual_states + out output = self.LayerNorm(layer_norm_input).to(layer_norm_input)
if input_mask is None: output_states = output else: if input_mask.dim() != layer_norm_input.dim(): if input_mask.dim() == 4: input_mask = input_mask.squeeze(1).squeeze(1) input_mask = input_mask.unsqueeze(2)
input_mask = input_mask.to(output.dtype) output_states = output * input_mask
return output_states
class DebertaV2Encoder(nn.Module): """Modified BertEncoder with relative position bias support"""
def __init__(self, config): super().__init__()
self.layer = nn.ModuleList([DebertaV2Layer(config) for _ in range(config.num_hidden_layers)]) self.relative_attention = getattr(config, "relative_attention", False)
if self.relative_attention: self.max_relative_positions = getattr(config, "max_relative_positions", -1) if self.max_relative_positions < 1: self.max_relative_positions = config.max_position_embeddings
self.position_buckets = getattr(config, "position_buckets", -1) pos_ebd_size = self.max_relative_positions * 2
if self.position_buckets > 0: pos_ebd_size = self.position_buckets * 2
self.rel_embeddings = nn.Embedding(pos_ebd_size, config.hidden_size)
self.norm_rel_ebd = [x.strip() for x in getattr(config, "norm_rel_ebd", "none").lower().split("|")]
if "layer_norm" in self.norm_rel_ebd: self.LayerNorm = LayerNorm(config.hidden_size, config.layer_norm_eps, elementwise_affine=True)
self.conv = ConvLayer(config) if getattr(config, "conv_kernel_size", 0) > 0 else None self.gradient_checkpointing = False
def get_rel_embedding(self): rel_embeddings = self.rel_embeddings.weight if self.relative_attention else None if rel_embeddings is not None and ("layer_norm" in self.norm_rel_ebd): rel_embeddings = self.LayerNorm(rel_embeddings) return rel_embeddings
def get_attention_mask(self, attention_mask): if attention_mask.dim() <= 2: extended_attention_mask = attention_mask.unsqueeze(1).unsqueeze(2) attention_mask = extended_attention_mask * extended_attention_mask.squeeze(-2).unsqueeze(-1) elif attention_mask.dim() == 3: attention_mask = attention_mask.unsqueeze(1)
return attention_mask
def get_rel_pos(self, hidden_states, query_states=None, relative_pos=None): if self.relative_attention and relative_pos is None: q = query_states.size(-2) if query_states is not None else hidden_states.size(-2) relative_pos = build_relative_position( q, hidden_states.size(-2), bucket_size=self.position_buckets, max_position=self.max_relative_positions, device=hidden_states.device, ) return relative_pos
def forward( self, hidden_states, attention_mask, output_hidden_states=True, output_attentions=False, query_states=None, relative_pos=None, return_dict=True, ): if attention_mask.dim() <= 2: input_mask = attention_mask else: input_mask = attention_mask.sum(-2) > 0 attention_mask = self.get_attention_mask(attention_mask) relative_pos = self.get_rel_pos(hidden_states, query_states, relative_pos)
all_hidden_states = () if output_hidden_states else None all_attentions = () if output_attentions else None
if isinstance(hidden_states, Sequence): next_kv = hidden_states[0] else: next_kv = hidden_states rel_embeddings = self.get_rel_embedding() output_states = next_kv for i, layer_module in enumerate(self.layer): if output_hidden_states: all_hidden_states = all_hidden_states + (output_states,)
if self.gradient_checkpointing and self.training:
def create_custom_forward(module): def custom_forward(*inputs): return module(*inputs, output_attentions)
return custom_forward
output_states = torch.utils.checkpoint.checkpoint( create_custom_forward(layer_module), next_kv, attention_mask, query_states, relative_pos, rel_embeddings, ) else: output_states = layer_module( next_kv, attention_mask, query_states=query_states, relative_pos=relative_pos, rel_embeddings=rel_embeddings, output_attentions=output_attentions, )
if output_attentions: output_states, att_m = output_states
if i == 0 and self.conv is not None: output_states = self.conv(hidden_states, output_states, input_mask)
if query_states is not None: query_states = output_states if isinstance(hidden_states, Sequence): next_kv = hidden_states[i + 1] if i + 1 < len(self.layer) else None else: next_kv = output_states
if output_attentions: all_attentions = all_attentions + (att_m,)
if output_hidden_states: all_hidden_states = all_hidden_states + (output_states,)
if not return_dict: return tuple(v for v in [output_states, all_hidden_states, all_attentions] if v is not None) return BaseModelOutput( last_hidden_state=output_states, hidden_states=all_hidden_states, attentions=all_attentions )
def make_log_bucket_position(relative_pos, bucket_size, max_position): sign = torch.sign(relative_pos) mid = bucket_size // 2 abs_pos = torch.where( (relative_pos < mid) & (relative_pos > -mid), torch.tensor(mid - 1).type_as(relative_pos), torch.abs(relative_pos), ) log_pos = ( torch.ceil(torch.log(abs_pos / mid) / torch.log(torch.tensor((max_position - 1) / mid)) * (mid - 1)) + mid ) bucket_pos = torch.where(abs_pos <= mid, relative_pos.type_as(log_pos), log_pos * sign) return bucket_pos
def build_relative_position(query_size, key_size, bucket_size=-1, max_position=-1, device=None): """ Build relative position according to the query and key
We assume the absolute position of query \\(P_q\\) is range from (0, query_size) and the absolute position of key \\(P_k\\) is range from (0, key_size), The relative positions from query to key is \\(R_{q \\rightarrow k} = P_q - P_k\\)
Args: query_size (int): the length of query key_size (int): the length of key bucket_size (int): the size of position bucket max_position (int): the maximum allowed absolute position device (`torch.device`): the device on which tensors will be created.
Return: `torch.LongTensor`: A tensor with shape [1, query_size, key_size] """
q_ids = torch.arange(0, query_size, device=device) k_ids = torch.arange(0, key_size, device=device) rel_pos_ids = q_ids[:, None] - k_ids[None, :] if bucket_size > 0 and max_position > 0: rel_pos_ids = make_log_bucket_position(rel_pos_ids, bucket_size, max_position) rel_pos_ids = rel_pos_ids.to(torch.long) rel_pos_ids = rel_pos_ids[:query_size, :] rel_pos_ids = rel_pos_ids.unsqueeze(0) return rel_pos_ids
@torch.jit.script# Copied from transformers.models.deberta.modeling_deberta.c2p_dynamic_expanddef c2p_dynamic_expand(c2p_pos, query_layer, relative_pos): return c2p_pos.expand([query_layer.size(0), query_layer.size(1), query_layer.size(2), relative_pos.size(-1)])
@torch.jit.script# Copied from transformers.models.deberta.modeling_deberta.p2c_dynamic_expanddef p2c_dynamic_expand(c2p_pos, query_layer, key_layer): return c2p_pos.expand([query_layer.size(0), query_layer.size(1), key_layer.size(-2), key_layer.size(-2)])
@torch.jit.script# Copied from transformers.models.deberta.modeling_deberta.pos_dynamic_expanddef pos_dynamic_expand(pos_index, p2c_att, key_layer): return pos_index.expand(p2c_att.size()[:2] + (pos_index.size(-2), key_layer.size(-2)))
class DisentangledSelfAttention(nn.Module): """ Disentangled self-attention module
Parameters: config (`DebertaV2Config`): A model config class instance with the configuration to build a new model. The schema is similar to *BertConfig*, for more details, please refer [`DebertaV2Config`]
"""
def __init__(self, config): super().__init__() if config.hidden_size % config.num_attention_heads != 0: raise ValueError( f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention " f"heads ({config.num_attention_heads})" ) self.num_attention_heads = config.num_attention_heads _attention_head_size = config.hidden_size // config.num_attention_heads self.attention_head_size = getattr(config, "attention_head_size", _attention_head_size) self.all_head_size = self.num_attention_heads * self.attention_head_size self.query_proj = nn.Linear(config.hidden_size, self.all_head_size, bias=True) self.key_proj = nn.Linear(config.hidden_size, self.all_head_size, bias=True) self.value_proj = nn.Linear(config.hidden_size, self.all_head_size, bias=True)
self.share_att_key = getattr(config, "share_att_key", False) self.pos_att_type = config.pos_att_type if config.pos_att_type is not None else [] self.relative_attention = getattr(config, "relative_attention", False)
if self.relative_attention: self.position_buckets = getattr(config, "position_buckets", -1) self.max_relative_positions = getattr(config, "max_relative_positions", -1) if self.max_relative_positions < 1: self.max_relative_positions = config.max_position_embeddings self.pos_ebd_size = self.max_relative_positions if self.position_buckets > 0: self.pos_ebd_size = self.position_buckets
self.pos_dropout = StableDropout(config.hidden_dropout_prob)
if not self.share_att_key: if "c2p" in self.pos_att_type: self.pos_key_proj = nn.Linear(config.hidden_size, self.all_head_size, bias=True) if "p2c" in self.pos_att_type: self.pos_query_proj = nn.Linear(config.hidden_size, self.all_head_size)
self.dropout = StableDropout(config.attention_probs_dropout_prob)
def transpose_for_scores(self, x, attention_heads): new_x_shape = x.size()[:-1] + (attention_heads, -1) x = x.view(new_x_shape) return x.permute(0, 2, 1, 3).contiguous().view(-1, x.size(1), x.size(-1))
def forward( self, hidden_states, attention_mask, output_attentions=False, query_states=None, relative_pos=None, rel_embeddings=None, ): """ Call the module
Args: hidden_states (`torch.FloatTensor`): Input states to the module usually the output from previous layer, it will be the Q,K and V in *Attention(Q,K,V)*
attention_mask (`torch.BoolTensor`): An attention mask matrix of shape [*B*, *N*, *N*] where *B* is the batch size, *N* is the maximum sequence length in which element [i,j] = *1* means the *i* th token in the input can attend to the *j* th token.
output_attentions (`bool`, optional): Whether return the attention matrix.
query_states (`torch.FloatTensor`, optional): The *Q* state in *Attention(Q,K,V)*.
relative_pos (`torch.LongTensor`): The relative position encoding between the tokens in the sequence. It's of shape [*B*, *N*, *N*] with values ranging in [*-max_relative_positions*, *max_relative_positions*].
rel_embeddings (`torch.FloatTensor`): The embedding of relative distances. It's a tensor of shape [\\(2 \\times \\text{max_relative_positions}\\), *hidden_size*].
""" if query_states is None: query_states = hidden_states query_layer = self.transpose_for_scores(self.query_proj(query_states), self.num_attention_heads) key_layer = self.transpose_for_scores(self.key_proj(hidden_states), self.num_attention_heads) value_layer = self.transpose_for_scores(self.value_proj(hidden_states), self.num_attention_heads)
rel_att = None # Take the dot product between "query" and "key" to get the raw attention scores. scale_factor = 1 if "c2p" in self.pos_att_type: scale_factor += 1 if "p2c" in self.pos_att_type: scale_factor += 1 scale = torch.sqrt(torch.tensor(query_layer.size(-1), dtype=torch.float) * scale_factor) attention_scores = torch.bmm(query_layer, key_layer.transpose(-1, -2)) / scale.to(dtype=query_layer.dtype) if self.relative_attention: rel_embeddings = self.pos_dropout(rel_embeddings) rel_att = self.disentangled_attention_bias( query_layer, key_layer, relative_pos, rel_embeddings, scale_factor )
if rel_att is not None: attention_scores = attention_scores + rel_att attention_scores = attention_scores attention_scores = attention_scores.view( -1, self.num_attention_heads, attention_scores.size(-2), attention_scores.size(-1) )
# bsz x height x length x dimension attention_probs = XSoftmax.apply(attention_scores, attention_mask, -1) attention_probs = self.dropout(attention_probs) context_layer = torch.bmm( attention_probs.view(-1, attention_probs.size(-2), attention_probs.size(-1)), value_layer ) context_layer = ( context_layer.view(-1, self.num_attention_heads, context_layer.size(-2), context_layer.size(-1)) .permute(0, 2, 1, 3) .contiguous() ) new_context_layer_shape = context_layer.size()[:-2] + (-1,) context_layer = context_layer.view(new_context_layer_shape) if output_attentions: return (context_layer, attention_probs) else: return context_layer
def disentangled_attention_bias(self, query_layer, key_layer, relative_pos, rel_embeddings, scale_factor): if relative_pos is None: q = query_layer.size(-2) relative_pos = build_relative_position( q, key_layer.size(-2), bucket_size=self.position_buckets, max_position=self.max_relative_positions, device=query_layer.device, ) if relative_pos.dim() == 2: relative_pos = relative_pos.unsqueeze(0).unsqueeze(0) elif relative_pos.dim() == 3: relative_pos = relative_pos.unsqueeze(1) # bsz x height x query x key elif relative_pos.dim() != 4: raise ValueError(f"Relative position ids must be of dim 2 or 3 or 4. {relative_pos.dim()}")
att_span = self.pos_ebd_size relative_pos = relative_pos.long().to(query_layer.device)
rel_embeddings = rel_embeddings[0 : att_span * 2, :].unsqueeze(0) if self.share_att_key: pos_query_layer = self.transpose_for_scores( self.query_proj(rel_embeddings), self.num_attention_heads ).repeat(query_layer.size(0) // self.num_attention_heads, 1, 1) pos_key_layer = self.transpose_for_scores(self.key_proj(rel_embeddings), self.num_attention_heads).repeat( query_layer.size(0) // self.num_attention_heads, 1, 1 ) else: if "c2p" in self.pos_att_type: pos_key_layer = self.transpose_for_scores( self.pos_key_proj(rel_embeddings), self.num_attention_heads ).repeat( query_layer.size(0) // self.num_attention_heads, 1, 1 ) # .split(self.all_head_size, dim=-1) if "p2c" in self.pos_att_type: pos_query_layer = self.transpose_for_scores( self.pos_query_proj(rel_embeddings), self.num_attention_heads ).repeat( query_layer.size(0) // self.num_attention_heads, 1, 1 ) # .split(self.all_head_size, dim=-1)
score = 0 # content->position if "c2p" in self.pos_att_type: scale = torch.sqrt(torch.tensor(pos_key_layer.size(-1), dtype=torch.float) * scale_factor) c2p_att = torch.bmm(query_layer, pos_key_layer.transpose(-1, -2)) c2p_pos = torch.clamp(relative_pos + att_span, 0, att_span * 2 - 1) c2p_att = torch.gather( c2p_att, dim=-1, index=c2p_pos.squeeze(0).expand([query_layer.size(0), query_layer.size(1), relative_pos.size(-1)]), ) score += c2p_att / scale.to(dtype=c2p_att.dtype)
# position->content if "p2c" in self.pos_att_type: scale = torch.sqrt(torch.tensor(pos_query_layer.size(-1), dtype=torch.float) * scale_factor) if key_layer.size(-2) != query_layer.size(-2): r_pos = build_relative_position( key_layer.size(-2), key_layer.size(-2), bucket_size=self.position_buckets, max_position=self.max_relative_positions, device=query_layer.device, ) r_pos = r_pos.unsqueeze(0) else: r_pos = relative_pos
p2c_pos = torch.clamp(-r_pos + att_span, 0, att_span * 2 - 1) p2c_att = torch.bmm(key_layer, pos_query_layer.transpose(-1, -2)) p2c_att = torch.gather( p2c_att, dim=-1, index=p2c_pos.squeeze(0).expand([query_layer.size(0), key_layer.size(-2), key_layer.size(-2)]), ).transpose(-1, -2) score += p2c_att / scale.to(dtype=p2c_att.dtype)
return score
# Copied from transformers.models.deberta.modeling_deberta.DebertaEmbeddings with DebertaLayerNorm->LayerNormclass DebertaV2Embeddings(nn.Module): """Construct the embeddings from word, position and token_type embeddings."""
def __init__(self, config): super().__init__() pad_token_id = getattr(config, "pad_token_id", 0) self.embedding_size = getattr(config, "embedding_size", config.hidden_size) self.word_embeddings = nn.Embedding(config.vocab_size, self.embedding_size, padding_idx=pad_token_id)
self.position_biased_input = getattr(config, "position_biased_input", True) if not self.position_biased_input: self.position_embeddings = None else: self.position_embeddings = nn.Embedding(config.max_position_embeddings, self.embedding_size)
if config.type_vocab_size > 0: self.token_type_embeddings = nn.Embedding(config.type_vocab_size, self.embedding_size)
if self.embedding_size != config.hidden_size: self.embed_proj = nn.Linear(self.embedding_size, config.hidden_size, bias=False) self.LayerNorm = LayerNorm(config.hidden_size, config.layer_norm_eps) self.dropout = StableDropout(config.hidden_dropout_prob) self.config = config
# position_ids (1, len position emb) is contiguous in memory and exported when serialized self.register_buffer("position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)))
def forward(self, input_ids=None, token_type_ids=None, position_ids=None, mask=None, inputs_embeds=None): if input_ids is not None: input_shape = input_ids.size() else: input_shape = inputs_embeds.size()[:-1]
seq_length = input_shape[1]
if position_ids is None: position_ids = self.position_ids[:, :seq_length]
if token_type_ids is None: token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
if inputs_embeds is None: inputs_embeds = self.word_embeddings(input_ids)
if self.position_embeddings is not None: position_embeddings = self.position_embeddings(position_ids.long()) else: position_embeddings = torch.zeros_like(inputs_embeds)
embeddings = inputs_embeds if self.position_biased_input: embeddings += position_embeddings if self.config.type_vocab_size > 0: token_type_embeddings = self.token_type_embeddings(token_type_ids) embeddings += token_type_embeddings
if self.embedding_size != self.config.hidden_size: embeddings = self.embed_proj(embeddings)
embeddings = self.LayerNorm(embeddings)
if mask is not None: if mask.dim() != embeddings.dim(): if mask.dim() == 4: mask = mask.squeeze(1).squeeze(1) mask = mask.unsqueeze(2) mask = mask.to(embeddings.dtype)
embeddings = embeddings * mask
embeddings = self.dropout(embeddings) return embeddings
# Copied from transformers.models.deberta.modeling_deberta.DebertaPreTrainedModel with Deberta->DebertaV2class DebertaV2PreTrainedModel(PreTrainedModel): """ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models. """
config_class = DebertaV2Config base_model_prefix = "deberta" _keys_to_ignore_on_load_missing = ["position_ids"] _keys_to_ignore_on_load_unexpected = ["position_embeddings"] supports_gradient_checkpointing = True
def _init_weights(self, module): """Initialize the weights.""" if isinstance(module, nn.Linear): # Slightly different from the TF version which uses truncated_normal for initialization # cf https://github.com/pytorch/pytorch/pull/5617 module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) if module.bias is not None: module.bias.data.zero_() elif isinstance(module, nn.Embedding): module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) if module.padding_idx is not None: module.weight.data[module.padding_idx].zero_()
def _set_gradient_checkpointing(self, module, value=False): if isinstance(module, DebertaV2Encoder): module.gradient_checkpointing = value
DEBERTA_START_DOCSTRING = r""" The DeBERTa model was proposed in [DeBERTa: Decoding-enhanced BERT with Disentangled Attention](https://arxiv.org/abs/2006.03654) by Pengcheng He, Xiaodong Liu, Jianfeng Gao, Weizhu Chen. It's build on top of BERT/RoBERTa with two improvements, i.e. disentangled attention and enhanced mask decoder. With those two improvements, it out perform BERT/RoBERTa on a majority of tasks with 80GB pretraining data.
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
Parameters: config ([`DebertaV2Config`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights."""
DEBERTA_INPUTS_DOCSTRING = r""" Args: input_ids (`torch.LongTensor` of shape `({0})`): Indices of input sequence tokens in the vocabulary.
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details.
[What are input IDs?](../glossary#input-ids) attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*): Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
- 1 for tokens that are **not masked**, - 0 for tokens that are **masked**.
[What are attention masks?](../glossary#attention-mask) token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*): Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0, 1]`:
- 0 corresponds to a *sentence A* token, - 1 corresponds to a *sentence B* token.
[What are token type IDs?](../glossary#token-type-ids) position_ids (`torch.LongTensor` of shape `({0})`, *optional*): Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0, config.max_position_embeddings - 1]`.
[What are position IDs?](../glossary#position-ids) inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*): Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert *input_ids* indices into associated vectors than the model's internal embedding lookup matrix. output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple."""
@add_start_docstrings( "The bare DeBERTa Model transformer outputting raw hidden-states without any specific head on top.", DEBERTA_START_DOCSTRING,)# Copied from transformers.models.deberta.modeling_deberta.DebertaModel with Deberta->DebertaV2class DebertaV2Model(DebertaV2PreTrainedModel): def __init__(self, config): super().__init__(config)
self.embeddings = DebertaV2Embeddings(config) self.encoder = DebertaV2Encoder(config) self.z_steps = 0 self.config = config # Initialize weights and apply final processing self.post_init()
def get_input_embeddings(self): return self.embeddings.word_embeddings
def set_input_embeddings(self, new_embeddings): self.embeddings.word_embeddings = new_embeddings
def _prune_heads(self, heads_to_prune): """ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base class PreTrainedModel """ raise NotImplementedError("The prune function is not implemented in DeBERTa model.")
@add_start_docstrings_to_model_forward(DEBERTA_INPUTS_DOCSTRING.format("batch_size, sequence_length")) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC, output_type=BaseModelOutput, config_class=_CONFIG_FOR_DOC, ) def forward( self, input_ids: Optional[torch.Tensor] = None, attention_mask: Optional[torch.Tensor] = None, token_type_ids: Optional[torch.Tensor] = None, position_ids: Optional[torch.Tensor] = None, inputs_embeds: Optional[torch.Tensor] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> Union[Tuple, BaseModelOutput]: output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) return_dict = return_dict if return_dict is not None else self.config.use_return_dict
if input_ids is not None and inputs_embeds is not None: raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time") elif input_ids is not None: input_shape = input_ids.size() elif inputs_embeds is not None: input_shape = inputs_embeds.size()[:-1] else: raise ValueError("You have to specify either input_ids or inputs_embeds")
device = input_ids.device if input_ids is not None else inputs_embeds.device
if attention_mask is None: attention_mask = torch.ones(input_shape, device=device) if token_type_ids is None: token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
embedding_output = self.embeddings( input_ids=input_ids, token_type_ids=token_type_ids, position_ids=position_ids, mask=attention_mask, inputs_embeds=inputs_embeds, )
encoder_outputs = self.encoder( embedding_output, attention_mask, output_hidden_states=True, output_attentions=output_attentions, return_dict=return_dict, ) encoded_layers = encoder_outputs[1]
if self.z_steps > 1: hidden_states = encoded_layers[-2] layers = [self.encoder.layer[-1] for _ in range(self.z_steps)] query_states = encoded_layers[-1] rel_embeddings = self.encoder.get_rel_embedding() attention_mask = self.encoder.get_attention_mask(attention_mask) rel_pos = self.encoder.get_rel_pos(embedding_output) for layer in layers[1:]: query_states = layer( hidden_states, attention_mask, output_attentions=False, query_states=query_states, relative_pos=rel_pos, rel_embeddings=rel_embeddings, ) encoded_layers.append(query_states)
sequence_output = encoded_layers[-1]
if not return_dict: return (sequence_output,) + encoder_outputs[(1 if output_hidden_states else 2) :]
return BaseModelOutput( last_hidden_state=sequence_output, hidden_states=encoder_outputs.hidden_states if output_hidden_states else None, attentions=encoder_outputs.attentions, )
@add_start_docstrings("""DeBERTa Model with a `language modeling` head on top.""", DEBERTA_START_DOCSTRING)class DebertaV2ForMaskedLM(DebertaV2PreTrainedModel): _keys_to_ignore_on_load_unexpected = [r"pooler"] _keys_to_ignore_on_load_missing = [r"position_ids", r"predictions.decoder.bias", "cls.predictions.decoder.weight"]
def __init__(self, config): super().__init__(config)
self.deberta = DebertaV2Model(config) self.cls = DebertaV2OnlyMLMHead(config)
# Initialize weights and apply final processing self.post_init()
def get_output_embeddings(self): return self.cls.predictions.decoder
def set_output_embeddings(self, new_embeddings): self.cls.predictions.decoder = new_embeddings
@add_start_docstrings_to_model_forward(DEBERTA_INPUTS_DOCSTRING.format("batch_size, sequence_length")) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC, output_type=MaskedLMOutput, config_class=_CONFIG_FOR_DOC, mask="[MASK]", ) # Copied from transformers.models.deberta.modeling_deberta.DebertaForMaskedLM.forward with Deberta->DebertaV2 def forward( self, input_ids: Optional[torch.Tensor] = None, attention_mask: Optional[torch.Tensor] = None, token_type_ids: Optional[torch.Tensor] = None, position_ids: Optional[torch.Tensor] = None, inputs_embeds: Optional[torch.Tensor] = None, labels: Optional[torch.Tensor] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> Union[Tuple, MaskedLMOutput]: r""" labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]` """
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
outputs = self.deberta( input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, inputs_embeds=inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, )
sequence_output = outputs[0] prediction_scores = self.cls(sequence_output)
masked_lm_loss = None if labels is not None: loss_fct = CrossEntropyLoss() # -100 index = padding token masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
if not return_dict: output = (prediction_scores,) + outputs[1:] return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
return MaskedLMOutput( loss=masked_lm_loss, logits=prediction_scores, hidden_states=outputs.hidden_states, attentions=outputs.attentions, )
# copied from transformers.models.bert.BertPredictionHeadTransform with bert -> debertaclass DebertaV2PredictionHeadTransform(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) if isinstance(config.hidden_act, str): self.transform_act_fn = ACT2FN[config.hidden_act] else: self.transform_act_fn = config.hidden_act self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
def forward(self, hidden_states): hidden_states = self.dense(hidden_states) hidden_states = self.transform_act_fn(hidden_states) hidden_states = self.LayerNorm(hidden_states) return hidden_states
# copied from transformers.models.bert.BertLMPredictionHead with bert -> debertaclass DebertaV2LMPredictionHead(nn.Module): def __init__(self, config): super().__init__() self.transform = DebertaV2PredictionHeadTransform(config)
# The output weights are the same as the input embeddings, but there is # an output-only bias for each token. self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
self.bias = nn.Parameter(torch.zeros(config.vocab_size))
# Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings` self.decoder.bias = self.bias
def forward(self, hidden_states): hidden_states = self.transform(hidden_states) hidden_states = self.decoder(hidden_states) return hidden_states
# copied from transformers.models.bert.BertOnlyMLMHead with bert -> debertaclass DebertaV2OnlyMLMHead(nn.Module): def __init__(self, config): super().__init__() self.predictions = DebertaV2LMPredictionHead(config)
def forward(self, sequence_output): prediction_scores = self.predictions(sequence_output) return prediction_scores
@add_start_docstrings( """ DeBERTa Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output) e.g. for GLUE tasks. """, DEBERTA_START_DOCSTRING,)class DebertaV2ForSequenceClassification(DebertaV2PreTrainedModel): def __init__(self, config): super().__init__(config)
num_labels = getattr(config, "num_labels", 2) self.num_labels = num_labels
self.deberta = DebertaV2Model(config) self.pooler = ContextPooler(config) output_dim = self.pooler.output_dim
self.classifier = nn.Linear(output_dim, num_labels) drop_out = getattr(config, "cls_dropout", None) drop_out = self.config.hidden_dropout_prob if drop_out is None else drop_out self.dropout = StableDropout(drop_out)
# Initialize weights and apply final processing self.post_init()
def get_input_embeddings(self): return self.deberta.get_input_embeddings()
def set_input_embeddings(self, new_embeddings): self.deberta.set_input_embeddings(new_embeddings)
@add_start_docstrings_to_model_forward(DEBERTA_INPUTS_DOCSTRING.format("batch_size, sequence_length")) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC, output_type=SequenceClassifierOutput, config_class=_CONFIG_FOR_DOC, ) # Copied from transformers.models.deberta.modeling_deberta.DebertaForSequenceClassification.forward with Deberta->DebertaV2 def forward( self, input_ids: Optional[torch.Tensor] = None, attention_mask: Optional[torch.Tensor] = None, token_type_ids: Optional[torch.Tensor] = None, position_ids: Optional[torch.Tensor] = None, inputs_embeds: Optional[torch.Tensor] = None, labels: Optional[torch.Tensor] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> Union[Tuple, SequenceClassifierOutput]: r""" labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): Labels for computing the sequence classification/regression loss. Indices should be in `[0, ..., config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If `config.num_labels > 1` a classification loss is computed (Cross-Entropy). """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
outputs = self.deberta( input_ids, token_type_ids=token_type_ids, attention_mask=attention_mask, position_ids=position_ids, inputs_embeds=inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, )
encoder_layer = outputs[0] pooled_output = self.pooler(encoder_layer) pooled_output = self.dropout(pooled_output) logits = self.classifier(pooled_output)
loss = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: # regression task loss_fn = nn.MSELoss() logits = logits.view(-1).to(labels.dtype) loss = loss_fn(logits, labels.view(-1)) elif labels.dim() == 1 or labels.size(-1) == 1: label_index = (labels >= 0).nonzero() labels = labels.long() if label_index.size(0) > 0: labeled_logits = torch.gather( logits, 0, label_index.expand(label_index.size(0), logits.size(1)) ) labels = torch.gather(labels, 0, label_index.view(-1)) loss_fct = CrossEntropyLoss() loss = loss_fct(labeled_logits.view(-1, self.num_labels).float(), labels.view(-1)) else: loss = torch.tensor(0).to(logits) else: log_softmax = nn.LogSoftmax(-1) loss = -((log_softmax(logits) * labels).sum(-1)).mean() elif self.config.problem_type == "regression": loss_fct = MSELoss() if self.num_labels == 1: loss = loss_fct(logits.squeeze(), labels.squeeze()) else: loss = loss_fct(logits, labels) elif self.config.problem_type == "single_label_classification": loss_fct = CrossEntropyLoss() loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1)) elif self.config.problem_type == "multi_label_classification": loss_fct = BCEWithLogitsLoss() loss = loss_fct(logits, labels) if not return_dict: output = (logits,) + outputs[1:] return ((loss,) + output) if loss is not None else output
return SequenceClassifierOutput( loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions )
@add_start_docstrings( """ DeBERTa Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for Named-Entity-Recognition (NER) tasks. """, DEBERTA_START_DOCSTRING,)# Copied from transformers.models.deberta.modeling_deberta.DebertaForTokenClassification with Deberta->DebertaV2class DebertaV2ForTokenClassification(DebertaV2PreTrainedModel): _keys_to_ignore_on_load_unexpected = [r"pooler"]
def __init__(self, config): super().__init__(config) self.num_labels = config.num_labels
self.deberta = DebertaV2Model(config) self.dropout = nn.Dropout(config.hidden_dropout_prob) self.classifier = nn.Linear(config.hidden_size, config.num_labels)
# Initialize weights and apply final processing self.post_init()
@add_start_docstrings_to_model_forward(DEBERTA_INPUTS_DOCSTRING.format("batch_size, sequence_length")) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC, output_type=TokenClassifierOutput, config_class=_CONFIG_FOR_DOC, ) def forward( self, input_ids: Optional[torch.Tensor] = None, attention_mask: Optional[torch.Tensor] = None, token_type_ids: Optional[torch.Tensor] = None, position_ids: Optional[torch.Tensor] = None, inputs_embeds: Optional[torch.Tensor] = None, labels: Optional[torch.Tensor] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> Union[Tuple, TokenClassifierOutput]: r""" labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`. """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
outputs = self.deberta( input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, inputs_embeds=inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, )
sequence_output = outputs[0]
sequence_output = self.dropout(sequence_output) logits = self.classifier(sequence_output)
loss = None if labels is not None: loss_fct = CrossEntropyLoss() loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
if not return_dict: output = (logits,) + outputs[1:] return ((loss,) + output) if loss is not None else output
return TokenClassifierOutput( loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions ) class TokenClassifierRegressionOutput(ModelOutput): """ Base class for outputs of token classification models.
Args: loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided) : Classification loss. logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.num_labels)`): Classification scores (before SoftMax). hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs. attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`.
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. """
loss: Optional[torch.FloatTensor] = None logits: torch.FloatTensor = None values: torch.FloatTensor = None hidden_states: Optional[Tuple[torch.FloatTensor]] = None attentions: Optional[Tuple[torch.FloatTensor]] = None class DebertaV2ForTokenClassificationRegression(DebertaV2PreTrainedModel): _keys_to_ignore_on_load_unexpected = [r"pooler"]
def __init__(self, config): super().__init__(config) self.num_labels = 4
self.deberta = DebertaV2Model(config) self.dropout = nn.Dropout(config.hidden_dropout_prob) self.hidden1 = nn.Linear(config.hidden_size, config.hidden_size) self.classifier = nn.Linear(config.hidden_size, self.num_labels) self.hidden2 = nn.Linear(config.hidden_size, config.hidden_size) self.regressor = nn.Linear(config.hidden_size, 1)
# Initialize weights and apply final processing self.post_init()
@add_start_docstrings_to_model_forward(DEBERTA_INPUTS_DOCSTRING.format("batch_size, sequence_length")) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC, output_type=TokenClassifierOutput, config_class=_CONFIG_FOR_DOC, ) def forward( self, input_ids: Optional[torch.Tensor] = None, attention_mask: Optional[torch.Tensor] = None, token_type_ids: Optional[torch.Tensor] = None, position_ids: Optional[torch.Tensor] = None, inputs_embeds: Optional[torch.Tensor] = None, labels: Optional[torch.Tensor] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> Union[Tuple, TokenClassifierOutput]: r""" labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`. """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
outputs = self.deberta( input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, inputs_embeds=inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, )
sequence_output = outputs[0]
sequence_output = self.dropout(sequence_output) logits = self.classifier(self.hidden1(sequence_output)) values = self.regressor(self.hidden2(sequence_output))
loss = None if labels is not None: loss_fct = CrossEntropyLoss() loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
if not return_dict: output = (logits,) + outputs[1:] return ((loss,) + output) if loss is not None else output
return TokenClassifierRegressionOutput( loss=loss, logits=logits, values=values, hidden_states=outputs.hidden_states, attentions=outputs.attentions )
@add_start_docstrings( """ DeBERTa Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`). """, DEBERTA_START_DOCSTRING,)class DebertaV2ForQuestionAnswering(DebertaV2PreTrainedModel): _keys_to_ignore_on_load_unexpected = [r"pooler"]
def __init__(self, config): super().__init__(config) self.num_labels = config.num_labels
self.deberta = DebertaV2Model(config) self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
# Initialize weights and apply final processing self.post_init()
@add_start_docstrings_to_model_forward(DEBERTA_INPUTS_DOCSTRING.format("batch_size, sequence_length")) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC, output_type=QuestionAnsweringModelOutput, config_class=_CONFIG_FOR_DOC, qa_target_start_index=_QA_TARGET_START_INDEX, qa_target_end_index=_QA_TARGET_END_INDEX, ) # Copied from transformers.models.deberta.modeling_deberta.DebertaForQuestionAnswering.forward with Deberta->DebertaV2 def forward( self, input_ids: Optional[torch.Tensor] = None, attention_mask: Optional[torch.Tensor] = None, token_type_ids: Optional[torch.Tensor] = None, position_ids: Optional[torch.Tensor] = None, inputs_embeds: Optional[torch.Tensor] = None, start_positions: Optional[torch.Tensor] = None, end_positions: Optional[torch.Tensor] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> Union[Tuple, QuestionAnsweringModelOutput]: r""" start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*): Labels for position (index) of the start of the labelled span for computing the token classification loss. Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence are not taken into account for computing the loss. end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*): Labels for position (index) of the end of the labelled span for computing the token classification loss. Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence are not taken into account for computing the loss. """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
outputs = self.deberta( input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, inputs_embeds=inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, )
sequence_output = outputs[0]
logits = self.qa_outputs(sequence_output) start_logits, end_logits = logits.split(1, dim=-1) start_logits = start_logits.squeeze(-1).contiguous() end_logits = end_logits.squeeze(-1).contiguous()
total_loss = None if start_positions is not None and end_positions is not None: # If we are on multi-GPU, split add a dimension if len(start_positions.size()) > 1: start_positions = start_positions.squeeze(-1) if len(end_positions.size()) > 1: end_positions = end_positions.squeeze(-1) # sometimes the start/end positions are outside our model inputs, we ignore these terms ignored_index = start_logits.size(1) start_positions = start_positions.clamp(0, ignored_index) end_positions = end_positions.clamp(0, ignored_index)
loss_fct = CrossEntropyLoss(ignore_index=ignored_index) start_loss = loss_fct(start_logits, start_positions) end_loss = loss_fct(end_logits, end_positions) total_loss = (start_loss + end_loss) / 2
if not return_dict: output = (start_logits, end_logits) + outputs[1:] return ((total_loss,) + output) if total_loss is not None else output
return QuestionAnsweringModelOutput( loss=total_loss, start_logits=start_logits, end_logits=end_logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions, )
@add_start_docstrings( """ DeBERTa Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a softmax) e.g. for RocStories/SWAG tasks. """, DEBERTA_START_DOCSTRING,)class DebertaV2ForMultipleChoice(DebertaV2PreTrainedModel): def __init__(self, config): super().__init__(config)
num_labels = getattr(config, "num_labels", 2) self.num_labels = num_labels
self.deberta = DebertaV2Model(config) self.pooler = ContextPooler(config) output_dim = self.pooler.output_dim
self.classifier = nn.Linear(output_dim, 1) drop_out = getattr(config, "cls_dropout", None) drop_out = self.config.hidden_dropout_prob if drop_out is None else drop_out self.dropout = StableDropout(drop_out)
self.init_weights()
def get_input_embeddings(self): return self.deberta.get_input_embeddings()
def set_input_embeddings(self, new_embeddings): self.deberta.set_input_embeddings(new_embeddings)
@add_start_docstrings_to_model_forward(DEBERTA_INPUTS_DOCSTRING.format("batch_size, sequence_length")) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC, output_type=MultipleChoiceModelOutput, config_class=_CONFIG_FOR_DOC, ) def forward( self, input_ids: Optional[torch.Tensor] = None, attention_mask: Optional[torch.Tensor] = None, token_type_ids: Optional[torch.Tensor] = None, position_ids: Optional[torch.Tensor] = None, inputs_embeds: Optional[torch.Tensor] = None, labels: Optional[torch.Tensor] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> Union[Tuple, MultipleChoiceModelOutput]: r""" labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): Labels for computing the multiple choice classification loss. Indices should be in `[0, ..., num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See `input_ids` above) """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
flat_input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None flat_position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None flat_token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None flat_attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None flat_inputs_embeds = ( inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1)) if inputs_embeds is not None else None )
outputs = self.deberta( flat_input_ids, position_ids=flat_position_ids, token_type_ids=flat_token_type_ids, attention_mask=flat_attention_mask, inputs_embeds=flat_inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, )
encoder_layer = outputs[0] pooled_output = self.pooler(encoder_layer) pooled_output = self.dropout(pooled_output) logits = self.classifier(pooled_output) reshaped_logits = logits.view(-1, num_choices)
loss = None if labels is not None: loss_fct = CrossEntropyLoss() loss = loss_fct(reshaped_logits, labels)
if not return_dict: output = (reshaped_logits,) + outputs[1:] return ((loss,) + output) if loss is not None else output
return MultipleChoiceModelOutput( loss=loss, logits=reshaped_logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738import yamlimport randomimport inspectimport numpy as npfrom tqdm import tqdm
import torchimport torch.nn as nnimport torch.nn.functional as F
from einops import repeatfrom tools.torch_tools import wav_to_fbank
from audioldm.audio.stft import TacotronSTFTfrom audioldm.variational_autoencoder import AutoencoderKLfrom audioldm.utils import default_audioldm_config, get_metadata
from transformers import CLIPTokenizer, AutoTokenizer, AutoProcessorfrom transformers import CLIPTextModel, T5EncoderModel, AutoModel, ClapAudioModel, ClapTextModel
import syssys.path.insert(0, "diffusers/src")
import diffusersfrom diffusers.utils import randn_tensorfrom diffusers import DDPMScheduler, UNet2DConditionModel, UNet2DConditionModelMusicfrom diffusers import AutoencoderKL as DiffuserAutoencoderKLfrom layers.layers import chord_tokenizer, beat_tokenizer, Chord_Embedding, Beat_Embedding, Music_PositionalEncoding, Fundamental_Music_Embedding
def build_pretrained_models(name): checkpoint = torch.load(get_metadata()[name]["path"], map_location="cpu") scale_factor = checkpoint["state_dict"]["scale_factor"].item()
vae_state_dict = {k[18:]: v for k, v in checkpoint["state_dict"].items() if "first_stage_model." in k}
config = default_audioldm_config(name) vae_config = config["model"]["params"]["first_stage_config"]["params"] vae_config["scale_factor"] = scale_factor
vae = AutoencoderKL(**vae_config) vae.load_state_dict(vae_state_dict)
fn_STFT = TacotronSTFT( config["preprocessing"]["stft"]["filter_length"], config["preprocessing"]["stft"]["hop_length"], config["preprocessing"]["stft"]["win_length"], config["preprocessing"]["mel"]["n_mel_channels"], config["preprocessing"]["audio"]["sampling_rate"], config["preprocessing"]["mel"]["mel_fmin"], config["preprocessing"]["mel"]["mel_fmax"], )
vae.eval() fn_STFT.eval() return vae, fn_STFT
class AudioDiffusion(nn.Module): def __init__( self, text_encoder_name, scheduler_name, unet_model_name=None, unet_model_config_path=None, snr_gamma=None, freeze_text_encoder=True, uncondition=False,
): super().__init__()
assert unet_model_name is not None or unet_model_config_path is not None, "Either UNet pretrain model name or a config file path is required"
self.text_encoder_name = text_encoder_name self.scheduler_name = scheduler_name self.unet_model_name = unet_model_name self.unet_model_config_path = unet_model_config_path self.snr_gamma = snr_gamma self.freeze_text_encoder = freeze_text_encoder self.uncondition = uncondition
# https://huggingface.co/docs/diffusers/v0.14.0/en/api/schedulers/overview self.noise_scheduler = DDPMScheduler.from_pretrained(self.scheduler_name, subfolder="scheduler") self.inference_scheduler = DDPMScheduler.from_pretrained(self.scheduler_name, subfolder="scheduler")
if unet_model_config_path: unet_config = UNet2DConditionModel.load_config(unet_model_config_path) self.unet = UNet2DConditionModel.from_config(unet_config, subfolder="unet") self.set_from = "random" print("UNet initialized randomly.") else: self.unet = UNet2DConditionModel.from_pretrained(unet_model_name, subfolder="unet") self.set_from = "pre-trained" self.group_in = nn.Sequential(nn.Linear(8, 512), nn.Linear(512, 4)) self.group_out = nn.Sequential(nn.Linear(4, 512), nn.Linear(512, 8)) print("UNet initialized from stable diffusion checkpoint.")
if "stable-diffusion" in self.text_encoder_name: self.tokenizer = CLIPTokenizer.from_pretrained(self.text_encoder_name, subfolder="tokenizer") self.text_encoder = CLIPTextModel.from_pretrained(self.text_encoder_name, subfolder="text_encoder") elif "t5" in self.text_encoder_name: self.tokenizer = AutoTokenizer.from_pretrained(self.text_encoder_name) self.text_encoder = T5EncoderModel.from_pretrained(self.text_encoder_name) else: self.tokenizer = AutoTokenizer.from_pretrained(self.text_encoder_name) self.text_encoder = AutoModel.from_pretrained(self.text_encoder_name)
def compute_snr(self, timesteps): """ Computes SNR as per https://github.com/TiankaiHang/Min-SNR-Diffusion-Training/blob/521b624bd70c67cee4bdf49225915f5945a872e3/guided_diffusion/gaussian_diffusion.py#L847-L849 """ alphas_cumprod = self.noise_scheduler.alphas_cumprod sqrt_alphas_cumprod = alphas_cumprod**0.5 sqrt_one_minus_alphas_cumprod = (1.0 - alphas_cumprod) ** 0.5
# Expand the tensors. # Adapted from https://github.com/TiankaiHang/Min-SNR-Diffusion-Training/blob/521b624bd70c67cee4bdf49225915f5945a872e3/guided_diffusion/gaussian_diffusion.py#L1026 sqrt_alphas_cumprod = sqrt_alphas_cumprod.to(device=timesteps.device)[timesteps].float() while len(sqrt_alphas_cumprod.shape) < len(timesteps.shape): sqrt_alphas_cumprod = sqrt_alphas_cumprod[..., None] alpha = sqrt_alphas_cumprod.expand(timesteps.shape)
sqrt_one_minus_alphas_cumprod = sqrt_one_minus_alphas_cumprod.to(device=timesteps.device)[timesteps].float() while len(sqrt_one_minus_alphas_cumprod.shape) < len(timesteps.shape): sqrt_one_minus_alphas_cumprod = sqrt_one_minus_alphas_cumprod[..., None] sigma = sqrt_one_minus_alphas_cumprod.expand(timesteps.shape)
# Compute SNR. snr = (alpha / sigma) ** 2 return snr
def encode_text(self, prompt): device = self.text_encoder.device batch = self.tokenizer( prompt, max_length=self.tokenizer.model_max_length, padding=True, truncation=True, return_tensors="pt" ) input_ids, attention_mask = batch.input_ids.to(device), batch.attention_mask.to(device)
if self.freeze_text_encoder: with torch.no_grad(): encoder_hidden_states = self.text_encoder( input_ids=input_ids, attention_mask=attention_mask )[0] else: encoder_hidden_states = self.text_encoder( input_ids=input_ids, attention_mask=attention_mask )[0]
boolean_encoder_mask = (attention_mask == 1).to(device) return encoder_hidden_states, boolean_encoder_mask
def forward(self, latents, prompt, validation_mode=False): device = self.text_encoder.device num_train_timesteps = self.noise_scheduler.num_train_timesteps self.noise_scheduler.set_timesteps(num_train_timesteps, device=device)
encoder_hidden_states, boolean_encoder_mask = self.encode_text(prompt)
if self.uncondition: mask_indices = [k for k in range(len(prompt)) if random.random() < 0.1] if len(mask_indices) > 0: encoder_hidden_states[mask_indices] = 0
bsz = latents.shape[0]
if validation_mode: timesteps = (self.noise_scheduler.num_train_timesteps//2) * torch.ones((bsz,), dtype=torch.int64, device=device) else: # Sample a random timestep for each instance timesteps = torch.randint(0, self.noise_scheduler.num_train_timesteps, (bsz,), device=device) # print('in if ', timesteps) timesteps = timesteps.long() # print('outside if ' , timesteps) noise = torch.randn_like(latents) noisy_latents = self.noise_scheduler.add_noise(latents, noise, timesteps)
# Get the target for loss depending on the prediction type if self.noise_scheduler.config.prediction_type == "epsilon": target = noise elif self.noise_scheduler.config.prediction_type == "v_prediction": target = self.noise_scheduler.get_velocity(latents, noise, timesteps) else: raise ValueError(f"Unknown prediction type {self.noise_scheduler.config.prediction_type}")
if self.set_from == "random": model_pred = self.unet( noisy_latents, timesteps, encoder_hidden_states, encoder_attention_mask=boolean_encoder_mask ).sample
elif self.set_from == "pre-trained": compressed_latents = self.group_in(noisy_latents.permute(0, 2, 3, 1).contiguous()).permute(0, 3, 1, 2).contiguous() model_pred = self.unet( compressed_latents, timesteps, encoder_hidden_states, encoder_attention_mask=boolean_encoder_mask ).sample model_pred = self.group_out(model_pred.permute(0, 2, 3, 1).contiguous()).permute(0, 3, 1, 2).contiguous()
if self.snr_gamma is None: loss = F.mse_loss(model_pred.float(), target.float(), reduction="mean") else: # Compute loss-weights as per Section 3.4 of https://arxiv.org/abs/2303.09556. # Adaptef from huggingface/diffusers/blob/main/examples/text_to_image/train_text_to_image.py snr = self.compute_snr(timesteps) mse_loss_weights = ( torch.stack([snr, self.snr_gamma * torch.ones_like(timesteps)], dim=1).min(dim=1)[0] / snr ) loss = F.mse_loss(model_pred.float(), target.float(), reduction="none") loss = loss.mean(dim=list(range(1, len(loss.shape)))) * mse_loss_weights loss = loss.mean()
return loss
@torch.no_grad() def inference(self, prompt, inference_scheduler, num_steps=20, guidance_scale=3, num_samples_per_prompt=1, disable_progress=True): device = self.text_encoder.device classifier_free_guidance = guidance_scale > 1.0 batch_size = len(prompt) * num_samples_per_prompt
if classifier_free_guidance: prompt_embeds, boolean_prompt_mask = self.encode_text_classifier_free(prompt, num_samples_per_prompt) else: prompt_embeds, boolean_prompt_mask = self.encode_text(prompt) prompt_embeds = prompt_embeds.repeat_interleave(num_samples_per_prompt, 0) boolean_prompt_mask = boolean_prompt_mask.repeat_interleave(num_samples_per_prompt, 0)
inference_scheduler.set_timesteps(num_steps, device=device) timesteps = inference_scheduler.timesteps
num_channels_latents = self.unet.in_channels latents = self.prepare_latents(batch_size, inference_scheduler, num_channels_latents, prompt_embeds.dtype, device)
num_warmup_steps = len(timesteps) - num_steps * inference_scheduler.order progress_bar = tqdm(range(num_steps), disable=disable_progress)
for i, t in enumerate(timesteps): # expand the latents if we are doing classifier free guidance latent_model_input = torch.cat([latents] * 2) if classifier_free_guidance else latents latent_model_input = inference_scheduler.scale_model_input(latent_model_input, t)
noise_pred = self.unet( latent_model_input, t, encoder_hidden_states=prompt_embeds, encoder_attention_mask=boolean_prompt_mask ).sample
# perform guidance if classifier_free_guidance: noise_pred_uncond, noise_pred_text = noise_pred.chunk(2) noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
# compute the previous noisy sample x_t -> x_t-1 latents = inference_scheduler.step(noise_pred, t, latents).prev_sample
# call the callback, if provided if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % inference_scheduler.order == 0): progress_bar.update(1)
if self.set_from == "pre-trained": latents = self.group_out(latents.permute(0, 2, 3, 1).contiguous()).permute(0, 3, 1, 2).contiguous() return latents
def prepare_latents(self, batch_size, inference_scheduler, num_channels_latents, dtype, device): shape = (batch_size, num_channels_latents, 256, 16) latents = randn_tensor(shape, generator=None, device=device, dtype=dtype) # scale the initial noise by the standard deviation required by the scheduler latents = latents * inference_scheduler.init_noise_sigma return latents
def encode_text_classifier_free(self, prompt, num_samples_per_prompt): device = self.text_encoder.device batch = self.tokenizer( prompt, max_length=self.tokenizer.model_max_length, padding=True, truncation=True, return_tensors="pt" ) input_ids, attention_mask = batch.input_ids.to(device), batch.attention_mask.to(device)
with torch.no_grad(): prompt_embeds = self.text_encoder( input_ids=input_ids, attention_mask=attention_mask )[0] prompt_embeds = prompt_embeds.repeat_interleave(num_samples_per_prompt, 0) attention_mask = attention_mask.repeat_interleave(num_samples_per_prompt, 0)
# get unconditional embeddings for classifier free guidance uncond_tokens = [""] * len(prompt)
max_length = prompt_embeds.shape[1] uncond_batch = self.tokenizer( uncond_tokens, max_length=max_length, padding="max_length", truncation=True, return_tensors="pt", ) uncond_input_ids = uncond_batch.input_ids.to(device) uncond_attention_mask = uncond_batch.attention_mask.to(device)
with torch.no_grad(): negative_prompt_embeds = self.text_encoder( input_ids=uncond_input_ids, attention_mask=uncond_attention_mask )[0] negative_prompt_embeds = negative_prompt_embeds.repeat_interleave(num_samples_per_prompt, 0) uncond_attention_mask = uncond_attention_mask.repeat_interleave(num_samples_per_prompt, 0)
# For classifier free guidance, we need to do two forward passes. # We concatenate the unconditional and text embeddings into a single batch to avoid doing two forward passes prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds]) prompt_mask = torch.cat([uncond_attention_mask, attention_mask]) boolean_prompt_mask = (prompt_mask == 1).to(device)
return prompt_embeds, boolean_prompt_mask
class MusicAudioDiffusion(nn.Module): def __init__( self, text_encoder_name, scheduler_name, unet_model_name=None, unet_model_config_path=None, snr_gamma=None, freeze_text_encoder=True, uncondition=False,
d_fme = 1024, #FME fme_type = "se", base = 1, if_trainable = True, translation_bias_type = "nd", emb_nn = True, d_pe = 1024, #PE if_index = True, if_global_timing = True, if_modulo_timing = False, d_beat = 1024, #Beat d_oh_beat_type = 7, beat_len = 50, d_chord = 1024, #Chord d_oh_chord_type = 12, d_oh_inv_type = 4, chord_len = 20,
): super().__init__()
assert unet_model_name is not None or unet_model_config_path is not None, "Either UNet pretrain model name or a config file path is required"
self.text_encoder_name = text_encoder_name self.scheduler_name = scheduler_name self.unet_model_name = unet_model_name self.unet_model_config_path = unet_model_config_path self.snr_gamma = snr_gamma self.freeze_text_encoder = freeze_text_encoder self.uncondition = uncondition
# https://huggingface.co/docs/diffusers/v0.14.0/en/api/schedulers/overview self.noise_scheduler = DDPMScheduler.from_pretrained(self.scheduler_name, subfolder="scheduler") self.inference_scheduler = DDPMScheduler.from_pretrained(self.scheduler_name, subfolder="scheduler")
if unet_model_config_path: unet_config = UNet2DConditionModelMusic.load_config(unet_model_config_path) self.unet = UNet2DConditionModelMusic.from_config(unet_config, subfolder="unet") self.set_from = "random" print("UNet initialized randomly.") else: self.unet = UNet2DConditionModel.from_pretrained(unet_model_name, subfolder="unet") self.set_from = "pre-trained" self.group_in = nn.Sequential(nn.Linear(8, 512), nn.Linear(512, 4)) self.group_out = nn.Sequential(nn.Linear(4, 512), nn.Linear(512, 8)) print("UNet initialized from stable diffusion checkpoint.")
if "stable-diffusion" in self.text_encoder_name: self.tokenizer = CLIPTokenizer.from_pretrained(self.text_encoder_name, subfolder="tokenizer") self.text_encoder = CLIPTextModel.from_pretrained(self.text_encoder_name, subfolder="text_encoder") elif "t5" in self.text_encoder_name: self.tokenizer = AutoTokenizer.from_pretrained(self.text_encoder_name) self.text_encoder = T5EncoderModel.from_pretrained(self.text_encoder_name) else: self.tokenizer = AutoTokenizer.from_pretrained(self.text_encoder_name) self.text_encoder = AutoModel.from_pretrained(self.text_encoder_name)
self.device = self.text_encoder.device #Music Feature Encoder self.FME = Fundamental_Music_Embedding(d_model = d_fme, base= base, if_trainable = False, type = fme_type,emb_nn=emb_nn,translation_bias_type = translation_bias_type) self.PE = Music_PositionalEncoding(d_model = d_pe, if_index = if_index, if_global_timing = if_global_timing, if_modulo_timing = if_modulo_timing, device = self.device) # self.PE2 = Music_PositionalEncoding(d_model = d_pe, if_index = if_index, if_global_timing = if_global_timing, if_modulo_timing = if_modulo_timing, device = self.device) self.beat_tokenizer = beat_tokenizer(seq_len_beat=beat_len, if_pad = True) self.beat_embedding_layer = Beat_Embedding(self.PE, d_model = d_beat, d_oh_beat_type = d_oh_beat_type) self.chord_embedding_layer = Chord_Embedding(self.FME, self.PE, d_model = d_chord, d_oh_type = d_oh_chord_type, d_oh_inv = d_oh_inv_type) self.chord_tokenizer = chord_tokenizer(seq_len_chord=chord_len, if_pad = True)
def compute_snr(self, timesteps): """ Computes SNR as per https://github.com/TiankaiHang/Min-SNR-Diffusion-Training/blob/521b624bd70c67cee4bdf49225915f5945a872e3/guided_diffusion/gaussian_diffusion.py#L847-L849 """ alphas_cumprod = self.noise_scheduler.alphas_cumprod sqrt_alphas_cumprod = alphas_cumprod**0.5 sqrt_one_minus_alphas_cumprod = (1.0 - alphas_cumprod) ** 0.5
# Expand the tensors. # Adapted from https://github.com/TiankaiHang/Min-SNR-Diffusion-Training/blob/521b624bd70c67cee4bdf49225915f5945a872e3/guided_diffusion/gaussian_diffusion.py#L1026 sqrt_alphas_cumprod = sqrt_alphas_cumprod.to(device=timesteps.device)[timesteps].float() while len(sqrt_alphas_cumprod.shape) < len(timesteps.shape): sqrt_alphas_cumprod = sqrt_alphas_cumprod[..., None] alpha = sqrt_alphas_cumprod.expand(timesteps.shape)
sqrt_one_minus_alphas_cumprod = sqrt_one_minus_alphas_cumprod.to(device=timesteps.device)[timesteps].float() while len(sqrt_one_minus_alphas_cumprod.shape) < len(timesteps.shape): sqrt_one_minus_alphas_cumprod = sqrt_one_minus_alphas_cumprod[..., None] sigma = sqrt_one_minus_alphas_cumprod.expand(timesteps.shape)
# Compute SNR. snr = (alpha / sigma) ** 2 return snr
def encode_text(self, prompt): device = self.text_encoder.device batch = self.tokenizer( prompt, max_length=self.tokenizer.model_max_length, padding=True, truncation=True, return_tensors="pt" ) input_ids, attention_mask = batch.input_ids.to(device), batch.attention_mask.to(device) #cuda if self.freeze_text_encoder: with torch.no_grad(): encoder_hidden_states = self.text_encoder( input_ids=input_ids, attention_mask=attention_mask )[0] #batch, len_text, dim else: encoder_hidden_states = self.text_encoder( input_ids=input_ids, attention_mask=attention_mask )[0] boolean_encoder_mask = (attention_mask == 1).to(device) ##batch, len_text return encoder_hidden_states, boolean_encoder_mask
def encode_beats(self, beats): # device = self.beat_embedding_layer.device out_beat = [] out_beat_timing = [] out_mask = [] for beat in beats: tokenized_beats,tokenized_beats_timing, tokenized_beat_mask = self.beat_tokenizer(beat) out_beat.append(tokenized_beats) out_beat_timing.append(tokenized_beats_timing) out_mask.append(tokenized_beat_mask) out_beat, out_beat_timing, out_mask = torch.tensor(out_beat).cuda(), torch.tensor(out_beat_timing).cuda(), torch.tensor(out_mask).cuda() #batch, len_beat embedded_beat = self.beat_embedding_layer(out_beat, out_beat_timing)
return embedded_beat, out_mask
def encode_chords(self, chords,chords_time): out_chord_root = [] out_chord_type = [] out_chord_inv = [] out_chord_timing = [] out_mask = [] for chord, chord_time in zip(chords,chords_time): #batch loop tokenized_chord_root, tokenized_chord_type, tokenized_chord_inv, tokenized_chord_time, tokenized_chord_mask = self.chord_tokenizer(chord, chord_time) out_chord_root.append(tokenized_chord_root) out_chord_type.append(tokenized_chord_type) out_chord_inv.append(tokenized_chord_inv) out_chord_timing.append(tokenized_chord_time) out_mask.append(tokenized_chord_mask) #chords: (B, LEN, 4) out_chord_root, out_chord_type, out_chord_inv, out_chord_timing, out_mask = torch.tensor(out_chord_root).cuda(), torch.tensor(out_chord_type).cuda(), torch.tensor(out_chord_inv).cuda(), torch.tensor(out_chord_timing).cuda(), torch.tensor(out_mask).cuda() embedded_chord = self.chord_embedding_layer(out_chord_root, out_chord_type, out_chord_inv, out_chord_timing) return embedded_chord, out_mask # return out_chord_root, out_mask
def forward(self, latents, prompt, beats, chords,chords_time, validation_mode=False): device = self.text_encoder.device num_train_timesteps = self.noise_scheduler.num_train_timesteps self.noise_scheduler.set_timesteps(num_train_timesteps, device=device)
encoder_hidden_states, boolean_encoder_mask = self.encode_text(prompt) # with torch.no_grad(): encoded_beats, beat_mask = self.encode_beats(beats) #batch, len_beats, dim; batch, len_beats encoded_chords, chord_mask = self.encode_chords(chords,chords_time)
if self.uncondition: mask_indices = [k for k in range(len(prompt)) if random.random() < 0.1] if len(mask_indices) > 0: encoder_hidden_states[mask_indices] = 0 encoded_chords[mask_indices] = 0 encoded_beats[mask_indices] = 0
bsz = latents.shape[0]
if validation_mode: timesteps = (self.noise_scheduler.num_train_timesteps//2) * torch.ones((bsz,), dtype=torch.int64, device=device) else: timesteps = torch.randint(0, self.noise_scheduler.num_train_timesteps, (bsz,), device=device) timesteps = timesteps.long()
noise = torch.randn_like(latents) noisy_latents = self.noise_scheduler.add_noise(latents, noise, timesteps)
# Get the target for loss depending on the prediction type if self.noise_scheduler.config.prediction_type == "epsilon": target = noise elif self.noise_scheduler.config.prediction_type == "v_prediction": target = self.noise_scheduler.get_velocity(latents, noise, timesteps) else: raise ValueError(f"Unknown prediction type {self.noise_scheduler.config.prediction_type}")
if self.set_from == "random": # model_pred = torch.zeros((bsz,8,256,16)).to(device) model_pred = self.unet( noisy_latents, timesteps, encoder_hidden_states, encoded_beats, encoded_chords, encoder_attention_mask=boolean_encoder_mask, beat_attention_mask = beat_mask, chord_attention_mask = chord_mask ).sample
elif self.set_from == "pre-trained": compressed_latents = self.group_in(noisy_latents.permute(0, 2, 3, 1).contiguous()).permute(0, 3, 1, 2).contiguous() model_pred = self.unet( compressed_latents, timesteps, encoder_hidden_states, encoder_attention_mask=boolean_encoder_mask ).sample model_pred = self.group_out(model_pred.permute(0, 2, 3, 1).contiguous()).permute(0, 3, 1, 2).contiguous()
if self.snr_gamma is None: loss = F.mse_loss(model_pred.float(), target.float(), reduction="mean") else: # Compute loss-weights as per Section 3.4 of https://arxiv.org/abs/2303.09556. # Adaptef from huggingface/diffusers/blob/main/examples/text_to_image/train_text_to_image.py snr = self.compute_snr(timesteps) mse_loss_weights = ( torch.stack([snr, self.snr_gamma * torch.ones_like(timesteps)], dim=1).min(dim=1)[0] / snr ) loss = F.mse_loss(model_pred.float(), target.float(), reduction="none") loss = loss.mean(dim=list(range(1, len(loss.shape)))) * mse_loss_weights loss = loss.mean()
return loss
@torch.no_grad() def inference(self, prompt, beats, chords,chords_time, inference_scheduler, num_steps=20, guidance_scale=3, num_samples_per_prompt=1, disable_progress=True): device = self.text_encoder.device classifier_free_guidance = guidance_scale > 1.0 batch_size = len(prompt) * num_samples_per_prompt
if classifier_free_guidance: prompt_embeds, boolean_prompt_mask = self.encode_text_classifier_free(prompt, num_samples_per_prompt) encoded_beats, beat_mask = self.encode_beats_classifier_free(beats, num_samples_per_prompt) #batch, len_beats, dim; batch, len_beats encoded_chords, chord_mask = self.encode_chords_classifier_free(chords, chords_time, num_samples_per_prompt) else: prompt_embeds, boolean_prompt_mask = self.encode_text(prompt) prompt_embeds = prompt_embeds.repeat_interleave(num_samples_per_prompt, 0) boolean_prompt_mask = boolean_prompt_mask.repeat_interleave(num_samples_per_prompt, 0)
encoded_beats, beat_mask = self.encode_beats(beats) #batch, len_beats, dim; batch, len_beats encoded_beats = encoded_beats.repeat_interleave(num_samples_per_prompt, 0) beat_mask = beat_mask.repeat_interleave(num_samples_per_prompt, 0)
encoded_chords, chord_mask = self.encode_chords(chords,chords_time) encoded_chords = encoded_chords.repeat_interleave(num_samples_per_prompt, 0) chord_mask = chord_mask.repeat_interleave(num_samples_per_prompt, 0)
# print(f"encoded_chords:{encoded_chords.shape}, chord_mask:{chord_mask.shape}, prompt_embeds:{prompt_embeds.shape},boolean_prompt_mask:{boolean_prompt_mask.shape} ") inference_scheduler.set_timesteps(num_steps, device=device) timesteps = inference_scheduler.timesteps
num_channels_latents = self.unet.in_channels latents = self.prepare_latents(batch_size, inference_scheduler, num_channels_latents, prompt_embeds.dtype, device)
num_warmup_steps = len(timesteps) - num_steps * inference_scheduler.order progress_bar = tqdm(range(num_steps), disable=disable_progress)
for i, t in enumerate(timesteps): # expand the latents if we are doing classifier free guidance latent_model_input = torch.cat([latents] * 2) if classifier_free_guidance else latents latent_model_input = inference_scheduler.scale_model_input(latent_model_input, t)
noise_pred = self.unet( latent_model_input, t, encoder_hidden_states=prompt_embeds, encoder_attention_mask=boolean_prompt_mask, beat_features = encoded_beats, beat_attention_mask = beat_mask, chord_features = encoded_chords,chord_attention_mask = chord_mask ).sample
# perform guidance if classifier_free_guidance: #should work for beats and chords too noise_pred_uncond, noise_pred_text = noise_pred.chunk(2) noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
# compute the previous noisy sample x_t -> x_t-1 latents = inference_scheduler.step(noise_pred, t, latents).prev_sample
# call the callback, if provided if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % inference_scheduler.order == 0): progress_bar.update(1)
if self.set_from == "pre-trained": latents = self.group_out(latents.permute(0, 2, 3, 1).contiguous()).permute(0, 3, 1, 2).contiguous() return latents
def prepare_latents(self, batch_size, inference_scheduler, num_channels_latents, dtype, device): shape = (batch_size, num_channels_latents, 256, 16) latents = randn_tensor(shape, generator=None, device=device, dtype=dtype) # scale the initial noise by the standard deviation required by the scheduler latents = latents * inference_scheduler.init_noise_sigma return latents
def encode_text_classifier_free(self, prompt, num_samples_per_prompt): device = self.text_encoder.device batch = self.tokenizer( prompt, max_length=self.tokenizer.model_max_length, padding=True, truncation=True, return_tensors="pt" ) input_ids, attention_mask = batch.input_ids.to(device), batch.attention_mask.to(device)
with torch.no_grad(): prompt_embeds = self.text_encoder( input_ids=input_ids, attention_mask=attention_mask )[0] prompt_embeds = prompt_embeds.repeat_interleave(num_samples_per_prompt, 0) attention_mask = attention_mask.repeat_interleave(num_samples_per_prompt, 0)
# get unconditional embeddings for classifier free guidance # print(len(prompt), 'this is prompt len') uncond_tokens = [""] * len(prompt)
max_length = prompt_embeds.shape[1] uncond_batch = self.tokenizer( uncond_tokens, max_length=max_length, padding="max_length", truncation=True, return_tensors="pt", ) uncond_input_ids = uncond_batch.input_ids.to(device) uncond_attention_mask = uncond_batch.attention_mask.to(device)
with torch.no_grad(): negative_prompt_embeds = self.text_encoder( input_ids=uncond_input_ids, attention_mask=uncond_attention_mask )[0] negative_prompt_embeds = negative_prompt_embeds.repeat_interleave(num_samples_per_prompt, 0) uncond_attention_mask = uncond_attention_mask.repeat_interleave(num_samples_per_prompt, 0)
# For classifier free guidance, we need to do two forward passes. # We concatenate the unconditional and text embeddings into a single batch to avoid doing two forward passes prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds]) prompt_mask = torch.cat([uncond_attention_mask, attention_mask]) boolean_prompt_mask = (prompt_mask == 1).to(device)
return prompt_embeds, boolean_prompt_mask
def encode_beats_classifier_free(self, beats, num_samples_per_prompt): with torch.no_grad(): out_beat = [] out_beat_timing = [] out_mask = [] for beat in beats: tokenized_beats,tokenized_beats_timing, tokenized_beat_mask = self.beat_tokenizer(beat) out_beat.append(tokenized_beats) out_beat_timing.append(tokenized_beats_timing) out_mask.append(tokenized_beat_mask) out_beat, out_beat_timing, out_mask = torch.tensor(out_beat).cuda(), torch.tensor(out_beat_timing).cuda(), torch.tensor(out_mask).cuda() #batch, len_beat embedded_beat = self.beat_embedding_layer(out_beat, out_beat_timing) embedded_beat = embedded_beat.repeat_interleave(num_samples_per_prompt, 0) out_mask = out_mask.repeat_interleave(num_samples_per_prompt, 0)
uncond_beats = [[[],[]]] * len(beats)
max_length = embedded_beat.shape[1] with torch.no_grad(): out_beat_unc = [] out_beat_timing_unc = [] out_mask_unc = [] for beat in uncond_beats: tokenized_beats, tokenized_beats_timing, tokenized_beat_mask = self.beat_tokenizer(beat) out_beat_unc.append(tokenized_beats) out_beat_timing_unc.append(tokenized_beats_timing) out_mask_unc.append(tokenized_beat_mask) out_beat_unc, out_beat_timing_unc, out_mask_unc = torch.tensor(out_beat_unc).cuda(), torch.tensor(out_beat_timing_unc).cuda(), torch.tensor(out_mask_unc).cuda() #batch, len_beat embedded_beat_unc = self.beat_embedding_layer(out_beat_unc, out_beat_timing_unc)
embedded_beat_unc = embedded_beat_unc.repeat_interleave(num_samples_per_prompt, 0) out_mask_unc = out_mask_unc.repeat_interleave(num_samples_per_prompt, 0)
embedded_beat = torch.cat([embedded_beat_unc, embedded_beat]) out_mask = torch.cat([out_mask_unc, out_mask])
return embedded_beat, out_mask
def encode_chords_classifier_free(self, chords, chords_time, num_samples_per_prompt):
with torch.no_grad(): out_chord_root = [] out_chord_type = [] out_chord_inv = [] out_chord_timing = [] out_mask = [] for chord, chord_time in zip(chords,chords_time): #batch loop tokenized_chord_root, tokenized_chord_type, tokenized_chord_inv, tokenized_chord_time, tokenized_chord_mask = self.chord_tokenizer(chord, chord_time) out_chord_root.append(tokenized_chord_root) out_chord_type.append(tokenized_chord_type) out_chord_inv.append(tokenized_chord_inv) out_chord_timing.append(tokenized_chord_time) out_mask.append(tokenized_chord_mask) out_chord_root, out_chord_type, out_chord_inv, out_chord_timing, out_mask = torch.tensor(out_chord_root).cuda(), torch.tensor(out_chord_type).cuda(), torch.tensor(out_chord_inv).cuda(), torch.tensor(out_chord_timing).cuda(), torch.tensor(out_mask).cuda() embedded_chord = self.chord_embedding_layer(out_chord_root, out_chord_type, out_chord_inv, out_chord_timing) embedded_chord = embedded_chord.repeat_interleave(num_samples_per_prompt, 0) out_mask = out_mask.repeat_interleave(num_samples_per_prompt, 0)
chords_unc=[[]] * len(chords) chords_time_unc=[[]] * len(chords_time)
max_length = embedded_chord.shape[1]
with torch.no_grad(): out_chord_root_unc = [] out_chord_type_unc = [] out_chord_inv_unc = [] out_chord_timing_unc = [] out_mask_unc = [] for chord, chord_time in zip(chords_unc,chords_time_unc): #batch loop tokenized_chord_root, tokenized_chord_type, tokenized_chord_inv, tokenized_chord_time, tokenized_chord_mask = self.chord_tokenizer(chord, chord_time) out_chord_root_unc.append(tokenized_chord_root) out_chord_type_unc.append(tokenized_chord_type) out_chord_inv_unc.append(tokenized_chord_inv) out_chord_timing_unc.append(tokenized_chord_time) out_mask_unc.append(tokenized_chord_mask) out_chord_root_unc, out_chord_type_unc, out_chord_inv_unc, out_chord_timing_unc, out_mask_unc = torch.tensor(out_chord_root_unc).cuda(), torch.tensor(out_chord_type_unc).cuda(), torch.tensor(out_chord_inv_unc).cuda(), torch.tensor(out_chord_timing_unc).cuda(), torch.tensor(out_mask_unc).cuda() embedded_chord_unc = self.chord_embedding_layer(out_chord_root_unc, out_chord_type_unc, out_chord_inv_unc, out_chord_timing_unc)
embedded_chord_unc = embedded_chord_unc.repeat_interleave(num_samples_per_prompt, 0) out_mask_unc = out_mask_unc.repeat_interleave(num_samples_per_prompt, 0)
embedded_chord = torch.cat([embedded_chord_unc, embedded_chord]) out_mask = torch.cat([out_mask_unc, out_mask])
return embedded_chord, out_mask123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260import gradio as grimport jsonimport torchimport waviofrom tqdm import tqdmfrom huggingface_hub import snapshot_download
from audioldm.audio.stft import TacotronSTFTfrom audioldm.variational_autoencoder import AutoencoderKL
from transformers import AutoTokenizer, T5ForConditionalGenerationfrom modelling_deberta_v2 import DebertaV2ForTokenClassificationRegression
from diffusers import DDPMSchedulerfrom models import MusicAudioDiffusion
from gradio import Markdown
class MusicFeaturePredictor: def __init__(self, path, device="cuda:0", cache_dir=None, local_files_only=False): self.beats_tokenizer = AutoTokenizer.from_pretrained( "microsoft/deberta-v3-large", cache_dir=cache_dir, local_files_only=local_files_only, ) self.beats_model = DebertaV2ForTokenClassificationRegression.from_pretrained( "microsoft/deberta-v3-large", cache_dir=cache_dir, local_files_only=local_files_only, ) self.beats_model.eval() self.beats_model.to(device)
beats_ckpt = f"{path}/beats/microsoft-deberta-v3-large.pt" beats_weight = torch.load(beats_ckpt, map_location="cpu") self.beats_model.load_state_dict(beats_weight)
self.chords_tokenizer = AutoTokenizer.from_pretrained( "google/flan-t5-large", cache_dir=cache_dir, local_files_only=local_files_only, ) self.chords_model = T5ForConditionalGeneration.from_pretrained( "google/flan-t5-large", cache_dir=cache_dir, local_files_only=local_files_only, ) self.chords_model.eval() self.chords_model.to(device)
chords_ckpt = f"{path}/chords/flan-t5-large.bin" chords_weight = torch.load(chords_ckpt, map_location="cpu") self.chords_model.load_state_dict(chords_weight)
def generate_beats(self, prompt): tokenized = self.beats_tokenizer( prompt, max_length=512, padding=True, truncation=True, return_tensors="pt" ) tokenized = {k: v.to(self.beats_model.device) for k, v in tokenized.items()}
with torch.no_grad(): out = self.beats_model(**tokenized)
max_beat = ( 1 + torch.argmax(out["logits"][:, 0, :], -1).detach().cpu().numpy() ).tolist()[0] intervals = ( out["values"][:, :, 0] .detach() .cpu() .numpy() .astype("float32") .round(4) .tolist() )
intervals = np.cumsum(intervals) predicted_beats_times = [] for t in intervals: if t < 10: predicted_beats_times.append(round(t, 2)) else: break predicted_beats_times = list(np.array(predicted_beats_times)[:50])
if len(predicted_beats_times) == 0: predicted_beats = [[], []] else: beat_counts = [] for i in range(len(predicted_beats_times)): beat_counts.append(float(1.0 + np.mod(i, max_beat))) predicted_beats = [[predicted_beats_times, beat_counts]]
return max_beat, predicted_beats_times, predicted_beats
def generate(self, prompt): max_beat, predicted_beats_times, predicted_beats = self.generate_beats(prompt)
chords_prompt = "Caption: {} \\n Timestamps: {} \\n Max Beat: {}".format( prompt, " , ".join([str(round(t, 2)) for t in predicted_beats_times]), max_beat, )
tokenized = self.chords_tokenizer( chords_prompt, max_length=512, padding=True, truncation=True, return_tensors="pt", ) tokenized = {k: v.to(self.chords_model.device) for k, v in tokenized.items()}
generated_chords = self.chords_model.generate( input_ids=tokenized["input_ids"], attention_mask=tokenized["attention_mask"], min_length=8, max_length=128, num_beams=5, early_stopping=True, num_return_sequences=1, )
generated_chords = self.chords_tokenizer.decode( generated_chords[0], skip_special_tokens=True, clean_up_tokenization_spaces=True, ).split(" n ")
predicted_chords, predicted_chords_times = [], [] for item in generated_chords: c, ct = item.split(" at ") predicted_chords.append(c) predicted_chords_times.append(float(ct))
return predicted_beats, predicted_chords, predicted_chords_times
class Mustango: def __init__( self, name="declare-lab/mustango", device="cuda:0", cache_dir=None, local_files_only=False, ): path = snapshot_download(repo_id=name, cache_dir=cache_dir)
self.music_model = MusicFeaturePredictor( path, device, cache_dir=cache_dir, local_files_only=local_files_only )
vae_config = json.load(open(f"{path}/configs/vae_config.json")) stft_config = json.load(open(f"{path}/configs/stft_config.json")) main_config = json.load(open(f"{path}/configs/main_config.json"))
self.vae = AutoencoderKL(**vae_config).to(device) self.stft = TacotronSTFT(**stft_config).to(device) self.model = MusicAudioDiffusion( main_config["text_encoder_name"], main_config["scheduler_name"], unet_model_config_path=f"{path}/configs/music_diffusion_model_config.json", ).to(device)
vae_weights = torch.load( f"{path}/vae/pytorch_model_vae.bin", map_location=device ) stft_weights = torch.load( f"{path}/stft/pytorch_model_stft.bin", map_location=device ) main_weights = torch.load( f"{path}/ldm/pytorch_model_ldm.bin", map_location=device )
self.vae.load_state_dict(vae_weights) self.stft.load_state_dict(stft_weights) self.model.load_state_dict(main_weights)
print("Successfully loaded checkpoint from:", name)
self.vae.eval() self.stft.eval() self.model.eval()
self.scheduler = DDPMScheduler.from_pretrained( main_config["scheduler_name"], subfolder="scheduler" )
def generate(self, prompt, steps=100, guidance=3, samples=1, disable_progress=True): """Genrate music for a single prompt string."""
with torch.no_grad(): beats, chords, chords_times = self.music_model.generate(prompt) latents = self.model.inference( [prompt], beats, [chords], [chords_times], self.scheduler, steps, guidance, samples, disable_progress, ) mel = self.vae.decode_first_stage(latents) wave = self.vae.decode_to_waveform(mel)
return wave[0]
# Initialize Mustangoif torch.cuda.is_available(): mustango = Mustango()else: mustango = Mustango(device="cpu")
def gradio_generate(prompt, steps, guidance): output_wave = mustango.generate(prompt, steps, guidance) # output_filename = f"{prompt.replace(' ', '_')}_{steps}_{guidance}"[:250] + ".wav" output_filename = "temp.wav" wavio.write(output_filename, output_wave, rate=16000, sampwidth=2) return output_filename
# description_text = """# <p><a href="https://huggingface.co/spaces/declare-lab/mustango/blob/main/app.py?duplicate=true"> <img style="margin-top: 0em; margin-bottom: 0em" src="https://bit.ly/3gLdBN6" alt="Duplicate Space"></a> For faster inference without waiting in queue, you may duplicate the space and upgrade to a GPU in the settings. <br/><br/># Generate music using Mustango by providing a text prompt.# <br/><br/> Meet Mustango, an exciting addition to the vibrant landscape of Multimodal Large Language Models \# designed for controlled music generation. Mustango leverages Latent Diffusion Model (LDM), Flan-T5, and \# musical features to do the magic! \# <p/># """description_text = ""# Gradio input and output componentsinput_text = gr.inputs.Textbox(lines=2, label="Prompt")output_audio = gr.outputs.Audio(label="Generated Music", type="filepath")denoising_steps = gr.Slider(minimum=100, maximum=200, value=100, step=1, label="Steps", interactive=True)guidance_scale = gr.Slider(minimum=1, maximum=10, value=3, step=0.1, label="Guidance Scale", interactive=True)
# Gradio interfacegr_interface = gr.Interface( fn=gradio_generate, inputs=[input_text, denoising_steps, guidance_scale], outputs=[output_audio], title="Mustango: Toward Controllable Text-to-Music Generation", description=description_text, allow_flagging=False, examples=[ ["This techno song features a synth lead playing the main melody. This is accompanied by programmed percussion playing a simple kick focused beat. The hi-hat is accented in an open position on the 3-and count of every bar. The synth plays the bass part with a voicing that sounds like a cello. This techno song can be played in a club. The chord sequence is Gm, A7, Eb, Bb, C, F, Gm. The beat counts to 2. The tempo of this song is 128.0 beats per minute. The key of this song is G minor."], ["This is a new age piece. There is a flute playing the main melody with a lot of staccato notes. The rhythmic background consists of a medium tempo electronic drum beat with percussive elements all over the spectrum. There is a playful atmosphere to the piece. This piece can be used in the soundtrack of a children's TV show or an advertisement jingle."], ["The song is an instrumental. The song is in medium tempo with a classical guitar playing a lilting melody in accompaniment style. The song is emotional and romantic. The song is a romantic instrumental song. The chord sequence is Gm, F6, Ebm. The time signature is 4/4. This song is in Adagio. The key of this song is G minor."], ["This folk song features a female voice singing the main melody. This is accompanied by a tabla playing the percussion. A guitar strums chords. For most parts of the song, only one chord is played. At the last bar, a different chord is played. This song has minimal instruments. This song has a story-telling mood. This song can be played in a village scene in an Indian movie. The chord sequence is Bbm, Ab. The beat is 3. The tempo of this song is Allegro. The key of this song is Bb minor."], ["This is a live performance of a classical music piece. There is an orchestra performing the piece with a violin lead playing the main melody. The atmosphere is sentimental and heart-touching. This piece could be playing in the background at a classy restaurant. The chord progression in this song is Am7, Gm, Dm, A7, Dm. The beat is 3. This song is in Largo. The key of this song is D minor."], ["This is a techno piece with drums and beats and a leading melody. A synth plays chords. The music kicks off with a powerful and relentless drumbeat. Over the pounding beats, a leading melody emerges. In the middle of the song, a flock of seagulls flies over the venue and make loud bird sounds. It has strong danceability and can be played in a club. The tempo is 120 bpm. The chords played by the synth are Am, Cm, Dm, Gm."], ], cache_examples=False,)
# Launch Gradio appgr_interface.launch()12345678from .ldm import LatentDiffusionfrom .utils import seed_everything, save_wave, get_time, get_durationfrom .pipeline import *
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183#!/usr/bin/python3import osfrom audioldm import text_to_audio, style_transfer, build_model, save_wave, get_time, round_up_duration, get_durationimport argparse
CACHE_DIR = os.getenv( "AUDIOLDM_CACHE_DIR", os.path.join(os.path.expanduser("~"), ".cache/audioldm"))
parser = argparse.ArgumentParser()
parser.add_argument( "--mode", type=str, required=False, default="generation", help="generation: text-to-audio generation; transfer: style transfer", choices=["generation", "transfer"])
parser.add_argument( "-t", "--text", type=str, required=False, default="", help="Text prompt to the model for audio generation",)
parser.add_argument( "-f", "--file_path", type=str, required=False, default=None, help="(--mode transfer): Original audio file for style transfer; Or (--mode generation): the guidance audio file for generating simialr audio",)
parser.add_argument( "--transfer_strength", type=float, required=False, default=0.5, help="A value between 0 and 1. 0 means original audio without transfer, 1 means completely transfer to the audio indicated by text",)
parser.add_argument( "-s", "--save_path", type=str, required=False, help="The path to save model output", default="./output",)
parser.add_argument( "--model_name", type=str, required=False, help="The checkpoint you gonna use", default="audioldm-s-full", choices=["audioldm-s-full", "audioldm-l-full", "audioldm-s-full-v2"])
parser.add_argument( "-ckpt", "--ckpt_path", type=str, required=False, help="The path to the pretrained .ckpt model", default=None,)
parser.add_argument( "-b", "--batchsize", type=int, required=False, default=1, help="Generate how many samples at the same time",)
parser.add_argument( "--ddim_steps", type=int, required=False, default=200, help="The sampling step for DDIM",)
parser.add_argument( "-gs", "--guidance_scale", type=float, required=False, default=2.5, help="Guidance scale (Large => better quality and relavancy to text; Small => better diversity)",)
parser.add_argument( "-dur", "--duration", type=float, required=False, default=10.0, help="The duration of the samples",)
parser.add_argument( "-n", "--n_candidate_gen_per_text", type=int, required=False, default=3, help="Automatic quality control. This number control the number of candidates (e.g., generate three audios and choose the best to show you). A Larger value usually lead to better quality with heavier computation",)
parser.add_argument( "--seed", type=int, required=False, default=42, help="Change this value (any integer number) will lead to a different generation result.",)
args = parser.parse_args()
if(args.ckpt_path is not None): print("Warning: ckpt_path has no effect after version 0.0.20.") assert args.duration % 2.5 == 0, "Duration must be a multiple of 2.5"
mode = args.modeif(mode == "generation" and args.file_path is not None): mode = "generation_audio_to_audio" if(len(args.text) > 0): print("Warning: You have specified the --file_path. --text will be ignored") args.text = "" save_path = os.path.join(args.save_path, mode)
if(args.file_path is not None): save_path = os.path.join(save_path, os.path.basename(args.file_path.split(".")[0]))
text = args.textrandom_seed = args.seedduration = args.durationguidance_scale = args.guidance_scalen_candidate_gen_per_text = args.n_candidate_gen_per_text
os.makedirs(save_path, exist_ok=True)audioldm = build_model(model_name=args.model_name)
if(args.mode == "generation"): waveform = text_to_audio( audioldm, text, args.file_path, random_seed, duration=duration, guidance_scale=guidance_scale, ddim_steps=args.ddim_steps, n_candidate_gen_per_text=n_candidate_gen_per_text, batchsize=args.batchsize, ) elif(args.mode == "transfer"): assert args.file_path is not None assert os.path.exists(args.file_path), "The original audio file \'%s\' for style transfer does not exist." % args.file_path waveform = style_transfer( audioldm, text, args.file_path, args.transfer_strength, random_seed, duration=duration, guidance_scale=guidance_scale, ddim_steps=args.ddim_steps, batchsize=args.batchsize, ) waveform = waveform[:,None,:]
save_wave(waveform, save_path, name="%s_%s" % (get_time(), text))12from .tools import wav_to_fbank, read_wav_filefrom .stft import TacotronSTFT123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100import torchimport numpy as npimport librosa.util as librosa_utilfrom scipy.signal import get_window
def window_sumsquare( window, n_frames, hop_length, win_length, n_fft, dtype=np.float32, norm=None,): """ # from librosa 0.6 Compute the sum-square envelope of a window function at a given hop length.
This is used to estimate modulation effects induced by windowing observations in short-time fourier transforms.
Parameters ---------- window : string, tuple, number, callable, or list-like Window specification, as in `get_window`
n_frames : int > 0 The number of analysis frames
hop_length : int > 0 The number of samples to advance between frames
win_length : [optional] The length of the window function. By default, this matches `n_fft`.
n_fft : int > 0 The length of each analysis frame.
dtype : np.dtype The data type of the output
Returns ------- wss : np.ndarray, shape=`(n_fft + hop_length * (n_frames - 1))` The sum-squared envelope of the window function """ if win_length is None: win_length = n_fft
n = n_fft + hop_length * (n_frames - 1) x = np.zeros(n, dtype=dtype)
# Compute the squared window at the desired length win_sq = get_window(window, win_length, fftbins=True) win_sq = librosa_util.normalize(win_sq, norm=norm) ** 2 win_sq = librosa_util.pad_center(win_sq, n_fft)
# Fill the envelope for i in range(n_frames): sample = i * hop_length x[sample : min(n, sample + n_fft)] += win_sq[: max(0, min(n_fft, n - sample))] return x
def griffin_lim(magnitudes, stft_fn, n_iters=30): """ PARAMS ------ magnitudes: spectrogram magnitudes stft_fn: STFT class with transform (STFT) and inverse (ISTFT) methods """
angles = np.angle(np.exp(2j * np.pi * np.random.rand(*magnitudes.size()))) angles = angles.astype(np.float32) angles = torch.autograd.Variable(torch.from_numpy(angles)) signal = stft_fn.inverse(magnitudes, angles).squeeze(1)
for i in range(n_iters): _, angles = stft_fn.transform(signal) signal = stft_fn.inverse(magnitudes, angles).squeeze(1) return signal
def dynamic_range_compression(x, normalize_fun=torch.log, C=1, clip_val=1e-5): """ PARAMS ------ C: compression factor """ return normalize_fun(torch.clamp(x, min=clip_val) * C)
def dynamic_range_decompression(x, C=1): """ PARAMS ------ C: compression factor used to compress """ return torch.exp(x) / C123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186import torchimport torch.nn.functional as Fimport numpy as npfrom scipy.signal import get_windowfrom librosa.util import pad_center, tinyfrom librosa.filters import mel as librosa_mel_fn
from audioldm.audio.audio_processing import ( dynamic_range_compression, dynamic_range_decompression, window_sumsquare,)
class STFT(torch.nn.Module): """adapted from Prem Seetharaman's https://github.com/pseeth/pytorch-stft"""
def __init__(self, filter_length, hop_length, win_length, window="hann"): super(STFT, self).__init__() self.filter_length = filter_length self.hop_length = hop_length self.win_length = win_length self.window = window self.forward_transform = None scale = self.filter_length / self.hop_length fourier_basis = np.fft.fft(np.eye(self.filter_length))
cutoff = int((self.filter_length / 2 + 1)) fourier_basis = np.vstack( [np.real(fourier_basis[:cutoff, :]), np.imag(fourier_basis[:cutoff, :])] )
forward_basis = torch.FloatTensor(fourier_basis[:, None, :]) inverse_basis = torch.FloatTensor( np.linalg.pinv(scale * fourier_basis).T[:, None, :] )
if window is not None: assert filter_length >= win_length # get window and zero center pad it to filter_length fft_window = get_window(window, win_length, fftbins=True) fft_window = pad_center(fft_window, filter_length) fft_window = torch.from_numpy(fft_window).float()
# window the bases forward_basis *= fft_window inverse_basis *= fft_window
self.register_buffer("forward_basis", forward_basis.float()) self.register_buffer("inverse_basis", inverse_basis.float())
def transform(self, input_data): device = self.forward_basis.device input_data = input_data.to(device) num_batches = input_data.size(0) num_samples = input_data.size(1)
self.num_samples = num_samples
# similar to librosa, reflect-pad the input input_data = input_data.view(num_batches, 1, num_samples) input_data = F.pad( input_data.unsqueeze(1), (int(self.filter_length / 2), int(self.filter_length / 2), 0, 0), mode="reflect", ) input_data = input_data.squeeze(1)
forward_transform = F.conv1d( input_data, torch.autograd.Variable(self.forward_basis, requires_grad=False), stride=self.hop_length, padding=0, )#.cpu()
cutoff = int((self.filter_length / 2) + 1) real_part = forward_transform[:, :cutoff, :] imag_part = forward_transform[:, cutoff:, :]
magnitude = torch.sqrt(real_part**2 + imag_part**2) phase = torch.autograd.Variable(torch.atan2(imag_part.data, real_part.data))
return magnitude, phase
def inverse(self, magnitude, phase): device = self.forward_basis.device magnitude, phase = magnitude.to(device), phase.to(device) recombine_magnitude_phase = torch.cat( [magnitude * torch.cos(phase), magnitude * torch.sin(phase)], dim=1 )
inverse_transform = F.conv_transpose1d( recombine_magnitude_phase, torch.autograd.Variable(self.inverse_basis, requires_grad=False), stride=self.hop_length, padding=0, )
if self.window is not None: window_sum = window_sumsquare( self.window, magnitude.size(-1), hop_length=self.hop_length, win_length=self.win_length, n_fft=self.filter_length, dtype=np.float32, ) # remove modulation effects approx_nonzero_indices = torch.from_numpy( np.where(window_sum > tiny(window_sum))[0] ) window_sum = torch.autograd.Variable( torch.from_numpy(window_sum), requires_grad=False ) window_sum = window_sum inverse_transform[:, :, approx_nonzero_indices] /= window_sum[ approx_nonzero_indices ]
# scale by hop ratio inverse_transform *= float(self.filter_length) / self.hop_length
inverse_transform = inverse_transform[:, :, int(self.filter_length / 2) :] inverse_transform = inverse_transform[:, :, : -int(self.filter_length / 2) :]
return inverse_transform
def forward(self, input_data): self.magnitude, self.phase = self.transform(input_data) reconstruction = self.inverse(self.magnitude, self.phase) return reconstruction
class TacotronSTFT(torch.nn.Module): def __init__( self, filter_length, hop_length, win_length, n_mel_channels, sampling_rate, mel_fmin, mel_fmax, ): super(TacotronSTFT, self).__init__() self.n_mel_channels = n_mel_channels self.sampling_rate = sampling_rate self.stft_fn = STFT(filter_length, hop_length, win_length) mel_basis = librosa_mel_fn( sampling_rate, filter_length, n_mel_channels, mel_fmin, mel_fmax ) mel_basis = torch.from_numpy(mel_basis).float() self.register_buffer("mel_basis", mel_basis)
def spectral_normalize(self, magnitudes, normalize_fun): output = dynamic_range_compression(magnitudes, normalize_fun) return output
def spectral_de_normalize(self, magnitudes): output = dynamic_range_decompression(magnitudes) return output
def mel_spectrogram(self, y, normalize_fun=torch.log): """Computes mel-spectrograms from a batch of waves PARAMS ------ y: Variable(torch.FloatTensor) with shape (B, T) in range [-1, 1]
RETURNS ------- mel_output: torch.FloatTensor of shape (B, n_mel_channels, T) """ assert torch.min(y.data) >= -1, torch.min(y.data) assert torch.max(y.data) <= 1, torch.max(y.data)
magnitudes, phases = self.stft_fn.transform(y) magnitudes = magnitudes.data mel_output = torch.matmul(self.mel_basis, magnitudes) mel_output = self.spectral_normalize(mel_output, normalize_fun) energy = torch.norm(magnitudes, dim=1)
log_magnitudes = self.spectral_normalize(magnitudes, normalize_fun)
return mel_output, log_magnitudes, energy12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485import torchimport numpy as npimport torchaudio
def get_mel_from_wav(audio, _stft): audio = torch.clip(torch.FloatTensor(audio).unsqueeze(0), -1, 1) audio = torch.autograd.Variable(audio, requires_grad=False) melspec, log_magnitudes_stft, energy = _stft.mel_spectrogram(audio) melspec = torch.squeeze(melspec, 0).numpy().astype(np.float32) log_magnitudes_stft = ( torch.squeeze(log_magnitudes_stft, 0).numpy().astype(np.float32) ) energy = torch.squeeze(energy, 0).numpy().astype(np.float32) return melspec, log_magnitudes_stft, energy
def _pad_spec(fbank, target_length=1024): n_frames = fbank.shape[0] p = target_length - n_frames # cut and pad if p > 0: m = torch.nn.ZeroPad2d((0, 0, 0, p)) fbank = m(fbank) elif p < 0: fbank = fbank[0:target_length, :]
if fbank.size(-1) % 2 != 0: fbank = fbank[..., :-1]
return fbank
def pad_wav(waveform, segment_length): waveform_length = waveform.shape[-1] assert waveform_length > 100, "Waveform is too short, %s" % waveform_length if segment_length is None or waveform_length == segment_length: return waveform elif waveform_length > segment_length: return waveform[:segment_length] elif waveform_length < segment_length: temp_wav = np.zeros((1, segment_length)) temp_wav[:, :waveform_length] = waveform return temp_wav
def normalize_wav(waveform): waveform = waveform - np.mean(waveform) waveform = waveform / (np.max(np.abs(waveform)) + 1e-8) return waveform * 0.5
def read_wav_file(filename, segment_length): # waveform, sr = librosa.load(filename, sr=None, mono=True) # 4 times slower waveform, sr = torchaudio.load(filename) # Faster!!! waveform = torchaudio.functional.resample(waveform, orig_freq=sr, new_freq=16000) waveform = waveform.numpy()[0, ...] waveform = normalize_wav(waveform) waveform = waveform[None, ...] waveform = pad_wav(waveform, segment_length) waveform = waveform / np.max(np.abs(waveform)) waveform = 0.5 * waveform return waveform
def wav_to_fbank(filename, target_length=1024, fn_STFT=None): assert fn_STFT is not None
# mixup waveform = read_wav_file(filename, target_length * 160) # hop size is 160
waveform = waveform[0, ...] waveform = torch.FloatTensor(waveform)
fbank, log_magnitudes_stft, energy = get_mel_from_wav(waveform, fn_STFT)
fbank = torch.FloatTensor(fbank.T) log_magnitudes_stft = torch.FloatTensor(log_magnitudes_stft.T)
fbank, log_magnitudes_stft = _pad_spec(fbank, target_length), _pad_spec( log_magnitudes_stft, target_length )
return fbank, log_magnitudes_stft, waveform123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170import torchimport torch.nn as nnfrom audioldm.clap.open_clip import create_modelfrom audioldm.clap.training.data import get_audio_featuresimport torchaudiofrom transformers import RobertaTokenizerimport torch.nn.functional as F
class CLAPAudioEmbeddingClassifierFreev2(nn.Module): def __init__( self, pretrained_path="", key="class", sampling_rate=16000, embed_mode="audio", amodel = "HTSAT-tiny", unconditional_prob=0.1, random_mute=False, max_random_mute_portion=0.5, training_mode=True, ): super().__init__()
self.key = key self.device = "cpu" self.precision = "fp32" self.amodel = amodel # or 'PANN-14' self.tmodel = "roberta" # the best text encoder in our training self.enable_fusion = False # False if you do not want to use the fusion model self.fusion_type = "aff_2d" self.pretrained = pretrained_path self.embed_mode = embed_mode self.embed_mode_orig = embed_mode self.sampling_rate = sampling_rate self.unconditional_prob = unconditional_prob self.random_mute = random_mute self.tokenize = RobertaTokenizer.from_pretrained("roberta-base") self.max_random_mute_portion = max_random_mute_portion self.training_mode = training_mode self.model, self.model_cfg = create_model( self.amodel, self.tmodel, self.pretrained, precision=self.precision, device=self.device, enable_fusion=self.enable_fusion, fusion_type=self.fusion_type, ) for p in self.model.parameters(): p.requires_grad = False
self.model.eval()
def get_unconditional_condition(self, batchsize): self.unconditional_token = self.model.get_text_embedding( self.tokenizer(["", ""]) )[0:1] return torch.cat([self.unconditional_token.unsqueeze(0)] * batchsize, dim=0)
def batch_to_list(self, batch): ret = [] for i in range(batch.size(0)): ret.append(batch[i]) return ret
def make_decision(self, probability): if float(torch.rand(1)) < probability: return True else: return False
def random_uniform(self, start, end): val = torch.rand(1).item() return start + (end - start) * val
def _random_mute(self, waveform): # waveform: [bs, t-steps] t_steps = waveform.size(-1) for i in range(waveform.size(0)): mute_size = int( self.random_uniform(0, end=int(t_steps * self.max_random_mute_portion)) ) mute_start = int(self.random_uniform(0, t_steps - mute_size)) waveform[i, mute_start : mute_start + mute_size] = 0 return waveform
def cos_similarity(self, waveform, text): # waveform: [bs, t_steps] with torch.no_grad(): self.embed_mode = "audio" audio_emb = self(waveform.cuda()) self.embed_mode = "text" text_emb = self(text) similarity = F.cosine_similarity(audio_emb, text_emb, dim=2), audio_emb, text_emb return similarity.squeeze()
def forward(self, batch, key=None): # If you want this conditioner to be unconditional, set self.unconditional_prob = 1.0 # If you want this conditioner to be fully conditional, set self.unconditional_prob = 0.0 if self.model.training == True and not self.training_mode: print( "The pretrained CLAP model should always be in eval mode. Reloading model just in case you change the parameters." ) self.model, self.model_cfg = create_model( self.amodel, self.tmodel, self.pretrained, precision=self.precision, device="cuda", enable_fusion=self.enable_fusion, fusion_type=self.fusion_type, ) for p in self.model.parameters(): p.requires_grad = False self.model.eval()
# the 'fusion' truncate mode can be changed to 'rand_trunc' if run in unfusion mode if self.embed_mode == "audio": with torch.no_grad(): audio_dict_list = [] assert ( self.sampling_rate == 16000 ), "We only support 16000 sampling rate" if self.random_mute: batch = self._random_mute(batch) # batch: [bs, 1, t-samples] batch = torchaudio.functional.resample( batch, orig_freq=self.sampling_rate, new_freq=48000 ) for waveform in self.batch_to_list(batch): audio_dict = {} audio_dict = get_audio_features( audio_dict, waveform, 480000, data_truncating="fusion", data_filling="repeatpad", audio_cfg=self.model_cfg["audio_cfg"], ) audio_dict_list.append(audio_dict) # [bs, 512] embed = self.model.get_audio_embedding(audio_dict_list) elif self.embed_mode == "text": with torch.no_grad(): # the 'fusion' truncate mode can be changed to 'rand_trunc' if run in unfusion mode text_data = self.tokenizer(batch) embed = self.model.get_text_embedding(text_data)
embed = embed.unsqueeze(1) self.unconditional_token = self.model.get_text_embedding( self.tokenizer(["", ""]) )[0:1]
for i in range(embed.size(0)): if self.make_decision(self.unconditional_prob): embed[i] = self.unconditional_token
# [bs, 1, 512] return embed.detach()
def tokenizer(self, text): result = self.tokenize( text, padding="max_length", truncation=True, max_length=512, return_tensors="pt", ) return {k: v.squeeze(0) for k, v in result.items()}12345678910111213141516171819202122232425from .factory import ( list_models, create_model, create_model_and_transforms, add_model_config,)from .loss import ClipLoss, gather_features, LPLoss, lp_gather_features, LPMetricsfrom .model import ( CLAP, CLAPTextCfg, CLAPVisionCfg, CLAPAudioCfp, convert_weights_to_fp16, trace_model,)from .openai import load_openai_model, list_openai_modelsfrom .pretrained import ( list_pretrained, list_pretrained_tag_models, list_pretrained_model_tags, get_pretrained_url, download_pretrained,)from .tokenizer import SimpleTokenizer, tokenizefrom .transform import image_transform.ipynb_checkpoints/README-checkpoint.mdAdded+13
.ipynb_checkpoints/app-checkpoint.pyAdded+260
.ipynb_checkpoints/modelling_deberta_v2-checkpoint.pyAdded+1750
.ipynb_checkpoints/models-checkpoint.pyAdded+738
app.pyAdded+260
audioldm/__init__.pyAdded+8
audioldm/__main__.pyAdded+183
audioldm/__pycache__/__init__.cpython-311.pycAdded
audioldm/__pycache__/__init__.cpython-37.pycAdded
audioldm/__pycache__/__init__.cpython-39.pycAdded
audioldm/__pycache__/ldm.cpython-311.pycAdded
audioldm/__pycache__/ldm.cpython-37.pycAdded
audioldm/__pycache__/ldm.cpython-39.pycAdded
audioldm/__pycache__/pipeline.cpython-311.pycAdded
audioldm/__pycache__/pipeline.cpython-37.pycAdded
audioldm/__pycache__/pipeline.cpython-39.pycAdded
audioldm/__pycache__/utils.cpython-311.pycAdded
audioldm/__pycache__/utils.cpython-37.pycAdded
audioldm/__pycache__/utils.cpython-39.pycAdded
audioldm/audio/__init__.pyAdded+2
audioldm/audio/__pycache__/__init__.cpython-311.pycAdded
audioldm/audio/__pycache__/__init__.cpython-37.pycAdded
audioldm/audio/__pycache__/__init__.cpython-39.pycAdded
audioldm/audio/__pycache__/audio_processing.cpython-311.pycAdded
audioldm/audio/__pycache__/audio_processing.cpython-37.pycAdded
audioldm/audio/__pycache__/audio_processing.cpython-39.pycAdded
audioldm/audio/__pycache__/mix.cpython-39.pycAdded
audioldm/audio/__pycache__/stft.cpython-311.pycAdded
audioldm/audio/__pycache__/stft.cpython-37.pycAdded
audioldm/audio/__pycache__/stft.cpython-39.pycAdded
audioldm/audio/__pycache__/tools.cpython-311.pycAdded
audioldm/audio/__pycache__/tools.cpython-37.pycAdded
audioldm/audio/__pycache__/tools.cpython-39.pycAdded
audioldm/audio/__pycache__/torch_tools.cpython-39.pycAdded
audioldm/audio/audio_processing.pyAdded+100
audioldm/audio/stft.pyAdded+186
audioldm/audio/tools.pyAdded+85
audioldm/clap/__init__.pyAdded
audioldm/clap/__pycache__/__init__.cpython-39.pycAdded
audioldm/clap/__pycache__/encoders.cpython-39.pycAdded
audioldm/clap/encoders.pyAdded+170
audioldm/clap/open_clip/__init__.pyAdded+25
audioldm/clap/open_clip/__pycache__/__init__.cpython-39.pycAdded
audioldm/clap/open_clip/__pycache__/factory.cpython-39.pycAdded
audioldm/clap/open_clip/__pycache__/feature_fusion.cpython-39.pycAdded
audioldm/clap/open_clip/__pycache__/htsat.cpython-39.pycAdded
audioldm/clap/open_clip/__pycache__/loss.cpython-39.pycAdded
audioldm/clap/open_clip/__pycache__/model.cpython-39.pycAdded
audioldm/clap/open_clip/__pycache__/openai.cpython-39.pycAdded
audioldm/clap/open_clip/__pycache__/pann_model.cpython-39.pycAdded