Spaces:
Runtime error
Runtime error
Merge branch 'ismir' into pr/9
Browse filesFiles changed (14)
- .gitignore-3
- README.md+10-2
- app.py+101-22
- conf/lora/lora.yml+4-2
- scripts/exp/fine_tune.py+2-4
- scripts/exp/train.py+9-3
- scripts/utils/augment.py+38-24
- scripts/utils/remove_quiet_files.pyAdded+29
- scripts/utils/split_long_audio_file.pyAdded+34
- scripts/utils/xeno-canto-dl.pyAdded+234
- setup.py+3-2
- vampnet/interface.py+2-3
- vampnet/mask.py+38-20
- vampnet/modules/transformer.py+16-17
178 unmodified lines179180181182183184185186187178 unmodified linessamples*/models-all/models.zipaudiotools/descript-audio-codec/# *.pth.git-oldconf/generated/*runs*/178 unmodified lines179180181182183184178 unmodified linessamples*/models-all/models.zip.git-oldconf/generated/*runs*/
17 unmodified lines1819202122232466 unmodified lines9192939495969717 unmodified lines# Setting upRequires Python 3.9 or later.install VampNet66 unmodified lineslaunch the interface:```bashpython demo.py --args.load conf/generated/<fine_tune_name>/interface.yml```17 unmodified lines18192021222324252627282930313266 unmodified lines9910010110210310410517 unmodified lines# Setting up**Requires Python 3.9**.you'll need a Python 3.9 environment to run VampNet. This is due to a [known issue with madmom](https://github.com/hugofloresgarcia/vampnet/issues/15).(for example, using conda)```bashconda create -n vampnet python=3.9conda activate vampnet```install VampNet66 unmodified lineslaunch the interface:```bashpython app.py --args.load conf/generated/<fine_tune_name>/interface.yml```
17 unmodified lines1819202122232425262728293031323316 unmodified lines5051525354555611 unmodified lines68697071727333 unmodified lines10710810911011111211312 unmodified lines1261271281291301312 unmodified lines13413513613713813914042 unmodified lines18318418518618718876 unmodified lines26526626726826927027127227327427527627727827928028128228328428528628728828929029129229315 unmodified lines30931031131231331431531631731831932032132211 unmodified lines33433533633733833956 unmodified lines3963973983994004014024034044054064074084099 unmodified lines4194204214224234244256 unmodified lines43243343443543643768 unmodified lines50650750850951051151251317 unmodified lines# Interface = argbind.bind(Interface)# AudioLoader = argbind.bind(at.data.datasets.AudioLoader)interface = Interface(coarse_ckpt="./models/vampnet/coarse.pth",coarse2fine_ckpt="./models/vampnet/c2f.pth",codec_ckpt="./models/vampnet/codec.pth",wavebeat_ckpt="./models/wavebeat.pth",device="cuda" if torch.cuda.is_available() else "cpu",)# loader = AudioLoader()print(f"interface device is {interface.device}")# dataset = at.data.datasets.AudioDataset(# loader,16 unmodified lines)sig = interface.preprocess(sig)out_dir = OUT_DIR / str(uuid.uuid4())out_dir.mkdir(parents=True, exist_ok=True)sig.write(out_dir / "input.wav")return sig.path_to_file11 unmodified linesout_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())12 unmodified linestop_p=_top_p,gen_fn=interface.coarse.generate,seed=_seed,)if use_coarse2fine:2 unmodified linesmask_temperature=data[masktemp]*10,sampling_temperature=data[sampletemp],mask=mask,sampling_steps=data[num_steps],seed=_seed,)42 unmodified lines"use_coarse2fine": data[use_coarse2fine],"stretch_factor": data[stretch_factor],"seed": data[seed],}# save with yaml76 unmodified lines"beat_mask_downbeats": False,},"slight periodic variation": {"periodic_p": 7,"onset_mask_width": 0,"beat_mask_width": 0,"beat_mask_downbeats": False,},"strong periodic variation": {"periodic_p": 13,"onset_mask_width": 5,"beat_mask_width": 0,"beat_mask_downbeats": False,},"very strong periodic variation": {"periodic_p": 17,"onset_mask_width": 5,"beat_mask_width": 0,"beat_mask_downbeats": False,},"beat-driven variation": {"periodic_p": 0,"onset_mask_width": 0,"beat_mask_width": 20,"beat_mask_downbeats": False,},"beat-driven variation (downbeats only, strong)": {"periodic_p": 0,"onset_mask_width": 0,15 unmodified linesminimum=0,maximum=128,step=1,value=13,)onset_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",68 unmodified linestypical_mass,typical_min_tokens,beat_mask_width,seed,beat_mask_downbeats}# connect widgets17 unmodified lines1819202122232425262728293031323334353637383940414243444546474849505152535416 unmodified lines7172737475767711 unmodified lines8990919293949596979833 unmodified lines13213313413513613713813914014114214314414514614714814915015115215315415515615715812 unmodified lines1711721731741751761772 unmodified lines18018118218318418518618742 unmodified lines23023123223323423523676 unmodified lines31331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235315 unmodified lines36937037137237337437537637737837938038138211 unmodified lines39439539639739839940040140240340440540640756 unmodified lines4644654664674684694704714724734744754764774789 unmodified lines4884894904914924934946 unmodified lines50150250350450550650750850951051151251368 unmodified lines58258358458558658758858959059159217 unmodified lines# Interface = argbind.bind(Interface)# AudioLoader = argbind.bind(at.data.datasets.AudioLoader)# loader = AudioLoader()print(f"interface device is {interface.device}")Interface = argbind.bind(Interface)# AudioLoader = argbind.bind(at.data.datasets.AudioLoader)conf = 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():interface = Interface(coarse_ckpt="./models/vampnet/coarse.pth",coarse2fine_ckpt="./models/vampnet/c2f.pth",codec_ckpt="./models/vampnet/codec.pth",wavebeat_ckpt="./models/wavebeat.pth",device="cuda" if torch.cuda.is_available() else "cpu",)return interfaceinterface = load_interface()# dataset = at.data.datasets.AudioDataset(# loader,16 unmodified lines)sig = interface.preprocess(sig)out_dir = OUT_DIR / "tmp" / str(uuid.uuid4())out_dir.mkdir(parents=True, exist_ok=True)sig.write(out_dir / "input.wav")return sig.path_to_file11 unmodified linesout_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())12 unmodified linestop_p=_top_p,gen_fn=interface.coarse.generate,seed=_seed,sample_cutoff=data[sample_cutoff],)if use_coarse2fine:2 unmodified linesmask_temperature=data[masktemp]*10,sampling_temperature=data[sampletemp],mask=mask,sampling_steps=data[num_steps],sample_cutoff=data[sample_cutoff],seed=_seed,)42 unmodified lines"use_coarse2fine": data[use_coarse2fine],"stretch_factor": data[stretch_factor],"seed": data[seed],"samplecutoff": data[sample_cutoff],}# save with yaml76 unmodified lines"beat_mask_downbeats": False,},"slight periodic variation": {"periodic_p": 5,"onset_mask_width": 5,"beat_mask_width": 0,"beat_mask_downbeats": False,},"moderate periodic variation": {"periodic_p": 13,"onset_mask_width": 5,"beat_mask_width": 0,"beat_mask_downbeats": False,},"strong periodic variation": {"periodic_p": 17,"onset_mask_width": 5,"beat_mask_width": 0,"beat_mask_downbeats": False,},"very strong periodic variation": {"periodic_p": 21,"onset_mask_width": 5,"beat_mask_width": 0,"beat_mask_downbeats": False,},"beat-driven variation": {"periodic_p": 0,"onset_mask_width": 0,"beat_mask_width": 50,"beat_mask_downbeats": False,},"beat-driven variation (downbeats only)": {"periodic_p": 0,"onset_mask_width": 0,"beat_mask_width": 50,"beat_mask_downbeats": True,},"beat-driven variation (downbeats only, strong)": {"periodic_p": 0,"onset_mask_width": 0,15 unmodified linesminimum=0,maximum=128,step=1,value=5,)onset_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",68 unmodified linestypical_mass,typical_min_tokens,beat_mask_width,beat_mask_downbeats,seed,# lora_choice,pitch_shift_amt,sample_cutoff}# connect widgets
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 lines484950515253545556575847 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","Interface.codec_ckpt": "./models/vampnet/codec.pth",47 unmodified lines48495051525354555647 unmodified lines}interface_conf = {"Interface.coarse_ckpt": f"./runs/{name}/coarse/latest/vampnet/weights.pth","Interface.coarse2fine_ckpt": f"./runs/{name}/c2f/latest/vampnet/weights.pth","Interface.wavebeat_ckpt": "./models/wavebeat.pth","Interface.codec_ckpt": "./models/vampnet/codec.pth",
13 unmodified lines141516171819208 unmodified lines293031323334566 unmodified lines6016026036046056066078 unmodified lines6166176186196206216226236246256266276288 unmodified lines63763863964064164213 unmodified linesfrom einops import rearrangefrom rich import prettyfrom rich.traceback import installfrom tensorboardX import SummaryWriterimport vampnetfrom vampnet.modules.transformer import VampNet8 unmodified linesimport loralib as lora# Enable cudnn autotuner to speed up training# (can be altered by the funcs.seed function)566 unmodified linesaccel=accel,tracker=tracker,save_path=save_path)train_dataloader = accel.prepare_dataloader(state.train_data,8 unmodified linesnum_workers=num_workers,batch_size=batch_size,collate_fn=state.val_data.collate,persistent_workers=True,)if fine_tune:lora.mark_only_lora_as_trainable(state.model)# Wrap the functions so that they neatly track in TensorBoard + progress bars# and only run when specific conditions are met.8 unmodified linessave_samples = when(lambda: accel.local_rank == 0)(save_samples)checkpoint = when(lambda: accel.local_rank == 0)(checkpoint)with tracker.live:for tracker.step, batch in enumerate(train_dataloader, start=tracker.step):train_loop(state, batch, accel)13 unmodified lines141516171819208 unmodified lines293031323334353637566 unmodified lines6046056066076086096108 unmodified lines6196206216226236246256266276286296306316326338 unmodified lines64264364464564664764813 unmodified linesfrom einops import rearrangefrom rich import prettyfrom rich.traceback import installfrom torch.utils.tensorboard import SummaryWriterimport vampnetfrom vampnet.modules.transformer import VampNet8 unmodified linesimport loralib as loraimport torch._dynamotorch._dynamo.config.verbose=True# Enable cudnn autotuner to speed up training# (can be altered by the funcs.seed function)566 unmodified linesaccel=accel,tracker=tracker,save_path=save_path)print("initialized state.")train_dataloader = accel.prepare_dataloader(state.train_data,8 unmodified linesnum_workers=num_workers,batch_size=batch_size,collate_fn=state.val_data.collate,persistent_workers=num_workers > 0,)print("initialized dataloader.")if fine_tune:lora.mark_only_lora_as_trainable(state.model)print("marked only lora as trainable.")# Wrap the functions so that they neatly track in TensorBoard + progress bars# and only run when specific conditions are met.8 unmodified linessave_samples = when(lambda: accel.local_rank == 0)(save_samples)checkpoint = when(lambda: accel.local_rank == 0)(checkpoint)print("starting training loop.")with tracker.live:for tracker.step, batch in enumerate(train_dataloader, start=tracker.step):train_loop(state, batch, accel)
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()12345678910111213141516171819202122232425262728293031323334from pathlib import Pathimport argbind
import audiotools as atimport tqdm
@argbind.bind(without_prefix=True)def split_long_audio_file( file: str = None, max_chunk_size_s: int = 60*10): file = Path(file) output_dir = file.parent / file.stem output_dir.mkdir() sig = at.AudioSignal(file)
# split into chunks for i, sig in tqdm.tqdm(enumerate(sig.windows( window_duration=max_chunk_size_s, hop_duration=max_chunk_size_s/2, preprocess=True)) ): sig.write(output_dir / f"{i}.wav")
print(f"wrote {len(list(output_dir.glob('*.wav')))} files to {output_dir}") return output_dir
if __name__ == "__main__": args = argbind.parse_args()
with argbind.scope(args): split_long_audio_file()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) continue27 unmodified lines28293031323334353637383927 unmodified linesinstall_requires=["torch","argbind>=0.3.2","numpy==1.22","wavebeat @ git+https://github.com/hugofloresgarcia/wavebeat","lac @ git+https://github.com/hugofloresgarcia/lac.git","descript-audiotools @ git+https://github.com/descriptinc/audiotools.git@0.7.2","gradio","tensorboardX","loralib",],)27 unmodified lines2829303132333435363738394027 unmodified linesinstall_requires=["torch","argbind>=0.3.2","numpy==1.23","wavebeat @ git+https://github.com/hugofloresgarcia/wavebeat","lac @ git+https://github.com/hugofloresgarcia/lac.git","descript-audiotools @ git+https://github.com/descriptinc/audiotools.git@0.7.2","gradio","loralib","torch_pitch_shift","madmom",],)
119 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 lines367368369370371372373374375376377378379380381205 unmodified lines58758858959059159259359459559659759859960060160260346 unmodified lines65065165265365465565619 unmodified lines676677678679680681682683684685153 unmodified lines8398408418428438448456 unmodified lines852853854855856857858366 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__(205 unmodified linesself,codec,time_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)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}")19 unmodified lineslogging.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}")153 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 lines367368369370371372205 unmodified lines57857958058158258358458558658758858959059159259359459546 unmodified lines64264364464564664719 unmodified lines667668669670671672673674675676677678679153 unmodified lines8338348358368378388398408418428436 unmodified lines850851852853854855856857366 unmodified linesreturn x, position_bias, encoder_decoder_position_biasclass TransformerStack(nn.Module):def __init__(205 unmodified linesself,codec,time_steps: int = 300,sampling_steps: int = 36,start_tokens: Optional[torch.Tensor] = None,sampling_temperature: float = 1.0,mask: Optional[torch.Tensor] = None,mask_temperature: float = 10.5,typical_filtering=False,typical_mass=0.2,typical_min_tokens=1,top_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}")19 unmodified lineslogging.debug(f"permuted logits with shape: {logits.shape}")sampled_z, selected_probs = sample_from_logits(logits, 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,)logging.debug(f"sampled z with shape: {sampled_z.shape}")153 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)
.gitignore-3
README.md+10-2
app.py+101-22
conf/lora/lora.yml+4-2
scripts/exp/fine_tune.py+2-4
scripts/exp/train.py+9-3
scripts/utils/augment.py+38-24
scripts/utils/remove_quiet_files.pyAdded+29
scripts/utils/split_long_audio_file.pyAdded+34
scripts/utils/xeno-canto-dl.pyAdded+234
setup.py+3-2
vampnet/interface.py+2-3
vampnet/mask.py+38-20
vampnet/modules/transformer.py+16-17