postpop commited on
Commit
fb3c11b
·
verified ·
1 Parent(s): de02487

Add embedding-only perch2-torch (torch.export .pt2) and perch2_embed.py helper

Browse files
Files changed (4) hide show
  1. .gitattributes +1 -0
  2. README.md +133 -0
  3. perch2_embed.py +75 -0
  4. perch_v2_embed.pt2 +3 -0
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ perch_v2_embed.pt2 filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ library_name: pytorch
4
+ pipeline_tag: feature-extraction
5
+ base_model:
6
+ - DAS-DeepAudioSegmenter/perch2-torch
7
+ tags:
8
+ - audio
9
+ - bioacoustics
10
+ - embeddings
11
+ - torch-export
12
+ - das
13
+ ---
14
+
15
+ # PERCH 2 embeddings (PyTorch, embedding only)
16
+
17
+ The PERCH 2 embedding network from [perch2-torch](https://huggingface.co/DAS-DeepAudioSegmenter/perch2-torch) as a
18
+ single self-contained `torch.export` file. The 14,795-class label head is left out, so the file holds just the waveform
19
+ frontend and EfficientNet-B3 backbone: 10.7 M instead of 101.7 M parameters, and 47.6 MB instead of 408 MB. For class
20
+ logits, use [perch2-torch](https://huggingface.co/DAS-DeepAudioSegmenter/perch2-torch).
21
+
22
+ ## Use the model file
23
+
24
+ `perch_v2_embed.pt2` takes a batch of 5 s mono windows at 32 kHz, `(batch, 160000)` with batch 1-4096, and returns
25
+ the unpooled spatial embedding `(batch, 16, 4, 1536)`: 16 time frames and 4 frequency positions per window.
26
+
27
+ ```python
28
+ import torch
29
+ from huggingface_hub import hf_hub_download
30
+ from torch.export.passes import move_to_device_pass
31
+
32
+ path = hf_hub_download("DAS-DeepAudioSegmenter/perch2-torch-embed", "perch_v2_embed.pt2")
33
+ core = move_to_device_pass(torch.export.load(path), "cpu").module() # or "cuda" / "mps"
34
+
35
+ windows = torch.zeros(2, 160_000) # two 5 s windows of 32 kHz audio
36
+ spatial = core(windows) # (2, 16, 4, 1536)
37
+ embedding = spatial.mean(dim=(1, 2)) # (2, 1536), one embedding per window
38
+ ```
39
+
40
+ Requires PyTorch >= 2.11. `torch.export` files load in the version they were exported with or newer; tested with 2.11
41
+ and 2.14.
42
+
43
+ ## Limitations of the model file on its own
44
+
45
+ - **Fixed 5 s input.** Each window must be exactly 160,000 samples. Shorter audio has to be zero-padded, and longer
46
+ audio cut into windows by you.
47
+ - **32 kHz assumed.** The model does not resample; whatever you pass is treated as 32 kHz audio.
48
+ - **Per-window output only.** You get unpooled frames for each window. There is no song-level average or maximum, and
49
+ no continuous time axis across overlapping windows, which needs the overlap frames trimmed and averaged.
50
+ - **Memory.** All windows passed in one call (up to 4,096) are processed at once, so long recordings have to be split
51
+ into batches.
52
+
53
+ ## Alternative: `perch2_embed.py` for audio of any length
54
+
55
+ `perch2_embed.py` handles all of the above: windowing, padding, batching, overlap pooling and truncation. It needs only
56
+ torch and huggingface_hub.
57
+
58
+ ```bash
59
+ pip install torch huggingface_hub soundfile
60
+ hf download DAS-DeepAudioSegmenter/perch2-torch-embed perch2_embed.py --local-dir .
61
+ ```
62
+
63
+ ```python
64
+ import soundfile as sf
65
+ from perch2_embed import load, embed
66
+
67
+ core = load("auto") # downloads and caches perch_v2_embed.pt2
68
+ wave, sr = sf.read("song.wav", dtype="float32") # the model assumes 32 kHz: resample first for normal speed
69
+ out = embed(core, wave if wave.ndim == 1 else wave.mean(axis=1), sample_rate=sr)
70
+ out["avg"].shape, out["max"].shape, out["temporal"].shape # (1536,), (1536,), (frames, 1536)
71
+ ```
72
+
73
+ ### Options
74
+
75
+ `load(device="cpu", path=None, revision=None)`
76
+ - `device`: `"cpu"`, `"cuda"`, `"mps"`, or `"auto"` (CUDA, then MPS, then CPU).
77
+ - `path`: a local copy of `perch_v2_embed.pt2`; otherwise it is downloaded from this repo and cached.
78
+ - `revision`: a repo revision to pin the downloaded file.
79
+
80
+ `embed(core, wave, hop_frames=1, max_seconds=None, sample_rate=32000, batch_size=32)`
81
+ - `wave`: mono 1-D float array or tensor of any length, fed to the model unchanged (treated as 32 kHz).
82
+ - `hop_frames`: window hop in 0.32 s frames, 1-15. `1` is the model's own hop and reproduces the full perch2-torch
83
+ model; larger values compute fewer windows (see below).
84
+ - `max_seconds`: keep only the first `max_seconds` of audio. `None` embeds everything.
85
+ - `sample_rate`: the rate at which `wave` was sampled. Nothing is resampled: it only converts `max_seconds` to samples
86
+ and frame positions to seconds in `times`.
87
+ - `batch_size`: 5 s windows per forward pass, which sets memory use.
88
+
89
+ ### Returns
90
+
91
+ A dict with:
92
+ - `avg` `(1536,)`: the same as the full model's `embedding` output;
93
+ - `max` `(1536,)`: the maximum over the same overlap-trimmed frames (the full model does not output this);
94
+ - `temporal` `(frames, 1536)`: stitched frames 0.32 s apart in model time, averaged over the 4 frequency positions;
95
+ - `spatial` `(frames, 4, 1536)`: the same frames with the frequency positions kept;
96
+ - `times` `(frames,)`: frame centres in seconds;
97
+ - `n_windows`: the number of 5 s windows computed.
98
+
99
+ ### Notes
100
+
101
+ - The model always treats its input as 32,000 samples per second, so the sample rate of `wave` sets the playback
102
+ speed the model hears. Audio at 32 kHz is heard at normal speed. Audio at a higher rate fed unchanged is slowed
103
+ down and lowered in pitch by `sample_rate / 32000`. For example, a recording resampled to 64 kHz (e.g.
104
+ `librosa.load(path, sr=64000)`) and fed unchanged is heard at half speed and half pitch, and a 44.1 kHz file read
105
+ as is plays at 0.73x speed. Windows, hops and frames are fixed in samples: one 5 s window covers 160,000 / sample_rate
106
+ seconds of your audio and frames are 10,240 / sample_rate seconds apart (0.32 s at 32 kHz, 0.16 s at 64 kHz). Pass the
107
+ true `sample_rate` so that `max_seconds` and `times` are in seconds of the original audio.
108
+ - `hop_frames > 1` computes fewer windows, but the embeddings change. On 75 bird songs of 8 s or longer (audio loaded at
109
+ 64 kHz), cosine similarity to the default hop was:
110
+
111
+ | hop | windows computed | avg: median (worst) | max: median (worst) |
112
+ |---|---|---|---|
113
+ | 2 (0.64 s) | 52% | 0.993 (0.889) | 0.978 (0.930) |
114
+ | 4 (1.28 s) | 28% | 0.989 (0.888) | 0.982 (0.937) |
115
+ | 8 (2.56 s) | 15% | 0.977 (0.879) | 0.983 (0.938) |
116
+ | 15 (4.8 s) | 10% | 0.955 (0.840) | 0.969 (0.862) |
117
+
118
+ Use the same hop for everything you compare.
119
+
120
+ ## Verification
121
+
122
+ Against perch2-torch (revision `d5d3bb6a`):
123
+ - the core matches the full model's frontend and backbone: CPU difference <= 4e-6, MPS relative difference 2.4e-6;
124
+ - `embed()` at the default hop matches the full model's windowing and pooling for inputs of 1 to 361 windows (avg
125
+ within 3e-7, max and temporal within 1e-5), and `avg` equals the full model's `embedding` within 3e-7;
126
+ - truncation equals embedding the pre-cut audio;
127
+ - PyTorch 2.14 loads the file with timm unavailable and gives identical output.
128
+
129
+ ## Attribution and license
130
+
131
+ Exported from [perch2-torch](https://huggingface.co/DAS-DeepAudioSegmenter/perch2-torch), which is derived from the
132
+ Apache-2.0 [PERCH ONNX model](https://huggingface.co/justinchuby/Perch-onnx) and the Apache-2.0
133
+ [wrice EfficientNet-B3 checkpoint](https://huggingface.co/wrice/perch-v2-efficientnet-b3). Apache-2.0.
perch2_embed.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """PERCH 2 embeddings for audio of any length, using perch_v2_embed.pt2 (needs only torch and huggingface_hub).
2
+
3
+ from perch2_embed import load, embed
4
+ core = load("cpu") # or "cuda", "mps", "auto"
5
+ out = embed(core, wave) # mono float waveform at 32 kHz
6
+ out["avg"], out["max"], out["temporal"], out["times"]
7
+ """
8
+ import math
9
+
10
+ import torch
11
+
12
+ REPO, FILE = "DAS-DeepAudioSegmenter/perch2-torch-embed", "perch_v2_embed.pt2"
13
+ WINDOW, FRAME = 160_000, 10_240 # 5 s window and 0.32 s frame step, in samples at the 32 kHz model rate
14
+
15
+
16
+ def load(device="cpu", path=None, revision=None):
17
+ """Load the embedding core onto a device ("cpu", "cuda", "mps" or "auto"). Downloads and caches the file unless
18
+ `path` points to a local copy."""
19
+ from torch.export.passes import move_to_device_pass
20
+ if path is None:
21
+ from huggingface_hub import hf_hub_download
22
+ path = hf_hub_download(REPO, FILE, revision=revision)
23
+ if device == "auto":
24
+ device = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"
25
+ return move_to_device_pass(torch.export.load(path), device).module()
26
+
27
+
28
+ def embed(core, wave, hop_frames=1, max_seconds=None, sample_rate=32_000, batch_size=32):
29
+ """Embed a mono waveform of any length with the perch_v2_embed.pt2 core.
30
+
31
+ wave 1-D float array or tensor. It is fed to the model unchanged, i.e. treated as 32 kHz audio.
32
+ hop_frames window hop in 0.32 s frames, 1-15 (1 = the model's own 0.32 s hop; larger = fewer windows).
33
+ max_seconds keep only the first max_seconds of audio (None = everything).
34
+ sample_rate rate of `wave`; used only to convert max_seconds and the returned times to seconds.
35
+ batch_size 5 s windows per forward pass (memory use).
36
+
37
+ Returns a dict with avg (1536,), max (1536,), temporal (frames, 1536) (mean over the 4 frequency positions),
38
+ spatial (frames, 4, 1536), times (frames,) frame centres in seconds, and n_windows.
39
+ """
40
+ if not 1 <= hop_frames <= 15:
41
+ raise ValueError("hop_frames must be 1-15: windows must overlap or touch")
42
+ wave = torch.as_tensor(wave, dtype=torch.float32).flatten()
43
+ if max_seconds is not None:
44
+ wave = wave[: int(max_seconds * sample_rate)]
45
+ length, hop = len(wave), hop_frames * FRAME
46
+ if length == 0:
47
+ raise ValueError("empty waveform")
48
+ n = math.ceil(max(length - WINDOW, 0) / hop) + 1
49
+ windows = torch.nn.functional.pad(wave, (0, (n - 1) * hop + WINDOW - length)).unfold(0, WINDOW, hop)
50
+ device = next(core.parameters()).device
51
+ with torch.inference_mode():
52
+ chunks = torch.cat([core(windows[i:i + batch_size].to(device)).float().cpu() for i in range(0, n, batch_size)])
53
+ # Overlap pooling. At hop_frames=1 this uses the full model's rule: windows after the third drop their first
54
+ # 2 frames and all but the last two drop their last 2. At larger hops every overlapping frame is averaged.
55
+ n_time = chunks.shape[1]
56
+ total = (n - 1) * hop_frames + n_time
57
+ sums, counts = chunks.new_zeros(total, *chunks.shape[2:]), chunks.new_zeros(total)
58
+ maximum = torch.full(chunks.shape[3:], -torch.inf)
59
+ trim = 2 if hop_frames == 1 else 0
60
+ for i in range(n):
61
+ lo = trim if i > 2 else 0
62
+ hi = n_time - trim if i < n - 2 else n_time
63
+ part, start = chunks[i, lo:hi], i * hop_frames
64
+ sums[start + lo:start + hi] += part
65
+ counts[start + lo:start + hi] += 1
66
+ maximum = torch.maximum(maximum, part.amax(dim=(0, 1)))
67
+ avg = sums.sum(dim=(0, 1)) / (counts.sum() * chunks.shape[2])
68
+ spatial = sums / counts.clamp_min(1)[:, None, None]
69
+ centers = (torch.arange(total) + 0.5) * FRAME
70
+ keep = centers < length
71
+ if not keep.any(): # audio shorter than half a frame: one frame, centred on the audio
72
+ keep[0] = True
73
+ centers[0] = length / 2
74
+ return {"avg": avg, "max": maximum, "temporal": spatial[keep].mean(dim=1), "spatial": spatial[keep],
75
+ "times": centers[keep] / sample_rate, "n_windows": n}
perch_v2_embed.pt2 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:57955a2fdef96bfe7a163b3a08f5763ad2f1c16b291078cea8c16e5ac05e2bb4
3
+ size 47595286