benjaminsshoffman commited on
Commit
b7a8ee2
Β·
verified Β·
1 Parent(s): b9f980c

Create README.md

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