benjaminsshoffman commited on
Commit
a7993a8
Β·
verified Β·
1 Parent(s): 9345ef5

Create README.md

Browse files
Files changed (1) hide show
  1. README.md +328 -0
README.md ADDED
@@ -0,0 +1,328 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: mit
3
+ language:
4
+ - en
5
+ tags:
6
+ - audio
7
+ - sound_event_detection
8
+ - bioacoustics
9
+ ---
10
+
11
+ # Sound Event Detection
12
+ Run using code available on [`Github`](https://github.com/earthspecies/sound-event-detection)
13
+
14
+ Pretrained sound event detection models focused on bioacoustics. Supports three main functions:
15
+
16
+ - Inference with pre-trained models: Within python, via a script, or via the large-scale inference (LSI) pipeline.
17
+ - Evaluation of model performance on detection datasets.
18
+ - Load pre-computed model detections for datasets like Xeno-Canto and iNaturalist.
19
+
20
+ ## Installation
21
+
22
+ Requires [`uv`](https://docs.astral.sh/uv/). Installation may take several minutes. GPU is not required but will improve speed.
23
+
24
+ Required packages are listed in `pyproject.toml`. To install them, run:
25
+
26
+ ```bash
27
+ uv sync --group gpu # omit --group gpu for CPU-only
28
+ ```
29
+
30
+ All commands run through `uv run`. It may be necessary to include `--group gpu` if using a GPU. Evaluation and LSI also need the dataset storage referenced by `configs/data/*.yml`.
31
+
32
+ Large-scale inference and using precomputed selection tables both require [`alp-data`](https://github.com/earthspecies/alp-data/), which is already included in `pyproject.toml`.
33
+
34
+ ## Quick start β€” BirdCODE over a folder of audio
35
+
36
+ Run the pretrained BirdCODE detector (loaded from the Hub) over every audio file in a folder β€” any sample rate, resampled to 32 kHz as needed β€” and write a selection table next to each recording: `dir/x.wav` β†’ `dir/BirdCODE_predictions/x.txt`. Currently supports wav, flac, ogg, and mp3.
37
+
38
+ ```bash
39
+ uv run sed-folder --folder /path/to/audio
40
+ ```
41
+
42
+ Two short demo recordings are provided. To run BirdCODE on them, do:
43
+
44
+ ```bash
45
+ uv run sed-folder --folder tests/samples/demo/audio
46
+ ```
47
+
48
+ This writes `tests/samples/demo/audio/BirdCODE_predictions/{20230730,20260623}.txt`, which should match the tables in `tests/samples/demo/output_expected/`. On CPU it takes roughly 1.5 minutes after the model weights (~1.1 GB) are downloaded.
49
+
50
+ Postprocessing is applied: By default, per-frame detections are thresholded at 0.5, boxes with the same label are merged if separated by less than 1 second, and non-maximal suppression is applied with an IoU threshold of 0.8. Geography filtering is off by default; enable it with `--geo-filter`, a directory of `*.gpkg` range maps, and the recording site's coordinates (applied to every file):
51
+
52
+ ```bash
53
+ uv run sed-folder --folder /path/to/audio \
54
+ --geo-filter --range-map-dir geography/range_maps \
55
+ --latitude 42.5 --longitude -72.2
56
+ ```
57
+
58
+ ## Official models
59
+
60
+ | Model | Publication | Checkpoint | Summary |
61
+ |---|---|---|---|
62
+ | BirdCODE | TODO | [EarthSpeciesProject/sed-birdcode](https://huggingface.co/EarthSpeciesProject/sed-birdcode) | Bird Communication Detector |
63
+
64
+ ## CLI entry points
65
+
66
+ | Command | Purpose | Assumes running |
67
+ |---|---|---|
68
+ | `sed-folder` | Run BirdCODE over a folder of audio β†’ selection tables | β€” (loads the model in-process) |
69
+ | `sed-server` | Serve a frame detector or sliding-window detector | backing classifier server (sliding-window only) |
70
+ | `sed-denoising-server` | Serve the denoising detector | a detector server + a separator server |
71
+ | `sed-eval` | Run an evaluation against a served model | a `sed-server` / `sed-denoising-server` server |
72
+ | `sed-lsi` | Large-scale inference over a dataset | a `sed-server` (`preds`) or `sed-denoising-server` (`denoised`/`stems`) server |
73
+ | `sed-lsi-postprocess` | Turn LSI predictions into selection tables | β€” (reads shards) |
74
+ | `sed-lsi-features` | Add per-event acoustic features to selection tables | β€” (reads shards) |
75
+
76
+ Every CLI has a `describe` subcommand that prints its config schema(s), e.g. `uv run sed-eval describe`.
77
+
78
+ ## Using BirdCODE in Python
79
+
80
+ `FrameDetector` loads a trained detector in-process, either from the HuggingFace Hub by repo id or from a checkpoint directory (local, `gs://…`, or `r2://…`):
81
+
82
+ ```python
83
+ from sound_event_detection.models import FrameDetector
84
+
85
+ # From the HuggingFace Hub (downloads the snapshot, then rebuilds the model);
86
+ birdcode = FrameDetector.from_hf_hub("EarthSpeciesProject/sed-birdcode").eval().to("cuda")
87
+
88
+ # Or from a checkpoint directory: weights from best_model.pt, labels from
89
+ # labels.txt, architecture from config.yaml.
90
+ ckpt = "checkpoints/birdcode_esp_research"
91
+ birdcode = FrameDetector.from_checkpoint_dir(ckpt, f"{ckpt}/config.yaml").to("cuda")
92
+
93
+ out = birdcode.run(audio, overlap=0.5) # audio: np.ndarray [batch, samples] at 32 kHz
94
+ out.predictions # [batch, time, classes] probabilities in [0, 1]
95
+ out.class_names # list[str] labels aligned to the classes axis
96
+ ```
97
+
98
+ ## Serving models
99
+
100
+ For large-scale inference and evaluation, we serve the model over HTTP, then point a client CLI at it via an http-client config.
101
+
102
+ A **model config** YAML tells the server what to load, dispatching on `type`. The unified server (`sed-server`) reads its path from the `SED_MODEL_CONFIG` environment variable.
103
+
104
+ ### Frame detectors β€” `type: frame`
105
+
106
+ Trained detectors (BirdCODE and ablations) loaded either from the HuggingFace Hub or from a local checkpoint directory. All current checkpoints run at 32 kHz.
107
+
108
+ Set `hf_repo_id` to download and serve a checkpoint from the Hub β€” this is how the example config loads BirdCODE. An optional `revision` pins a branch, tag, or commit (defaults to the repo's default branch):
109
+
110
+ ```yaml
111
+ type: frame
112
+ hf_repo_id: EarthSpeciesProject/sed-birdcode
113
+ # revision: main # optional
114
+ ```
115
+
116
+ Alternatively, `model_folder` serves a local checkpoint directory (expects `config.yaml`, `best_model.pt`, and `labels.txt`).
117
+
118
+ Serve either config the same way:
119
+
120
+ ```bash
121
+ SED_MODEL_CONFIG=configs/birdcode/models/birdcode_esp_research.yml \
122
+ uv run sed-server --host 0.0.0.0 --port 8100
123
+ ```
124
+
125
+ `sed-server` accepts `--host` (default `localhost`), `--port` (default `8100`), `--workers`, `--reload`, and `--log-level`. `SED_DEVICE=cpu|cuda` selects the device (default: cuda if available).
126
+
127
+ Ablation checkpoints use the same `type: frame` shape:
128
+ `configs/birdcode/models/ablations/`.
129
+
130
+ ### Sliding-window detectors β€” `type: perch2 | audioprotopnet | beats_sl_all`
131
+
132
+ Clip classifiers wrapped in a `SlidingWindowDetector` to produce frame-level predictions. Each needs a **backing classifier server** already running, discovered through `addr_file` (a text file containing `host:port`):
133
+
134
+ ```yaml
135
+ type: audioprotopnet
136
+ addr_file: ~/audioprotopnet-server/server.addr
137
+ window_size: 5.0 # seconds
138
+ hop_size: 2.0 # seconds
139
+ analysis_window: 2.0 # optional; defaults to window_size
140
+ ```
141
+
142
+ | Type | Backing server | Sample rate |
143
+ |---|---|---|
144
+ | `perch2` | [earthspecies/perch2-server](https://github.com/earthspecies/perch2-server) | 32 kHz |
145
+ | `audioprotopnet` | [earthspecies/audioprotopnet-server](https://github.com/earthspecies/audioprotopnet-server) | 32 kHz |
146
+ | `beats_sl_all` | in-repo (below) | 16 kHz |
147
+
148
+ The external servers write their own `server.addr`; point the config's `addr_file` at it. Serve the wrapper the same way as a frame detector:
149
+
150
+ ```bash
151
+ SED_MODEL_CONFIG=configs/birdcode/models/baselines/audioprotopnet_2s.yml \
152
+ uv run sed-server --port 8100
153
+ ```
154
+
155
+ `beats_sl_all` runs at 16 kHz β€” evaluate it with `frame_eval_16k.yml` (frame detection) or `birdset_clip_eval_16k.yml` (clip classification). Its backing classifier is served in-repo:
156
+
157
+ ```bash
158
+ # 1. backing classifier (16 kHz), then record its host:port
159
+ SED_DEVICE=cuda uv run uvicorn \
160
+ sound_event_detection.serving.sl_beats_all_server:app --host 0.0.0.0 --port 8200
161
+ echo "HOST:8200" > .server_addrs/beats_sl_all.addr # path the config's addr_file points at
162
+
163
+ # 2. the sliding-window wrapper
164
+ SED_MODEL_CONFIG=configs/birdcode/models/baselines/beats_sl_all_2s.yml \
165
+ uv run sed-server --port 8100
166
+ ```
167
+
168
+ ### Denoising detector β€” `type: denoising_detector`
169
+
170
+ NOTE: This requires a separator server to be running. Separator server code will be provided at a later date.
171
+
172
+ Wraps a detector client and a source-separator client, adding `POST /separate_and_detect` (used by LSI) to the standard contract. Both backing servers must be up when it starts. Its model config names them as pure http-client configs:
173
+
174
+ ```yaml
175
+ type: denoising_detector
176
+ detector: {url: http://localhost:8100, timeout: 300} # a sed-server detector server
177
+ separator: {url: http://localhost:8200, timeout: 300} # a separator server
178
+ threshold: 0.5
179
+ resampling_method: torchaudio_kaiser_fast
180
+ ```
181
+
182
+ ```bash
183
+ # with a detector server and a separator server already running:
184
+ SED_MODEL_CONFIG=configs/birdcode/models/denoising_detector.yml \
185
+ uv run sed-denoising-server --host 0.0.0.0 --port 8110
186
+ ```
187
+
188
+ `sed-denoising-server` takes the same options as `sed-server` (default port `8110`).
189
+
190
+ ### HTTP contract
191
+
192
+ - `GET /` β€” model metadata: `{labels, sample_rate, frame_rate, window_duration}`
193
+ - `GET /health` β€” `{status: "ok"}` once the model is loaded
194
+ - `GET /labels` β€” ordered label list
195
+ - `POST /run` β€” frame-level inference; response `{predictions, shape [batch, time, classes], frame_rate}`
196
+ - `POST /run_as_classifier` β€” clip-level pooled inference; response shape `[batch, classes]`
197
+ - `POST /separate_and_detect` β€” denoising server only; per-stem audio + predictions
198
+
199
+ ## Evaluation β€” `sed-eval`
200
+
201
+ Serve a model, then run `sed-eval` against it with an **eval config** (*what* to evaluate) and an **http-client config** (*how* to reach the model β€” a `url` plus optional `timeout`/`retries`/`auth`; the client kind is auto-detected from the server).
202
+
203
+ ```bash
204
+ # write an http-client config pointing at the running server, e.g.:
205
+ # url: http://HOST:8100
206
+ uv run sed-eval --eval-config configs/birdcode/frame_eval.yml \
207
+ --httpclient-config configs/birdcode/httpclient.yml \
208
+ [--checkpoint-dir <dir>] [--output-dir <dir>]
209
+ ```
210
+
211
+ - `--checkpoint-dir` β€” resumable checkpoint directory (auto-generated under `checkpoints/sed/` if omitted).
212
+ - `--output-dir` β€” override the eval config's `output_dir`.
213
+ - `sed-eval --resume <checkpoint-dir>` β€” resume a run; configs are reloaded from the checkpoint.
214
+
215
+ ### Eval configs
216
+
217
+ | Config | Pathway | Datasets | Sample rate |
218
+ |---|---|---|---|
219
+ | `configs/birdcode/frame_eval.yml` | frame (detection) | 68 WABAD sites + Powdermill + XC-AJ | 32 kHz |
220
+ | `configs/birdcode/birdset_clip_eval.yml` | clip (classification) | 8 BirdSet test splits | 32 kHz |
221
+
222
+ An eval config selects the pathway through its dataset lists: `frame_datasets` (strong labels, with `species_column`) go through detection; `clip_datasets` (weak labels) through classification.
223
+
224
+ ### Metrics
225
+
226
+ - **Frame pathway**: frame mAP, event mAP per IoU threshold, thresholded precision/recall/F1.
227
+ - **Clip pathway**: cmAP (headline), cmAP5, mAP, pcmAP, MultilabelAUROC, top-1/top-3 accuracy, per-class AP, and `gt_coverage`.
228
+
229
+ ### Results
230
+
231
+ Each eval run writes `<output_dir>/results.yaml`, updated after every dataset:
232
+
233
+ - `model` β€” the served model's metadata (`GET /` response)
234
+ - `frame_eval` β€” the scoring parameters used
235
+ - `frame_datasets.<name>` β€” per-dataset detection metrics
236
+ - `clip_datasets.<name>` β€” per-dataset classification metrics
237
+
238
+ ## Large-scale inference (LSI)
239
+
240
+ Run a served detector over a dataset, persist per-recording results as compressed `.npz` shards, then postprocess (and optionally enrich) them into selection tables. Three stages: **run β†’ postprocess β†’ features**. Each stage takes `--job-index N --num-jobs M` to split the work across an array of parallel jobs, and writes a `lineage.yaml` chaining back to the stage that produced its input.
241
+
242
+ The LSI configs (`configs/inference/lsi_birdcode_*.yml`) run the BirdCODE frame detector over the full Xeno-Canto and iNaturalist training splits; they read their datasets from `configs/data/inference/`.
243
+
244
+ ### Run β€” `sed-lsi`
245
+
246
+ Builds a dataset from a **run config** (*what* to run) and a detector client from an **http-client config** (*how* to reach the model), then runs the sharded engine over this job's slice.
247
+
248
+ ```bash
249
+ # with the appropriate server running (see below):
250
+ uv run sed-lsi --run-config configs/inference/lsi_birdcode_xc.yml \
251
+ --httpclient-config <httpclient.yml> [--job-index N --num-jobs M] [--output-dir DIR]
252
+ ```
253
+
254
+ The run config's `output.detail` selects what is stored per recording β€” and which server the `url` must reach:
255
+
256
+ | `detail` | Stored | Server |
257
+ |---|---|---|
258
+ | `preds` | combined framewise predictions | a `sed-server` detector server |
259
+ | `denoised` | predictions + a threshold-gated denoised waveform | a `sed-denoising-server` server |
260
+ | `stems` | the above + every separated stem (audio + preds) | a `sed-denoising-server` server |
261
+
262
+ ### Postprocess β€” `sed-lsi-postprocess`
263
+
264
+ Reads the combined predictions in each shard and writes a per-recording selection table (1:1 with the input shards). Re-postprocessing is a cheap re-run into a sibling directory.
265
+
266
+ ```bash
267
+ uv run sed-lsi-postprocess --config configs/inference/lsi_birdcode_xc_postprocess.yml \
268
+ --run-dir <run_dir> [--job-index N --num-jobs M]
269
+ ```
270
+
271
+ `--run-dir` overrides the config's `input.run_dir` (postprocess several runs
272
+ with one config).
273
+
274
+ #### Geography filtering
275
+
276
+ Setting `postprocessing.geo_filter: true` drops detections for species whose range maps exclude a recording's location (using the latitude/longitude stored in each shard). It requires `postprocessing.range_map_dir` β€” a directory (local path or cloud URI) of `*.gpkg` range-map files, globbed at startup and checked to exist before any shards are processed:
277
+
278
+ ```yaml
279
+ postprocessing:
280
+ geo_filter: true
281
+ range_map_dir: geography/range_maps # dir of *.gpkg range maps
282
+ ```
283
+
284
+ To use geography filtering, download the open range-map dataset from iNaturalist (<https://www.inaturalist.org/pages/range_maps>) into `range_map_dir`. Each range map's species `name` is resolved to a GBIF canonical name to match the detector's labels. The filter fails open: a detection is dropped only on positive out-of-range evidence (valid coordinates **and** a range map that excludes the point); recordings without coordinates, or species without a range map, are left untouched.
285
+
286
+ ### Features β€” `sed-lsi-features`
287
+
288
+ Enriches a postprocessed selection table with per-event `v0minimal` acoustic features. Writes enriched selection tables 1:1 with the postprocess shards.
289
+
290
+ ```bash
291
+ uv run sed-lsi-features --config configs/inference/lsi_birdcode_xc_features.yml \
292
+ --run-dir <run_dir> --postprocessing postprocessed_thr0.50_merge1.00_nms0.80_geo \
293
+ [--job-index N --num-jobs M]
294
+ ```
295
+
296
+ ## Loading a dataset with attached selection tables (Python)
297
+
298
+ Public GCS buckets hold BirdCODE detections as selection tables for a subset of **Xeno-Canto** and **iNaturalist** recordings. Two data configs load each corpus with those tables attached via the `attach_lsi_selection_tables` transform:
299
+
300
+ - `configs/data/inference/xeno_canto_selection_tables.yml`
301
+ - `configs/data/inference/inaturalist_selection_tables.yml`
302
+
303
+ Load either with `alp_data.dataset_from_config`, importing the transforms module first so the custom transform is registered:
304
+
305
+ ```python
306
+ import io
307
+ import pandas as pd
308
+ from alp_data import dataset_from_config
309
+ import sound_event_detection.data.transforms # noqa: F401 β€” registers attach_lsi_selection_tables
310
+
311
+ dataset, meta = dataset_from_config("configs/data/inference/xeno_canto_selection_tables.yml")
312
+ print(meta["attach_lsi_selection_tables"]) # {'matched': ..., 'unmatched': ...}
313
+
314
+ # The attached `selection_table` column lives on the metadata backend
315
+ # (`dataset._data`), so you can read it without decoding audio. It is a TSV
316
+ # string (empty for unmatched rows); parse it into a DataFrame of events:
317
+ for row in dataset._data:
318
+ if row["selection_table"]:
319
+ events = pd.read_csv(io.StringIO(row["selection_table"]), sep="\t")
320
+ break
321
+ ```
322
+
323
+ Each row of a parsed `selection_table` is one detection event, with columns:
324
+
325
+ - `Begin Time (s)`, `End Time (s)` β€” the event's span within the recording
326
+ - `Species` β€” predicted class label
327
+ - `Score` β€” mean BirdCODE probability over the event
328
+ - 13 `v0minimal` acoustic-feature columns (see `sound_event_detection.inference.features_v0minimal.FEATURE_COLS`)