open-perch 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
open_perch/__init__.py ADDED
@@ -0,0 +1,91 @@
1
+ """Faithful PyTorch reimplementation of the Perch v1 / v2 / SurfPerch encoders.
2
+
3
+ An independent, unofficial, best-effort port: not affiliated with or endorsed
4
+ by Google, and provided "as is" without warranty (Apache License 2.0, §7-8).
5
+
6
+ Quickstart::
7
+
8
+ from open_perch import load_audio, perch_v2
9
+
10
+ model = perch_v2(weights="DEFAULT") # downloads converted weights
11
+ audio = load_audio("recording.wav") # needs the [audio] extra
12
+ emb = model.embed_audio(audio, 32_000) # (n_windows, 1536)
13
+
14
+ ``load_perch("v2", weights="DEFAULT")`` is the same; ``load_perch(weights=
15
+ "perch_v2.pt")`` loads a file from ``open-perch convert`` and reads the
16
+ version from it.
17
+
18
+ Main entry points: :func:`perch_v1` / :func:`perch_v2` / :func:`surfperch`,
19
+ :func:`load_perch` and :class:`PerchWeights` (models and weights), :meth:`PerchModel.embed_audio` / :meth:`PerchModel.preprocess`
20
+ (Perch-equivalent preprocessing), :meth:`PerchModel.forward` (raw 5 s windows
21
+ at 32 kHz, for training) and :mod:`open_perch.audio`.
22
+
23
+ Original Perch authors:
24
+ v1: Ghani et al. 2023 (Sci Rep 13, 22876; doi:10.1038/s41598-023-49989-z)
25
+ v2: van Merrienboer et al. 2025 (arXiv:2508.04665)
26
+ SurfPerch: Williams et al. 2025 (Phil Trans R Soc B 380, 20240280;
27
+ doi:10.1098/rstb.2024.0280)
28
+
29
+ Source: https://github.com/google-research/perch (Apache-2.0).
30
+ This package ports the encoder + mel-spec frontend so the model can be
31
+ fine-tuned in PyTorch training pipelines, plus the audio preprocessing that
32
+ Perch's Python wrapper applies before the model (``open_perch.audio``).
33
+ Classification heads are not included.
34
+ """
35
+
36
+ from importlib.metadata import PackageNotFoundError, version
37
+
38
+ from open_perch.audio import (
39
+ PERCH_TARGET_PEAK,
40
+ ResampleMethod,
41
+ frame_audio,
42
+ load_audio,
43
+ normalize_audio,
44
+ resample,
45
+ )
46
+ from open_perch.backbone import EfficientNetBackbone
47
+ from open_perch.checkpoints import load_perch
48
+ from open_perch.config import (
49
+ PERCH_SURFPERCH_CONFIG,
50
+ PERCH_V1_CONFIG,
51
+ PERCH_V2_CONFIG,
52
+ FrontendConfig,
53
+ PerchConfig,
54
+ perch_config,
55
+ )
56
+ from open_perch.frontend import MelSpectrogramFrontend
57
+ from open_perch.hub import perch_v1, perch_v2, surfperch
58
+ from open_perch.model import PerchModel, PerchOutputs, PerchOutputsFull
59
+ from open_perch.weights import PerchWeights, Weights
60
+
61
+ try:
62
+ __version__ = version("open-perch")
63
+ except PackageNotFoundError: # not installed (e.g. running from a bare source tree)
64
+ __version__ = "0.0.0+unknown"
65
+
66
+ __all__ = [
67
+ "__version__",
68
+ "FrontendConfig",
69
+ "PerchConfig",
70
+ "PERCH_V1_CONFIG",
71
+ "PERCH_V2_CONFIG",
72
+ "PERCH_SURFPERCH_CONFIG",
73
+ "perch_config",
74
+ "MelSpectrogramFrontend",
75
+ "EfficientNetBackbone",
76
+ "PerchModel",
77
+ "PerchOutputs",
78
+ "PerchOutputsFull",
79
+ "load_perch",
80
+ "perch_v1",
81
+ "perch_v2",
82
+ "surfperch",
83
+ "PerchWeights",
84
+ "Weights",
85
+ "PERCH_TARGET_PEAK",
86
+ "ResampleMethod",
87
+ "load_audio",
88
+ "resample",
89
+ "frame_audio",
90
+ "normalize_audio",
91
+ ]
open_perch/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ """``python -m open_perch`` runs the ``open-perch`` command line."""
2
+
3
+ from open_perch.cli import main
4
+
5
+ raise SystemExit(main())
open_perch/audio.py ADDED
@@ -0,0 +1,310 @@
1
+ """Perch-faithful audio preprocessing.
2
+
3
+ The Perch SavedModels take fixed 5 s windows of 32 kHz audio, but what Perch
4
+ does to a recording *before* the SavedModel lives in perch-hoplite's Python
5
+ wrapper (``TaxonomyModelTF.batch_embed``), used for Perch v1, v2 and
6
+ SurfPerch alike:
7
+
8
+ 1. ``audio_io.load_audio_window_soundfile``: read with soundfile (float64),
9
+ keep the **first channel**, resample with
10
+ ``librosa.resample(res_type='polyphase')`` (= ``scipy.signal.resample_poly``),
11
+ cast to float32.
12
+ 2. ``EmbeddingModel.frame_audio``: clips shorter than one window are
13
+ **centre-padded**; then frame with ``librosa.util.frame``, which **drops
14
+ the trailing partial window**.
15
+ 3. ``EmbeddingModel.normalize_audio``: per window, subtract the mean (pad
16
+ zeros included), divide by the absolute peak and multiply by
17
+ ``target_peak=0.25``.
18
+
19
+ This module reproduces those steps in PyTorch: :func:`load_audio`,
20
+ :func:`resample`, :func:`frame_audio` and :func:`normalize_audio`.
21
+ :meth:`open_perch.PerchModel.preprocess` chains the last three.
22
+
23
+ Only torch is needed on the default path; soundfile (``[audio]`` extra) and
24
+ scipy (``[scipy]`` extra) are imported lazily, and librosa never.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import math
30
+ from functools import lru_cache
31
+ from pathlib import Path
32
+ from typing import Literal
33
+
34
+ import torch
35
+ from torch import Tensor
36
+ from torch.nn import functional as F
37
+
38
+ ResampleMethod = Literal["polyphase", "scipy", "torchaudio"]
39
+
40
+ # Peak normalisation target of perch-hoplite's ``TaxonomyModelTF``
41
+ # (perch_hoplite/zoo/taxonomy_model_tf.py): the dataclass default
42
+ # ``target_peak = 0.25``, also set by every preset loader (``load_version``,
43
+ # ``load_v2_version``, ``load_surfperch_version``).
44
+ PERCH_TARGET_PEAK = 0.25
45
+
46
+ # scipy.signal.resample_poly defaults: window=('kaiser', 5.0), and a
47
+ # half-length of 10 * max(up, down) taps.
48
+ _KAISER_BETA = 5.0
49
+ _HALF_LEN_FACTOR = 10
50
+
51
+
52
+ # ---------------------------------------------------------------------------
53
+ # Resampling
54
+ # ---------------------------------------------------------------------------
55
+
56
+
57
+ def _check_rate(name: str, rate: int) -> int:
58
+ if int(rate) != rate or rate <= 0:
59
+ raise ValueError(f"{name} must be a positive integer, got {rate!r}")
60
+ return int(rate)
61
+
62
+
63
+ def _compute_dtype(device: torch.device) -> torch.dtype:
64
+ # hoplite resamples in float64; MPS has no float64 support.
65
+ return torch.float32 if device.type == "mps" else torch.float64
66
+
67
+
68
+ @lru_cache(maxsize=16)
69
+ # The plan is cached across calls, so it must never be built from inference
70
+ # tensors: a first call under ``torch.inference_mode()`` would otherwise break
71
+ # every later autograd call on CPU, where ``.to()`` returns the cached tensor.
72
+ @torch.inference_mode(False)
73
+ def _polyphase_plan(up: int, down: int) -> tuple[int, int, tuple[tuple[int, Tensor], ...]]:
74
+ """Polyphase decomposition of scipy's ``resample_poly`` filter.
75
+
76
+ ``resample_poly`` computes ``upfirdn(h, x, up, down)`` and keeps
77
+ ``n_pre_remove .. n_pre_remove + n_out``. Folding its ``n_pre_pad`` /
78
+ ``n_pre_remove`` bookkeeping in (``n_pre_remove * down - n_pre_pad ==
79
+ half_len``), output sample ``n`` is the centred sum
80
+
81
+ y[n] = sum_i x[i] * h[n * down - i * up + half_len].
82
+
83
+ Splitting ``n = up * k + j`` turns each output phase ``j`` into a
84
+ stride-``down`` correlation of ``x`` with its own sub-filter, so the
85
+ whole resampler is a ``conv1d`` with ``up`` output channels whose outputs
86
+ are interleaved. Phase ``j`` reads input around ``k * down + d_j`` with
87
+ ``d_j = (j * down) // up``; to avoid a kernel ``~down`` taps wide for
88
+ every phase (mostly zeros when ``up`` is large, e.g. 44.1 -> 32 kHz has
89
+ up=320, down=441), consecutive phases are grouped into a few narrower
90
+ convolutions, each applied to the input shifted by its own offset.
91
+
92
+ Returns ``(pad_left, kernel_width_max, groups)``; ``groups`` holds
93
+ ``(offset, weight)`` pairs with ``weight`` of shape ``(n_phases, 1, K)``
94
+ (CPU, float64), in phase order.
95
+ """
96
+ max_rate = max(up, down)
97
+ half_len = _HALF_LEN_FACTOR * max_rate
98
+ num_taps = 2 * half_len + 1
99
+
100
+ # scipy.signal.firwin(num_taps, 1 / max_rate, window=('kaiser', 5.0)):
101
+ # windowed sinc normalised to unit DC gain; resample_poly then scales by up.
102
+ m = torch.arange(num_taps, dtype=torch.float64) - half_len
103
+ h = torch.sinc(m / max_rate) / max_rate
104
+ h = h * torch.kaiser_window(num_taps, periodic=False, beta=_KAISER_BETA, dtype=torch.float64)
105
+ h = h / h.sum() * up
106
+
107
+ phase = torch.arange(up)
108
+ phi = (phase * down) % up # position of the output within the up-grid
109
+ d = (phase * down) // up # input offset of phase j
110
+ # Sub-filter taps h[phi + half_len + m * up] exist for m in [m_lo, m_hi].
111
+ m_lo = -torch.div(half_len + phi, up, rounding_mode="floor")
112
+ m_hi = torch.div(half_len - phi, up, rounding_mode="floor")
113
+ pad_left = half_len // up # = max(m_hi - d), reached at j = 0
114
+ col_lo = d + pad_left - m_hi # first/last kernel column of phase j
115
+ col_hi = d + pad_left - m_lo
116
+
117
+ # Group size: let the spread of d within a group roughly equal the
118
+ # per-phase tap count, so each group's kernel is at most ~half zeros.
119
+ taps = int((m_hi - m_lo).max()) + 1
120
+ group = max(1, min(up, math.ceil(taps * up / down)))
121
+
122
+ groups = []
123
+ kernel_width_max = 0
124
+ for start in range(0, up, group):
125
+ sl = slice(start, min(start + group, up))
126
+ offset = int(col_lo[sl].min())
127
+ width = int(col_hi[sl].max()) - offset + 1
128
+ t = torch.arange(width) + offset # absolute column
129
+ idx = phi[sl, None] + half_len + (d[sl, None] + pad_left - t[None, :]) * up
130
+ valid = (idx >= 0) & (idx < num_taps)
131
+ weight = torch.where(valid, h[idx.clamp(0, num_taps - 1)], torch.zeros(()))
132
+ groups.append((offset, weight.unsqueeze(1).contiguous()))
133
+ kernel_width_max = max(kernel_width_max, offset + width)
134
+ return pad_left, kernel_width_max, tuple(groups)
135
+
136
+
137
+ def _resample_polyphase(x: Tensor, up: int, down: int) -> Tensor:
138
+ """``scipy.signal.resample_poly(x, up, down, axis=-1)`` in torch.
139
+
140
+ ``x``: ``(N, n)`` in the compute dtype. ``up``/``down`` coprime.
141
+ """
142
+ n = x.shape[-1]
143
+ n_out = -(-n * up // down) # ceil(n * up / down)
144
+ n_per_phase = -(-n_out // up)
145
+ pad_left, kernel_end, groups = _polyphase_plan(up, down)
146
+
147
+ # Zero padding ("constant" padtype): enough on the right for every group
148
+ # to produce n_per_phase outputs.
149
+ pad_right = max(0, (n_per_phase - 1) * down + kernel_end - (n + pad_left))
150
+ xp = F.pad(x.unsqueeze(1), (pad_left, pad_right)) # (N, 1, L)
151
+
152
+ outs = []
153
+ for offset, weight in groups:
154
+ w = weight.to(device=x.device, dtype=x.dtype)
155
+ y = F.conv1d(xp[..., offset:], w, stride=down) # (N, phases, >=k)
156
+ outs.append(y[..., :n_per_phase])
157
+ y = torch.cat(outs, dim=1) # (N, up, k)
158
+ return y.transpose(1, 2).reshape(x.shape[0], -1)[:, :n_out] # interleave phases
159
+
160
+
161
+ def resample(
162
+ audio: Tensor,
163
+ orig_sr: int,
164
+ target_sr: int,
165
+ method: ResampleMethod = "polyphase",
166
+ ) -> Tensor:
167
+ """Resample ``audio`` along its last axis from ``orig_sr`` to ``target_sr``.
168
+
169
+ Args:
170
+ audio: ``(..., samples)`` floating-point tensor.
171
+ orig_sr, target_sr: integer sample rates.
172
+ method:
173
+ * ``"polyphase"`` (default): pure-torch port of
174
+ ``scipy.signal.resample_poly`` (Kaiser window, beta 5, constant
175
+ padding), which is what Perch's wrapper uses via
176
+ ``librosa.resample(res_type='polyphase')``. Matches scipy to
177
+ float64 rounding (~1e-15 measured; the tests assert <= 1e-10),
178
+ runs on ``audio``'s device and is differentiable.
179
+ * ``"scipy"``: ``scipy.signal.resample_poly`` itself, on CPU numpy
180
+ (needs the ``[scipy]`` extra). The exact reference. Detaches:
181
+ no gradient flows back through it.
182
+ * ``"torchaudio"``: ``torchaudio.functional.resample``. A different
183
+ filter: **not** Perch-equivalent, offered for speed/compatibility.
184
+
185
+ Returns:
186
+ ``(..., ceil(samples * target_sr / orig_sr))`` tensor with ``audio``'s
187
+ dtype and device. Computation happens in float64 (float32 on MPS),
188
+ as in hoplite. If the rates are equal the input is returned unchanged.
189
+ """
190
+ orig_sr = _check_rate("orig_sr", orig_sr)
191
+ target_sr = _check_rate("target_sr", target_sr)
192
+ if method not in ("polyphase", "scipy", "torchaudio"):
193
+ raise ValueError(
194
+ f"Unknown resample method {method!r}; expected 'polyphase', 'scipy' or 'torchaudio'"
195
+ )
196
+ if not audio.is_floating_point():
197
+ raise TypeError(f"audio must be a floating-point tensor, got {audio.dtype}")
198
+ if audio.ndim < 1:
199
+ raise ValueError("audio must have at least one dimension (samples)")
200
+ if orig_sr == target_sr:
201
+ return audio
202
+
203
+ g = math.gcd(orig_sr, target_sr)
204
+ up, down = target_sr // g, orig_sr // g
205
+ lead, n = audio.shape[:-1], audio.shape[-1]
206
+ if n == 0: # as scipy: empty in, empty out
207
+ return audio.new_zeros((*lead, 0))
208
+ if lead.numel() == 0: # empty batch: as scipy, (*lead, ceil(n * up / down))
209
+ return audio.new_zeros((*lead, -(-n * up // down)))
210
+ work = audio.reshape(-1, n).to(_compute_dtype(audio.device))
211
+
212
+ if method == "polyphase":
213
+ out = _resample_polyphase(work, up, down)
214
+ elif method == "scipy":
215
+ try:
216
+ from scipy.signal import resample_poly
217
+ except ImportError as e:
218
+ raise ImportError(
219
+ "resample(method='scipy') needs scipy: pip install 'open-perch[scipy]'"
220
+ ) from e
221
+ y = resample_poly(work.detach().cpu().double().numpy(), up, down, axis=-1)
222
+ # Cast before moving: MPS has no float64.
223
+ out = torch.from_numpy(y).to(device=work.device, dtype=work.dtype)
224
+ else:
225
+ import torchaudio.functional as TAF
226
+
227
+ out = TAF.resample(work, orig_sr, target_sr)
228
+
229
+ return out.to(audio.dtype).reshape(*lead, out.shape[-1])
230
+
231
+
232
+ # ---------------------------------------------------------------------------
233
+ # Framing and normalisation
234
+ # ---------------------------------------------------------------------------
235
+
236
+
237
+ def frame_audio(audio: Tensor, window_samples: int, hop_samples: int) -> Tensor:
238
+ """Cut ``(..., samples)`` into ``(..., n_windows, window_samples)``.
239
+
240
+ Mirrors hoplite's ``EmbeddingModel.frame_audio``: a clip shorter than one
241
+ window is centre-padded with zeros (``librosa.util.pad_center``: left pad
242
+ ``(window - samples) // 2``, the rest on the right); otherwise windows
243
+ start every ``hop_samples`` and a trailing partial window is dropped
244
+ (``librosa.util.frame``). The result may be a view of ``audio``.
245
+ """
246
+ if window_samples <= 0 or hop_samples <= 0:
247
+ raise ValueError(
248
+ f"window_samples and hop_samples must be positive, got {window_samples}, {hop_samples}"
249
+ )
250
+ n = audio.shape[-1]
251
+ if n < window_samples:
252
+ left = (window_samples - n) // 2
253
+ audio = F.pad(audio, (left, window_samples - n - left))
254
+ return audio.unfold(-1, window_samples, hop_samples)
255
+
256
+
257
+ def normalize_audio(frames: Tensor, target_peak: float | None = PERCH_TARGET_PEAK) -> Tensor:
258
+ """Per-window mean removal and peak normalisation, as Perch's wrapper.
259
+
260
+ Mirrors hoplite's ``EmbeddingModel.normalize_audio``: subtract each
261
+ window's mean (over all of its samples, centre-padding zeros included),
262
+ divide by its absolute peak and multiply by ``target_peak``. Silent
263
+ windows come back as zeros (hoplite leaves them uninitialised).
264
+ ``target_peak=None`` returns ``frames`` unchanged.
265
+ """
266
+ if target_peak is None:
267
+ return frames
268
+ centred = frames - frames.mean(dim=-1, keepdim=True)
269
+ peak = centred.abs().amax(dim=-1, keepdim=True)
270
+ # Where peak == 0 every centred sample is 0, so dividing by 1 yields 0.
271
+ return centred / torch.where(peak > 0, peak, torch.ones_like(peak)) * target_peak
272
+
273
+
274
+ # ---------------------------------------------------------------------------
275
+ # File loading
276
+ # ---------------------------------------------------------------------------
277
+
278
+
279
+ def load_audio(
280
+ path: str | Path,
281
+ sample_rate: int = 32_000,
282
+ *,
283
+ resample_method: ResampleMethod = "polyphase",
284
+ ) -> Tensor:
285
+ """Load an audio file as Perch's wrapper does.
286
+
287
+ Mirrors hoplite's ``audio_io.load_audio_window_soundfile``: read with
288
+ soundfile as float64, keep the **first** channel (not the channel mean),
289
+ resample to ``sample_rate`` with :func:`resample` and cast to float32.
290
+ Needs the ``[audio]`` extra (soundfile).
291
+
292
+ Returns a 1-D float32 tensor of samples at ``sample_rate``.
293
+ """
294
+ try:
295
+ import soundfile
296
+ except ImportError as e:
297
+ raise ImportError("load_audio needs soundfile: pip install 'open-perch[audio]'") from e
298
+ data, sr = soundfile.read(str(path), dtype="float64", always_2d=True)
299
+ audio = torch.from_numpy(data[:, 0].copy())
300
+ return resample(audio, sr, sample_rate, method=resample_method).to(torch.float32)
301
+
302
+
303
+ __all__ = [
304
+ "PERCH_TARGET_PEAK",
305
+ "ResampleMethod",
306
+ "frame_audio",
307
+ "load_audio",
308
+ "normalize_audio",
309
+ "resample",
310
+ ]
open_perch/backbone.py ADDED
@@ -0,0 +1,207 @@
1
+ """EfficientNet backbone wrapper.
2
+
3
+ Uses timm's ``tf_efficientnet_b{1,3}`` variants, which match the
4
+ TensorFlow EfficientNet numerics that Perch was trained with:
5
+ * ``pad_type='same'`` -> Conv2dSame, emulating TF's asymmetric SAME padding
6
+ (except the stem, which Perch runs with VALID padding; patched below).
7
+ * SiLU/Swish activation in stem, MBConv blocks and head, plus drop_path
8
+ stochastic depth.
9
+ * ``bn_eps=1e-5``: Flax's ``nn.BatchNorm`` default, overriding timm's
10
+ tf_efficientnet default of 1e-3 (the TF Keras value).
11
+
12
+ We instantiate with ``in_chans=1`` and ``num_classes=0`` so the model takes a
13
+ single-channel (mel-spec) input and outputs the bare backbone -- no Perch
14
+ classification head is included (deferred).
15
+
16
+ A single timm model is used; intermediate stage outputs are captured via
17
+ forward hooks on each ``model.blocks[i]`` stage. This keeps weight sharing
18
+ between the pooled embedding and the per-stage feature maps automatic during
19
+ training.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ from dataclasses import dataclass
25
+ from typing import Any, cast
26
+
27
+ import timm
28
+ import torch
29
+ from torch import Tensor, nn
30
+
31
+ from open_perch.config import PerchConfig
32
+
33
+
34
+ @dataclass
35
+ class BackboneOutputs:
36
+ """Outputs of one :meth:`EfficientNetBackbone.forward` pass.
37
+
38
+ Attributes:
39
+ embedding: ``(B, D)`` global-average-pooled feature map.
40
+ spatial: ``(B, D, H, W)`` final feature map (after ``conv_head``).
41
+ stages: per-stage ``(B, C_i, H_i, W_i)`` maps (before ``conv_head``);
42
+ empty unless ``want_stages=True``.
43
+ """
44
+
45
+ embedding: Tensor # (B, D) global-avg-pooled
46
+ spatial: Tensor # (B, D, H, W) final feature map (post-conv_head)
47
+ stages: list[Tensor] # (B, C_i, H_i, W_i) per stage (pre-conv_head)
48
+
49
+
50
+ def _patch_stem_to_valid_padding(encoder: nn.Module) -> None:
51
+ """Replace timm's Conv2dSame stem with a plain Conv2d(padding=0).
52
+
53
+ chirp uses ``padding='VALID'`` for the stem conv, which produces an
54
+ output 1 pixel smaller per spatial dim than timm's SAME-padded stem on
55
+ the (500, 128) Perch mel-spec input.
56
+ """
57
+ old = encoder.conv_stem
58
+ new = nn.Conv2d(
59
+ old.in_channels,
60
+ old.out_channels,
61
+ kernel_size=old.kernel_size,
62
+ stride=old.stride,
63
+ padding=0,
64
+ bias=old.bias is not None,
65
+ )
66
+ if old.weight.shape != new.weight.shape:
67
+ raise RuntimeError(
68
+ f"stem weight shape changed: {old.weight.shape} -> {new.weight.shape}"
69
+ )
70
+ new.weight = old.weight
71
+ if old.bias is not None:
72
+ new.bias = old.bias
73
+ encoder.conv_stem = new
74
+
75
+
76
+ class EfficientNetBackbone(nn.Module):
77
+ """timm ``tf_efficientnet_b{1,3}`` exposing pooled, spatial and per-stage outputs.
78
+
79
+ Takes the frontend's ``(B, 1, T, F)`` spectrogram. Usually built for you
80
+ by :class:`~open_perch.PerchModel`.
81
+
82
+ Args:
83
+ cfg: model configuration (selects B1 or B3 via ``cfg.timm_model``).
84
+ in_chans: input channels (1 for a mel spectrogram).
85
+ drop_path_rate: stochastic-depth rate; defaults to ``cfg.drop_path_rate``.
86
+ """
87
+
88
+ def __init__(
89
+ self,
90
+ cfg: PerchConfig,
91
+ in_chans: int = 1,
92
+ drop_path_rate: float | None = None,
93
+ ):
94
+ super().__init__()
95
+ self.cfg = cfg
96
+ self.in_chans = in_chans
97
+ self.drop_path_rate: float = (
98
+ drop_path_rate if drop_path_rate is not None else cfg.drop_path_rate
99
+ )
100
+
101
+ # forward_features() returns the unpooled spatial map AFTER conv_head
102
+ # + bn2 -- this is the 1536-channel (B3) / 1280-channel (B1) feature
103
+ # map that Perch GAP-pools into the embedding.
104
+ self.encoder: nn.Module = timm.create_model(
105
+ cfg.timm_model,
106
+ pretrained=False,
107
+ in_chans=in_chans,
108
+ num_classes=0,
109
+ global_pool="",
110
+ drop_path_rate=self.drop_path_rate,
111
+ # Flax nn.BatchNorm default epsilon is 1e-5; timm tf_efficientnet
112
+ # variants default to 1e-3 (TF Keras default).
113
+ bn_eps=1e-5,
114
+ )
115
+
116
+ # chirp/models/efficientnet.py's OpSet.activation defaults to nn.relu
117
+ # in the open-source code, but the released checkpoints use SiLU in
118
+ # the MBConv blocks (verified by SavedModel parity), so timm's
119
+ # default activation is kept as-is.
120
+
121
+ # Perch's stem uses padding='VALID' (no padding) -- see
122
+ # chirp/models/efficientnet.py::Stem line ~176. timm's tf_efficientnet
123
+ # uses Conv2dSame for the stem (SAME padding). Swap the stem to a
124
+ # plain Conv2d(padding=0) so spatial alignment matches Perch. Weight
125
+ # shape (Cout, 1, 3, 3) is unchanged so the converted weights drop
126
+ # straight in.
127
+ _patch_stem_to_valid_padding(self.encoder)
128
+
129
+ if cfg.embedding_dim != self.encoder.num_features:
130
+ raise ValueError(
131
+ f"Configured embedding_dim={cfg.embedding_dim} disagrees with "
132
+ f"timm backbone num_features={self.encoder.num_features} for "
133
+ f"model={cfg.timm_model!r}"
134
+ )
135
+
136
+ # Per-stage outputs are captured by hooks on each model.blocks[i].
137
+ # timm stores EfficientNet stages as model.blocks: a Sequential of
138
+ # Sequentials, one per stage (7 stages for EfficientNet).
139
+ self._stage_cache: list[Tensor] = []
140
+ self._stage_hooks: list[torch.utils.hooks.RemovableHandle] = []
141
+ self._stages_enabled = False
142
+ # The hooks stay registered between calls; they only record while
143
+ # this is set (inside a want_stages=True forward).
144
+ self._capturing_stages = False
145
+
146
+ self.feature_info: list[dict[str, Any]] = cast(
147
+ list[dict[str, Any]], self.encoder.feature_info
148
+ )
149
+
150
+ @property
151
+ def embedding_dim(self) -> int:
152
+ """Size D of the pooled embedding."""
153
+ return int(self.encoder.num_features)
154
+
155
+ def _enable_stage_hooks(self) -> None:
156
+ if self._stages_enabled:
157
+ return
158
+ for stage in self.encoder.blocks:
159
+ handle = stage.register_forward_hook(self._stage_hook)
160
+ self._stage_hooks.append(handle)
161
+ self._stages_enabled = True
162
+
163
+ def _stage_hook(self, _module: nn.Module, _inp, output: Tensor) -> None:
164
+ if self._capturing_stages:
165
+ self._stage_cache.append(output)
166
+
167
+ def remove_stage_hooks(self) -> None:
168
+ """Detach the per-stage forward hooks installed by ``want_stages=True``."""
169
+ for h in self._stage_hooks:
170
+ h.remove()
171
+ self._stage_hooks.clear()
172
+ self._stages_enabled = False
173
+
174
+ def forward_spatial(self, x: Tensor) -> Tensor:
175
+ """(B, 1, T, F) -> (B, D, H, W) post-conv_head."""
176
+ return self.encoder.forward_features(x)
177
+
178
+ def forward_pooled(self, spatial: Tensor) -> Tensor:
179
+ """Global average pool: ``(B, D, H, W)`` -> ``(B, D)``."""
180
+ return spatial.mean(dim=(-2, -1))
181
+
182
+ def forward(self, x: Tensor, *, want_stages: bool = False) -> BackboneOutputs:
183
+ """Encode a ``(B, 1, T, F)`` spectrogram.
184
+
185
+ Args:
186
+ x: frontend output.
187
+ want_stages: also capture each EfficientNet stage's output.
188
+ """
189
+ stages: list[Tensor]
190
+ if want_stages:
191
+ self._enable_stage_hooks()
192
+ self._stage_cache = []
193
+ self._capturing_stages = True
194
+ try:
195
+ spatial = self.encoder.forward_features(x)
196
+ stages = self._stage_cache
197
+ finally:
198
+ self._capturing_stages = False
199
+ self._stage_cache = []
200
+ else:
201
+ spatial = self.encoder.forward_features(x)
202
+ stages = []
203
+ embedding = spatial.mean(dim=(-2, -1))
204
+ return BackboneOutputs(embedding=embedding, spatial=spatial, stages=stages)
205
+
206
+
207
+ __all__ = ["EfficientNetBackbone", "BackboneOutputs"]