Spaces:
Runtime error
Runtime error
fix audiotools version + sampling trick (#7)
Browse files- sampling tricks, fix audiotools pin (1062aecaf5ba2e866553c342f9a7ad78b6ec695a)
- remove share from demo (4fd6833b5f5c90fa51a330c389e2be09d8b057c5)
Files changed (5)
- .gitignore+2
- app.py+53-14
- requirements.txt+1-1
- scripts/exp/train.py+7-5
- vampnet/modules/transformer.py+109-37
174 unmodified lines1751761771781791802 unmodified lines183184185174 unmodified linessamples-*/**gradio-outputs/samples*/models-all/models.zip2 unmodified lines# *.pth.git-oldconf/generated/*174 unmodified lines1751761771781791801812 unmodified lines184185186187174 unmodified linessamples-*/**gradio-outputs/models/samples*/models-all/models.zip2 unmodified lines# *.pth.git-oldconf/generated/*runs*/
106 unmodified lines10710810911011111211311411511611711811912012112212312412512612712812913026 unmodified lines1571581591601611621634 unmodified lines1681691701711721739 unmodified lines1831841851861871881891901911921931941951 unmodified line197198199200201202203204172 unmodified lines37737837938038138238338438538638738838939039139235 unmodified lines42842943043143243321 unmodified lines4554564574584594604616 unmodified lines46846947047147247324 unmodified lines498499500501106 unmodified linesmask = pmask.codebook_unmask(mask, ncc)print(f"created mask with: linear random {data[rand_mask_intensity]}, inpaint {data[prefix_s]}:{data[suffix_s]}, periodic {data[periodic_p]}:{data[periodic_w]}, dropout {data[dropout]}, codebook unmask {ncc}, onset mask {data[onset_mask_width]}, num steps {data[num_steps]}, init temp {data[temp]}, use coarse2fine {data[use_coarse2fine]}")# save the mask as a txt filenp.savetxt(out_dir / "mask.txt", mask[:,0,:].long().cpu().numpy())zv, mask_z = interface.coarse_vamp(z,mask=mask,sampling_steps=data[num_steps],temperature=float(data[temp]*10),return_mask=True,typical_filtering=data[typical_filtering],typical_mass=data[typical_mass],typical_min_tokens=data[typical_min_tokens],gen_fn=interface.coarse.generate,)if use_coarse2fine:zv = interface.coarse_to_fine(zv, temperature=data[temp], mask=mask)sig = interface.to_signal(zv).cpu()print("done")26 unmodified linessig_out.write(out_dir / "output.wav")_data = {"temp": data[temp],"prefix_s": data[prefix_s],"suffix_s": data[suffix_s],"rand_mask_intensity": data[rand_mask_intensity],4 unmodified lines"n_conditioning_codebooks": data[n_conditioning_codebooks],"use_coarse2fine": data[use_coarse2fine],"stretch_factor": data[stretch_factor],}# save with yaml9 unmodified linesreturn f"saved! your save code is {out_dir.stem}", zip_pathwith gr.Blocks() as demo:with gr.Row():with gr.Column():gr.Markdown("# VampNet")gr.Markdown("""## Description:This is a demo of VampNet, a masked generative music model capable of doing music variations.You can control the extent and nature of variation with a set of manual controls and presets.Use this interface to experiment with different mask settings and explore the audio outputs.""")1 unmodified linegr.Markdown("""## Instructions:1. You can start by uploading some audio, or by loading the example audio.2. Choose a preset for the vamp operation, or manually adjust the controls to customize the mask settings. Click the load preset button.3. Click the "generate (vamp)!!!" button to generate audio. Listen to the output audio, and the masked audio to hear the mask hints.4. Optionally, you can add some notes and save the result.5. You can also use the output as the new input and continue experimenting!""")172 unmodified linesvalue=0.0)temp = gr.Slider(label="temperature",minimum=0.0,maximum=10.0,value=1.8)with gr.Accordion("sampling settings", open=False):typical_filtering = gr.Checkbox(label="typical filtering ",value=False35 unmodified lines)# mask settingswith gr.Column():vamp_button = gr.Button("generate (vamp)!!!")21 unmodified lines_inputs = {input_audio,num_steps,temp,prefix_s, suffix_s,rand_mask_intensity,periodic_p, periodic_w,6 unmodified linestypical_mass,typical_min_tokens,beat_mask_width,beat_mask_downbeats}24 unmodified linesoutputs=[thank_you, download_file])demo.queue().launch()106 unmodified lines10710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114226 unmodified lines1691701711721731741751761774 unmodified lines1821831841851861871889 unmodified lines1981992002012022032042052062072082092102111 unmodified line213214215216217218219220172 unmodified lines39339439539639739839940040140240340440540640740840941041141241341441541641741841942035 unmodified lines45645745845946046146246346446546646746846921 unmodified lines4914924934944954964974984996 unmodified lines50650750850951051151224 unmodified lines537538539540106 unmodified linesmask = pmask.codebook_unmask(mask, ncc)print(data)_top_p = data[top_p] if data[top_p] > 0 else None# save the mask as a txt filenp.savetxt(out_dir / "mask.txt", mask[:,0,:].long().cpu().numpy())_seed = data[seed] if data[seed] > 0 else Nonezv, mask_z = interface.coarse_vamp(z,mask=mask,sampling_steps=data[num_steps],mask_temperature=data[masktemp]*10,sampling_temperature=data[sampletemp],return_mask=True,typical_filtering=data[typical_filtering],typical_mass=data[typical_mass],typical_min_tokens=data[typical_min_tokens],top_p=_top_p,gen_fn=interface.coarse.generate,seed=_seed,)if use_coarse2fine:zv = interface.coarse_to_fine(zv,mask_temperature=data[masktemp]*10,sampling_temperature=data[sampletemp],mask=mask,sampling_steps=data[num_steps],seed=_seed,)sig = interface.to_signal(zv).cpu()print("done")26 unmodified linessig_out.write(out_dir / "output.wav")_data = {"masktemp": data[masktemp],"sampletemp": data[sampletemp],"top_p": data[top_p],"prefix_s": data[prefix_s],"suffix_s": data[suffix_s],"rand_mask_intensity": data[rand_mask_intensity],4 unmodified lines"n_conditioning_codebooks": data[n_conditioning_codebooks],"use_coarse2fine": data[use_coarse2fine],"stretch_factor": data[stretch_factor],"seed": data[seed],}# save with yaml9 unmodified linesreturn f"saved! your save code is {out_dir.stem}", zip_pathwith gr.Blocks() as demo:with gr.Row():with gr.Column():gr.Markdown("# VampNet Audio Vamping")gr.Markdown("""## Description:This is a demo of the VampNet, a generative audio model that transforms the input audio based on the chosen settings.You can control the extent and nature of variation with a set of manual controls and presets.Use this interface to experiment with different mask settings and explore the audio outputs.""")1 unmodified linegr.Markdown("""## Instructions:1. You can start by uploading some audio, or by loading the example audio.2. Choose a preset for the vamp operation, or manually adjust the controls to customize the mask settings.3. Click the "generate (vamp)!!!" button to apply the vamp operation. Listen to the output audio.4. Optionally, you can add some notes and save the result.5. You can also use the output as the new input and continue experimenting!""")172 unmodified linesvalue=0.0)masktemp = gr.Slider(label="mask temperature",minimum=0.0,maximum=10.0,value=1.5)sampletemp = gr.Slider(label="sample temperature",minimum=0.1,maximum=2.0,value=1.0)with gr.Accordion("sampling settings", open=False):top_p = gr.Slider(label="top p (0.0 = off)",minimum=0.0,maximum=1.0,value=0.0)typical_filtering = gr.Checkbox(label="typical filtering ",value=False35 unmodified lines)seed = gr.Number(label="seed (0 for random)",value=0,precision=0,)# mask settingswith gr.Column():vamp_button = gr.Button("generate (vamp)!!!")21 unmodified lines_inputs = {input_audio,num_steps,masktemp,sampletemp,top_p,prefix_s, suffix_s,rand_mask_intensity,periodic_p, periodic_w,6 unmodified linestypical_mass,typical_min_tokens,beat_mask_width,seed,beat_mask_downbeats}24 unmodified linesoutputs=[thank_you, download_file])demo.launch()
4 unmodified lines56784 unmodified linesloralibwavebeat @ git+https://github.com/hugofloresgarcia/wavebeatlac @ git+https://github.com/hugofloresgarcia/lac.gitaudiotools @ git+https://github.com/hugofloresgarcia/audiotools.git4 unmodified lines56784 unmodified linesloralibwavebeat @ git+https://github.com/hugofloresgarcia/wavebeatlac @ git+https://github.com/hugofloresgarcia/lac.gitdescript-audiotools @ git+https://github.com/descriptinc/audiotools.git@0.7.2
484 unmodified lines4854864874884894904916 unmodified lines4984995005015025035046 unmodified lines511512513514515516517518519520521484 unmodified linessave_path: str,resume: bool = False,tag: str = "latest",load_weights: bool = False,fine_tune_checkpoint: Optional[str] = None,grad_clip_val: float = 5.0,) -> State:6 unmodified lineskwargs = {"folder": f"{save_path}/{tag}","map_location": "cpu","package": not load_weights,}tracker.print(f"Loading checkpoint from {kwargs['folder']}")if (Path(kwargs["folder"]) / "vampnet").exists():6 unmodified linesif args["fine_tune"]:assert fine_tune_checkpoint is not None, "Must provide a fine-tune checkpoint"model = VampNet.load(location=Path(fine_tune_checkpoint), map_location="cpu")model = VampNet() if model is None else modelmodel = accel.prepare_model(model)# assert accel.unwrap(model).n_codebooks == codec.quantizer.n_codebooks484 unmodified lines4854864874884894906 unmodified lines4974984995005015025036 unmodified lines510511512513514515516517518519520521522523484 unmodified linessave_path: str,resume: bool = False,tag: str = "latest",fine_tune_checkpoint: Optional[str] = None,grad_clip_val: float = 5.0,) -> State:6 unmodified lineskwargs = {"folder": f"{save_path}/{tag}","map_location": "cpu","package": False,}tracker.print(f"Loading checkpoint from {kwargs['folder']}")if (Path(kwargs["folder"]) / "vampnet").exists():6 unmodified linesif args["fine_tune"]:assert fine_tune_checkpoint is not None, "Must provide a fine-tune checkpoint"model = torch.compile(VampNet.load(location=Path(fine_tune_checkpoint),map_location="cpu",))model = torch.compile(VampNet()) if model is None else modelmodel = accel.prepare_model(model)# assert accel.unwrap(model).n_codebooks == codec.quantizer.n_codebooks
366 unmodified lines367368369370371372207 unmodified lines58058158258358458558658758858959059159259359459559659759859941 unmodified lines64164264364464564664764864965065165265310 unmodified lines66466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170230 unmodified lines73373473573673773873926 unmodified lines766767768769770771366 unmodified linesreturn x, position_bias, encoder_decoder_position_biasclass TransformerStack(nn.Module):def __init__(207 unmodified linestime_steps: int = 300,sampling_steps: int = 24,start_tokens: Optional[torch.Tensor] = None,mask: Optional[torch.Tensor] = None,temperature: float = 2.5,typical_filtering=False,typical_mass=0.2,typical_min_tokens=1,return_signal=True,):logging.debug(f"beginning generation with {sampling_steps} steps")###################### resolve temperature ######################logging.debug(f"temperature: {temperature}")#####################41 unmodified lines################## begin sampling ##################for i in range(sampling_steps):logging.debug(f"step {i} of {sampling_steps}")# our current temperaturelogging.debug(f"temperature: {temperature}")# our current schedule stepr = scalar_to_batch_tensor((i + 1) / sampling_steps,10 unmodified lines# NOTE: this collapses the codebook dimension into the sequence dimensionlogits = self.forward(latents, r) # b, prob, seqlogits = logits.permute(0, 2, 1) # b, seq, probif typical_filtering:typical_filter(logits,typical_mass=typical_mass,typical_min_tokens=typical_min_tokens)logging.debug(f"permuted logits with shape: {logits.shape}")# logits2probsprobs = torch.softmax(logits, dim=-1)logging.debug(f"computed probs with shape: {probs.shape}")# sample from logits with multinomial samplingb = probs.shape[0]probs = rearrange(probs, "b seq prob -> (b seq) prob")sampled_z = torch.multinomial(probs, 1).squeeze(-1)sampled_z = rearrange(sampled_z, "(b seq)-> b seq", b=b)probs = rearrange(probs, "(b seq) prob -> b seq prob", b=b)logging.debug(f"sampled z with shape: {sampled_z.shape}")# get the confidences: which tokens did we sample?selected_probs = (torch.take_along_dim(probs, sampled_z.long().unsqueeze(-1),dim=-1).squeeze(-1))# flatten z_masked and mask, so we can deal with the sampling logic# we'll unflatten them at the end of the loop for the next forward pass# remove conditioning codebooks, we'll add them back at the end30 unmodified lines# get our new maskmask = mask_by_random_topk(num_to_mask, selected_probs, temperature * (1-r))# update the mask26 unmodified lineselse:return sampled_zdef mask_by_random_topk(num_to_mask: int, probs: torch.Tensor, temperature: float = 1.0):"""366 unmodified lines367368369370371372373374375376377378379380381207 unmodified lines58959059159259359459559659759859960060160260360460560660760841 unmodified lines65065165265365465565665765865966010 unmodified lines67167267367467567667767867968068168268368468568668768868930 unmodified lines72072172272372472572626 unmodified lines753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843366 unmodified linesreturn x, position_bias, encoder_decoder_position_biasdef t_schedule(n_steps, max_temp=1.0, min_temp=0.0, k=1.0):x = np.linspace(0, 1, n_steps)a = (0.5 - min_temp) / (max_temp - min_temp)x = (x * 12) - 6x0 = np.log((1 / a - 1) + 1e-5) / ky = (1 / (1 + np.exp(- k *(x-x0))))[::-1]return yclass TransformerStack(nn.Module):def __init__(207 unmodified linestime_steps: int = 300,sampling_steps: int = 24,start_tokens: Optional[torch.Tensor] = None,sampling_temperature: float = 1.0,mask: Optional[torch.Tensor] = None,mask_temperature: float = 20.5,typical_filtering=False,typical_mass=0.2,typical_min_tokens=1,top_p=None,return_signal=True,seed: int = None):if seed is not None:at.util.seed(seed)logging.debug(f"beginning generation with {sampling_steps} steps")#####################41 unmodified lines################## begin sampling ##################t_sched = t_schedule(sampling_steps, max_temp=sampling_temperature)for i in range(sampling_steps):logging.debug(f"step {i} of {sampling_steps}")# our current schedule stepr = scalar_to_batch_tensor((i + 1) / sampling_steps,10 unmodified lines# NOTE: this collapses the codebook dimension into the sequence dimensionlogits = self.forward(latents, r) # b, prob, seqlogits = logits.permute(0, 2, 1) # b, seq, probb = logits.shape[0]logging.debug(f"permuted logits with shape: {logits.shape}")sampled_z, selected_probs = sample_from_logits(logits, sample=True, temperature=t_sched[i],typical_filtering=typical_filtering, typical_mass=typical_mass,typical_min_tokens=typical_min_tokens,top_k=None, top_p=top_p, return_probs=True)logging.debug(f"sampled z with shape: {sampled_z.shape}")# flatten z_masked and mask, so we can deal with the sampling logic# we'll unflatten them at the end of the loop for the next forward pass# remove conditioning codebooks, we'll add them back at the end30 unmodified lines# get our new maskmask = mask_by_random_topk(num_to_mask, selected_probs, mask_temperature * (1-r))# update the mask26 unmodified lineselse:return sampled_zdef sample_from_logits(logits,sample: bool = True,temperature: float = 1.0,top_k: int = None,top_p: float = None,typical_filtering: bool = False,typical_mass: float = 0.2,typical_min_tokens: int = 1,return_probs: bool = False):"""Convenience function to sample from a categorial distribution with input asunnormalized logits.Parameters----------logits : Tensor[..., vocab_size]config: SamplingConfigThe set of hyperparameters to be used for samplingsample : bool, optionalWhether to perform multinomial sampling, by default Truetemperature : float, optionalScaling parameter when multinomial samping, by default 1.0top_k : int, optionalRestricts sampling to only `top_k` values acc. to probability,by default Nonetop_p : float, optionalRestricts sampling to only those values with cumulativeprobability = `top_p`, by default NoneReturns-------Tensor[...]Sampled tokens"""shp = logits.shape[:-1]if typical_filtering:typical_filter(logits,typical_mass=typical_mass,typical_min_tokens=typical_min_tokens)# Apply top_k samplingif top_k is not None:v, _ = logits.topk(top_k)logits[logits < v[..., [-1]]] = -float("inf")# Apply top_p (nucleus) samplingif top_p is not None and top_p < 1.0:v, sorted_indices = logits.sort(descending=True)cumulative_probs = v.softmax(dim=-1).cumsum(dim=-1)sorted_indices_to_remove = cumulative_probs > top_p# Right shift indices_to_remove to keep 1st token over thresholdsorted_indices_to_remove = F.pad(sorted_indices_to_remove, (1, 0), value=False)[..., :-1]# Compute indices_to_remove in unsorted arrayindices_to_remove = sorted_indices_to_remove.scatter(-1, sorted_indices, sorted_indices_to_remove)logits[indices_to_remove] = -float("inf")# Perform multinomial sampling after normalizing logitsprobs = (F.softmax(logits / temperature, dim=-1)if temperature > 0else logits.softmax(dim=-1))token = (probs.view(-1, probs.size(-1)).multinomial(1).squeeze(1).view(*shp)if sampleelse logits.argmax(-1))if return_probs:token_probs = probs.take_along_dim(token.unsqueeze(-1), dim=-1).squeeze(-1)return token, token_probselse:return tokendef mask_by_random_topk(num_to_mask: int, probs: torch.Tensor, temperature: float = 1.0):"""
.gitignore+2
app.py+53-14
requirements.txt+1-1
scripts/exp/train.py+7-5
vampnet/modules/transformer.py+109-37