-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodal_app.py
More file actions
5777 lines (5176 loc) · 288 KB
/
Copy pathmodal_app.py
File metadata and controls
5777 lines (5176 loc) · 288 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Modal deployment for Fusion Embedding 1 — serverless GPU training on Linux.
Why Modal (recap): Linux containers make 4-bit (bitsandbytes) + FlashAttention "just
work" (no Windows/WSL pain); per-second billing fits the burst-y, connector-only stages;
a Volume caches the frozen Qwen weights + preprocessed mel features so the H100 is never
blocked on downloads or audio decode. The exact same `fusion_embedding` code runs here
and locally — Modal only provides the GPU + filesystem.
Pipeline (run in order):
uv run --env-file .env modal run modal_app.py::smoke # cheap T4 — prove the image + GPU path
uv run --env-file .env modal run modal_app.py::warm_cache # one-time: pull Qwen weights to the Volume
uv run --env-file .env modal run modal_app.py::preprocess --shard demo # CPU: audio -> mel on the Volume
uv run --env-file .env modal run modal_app.py::train_p1 # GPU: connector training (Stage 1)
Status: image + Volume + Secret + the tiny-stand-in GPU smoke are REAL and runnable today.
`preprocess` and `train_p1` carry `# TODO(fusion)` markers where the real dataset and the
HLD §10 `load_components` seam plug in — they run end-to-end on synthetic data until then.
"""
from __future__ import annotations
import modal
APP_NAME = "fusion-embedding"
# --- Persistent storage: one Volume holds the HF weight cache, preprocessed features,
# and connector checkpoints. Created on first use; survives across runs. ---
volume = modal.Volume.from_name("fusion-data", create_if_missing=True)
VOL = "/vol"
HF_CACHE = f"{VOL}/hf-cache" # frozen Qwen weights (downloaded once)
FEATURES = f"{VOL}/features" # preprocessed mel shards (WebDataset/pt)
CKPTS = f"{VOL}/checkpoints" # connector + temperature checkpoints (~30MB each)
# --- HF token: stored in Modal's secret store as `huggingface` (you create it; see below).
# Referenced by name — the token never appears in this file or the repo. ---
hf_secret = modal.Secret.from_name("huggingface")
# --- Container image: cu124 torch + the `hf` extra (transformers/bitsandbytes/librosa).
# Built once and cached by Modal; bitsandbytes/flash-attn build cleanly on Linux. ---
image = (
modal.Image.debian_slim(python_version="3.11")
.apt_install("ffmpeg", "libsndfile1", # audio decode backends for librosa/soundfile
"zip", "unzip", "p7zip-full") # WavCaps multi-part zip reassembly
.pip_install(
"torch==2.6.0",
"numpy>=1.24",
"transformers>=4.46",
"accelerate>=0.30",
"bitsandbytes>=0.43", # 4-bit frozen base (Linux only)
"soundfile>=0.12",
"librosa>=0.10",
"datasets>=3.0", # real audio-caption datasets
"pillow>=10.0", # Phase 0: image path through the frozen base
"torchvision==0.21.0", # Phase 0: Qwen3-VL processor requirement
"av>=12.0", # Phase 0: video-frame extraction for AV pairs
extra_index_url="https://download.pytorch.org/whl/cu124",
)
)
# MAEB runs need mteb on top of the training deps (separate image so the trainer image
# stays untouched); local files must be added LAST on each derived image.
maeb_image = (image.pip_install("torch==2.7.1", "torchvision==0.22.1", "torchaudio==2.7.1",
"torchcodec==0.5", "mteb==2.18.0")
.add_local_python_source("fusion_embedding")
.add_local_file("fe2_release/mteb_wrapper.py", "/root/mteb_wrapper.py")
.add_local_file("submission/fusion_embedding_models.py",
"/root/fusion_embedding_models.py"))
# Stage A tower probe (2026-07-10): alternate frozen audio towers. GLAP's controlled ablation
# (arXiv:2506.11350 Tab.4) shows Whisper-family encoders (our Qwen2.5-Omni tower's family) trail
# sound-event encoders by ~10 mAP@10 on AudioCaps T2A; Dasheng is their production pick.
# Separate derived image so the base trainer image is untouched.
# torchaudio must ABI-pair with the base image's torch==2.6.0 cu124 (torch/torchcodec
# pairing trap, 2026-07-08) — same extra index so pip resolves the cu124 wheel.
alt_tower_image = (image.pip_install("dasheng==0.0.9", "torchaudio==2.6.0",
extra_index_url="https://download.pytorch.org/whl/cu124")
.add_local_python_source("fusion_embedding"))
# Ship the local package into the image so `import fusion_embedding` works in the container.
image = image.add_local_python_source("fusion_embedding")
# FE2 hub-smoke image: the released inference.py rides along so the smoke exercises the
# EXACT artifact users run (loaded from the public HF repo, not the local checkout).
fe2_smoke_image = image.add_local_file("fe2_release/inference.py", "/root/fe2_inference.py")
app = modal.App(APP_NAME, image=image)
# Shared env so every function caches HF downloads onto the Volume, not the ephemeral disk.
# HF_XET_HIGH_PERFORMANCE is the current fast-transfer backend (Xet); the old
# HF_HUB_ENABLE_HF_TRANSFER flag is deprecated (hf_transfer is no longer used). hf_xet ships
# in the image, so this actually enables faster weight/dataset pulls.
# FUSION_DATA_ROOT makes fusion_embedding.paths resolve features/frames/checkpoints to the
# Volume here — and to a local dir / mounted bucket off Modal. One env var = provider-portable.
HF_ENV = {"HF_HOME": HF_CACHE, "HF_XET_HIGH_PERFORMANCE": "1", "FUSION_DATA_ROOT": VOL,
"PYTORCH_CUDA_ALLOC_CONF": "expandable_segments:True",
# A dead connection must FAIL (and be retried), not hang forever — a FreeSound
# ingest sat 34 min on one tar download with no exception (2026-07-06).
"HF_HUB_DOWNLOAD_TIMEOUT": "60"}
BASE_MODEL = "Qwen/Qwen3-VL-Embedding-2B"
AUDIO_MODEL = "Qwen/Qwen2.5-Omni-7B"
# --------------------------------------------------------------------------- #
# 0. Smoke — cheapest possible proof the image, GPU, and our code line up.
# No weights, no data: runs the tiny CPU stand-ins on a real Modal GPU.
# --------------------------------------------------------------------------- #
@app.function(gpu="T4", timeout=600)
def smoke() -> dict:
import torch
from fusion_embedding.config import FusionConfig
from fusion_embedding.train_stage1 import build_tiny_training_setup, train_stage1
from fusion_embedding.memory_bank import TextMemoryBank
assert torch.cuda.is_available(), "no CUDA in the Modal container"
dev = "cuda"
cfg = FusionConfig.tiny(max_steps=120, d_resampler=32, use_bf16=True)
s = build_tiny_training_setup(cfg, n_train=8, batch_size=8, seed=0)
s.model.to(dev)
bank = TextMemoryBank(dim=cfg.d_llm, capacity=32, device=dev)
state = train_stage1(
s.model, s.train_loader, s.loss_fn, cfg,
steps=120, eval_fn=s.eval_fn, device=dev, log_every=60, memory_bank=bank,
)
out = {
"gpu": torch.cuda.get_device_name(0),
"a2t_R@1": state.final_eval["a2t_R@1"],
"base_drift": state.final_eval["base_drift"],
"peak_vram_mb": round(torch.cuda.max_memory_allocated() / 1e6, 1),
}
print("SMOKE:", out)
return out
# --------------------------------------------------------------------------- #
# 0b. introspect — discover the REAL Qwen APIs before writing load_components.
# CPU-only (no GPU cost): loads the cached configs + the small 2B model, and
# builds the 7B on the meta device (zero memory) to read its module tree.
# Prints exactly what the frozen-base contract needs: embed_tokens path,
# inputs_embeds support, hidden size, audio-tower path + forward signature,
# d_audio, and the tokenizer special-token ids.
# --------------------------------------------------------------------------- #
@app.function(volumes={VOL: volume}, secrets=[hf_secret], cpu=4.0, memory=16384, timeout=1800, env=HF_ENV)
def introspect() -> dict:
import inspect
import json
import torch
from transformers import AutoConfig, AutoModel, AutoTokenizer
report: dict = {}
def safe(fn):
try:
return fn()
except Exception as e: # noqa: BLE001 - discovery: capture, don't crash
return f"ERR: {type(e).__name__}: {e}"
# ---- Base: Qwen3-VL-Embedding-2B ----
b: dict = {}
cfg = AutoConfig.from_pretrained(BASE_MODEL, trust_remote_code=True)
b["config_class"] = type(cfg).__name__
b["hidden_size"] = getattr(cfg, "hidden_size", None) or safe(lambda: cfg.text_config.hidden_size)
b["top_level_keys"] = [k for k in vars(cfg) if not k.startswith("_")][:40]
tok = safe(lambda: AutoTokenizer.from_pretrained(BASE_MODEL, trust_remote_code=True))
if not isinstance(tok, str):
b["eos_id"] = tok.eos_token_id
b["pad_id"] = tok.pad_token_id
b["eos_token"] = tok.eos_token
b["has_audio_pad"] = "<|audio_pad|>" in tok.get_vocab()
b["vocab_size"] = len(tok)
# candidate placeholder tokens already in the vocab
b["pad_like_tokens"] = [t for t in tok.get_vocab() if "pad" in t.lower() or "audio" in t.lower()][:20]
def load_base():
m = AutoModel.from_pretrained(
BASE_MODEL, trust_remote_code=True, torch_dtype=torch.float32, low_cpu_mem_usage=True
)
return m
m = safe(load_base)
if not isinstance(m, str):
b["model_class"] = type(m).__name__
b["forward_params"] = list(inspect.signature(m.forward).parameters)
b["accepts_inputs_embeds"] = "inputs_embeds" in b["forward_params"]
# find embed_tokens-like modules
b["embed_modules"] = [n for n, _ in m.named_modules() if n.endswith("embed_tokens")][:5]
# top-level children (orientation in the module tree)
b["top_children"] = [n for n, _ in m.named_children()]
b["get_input_embeddings"] = safe(lambda: type(m.get_input_embeddings()).__name__)
report["base"] = b
# ---- Audio: Qwen2.5-Omni-7B (meta device — no weight memory) ----
a: dict = {}
acfg = AutoConfig.from_pretrained(AUDIO_MODEL, trust_remote_code=True)
a["config_class"] = type(acfg).__name__
a["sub_configs"] = [k for k in vars(acfg) if not k.startswith("_")][:40]
# hunt for the audio sub-config + its hidden dim (d_audio should be 1280)
for key in vars(acfg):
sub = getattr(acfg, key)
if hasattr(sub, "to_dict") and "audio" in key.lower():
a[f"audio_cfg::{key}"] = {
kk: vv for kk, vv in sub.to_dict().items()
if any(s in kk for s in ("hidden", "d_model", "num_mel", "layers", "dim"))
}
def build_meta():
from accelerate import init_empty_weights
with init_empty_weights():
mm = AutoModel.from_config(acfg, trust_remote_code=True)
return mm
am = safe(build_meta)
if not isinstance(am, str):
a["model_class"] = type(am).__name__
a["top_children"] = [n for n, _ in am.named_children()]
# find the audio tower/encoder submodule by name
audio_mods = [n for n, _ in am.named_modules() if ("audio" in n.lower() and n.count(".") <= 1)]
a["audio_module_names"] = audio_mods[:15]
for name, mod in am.named_modules():
if name in audio_mods and hasattr(mod, "forward"):
a[f"forward::{name}"] = list(inspect.signature(mod.forward).parameters)
else:
a["meta_build"] = am
# feature extractor / processor (cheap, real)
a["processor"] = safe(
lambda: type(
__import__("transformers").AutoProcessor.from_pretrained(AUDIO_MODEL, trust_remote_code=True)
).__name__
)
report["audio"] = a
print("INTROSPECT REPORT:\n" + json.dumps(report, indent=2, default=str))
return report
# --------------------------------------------------------------------------- #
# 0c. introspect_audio — targeted dig into the Omni thinker's audio tower.
# --------------------------------------------------------------------------- #
@app.function(volumes={VOL: volume}, secrets=[hf_secret], cpu=4.0, memory=16384, timeout=1800, env=HF_ENV)
def introspect_audio() -> dict:
import inspect
import json
import torch
import transformers
from transformers import AutoConfig
report: dict = {}
def safe(fn):
try:
return fn()
except Exception as e: # noqa: BLE001
return f"ERR: {type(e).__name__}: {e}"
# confirm base d_llm
bcfg = AutoConfig.from_pretrained(BASE_MODEL, trust_remote_code=True)
report["base_hidden"] = safe(lambda: bcfg.text_config.hidden_size)
report["base_text_cfg_class"] = safe(lambda: type(bcfg.text_config).__name__)
acfg = AutoConfig.from_pretrained(AUDIO_MODEL, trust_remote_code=True)
th = acfg.thinker_config
report["thinker_cfg_class"] = type(th).__name__
report["thinker_sub"] = [k for k in vars(th) if not k.startswith("_")][:40]
audio_cfg = safe(lambda: th.audio_config)
if not isinstance(audio_cfg, str):
report["audio_config"] = {k: v for k, v in audio_cfg.to_dict().items()
if any(s in k for s in ("hidden", "d_model", "mel", "layer", "dim", "output", "size"))}
report["audio_config_class"] = type(audio_cfg).__name__
# what Omni classes exist in this transformers build?
report["omni_classes"] = [n for n in dir(transformers) if "Omni" in n][:30]
# build the audio encoder alone, on meta (zero memory), to read its forward + tree
def build_audio_encoder():
from accelerate import init_empty_weights
# the audio tower class
cls = None
for name in ("Qwen2_5OmniAudioEncoder",):
cls = getattr(transformers, name, None)
if cls is not None:
break
if cls is None:
return "no audio encoder class found"
with init_empty_weights():
enc = cls(audio_cfg)
return enc
enc = safe(build_audio_encoder)
if not isinstance(enc, str):
report["audio_encoder_class"] = type(enc).__name__
report["audio_encoder_forward"] = list(inspect.signature(enc.forward).parameters)
report["audio_encoder_children"] = [n for n, _ in enc.named_children()]
else:
report["audio_encoder_build"] = enc
# feature extractor (how mel is produced)
def load_feat():
from transformers import Qwen2_5OmniProcessor
proc = Qwen2_5OmniProcessor.from_pretrained(AUDIO_MODEL, trust_remote_code=True)
fe = getattr(proc, "feature_extractor", None) or getattr(proc, "omni_processor", None)
return {
"processor_class": type(proc).__name__,
"feature_extractor_class": type(fe).__name__ if fe is not None else None,
"fe_sampling_rate": getattr(fe, "sampling_rate", None),
"fe_n_mels": getattr(fe, "feature_size", None),
"fe_call_params": list(inspect.signature(fe.__call__).parameters) if fe is not None else None,
}
report["feature_extractor"] = safe(load_feat)
print("AUDIO INTROSPECT:\n" + json.dumps(report, indent=2, default=str))
return report
# --------------------------------------------------------------------------- #
# 0d. introspect_encoder — read the Omni audio encoder's forward + load the FE.
# --------------------------------------------------------------------------- #
@app.function(volumes={VOL: volume}, secrets=[hf_secret], cpu=4.0, memory=16384, timeout=1800, env=HF_ENV)
def introspect_encoder() -> dict:
import inspect
import json
from transformers import AutoConfig
from transformers.models.qwen2_5_omni import modeling_qwen2_5_omni as mod
report: dict = {}
def safe(fn):
try:
return fn()
except Exception as e: # noqa: BLE001
return f"ERR: {type(e).__name__}: {e}"
acfg = AutoConfig.from_pretrained(AUDIO_MODEL, trust_remote_code=True)
audio_cfg = acfg.thinker_config.audio_config
enc_cls = mod.Qwen2_5OmniAudioEncoder
report["encoder_class"] = enc_cls.__name__
report["encoder_forward_params"] = list(inspect.signature(enc_cls.forward).parameters)
# the source tells us inputs, masking, and what it returns (1280 vs 3584)
src = inspect.getsource(enc_cls.forward)
report["encoder_forward_source"] = src[:3500]
# feature extractor — load directly (the full processor trips on the image side)
def load_fe():
from transformers import AutoFeatureExtractor
fe = AutoFeatureExtractor.from_pretrained(AUDIO_MODEL, trust_remote_code=True)
return {
"class": type(fe).__name__,
"sampling_rate": getattr(fe, "sampling_rate", None),
"feature_size": getattr(fe, "feature_size", None),
"n_mels": getattr(fe, "feature_size", None),
"call_params": list(inspect.signature(fe.__call__).parameters),
"hop_length": getattr(fe, "hop_length", None),
"chunk_length": getattr(fe, "chunk_length", None),
}
report["feature_extractor"] = safe(load_fe)
print("ENCODER INTROSPECT:\n" + json.dumps(report, indent=2, default=str))
return report
# --------------------------------------------------------------------------- #
# 0e. find_audio_dataset — STREAMING peek at candidate caption datasets (no full
# download): which load, their columns, and a sample caption. Picks the repo
# + columns for `preprocess` without burning full-download runs.
# --------------------------------------------------------------------------- #
@app.function(secrets=[hf_secret], cpu=2.0, timeout=900, env=HF_ENV)
def find_audio_dataset() -> dict:
import os
from datasets import load_dataset
from datasets import Audio
token = os.environ.get("HF_TOKEN") or None
candidates = [
("OpenSound/AudioCaps", "train"),
("OpenSound/AudioCaps", "test"),
]
report = {}
for repo, split in candidates:
try:
ds = load_dataset(repo, split=split, streaming=True, token=token)
feats = list(ds.features) if ds.features else None
if feats and "audio" in feats: # avoid torchcodec on peek
ds = ds.cast_column("audio", Audio(decode=False))
sample = next(iter(ds))
# show non-audio fields (strings) so we can spot caption columns
text_fields = {k: (str(v)[:80]) for k, v in sample.items()
if isinstance(v, (str, int, float, list)) and k != "audio"}
report[repo] = {"split": split, "features": feats, "sample_text_fields": text_fields}
print(f"OK {repo}:{split} features={feats}")
except Exception as e: # noqa: BLE001
report[repo] = f"ERR: {type(e).__name__}: {str(e)[:160]}"
print(f"FAIL {repo}: {str(e)[:120]}")
import json
print("DATASET REPORT:\n" + json.dumps(report, indent=2, default=str))
return report
@app.function(secrets=[hf_secret], cpu=2.0, timeout=900, env=HF_ENV)
def peek_eval() -> dict:
"""Peek the eval sets for Step 1: how AudioCaps-test / Clotho structure their 5 captions/clip
(one row per caption sharing a clip id, or a list column) + which repo ships decodable audio."""
import json
import os
from itertools import islice
from datasets import Audio, load_dataset
token = os.environ.get("HF_TOKEN") or None
candidates = [
("OpenSound/AudioCaps", None, "test"),
("confit/clotho", "2023", "test"),
("CLAPv2/Clotho", None, "test"),
]
report = {}
for repo, cfg, split in candidates:
key = f"{repo}:{cfg}" if cfg else repo
try:
ds = (load_dataset(repo, cfg, split=split, streaming=True, token=token) if cfg
else load_dataset(repo, split=split, streaming=True, token=token))
feats = list(ds.features) if ds.features else None
if feats and "audio" in feats:
ds = ds.cast_column("audio", Audio(decode=False))
rows = []
for r in islice(ds, 6):
rows.append({k: str(v)[:70] for k, v in r.items()
if isinstance(v, (str, int, float, list)) and k != "audio"})
report[key] = {"split": split, "features": feats, "first_rows": rows}
print(f"OK {key} features={feats}")
except Exception as e: # noqa: BLE001
report[key] = f"ERR: {type(e).__name__}: {str(e)[:180]}"
print(f"FAIL {key}: {str(e)[:150]}")
print("EVAL PEEK:\n" + json.dumps(report, indent=2, default=str))
return report
@app.function(secrets=[hf_secret], cpu=2.0, timeout=1800, env=HF_ENV)
def find_clotho_5ref() -> dict:
"""Discover a Clotho source that carries all 5 reference captions (for the published min-rank-over-5
A→T protocol). Searches HF for clotho datasets, then peeks each candidate's schema + first row —
flags repos with caption_1..caption_5 columns, a captions/all_captions list, or per-caption rows
groupable by an audio/file key. Cheap CPU probe; informs the 5-ref ingestion path."""
import json
import os
from itertools import islice
from datasets import load_dataset
from huggingface_hub import HfApi
token = os.environ.get("HF_TOKEN") or None
api = HfApi()
names = [d.id for d in api.list_datasets(search="clotho", limit=40, token=token)]
print(f"candidates ({len(names)}): {names}")
def _caption_cols(feats):
return [f for f in feats if "caption" in f.lower() or f.lower() in ("text", "captions", "raw_text")]
report = {"candidates": names, "schemas": {}}
for repo in names:
for split in ("test", "evaluation", "validation"):
try:
ds = load_dataset(repo, split=split, streaming=True, token=token)
feats = list(ds.features) if ds.features else None
row0 = next(islice(ds, 1), None)
sample = {k: str(v)[:80] for k, v in (row0 or {}).items() if k != "audio"}
report["schemas"][f"{repo}:{split}"] = {
"features": feats, "caption_like": _caption_cols(feats or []),
"has_audio": bool(feats and "audio" in feats), "sample": sample}
print(f"OK {repo}:{split} caption_like={_caption_cols(feats or [])} audio={'audio' in (feats or [])}")
break # first working split is enough
except Exception as e: # noqa: BLE001
report["schemas"].setdefault(f"{repo}:{split}", f"ERR: {type(e).__name__}: {str(e)[:90]}")
print("CLOTHO 5REF SEARCH:\n" + json.dumps(report, indent=2, default=str))
return report
@app.function(secrets=[hf_secret], cpu=2.0, timeout=1800, env=HF_ENV)
def list_clotho_files(repos: str = "confit/clotho,d0rj/clotho-v2.1,ZhangShiao/clotho") -> dict:
"""List raw files in candidate Clotho repos (bypasses dead loader scripts) — looking for an
`..._captions_evaluation.csv` (file_name,caption_1..5) + evaluation audio we can build 5-ref from."""
import json
import os
from huggingface_hub import HfApi
token = os.environ.get("HF_TOKEN") or None
api = HfApi()
out = {}
for repo in [r.strip() for r in repos.split(",") if r.strip()]:
try:
files = api.list_repo_files(repo, repo_type="dataset", token=token)
interesting = [f for f in files if any(k in f.lower() for k in
("eval", "caption", ".csv", ".7z", ".zip", ".parquet", "audio"))]
out[repo] = {"n_files": len(files), "interesting": interesting[:60]}
print(f"OK {repo}: {len(files)} files")
except Exception as e: # noqa: BLE001
out[repo] = f"ERR: {type(e).__name__}: {str(e)[:100]}"
print(f"FAIL {repo}: {str(e)[:100]}")
print("CLOTHO FILES:\n" + json.dumps(out, indent=2, default=str))
return out
@app.function(secrets=[hf_secret], cpu=2.0, timeout=1800, env=HF_ENV)
def verify_clotho_5ref(specs: str = "LakoreAI/clotho-dev-sample:test:caption_1|caption_2|caption_3|caption_4|caption_5;mteb/Clotho:test:text|raw_text") -> dict:
"""For each `repo:split:col1|col2|...` spec, count rows + unique clips + how many carry all listed
caption fields non-empty, and dump one full row. Decides which source = canonical 1045×5 Clotho eval."""
import json
import os
from datasets import Audio, load_dataset
token = os.environ.get("HF_TOKEN") or None
out = {}
for spec in [s for s in specs.split(";") if s.strip()]:
repo, split, cols = spec.split(":", 2)
cols = cols.split("|")
try:
ds = load_dataset(repo, split=split, streaming=True, token=token)
if ds.features and "audio" in ds.features:
ds = ds.cast_column("audio", Audio(decode=False))
n = full5 = 0
names = set()
first = None
for r in ds:
n += 1
if first is None:
first = {k: (str(v)[:60] if k != "audio" else "<audio>") for k, v in r.items()}
fn = r.get("file_name") or r.get("index") or r.get("id")
if fn is not None:
names.add(str(fn))
vals = [r.get(c) for c in cols]
if all(isinstance(v, str) and v.strip() for v in vals):
full5 += 1
if n >= 12000:
break
out[f"{repo}:{split}"] = {"rows": n, "unique_clip_keys": len(names),
"rows_with_all_cols_nonempty": full5, "cols": cols, "first_row": first}
print(f"{repo}:{split} rows={n} unique={len(names)} all_cols_nonempty={full5}")
except Exception as e: # noqa: BLE001
out[f"{repo}:{split}"] = f"ERR: {type(e).__name__}: {str(e)[:120]}"
print(f"FAIL {repo}:{split}: {str(e)[:110]}")
print("VERIFY CLOTHO:\n" + json.dumps(out, indent=2, default=str))
return out
@app.function(secrets=[hf_secret], cpu=2.0, timeout=1800, env=HF_ENV)
def peek_clotho_candidates(
repos: str = "mteb/Clotho,zachz/Clotho-PC-T2A,LakoreAI/clotho-dev-sample,humanify/ARAG-clotho-test",
split: str = "test") -> dict:
"""Probe audio-bearing Clotho repos with decode OFF (so schema reads don't trip torchcodec):
report features + a sample row + whether a clip carries all 5 refs (caption_1..5 / a list / groupable)."""
import json
import os
from itertools import islice
from datasets import Audio, load_dataset
token = os.environ.get("HF_TOKEN") or None
out = {}
for repo in [r.strip() for r in repos.split(",") if r.strip()]:
try:
ds = load_dataset(repo, split=split, streaming=True, token=token)
if ds.features and "audio" in ds.features:
ds = ds.cast_column("audio", Audio(decode=False))
feats = list(ds.features) if ds.features else None
rows = [{k: (str(v)[:70] if k != "audio" else "<audio>") for k, v in r.items()}
for r in islice(ds, 3)]
cap_cols = [f for f in (feats or []) if "caption" in f.lower()
or f.lower() in ("text", "captions", "raw_text", "all_captions")]
out[repo] = {"features": feats, "caption_cols": cap_cols,
"has_audio": bool(feats and "audio" in feats), "rows": rows}
print(f"OK {repo} caption_cols={cap_cols} audio={'audio' in (feats or [])}")
except Exception as e: # noqa: BLE001
out[repo] = f"ERR: {type(e).__name__}: {str(e)[:120]}"
print(f"FAIL {repo}: {str(e)[:110]}")
print("CLOTHO CANDIDATES:\n" + json.dumps(out, indent=2, default=str))
return out
@app.function(secrets=[hf_secret], cpu=2.0, timeout=1800, env=HF_ENV)
def peek_clotho_grouping(repo: str = "CLAPv2/Clotho", split: str = "test", limit: int = 6000) -> dict:
"""Decide whether CLAPv2/Clotho can drive a 5-ref eval: is each clip's audio DUPLICATED across
its caption rows (groupable) or one-caption-per-clip (not a min-rank-over-5 set)? Reports the
candidate grouping keys (audio path basename, index-minus-suffix) + their repeat distribution."""
import json
import os
from collections import Counter
from itertools import islice
from datasets import Audio, load_dataset
token = os.environ.get("HF_TOKEN") or None
ds = load_dataset(repo, split=split, streaming=True, token=token).cast_column("audio", Audio(decode=False))
path_counts, n = Counter(), 0
sample_paths = []
for r in islice(ds, limit):
a = r.get("audio") or {}
p = a.get("path") or ""
base = os.path.basename(str(p))
path_counts[base] += 1
if len(sample_paths) < 8:
sample_paths.append({"index": str(r.get("index"))[:60], "audio_path": str(p)[:90]})
n += 1
reps = Counter(path_counts.values()) # {captions-per-clip: how many clips}
out = {"repo": repo, "rows_scanned": n, "unique_audio_paths": len(path_counts),
"captions_per_clip_distribution": dict(sorted(reps.items())),
"max_captions_for_one_clip": max(path_counts.values()) if path_counts else 0,
"groupable_by_audio_path": len(path_counts) > 0 and len(path_counts) < n,
"sample": sample_paths}
print("CLOTHO GROUPING:\n" + json.dumps(out, indent=2))
return out
@app.function(secrets=[hf_secret], cpu=2.0, timeout=900, env=HF_ENV)
def peek_wavcaps() -> dict:
"""Peek streamable WavCaps AudioSet_SL mirrors: features + a sample (need an id field for
blacklist matching + a decodable audio field). Informs the ingestion path."""
import json
import os
from datasets import Audio, load_dataset
token = os.environ.get("HF_TOKEN") or None
# (repo, config, split)
candidates = [
("totoluo/wavcaps", "audioset_sl", "train"),
("TwinkStart/wavcaps-audioset", None, "test"),
("TwinkStart/wavcaps-soundbible", None, "test"),
]
report = {}
for repo, cfg, split in candidates:
key = f"{repo}:{cfg}" if cfg else repo
try:
ds = (load_dataset(repo, cfg, split=split, streaming=True, token=token) if cfg
else load_dataset(repo, split=split, streaming=True, token=token))
feats = list(ds.features) if ds.features else None
if feats and "audio" in feats:
ds = ds.cast_column("audio", Audio(decode=False))
sample = next(iter(ds))
text_fields = {k: str(v)[:100] for k, v in sample.items()
if isinstance(v, (str, int, float)) and k != "audio"}
report[key] = {"split": split, "features": feats, "sample_fields": text_fields}
print(f"OK {key} features={feats}")
except Exception as e: # noqa: BLE001
report[key] = f"ERR: {type(e).__name__}: {str(e)[:180]}"
print(f"FAIL {key}: {str(e)[:150]}")
print("WAVCAPS MIRRORS:\n" + json.dumps(report, indent=2, default=str))
return report
# --------------------------------------------------------------------------- #
# 1. warm_cache — pull the frozen Qwen weights onto the Volume once, so every
# later GPU run mounts them instantly instead of re-downloading.
# --------------------------------------------------------------------------- #
@app.function(volumes={VOL: volume}, secrets=[hf_secret], timeout=3600, env=HF_ENV)
def warm_cache() -> dict:
from huggingface_hub import snapshot_download
info = {}
for repo in (BASE_MODEL, AUDIO_MODEL):
# TODO(fusion): the Omni repo is large (~7B). If only the audio tower is needed,
# narrow with allow_patterns to cut download time/space once the layout is known.
path = snapshot_download(repo, cache_dir=HF_CACHE)
info[repo] = path
print(f"cached {repo} -> {path}")
volume.commit() # persist downloads to the Volume
return info
# --------------------------------------------------------------------------- #
# 2. preprocess — CPU fan-out: decode audio -> 128-mel -> store on the Volume,
# so the H100 never spends GPU-seconds on audio decode (the real bottleneck).
# --------------------------------------------------------------------------- #
@app.function(volumes={VOL: volume}, secrets=[hf_secret], cpu=4.0, memory=16384, timeout=3600, env=HF_ENV)
def preprocess(
shard: str = "audiocaps",
dataset_repo: str = "OpenSound/AudioCaps",
split: str = "train",
limit: int = 1200,
audio_col: str = "audio",
text_col: str = "caption",
task: str = "sound",
) -> dict:
"""Decode a real audio↔text dataset -> Whisper mel -> per-clip ``.pt`` on the Volume.
Default = AudioCaps (rich, UNIQUE per-clip captions -> clean contrastive, no class
collisions). The GPU never decodes audio — that cost is paid here once. The real Omni
WhisperFeatureExtractor is used so the mel matches what the frozen audio tower expects.
"""
import io
import itertools
import os
import librosa
import numpy as np
import soundfile as sf
import torch
from datasets import load_dataset, Audio
from transformers import AutoFeatureExtractor
token = os.environ.get("HF_TOKEN") or None
fe = AutoFeatureExtractor.from_pretrained(AUDIO_MODEL, trust_remote_code=True, token=token)
sr = fe.sampling_rate
# STREAMING: pull only the `limit` clips we consume (the full split is ~49K clips / many GB).
ds = load_dataset(dataset_repo, split=split, streaming=True, token=token)
print(f"streaming {dataset_repo}:{split} | features: {list(ds.features)}")
ds = ds.cast_column(audio_col, Audio(decode=False)) # raw bytes -> soundfile (no torchcodec)
ds = itertools.islice(ds, limit)
def decode_wav(a) -> np.ndarray:
if a.get("bytes"):
wav, sr0 = sf.read(io.BytesIO(a["bytes"]), dtype="float32")
else:
wav, sr0 = sf.read(a["path"], dtype="float32")
if wav.ndim > 1:
wav = wav.mean(axis=1)
if sr0 != sr:
wav = librosa.resample(wav, orig_sr=sr0, target_sr=sr)
return wav
out_dir = f"{FEATURES}/{shard}"
os.makedirs(out_dir, exist_ok=True)
n = 0
for i, row in enumerate(ds):
wav = decode_wav(row[audio_col])
caption = str(row[text_col]).replace("_", " ").strip()
feats = fe(wav, sampling_rate=sr, return_tensors="pt", return_attention_mask=True,
padding="max_length", truncation=True)
mel = feats["input_features"][0]
am = feats.get("attention_mask")
if am is not None: # trim padded mel to real length
L = int(am[0].sum().item()); mel = mel[:, :L]
torch.save({"mel": mel.contiguous(), "text": caption, "task": task},
f"{out_dir}/item-{i:05d}.pt")
n += 1
if i % 100 == 0:
print(f" {i}/{limit} '{caption[:50]}' mel{tuple(mel.shape)}")
volume.commit()
print(f"preprocessed {n} clips -> {out_dir}")
return {"shard": shard, "count": n, "dir": out_dir, "dataset": dataset_repo}
# --------------------------------------------------------------------------- #
# 4b. preprocess_wavcaps — REAL DATA scale-up: WavCaps (cvssp/WavCaps) -> mel.
# WavCaps ships caption JSONs + (multi-part) FLAC zips, NOT a streamable
# parquet. We download the source JSON + audio, apply the repo's eval-leakage
# BLACKLIST (AudioCaps/Clotho/ESC-50/VGGSound overlap), then mel like preprocess.
# Start with source="SoundBible" (1,232 clips, single zip) to validate the path.
# --------------------------------------------------------------------------- #
_WAVCAPS_JSON = {
"SoundBible": "json_files/SoundBible/sb_final.json",
"AudioSet_SL": "json_files/AudioSet_SL/as_final.json",
"BBC_Sound_Effects": "json_files/BBC_Sound_Effects/bbc_final.json",
"FreeSound": "json_files/FreeSound/fsd_final.json",
}
def _wavcaps_flac_name(source: str, item_id: str) -> str:
"""JSON id -> extracted flac filename (AudioSet ids carry a `.wav` we swap to `.flac`)."""
return item_id.replace(".wav", ".flac") if source == "AudioSet_SL" else f"{item_id}.flac"
def _flatten_ids(obj, acc: set) -> set:
"""Collect every leaf string (and its extension-stripped form) from a nested blacklist JSON."""
if isinstance(obj, str):
acc.add(obj); acc.add(obj.replace(".wav", "").replace(".flac", ""))
elif isinstance(obj, dict):
for v in obj.values():
_flatten_ids(v, acc)
elif isinstance(obj, (list, tuple)):
for v in obj:
_flatten_ids(v, acc)
return acc
@app.function(gpu="L4", volumes={VOL: volume}, secrets=[hf_secret], timeout=6 * 3600,
memory=32768, cpu=4.0, env=HF_ENV)
def ingest_clotho_eval(frame_shard: str = "clotho_eval5", zenodo_record: str = "4783391",
csv_name: str = "clotho_captions_evaluation.csv",
audio_7z: str = "clotho_audio_evaluation.7z",
audio_feature_layer: str = "post_proj", shard_size: int = 512,
limit: int = 0) -> dict:
"""Ingest the CANONICAL Clotho v2.1 EVALUATION set (1045 clips × 5 refs) straight from Zenodo —
the only source that carries all 5 captions per clip. Downloads the 5-caption CSV + evaluation
audio 7z, decodes each wav → Whisper mel → frozen tower → sharded frames + index with
`captions_multi` (5/clip) + `clip_ids` (file_name). Enables the published min-rank-over-5 A→T."""
import csv as _csv
import glob
import json
import os
import subprocess
import urllib.request
import librosa
import soundfile as sf
import torch
from transformers import AutoFeatureExtractor
from fusion_embedding.data import write_frame_shard
from fusion_embedding.hf_components import load_audio_tower
from fusion_embedding.paths import frames_dir
base = f"https://zenodo.org/records/{zenodo_record}/files"
work = "/tmp/clotho"; os.makedirs(work, exist_ok=True)
csv_path = os.path.join(work, csv_name); sevenz = os.path.join(work, audio_7z)
print(f"downloading {csv_name} ...", flush=True)
urllib.request.urlretrieve(f"{base}/{csv_name}?download=1", csv_path)
caps: dict = {}
with open(csv_path, newline="", encoding="utf-8") as fh: # file_name,caption_1..caption_5
reader = _csv.DictReader(fh)
for row in reader:
fn = row["file_name"]
caps[fn] = [row[f"caption_{i}"].strip() for i in range(1, 6)
if row.get(f"caption_{i}", "").strip()]
print(f"csv: {len(caps)} clips, cols={reader.fieldnames}", flush=True)
print(f"downloading {audio_7z} (~1.6GB) ...", flush=True)
urllib.request.urlretrieve(f"{base}/{audio_7z}?download=1", sevenz)
subprocess.run(["7z", "x", "-y", f"-o{work}", sevenz], check=True,
stdout=subprocess.DEVNULL)
wav_by_name = {os.path.basename(p): p for p in glob.glob(f"{work}/**/*.wav", recursive=True)}
print(f"extracted {len(wav_by_name)} wavs", flush=True)
token = os.environ.get("HF_TOKEN") or None
dev = "cuda"
fe = AutoFeatureExtractor.from_pretrained(AUDIO_MODEL, trust_remote_code=True, token=token)
sr = fe.sampling_rate
enc, _fe, d_audio = load_audio_tower(device=dev, dtype=torch.bfloat16,
audio_feature_layer=audio_feature_layer)
out_dir = frames_dir(frame_shard); os.makedirs(str(out_dir), exist_ok=True)
shard_recs, captions_multi, clip_ids, shard_files = [], [], [], []
n = n_missing = n_bad = 0
names = list(caps.keys())[:limit] if limit else list(caps.keys())
def _write():
if not shard_recs:
return
name = f"shard-{len(shard_files):04d}.pt"
write_frame_shard(out_dir / name, shard_recs, half=True)
shard_files.append(name); shard_recs.clear(); volume.commit()
for fn in names:
path = wav_by_name.get(fn)
if path is None:
n_missing += 1; continue
try:
wav, sr0 = sf.read(path, dtype="float32")
if wav.ndim > 1:
wav = wav.mean(axis=1)
if sr0 != sr:
wav = librosa.resample(wav, orig_sr=sr0, target_sr=sr)
except Exception: # noqa: BLE001
n_bad += 1; continue
feats = fe(wav, sampling_rate=sr, return_tensors="pt", return_attention_mask=True,
padding="max_length", truncation=True)
mel = feats["input_features"][0]
am = feats.get("attention_mask")
if am is not None:
mel = mel[:, : int(am[0].sum().item())]
with torch.no_grad():
frames, fmask = enc(mel.unsqueeze(0).to(dev),
torch.ones(1, mel.shape[1], dtype=torch.bool, device=dev))
t = int(fmask[0].sum().item())
shard_recs.append({"frames": frames[0, :t].cpu().contiguous(), "text": caps[fn][0], "task": "sound"})
captions_multi.append(caps[fn]); clip_ids.append(fn); n += 1
if len(shard_recs) >= shard_size:
_write()
if n % 200 == 0:
print(f" {n} clips missing={n_missing} bad={n_bad}", flush=True)
_write()
with open(str(out_dir / "index.json"), "w") as fh:
json.dump({"d_audio": d_audio, "shard_size": shard_size, "n_total": n,
"shards": shard_files, "captions_multi": captions_multi, "clip_ids": clip_ids,
"source_repo": f"zenodo:{zenodo_record}", "group_key": "file_name",
"captions": [c[0] for c in captions_multi]}, fh)
volume.commit()
result = {"frame_shard": frame_shard, "clips": n, "missing_audio": n_missing, "decode_fail": n_bad,
"total_captions": sum(len(c) for c in captions_multi),
"avg_caps_per_clip": round(sum(len(c) for c in captions_multi) / max(n, 1), 2),
"shards": len(shard_files), "d_audio": d_audio}
print(f"INGEST_CLOTHO5: {result}")
return result
@app.function(gpu="L4", volumes={VOL: volume}, secrets=[hf_secret], timeout=6 * 3600,
memory=32768, cpu=4.0, env=HF_ENV)
def ingest_mecat_eval(frame_shard: str = "mecat_eval", repo: str = "mispeech/MECAT-Caption",
revision: str = "be4a24c3f7309d74208e08a7cce49e72cb7a5834",
domains: str = "000,00A", audio_feature_layer: str = "post_proj",
shard_size: int = 512, limit: int = 0) -> dict:
"""Ingest the MECAT-Caption (arXiv:2507.23511, CC-BY-3.0) sound-only TEST domains as an
eval shard. Recon 2026-07-08: 000/test = 179 clips ("nothing present"), 00A/test = 848
clips (sound events, no speech/music) — OEA's published "MECAT 847 pairs" is almost
certainly the 00A test set (one clip lost their side). FLAC 16 kHz mono ~10.05 s; per
clip a JSON with 6 caption types x 3 paraphrases (speech/music are 'None' placeholders
on these domains).
``captions_multi`` stores the ORDERED single-caption protocol CANDIDATES per clip —
``caption_fields`` in the index documents the order: short_0, long_0, sound_0,
environment_0 (paraphrase [0] of each usable type). Score ONE variant via
``rescore_816(caption_index=k)``; leaving caption_index unset would min-rank over the
variants, which is NOT the published protocol. ``captions_all`` keeps every paraphrase
for auditability. Gallery variants (00A-only, leakage-excluded) are selected at score
time via ``id_allowlist_file`` on index ``clip_ids``."""
import io
import json
import os
import tarfile
import librosa
import soundfile as sf
import torch
from huggingface_hub import hf_hub_download
from transformers import AutoFeatureExtractor
from fusion_embedding.data import write_frame_shard
from fusion_embedding.hf_components import load_audio_tower
from fusion_embedding.paths import frames_dir
CAPTION_FIELDS = ["short", "long", "sound", "environment"]
work = "/tmp/mecat"; os.makedirs(work, exist_ok=True)
clips: list = [] # (clip_id, domain, flac_bytes, cap_json)
for dom in [d.strip() for d in domains.split(",") if d.strip()]:
tar_path = hf_hub_download(repo, f"{dom}/test_0000-0000000.tar.gz",
repo_type="dataset", revision=revision)
flacs, jsons = {}, {}
with tarfile.open(tar_path, "r:gz") as tf:
for m in tf.getmembers():
if not m.isfile():
continue
base = os.path.basename(m.name)
if base.endswith(".flac"):
flacs[base[:-5]] = tf.extractfile(m).read()
elif base.endswith(".json"):
jsons[base[:-5]] = json.loads(tf.extractfile(m).read().decode("utf-8"))
paired = sorted(set(flacs) & set(jsons))
print(f"domain {dom}: {len(flacs)} flac / {len(jsons)} json / {len(paired)} paired", flush=True)
clips.extend((cid, dom, flacs[cid], jsons[cid]) for cid in paired)
if limit:
clips = clips[:limit]
token = os.environ.get("HF_TOKEN") or None
dev = "cuda"
fe = AutoFeatureExtractor.from_pretrained(AUDIO_MODEL, trust_remote_code=True, token=token)
sr = fe.sampling_rate
enc, _fe, d_audio = load_audio_tower(device=dev, dtype=torch.bfloat16,
audio_feature_layer=audio_feature_layer)
out_dir = frames_dir(frame_shard); os.makedirs(str(out_dir), exist_ok=True)
shard_recs, captions_multi, captions_all, clip_ids, doms, shard_files = [], [], [], [], [], []
n = n_bad = 0
def _write():
if not shard_recs:
return
name = f"shard-{len(shard_files):04d}.pt"
write_frame_shard(out_dir / name, shard_recs, half=True)
shard_files.append(name); shard_recs.clear(); volume.commit()
for cid, dom, flac_bytes, cap in clips:
try:
wav, sr0 = sf.read(io.BytesIO(flac_bytes), dtype="float32")
if wav.ndim > 1:
wav = wav.mean(axis=1)
if sr0 != sr:
wav = librosa.resample(wav, orig_sr=sr0, target_sr=sr)
except Exception as e: # noqa: BLE001
n_bad += 1
if n_bad <= 3:
print(f"decode fail {cid}: {type(e).__name__}: {e}")
continue
feats = fe(wav, sampling_rate=sr, return_tensors="pt", return_attention_mask=True,
padding="max_length", truncation=True)
mel = feats["input_features"][0]
am = feats.get("attention_mask")
if am is not None:
mel = mel[:, : int(am[0].sum().item())]
with torch.no_grad():
frames, fmask = enc(mel.unsqueeze(0).to(dev),
torch.ones(1, mel.shape[1], dtype=torch.bool, device=dev))
t = int(fmask[0].sum().item())
variants = [str(cap[f][0]) for f in CAPTION_FIELDS]
shard_recs.append({"frames": frames[0, :t].cpu().contiguous(),
"text": variants[1], "task": "sound"}) # long_0 as the display text
captions_multi.append(variants)
captions_all.append({f: [str(x) for x in cap[f]] for f in CAPTION_FIELDS})
clip_ids.append(cid); doms.append(dom); n += 1