audiosetfit 0.1.0__tar.gz
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.
- audiosetfit-0.1.0/LICENSE +201 -0
- audiosetfit-0.1.0/PKG-INFO +311 -0
- audiosetfit-0.1.0/README.md +268 -0
- audiosetfit-0.1.0/pyproject.toml +62 -0
- audiosetfit-0.1.0/setup.cfg +4 -0
- audiosetfit-0.1.0/src/audiosetfit/__init__.py +42 -0
- audiosetfit-0.1.0/src/audiosetfit/data.py +93 -0
- audiosetfit-0.1.0/src/audiosetfit/encoders.py +295 -0
- audiosetfit-0.1.0/src/audiosetfit/losses.py +64 -0
- audiosetfit-0.1.0/src/audiosetfit/modeling.py +345 -0
- audiosetfit-0.1.0/src/audiosetfit/py.typed +0 -0
- audiosetfit-0.1.0/src/audiosetfit/sampler.py +128 -0
- audiosetfit-0.1.0/src/audiosetfit/trainer.py +284 -0
- audiosetfit-0.1.0/src/audiosetfit/training_args.py +61 -0
- audiosetfit-0.1.0/src/audiosetfit.egg-info/PKG-INFO +311 -0
- audiosetfit-0.1.0/src/audiosetfit.egg-info/SOURCES.txt +17 -0
- audiosetfit-0.1.0/src/audiosetfit.egg-info/dependency_links.txt +1 -0
- audiosetfit-0.1.0/src/audiosetfit.egg-info/requires.txt +16 -0
- audiosetfit-0.1.0/src/audiosetfit.egg-info/top_level.txt +1 -0
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or Derivative
|
|
95
|
+
Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work, excluding
|
|
103
|
+
those notices that do not pertain to any part of the Derivative
|
|
104
|
+
Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and do
|
|
117
|
+
not modify the License. You may add Your own attribution notices
|
|
118
|
+
within Derivative Works that You distribute, alongside or as an
|
|
119
|
+
addendum to the NOTICE text from the Work, provided that such
|
|
120
|
+
additional attribution notices cannot be construed as modifying
|
|
121
|
+
the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2026 AudioSetFit contributors
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1,311 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: audiosetfit
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Efficient few-shot audio classification with contrastive fine-tuning (a SetFit for audio).
|
|
5
|
+
Author: Ilja Baumann
|
|
6
|
+
License: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/iljab/audiosetfit
|
|
8
|
+
Project-URL: Repository, https://github.com/iljab/audiosetfit
|
|
9
|
+
Project-URL: Issues, https://github.com/iljab/audiosetfit/issues
|
|
10
|
+
Keywords: audio,speech,few-shot,classification,contrastive-learning,setfit,clap,transformers
|
|
11
|
+
Classifier: Development Status :: 3 - Alpha
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Intended Audience :: Science/Research
|
|
14
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
22
|
+
Classifier: Topic :: Multimedia :: Sound/Audio
|
|
23
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
24
|
+
Requires-Python: >=3.9
|
|
25
|
+
Description-Content-Type: text/markdown
|
|
26
|
+
License-File: LICENSE
|
|
27
|
+
Requires-Dist: torch>=2.1
|
|
28
|
+
Requires-Dist: transformers>=4.40
|
|
29
|
+
Requires-Dist: datasets>=4.0
|
|
30
|
+
Requires-Dist: scikit-learn>=1.3
|
|
31
|
+
Requires-Dist: numpy>=1.24
|
|
32
|
+
Requires-Dist: librosa>=0.10
|
|
33
|
+
Requires-Dist: soundfile>=0.12
|
|
34
|
+
Requires-Dist: torchcodec>=0.4
|
|
35
|
+
Requires-Dist: tqdm>=4.65
|
|
36
|
+
Requires-Dist: huggingface_hub>=0.23
|
|
37
|
+
Provides-Extra: dev
|
|
38
|
+
Requires-Dist: pytest>=7; extra == "dev"
|
|
39
|
+
Requires-Dist: ruff>=0.4; extra == "dev"
|
|
40
|
+
Requires-Dist: build>=1.2; extra == "dev"
|
|
41
|
+
Requires-Dist: twine>=5; extra == "dev"
|
|
42
|
+
Dynamic: license-file
|
|
43
|
+
|
|
44
|
+
# AudioSetFit
|
|
45
|
+
|
|
46
|
+
**Efficient few-shot audio classification with contrastive fine-tuning** - a [SetFit](https://github.com/huggingface/setfit) for audio.
|
|
47
|
+
|
|
48
|
+
`audiosetfit` ports SetFit's prompt-free, few-shot recipe from text to audio. Instead of a
|
|
49
|
+
`SentenceTransformer` body, it uses an **audio encoder** (CLAP by default) and trains in two
|
|
50
|
+
phases:
|
|
51
|
+
|
|
52
|
+
1. **Embedding fine-tuning (contrastive).** From a handful of labeled clips it builds
|
|
53
|
+
*positive* (same-class) and *negative* (different-class) pairs and fine-tunes the audio
|
|
54
|
+
body so same-class clips embed closer together. A few examples explode into hundreds of
|
|
55
|
+
informative pairs.
|
|
56
|
+
2. **Classifier head.** A lightweight head (sklearn `LogisticRegression` by default, or a
|
|
57
|
+
differentiable torch head) is fit on the resulting embeddings.
|
|
58
|
+
|
|
59
|
+
The contrastive trainer is **self-contained**, it does *not* depend on
|
|
60
|
+
`sentence-transformers`. The pair-sampling and loss math are reimplemented to operate
|
|
61
|
+
directly on audio embeddings, so any HF audio model can be plugged in as the body.
|
|
62
|
+
|
|
63
|
+
The public API intentionally mirrors SetFit:
|
|
64
|
+
|
|
65
|
+
```python
|
|
66
|
+
from audiosetfit import AudioSetFitModel, Trainer, TrainingArguments, sample_dataset
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
## Installation
|
|
70
|
+
|
|
71
|
+
```bash
|
|
72
|
+
# from the repo root
|
|
73
|
+
python3 -m venv .venv
|
|
74
|
+
source .venv/bin/activate
|
|
75
|
+
pip install --upgrade pip
|
|
76
|
+
pip install -e .
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
This installs `torch`, `transformers`, `datasets`, `librosa`, `soundfile`, `torchcodec`,
|
|
80
|
+
`scikit-learn`, etc. On Apple Silicon, PyTorch will use the **MPS** backend automatically;
|
|
81
|
+
on NVIDIA GPUs it uses CUDA; otherwise CPU.
|
|
82
|
+
|
|
83
|
+
> **FFmpeg required.** `datasets >= 4` decodes audio via `torchcodec`, which needs FFmpeg
|
|
84
|
+
> (4–7) installed on your system. On macOS: `brew install ffmpeg`; on Debian/Ubuntu:
|
|
85
|
+
> `sudo apt-get install ffmpeg`.
|
|
86
|
+
|
|
87
|
+
## Examples
|
|
88
|
+
|
|
89
|
+
The `examples/` scripts cover four small benchmarks across different audio domains. They share
|
|
90
|
+
the same CLI flags (`--backbone`, `--classes`, `--num-samples`, `--epochs`, `--max-pairs`,
|
|
91
|
+
`--no-embedding-finetuning`, `--differentiable-head`, `--num-workers`, ...).
|
|
92
|
+
|
|
93
|
+
### ESC-50 (environmental sounds)
|
|
94
|
+
|
|
95
|
+
[ESC-50](https://huggingface.co/datasets/ashraq/esc50) (2,000 clips, 50 classes) is the small
|
|
96
|
+
default starting point. The example restricts to a few classes for a fast first run:
|
|
97
|
+
|
|
98
|
+
```bash
|
|
99
|
+
python examples/train_esc50.py # 5 classes, 8 shots, CLAP
|
|
100
|
+
python examples/train_esc50.py --classes 10 --num-samples 16
|
|
101
|
+
python examples/train_esc50.py --no-embedding-finetuning # frozen-backbone baseline
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
### UrbanSound8K (urban sounds)
|
|
105
|
+
|
|
106
|
+
[UrbanSound8K](https://huggingface.co/datasets/danavery/urbansound8K) (8,732 clips, 10 classes,
|
|
107
|
+
10 folds) follows the dataset's fold protocol (folds 1-9 train, fold 10 test):
|
|
108
|
+
|
|
109
|
+
```bash
|
|
110
|
+
python examples/train_urbansound8k.py # 5 classes, 8 shots, CLAP
|
|
111
|
+
python examples/train_urbansound8k.py --classes 10 --num-samples 16
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
### CREMA-D (speech emotion)
|
|
115
|
+
|
|
116
|
+
A **speech** task where self-supervised speech encoders shine:
|
|
117
|
+
[CREMA-D](https://huggingface.co/datasets/confit/cremad-parquet) (7,442 clips, 91 actors,
|
|
118
|
+
6 emotions). It defaults to `facebook/wav2vec2-base` and uses a *speaker-disjoint* train/test split:
|
|
119
|
+
|
|
120
|
+
```bash
|
|
121
|
+
python examples/train_cremad.py # wav2vec2-base
|
|
122
|
+
python examples/train_cremad.py --backbone microsoft/wavlm-base
|
|
123
|
+
python examples/train_cremad.py --backbone facebook/hubert-base-ls960
|
|
124
|
+
python examples/train_cremad.py --backbone laion/clap-htsat-unfused # compare vs CLAP
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
### MSWC (keyword spotting)
|
|
128
|
+
|
|
129
|
+
A **keyword-spotting** example (SUPERB KS-style) on
|
|
130
|
+
[MSWC](https://huggingface.co/datasets/confit/mswc-parquet) (Multilingual Spoken Words Corpus).
|
|
131
|
+
Each clip is a single spoken word; this is a lexical/phonetic task, so it also defaults to a
|
|
132
|
+
speech encoder and uses the dataset's predefined train/test splits:
|
|
133
|
+
|
|
134
|
+
```bash
|
|
135
|
+
python examples/train_mswc_keywords.py # 10 keywords, wav2vec2-base
|
|
136
|
+
python examples/train_mswc_keywords.py --classes 5 --num-samples 16
|
|
137
|
+
python examples/train_mswc_keywords.py --language spanish
|
|
138
|
+
python examples/train_mswc_keywords.py --backbone laion/clap-htsat-unfused # compare vs CLAP
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
### Benchmarking (multi-backbone / multi-seed)
|
|
142
|
+
|
|
143
|
+
`examples/benchmark.py` drives the training scripts above across a grid of backbones x seeds and
|
|
144
|
+
prints a mean +/- std table, so backbone comparisons are reproducible instead of single noisy runs.
|
|
145
|
+
It reuses each dataset's own split logic. `Trainer.evaluate` reports both accuracy and macro-F1,
|
|
146
|
+
and `Trainer.classification_report(...)` adds per-class accuracy and a confusion matrix.
|
|
147
|
+
|
|
148
|
+
```bash
|
|
149
|
+
# CLAP vs wav2vec2 on CREMA-D over 3 seeds
|
|
150
|
+
python examples/benchmark.py --dataset cremad \
|
|
151
|
+
--backbones laion/clap-htsat-unfused facebook/wav2vec2-base --seeds 41 42 43
|
|
152
|
+
|
|
153
|
+
# Keyword spotting with speech encoders, write a CSV of every run
|
|
154
|
+
python examples/benchmark.py --dataset mswc \
|
|
155
|
+
--backbones facebook/wav2vec2-base microsoft/wavlm-base --seeds 42 43 --csv results.csv
|
|
156
|
+
|
|
157
|
+
# Forward extra flags to the training script after a literal `--`
|
|
158
|
+
python examples/benchmark.py --dataset esc50 --seeds 41 42 43 -- --no-embedding-finetuning
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
### Minimal end-to-end usage
|
|
162
|
+
|
|
163
|
+
```python
|
|
164
|
+
from datasets import Audio, load_dataset
|
|
165
|
+
from audiosetfit import AudioSetFitModel, Trainer, TrainingArguments, sample_dataset
|
|
166
|
+
|
|
167
|
+
ds = load_dataset("ashraq/esc50", split="train").cast_column("audio", Audio(sampling_rate=48000))
|
|
168
|
+
labels = sorted(set(ds["category"]))
|
|
169
|
+
train_ds = sample_dataset(ds, label_column="category", num_samples=8)
|
|
170
|
+
|
|
171
|
+
model = AudioSetFitModel.from_pretrained("laion/clap-htsat-unfused", labels=labels)
|
|
172
|
+
trainer = Trainer(
|
|
173
|
+
model=model,
|
|
174
|
+
args=TrainingArguments(embedding_num_epochs=1, max_pairs=256),
|
|
175
|
+
train_dataset=train_ds,
|
|
176
|
+
column_mapping={"category": "label"}, # the 'audio' column already matches
|
|
177
|
+
)
|
|
178
|
+
trainer.train()
|
|
179
|
+
|
|
180
|
+
preds = model.predict(["dog_bark.wav", "rain.wav"]) # file paths, arrays, or Audio dicts
|
|
181
|
+
model.save_pretrained("my-esc50-model")
|
|
182
|
+
reloaded = AudioSetFitModel.from_pretrained("my-esc50-model")
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
### Inputs accepted everywhere
|
|
186
|
+
|
|
187
|
+
`predict` / `encode` / datasets accept any mix of:
|
|
188
|
+
|
|
189
|
+
- file paths (`"clip.wav"`),
|
|
190
|
+
- raw waveforms (`np.ndarray`, assumed at the backbone's sample rate),
|
|
191
|
+
- Hugging Face `datasets` Audio dicts (`{"array", "sampling_rate", "path"}`).
|
|
192
|
+
|
|
193
|
+
Everything is resampled to the backbone's expected rate (CLAP = 48 kHz).
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
## Project layout
|
|
197
|
+
|
|
198
|
+
```
|
|
199
|
+
src/audiosetfit/
|
|
200
|
+
├── encoders.py # AudioEncoder base + CLAP/AST/wav2vec2-family/Whisper + build_encoder()
|
|
201
|
+
├── modeling.py # AudioSetFitModel, AudioSetFitHead, save/from_pretrained
|
|
202
|
+
├── sampler.py # ContrastiveDataset (same/different-label pair generation)
|
|
203
|
+
├── losses.py # CosineSimilarityLoss, ContrastiveLoss (on embedding tensors)
|
|
204
|
+
├── data.py # load_audio (resampling), sample_dataset
|
|
205
|
+
├── training_args.py # TrainingArguments (both phases)
|
|
206
|
+
└── trainer.py # self-contained two-phase Trainer
|
|
207
|
+
examples/train_esc50.py
|
|
208
|
+
examples/train_urbansound8k.py
|
|
209
|
+
examples/train_cremad.py
|
|
210
|
+
examples/train_mswc_keywords.py
|
|
211
|
+
examples/benchmark.py # multi-backbone / multi-seed harness
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
## Key training arguments
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
| Argument | Default | Purpose |
|
|
218
|
+
| ------------------------- | ---------------- | -------------------------------------------------------- |
|
|
219
|
+
| `train_embeddings` | `True` | Run phase 1. Set `False` for a frozen-backbone baseline. |
|
|
220
|
+
| `embedding_num_epochs` | `1` | Epochs over contrastive pairs. |
|
|
221
|
+
| `embedding_batch_size` | `16` | Pair batch size (lower it if you hit memory limits). |
|
|
222
|
+
| `body_learning_rate` | `2e-5` | LR for the audio body. |
|
|
223
|
+
| `loss` | `"cosine"` | `"cosine"` or `"contrastive"` (or pass an `nn.Module`). |
|
|
224
|
+
| `sampling_strategy` | `"oversampling"` | `"unique"` / `"oversampling"` / `"undersampling"`. |
|
|
225
|
+
| `max_steps` / `max_pairs` | `-1` | Cap phase-1 work (handy on CPU/laptops). |
|
|
226
|
+
| `classifier_num_epochs` | `25` | Torch-head epochs (ignored for sklearn head). |
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
## Backbones
|
|
230
|
+
|
|
231
|
+
Pick a backbone by passing its Hugging Face id to `from_pretrained` (or `--backbone` in the
|
|
232
|
+
example). The right `AudioEncoder` is selected automatically from the model's `model_type`.
|
|
233
|
+
|
|
234
|
+
```python
|
|
235
|
+
AudioSetFitModel.from_pretrained("laion/clap-htsat-unfused") # CLAP (default)
|
|
236
|
+
AudioSetFitModel.from_pretrained("MIT/ast-finetuned-audioset-10-10-0.4593") # AST
|
|
237
|
+
AudioSetFitModel.from_pretrained("facebook/wav2vec2-base") # wav2vec2
|
|
238
|
+
AudioSetFitModel.from_pretrained("facebook/hubert-base-ls960") # HuBERT
|
|
239
|
+
AudioSetFitModel.from_pretrained("microsoft/wavlm-base-plus") # WavLM
|
|
240
|
+
AudioSetFitModel.from_pretrained("openai/whisper-base") # Whisper encoder
|
|
241
|
+
```
|
|
242
|
+
|
|
243
|
+
```bash
|
|
244
|
+
python examples/train_esc50.py --backbone facebook/wav2vec2-base
|
|
245
|
+
python examples/train_esc50.py --backbone MIT/ast-finetuned-audioset-10-10-0.4593
|
|
246
|
+
```
|
|
247
|
+
|
|
248
|
+
Audio is resampled to each backbone's expected rate automatically (CLAP 48 kHz, others
|
|
249
|
+
16 kHz), so the same dataset works across all of them.
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
| Backbone | `model_type` (built-in) | Embedding | Pooling | Best for |
|
|
253
|
+
| ----------------------------- | -------------------------------------------------------------------------------------------------------- | ----------------- | --------------------- | ----------------------------------------- |
|
|
254
|
+
| **CLAP** (default) | `clap` | 512-d, normalized | projection head | General sound events, environmental audio |
|
|
255
|
+
| **AST** | `audio-spectrogram-transformer` | 768-d | CLS+dist pooled | AudioSet-style tagging |
|
|
256
|
+
| **wav2vec2 / HuBERT / WavLM** | `wav2vec2` / `hubert` / `wavlm` (+ `unispeech`, `unispeech-sat`, `data2vec-audio`, `wav2vec2-conformer`) | hidden_size | masked mean over time | Speech (commands, speaker, emotion) |
|
|
257
|
+
| **Whisper encoder** | `whisper` | d_model | mean over frames | Robust speech in noise |
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
### Adding another backbone
|
|
261
|
+
|
|
262
|
+
The encoder is the only modality-specific piece. Subclass `AudioEncoder`, implement
|
|
263
|
+
`prepare` (waveforms → model inputs) and `forward_features` (inputs → `[B, D]`), set
|
|
264
|
+
`target_sr` / `embedding_dim`, then register it:
|
|
265
|
+
|
|
266
|
+
```python
|
|
267
|
+
from audiosetfit import encoders
|
|
268
|
+
|
|
269
|
+
class MyEncoder(encoders.AudioEncoder):
|
|
270
|
+
def __init__(self, model_id, device=None):
|
|
271
|
+
super().__init__()
|
|
272
|
+
self.model_id = model_id
|
|
273
|
+
... # load backbone + feature extractor
|
|
274
|
+
self.target_sr = 16000
|
|
275
|
+
self.embedding_dim = ... # output dim
|
|
276
|
+
self.to(encoders._resolve_device(device))
|
|
277
|
+
def prepare(self, waveforms): ...
|
|
278
|
+
def forward_features(self, inputs): ...
|
|
279
|
+
def save(self, save_directory): ...
|
|
280
|
+
|
|
281
|
+
encoders._ENCODER_REGISTRY["my_model_type"] = MyEncoder
|
|
282
|
+
```
|
|
283
|
+
|
|
284
|
+
## Roadmap / next steps
|
|
285
|
+
|
|
286
|
+
**Benchmarking & evaluation**
|
|
287
|
+
- [x] Reproducible multi-backbone / multi-seed benchmark harness (`examples/benchmark.py`) with mean ± std tables.
|
|
288
|
+
- [x] Richer metrics in `Trainer.evaluate` (accuracy + macro-F1); per-class accuracy and confusion matrix via `Trainer.classification_report`.
|
|
289
|
+
- [ ] Published results table (CLAP vs wav2vec2 vs WavLM across all example datasets).
|
|
290
|
+
|
|
291
|
+
**Training method**
|
|
292
|
+
- [ ] `SupConLoss` / InfoNCE with in-batch negatives + group-by-label batch sampler (so larger batches add real negatives, as in SetFit).
|
|
293
|
+
- [ ] Audio augmentation for the few-shot regime (SpecAugment, additive noise, gain, time-shift, random crop).
|
|
294
|
+
- [ ] Embedding cache for the frozen-backbone path (skip re-encoding clips across runs/sweeps).
|
|
295
|
+
- [ ] Knowledge distillation from a large unlabeled audio pool (teacher → student).
|
|
296
|
+
|
|
297
|
+
**Models & inputs**
|
|
298
|
+
- [ ] Long-clip handling: windowing/chunking → encode → pool/vote.
|
|
299
|
+
- [ ] Multilabel audio tagging end-to-end example (sampler already supports multilabel pairs).
|
|
300
|
+
- [ ] (Optional) BEATs / OpenBEATs backbone (strongest general-purpose SSL embeddings).
|
|
301
|
+
|
|
302
|
+
**Productionization**
|
|
303
|
+
- [ ] ONNX / `torch.compile` export for fast CPU inference.
|
|
304
|
+
- [ ] Hub `push_to_hub` with an auto-generated model card (incl. the eval table).
|
|
305
|
+
- [ ] Smoke-test suite + CI using small real models (e.g. `openai/whisper-tiny`).
|
|
306
|
+
|
|
307
|
+
## Acknowledgements
|
|
308
|
+
|
|
309
|
+
Architecture and training recipe adapted from
|
|
310
|
+
[Hugging Face SetFit](https://github.com/huggingface/setfit)
|
|
311
|
+
(Tunstall et al., *Efficient Few-Shot Learning Without Prompts*, 2022).
|