Initial commit of buddi-asr source
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .github/workflows/ci.yml +31 -0
- .gitignore +40 -0
- CHANGELOG.md +17 -0
- CONTRIBUTING.md +21 -0
- LICENSE +21 -0
- Makefile +25 -0
- README.fa.md +113 -0
- README.md +171 -0
- SECURITY.md +15 -0
- configs/mix.example.json +36 -0
- configs/train_base_full.json +55 -0
- configs/train_base_lora.json +64 -0
- configs/train_tiny_full.json +55 -0
- configs/train_tiny_lora.json +64 -0
- data/README.md +34 -0
- data/label_maps/abjad_ar.json +164 -0
- dataset-metadata.json +9 -0
- deploy/systemd/buddi-asr.service +30 -0
- docs/DATA_GOVERNANCE.md +52 -0
- docs/EXPERIMENT_PLAN.md +72 -0
- docs/GPU_TRAINING.fa.md +148 -0
- docs/GPU_TRAINING.md +58 -0
- docs/MODEL_CARD_TEMPLATE.md +63 -0
- docs/RASPBERRY_PI.md +99 -0
- pyproject.toml +64 -0
- scripts/build_pi_runtime.sh +28 -0
- scripts/train_gpu.sh +279 -0
- src/buddi_asr/__init__.py +3 -0
- src/buddi_asr/benchmark.py +168 -0
- src/buddi_asr/cli.py +341 -0
- src/buddi_asr/config.py +34 -0
- src/buddi_asr/data/__init__.py +1 -0
- src/buddi_asr/data/abjad.py +312 -0
- src/buddi_asr/data/local.py +116 -0
- src/buddi_asr/data/manifest.py +145 -0
- src/buddi_asr/data/mix.py +112 -0
- src/buddi_asr/data/split.py +184 -0
- src/buddi_asr/data/validate.py +70 -0
- src/buddi_asr/errors.py +17 -0
- src/buddi_asr/evaluate.py +130 -0
- src/buddi_asr/export.py +178 -0
- src/buddi_asr/metrics.py +87 -0
- src/buddi_asr/text/__init__.py +1 -0
- src/buddi_asr/text/normalization.py +72 -0
- src/buddi_asr/training/__init__.py +1 -0
- src/buddi_asr/training/audio.py +27 -0
- src/buddi_asr/training/collator.py +29 -0
- src/buddi_asr/training/config.py +143 -0
- src/buddi_asr/training/dataset.py +67 -0
- src/buddi_asr/training/runtime.py +238 -0
.github/workflows/ci.yml
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: ci
|
| 2 |
+
|
| 3 |
+
on:
|
| 4 |
+
push:
|
| 5 |
+
pull_request:
|
| 6 |
+
|
| 7 |
+
permissions:
|
| 8 |
+
contents: read
|
| 9 |
+
|
| 10 |
+
jobs:
|
| 11 |
+
core:
|
| 12 |
+
runs-on: ubuntu-latest
|
| 13 |
+
strategy:
|
| 14 |
+
matrix:
|
| 15 |
+
python-version: ["3.10", "3.12"]
|
| 16 |
+
steps:
|
| 17 |
+
- uses: actions/checkout@v4
|
| 18 |
+
- uses: actions/setup-python@v5
|
| 19 |
+
with:
|
| 20 |
+
python-version: ${{ matrix.python-version }}
|
| 21 |
+
cache: pip
|
| 22 |
+
- name: Install core package
|
| 23 |
+
run: python -m pip install -e .
|
| 24 |
+
- name: Unit tests
|
| 25 |
+
run: python -m unittest discover -s tests -v
|
| 26 |
+
- name: Compile check
|
| 27 |
+
run: python -m compileall -q src tests
|
| 28 |
+
- name: Shell syntax
|
| 29 |
+
run: bash -n scripts/*.sh
|
| 30 |
+
- name: CLI smoke test
|
| 31 |
+
run: buddi-asr --version
|
.gitignore
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Python
|
| 2 |
+
__pycache__/
|
| 3 |
+
*.py[cod]
|
| 4 |
+
*.egg-info/
|
| 5 |
+
.venv/
|
| 6 |
+
.ruff_cache/
|
| 7 |
+
.pytest_cache/
|
| 8 |
+
build/
|
| 9 |
+
dist/
|
| 10 |
+
|
| 11 |
+
# Editors / OS
|
| 12 |
+
.DS_Store
|
| 13 |
+
.idea/
|
| 14 |
+
.vscode/
|
| 15 |
+
|
| 16 |
+
# Secrets and child-data salts
|
| 17 |
+
.env
|
| 18 |
+
*.secret
|
| 19 |
+
*.salt
|
| 20 |
+
|
| 21 |
+
# Raw and processed child audio must never be committed
|
| 22 |
+
data/raw/
|
| 23 |
+
data/processed/
|
| 24 |
+
data/manifests/*.jsonl
|
| 25 |
+
data/manifests/*.csv
|
| 26 |
+
!data/manifests/.gitkeep
|
| 27 |
+
|
| 28 |
+
# Training / model artifacts
|
| 29 |
+
artifacts/
|
| 30 |
+
checkpoints/
|
| 31 |
+
outputs/
|
| 32 |
+
runs/
|
| 33 |
+
*.bin
|
| 34 |
+
*.ggml
|
| 35 |
+
*.gguf
|
| 36 |
+
*.safetensors
|
| 37 |
+
adapter_model.*
|
| 38 |
+
|
| 39 |
+
# Reports can contain derived utterance text; review before publishing
|
| 40 |
+
reports/
|
CHANGELOG.md
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Changelog
|
| 2 |
+
|
| 3 |
+
## 0.2.0 — 2026-08-24
|
| 4 |
+
|
| 5 |
+
- Added a one-command real CUDA runner for RunPod and Linux GPU servers.
|
| 6 |
+
- Added strict GPU/data preflight, BF16/FP16 auto-selection, and VRAM-aware batches.
|
| 7 |
+
- Added automatic complete-checkpoint discovery and multi-GPU Accelerate launch.
|
| 8 |
+
- Added Tiny/Base × LoRA/Full configs plus Persian and English GPU guides.
|
| 9 |
+
- Added runtime, dependency, CUDA, and accelerator provenance to training outputs.
|
| 10 |
+
|
| 11 |
+
## 0.1.0 — 2026-08-24
|
| 12 |
+
|
| 13 |
+
- Initial privacy-aware Abjad-Kids and consented-local-data pipeline.
|
| 14 |
+
- Speaker-disjoint split and unique weighted mixing.
|
| 15 |
+
- Whisper Tiny/Base LoRA and full training configs.
|
| 16 |
+
- Cohort WER/CER evaluation, LoRA merge, and whisper.cpp Q5 export.
|
| 17 |
+
- Raspberry Pi persistent-server deployment and warm concurrency benchmark.
|
CONTRIBUTING.md
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Contributing
|
| 2 |
+
|
| 3 |
+
Never attach child audio, direct identity, private manifests, salts, prediction reports, or trained weights to an issue or pull request.
|
| 4 |
+
|
| 5 |
+
Before opening a change:
|
| 6 |
+
|
| 7 |
+
```bash
|
| 8 |
+
python -m pip install -e .
|
| 9 |
+
make check
|
| 10 |
+
```
|
| 11 |
+
|
| 12 |
+
Data adapters must preserve these invariants:
|
| 13 |
+
|
| 14 |
+
- no direct identity in output records;
|
| 15 |
+
- stable pseudonymous speaker grouping;
|
| 16 |
+
- no silent missing-label fallback;
|
| 17 |
+
- no audio-file split before speaker split;
|
| 18 |
+
- deterministic output under a recorded seed;
|
| 19 |
+
- no implicit oversampling of child utterances.
|
| 20 |
+
|
| 21 |
+
Add a privacy regression test for every data-path change. Model-quality changes should include the immutable test revision, cohort metrics, latency hardware, and exact config rather than a single overall WER.
|
LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2026 Buddi contributors
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
SOFTWARE.
|
Makefile
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.PHONY: install install-data install-train test lint check check-shell clean
|
| 2 |
+
|
| 3 |
+
install:
|
| 4 |
+
python -m pip install -e .
|
| 5 |
+
|
| 6 |
+
install-data:
|
| 7 |
+
python -m pip install -e '.[data]'
|
| 8 |
+
|
| 9 |
+
install-train:
|
| 10 |
+
python -m pip install -e '.[train]'
|
| 11 |
+
|
| 12 |
+
test:
|
| 13 |
+
PYTHONPATH=src python -m unittest discover -s tests -v
|
| 14 |
+
|
| 15 |
+
lint:
|
| 16 |
+
python -m ruff check src tests
|
| 17 |
+
|
| 18 |
+
check: test
|
| 19 |
+
python -m compileall -q src tests
|
| 20 |
+
|
| 21 |
+
check-shell:
|
| 22 |
+
bash -n scripts/*.sh
|
| 23 |
+
|
| 24 |
+
clean:
|
| 25 |
+
find src tests -type d -name __pycache__ -prune -exec rm -r {} +
|
README.fa.md
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Buddi-ASR — مدل سبک تشخیص صدای کودک
|
| 2 |
+
|
| 3 |
+
این پروژه مسیر کامل ساخت `Buddi-ASR-Tiny-ArGulf-v1` را آماده میکند: صدای کودک عربی/خلیجی و انگلیسی را به متن تبدیل میکند، روی Whisper Tiny یا Base آموزش میبیند و در پایان یک فایل Q5 قابل اجرای Raspberry Pi میسازد.
|
| 4 |
+
|
| 5 |
+
نکته شفاف: داخل ریپو وزنِ ساختگی یا آموزشندیده قرار نگرفته است. وزن واقعی فقط بعد از اجرای آموزش روی GPU و قبولی در ارزیابی جدا از کودک ساخته میشود.
|
| 6 |
+
|
| 7 |
+
## چیزهایی که همین حالا آمادهاند
|
| 8 |
+
|
| 9 |
+
- دانلود و آمادهسازی Abjad-Kids و تبدیل تمام ۱۴۴ برچسب رومن به متن عربی؛
|
| 10 |
+
- حذف نام کودک از manifest و نام فایل پردازششده؛
|
| 11 |
+
- هش پایدار شناسه کودک با salt خصوصی؛
|
| 12 |
+
- جلوگیری قطعی از حضور یک کودک در train و test؛
|
| 13 |
+
- ورود دیتای عمانی فقط با ستون رضایت والدین؛
|
| 14 |
+
- آموزش LoRA و Full Fine-tune برای Whisper Tiny/Base؛
|
| 15 |
+
- اجرای یکفرمانی GPU با preflight، تنظیم batch از روی VRAM، ادامهٔ خودکار checkpoint و پشتیبانی چند GPU؛
|
| 16 |
+
- محاسبه WER و CER کلی و به تفکیک زبان، لهجه، سن، دستگاه و منبع؛
|
| 17 |
+
- merge کردن LoRA و خروجی `q5_0` برای `whisper.cpp`؛
|
| 18 |
+
- تستهای خودکار و سرویس امن Raspberry Pi.
|
| 19 |
+
|
| 20 |
+
## اجرای سریع
|
| 21 |
+
|
| 22 |
+
```bash
|
| 23 |
+
python -m venv .venv
|
| 24 |
+
source .venv/bin/activate
|
| 25 |
+
python -m pip install --upgrade pip
|
| 26 |
+
python -m pip install -e '.[data]'
|
| 27 |
+
openssl rand -hex 32 > .buddi-speaker.salt
|
| 28 |
+
```
|
| 29 |
+
|
| 30 |
+
دیتاست را دانلود و ناشناسسازی کن:
|
| 31 |
+
|
| 32 |
+
```bash
|
| 33 |
+
buddi-asr download-abjad data/raw/abjad-kids
|
| 34 |
+
|
| 35 |
+
buddi-asr prepare-abjad \
|
| 36 |
+
data/raw/abjad-kids \
|
| 37 |
+
data/manifests/abjad.jsonl \
|
| 38 |
+
--processed-audio-dir data/processed/abjad \
|
| 39 |
+
--salt-file .buddi-speaker.salt \
|
| 40 |
+
--audit-output reports/abjad-audit.json
|
| 41 |
+
|
| 42 |
+
buddi-asr validate data/manifests/abjad.jsonl --report reports/abjad-validation.json
|
| 43 |
+
buddi-asr split data/manifests/abjad.jsonl data/manifests/splits --seed 42
|
| 44 |
+
```
|
| 45 |
+
|
| 46 |
+
آموزش نسخه Tiny با LoRA:
|
| 47 |
+
|
| 48 |
+
```bash
|
| 49 |
+
./scripts/train_gpu.sh tiny-lora --smoke
|
| 50 |
+
./scripts/train_gpu.sh tiny-lora
|
| 51 |
+
```
|
| 52 |
+
|
| 53 |
+
راهنمای کامل RunPod، تنظیم حافظه، ادامه بعد از قطع شدن و مسیر خروجیها در [آموزش واقعی GPU](docs/GPU_TRAINING.fa.md) است.
|
| 54 |
+
|
| 55 |
+
ارزیابی نهایی روی کودکهایی که مدل هرگز صدایشان را ندیده است:
|
| 56 |
+
|
| 57 |
+
```bash
|
| 58 |
+
buddi-asr evaluate \
|
| 59 |
+
artifacts/tiny-lora/final \
|
| 60 |
+
data/manifests/splits/test.jsonl \
|
| 61 |
+
reports/tiny-lora-test
|
| 62 |
+
```
|
| 63 |
+
|
| 64 |
+
تبدیل برای Raspberry Pi:
|
| 65 |
+
|
| 66 |
+
```bash
|
| 67 |
+
buddi-asr merge-lora openai/whisper-tiny artifacts/tiny-lora/final artifacts/tiny-merged
|
| 68 |
+
|
| 69 |
+
git clone https://github.com/openai/whisper.git vendor/openai-whisper
|
| 70 |
+
git clone https://github.com/ggml-org/whisper.cpp.git vendor/whisper.cpp
|
| 71 |
+
cmake -S vendor/whisper.cpp -B vendor/whisper.cpp/build -DGGML_BLAS=1
|
| 72 |
+
cmake --build vendor/whisper.cpp/build -j --config Release
|
| 73 |
+
|
| 74 |
+
buddi-asr export-whisper-cpp \
|
| 75 |
+
artifacts/tiny-merged vendor/whisper.cpp vendor/openai-whisper artifacts/pi \
|
| 76 |
+
--name buddi-asr-tiny-argulf-v1 --quantization q5_0
|
| 77 |
+
```
|
| 78 |
+
|
| 79 |
+
## نکته مهمی که در Abjad-Kids پیدا شد
|
| 80 |
+
|
| 81 |
+
نسخه فعلی مخزن ۴۰٬۶۴۶ ردیف و ۱۴۴ برچسب دارد، ولی مقاله ۴۶٬۳۹۷ نمونه و ۱۴۱ کلاس گفته است. همچنین ستون رسمی `speaker_id` ندارد و اسم بعضی کودکان داخل نام فایل آمده است. audit کامل هر ۴۰٬۶۴۶ ردیف را بدون خطا parse کرد: ۴۰٬۵۶۸ ردیف گروه گوینده قابل استخراج دارند و ۷۸ ردیف فقط session دارند. کد نامها را وارد manifest نمیکند و همان ۷۸ مورد را برای بازبینی هشدار میدهد.
|
| 82 |
+
|
| 83 |
+
هفت نگاشت شنیداریِ مبهم هم داخل `data/label_maps/abjad_ar.json` با `review_required` علامت خوردهاند. قبل از آموزش نهایی باید چند نمونه از آن کلاسها شنیده و متن قطعی شود.
|
| 84 |
+
|
| 85 |
+
## دیتای اختصاصی عمان
|
| 86 |
+
|
| 87 |
+
CSV خصوصی تو باید حداقل این ستونها را داشته باشد:
|
| 88 |
+
|
| 89 |
+
```csv
|
| 90 |
+
audio,text,speaker_key,language,consent_basis,dialect,age_group
|
| 91 |
+
audio/001.wav,بودي شنو يعني ديناصور,anonymous-001,ar,verified_parental_consent,gulf_omani,6-8
|
| 92 |
+
```
|
| 93 |
+
|
| 94 |
+
سپس:
|
| 95 |
+
|
| 96 |
+
```bash
|
| 97 |
+
buddi-asr import-local private/omani.csv data/manifests/omani.jsonl \
|
| 98 |
+
--processed-audio-dir data/processed/omani \
|
| 99 |
+
--salt-file .buddi-speaker.salt \
|
| 100 |
+
--source-name buddi_omani_child
|
| 101 |
+
```
|
| 102 |
+
|
| 103 |
+
نام واقعی، شماره تماس، ایمیل یا نام ��الدین نباید داخل فایل training باشد. ستون ناشناخته عمداً رد میشود تا اطلاعات هویتی تصادفی وارد خروجی نشود.
|
| 104 |
+
|
| 105 |
+
## انتخاب پیشنهادی من
|
| 106 |
+
|
| 107 |
+
1. اول Tiny LoRA را بهعنوان baseline بساز؛
|
| 108 |
+
2. بعد Base Full را با همان split آموزش بده؛
|
| 109 |
+
3. روی test یکسان، WER/CER و latency را مقایسه کن؛
|
| 110 |
+
4. اگر Base خطای کودک را محسوس کم کرد و روی Pi هنوز latency قابل قبول داشت، نسخه Base Q5 را انتخاب کن؛
|
| 111 |
+
5. ادعای «عمانی/خلیجی» فقط بعد از تست واقعی روی کودکان عمانیِ دیدهنشده منتشر شود.
|
| 112 |
+
|
| 113 |
+
راهنمای دقیقتر آزمایش در [docs/EXPERIMENT_PLAN.md](docs/EXPERIMENT_PLAN.md) و نصب Pi در [docs/RASPBERRY_PI.md](docs/RASPBERRY_PI.md) است.
|
README.md
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Buddi-ASR
|
| 2 |
+
|
| 3 |
+
> A privacy-aware training and deployment pipeline for a small Arabic/Gulf-Arabic + English child-speech model.
|
| 4 |
+
|
| 5 |
+
[فارسی](README.fa.md) · [GPU training](docs/GPU_TRAINING.md) · [Data governance](docs/DATA_GOVERNANCE.md) · [Experiment plan](docs/EXPERIMENT_PLAN.md) · [Raspberry Pi](docs/RASPBERRY_PI.md)
|
| 6 |
+
|
| 7 |
+
Buddi-ASR turns multilingual Whisper Tiny or Base into a domain model for short child utterances, then exports the merged checkpoint to a quantized `whisper.cpp` artifact for Raspberry Pi, mobile, or server inference.
|
| 8 |
+
|
| 9 |
+
This repository contains the reproducible pipeline, not fabricated model weights. A real `Buddi-ASR-Tiny-ArGulf-v1` checkpoint must be trained on licensed/consented audio and accepted only after speaker-disjoint evaluation.
|
| 10 |
+
|
| 11 |
+
```mermaid
|
| 12 |
+
flowchart TD
|
| 13 |
+
A["Licensed + consented audio"] --> B["PII-safe manifests"]
|
| 14 |
+
B --> C["Speaker-disjoint split"]
|
| 15 |
+
C --> D["Whisper Tiny/Base adaptation"]
|
| 16 |
+
D --> E["WER/CER by cohort"]
|
| 17 |
+
E --> F["Merge + Q5 export"]
|
| 18 |
+
F --> G["Raspberry Pi / mobile"]
|
| 19 |
+
```
|
| 20 |
+
|
| 21 |
+
## What is implemented
|
| 22 |
+
|
| 23 |
+
- Abjad-Kids download, 144-label audit, Romanized-label to Arabic conversion, and WAV duration probing.
|
| 24 |
+
- HMAC pseudonymization, anonymized processed filenames, consent-gated local CSV import, and PII-blocking manifest validation.
|
| 25 |
+
- Deterministic label-aware splitting with strict speaker isolation.
|
| 26 |
+
- Weighted dataset mixing without silently duplicating child utterances.
|
| 27 |
+
- Whisper Tiny/Base LoRA and full fine-tuning with Arabic/English per-example prompt tokens, waveform augmentation, early stopping, and reproducible configs.
|
| 28 |
+
- One-command CUDA training for RunPod/servers with VRAM-aware batch sizing, strict preflight, multi-GPU launch, automatic checkpoint resume, and runtime provenance.
|
| 29 |
+
- Normalized micro-averaged WER/CER overall and by language, dialect, age group, source, and category.
|
| 30 |
+
- Safe LoRA merge, official `whisper.cpp` conversion, Q4/Q5/Q8 quantization, artifact metadata, and SHA-256 checksum.
|
| 31 |
+
- Dependency-free unit tests for all data-critical paths and a hardened Raspberry Pi service example.
|
| 32 |
+
|
| 33 |
+
## Important dataset finding
|
| 34 |
+
|
| 35 |
+
The current Abjad-Kids repository reports 40,646 rows and 144 observed labels, while the associated 2026 paper reports 46,397 samples and 141 classes. The upstream CSV files also lack a documented speaker column; this project groups speakers from filenames only as an explicit heuristic. A full CSV audit parsed every row and found 40,568 filename-grouped rows plus 78 session-only rows that require special review.
|
| 36 |
+
|
| 37 |
+
Do not publish final metrics until:
|
| 38 |
+
|
| 39 |
+
1. the seven ambiguous label mappings in `data/label_maps/abjad_ar.json` have been checked by listening;
|
| 40 |
+
2. session-only speaker groups have been resolved with anonymous overrides or acknowledged as a limitation;
|
| 41 |
+
3. train, validation, and test show zero speaker overlap.
|
| 42 |
+
|
| 43 |
+
## Quick start
|
| 44 |
+
|
| 45 |
+
Python 3.10–3.12 is supported. Data utilities have no third-party runtime dependencies.
|
| 46 |
+
|
| 47 |
+
```bash
|
| 48 |
+
python -m venv .venv
|
| 49 |
+
source .venv/bin/activate
|
| 50 |
+
python -m pip install --upgrade pip
|
| 51 |
+
python -m pip install -e '.[data]'
|
| 52 |
+
```
|
| 53 |
+
|
| 54 |
+
Create a stable private salt. Losing or changing it changes speaker groups; committing it defeats pseudonymization.
|
| 55 |
+
|
| 56 |
+
```bash
|
| 57 |
+
openssl rand -hex 32 > .buddi-speaker.salt
|
| 58 |
+
```
|
| 59 |
+
|
| 60 |
+
Download and prepare Abjad-Kids:
|
| 61 |
+
|
| 62 |
+
```bash
|
| 63 |
+
buddi-asr download-abjad data/raw/abjad-kids
|
| 64 |
+
|
| 65 |
+
buddi-asr prepare-abjad \
|
| 66 |
+
data/raw/abjad-kids \
|
| 67 |
+
data/manifests/abjad.jsonl \
|
| 68 |
+
--processed-audio-dir data/processed/abjad \
|
| 69 |
+
--salt-file .buddi-speaker.salt \
|
| 70 |
+
--audit-output reports/abjad-audit.json
|
| 71 |
+
|
| 72 |
+
buddi-asr validate data/manifests/abjad.jsonl --report reports/abjad-validation.json
|
| 73 |
+
```
|
| 74 |
+
|
| 75 |
+
Create speaker-disjoint sets:
|
| 76 |
+
|
| 77 |
+
```bash
|
| 78 |
+
buddi-asr split data/manifests/abjad.jsonl data/manifests/splits \
|
| 79 |
+
--train 0.8 --validation 0.1 --test 0.1 --seed 42
|
| 80 |
+
```
|
| 81 |
+
|
| 82 |
+
Install GPU training dependencies and run the Tiny LoRA baseline:
|
| 83 |
+
|
| 84 |
+
```bash
|
| 85 |
+
./scripts/train_gpu.sh tiny-lora --smoke
|
| 86 |
+
./scripts/train_gpu.sh tiny-lora
|
| 87 |
+
```
|
| 88 |
+
|
| 89 |
+
The runner prepares Abjad-Kids when split manifests are absent. See the [real GPU training guide](docs/GPU_TRAINING.md) before renting a GPU or adding private Omani data.
|
| 90 |
+
|
| 91 |
+
Evaluate exactly once on the held-out test set after experiment selection:
|
| 92 |
+
|
| 93 |
+
```bash
|
| 94 |
+
buddi-asr evaluate \
|
| 95 |
+
artifacts/tiny-lora/final \
|
| 96 |
+
data/manifests/splits/test.jsonl \
|
| 97 |
+
reports/tiny-lora-test
|
| 98 |
+
```
|
| 99 |
+
|
| 100 |
+
Merge the adapter and export Q5 for the Pi:
|
| 101 |
+
|
| 102 |
+
```bash
|
| 103 |
+
buddi-asr merge-lora \
|
| 104 |
+
openai/whisper-tiny \
|
| 105 |
+
artifacts/tiny-lora/final \
|
| 106 |
+
artifacts/tiny-merged
|
| 107 |
+
|
| 108 |
+
git clone https://github.com/openai/whisper.git vendor/openai-whisper
|
| 109 |
+
git clone https://github.com/ggml-org/whisper.cpp.git vendor/whisper.cpp
|
| 110 |
+
cmake -S vendor/whisper.cpp -B vendor/whisper.cpp/build -DGGML_BLAS=1
|
| 111 |
+
cmake --build vendor/whisper.cpp/build -j --config Release
|
| 112 |
+
|
| 113 |
+
buddi-asr export-whisper-cpp \
|
| 114 |
+
artifacts/tiny-merged \
|
| 115 |
+
vendor/whisper.cpp \
|
| 116 |
+
vendor/openai-whisper \
|
| 117 |
+
artifacts/pi \
|
| 118 |
+
--name buddi-asr-tiny-argulf-v1 \
|
| 119 |
+
--quantization q5_0
|
| 120 |
+
```
|
| 121 |
+
|
| 122 |
+
## Add consented Omani/Gulf child speech
|
| 123 |
+
|
| 124 |
+
Use a private CSV with these required columns:
|
| 125 |
+
|
| 126 |
+
```csv
|
| 127 |
+
audio,text,speaker_key,language,consent_basis,dialect,age_group,device,noise_level
|
| 128 |
+
audio/001.wav,بودي أبغى قصة,anonymous-local-001,ar,verified_parental_consent,gulf_omani,6-8,iphone,quiet
|
| 129 |
+
```
|
| 130 |
+
|
| 131 |
+
`speaker_key` is pseudonymized and never written to the output. Unknown columns are rejected to prevent accidental identity export.
|
| 132 |
+
|
| 133 |
+
```bash
|
| 134 |
+
buddi-asr import-local private/omani.csv data/manifests/omani.jsonl \
|
| 135 |
+
--processed-audio-dir data/processed/omani \
|
| 136 |
+
--salt-file .buddi-speaker.salt \
|
| 137 |
+
--source-name buddi_omani_child
|
| 138 |
+
```
|
| 139 |
+
|
| 140 |
+
## Repository map
|
| 141 |
+
|
| 142 |
+
```text
|
| 143 |
+
configs/ Reproducible Tiny LoRA, Base full, and mixture configs
|
| 144 |
+
data/label_maps/ Audited Abjad Romanized-to-Arabic transcript map
|
| 145 |
+
deploy/systemd/ Hardened local-only Pi service
|
| 146 |
+
docs/ Governance, experiment, model-card, and Pi guides
|
| 147 |
+
scripts/train_gpu.sh One-command real CUDA training and recovery
|
| 148 |
+
src/buddi_asr/data/ Ingestion, manifest, split, mix, validation
|
| 149 |
+
src/buddi_asr/training/ Audio loading, augmentation, collator, trainer
|
| 150 |
+
src/buddi_asr/ CLI, metrics, evaluation, merge, export
|
| 151 |
+
tests/ Dependency-free unit and privacy regression tests
|
| 152 |
+
```
|
| 153 |
+
|
| 154 |
+
## Non-goals
|
| 155 |
+
|
| 156 |
+
- Training from scratch: Whisper pretraining is deliberately reused.
|
| 157 |
+
- Claiming “Gulf child ASR” from Abjad-Kids alone: it is short educational vocabulary, not Omani conversation.
|
| 158 |
+
- Speaker recognition, emotion surveillance, or child profiling.
|
| 159 |
+
- Sending raw child audio to third-party telemetry by default.
|
| 160 |
+
|
| 161 |
+
## Verification
|
| 162 |
+
|
| 163 |
+
```bash
|
| 164 |
+
make check
|
| 165 |
+
```
|
| 166 |
+
|
| 167 |
+
The CI suite runs without downloading models or child data. GPU/model integration should additionally be run on the target training image before a release.
|
| 168 |
+
|
| 169 |
+
## License
|
| 170 |
+
|
| 171 |
+
Code is MIT. Model and dataset releases must separately document every upstream model/dataset license and consent restriction. A code license never grants permission to publish child audio.
|
SECURITY.md
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Security policy
|
| 2 |
+
|
| 3 |
+
Report code vulnerabilities privately to the repository owner. Do not include real child audio, transcripts, consent records, tokens, salts, or infrastructure credentials in the report.
|
| 4 |
+
|
| 5 |
+
## Sensitive assets
|
| 6 |
+
|
| 7 |
+
Treat the following as secrets or restricted personal data:
|
| 8 |
+
|
| 9 |
+
- raw and processed child audio;
|
| 10 |
+
- reversible speaker mappings and consent registries;
|
| 11 |
+
- pseudonymization salts;
|
| 12 |
+
- full prediction reports;
|
| 13 |
+
- private dataset URLs or access tokens.
|
| 14 |
+
|
| 15 |
+
The included Pi service binds to localhost. Authentication, upload limits, rate limiting, and parental authorization belong in the Buddi API in front of it. Never expose `whisper-server` directly to the public internet.
|
configs/mix.example.json
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"seed": 42,
|
| 3 |
+
"target_size": 10000,
|
| 4 |
+
"sources": [
|
| 5 |
+
{
|
| 6 |
+
"name": "general_arabic",
|
| 7 |
+
"manifest": "../data/manifests/general_arabic_train.jsonl",
|
| 8 |
+
"split": "train",
|
| 9 |
+
"weight": 0.4
|
| 10 |
+
},
|
| 11 |
+
{
|
| 12 |
+
"name": "gulf_arabic",
|
| 13 |
+
"manifest": "../data/manifests/gulf_arabic_train.jsonl",
|
| 14 |
+
"split": "train",
|
| 15 |
+
"weight": 0.25
|
| 16 |
+
},
|
| 17 |
+
{
|
| 18 |
+
"name": "arabic_child_conversation",
|
| 19 |
+
"manifest": "../data/manifests/arabic_child_train.jsonl",
|
| 20 |
+
"split": "train",
|
| 21 |
+
"weight": 0.2
|
| 22 |
+
},
|
| 23 |
+
{
|
| 24 |
+
"name": "abjad_kids",
|
| 25 |
+
"manifest": "../data/manifests/abjad_train.jsonl",
|
| 26 |
+
"split": "train",
|
| 27 |
+
"weight": 0.1
|
| 28 |
+
},
|
| 29 |
+
{
|
| 30 |
+
"name": "english_child",
|
| 31 |
+
"manifest": "../data/manifests/english_child_train.jsonl",
|
| 32 |
+
"split": "train",
|
| 33 |
+
"weight": 0.05
|
| 34 |
+
}
|
| 35 |
+
]
|
| 36 |
+
}
|
configs/train_base_full.json
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"model_name_or_path": "openai/whisper-base",
|
| 3 |
+
"train_manifest": "../data/manifests/splits/train.jsonl",
|
| 4 |
+
"eval_manifest": "../data/manifests/splits/validation.jsonl",
|
| 5 |
+
"output_dir": "../artifacts/base-full",
|
| 6 |
+
"method": "full",
|
| 7 |
+
"task": "transcribe",
|
| 8 |
+
"language_prompts": {
|
| 9 |
+
"ar": "arabic",
|
| 10 |
+
"en": "english",
|
| 11 |
+
"ar-en": "arabic"
|
| 12 |
+
},
|
| 13 |
+
"seed": 42,
|
| 14 |
+
"sampling_rate": 16000,
|
| 15 |
+
"max_audio_seconds": 20.0,
|
| 16 |
+
"per_device_train_batch_size": 8,
|
| 17 |
+
"per_device_eval_batch_size": 8,
|
| 18 |
+
"gradient_accumulation_steps": 4,
|
| 19 |
+
"learning_rate": 0.00001,
|
| 20 |
+
"num_train_epochs": 8,
|
| 21 |
+
"max_steps": -1,
|
| 22 |
+
"warmup_ratio": 0.05,
|
| 23 |
+
"weight_decay": 0.01,
|
| 24 |
+
"logging_steps": 25,
|
| 25 |
+
"eval_steps": 250,
|
| 26 |
+
"save_steps": 250,
|
| 27 |
+
"save_total_limit": 2,
|
| 28 |
+
"generation_max_length": 128,
|
| 29 |
+
"fp16": true,
|
| 30 |
+
"bf16": false,
|
| 31 |
+
"gradient_checkpointing": true,
|
| 32 |
+
"freeze_feature_encoder": false,
|
| 33 |
+
"dataloader_num_workers": 0,
|
| 34 |
+
"dataloader_pin_memory": true,
|
| 35 |
+
"eval_accumulation_steps": 1,
|
| 36 |
+
"tf32": true,
|
| 37 |
+
"ddp_find_unused_parameters": false,
|
| 38 |
+
"early_stopping_patience": 4,
|
| 39 |
+
"report_to": [
|
| 40 |
+
"tensorboard"
|
| 41 |
+
],
|
| 42 |
+
"resume_from_checkpoint": "auto",
|
| 43 |
+
"augmentation": {
|
| 44 |
+
"probability": 0.6,
|
| 45 |
+
"gain_db_min": -6.0,
|
| 46 |
+
"gain_db_max": 6.0,
|
| 47 |
+
"noise_snr_db_min": 12.0,
|
| 48 |
+
"noise_snr_db_max": 30.0,
|
| 49 |
+
"speed_factors": [
|
| 50 |
+
0.9,
|
| 51 |
+
1.0,
|
| 52 |
+
1.1
|
| 53 |
+
]
|
| 54 |
+
}
|
| 55 |
+
}
|
configs/train_base_lora.json
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"model_name_or_path": "openai/whisper-base",
|
| 3 |
+
"train_manifest": "../data/manifests/splits/train.jsonl",
|
| 4 |
+
"eval_manifest": "../data/manifests/splits/validation.jsonl",
|
| 5 |
+
"output_dir": "../artifacts/base-lora",
|
| 6 |
+
"method": "lora",
|
| 7 |
+
"task": "transcribe",
|
| 8 |
+
"language_prompts": {
|
| 9 |
+
"ar": "arabic",
|
| 10 |
+
"en": "english",
|
| 11 |
+
"ar-en": "arabic"
|
| 12 |
+
},
|
| 13 |
+
"seed": 42,
|
| 14 |
+
"sampling_rate": 16000,
|
| 15 |
+
"max_audio_seconds": 20.0,
|
| 16 |
+
"per_device_train_batch_size": 8,
|
| 17 |
+
"per_device_eval_batch_size": 4,
|
| 18 |
+
"gradient_accumulation_steps": 4,
|
| 19 |
+
"learning_rate": 0.0001,
|
| 20 |
+
"num_train_epochs": 10,
|
| 21 |
+
"max_steps": -1,
|
| 22 |
+
"warmup_ratio": 0.05,
|
| 23 |
+
"weight_decay": 0.01,
|
| 24 |
+
"logging_steps": 25,
|
| 25 |
+
"eval_steps": 250,
|
| 26 |
+
"save_steps": 250,
|
| 27 |
+
"save_total_limit": 2,
|
| 28 |
+
"generation_max_length": 128,
|
| 29 |
+
"fp16": true,
|
| 30 |
+
"bf16": false,
|
| 31 |
+
"gradient_checkpointing": true,
|
| 32 |
+
"freeze_feature_encoder": true,
|
| 33 |
+
"dataloader_num_workers": 0,
|
| 34 |
+
"dataloader_pin_memory": true,
|
| 35 |
+
"eval_accumulation_steps": 1,
|
| 36 |
+
"tf32": true,
|
| 37 |
+
"ddp_find_unused_parameters": false,
|
| 38 |
+
"early_stopping_patience": 4,
|
| 39 |
+
"report_to": [
|
| 40 |
+
"tensorboard"
|
| 41 |
+
],
|
| 42 |
+
"resume_from_checkpoint": "auto",
|
| 43 |
+
"lora": {
|
| 44 |
+
"rank": 16,
|
| 45 |
+
"alpha": 32,
|
| 46 |
+
"dropout": 0.05,
|
| 47 |
+
"target_modules": [
|
| 48 |
+
"q_proj",
|
| 49 |
+
"v_proj"
|
| 50 |
+
]
|
| 51 |
+
},
|
| 52 |
+
"augmentation": {
|
| 53 |
+
"probability": 0.6,
|
| 54 |
+
"gain_db_min": -6.0,
|
| 55 |
+
"gain_db_max": 6.0,
|
| 56 |
+
"noise_snr_db_min": 12.0,
|
| 57 |
+
"noise_snr_db_max": 30.0,
|
| 58 |
+
"speed_factors": [
|
| 59 |
+
0.9,
|
| 60 |
+
1.0,
|
| 61 |
+
1.1
|
| 62 |
+
]
|
| 63 |
+
}
|
| 64 |
+
}
|
configs/train_tiny_full.json
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"model_name_or_path": "openai/whisper-tiny",
|
| 3 |
+
"train_manifest": "../data/manifests/splits/train.jsonl",
|
| 4 |
+
"eval_manifest": "../data/manifests/splits/validation.jsonl",
|
| 5 |
+
"output_dir": "../artifacts/tiny-full",
|
| 6 |
+
"method": "full",
|
| 7 |
+
"task": "transcribe",
|
| 8 |
+
"language_prompts": {
|
| 9 |
+
"ar": "arabic",
|
| 10 |
+
"en": "english",
|
| 11 |
+
"ar-en": "arabic"
|
| 12 |
+
},
|
| 13 |
+
"seed": 42,
|
| 14 |
+
"sampling_rate": 16000,
|
| 15 |
+
"max_audio_seconds": 20.0,
|
| 16 |
+
"per_device_train_batch_size": 8,
|
| 17 |
+
"per_device_eval_batch_size": 4,
|
| 18 |
+
"gradient_accumulation_steps": 4,
|
| 19 |
+
"learning_rate": 0.00001,
|
| 20 |
+
"num_train_epochs": 8,
|
| 21 |
+
"max_steps": -1,
|
| 22 |
+
"warmup_ratio": 0.05,
|
| 23 |
+
"weight_decay": 0.01,
|
| 24 |
+
"logging_steps": 25,
|
| 25 |
+
"eval_steps": 250,
|
| 26 |
+
"save_steps": 250,
|
| 27 |
+
"save_total_limit": 2,
|
| 28 |
+
"generation_max_length": 128,
|
| 29 |
+
"fp16": true,
|
| 30 |
+
"bf16": false,
|
| 31 |
+
"gradient_checkpointing": true,
|
| 32 |
+
"freeze_feature_encoder": false,
|
| 33 |
+
"dataloader_num_workers": 0,
|
| 34 |
+
"dataloader_pin_memory": true,
|
| 35 |
+
"eval_accumulation_steps": 1,
|
| 36 |
+
"tf32": true,
|
| 37 |
+
"ddp_find_unused_parameters": false,
|
| 38 |
+
"early_stopping_patience": 4,
|
| 39 |
+
"report_to": [
|
| 40 |
+
"tensorboard"
|
| 41 |
+
],
|
| 42 |
+
"resume_from_checkpoint": "auto",
|
| 43 |
+
"augmentation": {
|
| 44 |
+
"probability": 0.6,
|
| 45 |
+
"gain_db_min": -6.0,
|
| 46 |
+
"gain_db_max": 6.0,
|
| 47 |
+
"noise_snr_db_min": 12.0,
|
| 48 |
+
"noise_snr_db_max": 30.0,
|
| 49 |
+
"speed_factors": [
|
| 50 |
+
0.9,
|
| 51 |
+
1.0,
|
| 52 |
+
1.1
|
| 53 |
+
]
|
| 54 |
+
}
|
| 55 |
+
}
|
configs/train_tiny_lora.json
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"model_name_or_path": "openai/whisper-tiny",
|
| 3 |
+
"train_manifest": "../data/manifests/splits/train.jsonl",
|
| 4 |
+
"eval_manifest": "../data/manifests/splits/validation.jsonl",
|
| 5 |
+
"output_dir": "../artifacts/tiny-lora",
|
| 6 |
+
"method": "lora",
|
| 7 |
+
"task": "transcribe",
|
| 8 |
+
"language_prompts": {
|
| 9 |
+
"ar": "arabic",
|
| 10 |
+
"en": "english",
|
| 11 |
+
"ar-en": "arabic"
|
| 12 |
+
},
|
| 13 |
+
"seed": 42,
|
| 14 |
+
"sampling_rate": 16000,
|
| 15 |
+
"max_audio_seconds": 20.0,
|
| 16 |
+
"per_device_train_batch_size": 16,
|
| 17 |
+
"per_device_eval_batch_size": 8,
|
| 18 |
+
"gradient_accumulation_steps": 2,
|
| 19 |
+
"learning_rate": 0.0001,
|
| 20 |
+
"num_train_epochs": 10,
|
| 21 |
+
"max_steps": -1,
|
| 22 |
+
"warmup_ratio": 0.05,
|
| 23 |
+
"weight_decay": 0.01,
|
| 24 |
+
"logging_steps": 25,
|
| 25 |
+
"eval_steps": 250,
|
| 26 |
+
"save_steps": 250,
|
| 27 |
+
"save_total_limit": 2,
|
| 28 |
+
"generation_max_length": 128,
|
| 29 |
+
"fp16": true,
|
| 30 |
+
"bf16": false,
|
| 31 |
+
"gradient_checkpointing": true,
|
| 32 |
+
"freeze_feature_encoder": true,
|
| 33 |
+
"dataloader_num_workers": 0,
|
| 34 |
+
"dataloader_pin_memory": true,
|
| 35 |
+
"eval_accumulation_steps": 1,
|
| 36 |
+
"tf32": true,
|
| 37 |
+
"ddp_find_unused_parameters": false,
|
| 38 |
+
"early_stopping_patience": 4,
|
| 39 |
+
"report_to": [
|
| 40 |
+
"tensorboard"
|
| 41 |
+
],
|
| 42 |
+
"resume_from_checkpoint": "auto",
|
| 43 |
+
"lora": {
|
| 44 |
+
"rank": 16,
|
| 45 |
+
"alpha": 32,
|
| 46 |
+
"dropout": 0.05,
|
| 47 |
+
"target_modules": [
|
| 48 |
+
"q_proj",
|
| 49 |
+
"v_proj"
|
| 50 |
+
]
|
| 51 |
+
},
|
| 52 |
+
"augmentation": {
|
| 53 |
+
"probability": 0.6,
|
| 54 |
+
"gain_db_min": -6.0,
|
| 55 |
+
"gain_db_max": 6.0,
|
| 56 |
+
"noise_snr_db_min": 12.0,
|
| 57 |
+
"noise_snr_db_max": 30.0,
|
| 58 |
+
"speed_factors": [
|
| 59 |
+
0.9,
|
| 60 |
+
1.0,
|
| 61 |
+
1.1
|
| 62 |
+
]
|
| 63 |
+
}
|
| 64 |
+
}
|
data/README.md
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Buddi manifest contract
|
| 2 |
+
|
| 3 |
+
Every line is one UTF-8 JSON object:
|
| 4 |
+
|
| 5 |
+
```json
|
| 6 |
+
{
|
| 7 |
+
"audio": "../../processed/ab/abcdef.wav",
|
| 8 |
+
"text": "بودي أبغى قصة",
|
| 9 |
+
"language": "ar",
|
| 10 |
+
"speaker_id": "speaker_opaque-hmac",
|
| 11 |
+
"source": "buddi_omani_child",
|
| 12 |
+
"dialect": "gulf_omani",
|
| 13 |
+
"age_group": "6-8",
|
| 14 |
+
"category": "conversation",
|
| 15 |
+
"license": "private-consented",
|
| 16 |
+
"duration_sec": 2.14,
|
| 17 |
+
"split": "train",
|
| 18 |
+
"metadata": {
|
| 19 |
+
"consent_basis": "verified_parental_consent",
|
| 20 |
+
"device": "iphone",
|
| 21 |
+
"noise_level": "quiet",
|
| 22 |
+
"source_file_id": "file_opaque-hmac"
|
| 23 |
+
}
|
| 24 |
+
}
|
| 25 |
+
```
|
| 26 |
+
|
| 27 |
+
Rules:
|
| 28 |
+
|
| 29 |
+
- `speaker_id` is an HMAC pseudonym, never a name, email, phone, school ID, or reversible code.
|
| 30 |
+
- Audio paths are relative to the manifest where possible and processed filenames are opaque.
|
| 31 |
+
- `speaker_name`, `child_name`, `parent_name`, `full_name`, and `name` are blocked metadata keys.
|
| 32 |
+
- Every split is group-disjoint by `speaker_id`.
|
| 33 |
+
- Raw and processed audio, manifests, reports, salts, and weights are ignored by Git.
|
| 34 |
+
- A consent basis is required for local child-audio import. Consent withdrawal must remove the source rows and trigger retraining or an approved data-deletion procedure.
|
data/label_maps/abjad_ar.json
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_meta": {
|
| 3 |
+
"dataset": "Aziz-snoubra/Abjad-Kids",
|
| 4 |
+
"dataset_revision_reviewed": "2c011cf062359db59db66424683e10afb61f8a7e",
|
| 5 |
+
"expected_labels": 144,
|
| 6 |
+
"purpose": "Convert Romanized class labels into Arabic ASR transcripts",
|
| 7 |
+
"review_required": [
|
| 8 |
+
"Alam",
|
| 9 |
+
"Ders",
|
| 10 |
+
"Ein",
|
| 11 |
+
"Meya",
|
| 12 |
+
"Patta",
|
| 13 |
+
"Up",
|
| 14 |
+
"Zalam"
|
| 15 |
+
],
|
| 16 |
+
"warning": "The listed ambiguous items should be verified by listening before a production run."
|
| 17 |
+
},
|
| 18 |
+
"labels": {
|
| 19 |
+
"Abyad": "أبيض",
|
| 20 |
+
"Ahmar": "أحمر",
|
| 21 |
+
"Akhdar": "أخضر",
|
| 22 |
+
"Alam": "علم",
|
| 23 |
+
"Alif": "ألف",
|
| 24 |
+
"Arbaa": "أربعة",
|
| 25 |
+
"Arbaen": "أربعون",
|
| 26 |
+
"Arnab": "أرنب",
|
| 27 |
+
"Asfar": "أصفر",
|
| 28 |
+
"Asfour": "عصفور",
|
| 29 |
+
"Ashara": "عشرة",
|
| 30 |
+
"Assal": "عسل",
|
| 31 |
+
"Aswad": "أسود",
|
| 32 |
+
"Ayn": "عين",
|
| 33 |
+
"Azraq": "أزرق",
|
| 34 |
+
"Ba": "باء",
|
| 35 |
+
"Bab": "باب",
|
| 36 |
+
"Banafsajy": "بنفسجي",
|
| 37 |
+
"Bathenjan": "باذنجان",
|
| 38 |
+
"Beit": "بيت",
|
| 39 |
+
"Bonny": "بني",
|
| 40 |
+
"Dabet": "ضابط",
|
| 41 |
+
"Dad": "ضاد",
|
| 42 |
+
"Dal": "دال",
|
| 43 |
+
"Dalu": "دلو",
|
| 44 |
+
"Daraj": "درج",
|
| 45 |
+
"Defda": "ضفدع",
|
| 46 |
+
"Ders": "ضرس",
|
| 47 |
+
"Dob": "دب",
|
| 48 |
+
"Ein": "عين",
|
| 49 |
+
"Eshreen": "عشرون",
|
| 50 |
+
"Ethnen": "اثنين",
|
| 51 |
+
"Fa": "فاء",
|
| 52 |
+
"Fam": "فم",
|
| 53 |
+
"Farasha": "فراشة",
|
| 54 |
+
"Feel": "فيل",
|
| 55 |
+
"Ghaba": "غابة",
|
| 56 |
+
"Ghaima": "غيمة",
|
| 57 |
+
"Ghazal": "غزال",
|
| 58 |
+
"Gheen": "غين",
|
| 59 |
+
"Ha": "هاء",
|
| 60 |
+
"Hadeka": "حديقة",
|
| 61 |
+
"Hadeya": "هدية",
|
| 62 |
+
"Halib": "حليب",
|
| 63 |
+
"Hasoub": "حاسوب",
|
| 64 |
+
"Hatef": "هاتف",
|
| 65 |
+
"Helal": "هلال",
|
| 66 |
+
"Hha": "حاء",
|
| 67 |
+
"Jamal": "جمل",
|
| 68 |
+
"Jaras": "جرس",
|
| 69 |
+
"Jeem": "جيم",
|
| 70 |
+
"Jondy": "جندي",
|
| 71 |
+
"Kaf": "كاف",
|
| 72 |
+
"Kalb": "كلب",
|
| 73 |
+
"Ketab": "كتاب",
|
| 74 |
+
"Kha": "خاء",
|
| 75 |
+
"Khait": "خيط",
|
| 76 |
+
"Khamsa": "خمسة",
|
| 77 |
+
"Khamseen": "خمسون",
|
| 78 |
+
"Kharouf": "خروف",
|
| 79 |
+
"Khobz": "خبز",
|
| 80 |
+
"Kora": "كرة",
|
| 81 |
+
"Lahma": "لحمة",
|
| 82 |
+
"Lam": "لام",
|
| 83 |
+
"Leimon": "ليمون",
|
| 84 |
+
"Lesan": "لسان",
|
| 85 |
+
"Maa": "ماء",
|
| 86 |
+
"Masjed": "مسجد",
|
| 87 |
+
"Meem": "ميم",
|
| 88 |
+
"Meqas": "مقص",
|
| 89 |
+
"Meya": "مئة",
|
| 90 |
+
"Nafetha": "نافذة",
|
| 91 |
+
"Najm": "نجم",
|
| 92 |
+
"Namla": "نملة",
|
| 93 |
+
"Noon": "نون",
|
| 94 |
+
"Om": "أم",
|
| 95 |
+
"Patta": "بطة",
|
| 96 |
+
"Qaf": "قاف",
|
| 97 |
+
"Qalam": "قلم",
|
| 98 |
+
"Qamar": "قمر",
|
| 99 |
+
"Qerd": "قرد",
|
| 100 |
+
"Ra": "راء",
|
| 101 |
+
"Raml": "رمل",
|
| 102 |
+
"Resha": "ريشة",
|
| 103 |
+
"Romman": "رمان",
|
| 104 |
+
"Saa": "ساعة",
|
| 105 |
+
"Sabaa": "سبعة",
|
| 106 |
+
"Sabeen": "سبعون",
|
| 107 |
+
"Sama": "سماء",
|
| 108 |
+
"Saqer": "صقر",
|
| 109 |
+
"Saroukh": "صاروخ",
|
| 110 |
+
"Seen": "سين",
|
| 111 |
+
"Sefer": "صفر",
|
| 112 |
+
"Sennara": "صنارة",
|
| 113 |
+
"Seta": "ستة",
|
| 114 |
+
"Shajara": "شجرة",
|
| 115 |
+
"Shams": "شمس",
|
| 116 |
+
"Sheen": "شين",
|
| 117 |
+
"Shouka": "شوكة",
|
| 118 |
+
"Sokar": "سكر",
|
| 119 |
+
"Steen": "ستون",
|
| 120 |
+
"Ta": "تاء",
|
| 121 |
+
"Taera": "طائرة",
|
| 122 |
+
"Tah": "طاء",
|
| 123 |
+
"Tamr": "تمر",
|
| 124 |
+
"Tawous": "طاووس",
|
| 125 |
+
"Tefel": "طفل",
|
| 126 |
+
"Telfaz": "تلفاز",
|
| 127 |
+
"Tesaa": "تسعة",
|
| 128 |
+
"Teseen": "تسعون",
|
| 129 |
+
"Tha": "ثاء",
|
| 130 |
+
"Thahab": "ذهب",
|
| 131 |
+
"Thalatha": "ثلاثة",
|
| 132 |
+
"Thalatheen": "ثلاثون",
|
| 133 |
+
"Thallaja": "ثلاجة",
|
| 134 |
+
"Thamaneen": "ثمانون",
|
| 135 |
+
"Thamaneya": "ثمانية",
|
| 136 |
+
"Thoubaba": "ذبابة",
|
| 137 |
+
"Thouban": "ثعبان",
|
| 138 |
+
"Thoum": "ثوم",
|
| 139 |
+
"Thura": "ذرة",
|
| 140 |
+
"Tofaha": "تفاحة",
|
| 141 |
+
"Up": "أب",
|
| 142 |
+
"Wahed": "واحد",
|
| 143 |
+
"Wajh": "وجه",
|
| 144 |
+
"Walad": "ولد",
|
| 145 |
+
"Waraqa": "ورقة",
|
| 146 |
+
"Warda": "وردة",
|
| 147 |
+
"Wow": "واو",
|
| 148 |
+
"Ya": "ياء",
|
| 149 |
+
"Yad": "يد",
|
| 150 |
+
"Yaqten": "يقطين",
|
| 151 |
+
"Yassmin": "ياسمين",
|
| 152 |
+
"Zah": "ظاء",
|
| 153 |
+
"Zahra": "زهرة",
|
| 154 |
+
"Zahry": "زهري",
|
| 155 |
+
"Zai": "زاي",
|
| 156 |
+
"Zaiton": "زيتون",
|
| 157 |
+
"Zalam": "ظلام",
|
| 158 |
+
"Zarafa": "زرافة",
|
| 159 |
+
"Zarf": "ظرف",
|
| 160 |
+
"Zefr": "ظفر",
|
| 161 |
+
"sad": "صاد",
|
| 162 |
+
"zal": "ذال"
|
| 163 |
+
}
|
| 164 |
+
}
|
dataset-metadata.json
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"title": "buddi-asr-source-code",
|
| 3 |
+
"id": "nabuxai/buddi-asr-source-code",
|
| 4 |
+
"licenses": [
|
| 5 |
+
{
|
| 6 |
+
"name": "CC0-1.0"
|
| 7 |
+
}
|
| 8 |
+
]
|
| 9 |
+
}
|
deploy/systemd/buddi-asr.service
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[Unit]
|
| 2 |
+
Description=Buddi child ASR (whisper.cpp)
|
| 3 |
+
After=network.target
|
| 4 |
+
|
| 5 |
+
[Service]
|
| 6 |
+
Type=simple
|
| 7 |
+
User=buddi
|
| 8 |
+
Group=buddi
|
| 9 |
+
Environment=MODEL_PATH=/opt/buddi/models/buddi-asr-tiny-argulf-v1-q5_0.bin
|
| 10 |
+
ExecStart=/opt/buddi/whisper.cpp/build/bin/whisper-server --host 127.0.0.1 --port 8080 --model ${MODEL_PATH} --threads 4
|
| 11 |
+
Restart=on-failure
|
| 12 |
+
RestartSec=3
|
| 13 |
+
TimeoutStopSec=20
|
| 14 |
+
|
| 15 |
+
NoNewPrivileges=true
|
| 16 |
+
PrivateTmp=true
|
| 17 |
+
PrivateDevices=true
|
| 18 |
+
ProtectSystem=strict
|
| 19 |
+
ProtectHome=true
|
| 20 |
+
ProtectKernelTunables=true
|
| 21 |
+
ProtectKernelModules=true
|
| 22 |
+
ProtectControlGroups=true
|
| 23 |
+
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6
|
| 24 |
+
RestrictNamespaces=true
|
| 25 |
+
LockPersonality=true
|
| 26 |
+
CapabilityBoundingSet=
|
| 27 |
+
SystemCallArchitectures=native
|
| 28 |
+
|
| 29 |
+
[Install]
|
| 30 |
+
WantedBy=multi-user.target
|
docs/DATA_GOVERNANCE.md
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Child-data governance
|
| 2 |
+
|
| 3 |
+
## Minimum collection policy
|
| 4 |
+
|
| 5 |
+
Collect only audio and metadata needed to improve child ASR. Obtain verifiable parental or guardian consent before recording. The consent notice should state purpose, retention, who can access the audio, whether model weights may be published, withdrawal procedure, and the countries where processing occurs.
|
| 6 |
+
|
| 7 |
+
This repository is engineering tooling, not a legal determination. Review the applicable child-privacy and biometric laws for every launch country.
|
| 8 |
+
|
| 9 |
+
## Identity boundary
|
| 10 |
+
|
| 11 |
+
Keep three zones separate:
|
| 12 |
+
|
| 13 |
+
1. **Consent registry** — parent/guardian identity and legal records, encrypted and access-controlled.
|
| 14 |
+
2. **Raw audio vault** — source recordings keyed by a random internal code.
|
| 15 |
+
3. **Training workspace** — pseudonymous speaker IDs and opaque audio filenames only.
|
| 16 |
+
|
| 17 |
+
The training workspace must not contain names, email addresses, phone numbers, precise addresses, school names, birth dates, account IDs, face images, or a copy of the consent registry.
|
| 18 |
+
|
| 19 |
+
## Split policy
|
| 20 |
+
|
| 21 |
+
Split by child, never by audio file. All recordings from the same child stay in exactly one of train, validation, or test. Freeze the test speaker list before tuning. If an upstream dataset has no reliable speaker metadata, do not claim speaker-independent metrics without documenting the limitation.
|
| 22 |
+
|
| 23 |
+
## Access and retention
|
| 24 |
+
|
| 25 |
+
- Encrypt raw audio at rest and in transit.
|
| 26 |
+
- Restrict raw access to named roles and log every access.
|
| 27 |
+
- Set a finite raw-audio retention period.
|
| 28 |
+
- Keep the HMAC salt outside source control and separate from manifests.
|
| 29 |
+
- Disable external experiment telemetry unless the consent and data-processing agreement explicitly permit it.
|
| 30 |
+
- Review generated prediction reports before sharing; transcripts can contain sensitive speech.
|
| 31 |
+
|
| 32 |
+
## Withdrawal
|
| 33 |
+
|
| 34 |
+
Maintain a private mapping from the consent registry to the opaque speaker group. On withdrawal:
|
| 35 |
+
|
| 36 |
+
1. quarantine and delete the raw recordings under the retention policy;
|
| 37 |
+
2. remove all derived manifest rows and cached features;
|
| 38 |
+
3. record which checkpoints were trained with the data;
|
| 39 |
+
4. retrain or follow an approved machine-unlearning/release-revocation process;
|
| 40 |
+
5. document completion without placing identity in the training repository.
|
| 41 |
+
|
| 42 |
+
## Release checklist
|
| 43 |
+
|
| 44 |
+
- [ ] Dataset/model licenses recorded.
|
| 45 |
+
- [ ] Parental consent scope covers the intended model release.
|
| 46 |
+
- [ ] Zero direct identity fields in manifests.
|
| 47 |
+
- [ ] Zero speaker overlap across splits.
|
| 48 |
+
- [ ] Session-only Abjad speaker groups resolved or disclosed.
|
| 49 |
+
- [ ] Performance reported by age, language, dialect, noise, and device.
|
| 50 |
+
- [ ] Hallucination and empty-audio behavior tested.
|
| 51 |
+
- [ ] Human escalation and parental controls designed outside ASR.
|
| 52 |
+
- [ ] Raw child audio excluded from Git, containers, logs, and crash reports.
|
docs/EXPERIMENT_PLAN.md
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Buddi-ASR experiment plan
|
| 2 |
+
|
| 3 |
+
## Goal
|
| 4 |
+
|
| 5 |
+
Choose the smallest model that materially improves unseen-child recognition for Arabic/Gulf-Arabic and English while meeting the target-device latency budget.
|
| 6 |
+
|
| 7 |
+
## Immutable evaluation design
|
| 8 |
+
|
| 9 |
+
1. Build one speaker-disjoint split with a recorded seed.
|
| 10 |
+
2. Use validation for architecture and hyperparameter selection.
|
| 11 |
+
3. Keep test hidden until the candidate is frozen.
|
| 12 |
+
4. Compare every candidate on identical normalized and raw transcripts.
|
| 13 |
+
5. Report both WER and CER; short single-word Abjad samples can make WER look unusually harsh.
|
| 14 |
+
|
| 15 |
+
## Stage A — data sanity
|
| 16 |
+
|
| 17 |
+
- Listen to random examples from every source and all seven ambiguous Abjad mappings.
|
| 18 |
+
- Find empty, clipped, corrupt, duplicated, or mislabeled files.
|
| 19 |
+
- Measure hours, speakers, utterance duration, label distribution, device, noise, age, and dialect coverage.
|
| 20 |
+
- Confirm that Abjad-Kids is capped as an educational-vocabulary component, not the majority of conversational training.
|
| 21 |
+
|
| 22 |
+
## Stage B — baselines
|
| 23 |
+
|
| 24 |
+
Evaluate untouched `openai/whisper-tiny` and `openai/whisper-base` on the frozen validation set. Store predictions, normalized metrics, latency, and peak memory.
|
| 25 |
+
|
| 26 |
+
## Stage C — controlled candidates
|
| 27 |
+
|
| 28 |
+
| Candidate | Purpose | Starting config |
|
| 29 |
+
| --- | --- | --- |
|
| 30 |
+
| Tiny LoRA | Cheapest adaptation baseline | `configs/train_tiny_lora.json` |
|
| 31 |
+
| Tiny full | Check whether 39M full adaptation beats LoRA | `configs/train_tiny_full.json` |
|
| 32 |
+
| Base LoRA | Quality/compute middle point | `configs/train_base_lora.json` |
|
| 33 |
+
| Base full | Quality candidate | `configs/train_base_full.json` |
|
| 34 |
+
|
| 35 |
+
Change one major variable per run. Record code commit, config, manifest hashes, upstream revisions, random seed, hardware, runtime, and best checkpoint.
|
| 36 |
+
|
| 37 |
+
## Stage D — evaluation slices
|
| 38 |
+
|
| 39 |
+
Required slices:
|
| 40 |
+
|
| 41 |
+
- Arabic, English, and code-switching;
|
| 42 |
+
- Gulf/Omani versus non-Gulf Arabic;
|
| 43 |
+
- age 4–5, 6–8, 9–12 where consented metadata exists;
|
| 44 |
+
- quiet, household noise, car, classroom;
|
| 45 |
+
- phone, tablet, Buddi hardware microphone;
|
| 46 |
+
- short commands versus conversational questions;
|
| 47 |
+
- seen vocabulary versus unseen words;
|
| 48 |
+
- empty audio, laughter, singing, whispering, crying, and overlapping speech.
|
| 49 |
+
|
| 50 |
+
## Acceptance gates
|
| 51 |
+
|
| 52 |
+
- zero speaker overlap and zero corrupt/missing test audio;
|
| 53 |
+
- no unexplained regression on English while improving Arabic;
|
| 54 |
+
- statistically meaningful improvement over the untouched base on unseen children;
|
| 55 |
+
- no cohort hidden behind an overall average;
|
| 56 |
+
- empty/noise audio does not routinely hallucinate child-sensitive content;
|
| 57 |
+
- warm p95 latency and real-time factor meet the target hardware budget;
|
| 58 |
+
- model card contains data limitations and exact evaluation revision.
|
| 59 |
+
|
| 60 |
+
Do not use a universal WER threshold without a product error analysis. A one-word educational sample and an open conversational utterance have very different consequences.
|
| 61 |
+
|
| 62 |
+
## Distillation stage
|
| 63 |
+
|
| 64 |
+
Only after the supervised baseline is stable:
|
| 65 |
+
|
| 66 |
+
1. transcribe additional licensed/consented child audio with a stronger teacher;
|
| 67 |
+
2. store teacher confidence and provenance;
|
| 68 |
+
3. require human correction for evaluation data and low-confidence training data;
|
| 69 |
+
4. mix pseudo-labels at a controlled ratio;
|
| 70 |
+
5. re-run every frozen slice and compare against the supervised-only checkpoint.
|
| 71 |
+
|
| 72 |
+
Teacher output is not ground truth and must never contaminate test references.
|
docs/GPU_TRAINING.fa.md
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# آموزش واقعی Buddi-ASR روی GPU
|
| 2 |
+
|
| 3 |
+
این مسیر واقعاً وزنهای Whisper را با PyTorch/Transformers آموزش میدهد. اجرای `--smoke` فقط برای اطمینان از درست بودن محیط است؛ اجرای معمولی تا پایان epochها ادامه پیدا میکند و checkpoint قابلاستفاده میسازد.
|
| 4 |
+
|
| 5 |
+
## پیشنهاد سریع
|
| 6 |
+
|
| 7 |
+
برای اولین مدل از یک GPU انویدیا با حداقل ۸ گیگابایت VRAM و پروفایل `tiny-lora` شروع کن. ۱۲ تا ۱۶ گیگابایت راحتتر است. اسکریپت بر اساس VRAM، batch را کوچک میکند و gradient accumulation را طوری تنظیم میکند که batch مؤثر نزدیک ۳۲ بماند. این انتخاب تخمینی است؛ اگر خطای OOM دیدی، `--train-batch-size` را نصف کن.
|
| 8 |
+
|
| 9 |
+
برای نصب PyTorch از یک image آمادهٔ PyTorch + CUDA استفاده کن. سازگاری wheel و CUDA را از انتخابگر رسمی PyTorch بررسی کن: <https://pytorch.org/get-started/locally/>.
|
| 10 |
+
|
| 11 |
+
## RunPod یا سرور لینوکس CUDA
|
| 12 |
+
|
| 13 |
+
ریپو را داخل دیسک پایدار قرار بده؛ در RunPod بهتر است مسیر زیر `/workspace` باشد. سپس:
|
| 14 |
+
|
| 15 |
+
```bash
|
| 16 |
+
cd /workspace/buddi-asr
|
| 17 |
+
chmod +x scripts/train_gpu.sh
|
| 18 |
+
|
| 19 |
+
# تست کامل مسیر با ۲۰ step؛ دیتاست را در صورت نبودن آماده میکند
|
| 20 |
+
./scripts/train_gpu.sh tiny-lora --smoke
|
| 21 |
+
|
| 22 |
+
# آموزش واقعی؛ اگر قبلاً قطع شده باشد آخرین checkpoint را پیدا میکند
|
| 23 |
+
./scripts/train_gpu.sh tiny-lora
|
| 24 |
+
```
|
| 25 |
+
|
| 26 |
+
در اولین اجرا، اسکریپت این کارها را انجام میدهد:
|
| 27 |
+
|
| 28 |
+
1. محیط Python را میسازد و dependencyهای آموزش را نصب میکند؛
|
| 29 |
+
2. CUDA، نام GPU، VRAM و پشتیبانی BF16 را بررسی میکند؛
|
| 30 |
+
3. Abjad-Kids را دانلود و شناسههای گوینده را ناشناس میکند؛
|
| 31 |
+
4. split بدون اشتراک کودک میسازد و وجود تمام فایلهای صوتی را کنترل میکند؛
|
| 32 |
+
5. مدل را با checkpoint دورهای، early stopping و validation WER/CER آموزش میدهد؛
|
| 33 |
+
6. config نهایی، مشخصات GPU و نسخهٔ کتابخانهها را کنار وزن ذخیره میکند.
|
| 34 |
+
|
| 35 |
+
فایل salt داخل `.buddi-speaker.salt` خصوصی است و نباید در Git، پیام یا فایل عمومی قرار بگیرد. اگر دیسک GPU موقتی است، کل پروژه و این salt باید روی volume پایدار باشند؛ تغییر salt گروهبندی کودکها را تغییر میدهد.
|
| 36 |
+
|
| 37 |
+
## انتخاب پروفایل
|
| 38 |
+
|
| 39 |
+
| فرمان | مدل | روش | کاربرد |
|
| 40 |
+
| --- | --- | --- | --- |
|
| 41 |
+
| `./scripts/train_gpu.sh tiny-lora` | Whisper Tiny | LoRA | پیشنهاد اول و کمهزینه |
|
| 42 |
+
| `./scripts/train_gpu.sh tiny-full` | Whisper Tiny | Full | مقایسه با LoRA |
|
| 43 |
+
| `./scripts/train_gpu.sh base-lora` | Whisper Base | LoRA | کیفیت بالاتر با هزینه متوسط |
|
| 44 |
+
| `./scripts/train_gpu.sh base-full` | Whisper Base | Full | سنگینترین گزینهٔ این پروژه |
|
| 45 |
+
|
| 46 |
+
## کنترل حافظه و چند GPU
|
| 47 |
+
|
| 48 |
+
```bash
|
| 49 |
+
# GPU هشتگیگابایتی یا خطای OOM
|
| 50 |
+
./scripts/train_gpu.sh tiny-lora \
|
| 51 |
+
--train-batch-size 2 \
|
| 52 |
+
--eval-batch-size 1 \
|
| 53 |
+
--gradient-accumulation 16
|
| 54 |
+
|
| 55 |
+
# دو GPU روی یک سرور
|
| 56 |
+
./scripts/train_gpu.sh base-lora --num-gpus 2
|
| 57 |
+
|
| 58 |
+
# انتخاب GPUهای فیزیکی مشخص؛ runner از اولین مورد استفاده میکند
|
| 59 |
+
CUDA_VISIBLE_DEVICES=2,3 ./scripts/train_gpu.sh base-lora --num-gpus 2
|
| 60 |
+
|
| 61 |
+
# اگر محیط از قبل نصب شده است
|
| 62 |
+
./scripts/train_gpu.sh tiny-lora --skip-install
|
| 63 |
+
```
|
| 64 |
+
|
| 65 |
+
حالت `auto` روی GPUهای سازگار BF16 را انتخاب میکند و در غیر این صورت FP16 را به کار میبرد. برای اجبار:
|
| 66 |
+
|
| 67 |
+
```bash
|
| 68 |
+
./scripts/train_gpu.sh tiny-lora --precision fp16
|
| 69 |
+
```
|
| 70 |
+
|
| 71 |
+
اگر image انتخابی PyTorch مناسب نداشت، URL دقیق wheel را از سایت PyTorch بردار:
|
| 72 |
+
|
| 73 |
+
```bash
|
| 74 |
+
./scripts/train_gpu.sh tiny-lora \
|
| 75 |
+
--torch-index-url https://download.pytorch.org/whl/REPLACE_WITH_CUDA_CHANNEL
|
| 76 |
+
```
|
| 77 |
+
|
| 78 |
+
## ادامه بعد از قطع شدن
|
| 79 |
+
|
| 80 |
+
همان فرمان و همان `--output-dir` را دوباره اجرا کن. `--resume auto` آخرین پوشهٔ کامل `checkpoint-N` را انتخاب میکند:
|
| 81 |
+
|
| 82 |
+
```bash
|
| 83 |
+
./scripts/train_gpu.sh tiny-lora \
|
| 84 |
+
--output-dir /workspace/models/buddi-tiny-lora \
|
| 85 |
+
--resume auto
|
| 86 |
+
```
|
| 87 |
+
|
| 88 |
+
برای شروع کاملاً تازه، یک output جدید بده یا از `--resume none` استفاده کن. اسکریپت فایلهای قبلی را خودکار پاک نمیکند.
|
| 89 |
+
|
| 90 |
+
## دادهٔ خودت به جای Abjad تنها
|
| 91 |
+
|
| 92 |
+
دادهٔ عمانیِ دارای رضا��ت را با `buddi-asr import-local` وارد کن، manifestها را با `buddi-asr mix` ترکیب و سپس split کن. وقتی این سه فایل حاضر باشند، runner دوباره دیتاست را آماده نمیکند:
|
| 93 |
+
|
| 94 |
+
```text
|
| 95 |
+
data/manifests/splits/train.jsonl
|
| 96 |
+
data/manifests/splits/validation.jsonl
|
| 97 |
+
data/manifests/splits/test.jsonl
|
| 98 |
+
```
|
| 99 |
+
|
| 100 |
+
برای جلوگیری صریح از دانلود:
|
| 101 |
+
|
| 102 |
+
```bash
|
| 103 |
+
./scripts/train_gpu.sh tiny-lora --prepare-data no
|
| 104 |
+
```
|
| 105 |
+
|
| 106 |
+
## خروجیها
|
| 107 |
+
|
| 108 |
+
```text
|
| 109 |
+
artifacts/tiny-lora/checkpoint-N/ checkpointهای قابل ادامه
|
| 110 |
+
artifacts/tiny-lora/final/ LoRA adapter یا مدل کامل نهایی
|
| 111 |
+
artifacts/tiny-lora/training_summary.json
|
| 112 |
+
artifacts/tiny-lora/resolved_train_config.json
|
| 113 |
+
artifacts/tiny-lora/runtime.json GPU/CUDA و نسخه dependencyها
|
| 114 |
+
artifacts/logs/ لاگ runner
|
| 115 |
+
```
|
| 116 |
+
|
| 117 |
+
test مخفی عمداً بعد از هر experiment اجرا نمیشود. وقتی candidate را با validation انتخاب و فریز کردی، فقط یک بار اجرا کن:
|
| 118 |
+
|
| 119 |
+
```bash
|
| 120 |
+
buddi-asr evaluate \
|
| 121 |
+
artifacts/tiny-lora/final \
|
| 122 |
+
data/manifests/splits/test.jsonl \
|
| 123 |
+
reports/tiny-lora-test \
|
| 124 |
+
--device cuda
|
| 125 |
+
```
|
| 126 |
+
|
| 127 |
+
یا اجرای همان یک بار را با `--evaluate-test` درخواست کن. برای مشاهدهٔ منحنی loss و WER:
|
| 128 |
+
|
| 129 |
+
```bash
|
| 130 |
+
tensorboard --logdir artifacts
|
| 131 |
+
```
|
| 132 |
+
|
| 133 |
+
## اجرای دستی بدون runner
|
| 134 |
+
|
| 135 |
+
```bash
|
| 136 |
+
python -m pip install -e '.[data,train]'
|
| 137 |
+
|
| 138 |
+
buddi-asr preflight-gpu configs/train_tiny_lora.json \
|
| 139 |
+
--test-manifest data/manifests/splits/test.jsonl \
|
| 140 |
+
--precision auto \
|
| 141 |
+
--resume auto
|
| 142 |
+
|
| 143 |
+
buddi-asr train configs/train_tiny_lora.json \
|
| 144 |
+
--precision auto \
|
| 145 |
+
--resume auto
|
| 146 |
+
```
|
| 147 |
+
|
| 148 |
+
GPU runner هیچ وزن ساختگی تولید نمیکند. فقط وقتی `training_summary.json`، پوشهٔ `final` و ارزیابی روی دادهٔ جداشده ساخته شدند، یک checkpoint واقعی در اختیار داری.
|
docs/GPU_TRAINING.md
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Real GPU training
|
| 2 |
+
|
| 3 |
+
`scripts/train_gpu.sh` is the one-command path from a CUDA machine to a real, resumable Whisper checkpoint. It can bootstrap the Python environment, prepare Abjad-Kids when manifests are absent, size the batch from available VRAM, run a strict preflight, train on one or several GPUs, and preserve runtime metadata.
|
| 4 |
+
|
| 5 |
+
Start on a persistent disk with an NVIDIA PyTorch image:
|
| 6 |
+
|
| 7 |
+
```bash
|
| 8 |
+
cd /workspace/buddi-asr
|
| 9 |
+
chmod +x scripts/train_gpu.sh
|
| 10 |
+
|
| 11 |
+
# Twenty-step integration run
|
| 12 |
+
./scripts/train_gpu.sh tiny-lora --smoke
|
| 13 |
+
|
| 14 |
+
# Full run; automatically resumes a complete checkpoint
|
| 15 |
+
./scripts/train_gpu.sh tiny-lora
|
| 16 |
+
```
|
| 17 |
+
|
| 18 |
+
Available profiles are `tiny-lora`, `tiny-full`, `base-lora`, and `base-full`. Tiny LoRA is the recommended first baseline. The automatic batch choice is conservative but cannot predict every driver/model combination; halve `--train-batch-size` after an out-of-memory error.
|
| 19 |
+
|
| 20 |
+
Use the official [PyTorch install selector](https://pytorch.org/get-started/locally/) when the base image does not already expose CUDA to PyTorch. You can pass its wheel index with `--torch-index-url`.
|
| 21 |
+
|
| 22 |
+
## Useful overrides
|
| 23 |
+
|
| 24 |
+
```bash
|
| 25 |
+
# Low-memory GPU
|
| 26 |
+
./scripts/train_gpu.sh tiny-lora \
|
| 27 |
+
--train-batch-size 2 \
|
| 28 |
+
--eval-batch-size 1 \
|
| 29 |
+
--gradient-accumulation 16
|
| 30 |
+
|
| 31 |
+
# Two local GPUs through Accelerate
|
| 32 |
+
./scripts/train_gpu.sh base-lora --num-gpus 2
|
| 33 |
+
|
| 34 |
+
# Select physical devices explicitly
|
| 35 |
+
CUDA_VISIBLE_DEVICES=2,3 ./scripts/train_gpu.sh base-lora --num-gpus 2
|
| 36 |
+
|
| 37 |
+
# Existing environment and prepared manifests
|
| 38 |
+
./scripts/train_gpu.sh tiny-lora --skip-install --prepare-data no
|
| 39 |
+
|
| 40 |
+
# Stable checkpoint/output location
|
| 41 |
+
./scripts/train_gpu.sh tiny-lora \
|
| 42 |
+
--output-dir /workspace/models/buddi-tiny-lora \
|
| 43 |
+
--resume auto
|
| 44 |
+
```
|
| 45 |
+
|
| 46 |
+
The preflight rejects missing audio, speaker overlap across train/validation/test, repeated audio across splits, unavailable CUDA, unsupported BF16, and incomplete explicit checkpoints before training starts. Every run stores the resolved config, Trainer state, validation metrics, library versions, CUDA runtime, and GPU details beside the output.
|
| 47 |
+
|
| 48 |
+
The held-out test set is deliberately not evaluated after every experiment. Freeze the candidate using validation results, then run once:
|
| 49 |
+
|
| 50 |
+
```bash
|
| 51 |
+
buddi-asr evaluate \
|
| 52 |
+
artifacts/tiny-lora/final \
|
| 53 |
+
data/manifests/splits/test.jsonl \
|
| 54 |
+
reports/tiny-lora-test \
|
| 55 |
+
--device cuda
|
| 56 |
+
```
|
| 57 |
+
|
| 58 |
+
See the [Persian walkthrough](GPU_TRAINING.fa.md) for RunPod details, custom Omani data, recovery, output paths, and manual commands.
|
docs/MODEL_CARD_TEMPLATE.md
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
language:
|
| 3 |
+
- ar
|
| 4 |
+
- en
|
| 5 |
+
license: mit
|
| 6 |
+
library_name: transformers
|
| 7 |
+
pipeline_tag: automatic-speech-recognition
|
| 8 |
+
base_model: openai/whisper-tiny
|
| 9 |
+
tags:
|
| 10 |
+
- whisper
|
| 11 |
+
- children-speech
|
| 12 |
+
- arabic
|
| 13 |
+
- gulf-arabic
|
| 14 |
+
- buddi
|
| 15 |
+
---
|
| 16 |
+
|
| 17 |
+
# Buddi-ASR-[variant]-[version]
|
| 18 |
+
|
| 19 |
+
## Summary
|
| 20 |
+
|
| 21 |
+
State exactly which languages, dialects, age bands, microphone conditions, and utterance types were evaluated. Do not use “Omani child ASR” unless unseen Omani children are represented in the test set.
|
| 22 |
+
|
| 23 |
+
## Training data
|
| 24 |
+
|
| 25 |
+
| Source | Revision | License/consent | Speakers | Hours | Train share |
|
| 26 |
+
| --- | --- | --- | ---: | ---: | ---: |
|
| 27 |
+
| Fill before release | | | | | |
|
| 28 |
+
|
| 29 |
+
Describe direct-identity removal, speaker grouping confidence, withdrawal handling, and whether any pseudo-labels were used.
|
| 30 |
+
|
| 31 |
+
## Evaluation
|
| 32 |
+
|
| 33 |
+
| Slice | Speakers | Utterances | WER | CER | p50 latency | p95 latency |
|
| 34 |
+
| --- | ---: | ---: | ---: | ---: | ---: | ---: |
|
| 35 |
+
| Overall | | | | | | |
|
| 36 |
+
| Arabic | | | | | | |
|
| 37 |
+
| Gulf/Omani Arabic | | | | | | |
|
| 38 |
+
| English | | | | | | |
|
| 39 |
+
| Code-switching | | | | | | |
|
| 40 |
+
|
| 41 |
+
State whether metrics are raw or normalized and prove speaker-disjointness.
|
| 42 |
+
|
| 43 |
+
## Intended use
|
| 44 |
+
|
| 45 |
+
Short educational and conversational transcription inside Buddi with a downstream safety layer and parental controls.
|
| 46 |
+
|
| 47 |
+
## Prohibited use
|
| 48 |
+
|
| 49 |
+
Speaker identification, surveillance, emotion diagnosis, grading a child's intelligence, law-enforcement decisions, medical diagnosis, or unsupervised high-stakes decisions.
|
| 50 |
+
|
| 51 |
+
## Limitations
|
| 52 |
+
|
| 53 |
+
Document accents, age bands, noise, devices, speech conditions, vocabulary, hallucination behavior, and every material cohort regression.
|
| 54 |
+
|
| 55 |
+
## Reproducibility
|
| 56 |
+
|
| 57 |
+
- Code commit:
|
| 58 |
+
- Training config hash:
|
| 59 |
+
- Manifest hashes:
|
| 60 |
+
- Base model revision:
|
| 61 |
+
- Seed:
|
| 62 |
+
- Hardware/software image:
|
| 63 |
+
- Export quantization and SHA-256:
|
docs/RASPBERRY_PI.md
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Raspberry Pi 5 deployment
|
| 2 |
+
|
| 3 |
+
## Target
|
| 4 |
+
|
| 5 |
+
- Raspberry Pi 5, 16 GB, 64-bit Raspberry Pi OS;
|
| 6 |
+
- active cooling and the official power supply;
|
| 7 |
+
- NVMe storage and Ethernet;
|
| 8 |
+
- `whisper.cpp` kept warm as a local HTTP service;
|
| 9 |
+
- Q5 Tiny and Base compared on the same held-out child manifest.
|
| 10 |
+
|
| 11 |
+
The 16 GB board adds model/context headroom but does not add CPU cores. Benchmark one and two active conversations; do not infer multi-user capacity from idle WebSocket counts.
|
| 12 |
+
|
| 13 |
+
## Build runtime
|
| 14 |
+
|
| 15 |
+
Install system packages:
|
| 16 |
+
|
| 17 |
+
```bash
|
| 18 |
+
sudo apt update
|
| 19 |
+
sudo apt install -y git cmake build-essential libopenblas-dev ffmpeg
|
| 20 |
+
```
|
| 21 |
+
|
| 22 |
+
Build a fresh, pinned runtime directory:
|
| 23 |
+
|
| 24 |
+
```bash
|
| 25 |
+
./scripts/build_pi_runtime.sh /opt/buddi/whisper.cpp
|
| 26 |
+
```
|
| 27 |
+
|
| 28 |
+
The script defaults to `v1.9.2`; override explicitly if you have validated another revision:
|
| 29 |
+
|
| 30 |
+
```bash
|
| 31 |
+
WHISPER_CPP_REF=v1.9.2 ./scripts/build_pi_runtime.sh /opt/buddi/whisper.cpp
|
| 32 |
+
```
|
| 33 |
+
|
| 34 |
+
Copy the exported model and its JSON metadata into `/opt/buddi/models/`, then verify the SHA-256 printed by the export metadata:
|
| 35 |
+
|
| 36 |
+
```bash
|
| 37 |
+
sha256sum /opt/buddi/models/buddi-asr-tiny-argulf-v1-q5_0.bin
|
| 38 |
+
```
|
| 39 |
+
|
| 40 |
+
## Run locally
|
| 41 |
+
|
| 42 |
+
```bash
|
| 43 |
+
/opt/buddi/whisper.cpp/build/bin/whisper-server \
|
| 44 |
+
--host 127.0.0.1 \
|
| 45 |
+
--port 8080 \
|
| 46 |
+
--model /opt/buddi/models/buddi-asr-tiny-argulf-v1-q5_0.bin \
|
| 47 |
+
--threads 4
|
| 48 |
+
```
|
| 49 |
+
|
| 50 |
+
Keep the service on `127.0.0.1`. Put the Buddi API on the same device, or use a private authenticated tunnel. Do not expose the inference endpoint directly to the public internet.
|
| 51 |
+
|
| 52 |
+
## systemd
|
| 53 |
+
|
| 54 |
+
Create a dedicated unprivileged user and install the included unit after reviewing paths:
|
| 55 |
+
|
| 56 |
+
```bash
|
| 57 |
+
sudo useradd --system --home /nonexistent --shell /usr/sbin/nologin buddi
|
| 58 |
+
sudo cp deploy/systemd/buddi-asr.service /etc/systemd/system/
|
| 59 |
+
sudo systemctl daemon-reload
|
| 60 |
+
sudo systemctl enable --now buddi-asr
|
| 61 |
+
sudo systemctl status buddi-asr
|
| 62 |
+
```
|
| 63 |
+
|
| 64 |
+
## Measure real capacity
|
| 65 |
+
|
| 66 |
+
Use the persistent server so model-loading time is excluded. Run identical samples at concurrency one and two:
|
| 67 |
+
|
| 68 |
+
```bash
|
| 69 |
+
buddi-asr benchmark-server data/manifests/splits/test.jsonl reports/pi-c1 \
|
| 70 |
+
--concurrency 1 --limit 100
|
| 71 |
+
|
| 72 |
+
buddi-asr benchmark-server data/manifests/splits/test.jsonl reports/pi-c2 \
|
| 73 |
+
--concurrency 2 --limit 100
|
| 74 |
+
```
|
| 75 |
+
|
| 76 |
+
Compare:
|
| 77 |
+
|
| 78 |
+
- p50 and p95 ASR latency;
|
| 79 |
+
- p50 and p95 real-time factor;
|
| 80 |
+
- WER/CER, to catch export/quantization regressions;
|
| 81 |
+
- CPU temperature, throttling, memory, and request failures.
|
| 82 |
+
|
| 83 |
+
Suggested monitoring commands:
|
| 84 |
+
|
| 85 |
+
```bash
|
| 86 |
+
vcgencmd measure_temp
|
| 87 |
+
vcgencmd get_throttled
|
| 88 |
+
systemd-cgtop
|
| 89 |
+
```
|
| 90 |
+
|
| 91 |
+
A real-time factor below `1.0` means transcription is faster than audio duration. Voice UX also includes VAD endpointing, network, LLM first-token latency, and TTS startup; measure the whole Buddi turn separately.
|
| 92 |
+
|
| 93 |
+
## Operational rules
|
| 94 |
+
|
| 95 |
+
- Rate-limit by child/session in the parent Buddi API.
|
| 96 |
+
- Cap upload duration and body size before forwarding to ASR.
|
| 97 |
+
- Avoid logging raw audio or full child transcripts.
|
| 98 |
+
- Use an outbound Tailscale/Cloudflare tunnel if remote access is required; do not depend on public IPv4 or port forwarding.
|
| 99 |
+
- Keep Tiny as a fallback if Base misses latency or thermal targets.
|
pyproject.toml
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[build-system]
|
| 2 |
+
requires = ["setuptools>=75", "wheel"]
|
| 3 |
+
build-backend = "setuptools.build_meta"
|
| 4 |
+
|
| 5 |
+
[project]
|
| 6 |
+
name = "buddi-asr"
|
| 7 |
+
version = "0.2.0"
|
| 8 |
+
description = "Privacy-aware child Arabic and English Whisper fine-tuning pipeline for Buddi"
|
| 9 |
+
readme = "README.md"
|
| 10 |
+
requires-python = ">=3.10,<3.13"
|
| 11 |
+
license = { text = "MIT" }
|
| 12 |
+
authors = [{ name = "Buddi contributors" }]
|
| 13 |
+
keywords = ["asr", "whisper", "arabic", "gulf-arabic", "children", "raspberry-pi"]
|
| 14 |
+
classifiers = [
|
| 15 |
+
"Development Status :: 3 - Alpha",
|
| 16 |
+
"License :: OSI Approved :: MIT License",
|
| 17 |
+
"Programming Language :: Python :: 3",
|
| 18 |
+
"Programming Language :: Python :: 3.10",
|
| 19 |
+
"Programming Language :: Python :: 3.11",
|
| 20 |
+
"Programming Language :: Python :: 3.12",
|
| 21 |
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
| 22 |
+
]
|
| 23 |
+
dependencies = []
|
| 24 |
+
|
| 25 |
+
[project.optional-dependencies]
|
| 26 |
+
data = [
|
| 27 |
+
"huggingface-hub>=0.27,<1",
|
| 28 |
+
"soundfile>=0.12,<1",
|
| 29 |
+
]
|
| 30 |
+
train = [
|
| 31 |
+
"accelerate>=1.2,<2",
|
| 32 |
+
"librosa>=0.10.2,<1",
|
| 33 |
+
"numpy>=1.26,<3",
|
| 34 |
+
"peft>=0.14,<1",
|
| 35 |
+
"safetensors>=0.4,<1",
|
| 36 |
+
"soundfile>=0.12,<1",
|
| 37 |
+
"tensorboard>=2.18,<3",
|
| 38 |
+
"torch>=2.4,<3",
|
| 39 |
+
"transformers>=4.48,<5",
|
| 40 |
+
]
|
| 41 |
+
dev = [
|
| 42 |
+
"ruff>=0.9,<1",
|
| 43 |
+
]
|
| 44 |
+
|
| 45 |
+
[project.scripts]
|
| 46 |
+
buddi-asr = "buddi_asr.cli:main"
|
| 47 |
+
|
| 48 |
+
[project.urls]
|
| 49 |
+
Documentation = "https://github.com/your-org/buddi-asr#readme"
|
| 50 |
+
Issues = "https://github.com/your-org/buddi-asr/issues"
|
| 51 |
+
|
| 52 |
+
[tool.setuptools]
|
| 53 |
+
package-dir = { "" = "src" }
|
| 54 |
+
|
| 55 |
+
[tool.setuptools.packages.find]
|
| 56 |
+
where = ["src"]
|
| 57 |
+
|
| 58 |
+
[tool.ruff]
|
| 59 |
+
line-length = 100
|
| 60 |
+
target-version = "py310"
|
| 61 |
+
|
| 62 |
+
[tool.ruff.lint]
|
| 63 |
+
select = ["E", "F", "I", "UP", "B", "SIM"]
|
| 64 |
+
ignore = ["E501"]
|
scripts/build_pi_runtime.sh
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
|
| 4 |
+
if [[ $# -ne 1 ]]; then
|
| 5 |
+
echo "usage: $0 /explicit/new/path/for/whisper.cpp" >&2
|
| 6 |
+
exit 2
|
| 7 |
+
fi
|
| 8 |
+
|
| 9 |
+
target_path="$1"
|
| 10 |
+
runtime_ref="${WHISPER_CPP_REF:-v1.9.2}"
|
| 11 |
+
|
| 12 |
+
if [[ "$target_path" != /* || "$target_path" == "/" ]]; then
|
| 13 |
+
echo "error: target must be an explicit absolute path other than /" >&2
|
| 14 |
+
exit 2
|
| 15 |
+
fi
|
| 16 |
+
if [[ -e "$target_path" ]]; then
|
| 17 |
+
echo "error: target already exists; refusing to alter it: $target_path" >&2
|
| 18 |
+
exit 2
|
| 19 |
+
fi
|
| 20 |
+
|
| 21 |
+
git clone --branch "$runtime_ref" --depth 1 \
|
| 22 |
+
https://github.com/ggml-org/whisper.cpp.git "$target_path"
|
| 23 |
+
cmake -S "$target_path" -B "$target_path/build" \
|
| 24 |
+
-DCMAKE_BUILD_TYPE=Release \
|
| 25 |
+
-DGGML_BLAS=1
|
| 26 |
+
cmake --build "$target_path/build" -j 4 --config Release
|
| 27 |
+
|
| 28 |
+
echo "built whisper.cpp $runtime_ref at $target_path"
|
scripts/train_gpu.sh
ADDED
|
@@ -0,0 +1,279 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
set -Eeuo pipefail
|
| 3 |
+
|
| 4 |
+
script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
| 5 |
+
project_root="$(cd "$script_dir/.." && pwd)"
|
| 6 |
+
cd "$project_root"
|
| 7 |
+
|
| 8 |
+
usage() {
|
| 9 |
+
cat <<'EOF'
|
| 10 |
+
Usage: ./scripts/train_gpu.sh [PROFILE] [OPTIONS]
|
| 11 |
+
|
| 12 |
+
Profiles:
|
| 13 |
+
tiny-lora (default) | tiny-full | base-lora | base-full
|
| 14 |
+
|
| 15 |
+
Options:
|
| 16 |
+
--prepare-data auto|yes|no Download/prepare Abjad-Kids (default: auto)
|
| 17 |
+
--num-gpus N Number of local CUDA GPUs (default: 1)
|
| 18 |
+
--precision auto|fp16|bf16 Mixed precision (default: auto)
|
| 19 |
+
--train-batch-size N Override auto-sized per-GPU train batch
|
| 20 |
+
--eval-batch-size N Override auto-sized per-GPU eval batch
|
| 21 |
+
--gradient-accumulation N Override accumulation chosen for effective batch ~32
|
| 22 |
+
--workers N Audio-loader processes (default: 4)
|
| 23 |
+
--resume auto|none|PATH Resume policy (default: auto)
|
| 24 |
+
--output-dir PATH Override artifact directory
|
| 25 |
+
--smoke Run 20 optimizer steps in a separate output directory
|
| 26 |
+
--evaluate-test Evaluate the held-out test set after training
|
| 27 |
+
--skip-install Use the already-active Python environment
|
| 28 |
+
--torch-index-url URL Install torch from a PyTorch wheel index before extras
|
| 29 |
+
-h, --help Show this help
|
| 30 |
+
|
| 31 |
+
Environment:
|
| 32 |
+
BUDDI_VENV, BUDDI_PYTHON, BUDDI_SALT_FILE, CUDA_VISIBLE_DEVICES,
|
| 33 |
+
HF_HOME, HF_TOKEN, BUDDI_TORCH_INDEX_URL
|
| 34 |
+
EOF
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
profile="tiny-lora"
|
| 38 |
+
if [[ $# -gt 0 && "$1" != --* && "$1" != "-h" ]]; then
|
| 39 |
+
profile="$1"
|
| 40 |
+
shift
|
| 41 |
+
fi
|
| 42 |
+
|
| 43 |
+
prepare_data="auto"
|
| 44 |
+
num_gpus=1
|
| 45 |
+
precision="auto"
|
| 46 |
+
train_batch=""
|
| 47 |
+
eval_batch=""
|
| 48 |
+
gradient_accumulation=""
|
| 49 |
+
workers=4
|
| 50 |
+
resume="auto"
|
| 51 |
+
output_dir=""
|
| 52 |
+
smoke=0
|
| 53 |
+
evaluate_test=0
|
| 54 |
+
skip_install=0
|
| 55 |
+
torch_index_url="${BUDDI_TORCH_INDEX_URL:-}"
|
| 56 |
+
|
| 57 |
+
while [[ $# -gt 0 ]]; do
|
| 58 |
+
case "$1" in
|
| 59 |
+
--prepare-data) prepare_data="${2:?missing value}"; shift 2 ;;
|
| 60 |
+
--num-gpus) num_gpus="${2:?missing value}"; shift 2 ;;
|
| 61 |
+
--precision) precision="${2:?missing value}"; shift 2 ;;
|
| 62 |
+
--train-batch-size) train_batch="${2:?missing value}"; shift 2 ;;
|
| 63 |
+
--eval-batch-size) eval_batch="${2:?missing value}"; shift 2 ;;
|
| 64 |
+
--gradient-accumulation) gradient_accumulation="${2:?missing value}"; shift 2 ;;
|
| 65 |
+
--workers) workers="${2:?missing value}"; shift 2 ;;
|
| 66 |
+
--resume) resume="${2:?missing value}"; shift 2 ;;
|
| 67 |
+
--output-dir) output_dir="${2:?missing value}"; shift 2 ;;
|
| 68 |
+
--torch-index-url) torch_index_url="${2:?missing value}"; shift 2 ;;
|
| 69 |
+
--smoke) smoke=1; shift ;;
|
| 70 |
+
--evaluate-test) evaluate_test=1; shift ;;
|
| 71 |
+
--skip-install) skip_install=1; shift ;;
|
| 72 |
+
-h|--help) usage; exit 0 ;;
|
| 73 |
+
*) echo "Unknown option: $1" >&2; usage >&2; exit 2 ;;
|
| 74 |
+
esac
|
| 75 |
+
done
|
| 76 |
+
|
| 77 |
+
case "$profile" in
|
| 78 |
+
tiny-lora) config="configs/train_tiny_lora.json" ;;
|
| 79 |
+
tiny-full) config="configs/train_tiny_full.json" ;;
|
| 80 |
+
base-lora) config="configs/train_base_lora.json" ;;
|
| 81 |
+
base-full) config="configs/train_base_full.json" ;;
|
| 82 |
+
*) echo "Unknown profile: $profile" >&2; usage >&2; exit 2 ;;
|
| 83 |
+
esac
|
| 84 |
+
|
| 85 |
+
case "$prepare_data" in auto|yes|no) ;; *) echo "Invalid --prepare-data" >&2; exit 2 ;; esac
|
| 86 |
+
case "$precision" in auto|fp16|bf16) ;; *) echo "Invalid --precision" >&2; exit 2 ;; esac
|
| 87 |
+
for value in "$num_gpus" "$workers"; do
|
| 88 |
+
[[ "$value" =~ ^[0-9]+$ ]] || { echo "Numeric options must be integers" >&2; exit 2; }
|
| 89 |
+
done
|
| 90 |
+
[[ "$num_gpus" -gt 0 ]] || { echo "--num-gpus must be positive" >&2; exit 2; }
|
| 91 |
+
|
| 92 |
+
if [[ -n "${CUDA_VISIBLE_DEVICES:-}" ]]; then
|
| 93 |
+
IFS=',' read -r -a visible_devices <<< "$CUDA_VISIBLE_DEVICES"
|
| 94 |
+
if [[ "$num_gpus" -gt "${#visible_devices[@]}" ]]; then
|
| 95 |
+
echo "--num-gpus exceeds CUDA_VISIBLE_DEVICES=$CUDA_VISIBLE_DEVICES" >&2
|
| 96 |
+
exit 2
|
| 97 |
+
fi
|
| 98 |
+
selected_devices="${visible_devices[0]}"
|
| 99 |
+
for ((index = 1; index < num_gpus; index++)); do
|
| 100 |
+
selected_devices+=",${visible_devices[index]}"
|
| 101 |
+
done
|
| 102 |
+
export CUDA_VISIBLE_DEVICES="$selected_devices"
|
| 103 |
+
else
|
| 104 |
+
selected_devices="0"
|
| 105 |
+
for ((index = 1; index < num_gpus; index++)); do
|
| 106 |
+
selected_devices+=",$index"
|
| 107 |
+
done
|
| 108 |
+
export CUDA_VISIBLE_DEVICES="$selected_devices"
|
| 109 |
+
fi
|
| 110 |
+
|
| 111 |
+
python_seed="${BUDDI_PYTHON:-python3}"
|
| 112 |
+
venv_dir="${BUDDI_VENV:-$project_root/.venv-gpu}"
|
| 113 |
+
if [[ "$skip_install" -eq 0 ]]; then
|
| 114 |
+
if [[ ! -f "$venv_dir/bin/activate" ]]; then
|
| 115 |
+
"$python_seed" -m venv --system-site-packages "$venv_dir"
|
| 116 |
+
fi
|
| 117 |
+
# shellcheck disable=SC1091
|
| 118 |
+
source "$venv_dir/bin/activate"
|
| 119 |
+
python -m pip install --upgrade pip setuptools wheel
|
| 120 |
+
if [[ -n "$torch_index_url" ]]; then
|
| 121 |
+
python -m pip install --index-url "$torch_index_url" 'torch>=2.4,<3'
|
| 122 |
+
fi
|
| 123 |
+
python -m pip install -e '.[data,train]'
|
| 124 |
+
elif [[ -f "$venv_dir/bin/activate" ]]; then
|
| 125 |
+
# shellcheck disable=SC1091
|
| 126 |
+
source "$venv_dir/bin/activate"
|
| 127 |
+
fi
|
| 128 |
+
|
| 129 |
+
python - <<'PY'
|
| 130 |
+
import torch
|
| 131 |
+
|
| 132 |
+
if not torch.cuda.is_available():
|
| 133 |
+
raise SystemExit(
|
| 134 |
+
"CUDA is not visible to PyTorch. Start from an NVIDIA PyTorch image or pass "
|
| 135 |
+
"--torch-index-url with the wheel index selected at pytorch.org/get-started/locally/."
|
| 136 |
+
)
|
| 137 |
+
print(f"PyTorch {torch.__version__}; CUDA runtime {torch.version.cuda}")
|
| 138 |
+
for index in range(torch.cuda.device_count()):
|
| 139 |
+
props = torch.cuda.get_device_properties(index)
|
| 140 |
+
print(f"GPU {index}: {props.name}; VRAM {props.total_memory / 1024**3:.2f} GiB")
|
| 141 |
+
PY
|
| 142 |
+
|
| 143 |
+
detected_gpus="$(python -c 'import torch; print(torch.cuda.device_count())')"
|
| 144 |
+
if [[ "$num_gpus" -gt "$detected_gpus" ]]; then
|
| 145 |
+
echo "Requested $num_gpus GPU(s), but PyTorch sees $detected_gpus" >&2
|
| 146 |
+
exit 2
|
| 147 |
+
fi
|
| 148 |
+
if [[ "$precision" == "auto" ]]; then
|
| 149 |
+
precision="$(python -c 'import torch; print("bf16" if torch.cuda.is_bf16_supported() else "fp16")')"
|
| 150 |
+
fi
|
| 151 |
+
|
| 152 |
+
vram_mib="$(python -c 'import sys, torch; count=int(sys.argv[1]); print(min(torch.cuda.get_device_properties(i).total_memory for i in range(count)) // 1024**2)' "$num_gpus")"
|
| 153 |
+
if [[ -z "$train_batch" ]]; then
|
| 154 |
+
case "$profile" in
|
| 155 |
+
tiny-lora)
|
| 156 |
+
if (( vram_mib < 6000 )); then train_batch=2
|
| 157 |
+
elif (( vram_mib < 10000 )); then train_batch=4
|
| 158 |
+
elif (( vram_mib < 16000 )); then train_batch=8
|
| 159 |
+
else train_batch=16; fi ;;
|
| 160 |
+
tiny-full|base-lora)
|
| 161 |
+
if (( vram_mib < 6000 )); then train_batch=1
|
| 162 |
+
elif (( vram_mib < 10000 )); then train_batch=2
|
| 163 |
+
elif (( vram_mib < 16000 )); then train_batch=4
|
| 164 |
+
else train_batch=8; fi ;;
|
| 165 |
+
base-full)
|
| 166 |
+
if (( vram_mib < 10000 )); then train_batch=1
|
| 167 |
+
elif (( vram_mib < 16000 )); then train_batch=2
|
| 168 |
+
elif (( vram_mib < 24000 )); then train_batch=4
|
| 169 |
+
else train_batch=8; fi ;;
|
| 170 |
+
esac
|
| 171 |
+
fi
|
| 172 |
+
[[ "$train_batch" =~ ^[1-9][0-9]*$ ]] || { echo "Invalid train batch size" >&2; exit 2; }
|
| 173 |
+
if [[ -z "$eval_batch" ]]; then
|
| 174 |
+
eval_batch=$(( train_batch > 1 ? train_batch / 2 : 1 ))
|
| 175 |
+
fi
|
| 176 |
+
[[ "$eval_batch" =~ ^[1-9][0-9]*$ ]] || { echo "Invalid eval batch size" >&2; exit 2; }
|
| 177 |
+
if [[ -z "$gradient_accumulation" ]]; then
|
| 178 |
+
batch_across_gpus=$(( train_batch * num_gpus ))
|
| 179 |
+
gradient_accumulation=$(( (32 + batch_across_gpus - 1) / batch_across_gpus ))
|
| 180 |
+
fi
|
| 181 |
+
[[ "$gradient_accumulation" =~ ^[1-9][0-9]*$ ]] || {
|
| 182 |
+
echo "Invalid gradient accumulation" >&2
|
| 183 |
+
exit 2
|
| 184 |
+
}
|
| 185 |
+
|
| 186 |
+
train_manifest="data/manifests/splits/train.jsonl"
|
| 187 |
+
validation_manifest="data/manifests/splits/validation.jsonl"
|
| 188 |
+
test_manifest="data/manifests/splits/test.jsonl"
|
| 189 |
+
if [[ "$prepare_data" == "auto" ]]; then
|
| 190 |
+
if [[ -f "$train_manifest" && -f "$validation_manifest" && -f "$test_manifest" ]]; then
|
| 191 |
+
prepare_data="no"
|
| 192 |
+
else
|
| 193 |
+
prepare_data="yes"
|
| 194 |
+
fi
|
| 195 |
+
fi
|
| 196 |
+
|
| 197 |
+
mkdir -p reports artifacts/logs
|
| 198 |
+
log_file="artifacts/logs/${profile}-$(date -u +%Y%m%dT%H%M%SZ).log"
|
| 199 |
+
exec > >(tee -a "$log_file") 2>&1
|
| 200 |
+
|
| 201 |
+
if [[ "$prepare_data" == "yes" ]]; then
|
| 202 |
+
salt_file="${BUDDI_SALT_FILE:-$project_root/.buddi-speaker.salt}"
|
| 203 |
+
if [[ ! -s "$salt_file" ]]; then
|
| 204 |
+
umask 077
|
| 205 |
+
python -c 'import secrets; print(secrets.token_hex(32))' > "$salt_file"
|
| 206 |
+
fi
|
| 207 |
+
buddi-asr download-abjad data/raw/abjad-kids
|
| 208 |
+
buddi-asr prepare-abjad \
|
| 209 |
+
data/raw/abjad-kids \
|
| 210 |
+
data/manifests/abjad.jsonl \
|
| 211 |
+
--processed-audio-dir data/processed/abjad \
|
| 212 |
+
--audio-mode hardlink \
|
| 213 |
+
--salt-file "$salt_file" \
|
| 214 |
+
--audit-output reports/abjad-audit.json
|
| 215 |
+
buddi-asr validate \
|
| 216 |
+
data/manifests/abjad.jsonl \
|
| 217 |
+
--report reports/abjad-validation.json
|
| 218 |
+
buddi-asr split data/manifests/abjad.jsonl data/manifests/splits --seed 42
|
| 219 |
+
fi
|
| 220 |
+
|
| 221 |
+
for manifest in "$train_manifest" "$validation_manifest" "$test_manifest"; do
|
| 222 |
+
[[ -f "$manifest" ]] || {
|
| 223 |
+
echo "Missing $manifest. Use --prepare-data yes or provide your prepared split." >&2
|
| 224 |
+
exit 2
|
| 225 |
+
}
|
| 226 |
+
done
|
| 227 |
+
|
| 228 |
+
if [[ -z "$output_dir" ]]; then
|
| 229 |
+
if [[ "$smoke" -eq 1 ]]; then
|
| 230 |
+
output_dir="artifacts/smoke-${profile}"
|
| 231 |
+
else
|
| 232 |
+
output_dir="artifacts/${profile}"
|
| 233 |
+
fi
|
| 234 |
+
fi
|
| 235 |
+
|
| 236 |
+
common_args=(
|
| 237 |
+
"$config"
|
| 238 |
+
--output-dir "$output_dir"
|
| 239 |
+
--resume "$resume"
|
| 240 |
+
--precision "$precision"
|
| 241 |
+
--train-batch-size "$train_batch"
|
| 242 |
+
--eval-batch-size "$eval_batch"
|
| 243 |
+
--gradient-accumulation-steps "$gradient_accumulation"
|
| 244 |
+
--dataloader-workers "$workers"
|
| 245 |
+
)
|
| 246 |
+
if [[ "$smoke" -eq 1 ]]; then
|
| 247 |
+
common_args+=(--max-steps 20 --logging-steps 1 --eval-steps 10 --save-steps 10)
|
| 248 |
+
fi
|
| 249 |
+
|
| 250 |
+
echo "Profile: $profile"
|
| 251 |
+
echo "CUDA devices: $CUDA_VISIBLE_DEVICES"
|
| 252 |
+
echo "Precision: $precision"
|
| 253 |
+
echo "Per-GPU train/eval batch: $train_batch/$eval_batch"
|
| 254 |
+
echo "Gradient accumulation: $gradient_accumulation"
|
| 255 |
+
echo "Output: $output_dir"
|
| 256 |
+
echo "Log: $log_file"
|
| 257 |
+
|
| 258 |
+
buddi-asr preflight-gpu "${common_args[@]}" --test-manifest "$test_manifest"
|
| 259 |
+
if [[ "$num_gpus" -eq 1 ]]; then
|
| 260 |
+
buddi-asr train "${common_args[@]}"
|
| 261 |
+
else
|
| 262 |
+
accelerate launch \
|
| 263 |
+
--multi_gpu \
|
| 264 |
+
--num_processes "$num_gpus" \
|
| 265 |
+
-m buddi_asr.cli train "${common_args[@]}"
|
| 266 |
+
fi
|
| 267 |
+
|
| 268 |
+
if [[ "$evaluate_test" -eq 1 ]]; then
|
| 269 |
+
buddi-asr evaluate \
|
| 270 |
+
"$output_dir/final" \
|
| 271 |
+
"$test_manifest" \
|
| 272 |
+
"reports/${profile}-test" \
|
| 273 |
+
--device cuda
|
| 274 |
+
else
|
| 275 |
+
echo "Held-out test was not touched. After freezing the candidate, run:"
|
| 276 |
+
echo "buddi-asr evaluate '$output_dir/final' '$test_manifest' 'reports/${profile}-test' --device cuda"
|
| 277 |
+
fi
|
| 278 |
+
|
| 279 |
+
echo "Training finished. Final checkpoint: $output_dir/final"
|
src/buddi_asr/__init__.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Buddi ASR: child-focused Arabic and English speech recognition tooling."""
|
| 2 |
+
|
| 3 |
+
__version__ = "0.2.0"
|
src/buddi_asr/benchmark.py
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Warm HTTP load test for whisper.cpp's persistent inference server."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import json
|
| 6 |
+
import random
|
| 7 |
+
import time
|
| 8 |
+
import urllib.error
|
| 9 |
+
import urllib.request
|
| 10 |
+
import uuid
|
| 11 |
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
from typing import Any
|
| 14 |
+
|
| 15 |
+
from buddi_asr.data.manifest import ManifestRecord, read_manifest, resolve_audio_path
|
| 16 |
+
from buddi_asr.metrics import score_pairs
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def _multipart(audio_path: Path, language: str) -> tuple[bytes, str]:
|
| 20 |
+
boundary = "----buddi-" + uuid.uuid4().hex
|
| 21 |
+
chunks: list[bytes] = []
|
| 22 |
+
|
| 23 |
+
def field(name: str, value: str) -> None:
|
| 24 |
+
chunks.extend(
|
| 25 |
+
[
|
| 26 |
+
f"--{boundary}\r\n".encode(),
|
| 27 |
+
f'Content-Disposition: form-data; name="{name}"\r\n\r\n'.encode(),
|
| 28 |
+
value.encode("utf-8"),
|
| 29 |
+
b"\r\n",
|
| 30 |
+
]
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
chunks.extend(
|
| 34 |
+
[
|
| 35 |
+
f"--{boundary}\r\n".encode(),
|
| 36 |
+
b'Content-Disposition: form-data; name="file"; filename="audio.wav"\r\n',
|
| 37 |
+
b"Content-Type: audio/wav\r\n\r\n",
|
| 38 |
+
audio_path.read_bytes(),
|
| 39 |
+
b"\r\n",
|
| 40 |
+
]
|
| 41 |
+
)
|
| 42 |
+
field("response_format", "json")
|
| 43 |
+
field("temperature", "0")
|
| 44 |
+
if language in {"ar", "en"}:
|
| 45 |
+
field("language", language)
|
| 46 |
+
chunks.append(f"--{boundary}--\r\n".encode())
|
| 47 |
+
return b"".join(chunks), boundary
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def _transcribe(
|
| 51 |
+
server_url: str,
|
| 52 |
+
record: ManifestRecord,
|
| 53 |
+
manifest_path: Path,
|
| 54 |
+
timeout: float,
|
| 55 |
+
) -> dict[str, Any]:
|
| 56 |
+
audio_path = resolve_audio_path(record, manifest_path)
|
| 57 |
+
body, boundary = _multipart(audio_path, record.language)
|
| 58 |
+
request = urllib.request.Request(
|
| 59 |
+
server_url,
|
| 60 |
+
data=body,
|
| 61 |
+
headers={"Content-Type": f"multipart/form-data; boundary={boundary}"},
|
| 62 |
+
method="POST",
|
| 63 |
+
)
|
| 64 |
+
started = time.perf_counter()
|
| 65 |
+
try:
|
| 66 |
+
with urllib.request.urlopen(request, timeout=timeout) as response:
|
| 67 |
+
payload_bytes = response.read()
|
| 68 |
+
except urllib.error.URLError as exc:
|
| 69 |
+
raise RuntimeError(f"whisper.cpp request failed for {audio_path.name}: {exc}") from exc
|
| 70 |
+
latency = time.perf_counter() - started
|
| 71 |
+
try:
|
| 72 |
+
payload = json.loads(payload_bytes)
|
| 73 |
+
hypothesis = payload.get("text") or payload.get("transcription") or ""
|
| 74 |
+
except json.JSONDecodeError:
|
| 75 |
+
hypothesis = payload_bytes.decode("utf-8", errors="replace").strip()
|
| 76 |
+
if not isinstance(hypothesis, str):
|
| 77 |
+
hypothesis = str(hypothesis)
|
| 78 |
+
duration = record.duration_sec or 0.0
|
| 79 |
+
return {
|
| 80 |
+
"source_file_id": record.metadata.get("source_file_id"),
|
| 81 |
+
"reference": record.text,
|
| 82 |
+
"hypothesis": hypothesis,
|
| 83 |
+
"language": record.language,
|
| 84 |
+
"latency_sec": latency,
|
| 85 |
+
"audio_duration_sec": duration,
|
| 86 |
+
"real_time_factor": latency / duration if duration > 0 else None,
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def _percentile(values: list[float], percentile: float) -> float:
|
| 91 |
+
if not values:
|
| 92 |
+
return 0.0
|
| 93 |
+
ordered = sorted(values)
|
| 94 |
+
index = max(0, min(len(ordered) - 1, int(round((len(ordered) - 1) * percentile))))
|
| 95 |
+
return ordered[index]
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def benchmark_whisper_server(
|
| 99 |
+
manifest: str | Path,
|
| 100 |
+
output_dir: str | Path,
|
| 101 |
+
*,
|
| 102 |
+
server_url: str = "http://127.0.0.1:8080/inference",
|
| 103 |
+
concurrency: int = 1,
|
| 104 |
+
limit: int = 100,
|
| 105 |
+
seed: int = 42,
|
| 106 |
+
timeout: float = 120.0,
|
| 107 |
+
) -> dict[str, Any]:
|
| 108 |
+
if concurrency <= 0 or limit <= 0:
|
| 109 |
+
raise ValueError("concurrency and limit must be positive")
|
| 110 |
+
manifest_path = Path(manifest).resolve()
|
| 111 |
+
records = list(read_manifest(manifest_path))
|
| 112 |
+
if not records:
|
| 113 |
+
raise ValueError("benchmark manifest is empty")
|
| 114 |
+
selected = random.Random(seed).sample(records, min(limit, len(records)))
|
| 115 |
+
destination = Path(output_dir).resolve()
|
| 116 |
+
destination.mkdir(parents=True, exist_ok=True)
|
| 117 |
+
|
| 118 |
+
# One untimed request makes the measurement represent a persistent model,
|
| 119 |
+
# not model loading or cold filesystem caches.
|
| 120 |
+
_transcribe(server_url, selected[0], manifest_path, timeout)
|
| 121 |
+
started = time.perf_counter()
|
| 122 |
+
rows: list[dict[str, Any]] = []
|
| 123 |
+
with ThreadPoolExecutor(max_workers=concurrency) as executor:
|
| 124 |
+
futures = [
|
| 125 |
+
executor.submit(_transcribe, server_url, record, manifest_path, timeout)
|
| 126 |
+
for record in selected
|
| 127 |
+
]
|
| 128 |
+
for future in as_completed(futures):
|
| 129 |
+
rows.append(future.result())
|
| 130 |
+
wall_time = time.perf_counter() - started
|
| 131 |
+
latencies = [float(row["latency_sec"]) for row in rows]
|
| 132 |
+
real_time_factors = [
|
| 133 |
+
float(row["real_time_factor"])
|
| 134 |
+
for row in rows
|
| 135 |
+
if row["real_time_factor"] is not None
|
| 136 |
+
]
|
| 137 |
+
metrics = score_pairs(
|
| 138 |
+
[str(row["reference"]) for row in rows],
|
| 139 |
+
[str(row["hypothesis"]) for row in rows],
|
| 140 |
+
)
|
| 141 |
+
predictions = destination / f"predictions-c{concurrency}.jsonl"
|
| 142 |
+
with predictions.open("w", encoding="utf-8", newline="\n") as handle:
|
| 143 |
+
for row in rows:
|
| 144 |
+
handle.write(json.dumps(row, ensure_ascii=False, sort_keys=True) + "\n")
|
| 145 |
+
summary = {
|
| 146 |
+
"server_url": server_url,
|
| 147 |
+
"concurrency": concurrency,
|
| 148 |
+
"requests": len(rows),
|
| 149 |
+
"wall_time_sec": wall_time,
|
| 150 |
+
"throughput_requests_per_sec": len(rows) / wall_time if wall_time else 0.0,
|
| 151 |
+
"latency_sec": {
|
| 152 |
+
"p50": _percentile(latencies, 0.50),
|
| 153 |
+
"p95": _percentile(latencies, 0.95),
|
| 154 |
+
"max": max(latencies, default=0.0),
|
| 155 |
+
},
|
| 156 |
+
"real_time_factor": {
|
| 157 |
+
"p50": _percentile(real_time_factors, 0.50),
|
| 158 |
+
"p95": _percentile(real_time_factors, 0.95),
|
| 159 |
+
},
|
| 160 |
+
"asr": metrics,
|
| 161 |
+
"predictions": str(predictions),
|
| 162 |
+
"warning": "Prediction files contain transcript text; review before sharing.",
|
| 163 |
+
}
|
| 164 |
+
(destination / f"benchmark-c{concurrency}.json").write_text(
|
| 165 |
+
json.dumps(summary, ensure_ascii=False, indent=2, sort_keys=True) + "\n",
|
| 166 |
+
encoding="utf-8",
|
| 167 |
+
)
|
| 168 |
+
return summary
|
src/buddi_asr/cli.py
ADDED
|
@@ -0,0 +1,341 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Dependency-light command line interface for the complete Buddi-ASR workflow."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import argparse
|
| 6 |
+
import json
|
| 7 |
+
import os
|
| 8 |
+
import subprocess
|
| 9 |
+
import sys
|
| 10 |
+
from collections.abc import Sequence
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
from typing import Any
|
| 13 |
+
|
| 14 |
+
from buddi_asr import __version__
|
| 15 |
+
from buddi_asr.benchmark import benchmark_whisper_server
|
| 16 |
+
from buddi_asr.data.abjad import download_abjad, prepare_abjad
|
| 17 |
+
from buddi_asr.data.local import import_local_csv
|
| 18 |
+
from buddi_asr.data.mix import mix_manifests
|
| 19 |
+
from buddi_asr.data.split import split_manifest
|
| 20 |
+
from buddi_asr.data.validate import validate_manifest
|
| 21 |
+
from buddi_asr.errors import BuddiASRError
|
| 22 |
+
from buddi_asr.evaluate import evaluate_hf_model
|
| 23 |
+
from buddi_asr.export import export_whisper_cpp, merge_lora_adapter
|
| 24 |
+
from buddi_asr.metrics import score_pairs
|
| 25 |
+
from buddi_asr.training.runtime import run_gpu_preflight
|
| 26 |
+
from buddi_asr.training.train import run_training
|
| 27 |
+
|
| 28 |
+
PROJECT_ROOT = Path(__file__).resolve().parents[2]
|
| 29 |
+
DEFAULT_LABEL_MAP = PROJECT_ROOT / "data/label_maps/abjad_ar.json"
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _json_output(value: Any) -> None:
|
| 33 |
+
print(json.dumps(value, ensure_ascii=False, indent=2, sort_keys=True, default=str))
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def _read_salt(args: argparse.Namespace) -> str:
|
| 37 |
+
if getattr(args, "salt_file", None):
|
| 38 |
+
salt = Path(args.salt_file).read_text(encoding="utf-8").strip()
|
| 39 |
+
else:
|
| 40 |
+
salt = os.environ.get(getattr(args, "salt_env", "BUDDI_SPEAKER_SALT"), "").strip()
|
| 41 |
+
if not salt:
|
| 42 |
+
raise BuddiASRError(
|
| 43 |
+
"Pseudonymization salt is required. Set BUDDI_SPEAKER_SALT or pass --salt-file. "
|
| 44 |
+
"Keep the salt private and stable; never commit it."
|
| 45 |
+
)
|
| 46 |
+
return salt
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def _add_salt_arguments(parser: argparse.ArgumentParser) -> None:
|
| 50 |
+
parser.add_argument("--salt-file", help="Private file containing a stable random salt")
|
| 51 |
+
parser.add_argument(
|
| 52 |
+
"--salt-env",
|
| 53 |
+
default="BUDDI_SPEAKER_SALT",
|
| 54 |
+
help="Environment variable containing the salt (default: BUDDI_SPEAKER_SALT)",
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def _add_training_override_arguments(parser: argparse.ArgumentParser) -> None:
|
| 59 |
+
parser.add_argument("--output-dir", help="Override the config output directory")
|
| 60 |
+
parser.add_argument(
|
| 61 |
+
"--resume",
|
| 62 |
+
help="Resume policy: auto, none, or an explicit checkpoint directory",
|
| 63 |
+
)
|
| 64 |
+
parser.add_argument(
|
| 65 |
+
"--precision",
|
| 66 |
+
choices=("auto", "fp16", "bf16", "fp32"),
|
| 67 |
+
help="Override mixed precision; auto chooses BF16 when the GPU supports it",
|
| 68 |
+
)
|
| 69 |
+
parser.add_argument("--train-batch-size", type=int)
|
| 70 |
+
parser.add_argument("--eval-batch-size", type=int)
|
| 71 |
+
parser.add_argument("--gradient-accumulation-steps", type=int)
|
| 72 |
+
parser.add_argument("--dataloader-workers", type=int)
|
| 73 |
+
parser.add_argument("--max-steps", type=int, help="Positive value for a bounded smoke run")
|
| 74 |
+
parser.add_argument("--logging-steps", type=int)
|
| 75 |
+
parser.add_argument("--eval-steps", type=int)
|
| 76 |
+
parser.add_argument("--save-steps", type=int)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def _training_overrides(args: argparse.Namespace) -> dict[str, Any]:
|
| 80 |
+
overrides: dict[str, Any] = {}
|
| 81 |
+
direct = {
|
| 82 |
+
"per_device_train_batch_size": getattr(args, "train_batch_size", None),
|
| 83 |
+
"per_device_eval_batch_size": getattr(args, "eval_batch_size", None),
|
| 84 |
+
"gradient_accumulation_steps": getattr(args, "gradient_accumulation_steps", None),
|
| 85 |
+
"dataloader_num_workers": getattr(args, "dataloader_workers", None),
|
| 86 |
+
"max_steps": getattr(args, "max_steps", None),
|
| 87 |
+
"logging_steps": getattr(args, "logging_steps", None),
|
| 88 |
+
"eval_steps": getattr(args, "eval_steps", None),
|
| 89 |
+
"save_steps": getattr(args, "save_steps", None),
|
| 90 |
+
}
|
| 91 |
+
overrides.update({key: value for key, value in direct.items() if value is not None})
|
| 92 |
+
if getattr(args, "output_dir", None):
|
| 93 |
+
overrides["output_dir"] = str(Path(args.output_dir).expanduser().resolve())
|
| 94 |
+
resume = getattr(args, "resume", None)
|
| 95 |
+
if resume:
|
| 96 |
+
normalized = resume.casefold()
|
| 97 |
+
if normalized == "none":
|
| 98 |
+
overrides["resume_from_checkpoint"] = None
|
| 99 |
+
elif normalized == "auto":
|
| 100 |
+
overrides["resume_from_checkpoint"] = "auto"
|
| 101 |
+
else:
|
| 102 |
+
overrides["resume_from_checkpoint"] = str(Path(resume).expanduser().resolve())
|
| 103 |
+
precision = getattr(args, "precision", None)
|
| 104 |
+
if precision:
|
| 105 |
+
if precision == "auto":
|
| 106 |
+
try:
|
| 107 |
+
import torch
|
| 108 |
+
except ImportError as exc:
|
| 109 |
+
raise BuddiASRError("--precision auto requires the training dependencies") from exc
|
| 110 |
+
precision = (
|
| 111 |
+
"bf16" if torch.cuda.is_available() and torch.cuda.is_bf16_supported() else "fp16"
|
| 112 |
+
)
|
| 113 |
+
overrides["fp16"] = precision == "fp16"
|
| 114 |
+
overrides["bf16"] = precision == "bf16"
|
| 115 |
+
return overrides
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def build_parser() -> argparse.ArgumentParser:
|
| 119 |
+
parser = argparse.ArgumentParser(
|
| 120 |
+
prog="buddi-asr",
|
| 121 |
+
description="Build and evaluate child-focused Arabic/English Whisper models",
|
| 122 |
+
)
|
| 123 |
+
parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
|
| 124 |
+
commands = parser.add_subparsers(dest="command", required=True)
|
| 125 |
+
|
| 126 |
+
download = commands.add_parser("download-abjad", help="Download Abjad-Kids from Hugging Face")
|
| 127 |
+
download.add_argument("destination")
|
| 128 |
+
download.add_argument("--revision", default="main")
|
| 129 |
+
|
| 130 |
+
prepare = commands.add_parser(
|
| 131 |
+
"prepare-abjad", help="Audit, pseudonymize, and create an Abjad-Kids manifest"
|
| 132 |
+
)
|
| 133 |
+
prepare.add_argument("dataset_root")
|
| 134 |
+
prepare.add_argument("output_manifest")
|
| 135 |
+
prepare.add_argument("--processed-audio-dir")
|
| 136 |
+
prepare.add_argument("--label-map", default=str(DEFAULT_LABEL_MAP))
|
| 137 |
+
prepare.add_argument(
|
| 138 |
+
"--audio-mode", choices=("hardlink", "copy", "symlink", "reference"), default="hardlink"
|
| 139 |
+
)
|
| 140 |
+
prepare.add_argument("--speaker-overrides")
|
| 141 |
+
prepare.add_argument("--skip-missing", action="store_true")
|
| 142 |
+
prepare.add_argument("--audit-output")
|
| 143 |
+
_add_salt_arguments(prepare)
|
| 144 |
+
|
| 145 |
+
local = commands.add_parser(
|
| 146 |
+
"import-local", help="Import consented local child speech without direct identity"
|
| 147 |
+
)
|
| 148 |
+
local.add_argument("input_csv")
|
| 149 |
+
local.add_argument("output_manifest")
|
| 150 |
+
local.add_argument("--processed-audio-dir", required=True)
|
| 151 |
+
local.add_argument("--source-name", default="buddi_consent_collection")
|
| 152 |
+
local.add_argument("--audio-mode", choices=("hardlink", "copy", "symlink"), default="hardlink")
|
| 153 |
+
_add_salt_arguments(local)
|
| 154 |
+
|
| 155 |
+
validate = commands.add_parser("validate", help="Validate manifest, files, and split leakage")
|
| 156 |
+
validate.add_argument("manifest")
|
| 157 |
+
validate.add_argument("--no-check-audio", action="store_true")
|
| 158 |
+
validate.add_argument("--report")
|
| 159 |
+
|
| 160 |
+
split = commands.add_parser("split", help="Create speaker-disjoint train/validation/test sets")
|
| 161 |
+
split.add_argument("input_manifest")
|
| 162 |
+
split.add_argument("output_dir")
|
| 163 |
+
split.add_argument("--train", type=float, default=0.8)
|
| 164 |
+
split.add_argument("--validation", type=float, default=0.1)
|
| 165 |
+
split.add_argument("--test", type=float, default=0.1)
|
| 166 |
+
split.add_argument("--seed", type=int, default=42)
|
| 167 |
+
split.add_argument("--label-weight", type=float, default=0.25)
|
| 168 |
+
|
| 169 |
+
mix = commands.add_parser("mix", help="Build a weighted manifest from multiple sources")
|
| 170 |
+
mix.add_argument("config")
|
| 171 |
+
mix.add_argument("output_manifest")
|
| 172 |
+
|
| 173 |
+
train = commands.add_parser("train", help="Fine-tune Whisper with LoRA or full updates")
|
| 174 |
+
train.add_argument("config")
|
| 175 |
+
_add_training_override_arguments(train)
|
| 176 |
+
|
| 177 |
+
preflight = commands.add_parser(
|
| 178 |
+
"preflight-gpu",
|
| 179 |
+
help="Validate CUDA, VRAM, disk, manifests, and split isolation before training",
|
| 180 |
+
)
|
| 181 |
+
preflight.add_argument("config")
|
| 182 |
+
preflight.add_argument("--no-check-audio", action="store_true")
|
| 183 |
+
preflight.add_argument("--minimum-free-vram-gib", type=float, default=0.0)
|
| 184 |
+
preflight.add_argument(
|
| 185 |
+
"--test-manifest",
|
| 186 |
+
help="Optional held-out test manifest to include in leakage checks",
|
| 187 |
+
)
|
| 188 |
+
_add_training_override_arguments(preflight)
|
| 189 |
+
|
| 190 |
+
evaluate = commands.add_parser("evaluate", help="Evaluate a Hugging Face Whisper checkpoint")
|
| 191 |
+
evaluate.add_argument("model")
|
| 192 |
+
evaluate.add_argument("manifest")
|
| 193 |
+
evaluate.add_argument("output_dir")
|
| 194 |
+
evaluate.add_argument("--device", choices=("auto", "cpu", "cuda", "mps"), default="auto")
|
| 195 |
+
evaluate.add_argument("--max-new-tokens", type=int, default=128)
|
| 196 |
+
|
| 197 |
+
merge = commands.add_parser("merge-lora", help="Merge a LoRA adapter into its Whisper base")
|
| 198 |
+
merge.add_argument("base_model")
|
| 199 |
+
merge.add_argument("adapter_dir")
|
| 200 |
+
merge.add_argument("output_dir")
|
| 201 |
+
|
| 202 |
+
export = commands.add_parser("export-whisper-cpp", help="Convert and quantize for Raspberry Pi")
|
| 203 |
+
export.add_argument("model_dir")
|
| 204 |
+
export.add_argument("whisper_cpp_dir")
|
| 205 |
+
export.add_argument("openai_whisper_dir")
|
| 206 |
+
export.add_argument("output_dir")
|
| 207 |
+
export.add_argument("--name", default="buddi-asr-tiny-argulf-v1")
|
| 208 |
+
export.add_argument(
|
| 209 |
+
"--quantization", choices=("none", "q4_0", "q5_0", "q5_1", "q8_0"), default="q5_0"
|
| 210 |
+
)
|
| 211 |
+
export.add_argument("--build-if-needed", action="store_true")
|
| 212 |
+
|
| 213 |
+
score = commands.add_parser("score", help="Score matching reference/hypothesis text files")
|
| 214 |
+
score.add_argument("references")
|
| 215 |
+
score.add_argument("hypotheses")
|
| 216 |
+
|
| 217 |
+
benchmark = commands.add_parser(
|
| 218 |
+
"benchmark-server", help="Warm latency/load test against whisper.cpp server"
|
| 219 |
+
)
|
| 220 |
+
benchmark.add_argument("manifest")
|
| 221 |
+
benchmark.add_argument("output_dir")
|
| 222 |
+
benchmark.add_argument("--url", default="http://127.0.0.1:8080/inference")
|
| 223 |
+
benchmark.add_argument("--concurrency", type=int, default=1)
|
| 224 |
+
benchmark.add_argument("--limit", type=int, default=100)
|
| 225 |
+
benchmark.add_argument("--seed", type=int, default=42)
|
| 226 |
+
benchmark.add_argument("--timeout", type=float, default=120.0)
|
| 227 |
+
return parser
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
def _write_report(path: str | None, payload: dict[str, Any]) -> None:
|
| 231 |
+
if path:
|
| 232 |
+
Path(path).write_text(
|
| 233 |
+
json.dumps(payload, ensure_ascii=False, indent=2, sort_keys=True) + "\n",
|
| 234 |
+
encoding="utf-8",
|
| 235 |
+
)
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
def dispatch(args: argparse.Namespace) -> dict[str, Any]:
|
| 239 |
+
if args.command == "download-abjad":
|
| 240 |
+
return {"dataset_root": str(download_abjad(args.destination, revision=args.revision))}
|
| 241 |
+
if args.command == "prepare-abjad":
|
| 242 |
+
result = prepare_abjad(
|
| 243 |
+
args.dataset_root,
|
| 244 |
+
args.output_manifest,
|
| 245 |
+
label_map_path=args.label_map,
|
| 246 |
+
salt=_read_salt(args),
|
| 247 |
+
processed_audio_dir=args.processed_audio_dir,
|
| 248 |
+
audio_mode=args.audio_mode,
|
| 249 |
+
speaker_overrides_path=args.speaker_overrides,
|
| 250 |
+
skip_missing=args.skip_missing,
|
| 251 |
+
)
|
| 252 |
+
_write_report(args.audit_output, result)
|
| 253 |
+
return result
|
| 254 |
+
if args.command == "import-local":
|
| 255 |
+
return import_local_csv(
|
| 256 |
+
args.input_csv,
|
| 257 |
+
args.output_manifest,
|
| 258 |
+
processed_audio_dir=args.processed_audio_dir,
|
| 259 |
+
salt=_read_salt(args),
|
| 260 |
+
source_name=args.source_name,
|
| 261 |
+
audio_mode=args.audio_mode,
|
| 262 |
+
)
|
| 263 |
+
if args.command == "validate":
|
| 264 |
+
result = validate_manifest(args.manifest, check_audio=not args.no_check_audio)
|
| 265 |
+
_write_report(args.report, result)
|
| 266 |
+
return result
|
| 267 |
+
if args.command == "split":
|
| 268 |
+
return split_manifest(
|
| 269 |
+
args.input_manifest,
|
| 270 |
+
args.output_dir,
|
| 271 |
+
ratios={"train": args.train, "validation": args.validation, "test": args.test},
|
| 272 |
+
seed=args.seed,
|
| 273 |
+
label_weight=args.label_weight,
|
| 274 |
+
)
|
| 275 |
+
if args.command == "mix":
|
| 276 |
+
return mix_manifests(args.config, args.output_manifest)
|
| 277 |
+
if args.command == "train":
|
| 278 |
+
return run_training(args.config, overrides=_training_overrides(args))
|
| 279 |
+
if args.command == "preflight-gpu":
|
| 280 |
+
return run_gpu_preflight(
|
| 281 |
+
args.config,
|
| 282 |
+
overrides=_training_overrides(args),
|
| 283 |
+
check_audio=not args.no_check_audio,
|
| 284 |
+
minimum_free_vram_gib=args.minimum_free_vram_gib,
|
| 285 |
+
test_manifest=args.test_manifest,
|
| 286 |
+
)
|
| 287 |
+
if args.command == "evaluate":
|
| 288 |
+
return evaluate_hf_model(
|
| 289 |
+
args.model,
|
| 290 |
+
args.manifest,
|
| 291 |
+
args.output_dir,
|
| 292 |
+
device=args.device,
|
| 293 |
+
max_new_tokens=args.max_new_tokens,
|
| 294 |
+
)
|
| 295 |
+
if args.command == "merge-lora":
|
| 296 |
+
return merge_lora_adapter(args.base_model, args.adapter_dir, args.output_dir)
|
| 297 |
+
if args.command == "export-whisper-cpp":
|
| 298 |
+
return export_whisper_cpp(
|
| 299 |
+
args.model_dir,
|
| 300 |
+
args.whisper_cpp_dir,
|
| 301 |
+
args.openai_whisper_dir,
|
| 302 |
+
args.output_dir,
|
| 303 |
+
name=args.name,
|
| 304 |
+
quantization=args.quantization,
|
| 305 |
+
build_if_needed=args.build_if_needed,
|
| 306 |
+
)
|
| 307 |
+
if args.command == "score":
|
| 308 |
+
references = Path(args.references).read_text(encoding="utf-8").splitlines()
|
| 309 |
+
hypotheses = Path(args.hypotheses).read_text(encoding="utf-8").splitlines()
|
| 310 |
+
return score_pairs(references, hypotheses)
|
| 311 |
+
if args.command == "benchmark-server":
|
| 312 |
+
return benchmark_whisper_server(
|
| 313 |
+
args.manifest,
|
| 314 |
+
args.output_dir,
|
| 315 |
+
server_url=args.url,
|
| 316 |
+
concurrency=args.concurrency,
|
| 317 |
+
limit=args.limit,
|
| 318 |
+
seed=args.seed,
|
| 319 |
+
timeout=args.timeout,
|
| 320 |
+
)
|
| 321 |
+
raise AssertionError(f"Unhandled command: {args.command}")
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
def main(argv: Sequence[str] | None = None) -> int:
|
| 325 |
+
parser = build_parser()
|
| 326 |
+
args = parser.parse_args(argv)
|
| 327 |
+
try:
|
| 328 |
+
result = dispatch(args)
|
| 329 |
+
except (BuddiASRError, OSError, RuntimeError, ValueError, subprocess.SubprocessError) as exc:
|
| 330 |
+
print(f"error: {exc}", file=sys.stderr)
|
| 331 |
+
return 2
|
| 332 |
+
rank = os.environ.get("RANK", os.environ.get("LOCAL_RANK", "0"))
|
| 333 |
+
if rank == "0":
|
| 334 |
+
_json_output(result)
|
| 335 |
+
if args.command == "validate" and not result.get("ok", False):
|
| 336 |
+
return 2
|
| 337 |
+
return 0
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
if __name__ == "__main__":
|
| 341 |
+
raise SystemExit(main())
|
src/buddi_asr/config.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Small JSON configuration helpers.
|
| 2 |
+
|
| 3 |
+
JSON is intentionally used instead of YAML so data preparation and validation
|
| 4 |
+
stay dependency-free on a Raspberry Pi or CI worker.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import json
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
from typing import Any
|
| 12 |
+
|
| 13 |
+
from buddi_asr.errors import ConfigurationError
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def load_json(path: str | Path) -> dict[str, Any]:
|
| 17 |
+
config_path = Path(path)
|
| 18 |
+
try:
|
| 19 |
+
value = json.loads(config_path.read_text(encoding="utf-8"))
|
| 20 |
+
except FileNotFoundError as exc:
|
| 21 |
+
raise ConfigurationError(f"Configuration file not found: {config_path}") from exc
|
| 22 |
+
except json.JSONDecodeError as exc:
|
| 23 |
+
raise ConfigurationError(
|
| 24 |
+
f"Invalid JSON in {config_path} at line {exc.lineno}, column {exc.colno}: {exc.msg}"
|
| 25 |
+
) from exc
|
| 26 |
+
if not isinstance(value, dict):
|
| 27 |
+
raise ConfigurationError(f"Configuration root must be an object: {config_path}")
|
| 28 |
+
return value
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def require_keys(value: dict[str, Any], keys: tuple[str, ...], *, context: str) -> None:
|
| 32 |
+
missing = [key for key in keys if key not in value]
|
| 33 |
+
if missing:
|
| 34 |
+
raise ConfigurationError(f"{context} is missing required keys: {', '.join(missing)}")
|
src/buddi_asr/data/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""Dataset adapters and manifest operations."""
|
src/buddi_asr/data/abjad.py
ADDED
|
@@ -0,0 +1,312 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Abjad-Kids ingestion with label audit and identity pseudonymization."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import csv
|
| 6 |
+
import errno
|
| 7 |
+
import hashlib
|
| 8 |
+
import hmac
|
| 9 |
+
import json
|
| 10 |
+
import os
|
| 11 |
+
import re
|
| 12 |
+
import shutil
|
| 13 |
+
import unicodedata
|
| 14 |
+
import wave
|
| 15 |
+
from collections import Counter
|
| 16 |
+
from dataclasses import dataclass
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
from typing import Any
|
| 19 |
+
|
| 20 |
+
from buddi_asr.data.manifest import ManifestRecord, write_manifest
|
| 21 |
+
from buddi_asr.errors import ManifestError, OptionalDependencyError
|
| 22 |
+
|
| 23 |
+
ABJAD_REPO_ID = "Aziz-snoubra/Abjad-Kids"
|
| 24 |
+
ABJAD_CSV_FILES = ("alphabet.csv", "colors.csv", "numbers.csv")
|
| 25 |
+
UUID_RE = re.compile(
|
| 26 |
+
r"(?P<uuid>[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-"
|
| 27 |
+
r"[0-9a-fA-F]{4}-[0-9a-fA-F]{12})(?:_(?P<take>\d+))?$"
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@dataclass(frozen=True, slots=True)
|
| 32 |
+
class ParsedFilename:
|
| 33 |
+
speaker_hint: str | None
|
| 34 |
+
session_uuid: str
|
| 35 |
+
take: int
|
| 36 |
+
quality: str
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def download_abjad(
|
| 40 |
+
destination: str | Path,
|
| 41 |
+
*,
|
| 42 |
+
revision: str = "main",
|
| 43 |
+
token: str | None = None,
|
| 44 |
+
) -> Path:
|
| 45 |
+
"""Download the dataset repository without committing any of its content."""
|
| 46 |
+
|
| 47 |
+
try:
|
| 48 |
+
from huggingface_hub import snapshot_download
|
| 49 |
+
except ImportError as exc:
|
| 50 |
+
raise OptionalDependencyError(
|
| 51 |
+
"Downloading Abjad-Kids requires: python -m pip install -e '.[data]'"
|
| 52 |
+
) from exc
|
| 53 |
+
destination_path = Path(destination).resolve()
|
| 54 |
+
destination_path.mkdir(parents=True, exist_ok=True)
|
| 55 |
+
snapshot_download(
|
| 56 |
+
repo_id=ABJAD_REPO_ID,
|
| 57 |
+
repo_type="dataset",
|
| 58 |
+
revision=revision,
|
| 59 |
+
local_dir=destination_path,
|
| 60 |
+
token=token,
|
| 61 |
+
)
|
| 62 |
+
return destination_path
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def _normalize_speaker_hint(value: str) -> str:
|
| 66 |
+
normalized = unicodedata.normalize("NFKC", value).casefold()
|
| 67 |
+
return " ".join(normalized.replace("_", " ").split())
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def parse_abjad_filename(audio_path: str, label: str) -> ParsedFilename:
|
| 71 |
+
"""Extract the dataset's implicit speaker/session fields.
|
| 72 |
+
|
| 73 |
+
The upstream dataset has no documented speaker column. Many filenames use
|
| 74 |
+
``label_speaker_uuid_take.wav``. This parser is therefore explicitly marked
|
| 75 |
+
heuristic, and session-only rows are surfaced by the audit.
|
| 76 |
+
"""
|
| 77 |
+
|
| 78 |
+
stem = Path(audio_path).stem
|
| 79 |
+
prefix = f"{label}_"
|
| 80 |
+
remainder = stem[len(prefix) :] if stem.casefold().startswith(prefix.casefold()) else stem
|
| 81 |
+
match = UUID_RE.search(remainder)
|
| 82 |
+
if not match:
|
| 83 |
+
raise ManifestError(f"Cannot parse Abjad-Kids session UUID from: {audio_path}")
|
| 84 |
+
speaker_part = remainder[: match.start()].strip(" _-")
|
| 85 |
+
take = int(match.group("take") or 1)
|
| 86 |
+
session_uuid = match.group("uuid").lower()
|
| 87 |
+
if not speaker_part:
|
| 88 |
+
return ParsedFilename(None, session_uuid, take, "session_only")
|
| 89 |
+
return ParsedFilename(
|
| 90 |
+
_normalize_speaker_hint(speaker_part), session_uuid, take, "filename_heuristic"
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def pseudonymize(value: str, salt: str, *, namespace: str) -> str:
|
| 95 |
+
if len(salt.encode("utf-8")) < 16:
|
| 96 |
+
raise ManifestError("Pseudonymization salt must contain at least 16 UTF-8 bytes")
|
| 97 |
+
digest = hmac.new(
|
| 98 |
+
salt.encode("utf-8"), f"{namespace}:{value}".encode(), hashlib.sha256
|
| 99 |
+
).hexdigest()
|
| 100 |
+
return f"{namespace}_{digest[:24]}"
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def load_label_map(path: str | Path) -> tuple[dict[str, str], dict[str, Any]]:
|
| 104 |
+
label_path = Path(path)
|
| 105 |
+
try:
|
| 106 |
+
payload = json.loads(label_path.read_text(encoding="utf-8"))
|
| 107 |
+
except FileNotFoundError as exc:
|
| 108 |
+
raise ManifestError(f"Label map not found: {label_path}") from exc
|
| 109 |
+
except json.JSONDecodeError as exc:
|
| 110 |
+
raise ManifestError(f"Invalid label-map JSON: {label_path}: {exc.msg}") from exc
|
| 111 |
+
labels = payload.get("labels")
|
| 112 |
+
if not isinstance(labels, dict) or not labels:
|
| 113 |
+
raise ManifestError("Label map must contain a non-empty 'labels' object")
|
| 114 |
+
if not all(isinstance(key, str) and isinstance(value, str) for key, value in labels.items()):
|
| 115 |
+
raise ManifestError("All label-map keys and values must be strings")
|
| 116 |
+
return labels, payload.get("_meta", {})
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def load_speaker_overrides(path: str | Path | None) -> dict[str, str]:
|
| 120 |
+
"""Load ``source_file_id -> anonymous speaker group`` corrections."""
|
| 121 |
+
|
| 122 |
+
if path is None:
|
| 123 |
+
return {}
|
| 124 |
+
override_path = Path(path)
|
| 125 |
+
try:
|
| 126 |
+
value = json.loads(override_path.read_text(encoding="utf-8"))
|
| 127 |
+
except (OSError, json.JSONDecodeError) as exc:
|
| 128 |
+
raise ManifestError(f"Cannot load speaker overrides from {override_path}: {exc}") from exc
|
| 129 |
+
if not isinstance(value, dict) or not all(
|
| 130 |
+
isinstance(key, str) and isinstance(item, str) for key, item in value.items()
|
| 131 |
+
):
|
| 132 |
+
raise ManifestError("Speaker overrides must be a JSON object of string-to-string values")
|
| 133 |
+
return value
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def _wav_duration(path: Path) -> float | None:
|
| 137 |
+
try:
|
| 138 |
+
with wave.open(str(path), "rb") as audio:
|
| 139 |
+
frames = audio.getnframes()
|
| 140 |
+
rate = audio.getframerate()
|
| 141 |
+
return frames / rate if rate else None
|
| 142 |
+
except (wave.Error, OSError):
|
| 143 |
+
return None
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def _materialize(source: Path, destination: Path, mode: str) -> None:
|
| 147 |
+
destination.parent.mkdir(parents=True, exist_ok=True)
|
| 148 |
+
if destination.exists():
|
| 149 |
+
if destination.stat().st_size != source.stat().st_size:
|
| 150 |
+
raise ManifestError(f"Refusing to replace conflicting processed audio: {destination}")
|
| 151 |
+
return
|
| 152 |
+
if mode == "copy":
|
| 153 |
+
shutil.copy2(source, destination)
|
| 154 |
+
return
|
| 155 |
+
if mode == "symlink":
|
| 156 |
+
destination.symlink_to(source.resolve())
|
| 157 |
+
return
|
| 158 |
+
if mode != "hardlink":
|
| 159 |
+
raise ManifestError("audio_mode must be hardlink, copy, symlink, or reference")
|
| 160 |
+
try:
|
| 161 |
+
os.link(source, destination)
|
| 162 |
+
except OSError as exc:
|
| 163 |
+
if exc.errno not in {errno.EXDEV, errno.EPERM, errno.EACCES, errno.ENOTSUP}:
|
| 164 |
+
raise
|
| 165 |
+
shutil.copy2(source, destination)
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def _manifest_audio_value(audio_path: Path, manifest_path: Path) -> str:
|
| 169 |
+
try:
|
| 170 |
+
relative = os.path.relpath(audio_path.resolve(), manifest_path.resolve().parent)
|
| 171 |
+
except ValueError:
|
| 172 |
+
return str(audio_path.resolve())
|
| 173 |
+
return Path(relative).as_posix()
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def prepare_abjad(
|
| 177 |
+
dataset_root: str | Path,
|
| 178 |
+
output_manifest: str | Path,
|
| 179 |
+
*,
|
| 180 |
+
label_map_path: str | Path,
|
| 181 |
+
salt: str,
|
| 182 |
+
processed_audio_dir: str | Path | None = None,
|
| 183 |
+
audio_mode: str = "hardlink",
|
| 184 |
+
speaker_overrides_path: str | Path | None = None,
|
| 185 |
+
skip_missing: bool = False,
|
| 186 |
+
) -> dict[str, Any]:
|
| 187 |
+
"""Create an anonymized JSONL manifest and a machine-readable audit."""
|
| 188 |
+
|
| 189 |
+
root = Path(dataset_root).resolve()
|
| 190 |
+
manifest_path = Path(output_manifest).resolve()
|
| 191 |
+
if not root.is_dir():
|
| 192 |
+
raise ManifestError(f"Dataset root is not a directory: {root}")
|
| 193 |
+
if audio_mode != "reference" and processed_audio_dir is None:
|
| 194 |
+
raise ManifestError("processed_audio_dir is required unless audio_mode=reference")
|
| 195 |
+
|
| 196 |
+
label_map, label_meta = load_label_map(label_map_path)
|
| 197 |
+
speaker_overrides = load_speaker_overrides(speaker_overrides_path)
|
| 198 |
+
processed_root = Path(processed_audio_dir).resolve() if processed_audio_dir else None
|
| 199 |
+
|
| 200 |
+
records: list[ManifestRecord] = []
|
| 201 |
+
total_audio_seconds = 0.0
|
| 202 |
+
category_counts: Counter[str] = Counter()
|
| 203 |
+
label_counts: Counter[str] = Counter()
|
| 204 |
+
parse_quality_counts: Counter[str] = Counter()
|
| 205 |
+
missing_files: list[str] = []
|
| 206 |
+
unknown_labels: set[str] = set()
|
| 207 |
+
seen_source_ids: set[str] = set()
|
| 208 |
+
|
| 209 |
+
for csv_name in ABJAD_CSV_FILES:
|
| 210 |
+
category = Path(csv_name).stem
|
| 211 |
+
csv_path = root / csv_name
|
| 212 |
+
if not csv_path.is_file():
|
| 213 |
+
raise ManifestError(f"Expected Abjad-Kids metadata file is missing: {csv_path}")
|
| 214 |
+
with csv_path.open(encoding="utf-8-sig", newline="") as handle:
|
| 215 |
+
reader = csv.DictReader(handle)
|
| 216 |
+
if reader.fieldnames is None or not {"audio", "label"}.issubset(reader.fieldnames):
|
| 217 |
+
raise ManifestError(f"{csv_path} must contain audio and label columns")
|
| 218 |
+
for row_number, row in enumerate(reader, start=2):
|
| 219 |
+
relative_audio = row["audio"].strip()
|
| 220 |
+
label = row["label"].strip()
|
| 221 |
+
transcript = label_map.get(label)
|
| 222 |
+
if transcript is None:
|
| 223 |
+
unknown_labels.add(label)
|
| 224 |
+
continue
|
| 225 |
+
source = (root / relative_audio).resolve()
|
| 226 |
+
if not source.is_file():
|
| 227 |
+
missing_files.append(relative_audio)
|
| 228 |
+
if skip_missing:
|
| 229 |
+
continue
|
| 230 |
+
raise ManifestError(f"Missing audio referenced by {csv_path}:{row_number}: {source}")
|
| 231 |
+
|
| 232 |
+
parsed = parse_abjad_filename(relative_audio, label)
|
| 233 |
+
source_file_id = pseudonymize(relative_audio, salt, namespace="file")
|
| 234 |
+
if source_file_id in seen_source_ids:
|
| 235 |
+
raise ManifestError(f"Duplicate audio entry at {csv_path}:{row_number}")
|
| 236 |
+
seen_source_ids.add(source_file_id)
|
| 237 |
+
|
| 238 |
+
override = speaker_overrides.get(source_file_id)
|
| 239 |
+
if override:
|
| 240 |
+
speaker_basis = f"override:{override}"
|
| 241 |
+
parse_quality = "manual_override"
|
| 242 |
+
elif parsed.speaker_hint:
|
| 243 |
+
speaker_basis = f"name:{parsed.speaker_hint}"
|
| 244 |
+
parse_quality = parsed.quality
|
| 245 |
+
else:
|
| 246 |
+
speaker_basis = f"session:{parsed.session_uuid}"
|
| 247 |
+
parse_quality = parsed.quality
|
| 248 |
+
speaker_id = pseudonymize(speaker_basis, salt, namespace="speaker")
|
| 249 |
+
session_id = pseudonymize(parsed.session_uuid, salt, namespace="session")
|
| 250 |
+
|
| 251 |
+
if audio_mode == "reference":
|
| 252 |
+
final_audio = source
|
| 253 |
+
else:
|
| 254 |
+
assert processed_root is not None
|
| 255 |
+
opaque_name = source_file_id.removeprefix("file_") + source.suffix.lower()
|
| 256 |
+
final_audio = processed_root / opaque_name[:2] / opaque_name
|
| 257 |
+
_materialize(source, final_audio, audio_mode)
|
| 258 |
+
|
| 259 |
+
duration = _wav_duration(source)
|
| 260 |
+
record = ManifestRecord(
|
| 261 |
+
audio=_manifest_audio_value(final_audio, manifest_path),
|
| 262 |
+
text=transcript,
|
| 263 |
+
language="ar",
|
| 264 |
+
dialect="msa_levantine",
|
| 265 |
+
age_group="3-12",
|
| 266 |
+
speaker_id=speaker_id,
|
| 267 |
+
source="abjad_kids",
|
| 268 |
+
category=category,
|
| 269 |
+
license="MIT",
|
| 270 |
+
duration_sec=duration,
|
| 271 |
+
metadata={
|
| 272 |
+
"original_label": label,
|
| 273 |
+
"session_id": session_id,
|
| 274 |
+
"source_file_id": source_file_id,
|
| 275 |
+
"speaker_parse_quality": parse_quality,
|
| 276 |
+
"take": parsed.take,
|
| 277 |
+
},
|
| 278 |
+
)
|
| 279 |
+
record.validate()
|
| 280 |
+
records.append(record)
|
| 281 |
+
if duration is not None:
|
| 282 |
+
total_audio_seconds += duration
|
| 283 |
+
category_counts[category] += 1
|
| 284 |
+
label_counts[label] += 1
|
| 285 |
+
parse_quality_counts[parse_quality] += 1
|
| 286 |
+
|
| 287 |
+
if unknown_labels:
|
| 288 |
+
raise ManifestError(
|
| 289 |
+
"Unmapped Abjad-Kids labels; review instead of silently training them: "
|
| 290 |
+
+ ", ".join(sorted(unknown_labels))
|
| 291 |
+
)
|
| 292 |
+
write_manifest(records, manifest_path)
|
| 293 |
+
speakers = {record.speaker_id for record in records}
|
| 294 |
+
return {
|
| 295 |
+
"dataset": ABJAD_REPO_ID,
|
| 296 |
+
"manifest": str(manifest_path),
|
| 297 |
+
"records": len(records),
|
| 298 |
+
"speakers": len(speakers),
|
| 299 |
+
"labels_observed": len(label_counts),
|
| 300 |
+
"labels_mapped": len(label_map),
|
| 301 |
+
"label_counts": dict(sorted(label_counts.items())),
|
| 302 |
+
"label_map_expected": label_meta.get("expected_labels"),
|
| 303 |
+
"audio_hours": total_audio_seconds / 3600.0,
|
| 304 |
+
"categories": dict(sorted(category_counts.items())),
|
| 305 |
+
"speaker_parse_quality": dict(sorted(parse_quality_counts.items())),
|
| 306 |
+
"missing_files_skipped": len(missing_files),
|
| 307 |
+
"review_required_labels": label_meta.get("review_required", []),
|
| 308 |
+
"warning": (
|
| 309 |
+
"Filename-derived speaker groups are heuristic. Resolve session_only rows with an "
|
| 310 |
+
"anonymous override map before publishing final metrics."
|
| 311 |
+
),
|
| 312 |
+
}
|
src/buddi_asr/data/local.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Importer for consented Buddi/Gulf child speech collected outside Abjad-Kids."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import csv
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from typing import Any
|
| 8 |
+
|
| 9 |
+
from buddi_asr.data.abjad import (
|
| 10 |
+
_manifest_audio_value,
|
| 11 |
+
_materialize,
|
| 12 |
+
_wav_duration,
|
| 13 |
+
pseudonymize,
|
| 14 |
+
)
|
| 15 |
+
from buddi_asr.data.manifest import ManifestRecord, write_manifest
|
| 16 |
+
from buddi_asr.errors import ManifestError
|
| 17 |
+
|
| 18 |
+
REQUIRED_COLUMNS = {"audio", "text", "speaker_key", "language", "consent_basis"}
|
| 19 |
+
ALLOWED_CONSENT_BASES = {"verified_parental_consent", "public_research_license"}
|
| 20 |
+
SAFE_OPTIONAL_COLUMNS = {
|
| 21 |
+
"age_group",
|
| 22 |
+
"category",
|
| 23 |
+
"device",
|
| 24 |
+
"dialect",
|
| 25 |
+
"gender_optional",
|
| 26 |
+
"license",
|
| 27 |
+
"noise_level",
|
| 28 |
+
"split",
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def import_local_csv(
|
| 33 |
+
input_csv: str | Path,
|
| 34 |
+
output_manifest: str | Path,
|
| 35 |
+
*,
|
| 36 |
+
processed_audio_dir: str | Path,
|
| 37 |
+
salt: str,
|
| 38 |
+
source_name: str = "buddi_consent_collection",
|
| 39 |
+
audio_mode: str = "hardlink",
|
| 40 |
+
) -> dict[str, Any]:
|
| 41 |
+
"""Import a private CSV while stripping direct identity from the output."""
|
| 42 |
+
|
| 43 |
+
csv_path = Path(input_csv).resolve()
|
| 44 |
+
manifest_path = Path(output_manifest).resolve()
|
| 45 |
+
processed_root = Path(processed_audio_dir).resolve()
|
| 46 |
+
if not csv_path.is_file():
|
| 47 |
+
raise ManifestError(f"Input CSV not found: {csv_path}")
|
| 48 |
+
|
| 49 |
+
records: list[ManifestRecord] = []
|
| 50 |
+
seen_files: set[str] = set()
|
| 51 |
+
with csv_path.open(encoding="utf-8-sig", newline="") as handle:
|
| 52 |
+
reader = csv.DictReader(handle)
|
| 53 |
+
fields = set(reader.fieldnames or [])
|
| 54 |
+
missing = REQUIRED_COLUMNS - fields
|
| 55 |
+
if missing:
|
| 56 |
+
raise ManifestError("Input CSV is missing columns: " + ", ".join(sorted(missing)))
|
| 57 |
+
unsafe_extra = fields - REQUIRED_COLUMNS - SAFE_OPTIONAL_COLUMNS
|
| 58 |
+
if unsafe_extra:
|
| 59 |
+
raise ManifestError(
|
| 60 |
+
"Unrecognized columns are blocked to prevent accidental PII export: "
|
| 61 |
+
+ ", ".join(sorted(unsafe_extra))
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
for line_number, row in enumerate(reader, start=2):
|
| 65 |
+
consent_basis = row["consent_basis"].strip()
|
| 66 |
+
if consent_basis not in ALLOWED_CONSENT_BASES:
|
| 67 |
+
raise ManifestError(
|
| 68 |
+
f"{csv_path}:{line_number}: consent_basis must be one of "
|
| 69 |
+
+ ", ".join(sorted(ALLOWED_CONSENT_BASES))
|
| 70 |
+
)
|
| 71 |
+
relative_audio = row["audio"].strip()
|
| 72 |
+
source_audio = (csv_path.parent / relative_audio).resolve()
|
| 73 |
+
if not source_audio.is_file():
|
| 74 |
+
raise ManifestError(f"{csv_path}:{line_number}: audio not found: {source_audio}")
|
| 75 |
+
source_file_id = pseudonymize(relative_audio, salt, namespace="file")
|
| 76 |
+
if source_file_id in seen_files:
|
| 77 |
+
raise ManifestError(f"{csv_path}:{line_number}: duplicate audio row")
|
| 78 |
+
seen_files.add(source_file_id)
|
| 79 |
+
|
| 80 |
+
opaque_name = source_file_id.removeprefix("file_") + source_audio.suffix.lower()
|
| 81 |
+
final_audio = processed_root / opaque_name[:2] / opaque_name
|
| 82 |
+
_materialize(source_audio, final_audio, audio_mode)
|
| 83 |
+
speaker_id = pseudonymize(row["speaker_key"].strip(), salt, namespace="speaker")
|
| 84 |
+
metadata = {
|
| 85 |
+
"consent_basis": consent_basis,
|
| 86 |
+
"source_file_id": source_file_id,
|
| 87 |
+
}
|
| 88 |
+
for key in ("device", "gender_optional", "noise_level"):
|
| 89 |
+
value = row.get(key, "").strip()
|
| 90 |
+
if value:
|
| 91 |
+
metadata[key] = value
|
| 92 |
+
record = ManifestRecord(
|
| 93 |
+
audio=_manifest_audio_value(final_audio, manifest_path),
|
| 94 |
+
text=row["text"].strip(),
|
| 95 |
+
language=row["language"].strip(),
|
| 96 |
+
dialect=row.get("dialect", "").strip() or "unknown",
|
| 97 |
+
age_group=row.get("age_group", "").strip() or "unknown",
|
| 98 |
+
speaker_id=speaker_id,
|
| 99 |
+
source=source_name,
|
| 100 |
+
category=row.get("category", "").strip() or "conversation",
|
| 101 |
+
license=row.get("license", "").strip() or "private-consented",
|
| 102 |
+
duration_sec=_wav_duration(source_audio),
|
| 103 |
+
split=row.get("split", "").strip() or None,
|
| 104 |
+
metadata=metadata,
|
| 105 |
+
)
|
| 106 |
+
record.validate()
|
| 107 |
+
records.append(record)
|
| 108 |
+
|
| 109 |
+
write_manifest(records, manifest_path)
|
| 110 |
+
return {
|
| 111 |
+
"manifest": str(manifest_path),
|
| 112 |
+
"records": len(records),
|
| 113 |
+
"speakers": len({record.speaker_id for record in records}),
|
| 114 |
+
"source": source_name,
|
| 115 |
+
"direct_identity_exported": False,
|
| 116 |
+
}
|
src/buddi_asr/data/manifest.py
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Canonical, privacy-aware JSONL manifest contract."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import json
|
| 6 |
+
import os
|
| 7 |
+
from collections.abc import Iterable, Iterator
|
| 8 |
+
from dataclasses import asdict, dataclass, field
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
from typing import Any
|
| 11 |
+
|
| 12 |
+
from buddi_asr.errors import ManifestError
|
| 13 |
+
|
| 14 |
+
ALLOWED_SPLITS = {None, "train", "validation", "test"}
|
| 15 |
+
FORBIDDEN_METADATA_KEYS = {
|
| 16 |
+
"child_name",
|
| 17 |
+
"full_name",
|
| 18 |
+
"name",
|
| 19 |
+
"parent_name",
|
| 20 |
+
"speaker_name",
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
@dataclass(slots=True)
|
| 25 |
+
class ManifestRecord:
|
| 26 |
+
"""One utterance with no direct child identity.
|
| 27 |
+
|
| 28 |
+
``audio`` should be relative to the manifest whenever possible. ``speaker_id``
|
| 29 |
+
must be an opaque pseudonym. Never place a child's real name in metadata.
|
| 30 |
+
"""
|
| 31 |
+
|
| 32 |
+
audio: str
|
| 33 |
+
text: str
|
| 34 |
+
language: str
|
| 35 |
+
speaker_id: str
|
| 36 |
+
source: str
|
| 37 |
+
dialect: str = "unknown"
|
| 38 |
+
age_group: str = "unknown"
|
| 39 |
+
category: str = "unknown"
|
| 40 |
+
license: str = "unknown"
|
| 41 |
+
duration_sec: float | None = None
|
| 42 |
+
split: str | None = None
|
| 43 |
+
metadata: dict[str, Any] = field(default_factory=dict)
|
| 44 |
+
|
| 45 |
+
def validate(self) -> None:
|
| 46 |
+
for key in ("audio", "text", "language", "speaker_id", "source"):
|
| 47 |
+
value = getattr(self, key)
|
| 48 |
+
if not isinstance(value, str) or not value.strip():
|
| 49 |
+
raise ManifestError(f"Manifest field '{key}' must be a non-empty string")
|
| 50 |
+
if self.split not in ALLOWED_SPLITS:
|
| 51 |
+
raise ManifestError(
|
| 52 |
+
f"Invalid split '{self.split}'; expected train, validation, test, or null"
|
| 53 |
+
)
|
| 54 |
+
if self.duration_sec is not None and (
|
| 55 |
+
not isinstance(self.duration_sec, (int, float)) or self.duration_sec <= 0
|
| 56 |
+
):
|
| 57 |
+
raise ManifestError("duration_sec must be positive when present")
|
| 58 |
+
if not isinstance(self.metadata, dict):
|
| 59 |
+
raise ManifestError("metadata must be an object")
|
| 60 |
+
lowered = {str(key).casefold() for key in self.metadata}
|
| 61 |
+
leaked = sorted(lowered & FORBIDDEN_METADATA_KEYS)
|
| 62 |
+
if leaked:
|
| 63 |
+
raise ManifestError(
|
| 64 |
+
"Direct identity keys are forbidden in metadata: " + ", ".join(leaked)
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
@classmethod
|
| 68 |
+
def from_dict(cls, value: dict[str, Any]) -> ManifestRecord:
|
| 69 |
+
if not isinstance(value, dict):
|
| 70 |
+
raise ManifestError("Each JSONL line must contain an object")
|
| 71 |
+
known = {field_.name for field_ in cls.__dataclass_fields__.values()}
|
| 72 |
+
unexpected = sorted(set(value) - known)
|
| 73 |
+
if unexpected:
|
| 74 |
+
raise ManifestError("Unknown manifest fields: " + ", ".join(unexpected))
|
| 75 |
+
try:
|
| 76 |
+
record = cls(**value)
|
| 77 |
+
except TypeError as exc:
|
| 78 |
+
raise ManifestError(f"Invalid manifest record: {exc}") from exc
|
| 79 |
+
record.validate()
|
| 80 |
+
return record
|
| 81 |
+
|
| 82 |
+
def to_dict(self) -> dict[str, Any]:
|
| 83 |
+
self.validate()
|
| 84 |
+
return asdict(self)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def read_manifest(path: str | Path) -> Iterator[ManifestRecord]:
|
| 88 |
+
manifest_path = Path(path)
|
| 89 |
+
try:
|
| 90 |
+
handle = manifest_path.open(encoding="utf-8")
|
| 91 |
+
except FileNotFoundError as exc:
|
| 92 |
+
raise ManifestError(f"Manifest not found: {manifest_path}") from exc
|
| 93 |
+
with handle:
|
| 94 |
+
for line_number, line in enumerate(handle, start=1):
|
| 95 |
+
if not line.strip():
|
| 96 |
+
continue
|
| 97 |
+
try:
|
| 98 |
+
payload = json.loads(line)
|
| 99 |
+
except json.JSONDecodeError as exc:
|
| 100 |
+
raise ManifestError(
|
| 101 |
+
f"Invalid JSON at {manifest_path}:{line_number}: {exc.msg}"
|
| 102 |
+
) from exc
|
| 103 |
+
try:
|
| 104 |
+
yield ManifestRecord.from_dict(payload)
|
| 105 |
+
except ManifestError as exc:
|
| 106 |
+
raise ManifestError(f"{manifest_path}:{line_number}: {exc}") from exc
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def write_manifest(records: Iterable[ManifestRecord], path: str | Path) -> int:
|
| 110 |
+
manifest_path = Path(path)
|
| 111 |
+
manifest_path.parent.mkdir(parents=True, exist_ok=True)
|
| 112 |
+
count = 0
|
| 113 |
+
with manifest_path.open("w", encoding="utf-8", newline="\n") as handle:
|
| 114 |
+
for record in records:
|
| 115 |
+
handle.write(
|
| 116 |
+
json.dumps(record.to_dict(), ensure_ascii=False, sort_keys=True, separators=(",", ":"))
|
| 117 |
+
+ "\n"
|
| 118 |
+
)
|
| 119 |
+
count += 1
|
| 120 |
+
return count
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def resolve_audio_path(record: ManifestRecord, manifest_path: str | Path) -> Path:
|
| 124 |
+
audio_path = Path(record.audio)
|
| 125 |
+
if audio_path.is_absolute():
|
| 126 |
+
return audio_path
|
| 127 |
+
return (Path(manifest_path).resolve().parent / audio_path).resolve()
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def rebase_audio_path(
|
| 131 |
+
record: ManifestRecord,
|
| 132 |
+
source_manifest: str | Path,
|
| 133 |
+
destination_manifest: str | Path,
|
| 134 |
+
) -> ManifestRecord:
|
| 135 |
+
"""Copy a record while preserving its audio target from a new manifest directory."""
|
| 136 |
+
|
| 137 |
+
resolved = resolve_audio_path(record, source_manifest)
|
| 138 |
+
try:
|
| 139 |
+
rebased = os.path.relpath(resolved, Path(destination_manifest).resolve().parent)
|
| 140 |
+
audio = Path(rebased).as_posix()
|
| 141 |
+
except ValueError:
|
| 142 |
+
audio = str(resolved)
|
| 143 |
+
payload = record.to_dict()
|
| 144 |
+
payload["audio"] = audio
|
| 145 |
+
return ManifestRecord.from_dict(payload)
|
src/buddi_asr/data/mix.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Reproducible weighted mixing of prepared manifests without silent duplication."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import heapq
|
| 6 |
+
import random
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from typing import Any
|
| 9 |
+
|
| 10 |
+
from buddi_asr.config import load_json, require_keys
|
| 11 |
+
from buddi_asr.data.manifest import (
|
| 12 |
+
ManifestRecord,
|
| 13 |
+
read_manifest,
|
| 14 |
+
rebase_audio_path,
|
| 15 |
+
write_manifest,
|
| 16 |
+
)
|
| 17 |
+
from buddi_asr.errors import ConfigurationError
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def allocate_quotas(capacities: list[int], weights: list[float], target_size: int) -> list[int]:
|
| 21 |
+
if len(capacities) != len(weights) or not capacities:
|
| 22 |
+
raise ConfigurationError("capacities and weights must be non-empty and have equal length")
|
| 23 |
+
if target_size <= 0:
|
| 24 |
+
raise ConfigurationError("target_size must be positive")
|
| 25 |
+
if target_size > sum(capacities):
|
| 26 |
+
raise ConfigurationError(
|
| 27 |
+
f"target_size={target_size} exceeds {sum(capacities)} unique available records; "
|
| 28 |
+
"Buddi-ASR deliberately does not duplicate child utterances"
|
| 29 |
+
)
|
| 30 |
+
if any(capacity < 0 for capacity in capacities):
|
| 31 |
+
raise ConfigurationError("capacities cannot be negative")
|
| 32 |
+
if any(weight <= 0 for weight in weights):
|
| 33 |
+
raise ConfigurationError("all source weights must be positive")
|
| 34 |
+
|
| 35 |
+
quotas = [0] * len(capacities)
|
| 36 |
+
heap: list[tuple[float, int]] = []
|
| 37 |
+
for index, (capacity, weight) in enumerate(zip(capacities, weights, strict=True)):
|
| 38 |
+
if capacity:
|
| 39 |
+
heapq.heappush(heap, (1.0 / weight, index))
|
| 40 |
+
for _ in range(target_size):
|
| 41 |
+
if not heap:
|
| 42 |
+
raise AssertionError("quota allocator exhausted before reaching target")
|
| 43 |
+
_, index = heapq.heappop(heap)
|
| 44 |
+
quotas[index] += 1
|
| 45 |
+
if quotas[index] < capacities[index]:
|
| 46 |
+
heapq.heappush(heap, ((quotas[index] + 1) / weights[index], index))
|
| 47 |
+
return quotas
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def mix_manifests(config_path: str | Path, output_manifest: str | Path) -> dict[str, Any]:
|
| 51 |
+
config = load_json(config_path)
|
| 52 |
+
require_keys(config, ("sources", "target_size"), context="mix configuration")
|
| 53 |
+
sources = config["sources"]
|
| 54 |
+
if not isinstance(sources, list) or not sources:
|
| 55 |
+
raise ConfigurationError("mix configuration 'sources' must be a non-empty array")
|
| 56 |
+
target_size = config["target_size"]
|
| 57 |
+
if not isinstance(target_size, int):
|
| 58 |
+
raise ConfigurationError("mix target_size must be an integer")
|
| 59 |
+
seed = int(config.get("seed", 42))
|
| 60 |
+
output_path = Path(output_manifest).resolve()
|
| 61 |
+
|
| 62 |
+
source_paths: list[Path] = []
|
| 63 |
+
source_records: list[list[ManifestRecord]] = []
|
| 64 |
+
source_names: list[str] = []
|
| 65 |
+
weights: list[float] = []
|
| 66 |
+
for index, source in enumerate(sources):
|
| 67 |
+
if not isinstance(source, dict):
|
| 68 |
+
raise ConfigurationError(f"sources[{index}] must be an object")
|
| 69 |
+
require_keys(source, ("name", "manifest", "weight"), context=f"sources[{index}]")
|
| 70 |
+
manifest_path = Path(source["manifest"])
|
| 71 |
+
if not manifest_path.is_absolute():
|
| 72 |
+
manifest_path = (Path(config_path).resolve().parent / manifest_path).resolve()
|
| 73 |
+
records = list(read_manifest(manifest_path))
|
| 74 |
+
requested_split = source.get("split")
|
| 75 |
+
if requested_split:
|
| 76 |
+
records = [record for record in records if record.split == requested_split]
|
| 77 |
+
if not records:
|
| 78 |
+
raise ConfigurationError(f"source '{source['name']}' contains no selectable records")
|
| 79 |
+
source_paths.append(manifest_path)
|
| 80 |
+
source_records.append(records)
|
| 81 |
+
source_names.append(str(source["name"]))
|
| 82 |
+
weights.append(float(source["weight"]))
|
| 83 |
+
|
| 84 |
+
quotas = allocate_quotas([len(records) for records in source_records], weights, target_size)
|
| 85 |
+
selected: list[tuple[ManifestRecord, Path]] = []
|
| 86 |
+
for index, (records, quota) in enumerate(zip(source_records, quotas, strict=True)):
|
| 87 |
+
rng = random.Random(seed + index + 1)
|
| 88 |
+
for record in rng.sample(records, quota):
|
| 89 |
+
selected.append((record, source_paths[index]))
|
| 90 |
+
random.Random(seed).shuffle(selected)
|
| 91 |
+
|
| 92 |
+
rebased = [
|
| 93 |
+
rebase_audio_path(record, source_manifest, output_path)
|
| 94 |
+
for record, source_manifest in selected
|
| 95 |
+
]
|
| 96 |
+
write_manifest(rebased, output_path)
|
| 97 |
+
return {
|
| 98 |
+
"output": str(output_path),
|
| 99 |
+
"seed": seed,
|
| 100 |
+
"records": len(rebased),
|
| 101 |
+
"sources": [
|
| 102 |
+
{
|
| 103 |
+
"name": name,
|
| 104 |
+
"available": len(records),
|
| 105 |
+
"weight": weight,
|
| 106 |
+
"selected": quota,
|
| 107 |
+
}
|
| 108 |
+
for name, records, weight, quota in zip(
|
| 109 |
+
source_names, source_records, weights, quotas, strict=True
|
| 110 |
+
)
|
| 111 |
+
],
|
| 112 |
+
}
|
src/buddi_asr/data/split.py
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Deterministic speaker-disjoint, label-aware train/validation/test splitting."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import math
|
| 6 |
+
import random
|
| 7 |
+
from collections import Counter, defaultdict
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from typing import Any
|
| 10 |
+
|
| 11 |
+
from buddi_asr.data.manifest import (
|
| 12 |
+
ManifestRecord,
|
| 13 |
+
read_manifest,
|
| 14 |
+
rebase_audio_path,
|
| 15 |
+
write_manifest,
|
| 16 |
+
)
|
| 17 |
+
from buddi_asr.errors import ManifestError
|
| 18 |
+
|
| 19 |
+
SPLIT_ORDER = ("train", "validation", "test")
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def _validate_ratios(ratios: dict[str, float]) -> dict[str, float]:
|
| 23 |
+
if set(ratios) != set(SPLIT_ORDER):
|
| 24 |
+
raise ManifestError("ratios must contain exactly train, validation, and test")
|
| 25 |
+
if any(not isinstance(value, (int, float)) or value <= 0 for value in ratios.values()):
|
| 26 |
+
raise ManifestError("all split ratios must be positive numbers")
|
| 27 |
+
total = float(sum(ratios.values()))
|
| 28 |
+
if not math.isclose(total, 1.0, rel_tol=0, abs_tol=1e-8):
|
| 29 |
+
raise ManifestError(f"split ratios must sum to 1.0, got {total}")
|
| 30 |
+
return {name: float(ratios[name]) for name in SPLIT_ORDER}
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def _label_key(record: ManifestRecord) -> str:
|
| 34 |
+
return "\u241f".join((record.source, record.language, record.category, record.text))
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def _objective(
|
| 38 |
+
totals: dict[str, int],
|
| 39 |
+
labels: dict[str, Counter[str]],
|
| 40 |
+
target_totals: dict[str, float],
|
| 41 |
+
target_labels: dict[str, dict[str, float]],
|
| 42 |
+
all_labels: tuple[str, ...],
|
| 43 |
+
*,
|
| 44 |
+
label_weight: float,
|
| 45 |
+
) -> float:
|
| 46 |
+
total_cost = sum(
|
| 47 |
+
((totals[name] - target_totals[name]) ** 2) / max(target_totals[name], 1.0)
|
| 48 |
+
for name in SPLIT_ORDER
|
| 49 |
+
)
|
| 50 |
+
label_cost = 0.0
|
| 51 |
+
for name in SPLIT_ORDER:
|
| 52 |
+
for label in all_labels:
|
| 53 |
+
target = target_labels[name][label]
|
| 54 |
+
label_cost += ((labels[name][label] - target) ** 2) / max(target, 1.0)
|
| 55 |
+
return total_cost + label_weight * label_cost
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def assign_speaker_disjoint_splits(
|
| 59 |
+
records: list[ManifestRecord],
|
| 60 |
+
*,
|
| 61 |
+
ratios: dict[str, float],
|
| 62 |
+
seed: int,
|
| 63 |
+
label_weight: float = 0.25,
|
| 64 |
+
) -> dict[str, list[ManifestRecord]]:
|
| 65 |
+
ratios = _validate_ratios(ratios)
|
| 66 |
+
if len({record.speaker_id for record in records}) < len(SPLIT_ORDER):
|
| 67 |
+
raise ManifestError("At least three distinct speakers are required for three-way splitting")
|
| 68 |
+
|
| 69 |
+
groups: dict[str, list[ManifestRecord]] = defaultdict(list)
|
| 70 |
+
for record in records:
|
| 71 |
+
groups[record.speaker_id].append(record)
|
| 72 |
+
global_labels = Counter(_label_key(record) for record in records)
|
| 73 |
+
all_labels = tuple(sorted(global_labels))
|
| 74 |
+
target_totals = {name: len(records) * ratios[name] for name in SPLIT_ORDER}
|
| 75 |
+
target_labels = {
|
| 76 |
+
name: {label: global_labels[label] * ratios[name] for label in all_labels}
|
| 77 |
+
for name in SPLIT_ORDER
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
rng = random.Random(seed)
|
| 81 |
+
tie_breakers = {speaker: rng.random() for speaker in groups}
|
| 82 |
+
ordered_groups = sorted(
|
| 83 |
+
groups.items(),
|
| 84 |
+
key=lambda item: (
|
| 85 |
+
-len(item[1]),
|
| 86 |
+
-len({_label_key(record) for record in item[1]}),
|
| 87 |
+
tie_breakers[item[0]],
|
| 88 |
+
item[0],
|
| 89 |
+
),
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
+
assignments: dict[str, list[ManifestRecord]] = {name: [] for name in SPLIT_ORDER}
|
| 93 |
+
totals = {name: 0 for name in SPLIT_ORDER}
|
| 94 |
+
label_totals = {name: Counter() for name in SPLIT_ORDER}
|
| 95 |
+
|
| 96 |
+
for group_index, (_, group_records) in enumerate(ordered_groups):
|
| 97 |
+
group_labels = Counter(_label_key(record) for record in group_records)
|
| 98 |
+
# Seed every split with one speaker. Choosing the largest remaining target
|
| 99 |
+
# first avoids an empty evaluation split for small datasets.
|
| 100 |
+
if group_index < len(SPLIT_ORDER):
|
| 101 |
+
candidate_names = [
|
| 102 |
+
name for name in SPLIT_ORDER if not assignments[name]
|
| 103 |
+
]
|
| 104 |
+
else:
|
| 105 |
+
candidate_names = list(SPLIT_ORDER)
|
| 106 |
+
|
| 107 |
+
scored: list[tuple[float, float, str]] = []
|
| 108 |
+
for name in candidate_names:
|
| 109 |
+
candidate_totals = dict(totals)
|
| 110 |
+
candidate_labels = {key: Counter(value) for key, value in label_totals.items()}
|
| 111 |
+
candidate_totals[name] += len(group_records)
|
| 112 |
+
candidate_labels[name].update(group_labels)
|
| 113 |
+
score = _objective(
|
| 114 |
+
candidate_totals,
|
| 115 |
+
candidate_labels,
|
| 116 |
+
target_totals,
|
| 117 |
+
target_labels,
|
| 118 |
+
all_labels,
|
| 119 |
+
label_weight=label_weight,
|
| 120 |
+
)
|
| 121 |
+
deficit = target_totals[name] - totals[name]
|
| 122 |
+
scored.append((score, -deficit, name))
|
| 123 |
+
_, _, chosen = min(scored)
|
| 124 |
+
assignments[chosen].extend(group_records)
|
| 125 |
+
totals[chosen] += len(group_records)
|
| 126 |
+
label_totals[chosen].update(group_labels)
|
| 127 |
+
|
| 128 |
+
for offset, name in enumerate(SPLIT_ORDER):
|
| 129 |
+
split_rng = random.Random(seed + offset + 1)
|
| 130 |
+
split_rng.shuffle(assignments[name])
|
| 131 |
+
return assignments
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def split_manifest(
|
| 135 |
+
input_manifest: str | Path,
|
| 136 |
+
output_dir: str | Path,
|
| 137 |
+
*,
|
| 138 |
+
ratios: dict[str, float] | None = None,
|
| 139 |
+
seed: int = 42,
|
| 140 |
+
label_weight: float = 0.25,
|
| 141 |
+
) -> dict[str, Any]:
|
| 142 |
+
input_path = Path(input_manifest).resolve()
|
| 143 |
+
destination = Path(output_dir).resolve()
|
| 144 |
+
destination.mkdir(parents=True, exist_ok=True)
|
| 145 |
+
ratios = ratios or {"train": 0.8, "validation": 0.1, "test": 0.1}
|
| 146 |
+
records = list(read_manifest(input_path))
|
| 147 |
+
assignments = assign_speaker_disjoint_splits(
|
| 148 |
+
records, ratios=ratios, seed=seed, label_weight=label_weight
|
| 149 |
+
)
|
| 150 |
+
|
| 151 |
+
paths: dict[str, str] = {}
|
| 152 |
+
counts: dict[str, int] = {}
|
| 153 |
+
speakers_by_split: dict[str, set[str]] = {}
|
| 154 |
+
for name in SPLIT_ORDER:
|
| 155 |
+
output_path = destination / f"{name}.jsonl"
|
| 156 |
+
rebased: list[ManifestRecord] = []
|
| 157 |
+
for record in assignments[name]:
|
| 158 |
+
updated = rebase_audio_path(record, input_path, output_path)
|
| 159 |
+
updated.split = name
|
| 160 |
+
rebased.append(updated)
|
| 161 |
+
write_manifest(rebased, output_path)
|
| 162 |
+
paths[name] = str(output_path)
|
| 163 |
+
counts[name] = len(rebased)
|
| 164 |
+
speakers_by_split[name] = {record.speaker_id for record in rebased}
|
| 165 |
+
|
| 166 |
+
for left_index, left in enumerate(SPLIT_ORDER):
|
| 167 |
+
for right in SPLIT_ORDER[left_index + 1 :]:
|
| 168 |
+
overlap = speakers_by_split[left] & speakers_by_split[right]
|
| 169 |
+
if overlap:
|
| 170 |
+
raise AssertionError(f"Internal split error: {left}/{right} speaker overlap")
|
| 171 |
+
|
| 172 |
+
return {
|
| 173 |
+
"input": str(input_path),
|
| 174 |
+
"seed": seed,
|
| 175 |
+
"ratios_requested": _validate_ratios(ratios),
|
| 176 |
+
"records": len(records),
|
| 177 |
+
"counts": counts,
|
| 178 |
+
"actual_ratios": {
|
| 179 |
+
name: counts[name] / len(records) if records else 0.0 for name in SPLIT_ORDER
|
| 180 |
+
},
|
| 181 |
+
"speakers": {name: len(speakers_by_split[name]) for name in SPLIT_ORDER},
|
| 182 |
+
"paths": paths,
|
| 183 |
+
"speaker_overlap": 0,
|
| 184 |
+
}
|
src/buddi_asr/data/validate.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Manifest integrity, privacy, and split-leakage checks."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from collections import Counter, defaultdict
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from typing import Any
|
| 8 |
+
|
| 9 |
+
from buddi_asr.data.manifest import read_manifest, resolve_audio_path
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def validate_manifest(path: str | Path, *, check_audio: bool = True) -> dict[str, Any]:
|
| 13 |
+
manifest_path = Path(path).resolve()
|
| 14 |
+
records = list(read_manifest(manifest_path))
|
| 15 |
+
errors: list[str] = []
|
| 16 |
+
warnings: list[str] = []
|
| 17 |
+
seen_audio: set[str] = set()
|
| 18 |
+
speaker_splits: dict[str, set[str]] = defaultdict(set)
|
| 19 |
+
split_counts: Counter[str] = Counter()
|
| 20 |
+
language_counts: Counter[str] = Counter()
|
| 21 |
+
source_counts: Counter[str] = Counter()
|
| 22 |
+
parse_quality_counts: Counter[str] = Counter()
|
| 23 |
+
missing_duration = 0
|
| 24 |
+
|
| 25 |
+
for index, record in enumerate(records, start=1):
|
| 26 |
+
if record.audio in seen_audio:
|
| 27 |
+
errors.append(f"duplicate audio path at record {index}: {record.audio}")
|
| 28 |
+
seen_audio.add(record.audio)
|
| 29 |
+
if check_audio and not resolve_audio_path(record, manifest_path).is_file():
|
| 30 |
+
errors.append(f"audio not found at record {index}: {record.audio}")
|
| 31 |
+
if record.duration_sec is None:
|
| 32 |
+
missing_duration += 1
|
| 33 |
+
if record.split:
|
| 34 |
+
speaker_splits[record.speaker_id].add(record.split)
|
| 35 |
+
split_counts[record.split] += 1
|
| 36 |
+
language_counts[record.language] += 1
|
| 37 |
+
source_counts[record.source] += 1
|
| 38 |
+
quality = record.metadata.get("speaker_parse_quality")
|
| 39 |
+
if isinstance(quality, str):
|
| 40 |
+
parse_quality_counts[quality] += 1
|
| 41 |
+
|
| 42 |
+
leaking_speakers = {
|
| 43 |
+
speaker: sorted(splits) for speaker, splits in speaker_splits.items() if len(splits) > 1
|
| 44 |
+
}
|
| 45 |
+
if leaking_speakers:
|
| 46 |
+
examples = list(sorted(leaking_speakers.items()))[:5]
|
| 47 |
+
errors.append(
|
| 48 |
+
f"{len(leaking_speakers)} speaker IDs cross split boundaries; examples: {examples}"
|
| 49 |
+
)
|
| 50 |
+
session_only = parse_quality_counts.get("session_only", 0)
|
| 51 |
+
if session_only:
|
| 52 |
+
warnings.append(
|
| 53 |
+
f"{session_only} records have session-only speaker grouping; final speaker-disjoint "
|
| 54 |
+
"metrics require manual anonymous overrides or upstream speaker metadata"
|
| 55 |
+
)
|
| 56 |
+
if missing_duration:
|
| 57 |
+
warnings.append(f"{missing_duration} records do not have a probed duration")
|
| 58 |
+
|
| 59 |
+
return {
|
| 60 |
+
"ok": not errors,
|
| 61 |
+
"manifest": str(manifest_path),
|
| 62 |
+
"records": len(records),
|
| 63 |
+
"speakers": len({record.speaker_id for record in records}),
|
| 64 |
+
"errors": errors,
|
| 65 |
+
"warnings": warnings,
|
| 66 |
+
"splits": dict(sorted(split_counts.items())),
|
| 67 |
+
"languages": dict(sorted(language_counts.items())),
|
| 68 |
+
"sources": dict(sorted(source_counts.items())),
|
| 69 |
+
"speaker_parse_quality": dict(sorted(parse_quality_counts.items())),
|
| 70 |
+
}
|
src/buddi_asr/errors.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Project-specific exceptions with actionable user-facing messages."""
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class BuddiASRError(Exception):
|
| 5 |
+
"""Base class for expected command and validation failures."""
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class ConfigurationError(BuddiASRError):
|
| 9 |
+
"""Raised when a JSON configuration is incomplete or inconsistent."""
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class ManifestError(BuddiASRError):
|
| 13 |
+
"""Raised when a manifest record violates the Buddi data contract."""
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class OptionalDependencyError(BuddiASRError):
|
| 17 |
+
"""Raised with installation guidance for an unavailable optional feature."""
|
src/buddi_asr/evaluate.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Speaker-safe test-set evaluation with WER/CER breakdowns."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import json
|
| 6 |
+
from collections import defaultdict
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from typing import Any
|
| 9 |
+
|
| 10 |
+
from buddi_asr.data.manifest import read_manifest, resolve_audio_path
|
| 11 |
+
from buddi_asr.errors import OptionalDependencyError
|
| 12 |
+
from buddi_asr.metrics import score_pairs
|
| 13 |
+
from buddi_asr.text.normalization import normalize_for_metrics
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def _device_and_dtype(torch: Any, requested: str) -> tuple[str, Any]:
|
| 17 |
+
if requested == "auto":
|
| 18 |
+
if torch.cuda.is_available():
|
| 19 |
+
return "cuda", torch.float16
|
| 20 |
+
if getattr(torch.backends, "mps", None) and torch.backends.mps.is_available():
|
| 21 |
+
return "mps", torch.float32
|
| 22 |
+
return "cpu", torch.float32
|
| 23 |
+
if requested == "cuda":
|
| 24 |
+
return requested, torch.float16
|
| 25 |
+
return requested, torch.float32
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def evaluate_hf_model(
|
| 29 |
+
model_path: str | Path,
|
| 30 |
+
manifest_path: str | Path,
|
| 31 |
+
output_dir: str | Path,
|
| 32 |
+
*,
|
| 33 |
+
device: str = "auto",
|
| 34 |
+
max_new_tokens: int = 128,
|
| 35 |
+
) -> dict[str, Any]:
|
| 36 |
+
try:
|
| 37 |
+
import librosa
|
| 38 |
+
import torch
|
| 39 |
+
from transformers import WhisperForConditionalGeneration, WhisperProcessor
|
| 40 |
+
except ImportError as exc:
|
| 41 |
+
raise OptionalDependencyError(
|
| 42 |
+
"Evaluation dependencies are missing. Install: python -m pip install -e '.[train]'"
|
| 43 |
+
) from exc
|
| 44 |
+
|
| 45 |
+
model_location = str(model_path)
|
| 46 |
+
manifest_location = Path(manifest_path).resolve()
|
| 47 |
+
destination = Path(output_dir).resolve()
|
| 48 |
+
destination.mkdir(parents=True, exist_ok=True)
|
| 49 |
+
selected_device, dtype = _device_and_dtype(torch, device)
|
| 50 |
+
processor = WhisperProcessor.from_pretrained(model_location)
|
| 51 |
+
if (Path(model_location) / "adapter_config.json").is_file():
|
| 52 |
+
try:
|
| 53 |
+
from peft import PeftConfig, PeftModel
|
| 54 |
+
except ImportError as exc:
|
| 55 |
+
raise OptionalDependencyError(
|
| 56 |
+
"Evaluating an adapter requires PEFT from the training dependencies"
|
| 57 |
+
) from exc
|
| 58 |
+
peft_config = PeftConfig.from_pretrained(model_location)
|
| 59 |
+
base = WhisperForConditionalGeneration.from_pretrained(
|
| 60 |
+
peft_config.base_model_name_or_path, torch_dtype=dtype
|
| 61 |
+
)
|
| 62 |
+
model = PeftModel.from_pretrained(base, model_location)
|
| 63 |
+
else:
|
| 64 |
+
model = WhisperForConditionalGeneration.from_pretrained(model_location, torch_dtype=dtype)
|
| 65 |
+
model.to(selected_device)
|
| 66 |
+
model.eval()
|
| 67 |
+
|
| 68 |
+
rows: list[dict[str, Any]] = []
|
| 69 |
+
for record in read_manifest(manifest_location):
|
| 70 |
+
audio, _ = librosa.load(
|
| 71 |
+
resolve_audio_path(record, manifest_location), sr=16000, mono=True
|
| 72 |
+
)
|
| 73 |
+
inputs = processor.feature_extractor(audio, sampling_rate=16000, return_tensors="pt")
|
| 74 |
+
input_features = inputs.input_features.to(selected_device, dtype=dtype)
|
| 75 |
+
generate_kwargs: dict[str, Any] = {
|
| 76 |
+
"task": "transcribe",
|
| 77 |
+
"max_new_tokens": max_new_tokens,
|
| 78 |
+
}
|
| 79 |
+
if record.language in {"ar", "en"}:
|
| 80 |
+
generate_kwargs["language"] = record.language
|
| 81 |
+
with torch.inference_mode():
|
| 82 |
+
generated = model.generate(input_features, **generate_kwargs)
|
| 83 |
+
hypothesis = processor.tokenizer.batch_decode(generated, skip_special_tokens=True)[0]
|
| 84 |
+
rows.append(
|
| 85 |
+
{
|
| 86 |
+
"source_file_id": record.metadata.get("source_file_id"),
|
| 87 |
+
"speaker_id": record.speaker_id,
|
| 88 |
+
"language": record.language,
|
| 89 |
+
"dialect": record.dialect,
|
| 90 |
+
"age_group": record.age_group,
|
| 91 |
+
"source": record.source,
|
| 92 |
+
"category": record.category,
|
| 93 |
+
"reference": record.text,
|
| 94 |
+
"hypothesis": hypothesis,
|
| 95 |
+
"normalized_reference": normalize_for_metrics(record.text),
|
| 96 |
+
"normalized_hypothesis": normalize_for_metrics(hypothesis),
|
| 97 |
+
}
|
| 98 |
+
)
|
| 99 |
+
|
| 100 |
+
predictions_path = destination / "predictions.jsonl"
|
| 101 |
+
with predictions_path.open("w", encoding="utf-8", newline="\n") as handle:
|
| 102 |
+
for row in rows:
|
| 103 |
+
handle.write(json.dumps(row, ensure_ascii=False, sort_keys=True) + "\n")
|
| 104 |
+
|
| 105 |
+
def score(group: list[dict[str, Any]]) -> dict[str, float | int]:
|
| 106 |
+
return score_pairs(
|
| 107 |
+
[row["reference"] for row in group], [row["hypothesis"] for row in group]
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
breakdown_fields = ("language", "dialect", "age_group", "source", "category")
|
| 111 |
+
breakdowns: dict[str, dict[str, Any]] = {}
|
| 112 |
+
for field in breakdown_fields:
|
| 113 |
+
groups: dict[str, list[dict[str, Any]]] = defaultdict(list)
|
| 114 |
+
for row in rows:
|
| 115 |
+
groups[str(row[field])].append(row)
|
| 116 |
+
breakdowns[field] = {name: score(group) for name, group in sorted(groups.items())}
|
| 117 |
+
summary = {
|
| 118 |
+
"model": model_location,
|
| 119 |
+
"manifest": str(manifest_location),
|
| 120 |
+
"device": selected_device,
|
| 121 |
+
"overall": score(rows),
|
| 122 |
+
"breakdowns": breakdowns,
|
| 123 |
+
"predictions": str(predictions_path),
|
| 124 |
+
"warning": "Review predictions before sharing; transcript text may be sensitive.",
|
| 125 |
+
}
|
| 126 |
+
(destination / "metrics.json").write_text(
|
| 127 |
+
json.dumps(summary, ensure_ascii=False, indent=2, sort_keys=True) + "\n",
|
| 128 |
+
encoding="utf-8",
|
| 129 |
+
)
|
| 130 |
+
return summary
|
src/buddi_asr/export.py
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Merge PEFT adapters and create a checksummed whisper.cpp artifact."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import hashlib
|
| 6 |
+
import json
|
| 7 |
+
import re
|
| 8 |
+
import shutil
|
| 9 |
+
import subprocess
|
| 10 |
+
import sys
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
from typing import Any
|
| 13 |
+
|
| 14 |
+
from buddi_asr.errors import ManifestError, OptionalDependencyError
|
| 15 |
+
|
| 16 |
+
SUPPORTED_QUANTIZATIONS = {"none", "q4_0", "q5_0", "q5_1", "q8_0"}
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def _sha256(path: Path) -> str:
|
| 20 |
+
digest = hashlib.sha256()
|
| 21 |
+
with path.open("rb") as handle:
|
| 22 |
+
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
|
| 23 |
+
digest.update(chunk)
|
| 24 |
+
return digest.hexdigest()
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def merge_lora_adapter(
|
| 28 |
+
base_model: str,
|
| 29 |
+
adapter_dir: str | Path,
|
| 30 |
+
output_dir: str | Path,
|
| 31 |
+
) -> dict[str, Any]:
|
| 32 |
+
try:
|
| 33 |
+
import torch
|
| 34 |
+
from peft import PeftModel
|
| 35 |
+
from transformers import WhisperForConditionalGeneration, WhisperProcessor
|
| 36 |
+
except ImportError as exc:
|
| 37 |
+
raise OptionalDependencyError(
|
| 38 |
+
"Merging LoRA requires: python -m pip install -e '.[train]'"
|
| 39 |
+
) from exc
|
| 40 |
+
|
| 41 |
+
adapter_path = Path(adapter_dir).resolve()
|
| 42 |
+
destination = Path(output_dir).resolve()
|
| 43 |
+
if not (adapter_path / "adapter_config.json").is_file():
|
| 44 |
+
raise ManifestError(f"LoRA adapter_config.json not found in {adapter_path}")
|
| 45 |
+
if destination.exists() and any(destination.iterdir()):
|
| 46 |
+
raise ManifestError(f"Merge output directory must be empty: {destination}")
|
| 47 |
+
destination.mkdir(parents=True, exist_ok=True)
|
| 48 |
+
|
| 49 |
+
model = WhisperForConditionalGeneration.from_pretrained(
|
| 50 |
+
base_model, torch_dtype=torch.float32, low_cpu_mem_usage=True
|
| 51 |
+
)
|
| 52 |
+
peft_model = PeftModel.from_pretrained(model, adapter_path)
|
| 53 |
+
merged = peft_model.merge_and_unload(safe_merge=True)
|
| 54 |
+
merged.config.use_cache = True
|
| 55 |
+
merged.save_pretrained(destination, safe_serialization=True)
|
| 56 |
+
try:
|
| 57 |
+
processor = WhisperProcessor.from_pretrained(adapter_path)
|
| 58 |
+
except OSError:
|
| 59 |
+
processor = WhisperProcessor.from_pretrained(base_model)
|
| 60 |
+
processor.save_pretrained(destination)
|
| 61 |
+
return {
|
| 62 |
+
"base_model": base_model,
|
| 63 |
+
"adapter": str(adapter_path),
|
| 64 |
+
"merged_model": str(destination),
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def _find_quantizer(whisper_cpp: Path) -> Path | None:
|
| 69 |
+
candidates = (
|
| 70 |
+
whisper_cpp / "build/bin/quantize",
|
| 71 |
+
whisper_cpp / "build/bin/whisper-quantize",
|
| 72 |
+
whisper_cpp / "build/bin/Release/quantize",
|
| 73 |
+
whisper_cpp / "build/bin/Release/whisper-quantize",
|
| 74 |
+
)
|
| 75 |
+
return next((path for path in candidates if path.is_file()), None)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def export_whisper_cpp(
|
| 79 |
+
model_dir: str | Path,
|
| 80 |
+
whisper_cpp_dir: str | Path,
|
| 81 |
+
openai_whisper_dir: str | Path,
|
| 82 |
+
output_dir: str | Path,
|
| 83 |
+
*,
|
| 84 |
+
name: str = "buddi-asr-tiny-argulf-v1",
|
| 85 |
+
quantization: str = "q5_0",
|
| 86 |
+
build_if_needed: bool = False,
|
| 87 |
+
) -> dict[str, Any]:
|
| 88 |
+
model_path = Path(model_dir).resolve()
|
| 89 |
+
whisper_cpp = Path(whisper_cpp_dir).resolve()
|
| 90 |
+
openai_whisper = Path(openai_whisper_dir).resolve()
|
| 91 |
+
destination = Path(output_dir).resolve()
|
| 92 |
+
if quantization not in SUPPORTED_QUANTIZATIONS:
|
| 93 |
+
raise ManifestError(
|
| 94 |
+
"Unsupported quantization; choose: " + ", ".join(sorted(SUPPORTED_QUANTIZATIONS))
|
| 95 |
+
)
|
| 96 |
+
safe_name = re.sub(r"[^a-zA-Z0-9._-]+", "-", name).strip("-.")
|
| 97 |
+
if not safe_name:
|
| 98 |
+
raise ManifestError("Artifact name contains no safe filename characters")
|
| 99 |
+
if (model_path / "adapter_config.json").exists():
|
| 100 |
+
raise ManifestError("Export needs a merged/full model; run merge-lora first")
|
| 101 |
+
required_model_files = ("config.json", "vocab.json", "added_tokens.json")
|
| 102 |
+
missing_model = [name_ for name_ in required_model_files if not (model_path / name_).is_file()]
|
| 103 |
+
if missing_model:
|
| 104 |
+
raise ManifestError(
|
| 105 |
+
f"Model directory is not a complete Whisper export; missing: {', '.join(missing_model)}"
|
| 106 |
+
)
|
| 107 |
+
converter = whisper_cpp / "models/convert-h5-to-ggml.py"
|
| 108 |
+
if not converter.is_file():
|
| 109 |
+
raise ManifestError(f"whisper.cpp converter not found: {converter}")
|
| 110 |
+
if not (openai_whisper / "whisper/assets/mel_filters.npz").is_file():
|
| 111 |
+
raise ManifestError(
|
| 112 |
+
"OpenAI Whisper checkout must contain whisper/assets/mel_filters.npz: "
|
| 113 |
+
f"{openai_whisper}"
|
| 114 |
+
)
|
| 115 |
+
destination.mkdir(parents=True, exist_ok=True)
|
| 116 |
+
final_suffix = "f16" if quantization == "none" else quantization
|
| 117 |
+
final_model = destination / f"{safe_name}-{final_suffix}.bin"
|
| 118 |
+
if final_model.exists():
|
| 119 |
+
raise ManifestError(f"Refusing to overwrite existing artifact: {final_model}")
|
| 120 |
+
|
| 121 |
+
conversion_dir = destination / f".{safe_name}-conversion"
|
| 122 |
+
if conversion_dir.exists():
|
| 123 |
+
raise ManifestError(f"Stale conversion directory exists; inspect and remove it: {conversion_dir}")
|
| 124 |
+
conversion_dir.mkdir()
|
| 125 |
+
try:
|
| 126 |
+
subprocess.run(
|
| 127 |
+
[
|
| 128 |
+
sys.executable,
|
| 129 |
+
str(converter),
|
| 130 |
+
str(model_path),
|
| 131 |
+
str(openai_whisper),
|
| 132 |
+
str(conversion_dir),
|
| 133 |
+
],
|
| 134 |
+
check=True,
|
| 135 |
+
)
|
| 136 |
+
f16_model = conversion_dir / "ggml-model.bin"
|
| 137 |
+
if not f16_model.is_file():
|
| 138 |
+
raise ManifestError(f"Converter did not create expected file: {f16_model}")
|
| 139 |
+
if quantization == "none":
|
| 140 |
+
shutil.move(f16_model, final_model)
|
| 141 |
+
else:
|
| 142 |
+
quantizer = _find_quantizer(whisper_cpp)
|
| 143 |
+
if quantizer is None and build_if_needed:
|
| 144 |
+
subprocess.run(["cmake", "-B", "build"], cwd=whisper_cpp, check=True)
|
| 145 |
+
subprocess.run(
|
| 146 |
+
["cmake", "--build", "build", "-j", "--config", "Release"],
|
| 147 |
+
cwd=whisper_cpp,
|
| 148 |
+
check=True,
|
| 149 |
+
)
|
| 150 |
+
quantizer = _find_quantizer(whisper_cpp)
|
| 151 |
+
if quantizer is None:
|
| 152 |
+
raise ManifestError(
|
| 153 |
+
"whisper.cpp quantizer is not built. Run cmake -B build && "
|
| 154 |
+
"cmake --build build -j --config Release, or pass --build-if-needed"
|
| 155 |
+
)
|
| 156 |
+
subprocess.run(
|
| 157 |
+
[str(quantizer), str(f16_model), str(final_model), quantization], check=True
|
| 158 |
+
)
|
| 159 |
+
finally:
|
| 160 |
+
if conversion_dir.exists():
|
| 161 |
+
shutil.rmtree(conversion_dir)
|
| 162 |
+
|
| 163 |
+
artifact = {
|
| 164 |
+
"name": safe_name,
|
| 165 |
+
"format": "whisper.cpp-ggml",
|
| 166 |
+
"quantization": quantization,
|
| 167 |
+
"file": str(final_model),
|
| 168 |
+
"size_bytes": final_model.stat().st_size,
|
| 169 |
+
"sha256": _sha256(final_model),
|
| 170 |
+
"source_model_name": model_path.name,
|
| 171 |
+
}
|
| 172 |
+
metadata_path = destination / f"{safe_name}-{final_suffix}.json"
|
| 173 |
+
metadata_path.write_text(
|
| 174 |
+
json.dumps(artifact, ensure_ascii=False, indent=2, sort_keys=True) + "\n",
|
| 175 |
+
encoding="utf-8",
|
| 176 |
+
)
|
| 177 |
+
artifact["metadata"] = str(metadata_path)
|
| 178 |
+
return artifact
|
src/buddi_asr/metrics.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Dependency-free corpus WER and CER used by training and audits."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from collections.abc import Sequence
|
| 6 |
+
from dataclasses import asdict, dataclass
|
| 7 |
+
from typing import TypeVar
|
| 8 |
+
|
| 9 |
+
from buddi_asr.text.normalization import normalize_for_metrics
|
| 10 |
+
|
| 11 |
+
T = TypeVar("T")
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
@dataclass(frozen=True, slots=True)
|
| 15 |
+
class ErrorRate:
|
| 16 |
+
errors: int
|
| 17 |
+
reference_units: int
|
| 18 |
+
|
| 19 |
+
@property
|
| 20 |
+
def rate(self) -> float:
|
| 21 |
+
if self.reference_units == 0:
|
| 22 |
+
return 0.0 if self.errors == 0 else 1.0
|
| 23 |
+
return self.errors / self.reference_units
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def levenshtein_distance(reference: Sequence[T], hypothesis: Sequence[T]) -> int:
|
| 27 |
+
"""Memory-efficient Levenshtein edit distance."""
|
| 28 |
+
|
| 29 |
+
if len(reference) < len(hypothesis):
|
| 30 |
+
reference, hypothesis = hypothesis, reference
|
| 31 |
+
previous = list(range(len(hypothesis) + 1))
|
| 32 |
+
for row, ref_item in enumerate(reference, start=1):
|
| 33 |
+
current = [row]
|
| 34 |
+
for column, hyp_item in enumerate(hypothesis, start=1):
|
| 35 |
+
insert = current[column - 1] + 1
|
| 36 |
+
delete = previous[column] + 1
|
| 37 |
+
substitute = previous[column - 1] + (ref_item != hyp_item)
|
| 38 |
+
current.append(min(insert, delete, substitute))
|
| 39 |
+
previous = current
|
| 40 |
+
return previous[-1]
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def corpus_error_rate(
|
| 44 |
+
references: Sequence[str],
|
| 45 |
+
hypotheses: Sequence[str],
|
| 46 |
+
*,
|
| 47 |
+
unit: str,
|
| 48 |
+
) -> ErrorRate:
|
| 49 |
+
if len(references) != len(hypotheses):
|
| 50 |
+
raise ValueError("references and hypotheses must have equal length")
|
| 51 |
+
if unit not in {"word", "char"}:
|
| 52 |
+
raise ValueError("unit must be 'word' or 'char'")
|
| 53 |
+
|
| 54 |
+
total_errors = 0
|
| 55 |
+
total_reference_units = 0
|
| 56 |
+
for reference, hypothesis in zip(references, hypotheses, strict=True):
|
| 57 |
+
normalized_reference = normalize_for_metrics(reference)
|
| 58 |
+
normalized_hypothesis = normalize_for_metrics(hypothesis)
|
| 59 |
+
if unit == "word":
|
| 60 |
+
ref_units = normalized_reference.split()
|
| 61 |
+
hyp_units = normalized_hypothesis.split()
|
| 62 |
+
else:
|
| 63 |
+
ref_units = list(normalized_reference.replace(" ", ""))
|
| 64 |
+
hyp_units = list(normalized_hypothesis.replace(" ", ""))
|
| 65 |
+
total_errors += levenshtein_distance(ref_units, hyp_units)
|
| 66 |
+
total_reference_units += len(ref_units)
|
| 67 |
+
return ErrorRate(total_errors, total_reference_units)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def score_pairs(references: Sequence[str], hypotheses: Sequence[str]) -> dict[str, float | int]:
|
| 71 |
+
word = corpus_error_rate(references, hypotheses, unit="word")
|
| 72 |
+
char = corpus_error_rate(references, hypotheses, unit="char")
|
| 73 |
+
return {
|
| 74 |
+
"wer": word.rate,
|
| 75 |
+
"cer": char.rate,
|
| 76 |
+
"word_errors": word.errors,
|
| 77 |
+
"reference_words": word.reference_units,
|
| 78 |
+
"char_errors": char.errors,
|
| 79 |
+
"reference_chars": char.reference_units,
|
| 80 |
+
"utterances": len(references),
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def error_rate_dict(value: ErrorRate) -> dict[str, int | float]:
|
| 85 |
+
result = asdict(value)
|
| 86 |
+
result["rate"] = value.rate
|
| 87 |
+
return result
|
src/buddi_asr/text/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""Arabic and multilingual transcript normalization."""
|
src/buddi_asr/text/normalization.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Conservative Arabic/English normalization for ASR metrics.
|
| 2 |
+
|
| 3 |
+
Training text remains human-readable Arabic. Normalization is applied only for
|
| 4 |
+
comparison, so the model is not taught to emit stripped-down orthography.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import re
|
| 10 |
+
import unicodedata
|
| 11 |
+
|
| 12 |
+
ARABIC_DIACRITICS_RE = re.compile(
|
| 13 |
+
"[\u0610-\u061a\u064b-\u065f\u0670\u06d6-\u06ed]"
|
| 14 |
+
)
|
| 15 |
+
WHITESPACE_RE = re.compile(r"\s+")
|
| 16 |
+
|
| 17 |
+
CHAR_TRANSLATION = str.maketrans(
|
| 18 |
+
{
|
| 19 |
+
"أ": "ا",
|
| 20 |
+
"إ": "ا",
|
| 21 |
+
"آ": "ا",
|
| 22 |
+
"ٱ": "ا",
|
| 23 |
+
"ى": "ي",
|
| 24 |
+
"ـ": "",
|
| 25 |
+
"٠": "0",
|
| 26 |
+
"١": "1",
|
| 27 |
+
"٢": "2",
|
| 28 |
+
"٣": "3",
|
| 29 |
+
"٤": "4",
|
| 30 |
+
"٥": "5",
|
| 31 |
+
"٦": "6",
|
| 32 |
+
"٧": "7",
|
| 33 |
+
"٨": "8",
|
| 34 |
+
"٩": "9",
|
| 35 |
+
"۰": "0",
|
| 36 |
+
"۱": "1",
|
| 37 |
+
"۲": "2",
|
| 38 |
+
"۳": "3",
|
| 39 |
+
"۴": "4",
|
| 40 |
+
"۵": "5",
|
| 41 |
+
"۶": "6",
|
| 42 |
+
"۷": "7",
|
| 43 |
+
"۸": "8",
|
| 44 |
+
"۹": "9",
|
| 45 |
+
}
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def contains_arabic(text: str) -> bool:
|
| 50 |
+
return any("ARABIC" in unicodedata.name(char, "") for char in text)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def _replace_punctuation_and_symbols(text: str) -> str:
|
| 54 |
+
chars: list[str] = []
|
| 55 |
+
for char in text:
|
| 56 |
+
category = unicodedata.category(char)
|
| 57 |
+
if category.startswith(("P", "S")):
|
| 58 |
+
chars.append(" ")
|
| 59 |
+
else:
|
| 60 |
+
chars.append(char)
|
| 61 |
+
return "".join(chars)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def normalize_for_metrics(text: str, language: str | None = None) -> str:
|
| 65 |
+
"""Normalize orthographic variants without collapsing distinct Arabic letters."""
|
| 66 |
+
|
| 67 |
+
del language # Reserved for future dialect-specific policies.
|
| 68 |
+
normalized = unicodedata.normalize("NFKC", text).casefold()
|
| 69 |
+
normalized = ARABIC_DIACRITICS_RE.sub("", normalized)
|
| 70 |
+
normalized = normalized.translate(CHAR_TRANSLATION)
|
| 71 |
+
normalized = _replace_punctuation_and_symbols(normalized)
|
| 72 |
+
return WHITESPACE_RE.sub(" ", normalized).strip()
|
src/buddi_asr/training/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""Whisper fine-tuning components loaded only by training commands."""
|
src/buddi_asr/training/audio.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Light waveform augmentation suited to short child utterances."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from typing import Any
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def augment_waveform(audio: Any, sample_rate: int, settings: Any) -> Any:
|
| 9 |
+
"""Apply gain, optional speed perturbation, and controlled Gaussian noise."""
|
| 10 |
+
|
| 11 |
+
import librosa
|
| 12 |
+
import numpy as np
|
| 13 |
+
|
| 14 |
+
if np.random.random() > settings.probability:
|
| 15 |
+
return audio
|
| 16 |
+
gain_db = np.random.uniform(settings.gain_db_min, settings.gain_db_max)
|
| 17 |
+
audio = audio * (10.0 ** (gain_db / 20.0))
|
| 18 |
+
speed = float(np.random.choice(settings.speed_factors))
|
| 19 |
+
if speed != 1.0 and len(audio) > sample_rate // 4:
|
| 20 |
+
audio = librosa.effects.time_stretch(audio, rate=speed)
|
| 21 |
+
signal_power = float(np.mean(np.square(audio))) if len(audio) else 0.0
|
| 22 |
+
if signal_power > 0:
|
| 23 |
+
snr_db = np.random.uniform(settings.noise_snr_db_min, settings.noise_snr_db_max)
|
| 24 |
+
noise_power = signal_power / (10.0 ** (snr_db / 10.0))
|
| 25 |
+
noise = np.random.normal(0.0, np.sqrt(noise_power), size=audio.shape)
|
| 26 |
+
audio = audio + noise
|
| 27 |
+
return np.clip(audio, -1.0, 1.0).astype(np.float32)
|
src/buddi_asr/training/collator.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Whisper feature/label padding with correct loss masking."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from dataclasses import dataclass
|
| 6 |
+
from typing import Any
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
@dataclass
|
| 10 |
+
class WhisperDataCollator:
|
| 11 |
+
processor: Any
|
| 12 |
+
decoder_start_token_id: int
|
| 13 |
+
|
| 14 |
+
def __call__(self, features: list[dict[str, Any]]) -> dict[str, Any]:
|
| 15 |
+
import torch
|
| 16 |
+
|
| 17 |
+
input_features = [
|
| 18 |
+
{"input_features": feature["input_features"]} for feature in features
|
| 19 |
+
]
|
| 20 |
+
batch = self.processor.feature_extractor.pad(input_features, return_tensors="pt")
|
| 21 |
+
label_features = [{"input_ids": feature["labels"]} for feature in features]
|
| 22 |
+
labels_batch = self.processor.tokenizer.pad(label_features, return_tensors="pt")
|
| 23 |
+
labels = labels_batch["input_ids"].masked_fill(
|
| 24 |
+
labels_batch["attention_mask"].ne(1), -100
|
| 25 |
+
)
|
| 26 |
+
if labels.shape[1] and torch.all(labels[:, 0] == self.decoder_start_token_id):
|
| 27 |
+
labels = labels[:, 1:]
|
| 28 |
+
batch["labels"] = labels
|
| 29 |
+
return batch
|
src/buddi_asr/training/config.py
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Validated training configuration."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from dataclasses import asdict, dataclass, field
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from typing import Any
|
| 8 |
+
|
| 9 |
+
from buddi_asr.config import load_json
|
| 10 |
+
from buddi_asr.errors import ConfigurationError
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
@dataclass(slots=True)
|
| 14 |
+
class LoraSettings:
|
| 15 |
+
rank: int = 16
|
| 16 |
+
alpha: int = 32
|
| 17 |
+
dropout: float = 0.05
|
| 18 |
+
target_modules: list[str] = field(default_factory=lambda: ["q_proj", "v_proj"])
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
@dataclass(slots=True)
|
| 22 |
+
class AugmentationSettings:
|
| 23 |
+
probability: float = 0.6
|
| 24 |
+
gain_db_min: float = -6.0
|
| 25 |
+
gain_db_max: float = 6.0
|
| 26 |
+
noise_snr_db_min: float = 12.0
|
| 27 |
+
noise_snr_db_max: float = 30.0
|
| 28 |
+
speed_factors: list[float] = field(default_factory=lambda: [0.9, 1.0, 1.1])
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@dataclass(slots=True)
|
| 32 |
+
class TrainConfig:
|
| 33 |
+
model_name_or_path: str
|
| 34 |
+
train_manifest: str
|
| 35 |
+
eval_manifest: str
|
| 36 |
+
output_dir: str
|
| 37 |
+
method: str = "lora"
|
| 38 |
+
task: str = "transcribe"
|
| 39 |
+
language_prompts: dict[str, str] = field(
|
| 40 |
+
default_factory=lambda: {"ar": "arabic", "en": "english", "ar-en": "arabic"}
|
| 41 |
+
)
|
| 42 |
+
seed: int = 42
|
| 43 |
+
sampling_rate: int = 16000
|
| 44 |
+
max_audio_seconds: float = 30.0
|
| 45 |
+
per_device_train_batch_size: int = 16
|
| 46 |
+
per_device_eval_batch_size: int = 8
|
| 47 |
+
gradient_accumulation_steps: int = 2
|
| 48 |
+
learning_rate: float = 1e-4
|
| 49 |
+
num_train_epochs: float = 10.0
|
| 50 |
+
max_steps: int = -1
|
| 51 |
+
warmup_ratio: float = 0.05
|
| 52 |
+
weight_decay: float = 0.01
|
| 53 |
+
logging_steps: int = 25
|
| 54 |
+
eval_steps: int = 250
|
| 55 |
+
save_steps: int = 250
|
| 56 |
+
save_total_limit: int = 2
|
| 57 |
+
generation_max_length: int = 128
|
| 58 |
+
fp16: bool = True
|
| 59 |
+
bf16: bool = False
|
| 60 |
+
gradient_checkpointing: bool = True
|
| 61 |
+
freeze_feature_encoder: bool = True
|
| 62 |
+
dataloader_num_workers: int = 0
|
| 63 |
+
dataloader_pin_memory: bool = True
|
| 64 |
+
eval_accumulation_steps: int | None = 1
|
| 65 |
+
tf32: bool = True
|
| 66 |
+
ddp_find_unused_parameters: bool = False
|
| 67 |
+
early_stopping_patience: int = 4
|
| 68 |
+
report_to: list[str] = field(default_factory=lambda: ["tensorboard"])
|
| 69 |
+
resume_from_checkpoint: str | None = None
|
| 70 |
+
lora: LoraSettings = field(default_factory=LoraSettings)
|
| 71 |
+
augmentation: AugmentationSettings = field(default_factory=AugmentationSettings)
|
| 72 |
+
|
| 73 |
+
def validate(self) -> None:
|
| 74 |
+
if self.method not in {"lora", "full"}:
|
| 75 |
+
raise ConfigurationError("training method must be 'lora' or 'full'")
|
| 76 |
+
if self.task != "transcribe":
|
| 77 |
+
raise ConfigurationError("Buddi-ASR supports the Whisper transcribe task only")
|
| 78 |
+
for field_name in ("train_manifest", "eval_manifest"):
|
| 79 |
+
if not Path(getattr(self, field_name)).is_file():
|
| 80 |
+
raise ConfigurationError(f"{field_name} not found: {getattr(self, field_name)}")
|
| 81 |
+
if self.sampling_rate != 16000:
|
| 82 |
+
raise ConfigurationError("Whisper training must use a 16000 Hz sampling rate")
|
| 83 |
+
if self.max_audio_seconds <= 0 or self.max_audio_seconds > 30:
|
| 84 |
+
raise ConfigurationError("max_audio_seconds must be in (0, 30]")
|
| 85 |
+
if self.fp16 and self.bf16:
|
| 86 |
+
raise ConfigurationError("fp16 and bf16 cannot both be true")
|
| 87 |
+
if self.logging_steps <= 0 or self.eval_steps <= 0 or self.save_steps <= 0:
|
| 88 |
+
raise ConfigurationError("logging_steps, eval_steps, and save_steps must be positive")
|
| 89 |
+
if self.save_steps % self.eval_steps != 0:
|
| 90 |
+
raise ConfigurationError(
|
| 91 |
+
"save_steps must be a multiple of eval_steps when loading the best model"
|
| 92 |
+
)
|
| 93 |
+
if self.lora.rank <= 0 or self.lora.alpha <= 0:
|
| 94 |
+
raise ConfigurationError("LoRA rank and alpha must be positive")
|
| 95 |
+
if self.max_steps == 0 or self.max_steps < -1:
|
| 96 |
+
raise ConfigurationError("max_steps must be -1 or a positive integer")
|
| 97 |
+
if self.per_device_train_batch_size <= 0 or self.per_device_eval_batch_size <= 0:
|
| 98 |
+
raise ConfigurationError("per-device batch sizes must be positive")
|
| 99 |
+
if self.gradient_accumulation_steps <= 0:
|
| 100 |
+
raise ConfigurationError("gradient_accumulation_steps must be positive")
|
| 101 |
+
if self.dataloader_num_workers < 0:
|
| 102 |
+
raise ConfigurationError("dataloader_num_workers cannot be negative")
|
| 103 |
+
if self.eval_accumulation_steps is not None and self.eval_accumulation_steps <= 0:
|
| 104 |
+
raise ConfigurationError("eval_accumulation_steps must be null or positive")
|
| 105 |
+
if not 0 <= self.lora.dropout < 1:
|
| 106 |
+
raise ConfigurationError("LoRA dropout must be in [0, 1)")
|
| 107 |
+
if not 0 <= self.augmentation.probability <= 1:
|
| 108 |
+
raise ConfigurationError("augmentation probability must be in [0, 1]")
|
| 109 |
+
|
| 110 |
+
def to_dict(self) -> dict[str, Any]:
|
| 111 |
+
return asdict(self)
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def load_train_config(
|
| 115 |
+
path: str | Path,
|
| 116 |
+
*,
|
| 117 |
+
overrides: dict[str, Any] | None = None,
|
| 118 |
+
) -> TrainConfig:
|
| 119 |
+
payload = load_json(path)
|
| 120 |
+
config_dir = Path(path).resolve().parent
|
| 121 |
+
for key in ("train_manifest", "eval_manifest", "output_dir"):
|
| 122 |
+
value = payload.get(key)
|
| 123 |
+
if isinstance(value, str) and not Path(value).is_absolute():
|
| 124 |
+
payload[key] = str((config_dir / value).resolve())
|
| 125 |
+
resume = payload.get("resume_from_checkpoint")
|
| 126 |
+
if (
|
| 127 |
+
isinstance(resume, str)
|
| 128 |
+
and resume.casefold() not in {"auto", "none"}
|
| 129 |
+
and not Path(resume).is_absolute()
|
| 130 |
+
):
|
| 131 |
+
payload["resume_from_checkpoint"] = str((config_dir / resume).resolve())
|
| 132 |
+
try:
|
| 133 |
+
lora = LoraSettings(**payload.pop("lora", {}))
|
| 134 |
+
augmentation = AugmentationSettings(**payload.pop("augmentation", {}))
|
| 135 |
+
config = TrainConfig(**payload, lora=lora, augmentation=augmentation)
|
| 136 |
+
except TypeError as exc:
|
| 137 |
+
raise ConfigurationError(f"Invalid training configuration: {exc}") from exc
|
| 138 |
+
for key, value in (overrides or {}).items():
|
| 139 |
+
if key in {"lora", "augmentation"} or not hasattr(config, key):
|
| 140 |
+
raise ConfigurationError(f"Unknown or unsupported training override: {key}")
|
| 141 |
+
setattr(config, key, value)
|
| 142 |
+
config.validate()
|
| 143 |
+
return config
|
src/buddi_asr/training/dataset.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Lazy audio dataset that keeps manifests small and debuggable."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from typing import Any
|
| 7 |
+
|
| 8 |
+
from buddi_asr.data.manifest import ManifestRecord, read_manifest, resolve_audio_path
|
| 9 |
+
from buddi_asr.errors import ManifestError
|
| 10 |
+
from buddi_asr.training.audio import augment_waveform
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class ManifestSpeechDataset:
|
| 14 |
+
def __init__(
|
| 15 |
+
self,
|
| 16 |
+
manifest_path: str | Path,
|
| 17 |
+
processor: Any,
|
| 18 |
+
*,
|
| 19 |
+
language_prompts: dict[str, str],
|
| 20 |
+
task: str,
|
| 21 |
+
sampling_rate: int,
|
| 22 |
+
max_audio_seconds: float,
|
| 23 |
+
augmentation: Any | None = None,
|
| 24 |
+
) -> None:
|
| 25 |
+
self.manifest_path = Path(manifest_path).resolve()
|
| 26 |
+
self.records: list[ManifestRecord] = list(read_manifest(self.manifest_path))
|
| 27 |
+
if not self.records:
|
| 28 |
+
raise ManifestError(f"Training manifest is empty: {self.manifest_path}")
|
| 29 |
+
self.processor = processor
|
| 30 |
+
self.sampling_rate = sampling_rate
|
| 31 |
+
self.max_audio_seconds = max_audio_seconds
|
| 32 |
+
self.augmentation = augmentation
|
| 33 |
+
self.label_ids: list[list[int]] = []
|
| 34 |
+
for record in self.records:
|
| 35 |
+
language = language_prompts.get(record.language, record.language)
|
| 36 |
+
processor.tokenizer.set_prefix_tokens(language=language, task=task)
|
| 37 |
+
self.label_ids.append(processor.tokenizer(record.text).input_ids)
|
| 38 |
+
|
| 39 |
+
def __len__(self) -> int:
|
| 40 |
+
return len(self.records)
|
| 41 |
+
|
| 42 |
+
def __getitem__(self, index: int) -> dict[str, Any]:
|
| 43 |
+
import librosa
|
| 44 |
+
|
| 45 |
+
record = self.records[index]
|
| 46 |
+
audio_path = resolve_audio_path(record, self.manifest_path)
|
| 47 |
+
audio, _ = librosa.load(audio_path, sr=self.sampling_rate, mono=True)
|
| 48 |
+
duration = len(audio) / self.sampling_rate
|
| 49 |
+
if duration > self.max_audio_seconds + 0.01:
|
| 50 |
+
raise ManifestError(
|
| 51 |
+
f"Audio exceeds max_audio_seconds ({duration:.2f}s): {audio_path}. "
|
| 52 |
+
"Segment it before training; silent truncation would corrupt the transcript."
|
| 53 |
+
)
|
| 54 |
+
if self.augmentation is not None:
|
| 55 |
+
audio = augment_waveform(audio, self.sampling_rate, self.augmentation)
|
| 56 |
+
features = self.processor.feature_extractor(
|
| 57 |
+
audio,
|
| 58 |
+
sampling_rate=self.sampling_rate,
|
| 59 |
+
return_attention_mask=True,
|
| 60 |
+
)
|
| 61 |
+
item: dict[str, Any] = {
|
| 62 |
+
"input_features": features.input_features[0],
|
| 63 |
+
"labels": self.label_ids[index],
|
| 64 |
+
}
|
| 65 |
+
if getattr(features, "attention_mask", None) is not None:
|
| 66 |
+
item["attention_mask"] = features.attention_mask[0]
|
| 67 |
+
return item
|
src/buddi_asr/training/runtime.py
ADDED
|
@@ -0,0 +1,238 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""GPU preflight, checkpoint discovery, and reproducibility metadata."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import importlib.metadata
|
| 6 |
+
import shutil
|
| 7 |
+
from itertools import combinations
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from typing import Any
|
| 10 |
+
|
| 11 |
+
from buddi_asr.data.manifest import read_manifest, resolve_audio_path
|
| 12 |
+
from buddi_asr.data.validate import validate_manifest
|
| 13 |
+
from buddi_asr.errors import ManifestError, OptionalDependencyError
|
| 14 |
+
from buddi_asr.training.config import load_train_config
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def _gib(byte_count: int) -> float:
|
| 18 |
+
return round(byte_count / (1024**3), 2)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def find_latest_checkpoint(output_dir: str | Path) -> Path | None:
|
| 22 |
+
"""Return the highest complete ``checkpoint-N`` directory."""
|
| 23 |
+
|
| 24 |
+
root = Path(output_dir).resolve()
|
| 25 |
+
candidates: list[tuple[int, Path]] = []
|
| 26 |
+
if not root.is_dir():
|
| 27 |
+
return None
|
| 28 |
+
for path in root.glob("checkpoint-*"):
|
| 29 |
+
if not path.is_dir() or not (path / "trainer_state.json").is_file():
|
| 30 |
+
continue
|
| 31 |
+
try:
|
| 32 |
+
step = int(path.name.removeprefix("checkpoint-"))
|
| 33 |
+
except ValueError:
|
| 34 |
+
continue
|
| 35 |
+
candidates.append((step, path))
|
| 36 |
+
return max(candidates, default=(0, None), key=lambda item: item[0])[1]
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def resolve_resume_checkpoint(
|
| 40 |
+
requested: str | None,
|
| 41 |
+
output_dir: str | Path,
|
| 42 |
+
) -> Path | None:
|
| 43 |
+
"""Resolve ``auto``, ``none``, or an explicit Trainer checkpoint."""
|
| 44 |
+
|
| 45 |
+
if requested is None or requested.casefold() == "none":
|
| 46 |
+
return None
|
| 47 |
+
if requested.casefold() == "auto":
|
| 48 |
+
return find_latest_checkpoint(output_dir)
|
| 49 |
+
checkpoint = Path(requested).expanduser().resolve()
|
| 50 |
+
if not checkpoint.is_dir() or not (checkpoint / "trainer_state.json").is_file():
|
| 51 |
+
raise RuntimeError(
|
| 52 |
+
"resume_from_checkpoint must point to a complete Hugging Face Trainer "
|
| 53 |
+
f"checkpoint containing trainer_state.json: {checkpoint}"
|
| 54 |
+
)
|
| 55 |
+
return checkpoint
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def validate_training_manifests(
|
| 59 |
+
train_manifest: str | Path,
|
| 60 |
+
eval_manifest: str | Path,
|
| 61 |
+
*,
|
| 62 |
+
check_audio: bool,
|
| 63 |
+
test_manifest: str | Path | None = None,
|
| 64 |
+
) -> dict[str, Any]:
|
| 65 |
+
"""Validate manifests and reject speaker or audio leakage across every split."""
|
| 66 |
+
|
| 67 |
+
paths = {
|
| 68 |
+
"train": Path(train_manifest).resolve(),
|
| 69 |
+
"validation": Path(eval_manifest).resolve(),
|
| 70 |
+
}
|
| 71 |
+
if test_manifest is not None:
|
| 72 |
+
paths["test"] = Path(test_manifest).resolve()
|
| 73 |
+
reports: dict[str, dict[str, Any]] = {}
|
| 74 |
+
records_by_split: dict[str, list[Any]] = {}
|
| 75 |
+
speakers_by_split: dict[str, set[str]] = {}
|
| 76 |
+
audio_by_split: dict[str, set[str]] = {}
|
| 77 |
+
errors: list[str] = []
|
| 78 |
+
for split_name, path in paths.items():
|
| 79 |
+
report = validate_manifest(path, check_audio=check_audio)
|
| 80 |
+
records = list(read_manifest(path))
|
| 81 |
+
reports[split_name] = report
|
| 82 |
+
records_by_split[split_name] = records
|
| 83 |
+
speakers_by_split[split_name] = {record.speaker_id for record in records}
|
| 84 |
+
audio_by_split[split_name] = {str(resolve_audio_path(record, path)) for record in records}
|
| 85 |
+
errors.extend(f"{split_name}: {message}" for message in report["errors"])
|
| 86 |
+
if not records:
|
| 87 |
+
errors.append(f"{split_name} manifest is empty")
|
| 88 |
+
invalid_splits = sorted(
|
| 89 |
+
{record.split for record in records if record.split not in {None, split_name}}
|
| 90 |
+
)
|
| 91 |
+
if invalid_splits:
|
| 92 |
+
errors.append(
|
| 93 |
+
f"{split_name} manifest contains unexpected split values: {invalid_splits}"
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
for left, right in combinations(paths, 2):
|
| 97 |
+
speaker_overlap = speakers_by_split[left] & speakers_by_split[right]
|
| 98 |
+
if speaker_overlap:
|
| 99 |
+
errors.append(f"{len(speaker_overlap)} speaker IDs occur in both {left} and {right}")
|
| 100 |
+
audio_overlap = audio_by_split[left] & audio_by_split[right]
|
| 101 |
+
if audio_overlap:
|
| 102 |
+
errors.append(f"{len(audio_overlap)} audio files occur in both {left} and {right}")
|
| 103 |
+
if errors:
|
| 104 |
+
raise ManifestError("GPU preflight rejected the manifests: " + "; ".join(errors))
|
| 105 |
+
|
| 106 |
+
result = {
|
| 107 |
+
"speaker_overlap": 0,
|
| 108 |
+
"audio_overlap": 0,
|
| 109 |
+
"audio_files_checked": check_audio,
|
| 110 |
+
}
|
| 111 |
+
for split_name, path in paths.items():
|
| 112 |
+
result[split_name] = {
|
| 113 |
+
"path": str(path),
|
| 114 |
+
"records": len(records_by_split[split_name]),
|
| 115 |
+
"speakers": len(speakers_by_split[split_name]),
|
| 116 |
+
"warnings": reports[split_name]["warnings"],
|
| 117 |
+
}
|
| 118 |
+
return result
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def collect_runtime_metadata(torch: Any) -> dict[str, Any]:
|
| 122 |
+
"""Collect non-secret software and accelerator details for reproducibility."""
|
| 123 |
+
|
| 124 |
+
packages: dict[str, str] = {}
|
| 125 |
+
for name in ("accelerate", "librosa", "numpy", "peft", "torch", "transformers"):
|
| 126 |
+
try:
|
| 127 |
+
packages[name] = importlib.metadata.version(name)
|
| 128 |
+
except importlib.metadata.PackageNotFoundError:
|
| 129 |
+
packages[name] = "not-installed"
|
| 130 |
+
|
| 131 |
+
devices: list[dict[str, Any]] = []
|
| 132 |
+
if torch.cuda.is_available():
|
| 133 |
+
for index in range(torch.cuda.device_count()):
|
| 134 |
+
properties = torch.cuda.get_device_properties(index)
|
| 135 |
+
free_bytes, total_bytes = torch.cuda.mem_get_info(index)
|
| 136 |
+
with torch.cuda.device(index):
|
| 137 |
+
bf16_supported = bool(torch.cuda.is_bf16_supported())
|
| 138 |
+
devices.append(
|
| 139 |
+
{
|
| 140 |
+
"index": index,
|
| 141 |
+
"name": properties.name,
|
| 142 |
+
"compute_capability": f"{properties.major}.{properties.minor}",
|
| 143 |
+
"total_vram_gib": _gib(total_bytes),
|
| 144 |
+
"free_vram_gib": _gib(free_bytes),
|
| 145 |
+
"bf16_supported": bf16_supported,
|
| 146 |
+
}
|
| 147 |
+
)
|
| 148 |
+
return {
|
| 149 |
+
"packages": packages,
|
| 150 |
+
"cuda_available": bool(torch.cuda.is_available()),
|
| 151 |
+
"cuda_runtime": torch.version.cuda,
|
| 152 |
+
"cudnn_version": torch.backends.cudnn.version(),
|
| 153 |
+
"device_count": len(devices),
|
| 154 |
+
"devices": devices,
|
| 155 |
+
}
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def run_gpu_preflight(
|
| 159 |
+
config_path: str | Path,
|
| 160 |
+
*,
|
| 161 |
+
overrides: dict[str, Any] | None = None,
|
| 162 |
+
check_audio: bool = True,
|
| 163 |
+
minimum_free_vram_gib: float = 0.0,
|
| 164 |
+
test_manifest: str | Path | None = None,
|
| 165 |
+
) -> dict[str, Any]:
|
| 166 |
+
"""Fail before paid training if CUDA, data isolation, or disk state is invalid."""
|
| 167 |
+
|
| 168 |
+
config = load_train_config(config_path, overrides=overrides)
|
| 169 |
+
try:
|
| 170 |
+
import torch
|
| 171 |
+
except ImportError as exc:
|
| 172 |
+
raise OptionalDependencyError(
|
| 173 |
+
"GPU preflight requires training dependencies: python -m pip install -e '.[train]'"
|
| 174 |
+
) from exc
|
| 175 |
+
if not torch.cuda.is_available():
|
| 176 |
+
raise RuntimeError(
|
| 177 |
+
"CUDA is not available to PyTorch. Use an NVIDIA PyTorch image or install the "
|
| 178 |
+
"matching CUDA wheel from https://pytorch.org/get-started/locally/."
|
| 179 |
+
)
|
| 180 |
+
runtime = collect_runtime_metadata(torch)
|
| 181 |
+
if minimum_free_vram_gib < 0:
|
| 182 |
+
raise ValueError("minimum_free_vram_gib cannot be negative")
|
| 183 |
+
below_minimum = [
|
| 184 |
+
device for device in runtime["devices"] if device["free_vram_gib"] < minimum_free_vram_gib
|
| 185 |
+
]
|
| 186 |
+
if below_minimum:
|
| 187 |
+
names = ", ".join(
|
| 188 |
+
f"GPU {device['index']} ({device['free_vram_gib']} GiB free)"
|
| 189 |
+
for device in below_minimum
|
| 190 |
+
)
|
| 191 |
+
raise RuntimeError(
|
| 192 |
+
f"Insufficient free VRAM for the requested {minimum_free_vram_gib} GiB floor: {names}"
|
| 193 |
+
)
|
| 194 |
+
if config.bf16 and not all(device["bf16_supported"] for device in runtime["devices"]):
|
| 195 |
+
raise RuntimeError("bf16=true, but at least one selected CUDA device lacks BF16 support")
|
| 196 |
+
|
| 197 |
+
manifests = validate_training_manifests(
|
| 198 |
+
config.train_manifest,
|
| 199 |
+
config.eval_manifest,
|
| 200 |
+
check_audio=check_audio,
|
| 201 |
+
test_manifest=test_manifest,
|
| 202 |
+
)
|
| 203 |
+
output_dir = Path(config.output_dir).resolve()
|
| 204 |
+
disk_anchor = output_dir if output_dir.exists() else output_dir.parent
|
| 205 |
+
while not disk_anchor.exists() and disk_anchor != disk_anchor.parent:
|
| 206 |
+
disk_anchor = disk_anchor.parent
|
| 207 |
+
disk_free_gib = _gib(shutil.disk_usage(disk_anchor).free)
|
| 208 |
+
warnings = [
|
| 209 |
+
warning
|
| 210 |
+
for split_name in ("train", "validation", "test")
|
| 211 |
+
if split_name in manifests
|
| 212 |
+
for warning in manifests[split_name]["warnings"]
|
| 213 |
+
]
|
| 214 |
+
if disk_free_gib < 10:
|
| 215 |
+
warnings.append(
|
| 216 |
+
f"Only {disk_free_gib} GiB disk space is free; dataset caches and checkpoints may fill it"
|
| 217 |
+
)
|
| 218 |
+
checkpoint = resolve_resume_checkpoint(config.resume_from_checkpoint, output_dir)
|
| 219 |
+
precision = "bf16" if config.bf16 else "fp16" if config.fp16 else "fp32"
|
| 220 |
+
return {
|
| 221 |
+
"ok": True,
|
| 222 |
+
"model": config.model_name_or_path,
|
| 223 |
+
"method": config.method,
|
| 224 |
+
"precision": precision,
|
| 225 |
+
"output_dir": str(output_dir),
|
| 226 |
+
"resume_checkpoint": str(checkpoint) if checkpoint else None,
|
| 227 |
+
"per_device_train_batch_size": config.per_device_train_batch_size,
|
| 228 |
+
"gradient_accumulation_steps": config.gradient_accumulation_steps,
|
| 229 |
+
"effective_batch_per_update": (
|
| 230 |
+
config.per_device_train_batch_size
|
| 231 |
+
* config.gradient_accumulation_steps
|
| 232 |
+
* runtime["device_count"]
|
| 233 |
+
),
|
| 234 |
+
"disk_free_gib": disk_free_gib,
|
| 235 |
+
"runtime": runtime,
|
| 236 |
+
"manifests": manifests,
|
| 237 |
+
"warnings": warnings,
|
| 238 |
+
}
|