Spaces:
Runtime error
Runtime error
Merge branch 'lora-app' into ismir
Browse filesFiles changed (9)
- app.py+110-17
- conf/lora/lora.yml+4-2
- scripts/exp/fine_tune.py+2-2
- scripts/utils/augment.py+38-24
- scripts/utils/remove_quiet_files.pyAdded+29
- scripts/xeno-canto-dl.pyAdded+234
- vampnet/interface.py+2-3
- vampnet/mask.py+38-20
- vampnet/modules/transformer.py+9-14
17 unmodified lines1819202122232425262727 unmodified lines55565758596061626333 unmodified lines97989910010110210313 unmodified lines11711811912012112212353 unmodified lines177178179180181182139 unmodified lines32232332432532632732811 unmodified lines34034134234334434556 unmodified lines4024034044054064074084094104114124134144159 unmodified lines4254264274284294304316 unmodified lines43843944044144244317 unmodified lines4614624634644654664674684694705 unmodified lines47647747847948048136 unmodified lines51851952052152252352423 unmodified lines54854955055117 unmodified linesconf = argbind.parse_args()with argbind.scope(conf):interface = Interface()# loader = AudioLoader()print(f"interface device is {interface.device}")# dataset = at.data.datasets.AudioDataset(# loader,27 unmodified linesdef _vamp(data, return_mask=False):out_dir = OUT_DIR / str(uuid.uuid4())out_dir.mkdir()sig = at.AudioSignal(data[input_audio])z = interface.encode(sig)33 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())13 unmodified linesgen_fn=interface.coarse.generate,seed=_seed,sample_cutoff=data[sample_cutoff],classes=_classes,)if use_coarse2fine:53 unmodified lines"stretch_factor": data[stretch_factor],"seed": data[seed],"samplecutoff": data[sample_cutoff],}# save with yaml139 unmodified linesonset_mask_width = gr.Slider(label="onset mask width (multiplies with the periodic mask, 1 step ~= 10milliseconds) ",minimum=0,maximum=20,step=1,value=5,)11 unmodified lineswith gr.Accordion("extras ", open=False):rand_mask_intensity = gr.Slider(label="random mask intensity. (If this is less than 1, scatters prompts throughout the audio, should be between 0.9 and 1.0)",minimum=0.0,56 unmodified linesmasktemp = 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)9 unmodified lineslabel="typical filtering ",value=False)typical_mass = gr.Slider(label="typical mass (should probably stay between 0.1 and 0.5)",minimum=0.01,maximum=0.99,6 unmodified linesstep=1,value=64)use_coarse2fine = gr.Checkbox(label="use coarse2fine",17 unmodified linesvalue=0.0)use_new_trick = gr.Checkbox(label="new trick",value=False)seed = gr.Number(label="seed (0 for random)",5 unmodified lines# mask settingswith gr.Column():vamp_button = gr.Button("generate (vamp)!!!")output_audio = gr.Audio(label="output audio",36 unmodified linesbeat_mask_width,beat_mask_downbeats,seed,sample_cutoff,}# connect widgets23 unmodified linesoutputs=[thank_you, download_file])demo.launch(share=True, enable_queue=False, debug=True)17 unmodified lines1819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717227 unmodified lines10010110210310410510610710810911011111211311433 unmodified lines14814915015115215315415515615715815916016116216316416516616716816917017117217317413 unmodified lines18818919019119219353 unmodified lines247248249250251252253139 unmodified lines39339439539639739839911 unmodified lines41141241341441541641741841942042142242342456 unmodified lines4814824834844854864874884894904914924934944959 unmodified lines5055065075085095105116 unmodified lines51851952052152252352452552652752852953017 unmodified lines5485495505515525535 unmodified lines55956056156256356456556656756856957057157236 unmodified lines60961061161261361461561661723 unmodified lines64164264364417 unmodified linesconf = argbind.parse_args()from torch_pitch_shift import pitch_shift, get_fast_shiftsdef shift_pitch(signal, interval: int):signal.samples = pitch_shift(signal.samples,shift=interval,sample_rate=signal.sample_rate)return signaldef load_interface():with argbind.scope(conf):interface = Interface()# loader = AudioLoader()print(f"interface device is {interface.device}")return interfaceLORA_NONE = "None"def load_loras():loras = {}# find confs under conf/generatedfor conf_file in Path("conf/generated").glob("**/interface.yml"):name = conf_file.parent.namewith open(conf_file) as f:loras[name] = yaml.safe_load(f)loras[LORA_NONE] = Nonereturn lorasinterface = load_interface()loras = load_loras()cur_lora = LORA_NONEdef load_lora(name):global interfaceglobal cur_loraif name == cur_lora:returnif name != LORA_NONE:interface.lora_load(coarse_ckpt=loras[name]["Interface.coarse_lora_ckpt"],c2f_ckpt=loras[name]["Interface.coarse2fine_lora_ckpt"],full_ckpts=False)cur_lora = nameelse:interface = load_interface()cur_lora = LORA_NONE# dataset = at.data.datasets.AudioDataset(# loader,27 unmodified linesdef _vamp(data, return_mask=False):load_lora(data[lora_choice])out_dir = OUT_DIR / str(uuid.uuid4())out_dir.mkdir()sig = at.AudioSignal(data[input_audio])sig = interface.preprocess(sig)if data[pitch_shift_amt] != 0:sig = shift_pitch(sig, data[pitch_shift_amt])z = interface.encode(sig)33 unmodified linesmask = pmask.codebook_unmask(mask, ncc)print(f"dropout {data[dropout]}")print(f"masktemp {data[masktemp]}")print(f"sampletemp {data[sampletemp]}")print(f"top_p {data[top_p]}")print(f"prefix_s {data[prefix_s]}")print(f"suffix_s {data[suffix_s]}")print(f"rand_mask_intensity {data[rand_mask_intensity]}")print(f"num_steps {data[num_steps]}")print(f"periodic_p {data[periodic_p]}")print(f"periodic_w {data[periodic_w]}")print(f"n_conditioning_codebooks {data[n_conditioning_codebooks]}")print(f"use_coarse2fine {data[use_coarse2fine]}")print(f"onset_mask_width {data[onset_mask_width]}")print(f"beat_mask_width {data[beat_mask_width]}")print(f"beat_mask_downbeats {data[beat_mask_downbeats]}")print(f"stretch_factor {data[stretch_factor]}")print(f"seed {data[seed]}")print(f"pitch_shift_amt {data[pitch_shift_amt]}")print(f"sample_cutoff {data[sample_cutoff]}")_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())13 unmodified linesgen_fn=interface.coarse.generate,seed=_seed,sample_cutoff=data[sample_cutoff],)if use_coarse2fine:53 unmodified lines"stretch_factor": data[stretch_factor],"seed": data[seed],"samplecutoff": data[sample_cutoff],"lora": data[lora_choice],}# save with yaml139 unmodified linesonset_mask_width = gr.Slider(label="onset mask width (multiplies with the periodic mask, 1 step ~= 10milliseconds) ",minimum=0,maximum=100,step=1,value=5,)11 unmodified lineswith gr.Accordion("extras ", open=False):pitch_shift_amt = gr.Slider(label="pitch shift amount (semitones)",minimum=-12,maximum=12,step=1,value=0,)rand_mask_intensity = gr.Slider(label="random mask intensity. (If this is less than 1, scatters prompts throughout the audio, should be between 0.9 and 1.0)",minimum=0.0,56 unmodified linesmasktemp = gr.Slider(label="mask temperature",minimum=0.0,maximum=100.0,value=1.5)sampletemp = gr.Slider(label="sample temperature",minimum=0.1,maximum=10.0,value=1.0,step=0.001)9 unmodified lineslabel="typical filtering ",value=False)typical_mass = gr.Slider(label="typical mass (should probably stay between 0.1 and 0.5)",minimum=0.01,maximum=0.99,6 unmodified linesstep=1,value=64)sample_cutoff = gr.Slider(label="sample cutoff",minimum=0.0,maximum=1.0,value=0.5,step=0.01)use_coarse2fine = gr.Checkbox(label="use coarse2fine",17 unmodified linesvalue=0.0)seed = gr.Number(label="seed (0 for random)",5 unmodified lines# mask settingswith gr.Column():lora_choice = gr.Dropdown(label="lora choice",choices=list(loras.keys()),value=LORA_NONE,visible=False)vamp_button = gr.Button("generate (vamp)!!!")output_audio = gr.Audio(label="output audio",36 unmodified linesbeat_mask_width,beat_mask_downbeats,seed,lora_choice,pitch_shift_amt,sample_cutoff}# connect widgets23 unmodified linesoutputs=[thank_you, download_file])demo.launch(share=True, enable_queue=True, debug=True)
3 unmodified lines45678910111213141516173 unmodified linesfine_tune: Truetrain/AudioDataset.n_examples: 100000000val/AudioDataset.n_examples: 100NoamScheduler.warmup: 500batch_size: 7num_workers: 7save_iters: [100000, 200000, 300000, 4000000, 500000]AdamW.lr: 0.00013 unmodified lines456789101112131415161718193 unmodified linesfine_tune: Truetrain/AudioDataset.n_examples: 100000000val/AudioDataset.n_examples: 500NoamScheduler.warmup: 500batch_size: 7num_workers: 7save_iters: [10000, 20000, 30000, 40000, 50000]sample_freq: 1000val_freq: 500AdamW.lr: 0.0001
47 unmodified lines4849505152535455565747 unmodified lines}interface_conf = {"Interface.coarse_ckpt": f"./models/vampnet/coarse.pth","Interface.coarse_lora_ckpt": f"./runs/{name}/coarse/latest/lora.pth","Interface.coarse2fine_ckpt": f"./models/vampnet/c2f.pth","Interface.coarse2fine_lora_ckpt": f"./runs/{name}/c2f/latest/lora.pth","Interface.wavebeat_ckpt": "./models/wavebeat.pth",47 unmodified lines4849505152535455565747 unmodified lines}interface_conf = {"Interface.coarse_ckpt": f"./runs/{name}/coarse/latest/vampnet/weights.pth","Interface.coarse_lora_ckpt": f"./runs/{name}/coarse/latest/lora.pth","Interface.coarse2fine_ckpt": f"./runs/{name}/c2f/latest/vampnet/weights.pth","Interface.coarse2fine_lora_ckpt": f"./runs/{name}/c2f/latest/lora.pth","Interface.wavebeat_ckpt": "./models/wavebeat.pth",
4 unmodified lines5678910111213141516171819202122232425262728293031323334353637382 unmodified lines414243444546471 unmodified line49505152534 unmodified linesimport argbindimport tqdmfrom pedalboard import (Compressor, Gain, Chorus, LadderFilter, Phaser, Convolution, Reverb, Pedalboard)from pedalboard.io import AudioFile# Read in a whole file, resampling to our desired sample rate:samplerate = 44100.0with AudioFile('guitar-input.wav').resampled_to(samplerate) as f:audio = f.read(f.frames)# Make a pretty interesting sounding guitar pedalboard:board = Pedalboard([Compressor(threshold_db=-50, ratio=25),Gain(gain_db=30),Chorus(),LadderFilter(mode=LadderFilter.Mode.HPF12, cutoff_hz=900),Phaser(),Convolution("./guitar_amp.wav", 1.0),Reverb(room_size=0.25),])@argbind.bind(without_prefix=True)def augment(audio_folder: Path,dest_folder: Path,n_augmentations: int = 10,):"""2 unmodified linesThe dest foler will contain a folder for each of the clean dataset's files.Under each of these folders, there will be a clean file and many augmented files."""audio_files = at.util.find_audio(audio_folder)for audio_file in tqdm.tqdm(audio_files):1 unmodified linesubdir = subtree / audio_file.stemsubdir.mkdir(parents=True, exist_ok=True)# apply pedalboard transformsfor i in range(n_augmentations):4 unmodified lines5678910111213141516171819202122232 unmodified lines26272829303132331 unmodified line3536373839404142434445464748495051525354555657585960616263646566674 unmodified linesimport argbindimport tqdmimport torchfrom torch_pitch_shift import pitch_shift, get_fast_shiftsfrom torch_time_stretch import time_stretch, get_fast_stretchesfrom audiotools.core.util import sample_from_dist@argbind.bind(without_prefix=True)def augment(audio_folder: Path = None,dest_folder: Path = None,n_augmentations: int = 10,):"""2 unmodified linesThe dest foler will contain a folder for each of the clean dataset's files.Under each of these folders, there will be a clean file and many augmented files."""assert audio_folder is not Noneassert dest_folder is not Noneaudio_files = at.util.find_audio(audio_folder)for audio_file in tqdm.tqdm(audio_files):1 unmodified linesubdir = subtree / audio_file.stemsubdir.mkdir(parents=True, exist_ok=True)src = AudioSignal(audio_file).to("cuda" if torch.cuda.is_available() else "cpu")for i, chunk in tqdm.tqdm(enumerate(src.windows(10, 10))):# apply pedalboard transformsfor j in range(n_augmentations):# pitch shift between -7 and 7 semitonesimport randomdst = chunk.clone()dst.samples = pitch_shift(dst.samples,shift=random.choice(get_fast_shifts(src.sample_rate,condition=lambda x: x >= 0.25 and x <= 1.0)),sample_rate=src.sample_rate)dst.samples = time_stretch(dst.samples,stretch=random.choice(get_fast_stretches(src.sample_rate,condition=lambda x: x >= 0.667 and x <= 1.5, )),sample_rate=src.sample_rate,)dst.cpu().write(subdir / f"{i}-{j}.wav")if __name__ == "__main__":args = argbind.parse_args()with argbind.scope(args):augment()
1234567891011121314151617181920212223242526272829# removes files with loudness below 24db
from pathlib import Path import shutilimport audiotools as atimport argbind
@argbind.bind(without_prefix=True)def remove_quiet_files( src_dir: Path = None, dest_dir: Path = None, min_loudness: float = -30,): # copy src to dest dest_dir.mkdir(parents=True, exist_ok=True) shutil.copytree(src_dir, dest_dir, dirs_exist_ok=True) audio_files = at.util.find_audio(dest_dir) for audio_file in audio_files: sig = at.AudioSignal(audio_file) if sig.loudness() < min_loudness: audio_file.unlink() print(f"removed {audio_file}")
if __name__ == "__main__": args = argbind.parse_args()
with argbind.scope(args): remove_quiet_files()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234from xenopy import Query
SPECIES = [ "American Robin", "Northern Cardinal", "Mourning Dove", "American Crow", "Baltimore Oriole", "Blue Jay", "Eastern Bluebird", "House Finch", "American Goldfinch", "House Sparrow", "Song Sparrow", "Tufted Titmouse", "White-breasted Nuthatch", "European Starling", "American Redstart", "Red-winged Blackbird", "Brown-headed Cowbird", "Common Grackle", "Boat-tailed Grackle", "Common Yellowthroat", "Northern Mockingbird", "Carolina Wren", "Eastern Meadowlark", "Chipping Sparrow", "Tree Swallow", "Barn Swallow", "Cliff Swallow", "Pine Siskin", "Indigo Bunting", "Eastern Towhee", "Carolina Chickadee", "Great Crested Flycatcher", "Eastern Wood-Pewee", "Ovenbird", "Northern Flicker", "Red-eyed Vireo", "American Woodcock", "Eastern Phoebe", "Downy Woodpecker", "Scarlet Tanager", "Yellow Warbler", "White-eyed Vireo", "Common Loon", "White-throated Sparrow", "Yellow-throated Vireo", "Great Blue Heron", "Belted Kingfisher", "Pied-billed Grebe", "Wild Turkey", "Wood Thrush", "Rose-breasted Grosbeak", "Field Sparrow", "Hooded Warbler", "Northern Parula", "Chestnut-sided Warbler", "Blue-winged Warbler", "Red-bellied Woodpecker", "Yellow-billed Cuckoo", "Gray Catbird", "Northern Saw-whet Owl", "Osprey", "Common Nighthawk", "Broad-winged Hawk", "Black-throated Green Warbler", "Great Horned Owl", "Common Raven", "Barred Owl", "Canada Warbler", "Magnolia Warbler", "Black-and-white Warbler", "Eastern Kingbird", "Swainson's Thrush", "Worm-eating Warbler", "Prairie Warbler", "Baltimore Oriole", "Black-throated Blue Warbler", "Louisiana Waterthrush", "Blackburnian Warbler", "Black-capped Chickadee", "Cerulean Warbler", "Red-shouldered Hawk", "Cooper's Hawk", "Yellow-throated Warbler", "Blue-headed Vireo", "Blackpoll Warbler", "Ruffed Grouse", "Kentucky Warbler", "Hermit Thrush", "Cedar Waxwing", "Eastern Screech-Owl", "Northern Goshawk", "Green Heron", "Red-tailed Hawk", "Black Vulture", "Hairy Woodpecker", "Golden-crowned Kinglet", "Ruby-crowned Kinglet", "Bicknell's Thrush", "Blue-gray Gnatcatcher", "Veery", "Pileated Woodpecker", "Purple Finch", "White-crowned Sparrow", "Snow Bunting", "Pine Grosbeak", "American Tree Sparrow", "Dark-eyed Junco", "Snowy Owl", "White-winged Crossbill", "Red Crossbill", "Common Redpoll", "Northern Shrike", "Northern Harrier", "Rough-legged Hawk", "Long-eared Owl", "Evening Grosbeak", "Northern Pintail", "American Black Duck", "Mallard", "Canvasback", "Redhead", "Ring-necked Duck", "Greater Scaup", "Lesser Scaup", "Bufflehead", "Common Goldeneye", "Hooded Merganser", "Common Merganser", "Red-breasted Merganser", "Ruddy Duck", "Wood Duck", "Gadwall", "American Wigeon", "Northern Shoveler", "Green-winged Teal", "Blue-winged Teal", "Cinnamon Teal", "Ringed Teal", "Cape Teal", "Northern Fulmar", "Yellow-billed Loon", "Red-throated Loon", "Arctic Loon", "Pacific Loon", "Horned Grebe", "Red-necked Grebe", "Eared Grebe", "Western Grebe", "Clark's Grebe", "Double-crested Cormorant", "Pelagic Cormorant", "Great Cormorant", "American White Pelican", "Brown Pelican", "Brandt's Cormorant", "Least Bittern", "Great Egret", "Snowy Egret", "Little Blue Heron", "Tricolored Heron", "Reddish Egret", "Black-crowned Night-Heron", "Yellow-crowned Night-Heron", "White Ibis", "Glossy Ibis", "Roseate Spoonbill", "Wood Stork", "Black-bellied Whistling-Duck", "Fulvous Whistling-Duck", "Greater White-fronted Goose", "Snow Goose", "Ross's Goose", "Canada Goose", "Brant", "Mute Swan", "Tundra Swan", "Whooper Swan", "Sandhill Crane", "Black-necked Stilt", "American Avocet", "Northern Jacana", "Greater Yellowlegs", "Lesser Yellowlegs", "Willet", "Spotted Sandpiper", "Upland Sandpiper", "Whimbrel", "Long-billed Curlew", "Marbled Godwit", "Ruddy Turnstone", "Red Knot", "Sanderling", "Semipalmated Sandpiper", "Western Sandpiper", "Least Sandpiper", "White-rumped Sandpiper", "Baird's Sandpiper", "Pectoral Sandpiper", "Dunlin", "Buff-breasted Sandpiper", "Short-billed Dowitcher", "Long-billed Dowitcher", "Common Snipe", "American Woodcock", "Wilson's Phalarope", "Red-necked Phalarope", "Red Phalarope"]
from pathlib import Path
def remove_spaces(s): return s.replace(" ", "")
for species in SPECIES: if Path("/media/CHONK/hugo/xeno-canto-full/" + remove_spaces(species)).exists(): continue try: q = Query( name=species, q="A", length="10-30", )
# retrieve metadata metafiles = q.retrieve_meta(verbose=True) # retrieve recordings q.retrieve_recordings(multiprocess=True, nproc=10, attempts=10, outdir="/media/CHONK/hugo/xeno-canto-full/")
except: print("Failed to download " + species) continue119 unmodified lines120121122123124125126127128129130131132133134135136119 unmodified linesif coarse_ckpt is not None:self.coarse.to("cpu")state_dict = torch.load(coarse_ckpt, map_location="cpu")self.coarse.load_state_dict(state_dict, strict=False)self.coarse.to(self.device)if c2f_ckpt is not None:self.c2f.to("cpu")state_dict = torch.load(c2f_ckpt, map_location="cpu")self.c2f.load_state_dict(state_dict, strict=False)self.c2f.to(self.device)def s2t(self, seconds: float):"""seconds to tokens"""if isinstance(seconds, np.ndarray):119 unmodified lines120121122123124125126127128129130131132133134135119 unmodified linesif coarse_ckpt is not None:self.coarse.to("cpu")state_dict = torch.load(coarse_ckpt, map_location="cpu")print(f"loading coarse from {coarse_ckpt}")self.coarse.load_state_dict(state_dict, strict=False)self.coarse.to(self.device)if c2f_ckpt is not None:self.c2f.to("cpu")state_dict = torch.load(c2f_ckpt, map_location="cpu")print(f"loading c2f from {c2f_ckpt}")self.c2f.load_state_dict(state_dict, strict=False)self.c2f.to(self.device)def s2t(self, seconds: float):"""seconds to tokens"""if isinstance(seconds, np.ndarray):
190 unmodified lines191192193194195196197198199200201202203204205206207208209210211212213214215216217218219190 unmodified lineswidth: int = 1):import librosaonset_indices = librosa.onset.onset_detect(y=sig.clone().to_mono().samples.cpu().numpy()[0, 0],sr=sig.sample_rate,hop_length=interface.codec.hop_length,backtrack=True,)# create a mask, set onsetmask = torch.ones_like(z)n_timesteps = z.shape[-1]for onset_index in onset_indices:onset_index = min(onset_index, n_timesteps - 1)onset_index = max(onset_index, 0)mask[:, :, onset_index - width:onset_index + width] = 0.0print(mask)return maskif __name__ == "__main__":torch.set_printoptions(threshold=10000)190 unmodified lines191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237190 unmodified lineswidth: int = 1):import librosaimport madmomfrom madmom.features.onsets import RNNOnsetProcessor, OnsetPeakPickingProcessorimport tempfileimport numpy as npwith tempfile.NamedTemporaryFile(suffix='.wav') as f:sig = sig.clone()sig.write(f.name)proc = RNNOnsetProcessor(online=False)onsetproc = OnsetPeakPickingProcessor(threshold=0.3,fps=sig.sample_rate/interface.codec.hop_length)act = proc(f.name)onset_times = onsetproc(act)# convert to indices for z arrayonset_indices = librosa.time_to_frames(onset_times, sr=sig.sample_rate, hop_length=interface.codec.hop_length)if onset_indices.shape[0] == 0:mask = empty_mask(z)print(f"no onsets found, returning empty mask")else:torch.set_printoptions(threshold=1000)print("onset indices: ", onset_indices)print("onset times: ", onset_times)# create a mask, set onsetmask = torch.ones_like(z)n_timesteps = z.shape[-1]for onset_index in onset_indices:onset_index = min(onset_index, n_timesteps - 1)onset_index = max(onset_index, 0)mask[:, :, onset_index - width:onset_index + width] = 0.0print(mask)return maskif __name__ == "__main__":pass
366 unmodified lines367368369370371372373374375376377378379380381216 unmodified lines59859960060160260360446 unmodified lines65165265365465565665722 unmodified lines680681682683684685686156 unmodified lines8438448458468478488496 unmodified lines856857858859860861862366 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__(216 unmodified linestop_p=None,return_signal=True,seed: int = None,sample_cutoff: float = 0.5):if seed is not None:at.util.seed(seed)46 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}")22 unmodified lineslogits, sample=((i / sampling_steps) <= sample_cutoff),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,156 unmodified linesdef mask_by_random_topk(num_to_mask: int, probs: torch.Tensor, temperature: float = 1.0):"""Args:num_to_mask (int): number of tokens to mask6 unmodified lineslogging.debug(f"temperature: {temperature}")logging.debug("")confidence = torch.log(probs) + temperature * gumbel_noise_like(probs)logging.debug(f"confidence shape: {confidence.shape}")sorted_confidence, sorted_idx = confidence.sort(dim=-1)366 unmodified lines367368369370371372216 unmodified lines58959059159259359459546 unmodified lines64264364464564664722 unmodified lines670671672673674675676156 unmodified lines8338348358368378388398408418428436 unmodified lines850851852853854855856857366 unmodified linesreturn x, position_bias, encoder_decoder_position_biasclass TransformerStack(nn.Module):def __init__(216 unmodified linestop_p=None,return_signal=True,seed: int = None,sample_cutoff: float = 0.5,):if seed is not None:at.util.seed(seed)46 unmodified lines################## begin sampling ##################for i in range(sampling_steps):logging.debug(f"step {i} of {sampling_steps}")22 unmodified lineslogits, sample=((i / sampling_steps) <= sample_cutoff),temperature=sampling_temperature,typical_filtering=typical_filtering, typical_mass=typical_mass,typical_min_tokens=typical_min_tokens,top_k=None, top_p=top_p, return_probs=True,156 unmodified linesdef mask_by_random_topk(num_to_mask: int,probs: torch.Tensor,temperature: float = 1.0,):"""Args:num_to_mask (int): number of tokens to mask6 unmodified lineslogging.debug(f"temperature: {temperature}")logging.debug("")noise = gumbel_noise_like(probs)confidence = torch.log(probs) + temperature * noiselogging.debug(f"confidence shape: {confidence.shape}")sorted_confidence, sorted_idx = confidence.sort(dim=-1)
app.py+110-17
conf/lora/lora.yml+4-2
scripts/exp/fine_tune.py+2-2
scripts/utils/augment.py+38-24
scripts/utils/remove_quiet_files.pyAdded+29
scripts/xeno-canto-dl.pyAdded+234
vampnet/interface.py+2-3
vampnet/mask.py+38-20
vampnet/modules/transformer.py+9-14