atan2f commited on
Commit
509ca57
Β·
verified Β·
1 Parent(s): afd1866

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +128 -1
README.md CHANGED
@@ -10,4 +10,131 @@ tags:
10
  - htsat
11
  - core-ml
12
  - apple-silicon
13
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
  - htsat
11
  - core-ml
12
  - apple-silicon
13
+ ---
14
+
15
+ # larger-clap-general-coreml
16
+
17
+ Native Core ML (`.mlpackage`) build of [`laion/larger_clap_general`](https://huggingface.co/laion/larger_clap_general)'s **audio encoder + projection head**. Takes raw 48 kHz mono waveform, returns an L2-normalized 512-d embedding compatible with the original CLAP joint embedding space.
18
+
19
+ `larger_clap_general` is trained on **general audio, music and speech** β€” pair it with the upstream text encoder for zero-shot audio classification or open-vocabulary retrieval.
20
+
21
+ Built because `ort`'s CoreML execution provider can't accelerate HTSAT β€” reflect-pad, 5-D reshapes, relative-position-bias gather, and dynamic shapes shred the graph into CPU partitions, so the EP "registers" but every node runs on CPU. Loading this `.mlpackage` directly via Core ML (skipping ORT entirely) runs the full graph on the Apple GPU.
22
+
23
+ ## Inputs / Outputs
24
+
25
+ | | name | shape | dtype | notes |
26
+ |---|---|---|---|---|
27
+ | Input | `audio` | `[1, 480000]` | float32 | 10 s mono @ 48 kHz, peak-normalized to `[-1, 1]` |
28
+ | Output | `embedding` | `[1, 512]` | float32 | L2-normalized; cosine similarity == dot product |
29
+
30
+ The mel-spectrogram extraction (STFT, Slaney mel filterbank, log) is **baked into the model graph** β€” you pass raw audio, not features.
31
+
32
+ ## Variable-length audio
33
+
34
+ The graph has a fixed 10 s input shape. For arbitrary-length audio, recommended recipe:
35
+
36
+ | Duration | Strategy |
37
+ |---|---|
38
+ | ≀ 10 s | Zero-pad to 480_000 samples, single forward pass. |
39
+ | > 10 s | Sliding 10 s windows with 50 % overlap, embed each window, **mean-pool the embeddings, re-L2-normalize.** |
40
+
41
+ For very long files cap window count to bound runtime β€” uniformly spacing N windows across `[0, T-10s]` gives full-file coverage without per-window blow-up.
42
+
43
+ ## Usage
44
+
45
+ ### Swift (Core ML)
46
+ ```swift
47
+ import CoreML
48
+
49
+ let config = MLModelConfiguration()
50
+ config.computeUnits = .cpuAndGPU
51
+ let model = try MLModel(contentsOf: compiledURL, configuration: config)
52
+
53
+ let audio = try MLMultiArray(shape: [1, 480_000], dataType: .float32)
54
+ // copy your normalized waveform into audio.dataPointer ...
55
+
56
+ let provider = try MLDictionaryFeatureProvider(dictionary: ["audio": audio])
57
+ let out = try model.prediction(from: provider)
58
+ let embedding = out.featureValue(for: "embedding")!.multiArrayValue!
59
+ ```
60
+
61
+ ### Rust (objc2-core-ml)
62
+ See [`scripts/convert-clap-to-coreml.py`](#how-it-was-built) reference repo for a Rust integration that loads this `.mlpackage`, runs sliding-window embedding for arbitrary-length audio, and mean-pools.
63
+
64
+ ### Python (coremltools)
65
+ ```python
66
+ import coremltools as ct
67
+ import numpy as np
68
+
69
+ model = ct.models.MLModel("clap_audio_encoder.mlpackage")
70
+ waveform = np.zeros((1, 480_000), dtype=np.float32)
71
+ out = model.predict({"audio": waveform})
72
+ embedding = out["embedding"] # shape (1, 512)
73
+ ```
74
+
75
+ ## How it was built
76
+
77
+ `coremltools` 8 + `torch.export` from `laion/larger_clap_general`'s PyTorch weights, then `convert_to="mlprogram"` + int8 linear weight quantization. The conversion is non-trivial β€” `ct.convert` rejects the model out of the box. Patches applied:
78
+
79
+ 1. **`F.interpolate(mode='bicubic')` β†’ `'bilinear'`** β€” CoreML's MIL backend lacks bicubic upsampling. Used by HTSAT's positional-embedding resize. Accuracy delta is negligible.
80
+ 2. **`torch.jit.is_tracing()` β†’ `True`** β€” forces HF's CLAP code onto the static-shape path during conversion.
81
+ 3. **`ClapAudioLayer.set_shift_and_window_size` β†’ no-op** β€” the dynamic window adjustment hits a "data-dependent guard" error in `torch.export`. For our fixed `[1, 1, 1001, 64]` input the `__init__` values are already correct, so neutralizing is safe.
82
+ 4. **Custom STFT** β€” `torch.stft`'s op signature drifts across torch versions and the coremltools handler unpacks the wrong arity; implemented as strided conv1d with pre-baked cos/sin Hann bases instead.
83
+ 5. **Custom `fmod` MIL lowering** β€” HTSAT's relative-position arithmetic uses float modulo; coremltools has no built-in handler. Registered as `x - trunc(x/y) * y`.
84
+ 6. **`slice_scatter` override** β€” HTSAT's attention-mask builder generates empty-slice `slice_scatter` calls at deeper Swin stages (e.g. `slice(0, -window_size)` evaluates to `slice(0, 0)`). The built-in handler's shape check rejects these; registered override that no-ops empty slices and reduces non-empty ones to `slice_by_index + concat`.
85
+
86
+ A full conversion script that applies all six patches is in the reference repo (link below).
87
+
88
+ ## Validation
89
+
90
+ Cosine similarity vs the PyTorch reference, on random `[1, 480000]` peak-normalized inputs:
91
+
92
+ | Trial | Cosine |
93
+ |---|---|
94
+ | 1 | 0.999393 |
95
+ | 2 | 0.998725 |
96
+ | 3 | 0.998992 |
97
+
98
+ The drift is dominated by int8 weight quantization. For full fp32 weights you can re-run the conversion with the int8 step disabled (~3Γ— larger file, ~1.001 cosine on the same inputs).
99
+
100
+ ## Performance
101
+
102
+ Apple M-series, `MLComputeUnits.cpuAndGPU`:
103
+
104
+ | | Latency per 10 s window |
105
+ |---|---|
106
+ | Cold start (first forward pass) | ~5 s (Core ML graph compile + GPU upload) |
107
+ | Steady state | ~30 ms |
108
+
109
+ Compared to running the original `.onnx` via `ort` on Apple Silicon CPU, that's a roughly 10Γ— speedup for the steady state. ANE was not attempted (`MLComputeUnits.all`) β€” `CPUAndGPU` was the sweet spot during testing; the strictest backend often rejects whole-graph compilation for transformer audio models.
110
+
111
+ ## Limitations
112
+
113
+ - **Audio encoder only.** The text encoder + logit-scale are not part of this package β€” use the original `laion/larger_clap_general` for the text path if you need joint-embedding search.
114
+ - **Fixed input shape.** Audio shorter than 10 s must be zero-padded; longer requires the sliding-window recipe above.
115
+ - **int8 quantization.** ~99.9 % cosine is sufficient for retrieval / search use cases; if you're using these embeddings as inputs to downstream training, prefer the fp32 variant.
116
+
117
+ ## Credits
118
+
119
+ - [LAION](https://laion.ai) for [`larger_clap_general`](https://huggingface.co/laion/larger_clap_general).
120
+ - [gridshiftstudio/clap-music-coreml](https://huggingface.co/gridshiftstudio/clap-music-coreml) for the first public proof that this conversion is viable + the two key patches.
121
+
122
+ ## Citation
123
+
124
+ If you use this model in your work, please cite the original CLAP paper ([arXiv:2211.06687](https://arxiv.org/abs/2211.06687)):
125
+
126
+ ```bibtex
127
+ @misc{https://doi.org/10.48550/arxiv.2211.06687,
128
+ doi = {10.48550/ARXIV.2211.06687},
129
+ url = {https://arxiv.org/abs/2211.06687},
130
+ author = {Wu, Yusong and Chen, Ke and Zhang, Tianyu and Hui, Yuchen and Berg-Kirkpatrick, Taylor and Dubnov, Shlomo},
131
+ title = {Large-scale Contrastive Language-Audio Pretraining with Feature Fusion and Keyword-to-Caption Augmentation},
132
+ publisher = {arXiv},
133
+ year = {2022},
134
+ copyright = {Creative Commons Attribution 4.0 International}
135
+ }
136
+ ```
137
+
138
+ ## License
139
+
140
+ This artifact inherits the source model's license: **Apache 2.0**.