diff --git a/README.md b/README.md index 4ba85d415..742b9b71f 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@ C/C++ speech-to-text inference library. Runs diverse STT model families via [GGU | Canary-Qwen 2.5B | `canary-qwen-2.5b` | - | [docs/models/canary-qwen-2.5b.md](docs/models/canary-qwen-2.5b.md) | | Cohere Transcribe | `cohere-transcribe-03-2026`, `cohere-transcribe-arabic-07-2026` | - | [docs/models/cohere.md](docs/models/cohere.md) | | Fun-ASR-Nano | `fun-asr-mlt-nano-2512`, `fun-asr-nano-2512` | - | [docs/models/fun-asr-nano.md](docs/models/fun-asr-nano.md) | -| GigaAM | `gigaam-v3-ctc`, `gigaam-v3-e2e-ctc`, `gigaam-v3-e2e-rnnt`, `gigaam-v3-rnnt`, `gigaam-v4-e2e-rnnt` | token timestamps | [docs/models/gigaam.md](docs/models/gigaam.md) | +| GigaAM | `gigaam-multilingual-v2-e2e-rnnt`, `gigaam-v3-ctc`, `gigaam-v3-e2e-ctc`, `gigaam-v3-e2e-rnnt`, `gigaam-v3-rnnt`, `gigaam-v4-e2e-rnnt` | token timestamps | [docs/models/gigaam.md](docs/models/gigaam.md) | | Granite Speech 4 / 4.1 | `granite-4.0-1b-speech`, `granite-speech-4.1-2b`, `granite-speech-4.1-2b-nar`, `granite-speech-4.1-2b-plus` | diarize, translate, word timestamps | [docs/models/granite-speech.md](docs/models/granite-speech.md) | | Granite Speech 5.0 TurboCTC | `granite-speech-5.0-470m-turboctc`, `granite-speech-5.0-470m-turboctc-nc` | - | [docs/models/granite-speech-5.0-turboctc.md](docs/models/granite-speech-5.0-turboctc.md) | | MedASR | `medasr` | token timestamps | [docs/models/medasr.md](docs/models/medasr.md) | diff --git a/catalog/gigaam-multilingual-v2-e2e-rnnt.json b/catalog/gigaam-multilingual-v2-e2e-rnnt.json new file mode 100644 index 000000000..03f4112f4 --- /dev/null +++ b/catalog/gigaam-multilingual-v2-e2e-rnnt.json @@ -0,0 +1,102 @@ +{ + "schema": "transcribe-catalog-v1", + "variant": "gigaam-multilingual-v2-e2e-rnnt", + "family": "gigaam", + "display_name": "GigaAM Multilingual v2 E2E-RNN-T", + "params": 776083099, + "license": { + "spdx": "mit", + "display": "MIT" + }, + "upstream_repo": "ai-sage/GigaAM-Multilingual-v2", + "upstream_commit": "c21483b", + "published_repo": "handy-computer/gigaam-multilingual-v2-e2e-rnnt-gguf", + "docs_page": "gigaam.md", + "languages": [ + "ru", "en", "kk", "ky", "uz", "be", "fr", "es", "ba", "ka", "hy", "ro", + "tk", "az", "tg", "de", "it", "nl", "pl", "pt", "tt" + ], + "language_tag_form": "bare-bcp47", + "long_form_strategy": "chunked-unbounded", + "speed_opt_in": ["m1"], + "benchmark_exceptions": [ + {"kind":"speed","match":{"machine":"m4"},"reason":"No base Apple M4 was available when Multilingual-v2 was published. Speed is published for the Apple M4 Max, the Ryzen 7 PRO 4750U, and an Apple M1 as a stand-in (speed_opt_in)."} + ], + "capabilities": { + "transcribe": {"supported":true,"verified":false}, + "translate": {"supported":false}, + "lang_detect": {"supported":false}, + "timestamps": {"supported":true,"verified":false,"granularities":["token"]}, + "streaming": {"supported":false}, + "diarize": {"supported":false}, + "batching": {"supported":false} + }, + "downloads": [ + {"quant":"F32","filename":"gigaam-multilingual-v2-e2e-rnnt-F32.gguf","size_bytes":3104463040}, + {"quant":"F16","filename":"gigaam-multilingual-v2-e2e-rnnt-F16.gguf","size_bytes":1554223552}, + {"quant":"Q8_0","filename":"gigaam-multilingual-v2-e2e-rnnt-Q8_0.gguf","size_bytes":827548800}, + {"quant":"Q6_K","filename":"gigaam-multilingual-v2-e2e-rnnt-Q6_K.gguf","size_bytes":641640064}, + {"quant":"Q5_K_M","filename":"gigaam-multilingual-v2-e2e-rnnt-Q5_K_M.gguf","size_bytes":555713664}, + {"quant":"Q4_K_M","filename":"gigaam-multilingual-v2-e2e-rnnt-Q4_K_M.gguf","size_bytes":465101952} + ], + "accuracy_benchmarks": [ + {"dataset":"librispeech","split":"test-clean","language":"en","language_hint":"en","backend":"cuda","quant":"F32","metric":"wer","err_pct":1.95,"ci95":[1.81,2.1],"n_utts":2620,"batch_size":8,"timestamps":"none","engine_sha":"d704775e","publication_profile":"asr-publication-v2","measured_on":null,"errors":{"sub":806,"del":139,"ins":86},"empty_hyp":0,"utts_over_50pct":2}, + {"dataset":"librispeech","split":"test-clean","language":"en","language_hint":"en","backend":"cuda","quant":"F16","metric":"wer","err_pct":1.94,"ci95":[1.8,2.1],"n_utts":2620,"batch_size":8,"timestamps":"none","engine_sha":"d704775e","publication_profile":"asr-publication-v2","measured_on":null,"errors":{"sub":805,"del":138,"ins":84},"empty_hyp":0,"utts_over_50pct":2}, + {"dataset":"librispeech","split":"test-clean","language":"en","language_hint":"en","backend":"cuda","quant":"Q8_0","metric":"wer","err_pct":1.96,"ci95":[1.81,2.12],"n_utts":2620,"batch_size":8,"timestamps":"none","engine_sha":"d704775e","publication_profile":"asr-publication-v2","measured_on":null,"errors":{"sub":808,"del":144,"ins":85},"empty_hyp":0,"utts_over_50pct":2}, + {"dataset":"librispeech","split":"test-clean","language":"en","language_hint":"en","backend":"cuda","quant":"Q6_K","metric":"wer","err_pct":1.99,"ci95":[1.85,2.15],"n_utts":2620,"batch_size":8,"timestamps":"none","engine_sha":"d704775e","publication_profile":"asr-publication-v2","measured_on":null,"errors":{"sub":824,"del":144,"ins":84},"empty_hyp":0,"utts_over_50pct":3}, + {"dataset":"librispeech","split":"test-clean","language":"en","language_hint":"en","backend":"cuda","quant":"Q5_K_M","metric":"wer","err_pct":1.97,"ci95":[1.82,2.13],"n_utts":2620,"batch_size":8,"timestamps":"none","engine_sha":"d704775e","publication_profile":"asr-publication-v2","measured_on":null,"errors":{"sub":815,"del":138,"ins":86},"empty_hyp":0,"utts_over_50pct":2}, + {"dataset":"librispeech","split":"test-clean","language":"en","language_hint":"en","backend":"cuda","quant":"Q4_K_M","metric":"wer","err_pct":1.97,"ci95":[1.82,2.13],"n_utts":2620,"batch_size":8,"timestamps":"none","engine_sha":"d704775e","publication_profile":"asr-publication-v2","measured_on":null,"errors":{"sub":814,"del":136,"ins":90},"empty_hyp":0,"utts_over_50pct":5}, + {"dataset":"fleurs","split":"test","language":"ru","language_hint":"ru","backend":"cuda","quant":"Q8_0","metric":"wer","err_pct":4.03,"ci95":[3.58,4.46],"n_utts":775,"batch_size":8,"timestamps":"none","engine_sha":"d704775e","publication_profile":"asr-publication-v2","measured_on":null,"errors":{"sub":527,"del":63,"ins":18},"empty_hyp":0,"utts_over_50pct":0}, + {"dataset":"fleurs","split":"test","language":"en","language_hint":"en","backend":"cuda","quant":"Q8_0","metric":"wer","err_pct":4.52,"ci95":[4.11,4.99],"n_utts":647,"batch_size":8,"timestamps":"none","engine_sha":"d704775e","publication_profile":"asr-publication-v2","measured_on":null,"errors":{"sub":464,"del":134,"ins":57},"empty_hyp":0,"utts_over_50pct":0}, + {"dataset":"fleurs","split":"test","language":"kk","language_hint":"kk","backend":"cuda","quant":"Q8_0","metric":"wer","err_pct":4.79,"ci95":[4.34,5.27],"n_utts":856,"batch_size":8,"timestamps":"none","engine_sha":"d704775e","publication_profile":"asr-publication-v2","measured_on":null,"errors":{"sub":586,"del":100,"ins":33},"empty_hyp":0,"utts_over_50pct":0}, + {"dataset":"fleurs","split":"test","language":"ky","language_hint":"ky","backend":"cuda","quant":"Q8_0","metric":"wer","err_pct":5.9,"ci95":[5.49,6.36],"n_utts":977,"batch_size":8,"timestamps":"none","engine_sha":"d704775e","publication_profile":"asr-publication-v2","measured_on":null,"errors":{"sub":812,"del":159,"ins":50},"empty_hyp":0,"utts_over_50pct":2}, + {"dataset":"fleurs","split":"test","language":"uz","language_hint":"uz","backend":"cuda","quant":"Q8_0","metric":"wer","err_pct":28.9,"ci95":[27.67,30.23],"n_utts":862,"batch_size":8,"timestamps":"none","engine_sha":"d704775e","publication_profile":"asr-publication-v2","measured_on":null,"errors":{"sub":2639,"del":84,"ins":1891},"empty_hyp":0,"utts_over_50pct":107}, + {"dataset":"fleurs","split":"test","language":"be","language_hint":"be","backend":"cuda","quant":"Q8_0","metric":"wer","err_pct":4.43,"ci95":[4.07,4.83],"n_utts":967,"batch_size":8,"timestamps":"none","engine_sha":"d704775e","publication_profile":"asr-publication-v2","measured_on":null,"errors":{"sub":750,"del":112,"ins":60},"empty_hyp":0,"utts_over_50pct":0}, + {"dataset":"fleurs","split":"test","language":"fr","language_hint":"fr","backend":"cuda","quant":"Q8_0","metric":"wer","err_pct":4.36,"ci95":[3.92,4.77],"n_utts":676,"batch_size":8,"timestamps":"none","engine_sha":"d704775e","publication_profile":"asr-publication-v2","measured_on":null,"errors":{"sub":608,"del":122,"ins":54},"empty_hyp":0,"utts_over_50pct":0}, + {"dataset":"fleurs","split":"test","language":"es","language_hint":"es","backend":"cuda","quant":"Q8_0","metric":"wer","err_pct":2.93,"ci95":[2.63,3.23],"n_utts":908,"batch_size":8,"timestamps":"none","engine_sha":"d704775e","publication_profile":"asr-publication-v2","measured_on":null,"errors":{"sub":482,"del":148,"ins":53},"empty_hyp":0,"utts_over_50pct":1}, + {"dataset":"fleurs","split":"test","language":"ka","language_hint":"ka","backend":"cuda","quant":"Q8_0","metric":"wer","err_pct":6.51,"ci95":[6.03,7.0],"n_utts":979,"batch_size":8,"timestamps":"none","engine_sha":"d704775e","publication_profile":"asr-publication-v2","measured_on":null,"errors":{"sub":912,"del":129,"ins":75},"empty_hyp":0,"utts_over_50pct":3}, + {"dataset":"fleurs","split":"test","language":"hy","language_hint":"hy","backend":"cuda","quant":"Q8_0","metric":"wer","err_pct":4.5,"ci95":[4.09,4.9],"n_utts":932,"batch_size":8,"timestamps":"none","engine_sha":"d704775e","publication_profile":"asr-publication-v2","measured_on":null,"errors":{"sub":646,"del":118,"ins":53},"empty_hyp":0,"utts_over_50pct":1}, + {"dataset":"fleurs","split":"test","language":"ro","language_hint":"ro","backend":"cuda","quant":"Q8_0","metric":"wer","err_pct":4.22,"ci95":[3.85,4.62],"n_utts":883,"batch_size":8,"timestamps":"none","engine_sha":"d704775e","publication_profile":"asr-publication-v2","measured_on":null,"errors":{"sub":666,"del":151,"ins":61},"empty_hyp":0,"utts_over_50pct":0}, + {"dataset":"fleurs","split":"test","language":"az","language_hint":"az","backend":"cuda","quant":"Q8_0","metric":"wer","err_pct":6.67,"ci95":[6.19,7.15],"n_utts":923,"batch_size":8,"timestamps":"none","engine_sha":"d704775e","publication_profile":"asr-publication-v2","measured_on":null,"errors":{"sub":923,"del":208,"ins":64},"empty_hyp":0,"utts_over_50pct":0}, + {"dataset":"fleurs","split":"test","language":"tg","language_hint":"tg","backend":"cuda","quant":"Q8_0","metric":"wer","err_pct":8.0,"ci95":[7.01,9.12],"n_utts":600,"batch_size":8,"timestamps":"none","engine_sha":"d704775e","publication_profile":"asr-publication-v2","measured_on":null,"errors":{"sub":799,"del":160,"ins":84},"empty_hyp":1,"utts_over_50pct":11}, + {"dataset":"fleurs","split":"test","language":"de","language_hint":"de","backend":"cuda","quant":"Q8_0","metric":"wer","err_pct":3.87,"ci95":[3.51,4.23],"n_utts":862,"batch_size":8,"timestamps":"none","engine_sha":"d704775e","publication_profile":"asr-publication-v2","measured_on":null,"errors":{"sub":541,"del":147,"ins":36},"empty_hyp":0,"utts_over_50pct":0}, + {"dataset":"fleurs","split":"test","language":"it","language_hint":"it","backend":"cuda","quant":"Q8_0","metric":"wer","err_pct":2.04,"ci95":[1.8,2.29],"n_utts":865,"batch_size":8,"timestamps":"none","engine_sha":"d704775e","publication_profile":"asr-publication-v2","measured_on":null,"errors":{"sub":331,"del":75,"ins":28},"empty_hyp":0,"utts_over_50pct":0}, + {"dataset":"fleurs","split":"test","language":"nl","language_hint":"nl","backend":"cuda","quant":"Q8_0","metric":"wer","err_pct":4.58,"ci95":[3.95,5.26],"n_utts":364,"batch_size":8,"timestamps":"none","engine_sha":"d704775e","publication_profile":"asr-publication-v2","measured_on":null,"errors":{"sub":273,"del":73,"ins":39},"empty_hyp":0,"utts_over_50pct":0}, + {"dataset":"fleurs","split":"test","language":"pl","language_hint":"pl","backend":"cuda","quant":"Q8_0","metric":"wer","err_pct":4.64,"ci95":[4.17,5.26],"n_utts":758,"batch_size":8,"timestamps":"none","engine_sha":"d704775e","publication_profile":"asr-publication-v2","measured_on":null,"errors":{"sub":527,"del":103,"ins":38},"empty_hyp":0,"utts_over_50pct":2}, + {"dataset":"fleurs","split":"test","language":"pt","language_hint":"pt","backend":"cuda","quant":"Q8_0","metric":"wer","err_pct":4.44,"ci95":[4.0,4.92],"n_utts":919,"batch_size":8,"timestamps":"none","engine_sha":"d704775e","publication_profile":"asr-publication-v2","measured_on":null,"errors":{"sub":665,"del":174,"ins":115},"empty_hyp":0,"utts_over_50pct":3} + ], + "headline_benchmark": { + "dataset": "librispeech", + "split": "test-clean", + "language": "en", + "metric": "wer", + "batch_size": 8, + "timestamps": "none" + }, + "speed_benchmarks": [ + {"machine":"m1","backend":"cpu","quant":"Q4_K_M","sample":"dots","sample_duration_s":35.332,"total_ms":4454.9,"xrt_compute":7.93,"wall_ms":4455.6,"xrt_wall":7.93,"load_ms":226.4,"mel_ms":12.5,"encode_ms":4308.3,"decode_ms":134.2,"engine_sha":"d704775e","publication_profile":"asr-publication-v2","measured_on":"2026-12-04","thermal_gated":null}, + {"machine":"m1","backend":"cpu","quant":"Q4_K_M","sample":"jfk","sample_duration_s":11.0,"total_ms":1210.2,"xrt_compute":9.09,"wall_ms":1211.9,"xrt_wall":9.08,"load_ms":51.9,"mel_ms":4.2,"encode_ms":1177.0,"decode_ms":28.9,"engine_sha":"d704775e","publication_profile":"asr-publication-v2","measured_on":"2026-12-04","thermal_gated":null}, + {"machine":"m1","backend":"cpu","quant":"Q8_0","sample":"dots","sample_duration_s":35.332,"total_ms":3591.4,"xrt_compute":9.84,"wall_ms":3592.1,"xrt_wall":9.84,"load_ms":289.9,"mel_ms":12.4,"encode_ms":3447.4,"decode_ms":131.7,"engine_sha":"d704775e","publication_profile":"asr-publication-v2","measured_on":"2026-12-04","thermal_gated":null}, + {"machine":"m1","backend":"cpu","quant":"Q8_0","sample":"jfk","sample_duration_s":11.0,"total_ms":1051.1,"xrt_compute":10.47,"wall_ms":1052.8,"xrt_wall":10.45,"load_ms":52.4,"mel_ms":4.1,"encode_ms":1018.8,"decode_ms":28.2,"engine_sha":"d704775e","publication_profile":"asr-publication-v2","measured_on":"2026-12-04","thermal_gated":null}, + {"machine":"m1","backend":"metal","quant":"Q4_K_M","sample":"dots","sample_duration_s":35.332,"total_ms":1121.9,"xrt_compute":31.49,"wall_ms":1122.4,"xrt_wall":31.48,"load_ms":56.1,"mel_ms":11.9,"encode_ms":976.3,"decode_ms":133.6,"engine_sha":"d704775e","publication_profile":"asr-publication-v2","measured_on":"2026-12-04","thermal_gated":null}, + {"machine":"m1","backend":"metal","quant":"Q4_K_M","sample":"jfk","sample_duration_s":11.0,"total_ms":311.6,"xrt_compute":35.3,"wall_ms":317.7,"xrt_wall":34.62,"load_ms":54.5,"mel_ms":4.0,"encode_ms":274.7,"decode_ms":32.9,"engine_sha":"d704775e","publication_profile":"asr-publication-v2","measured_on":"2026-12-04","thermal_gated":null}, + {"machine":"m1","backend":"metal","quant":"Q8_0","sample":"dots","sample_duration_s":35.332,"total_ms":1054.8,"xrt_compute":33.5,"wall_ms":1055.3,"xrt_wall":33.48,"load_ms":58.7,"mel_ms":12.9,"encode_ms":904.6,"decode_ms":137.3,"engine_sha":"d704775e","publication_profile":"asr-publication-v2","measured_on":"2026-12-04","thermal_gated":null}, + {"machine":"m1","backend":"metal","quant":"Q8_0","sample":"jfk","sample_duration_s":11.0,"total_ms":286.7,"xrt_compute":38.37,"wall_ms":292.8,"xrt_wall":37.57,"load_ms":60.3,"mel_ms":4.0,"encode_ms":249.2,"decode_ms":33.5,"engine_sha":"d704775e","publication_profile":"asr-publication-v2","measured_on":"2026-12-04","thermal_gated":null}, + {"machine":"m4-max","backend":"cpu","quant":"Q4_K_M","sample":"dots","sample_duration_s":35.332,"total_ms":1598.8,"xrt_compute":22.1,"wall_ms":1599.3,"xrt_wall":22.09,"load_ms":140.6,"mel_ms":4.7,"encode_ms":1542.6,"decode_ms":51.4,"engine_sha":"d704775e","publication_profile":"asr-publication-v2","measured_on":"2026-12-04","thermal_gated":null}, + {"machine":"m4-max","backend":"cpu","quant":"Q4_K_M","sample":"jfk","sample_duration_s":11.0,"total_ms":446.4,"xrt_compute":24.64,"wall_ms":447.6,"xrt_wall":24.58,"load_ms":43.5,"mel_ms":1.6,"encode_ms":433.8,"decode_ms":11.0,"engine_sha":"d704775e","publication_profile":"asr-publication-v2","measured_on":"2026-12-04","thermal_gated":null}, + {"machine":"m4-max","backend":"cpu","quant":"Q8_0","sample":"dots","sample_duration_s":35.332,"total_ms":1264.9,"xrt_compute":27.93,"wall_ms":1265.3,"xrt_wall":27.92,"load_ms":39.6,"mel_ms":4.8,"encode_ms":1207.6,"decode_ms":52.5,"engine_sha":"d704775e","publication_profile":"asr-publication-v2","measured_on":"2026-12-04","thermal_gated":null}, + {"machine":"m4-max","backend":"cpu","quant":"Q8_0","sample":"jfk","sample_duration_s":11.0,"total_ms":330.2,"xrt_compute":33.31,"wall_ms":331.4,"xrt_wall":33.19,"load_ms":39.7,"mel_ms":1.5,"encode_ms":317.3,"decode_ms":11.3,"engine_sha":"d704775e","publication_profile":"asr-publication-v2","measured_on":"2026-12-04","thermal_gated":null}, + {"machine":"m4-max","backend":"metal","quant":"Q4_K_M","sample":"dots","sample_duration_s":35.332,"total_ms":225.7,"xrt_compute":156.55,"wall_ms":226.0,"xrt_wall":156.31,"load_ms":40.4,"mel_ms":5.5,"encode_ms":167.3,"decode_ms":52.9,"engine_sha":"d704775e","publication_profile":"asr-publication-v2","measured_on":"2026-12-04","thermal_gated":null}, + {"machine":"m4-max","backend":"metal","quant":"Q4_K_M","sample":"jfk","sample_duration_s":11.0,"total_ms":65.3,"xrt_compute":168.52,"wall_ms":69.3,"xrt_wall":158.63,"load_ms":42.1,"mel_ms":2.5,"encode_ms":51.5,"decode_ms":11.3,"engine_sha":"d704775e","publication_profile":"asr-publication-v2","measured_on":"2026-12-04","thermal_gated":null}, + {"machine":"m4-max","backend":"metal","quant":"Q8_0","sample":"dots","sample_duration_s":35.332,"total_ms":220.1,"xrt_compute":160.52,"wall_ms":220.4,"xrt_wall":160.28,"load_ms":46.9,"mel_ms":5.8,"encode_ms":162.3,"decode_ms":52.0,"engine_sha":"d704775e","publication_profile":"asr-publication-v2","measured_on":"2026-12-04","thermal_gated":null}, + {"machine":"m4-max","backend":"metal","quant":"Q8_0","sample":"jfk","sample_duration_s":11.0,"total_ms":64.0,"xrt_compute":171.82,"wall_ms":68.0,"xrt_wall":161.81,"load_ms":47.8,"mel_ms":2.4,"encode_ms":50.6,"decode_ms":11.0,"engine_sha":"d704775e","publication_profile":"asr-publication-v2","measured_on":"2026-12-04","thermal_gated":null}, + {"machine":"ryzen-4750u","backend":"cpu","quant":"Q4_K_M","sample":"dots","sample_duration_s":35.332,"total_ms":4449.4,"xrt_compute":7.94,"wall_ms":4455.4,"xrt_wall":7.93,"load_ms":56.2,"mel_ms":55.5,"encode_ms":3684.2,"decode_ms":709.7,"engine_sha":"d704775e","publication_profile":"asr-publication-v2","measured_on":"2026-12-04","thermal_gated":null}, + {"machine":"ryzen-4750u","backend":"cpu","quant":"Q4_K_M","sample":"jfk","sample_duration_s":11.0,"total_ms":1094.6,"xrt_compute":10.05,"wall_ms":1100.1,"xrt_wall":10.0,"load_ms":52.9,"mel_ms":23.8,"encode_ms":923.6,"decode_ms":147.2,"engine_sha":"d704775e","publication_profile":"asr-publication-v2","measured_on":"2026-12-04","thermal_gated":null}, + {"machine":"ryzen-4750u","backend":"cpu","quant":"Q8_0","sample":"dots","sample_duration_s":35.332,"total_ms":5338.1,"xrt_compute":6.62,"wall_ms":5344.5,"xrt_wall":6.61,"load_ms":71.1,"mel_ms":55.3,"encode_ms":4561.8,"decode_ms":720.9,"engine_sha":"d704775e","publication_profile":"asr-publication-v2","measured_on":"2026-12-04","thermal_gated":null}, + {"machine":"ryzen-4750u","backend":"cpu","quant":"Q8_0","sample":"jfk","sample_duration_s":11.0,"total_ms":1229.3,"xrt_compute":8.95,"wall_ms":1234.6,"xrt_wall":8.91,"load_ms":46.6,"mel_ms":25.9,"encode_ms":1053.3,"decode_ms":150.1,"engine_sha":"d704775e","publication_profile":"asr-publication-v2","measured_on":"2026-12-04","thermal_gated":null}, + {"machine":"ryzen-4750u","backend":"vulkan","quant":"Q4_K_M","sample":"dots","sample_duration_s":35.332,"total_ms":3943.8,"xrt_compute":8.96,"wall_ms":3944.5,"xrt_wall":8.96,"load_ms":198.1,"mel_ms":59.3,"encode_ms":3222.9,"decode_ms":661.6,"engine_sha":"d704775e","publication_profile":"asr-publication-v2","measured_on":"2026-12-04","thermal_gated":null}, + {"machine":"ryzen-4750u","backend":"vulkan","quant":"Q4_K_M","sample":"jfk","sample_duration_s":11.0,"total_ms":1090.6,"xrt_compute":10.09,"wall_ms":1104.5,"xrt_wall":9.96,"load_ms":175.9,"mel_ms":24.9,"encode_ms":901.2,"decode_ms":164.5,"engine_sha":"d704775e","publication_profile":"asr-publication-v2","measured_on":"2026-12-04","thermal_gated":null}, + {"machine":"ryzen-4750u","backend":"vulkan","quant":"Q8_0","sample":"dots","sample_duration_s":35.332,"total_ms":3925.7,"xrt_compute":9.0,"wall_ms":3927.7,"xrt_wall":9.0,"load_ms":329.8,"mel_ms":56.3,"encode_ms":3146.3,"decode_ms":723.1,"engine_sha":"d704775e","publication_profile":"asr-publication-v2","measured_on":"2026-12-04","thermal_gated":null}, + {"machine":"ryzen-4750u","backend":"vulkan","quant":"Q8_0","sample":"jfk","sample_duration_s":11.0,"total_ms":1060.1,"xrt_compute":10.38,"wall_ms":1070.1,"xrt_wall":10.28,"load_ms":331.2,"mel_ms":25.8,"encode_ms":870.6,"decode_ms":163.7,"engine_sha":"d704775e","publication_profile":"asr-publication-v2","measured_on":"2026-12-04","thermal_gated":null} + ] +} diff --git a/docs/models/gigaam-multilingual-v2-e2e-rnnt.md b/docs/models/gigaam-multilingual-v2-e2e-rnnt.md new file mode 100644 index 000000000..dcbb62f46 --- /dev/null +++ b/docs/models/gigaam-multilingual-v2-e2e-rnnt.md @@ -0,0 +1,192 @@ +# GigaAM Multilingual-v2 e2e-RNN-T + + +Upstream: [`ai-sage/GigaAM-Multilingual-v2`](https://huggingface.co/ai-sage/GigaAM-Multilingual-v2) at [`c21483b`](https://huggingface.co/ai-sage/GigaAM-Multilingual-v2/commit/c21483b). + +Offline multilingual speech-to-text covering 21 languages, with punctuation and capitalization: Russian, English, German, French, Spanish, Italian, Portuguese, Dutch, Polish, Romanian, Belarusian, Kazakh, Kyrgyz, Uzbek, Tajik, Turkmen, Azerbaijani, Georgian, Armenian, Bashkir and Tatar. A Zapformer encoder conditioned on a language embedding, with an RNN-T decoder. The source language is selected per call (--language kk, hy, ...) or left to the model (auto). Recordings of any length are encoded in overlapping 25 s windows. Not a streaming model and does not translate. + + +## What it's for + +Offline speech-to-text in 21 languages, with cased and punctuated output. +It is the most accurate GigaAM model on FLEURS Russian and English, and +covers far more languages than the others. It is about three times the +size of [`gigaam-v4-e2e-rnnt`](gigaam-v4-e2e-rnnt.md) and about three times +slower. + +The encoder is GigaAM-v4's Zapformer, larger and conditioned on a language +embedding. The source language is selected per call (`--language kk`). +Without a hint, or with `--language auto`, the model uses its default +embedding, which is how ai-sage reports its own results. On FLEURS the two +are within 0.2 points of each other on every language, so the hint is +optional. The model does not report which language it heard. + +The checkpoint's `raw` head (lowercase, no punctuation) and its streaming +modes are not part of this port. Other GigaAM models are on the +[GigaAM page](gigaam.md). See ai-sage's +[model card](https://huggingface.co/ai-sage/GigaAM-Multilingual-v2) for +training data and their own evaluation. + + +Licensed MIT. Ported from upstream commit [`c21483b`](https://huggingface.co/ai-sage/GigaAM-Multilingual-v2/commit/c21483b), pinned 2026-11-27. Validated against the upstream `modeling_gigaam.py` reference at transcribe.cpp commit [`d704775e`](https://github.com/handy-computer/transcribe.cpp/tree/d704775e) on 2026-12-04. + + +## Download + +Q8_0 is the recommended download. Every quant is within 0.05 points of +F32 on LibriSpeech and on FLEURS Russian, English and Kazakh, so Q4_K_M is +a good choice when size matters. On CPU it runs a little slower than Q8_0. + + +| Quantization | Download | Size | WER (LibriSpeech test-clean) | +| --- | --- | ---: | ---: | +| F32 | [gigaam-multilingual-v2-e2e-rnnt-F32.gguf](https://huggingface.co/handy-computer/gigaam-multilingual-v2-e2e-rnnt-gguf/resolve/main/gigaam-multilingual-v2-e2e-rnnt-F32.gguf) | 3.10 GB | 1.95% | +| F16 | [gigaam-multilingual-v2-e2e-rnnt-F16.gguf](https://huggingface.co/handy-computer/gigaam-multilingual-v2-e2e-rnnt-gguf/resolve/main/gigaam-multilingual-v2-e2e-rnnt-F16.gguf) | 1.55 GB | 1.94% | +| Q8_0 | [gigaam-multilingual-v2-e2e-rnnt-Q8_0.gguf](https://huggingface.co/handy-computer/gigaam-multilingual-v2-e2e-rnnt-gguf/resolve/main/gigaam-multilingual-v2-e2e-rnnt-Q8_0.gguf) | 828 MB | 1.96% | +| Q6_K | [gigaam-multilingual-v2-e2e-rnnt-Q6_K.gguf](https://huggingface.co/handy-computer/gigaam-multilingual-v2-e2e-rnnt-gguf/resolve/main/gigaam-multilingual-v2-e2e-rnnt-Q6_K.gguf) | 642 MB | 1.99% | +| Q5_K_M | [gigaam-multilingual-v2-e2e-rnnt-Q5_K_M.gguf](https://huggingface.co/handy-computer/gigaam-multilingual-v2-e2e-rnnt-gguf/resolve/main/gigaam-multilingual-v2-e2e-rnnt-Q5_K_M.gguf) | 556 MB | 1.97% | +| Q4_K_M | [gigaam-multilingual-v2-e2e-rnnt-Q4_K_M.gguf](https://huggingface.co/handy-computer/gigaam-multilingual-v2-e2e-rnnt-gguf/resolve/main/gigaam-multilingual-v2-e2e-rnnt-Q4_K_M.gguf) | 465 MB | 1.97% | + + + +WER on the full LibriSpeech test-clean split (2,620 utterances), batch size 8, timestamps none, language hint `en`, decoded on cuda. Measured at transcribe.cpp `d704775e`. + + + +Greedy RNN-T decoding, no external LM. PyTorch reference baseline on the same +manifest: 1.94%. ai-sage does not publish a LibriSpeech or FLEURS number. FLEURS +Uzbek reads high because its references spell oʻ and gʻ with U+02BB, which the +normalizer keeps, while the model writes an apostrophe, which it drops. Counting +the two as equal, Uzbek Q8_0 is 6.5%. + + +FLEURS test, language given: + + +**FLEURS test** + +| Language | Metric | Q8_0 | +| --- | --- | ---: | +| az | WER | 6.67% | +| be | WER | 4.43% | +| de | WER | 3.87% | +| en | WER | 4.52% | +| es | WER | 2.93% | +| fr | WER | 4.36% | +| hy | WER | 4.50% | +| it | WER | 2.04% | +| ka | WER | 6.51% | +| kk | WER | 4.79% | +| ky | WER | 5.90% | +| nl | WER | 4.58% | +| pl | WER | 4.64% | +| pt | WER | 4.44% | +| ro | WER | 4.22% | +| ru | WER | 4.03% | +| tg | WER | 8.00% | +| uz | WER | 28.90% | + + +## Languages + +`ru`, `en`, `de`, `fr`, `es`, `it`, `pt`, `nl`, `pl`, `ro`, `be`, `kk`, +`ky`, `uz`, `tg`, `tk`, `az`, `ka`, `hy`, `ba`, `tt`. FLEURS has no +Bashkir, Turkmen or Tatar test set, so those three are not in the table +above. Any other `--language` value fails with `run: unsupported language`. + +## Quick start + +```bash +cmake -B build +cmake --build build + +build/bin/transcribe-cli \ + -m models/gigaam-multilingual-v2-e2e-rnnt/gigaam-multilingual-v2-e2e-rnnt-Q8_0.gguf \ + --language ru \ + samples/ru.wav +``` + +Leave out `--language` to let the model choose. + +## Speed + +### Apple M4 Max + + +Compute latency (mel + encode + decode), speedup over realtime in parentheses; profile `asr-publication-v2`: mean over 3 iterations after 1 warmup. + +| Backend | Sample | Q8_0 | Q4_K_M | +| ------- | ------------ | ---------------: | ---------------: | +| Metal | jfk (11.0s) | 64 ms (171.82×) | 65 ms (168.52×) | +| Metal | dots (35.3s) | 220 ms (160.52×) | 226 ms (156.55×) | +| CPU | jfk (11.0s) | 330 ms (33.31×) | 446 ms (24.64×) | +| CPU | dots (35.3s) | 1.26 s (27.93×) | 1.60 s (22.10×) | + +Apple M4 Max: transcribe.cpp `d704775e` on 2026-12-04. + + +### AMD Ryzen 7 PRO 4750U + + +Compute latency (mel + encode + decode), speedup over realtime in parentheses; profile `asr-publication-v2`: mean over 3 iterations after 1 warmup. + +| Backend | Sample | Q8_0 | Q4_K_M | +| ------- | ------------ | --------------: | --------------: | +| Vulkan | jfk (11.0s) | 1.06 s (10.38×) | 1.09 s (10.09×) | +| Vulkan | dots (35.3s) | 3.93 s (9.00×) | 3.94 s (8.96×) | +| CPU | jfk (11.0s) | 1.23 s (8.95×) | 1.09 s (10.05×) | +| CPU | dots (35.3s) | 5.34 s (6.62×) | 4.45 s (7.94×) | + +AMD Ryzen 7 PRO 4750U (Radeon RADV RENOIR): transcribe.cpp `d704775e` on 2026-12-04. + + +### Apple M1 + +No base Apple M4 was available, so these Apple M1 numbers stand in for it. + + +Compute latency (mel + encode + decode), speedup over realtime in parentheses; profile `asr-publication-v2`: mean over 3 iterations after 1 warmup. + +| Backend | Sample | Q8_0 | Q4_K_M | +| ------- | ------------ | --------------: | --------------: | +| Metal | jfk (11.0s) | 287 ms (38.37×) | 312 ms (35.30×) | +| Metal | dots (35.3s) | 1.05 s (33.50×) | 1.12 s (31.49×) | +| CPU | jfk (11.0s) | 1.05 s (10.47×) | 1.21 s (9.09×) | +| CPU | dots (35.3s) | 3.59 s (9.84×) | 4.45 s (7.93×) | + +Apple M1 (stand-in for the base Apple M4): transcribe.cpp `d704775e` on 2026-12-04. + + +To run the benchmark yourself: + +```bash +uv run scripts/bench/run.py --profile --models gigaam-multilingual-v2-e2e-rnnt +``` + +## For developers + +This port is checked against ai-sage's PyTorch model, layer by layer, with +`scripts/validate.py`. The +[family doc](../porting/families/gigaam.md#multilingual-v2-e2e-rnn-t) has +the details. + +| Field | Value | +| --- | --- | +| Reference | `modeling_gigaam.py` from `ai-sage/GigaAM-Multilingual-v2` @ `c21483b`, built in F32 on CPU by `scripts/lib/gigaam_v4_hf.py` | +| Dump script | `scripts/dump_reference_gigaam_v4_hf.py` | +| Manifest | `tests/golden/gigaam/gigaam-multilingual-v2-e2e-rnnt.manifest.json` | +| Tolerances | `tests/tolerances/gigaam-multilingual-v2.json` | + +Convert the original model, quantize it, and validate: + +```bash +uv run --project scripts/envs/gigaam-v4 \ + scripts/convert-gigaam-v4.py ai-sage/GigaAM-Multilingual-v2 + +build/bin/transcribe-quantize \ + models/gigaam-multilingual-v2-e2e-rnnt/gigaam-multilingual-v2-e2e-rnnt-F32.gguf \ + models/gigaam-multilingual-v2-e2e-rnnt/gigaam-multilingual-v2-e2e-rnnt-Q8_0.gguf \ + --quant Q8_0 + +uv run scripts/validate.py all --family gigaam --variant gigaam-multilingual-v2-e2e-rnnt +``` diff --git a/docs/models/gigaam.md b/docs/models/gigaam.md index 574dcea77..21c473b27 100644 --- a/docs/models/gigaam.md +++ b/docs/models/gigaam.md @@ -18,6 +18,12 @@ A sixth, `gigaam-v4-e2e-rnnt`, comes from English, cased and punctuated, with a new encoder (Zapformer). See [GigaAM-v4 E2E RNN-T](#gigaam-v4-e2e-rnnt). +A seventh, `gigaam-multilingual-v2-e2e-rnnt`, comes from +[`ai-sage/GigaAM-Multilingual-v2`](https://huggingface.co/ai-sage/GigaAM-Multilingual-v2): +21 languages, cased and punctuated, on a larger Zapformer encoder with an +optional language hint. See +[GigaAM Multilingual-v2 E2E RNN-T](#gigaam-multilingual-v2-e2e-rnn-t). + For the architecture deep-dive, validation contract, and porting notes, see the family doc at [`docs/porting/families/gigaam.md`](../porting/families/gigaam.md). @@ -40,6 +46,11 @@ see the family doc at GigaAM-v4's Zapformer encoder with the v3 RNN-T head shape; lower WER on FLEURS Russian than `gigaam-v3-e2e-rnnt` (see the [model page](gigaam-v4-e2e-rnnt.md#download)). +- **Cased + punctuated text in 21 languages.** + `gigaam-multilingual-v2-e2e-rnnt` — the best GigaAM model on FLEURS + Russian and English, at about three times the size and compute of + `gigaam-v4-e2e-rnnt` (see the + [model page](gigaam-multilingual-v2-e2e-rnnt.md#download)). - **Russian, English, Kazakh, Kyrgyz, or Uzbek.** `gigaam-multilingual-large-ctc` — lowercase charwise output with no punctuation. No pre-built GGUF; convert it yourself, see @@ -51,23 +62,24 @@ see the family doc at ## All variants WER is on FLEURS Russian (`fleurs-ru`) for the **Q8_0** preset, -measured by transcribe.cpp's WER pipeline. `gigaam-v4-e2e-rnnt` also -transcribes English, so its row is LibriSpeech test-clean, which is -measured at every quant; its FLEURS Russian and English WER is on its -page. See each per-variant doc for the full quant matrix. +measured by transcribe.cpp's WER pipeline. `gigaam-v4-e2e-rnnt` and +`gigaam-multilingual-v2-e2e-rnnt` also transcribe English, so their rows +are LibriSpeech test-clean, which is measured at every quant. Their FLEURS +WER is on their pages. See each per-variant doc for the full quant matrix. - -| Variant | Params | Languages | Q8_0 size | Benchmark | Q8_0 | Capabilities | Doc | + +| Variant | Params | Languages | Q8_0 size | Benchmark | Q8_0 | Capabilities | Doc | | --- | ---: | --- | ---: | --- | ---: | --- | --- | -| `gigaam-v3-e2e-rnnt` | 223M | ru | 274 MB | FLEURS ru (WER) | 5.35% | token timestamps | [gigaam-v3-e2e-rnnt.md](gigaam-v3-e2e-rnnt.md) | -| `gigaam-v3-e2e-ctc` | 221M | ru | 272 MB | FLEURS ru (WER) | 5.53% | token timestamps | [gigaam-v3-e2e-ctc.md](gigaam-v3-e2e-ctc.md) | -| `gigaam-v3-rnnt` | 222M | ru | 273 MB | FLEURS ru (WER) | 8.07% | token timestamps | [gigaam-v3-rnnt.md](gigaam-v3-rnnt.md) | -| `gigaam-v3-ctc` | 221M | ru | 272 MB | FLEURS ru (WER) | 8.42% | token timestamps | [gigaam-v3-ctc.md](gigaam-v3-ctc.md) | -| `gigaam-v4-e2e-rnnt` | 239M | ru, en | 255 MB | LibriSpeech test-clean (WER) | 2.05% | token timestamps | [gigaam-v4-e2e-rnnt.md](gigaam-v4-e2e-rnnt.md) | +| `gigaam-v3-e2e-rnnt` | 223M | ru | 274 MB | FLEURS ru (WER) | 5.35% | token timestamps | [gigaam-v3-e2e-rnnt.md](gigaam-v3-e2e-rnnt.md) | +| `gigaam-v3-e2e-ctc` | 221M | ru | 272 MB | FLEURS ru (WER) | 5.53% | token timestamps | [gigaam-v3-e2e-ctc.md](gigaam-v3-e2e-ctc.md) | +| `gigaam-v3-rnnt` | 222M | ru | 273 MB | FLEURS ru (WER) | 8.07% | token timestamps | [gigaam-v3-rnnt.md](gigaam-v3-rnnt.md) | +| `gigaam-v3-ctc` | 221M | ru | 272 MB | FLEURS ru (WER) | 8.42% | token timestamps | [gigaam-v3-ctc.md](gigaam-v3-ctc.md) | +| `gigaam-v4-e2e-rnnt` | 239M | ru, en | 255 MB | LibriSpeech test-clean (WER) | 2.05% | token timestamps | [gigaam-v4-e2e-rnnt.md](gigaam-v4-e2e-rnnt.md) | +| `gigaam-multilingual-v2-e2e-rnnt` | 776M | 21 languages | 828 MB | LibriSpeech test-clean (WER) | 1.96% | token timestamps | [gigaam-multilingual-v2-e2e-rnnt.md](gigaam-multilingual-v2-e2e-rnnt.md) | -Pre-built GGUFs for every v3 variant, `gigaam-v4-e2e-rnnt`, and every -quant are hosted under +Pre-built GGUFs for every v3 variant, `gigaam-v4-e2e-rnnt`, +`gigaam-multilingual-v2-e2e-rnnt`, and every quant are hosted under [`handy-computer` on Hugging Face](https://huggingface.co/handy-computer); each per-variant doc has direct download links. @@ -128,6 +140,22 @@ Downloads, WER, speed and the reproduction commands are on the [family doc](../porting/families/gigaam.md#gigaam-v4-e2e-rnnt) has the validation results. +## GigaAM Multilingual-v2 E2E RNN-T + +`gigaam-multilingual-v2-e2e-rnnt` is the `e2e` head of +[`ai-sage/GigaAM-Multilingual-v2`](https://huggingface.co/ai-sage/GigaAM-Multilingual-v2). +It transcribes 21 languages into cased, punctuated text, from Russian and +English to Kazakh, Georgian and Tatar. The encoder is a larger version of +v4's Zapformer, conditioned on a language embedding. Pass `--language kk` +to select a language, or leave it out to let the model choose. On FLEURS +both give the same accuracy. The checkpoint's `raw` head and streaming +modes are not converted. + +Downloads, WER, speed and the reproduction commands are on the +[model page](gigaam-multilingual-v2-e2e-rnnt.md). The +[family doc](../porting/families/gigaam.md#multilingual-v2-e2e-rnn-t) has +the validation results. + ## Input limits GigaAM is trained for utterances up to about **25 seconds**. Longer audio is @@ -136,8 +164,8 @@ stitched into one sequence for a single greedy decode. There is no practical length limit, and the encoder workspace does not grow with input length. Audio up to 25 s is encoded in one pass. See the [input-length contract](../input-limits.md). -`gigaam-v4-e2e-rnnt` uses the same windows, each starting on an even -encoder frame so its half-rate stage groups the same frame pairs as one +`gigaam-v4-e2e-rnnt` and `gigaam-multilingual-v2-e2e-rnnt` use the same +windows, each starting on an even encoder frame so its half-rate stage groups the same frame pairs as one pass over the whole clip would. The runtime applies the same 25 s window to `gigaam-multilingual-large-ctc`. @@ -180,3 +208,5 @@ runtime contract. that it transcribes the five languages listed in [its section](#gigaam-multilingual-large-ctc). `gigaam-v4-e2e-rnnt` has them too, and transcribes Russian and English. +`gigaam-multilingual-v2-e2e-rnnt` has them too, and transcribes the 21 +languages listed in [its section](#gigaam-multilingual-v2-e2e-rnn-t). diff --git a/docs/porting/families/gigaam.md b/docs/porting/families/gigaam.md index f8d192514..a2e0792eb 100644 --- a/docs/porting/families/gigaam.md +++ b/docs/porting/families/gigaam.md @@ -17,6 +17,14 @@ every published quant, and it ships as `handy-computer/gigaam-v4-e2e-rnnt-gguf` ([model page](../../models/gigaam-v4-e2e-rnnt.md)). See [GigaAM-v4 E2E RNN-T](#gigaam-v4-e2e-rnnt). +`gigaam-multilingual-v2-e2e-rnnt` (ai-sage/GigaAM-Multilingual-v2) adds +language conditioning (FiLM and late fusion) and the SwishR/SwishL +activations to the Zapformer runtime. It converts and validates at F32, WER +and speed are measured for every published quant, and it ships as +`handy-computer/gigaam-multilingual-v2-e2e-rnnt-gguf` +([model page](../../models/gigaam-multilingual-v2-e2e-rnnt.md)). See +[Multilingual-v2 E2E RNN-T](#multilingual-v2-e2e-rnn-t). + ## Identity - Family key: `gigaam` @@ -24,6 +32,7 @@ every published quant, and it ships as `handy-computer/gigaam-v4-e2e-rnnt-gguf` - Hugging Face repo: `ai-sage/GigaAM-v3` (five sibling branches upstream; four ported) - Also converted, not yet published: `gigaam-multilingual-large-ctc` from `ai-sage/GigaAM-Multilingual`, see [GigaAM Multilingual Large CTC](#gigaam-multilingual-large-ctc) - Also ported and published: `gigaam-v4-e2e-rnnt` from `ai-sage/GigaAM-v4`, see [GigaAM-v4 E2E RNN-T](#gigaam-v4-e2e-rnnt) +- Also ported and published: `gigaam-multilingual-v2-e2e-rnnt` from `ai-sage/GigaAM-Multilingual-v2`, see [Multilingual-v2 E2E RNN-T](#multilingual-v2-e2e-rnn-t) - License: MIT - v3 variants in scope (one HF branch each): @@ -475,3 +484,184 @@ is 6 words over the reference (+0.01pp): 24 of the 25 utterances that differ are longer than 25 s, where C++ decodes in windows and the reference decodes the whole clip. `gigaam-v3-e2e-rnnt` Q8_0 is 5.35% on FLEURS ru. + +## Multilingual-v2 E2E RNN-T + +`gigaam-multilingual-v2-e2e-rnnt` is the `e2e` head of +[`ai-sage/GigaAM-Multilingual-v2`](https://huggingface.co/ai-sage/GigaAM-Multilingual-v2) +at `c21483b5`, the head of the `rnnt` branch. `main` holds the same files. +It transcribes 21 languages into cased, punctuated text: ru, en, kk, ky, +uz, be, fr, es, ba, ka, hy, ro, tk, az, tg, de, it, nl, pl, pt and tt. +Offline only. The C++ port started from +[ai-babai's prototype](https://github.com/ai-babai/transcribe.cpp/commit/1219a29f22884c530162125e4183fabdaa37c205) +and [kalpakprod's converter patch](https://github.com/handy-computer/transcribe.cpp/issues/279#issuecomment-7236155807) +(#311). + +It is the v4 Zapformer graph with three additions: + +- Activations. The checkpoint sets no activation key, so + `ZapformerEncoder` uses its default: SwishR (`swish` in the GGUF), and + SwishL in the frontend ConvNeXt. v4 sets SiLU. +- Language conditioning. A 32-row embedding table, 128 wide, holds the + default slot in row 0 and one row per language from row 1, in + `stt.gigaam.language.codes` order. FiLM projections scale and shift the + residual stream after global layers 3, 7, 11, 15, 19 and 23 + (`stt.gigaam.language.film_layers`). A 2048-wide ReLU MLP then fuses the + final frames with the language embedding. The converter splits that + MLP's first projection, so the language term is added once per + utterance instead of being concatenated to every frame. +- Decoding emits at most 3 tokens per encoder frame. The limit is + `stt.gigaam.rnnt.max_symbols`, from the checkpoint's + `max_symbols_per_step`. v4 GGUFs without the key keep 10. + +The encoder has three stages of 7, 12 and 6 layers at 1024, 1280 and 1024 +dims, the middle one at half the frame rate. With the head it has 776M +parameters. The RNN-T vocabulary is 4026 SentencePiece pieces plus blank. +The checkpoint's `raw` head and its streaming modes are not converted. + +| Item | Path | +|---|---| +| Intake | `reports/porting/gigaam/gigaam-multilingual-v2-e2e-rnnt/intake.json` | +| Porting log | `reports/porting/gigaam/gigaam-multilingual-v2-e2e-rnnt/_porting-log.md` | +| Golden manifest | `tests/golden/gigaam/gigaam-multilingual-v2-e2e-rnnt.manifest.json` | +| Tolerances | `tests/tolerances/gigaam-multilingual-v2.json` | +| Pin and reference loader | `scripts/lib/gigaam_v4_hf.py` (`MULTILINGUAL_REPO`, `MULTILINGUAL_REVISION`) | +| Converter | `scripts/convert-gigaam-v4.py` | +| Reference dumper | `scripts/dump_reference_gigaam_v4_hf.py --variant multilingual_v2_e2e_rnnt` | +| WER reference runner | `scripts/wer/run_reference_gigaam_v4_hf.py --variant multilingual_v2_e2e_rnnt` | +| Python env | `scripts/envs/gigaam-v4/` | +| C++ | `src/arch/gigaam/encoder.cpp` (`zap_activation`, FiLM and fusion in `build_zapformer_encoder_graph`), `weights.cpp` (`read_language_conditioning`), `model.cpp` (language slot) | +| Smoke tests | `tests/gigaam_multilingual_v2_smoke.cpp` (real model, `TRANSCRIBE_GIGAAM_MULTILINGUAL_V2_GGUF`), `tests/gigaam_smoke.cpp` (fixture loader, default build), `tests/quantize_policy_unit.cpp` (quant policy) | + +### Commands + +Conversion (writes +`models/gigaam-multilingual-v2-e2e-rnnt/gigaam-multilingual-v2-e2e-rnnt-F32.gguf`, +3104463040 bytes, 625 tensors): + +```bash +uv run --project scripts/envs/gigaam-v4 scripts/convert-gigaam-v4.py ai-sage/GigaAM-Multilingual-v2 +uv run scripts/quantize-all.py models/gigaam-multilingual-v2-e2e-rnnt/gigaam-multilingual-v2-e2e-rnnt-F32.gguf +``` + +Validation: + +```bash +variant=gigaam-multilingual-v2-e2e-rnnt +uv run scripts/validate.py all --family gigaam --variant "$variant" +cmake -B build -DTRANSCRIBE_BUILD_REAL_MODEL_TESTS=ON +cmake --build build --target transcribe_gigaam_smoke transcribe_gigaam_multilingual_v2_smoke transcribe_quantize_policy_unit +TRANSCRIBE_GIGAAM_MULTILINGUAL_V2_GGUF="$PWD/models/$variant/$variant-F32.gguf" \ + ctest --test-dir build -R '^transcribe_(gigaam_smoke|gigaam_multilingual_v2_smoke|quantize_policy_unit)$' \ + --no-tests=error --output-on-failure +uv run scripts/test_gigaam_v4.py +``` + +WER reference. The runner decodes each clip whole, in F32 on CPU. +`--language` picks the slot the same way the C++ hint does. + +```bash +uv run --project scripts/envs/gigaam-v4 scripts/wer/run_reference_gigaam_v4_hf.py \ + --variant multilingual_v2_e2e_rnnt --language kk \ + --manifest samples/wer/fleurs-kk.manifest.jsonl \ + --out reports/wer/gigaam-multilingual-v2-e2e-rnnt-REF.fleurs-kk.jsonl +``` + +### Reference + +The reference is `GigaAMDualASR` from the checkpoint's own +`modeling_gigaam.py`, built in F32 on CPU by `scripts/lib/gigaam_v4_hf.py` +from the pinned snapshot, in the v4 env. The dumper and the WER runner call +the module's public forward, `model(wav, length, language=...)`, so FiLM +and late fusion run exactly as upstream. The golden manifest has two cases. +`ru` uses the Russian slot and `fleurs-en` the default slot, and between +them they cover an odd and an even encoder length. + +Notes: + +- An explicit language uses its row index + 1. No hint and `auto` both + use row 0. An unknown code fails with + `TRANSCRIBE_ERR_UNSUPPORTED_LANGUAGE`, as the reference raises. There is + no language identification output. +- The language embedding is a `get_rows` lookup that the loader reads as + F32, so the quantizer keeps `lang.embed.weight` at F32 in every preset + (16 KB). Before that rule, every quantized GGUF failed to load. + `tests/quantize_policy_unit.cpp` pins it. The FiLM and fusion + projections quantize like any other linear. Their 128-wide rows fall + back to Q8_0 in the K presets. +- The converter refuses a language-conditioning config it does not + implement: another FiLM placement, another fusion, a default tag, or an + unknown-language policy other than raise. It also refuses a v4 + checkpoint that carries conditioning. The loader refuses duplicate + codes, `auto` as a code, FiLM layers out of range, and an embedding + table without its metadata. + +### Capability Validation + +| Capability | Mode | Command / test | Expected observable | Status | +|------------|------|----------------|---------------------|--------| +| Transcribe, explicit language | `--language ` | `validate.py all` (`ru` case), `transcribe_gigaam_multilingual_v2_smoke`, WER below | transcript equal to the reference's | PASS. Exact on `ru` against the reference. FLEURS ru, en and kk at F32 are within the reference + 0.01pp gate. On ten samples (ru, en, de, es, fr, up to 35 s), F32 and F16 transcripts are identical on CPU and Metal (M1). On four of them F32 is identical on CPU and Vulkan (Ryzen 4750U). Q8_0 on Metal and Vulkan matches F32. Q8_0 on CPU changes the case of one word on `fleurs-en`, and Q6_K and smaller change a word or a comma on a few clips. | +| Transcribe, default slot | no hint, or `auto` | `validate.py all` (`fleurs-en` case), smoke test (`auto` equals no hint) | transcript equal to the reference's | PASS. FLEURS Q8_0 with no hint is within 0.2pp of the hinted run on all 18 languages (table below). | +| Unsupported language | `--language zz` | smoke test, `gigaam_smoke` fixture | `TRANSCRIBE_ERR_UNSUPPORTED_LANGUAGE` | PASS | +| Long-form (> 25 s, windowed) | any | `samples/dots.wav` (35 s), `ru-long.wav`, LibriSpeech | every window uses the language slot, transcript as reference | PASS. LibriSpeech F32 is 1.95% against the reference's 1.94% on whole clips. | +| Batch | `transcribe_run_batch` | `transcribe_gigaam_multilingual_v2_smoke` | each batch result equal to its single run | ACCEPTED GAP, serial as for v4. Zapformer batches run the per-utterance loop. | +| Raw head, streaming, translate, language detection | n/a | n/a | n/a | SKIP (not converted or not exposed). | +| Word timestamps | n/a | n/a | n/a | ACCEPTED GAP, as for v3 and v4: token timestamps only. | + +Numerical validation at F32 on CPU, one thread, is within the tolerances on +both cases, with exact transcripts. The bounds cover Windows x64 and macOS +arm64. arm64 drifts more, up to 2.5e-5 at `enc.out` (v4: 1.1e-5). The six +extra layers and the fusion MLP after the output RmsNorm account for the +difference. + +### WER + +The reference row is the PyTorch module (F32, CPU, whole-clip greedy +decode) with the same language hint as the C++ rows. LibriSpeech uses +`en`. C++ rows are CUDA (L40S, Modal), batch 8, at `d704775e`. + +| Run | FLEURS ru (775) | FLEURS en (647) | FLEURS kk (856) | LibriSpeech test-clean (2620) | +|---|---:|---:|---:|---:| +| PyTorch reference | 4.02% | 4.50% | 4.84% | 1.94% | +| F32 | 4.02% | 4.49% | 4.81% | 1.95% | +| F16 | 4.03% | 4.48% | 4.80% | 1.94% | +| Q8_0 | 4.03% | 4.52% | 4.79% | 1.96% | +| Q6_K | 4.01% | 4.48% | 4.82% | 1.99% | +| Q5_K_M | 4.02% | 4.48% | 4.80% | 1.97% | +| Q4_K_M | 4.01% | 4.51% | 4.79% | 1.97% | + +F32 is within the `reference + 0.01pp` gate everywhere. Every quant is +within 0.05pp of F32. Unlike v4, Q4_K_M needs no tensors kept at a higher +tier. For comparison, `gigaam-v4-e2e-rnnt` Q8_0 is 4.36% on FLEURS ru and +4.92% on FLEURS en. + +FLEURS Q8_0 with the language hint (the published rows) and without it: + +| Lang | Hint | No hint | Lang | Hint | No hint | +|---|---:|---:|---|---:|---:| +| ru | 4.03% | 3.89% | ka | 6.51% | 6.44% | +| en | 4.52% | 4.57% | hy | 4.50% | 4.51% | +| kk | 4.79% | 4.68% | ro | 4.22% | 4.26% | +| ky | 5.90% | 5.72% | az | 6.67% | 6.69% | +| uz | 28.90% | 28.64% | tg | 8.00% | 7.99% | +| be | 4.43% | 4.41% | de | 3.87% | 3.88% | +| fr | 4.36% | 4.36% | it | 2.04% | 2.03% | +| es | 2.93% | 2.96% | nl | 4.58% | 4.57% | +| pl | 4.64% | 4.61% | pt | 4.44% | 4.51% | + +The Uzbek number is a scoring artifact. FLEURS Uzbek writes oʻ and gʻ +with U+02BB, and the model writes an ASCII apostrophe. The scorer's +normalizer removes the apostrophe but keeps U+02BB, so nearly every word +with those letters counts as an error. With the two treated as the same, +Q8_0 is 6.5%. ba, tk and tt are not in FLEURS. + +### Speed + +The host RNN-T decoder scores a 4027-class joint, four times v4's. Without +BLAS, the default off Apple, its dot products were scalar loops, and +decode took as long as encode on the Ryzen 4750U (3.0 s for `dots`, CPU +Q8_0). `decoder.cpp` now keeps eight partial sums per dot product and +scores each joint row against four frames per load. Decode now takes +0.72 s. v4 and the v3 RNN-T variants decode 1.7-3x faster too, with +identical transcripts and token counts. The published speed rows are at +`d704775e`. diff --git a/reports/porting/gigaam/gigaam-multilingual-v2-e2e-rnnt/_porting-log.md b/reports/porting/gigaam/gigaam-multilingual-v2-e2e-rnnt/_porting-log.md new file mode 100644 index 000000000..93bb18835 --- /dev/null +++ b/reports/porting/gigaam/gigaam-multilingual-v2-e2e-rnnt/_porting-log.md @@ -0,0 +1,20 @@ +# GigaAM Multilingual-v2 E2E RNN-T + +The C++ implementation adapts [ai-babai's prototype](https://github.com/ai-babai/transcribe.cpp/commit/1219a29f22884c530162125e4183fabdaa37c205) to the Zapformer implementation merged in [#285](https://github.com/handy-computer/transcribe.cpp/pull/285). The converter follows [kalpakprod's GGUF extension](https://github.com/handy-computer/transcribe.cpp/issues/279#issuecomment-7236155807), including the split late-fusion projection. + +The accuracy check uses F32 on CPU. The checkpoint is `ai-sage/GigaAM-Multilingual-v2@c21483b5e185ff32f6fb2e2c801f92f4e7fbfee8`. The two golden cases exercise the default and explicit language slots and both even and odd encoder lengths. The per-tensor bounds come from comparing those cases to the author's PyTorch model. + +Three additional Kazakh clips from the FLEURS test split (`google/fleurs@70bb2e84b976b7e960aa89f1c648e09c59f894dd`) were run on Windows CPU. The C++ and PyTorch transcripts matched exactly with and without the Kazakh hint on recordings `10021401141536914918.wav`, `1003383318376154990.wav` and `10037546300559313240.wav`. These six comparisons cover short-clip behavior. + +The fixture test loads a small conditioned checkpoint and rejects duplicate language codes. The real-model test alternates between unsupported, explicit, omitted and `auto` language hints on the same session and compares serial and batched decoding. + +Surprises from bringing it to the v4 bar: + +- **Every quantized GGUF failed to load.** `lang.embed.weight` is a `get_rows` table that the loader reads as F32. The quantizer's policy had no rule for it, so it landed in the Linear bucket (F16, Q8_0). The F32 file hid the problem. The quantizer now keeps it F32, and `tests/quantize_policy_unit.cpp` pins every F32-only lookup table for every preset. +- **The emission limit was inferred from the language list.** The runtime used 3 tokens per frame when the GGUF had language codes and 10 otherwise. The converter now writes the checkpoint's `max_symbols_per_step` as `stt.gigaam.rnnt.max_symbols` (3 here, 10 for v4). GGUFs without it keep 10. +- **`auto` was rejected.** Handy and other callers pass `auto` for "no hint". It is now an alias for the default slot, as in sensevoice. +- **Tolerances from one platform were too tight on another.** Windows x64 set them at 1.5x its own drift. macOS arm64 drifts up to 2.1x more at `enc.out` (2.5e-5). They now cover both. +- **The no-BLAS host decoder was as slow as the encoder.** The 4027-class joint is four times v4's, and the scalar dot products did not vectorize. Decode took 3.0 s for 35 s of audio on the Ryzen 4750U. Eight partial sums and four frames per joint row bring it to 0.72 s with identical transcripts. v3 and v4 decode faster too. +- **The hint barely matters on FLEURS.** Q8_0 without a hint is within 0.2pp of the hinted run on all 18 FLEURS languages, and better on ru, kk and ky. The upstream card reports its own numbers in `auto` mode. +- **Uzbek scores 28.9% for a scoring reason.** FLEURS writes oʻ and gʻ with U+02BB, and the model writes an apostrophe. The normalizer removes the apostrophe and keeps U+02BB. With the two treated as the same, Q8_0 is 6.5%. +- **`main` and `rnnt` are different commits with the same files**, as for v4. The pin is the head of the `rnnt` branch (c21483b5). diff --git a/reports/porting/gigaam/gigaam-multilingual-v2-e2e-rnnt/intake.json b/reports/porting/gigaam/gigaam-multilingual-v2-e2e-rnnt/intake.json new file mode 100644 index 000000000..7bbe496dc --- /dev/null +++ b/reports/porting/gigaam/gigaam-multilingual-v2-e2e-rnnt/intake.json @@ -0,0 +1,192 @@ +{ + "schema_version": "transcribe-intake-v1", + "family": "gigaam", + "hf_repo": "ai-sage/GigaAM-Multilingual-v2", + "hf_revision": "c21483b5e185ff32f6fb2e2c801f92f4e7fbfee8", + "sources": { + "config": { + "kind": "hf_file", + "path": "config.json", + "status": "found" + }, + "model_weights": { + "kind": "hf_file", + "path": "model.safetensors", + "status": "found" + }, + "reference_modeling_code": { + "kind": "hf_file", + "path": "modeling_gigaam.py", + "status": "found" + }, + "tokenizer_model": { + "kind": "hf_file", + "path": "e2e_tokenizer.model", + "status": "found" + }, + "model_card": { + "kind": "hf_file", + "path": "README.md", + "status": "found", + "detail": "The upstream model card lists 21 languages and identifies the license as MIT." + } + }, + "variants": [ + { + "name": "gigaam-multilingual-v2-e2e-rnnt", + "memory_gb": 1.57, + "files": [ + "config.json", + "modeling_gigaam.py", + "model.safetensors", + "e2e_tokenizer.model", + "raw_tokenizer.model" + ] + } + ], + "config": { + "architecture_candidates": [ + "encoder-transducer" + ], + "key_fields": { + "model_type": "gigaam", + "encoder.type": "ZapformerEncoder", + "encoder.encoder_dim": "1024,1280,1024", + "encoder.num_encoder_layers": "7,12,6", + "encoder.downsampling_factor": "1,2,1", + "encoder.activation": "swish", + "language_embedding_dim": 128, + "head.type": "RNNTHead", + "head.num_classes": 4027 + }, + "varying_across_variants": [ + "RNN-T head and SentencePiece vocabulary" + ] + }, + "dtype": { + "expected": "float32", + "source": "manual", + "evidence": "The safetensors header records the source dtypes. Both the CPU reference and the accuracy GGUF use F32 compute.", + "details": { + "config_declared": "float32", + "header_distribution": { + "F32": 29, + "F16": 620 + } + }, + "expected_f32_tensors": [] + }, + "frontend": { + "sample_rate": 16000, + "n_mels": 64, + "hop_length": 160, + "fft_size": 320, + "window": "hann_periodic", + "normalization": "none", + "preemphasis": null, + "dither": null, + "center": false, + "padding_mode": null, + "mel_filterbank_norm": "htk" + }, + "tokenizer": { + "type": "sentencepiece", + "vocab_size": 4026, + "special_tokens": { + "blank": 4026 + }, + "has_language_tokens": false, + "vocab_sha256": "3b049685e51a893350452f31613b47f4bd7640857f53facdf32266de82df3c0a" + }, + "capabilities": { + "languages": [ + "ru", + "en", + "kk", + "ky", + "uz", + "be", + "fr", + "es", + "ba", + "ka", + "hy", + "ro", + "tk", + "az", + "tg", + "de", + "it", + "nl", + "pl", + "pt", + "tt" + ], + "language_detection": false, + "translation": false, + "timestamps": [], + "streaming": false, + "speaker_diarization": false + }, + "upstream_benchmarks": [ + { + "dataset": "GigaAM Multilingual evaluation set (not named on the card)", + "language": "ru", + "metric": "wer", + "score": 2.3, + "score_unit": "percent", + "source": "https://huggingface.co/ai-sage/GigaAM-Multilingual-v2", + "notes": "Full-context column, 'auto' language mode. The card names neither the datasets nor the normalisation, so these are context, not a gate. The port is gated against its own PyTorch reference on FLEURS." + }, + { + "dataset": "GigaAM Multilingual evaluation set (not named on the card)", + "language": "en", + "metric": "wer", + "score": 5.42, + "score_unit": "percent", + "source": "https://huggingface.co/ai-sage/GigaAM-Multilingual-v2", + "notes": "Full-context column, 'auto' language mode. The card names neither the datasets nor the normalisation, so these are context, not a gate. The port is gated against its own PyTorch reference on FLEURS." + }, + { + "dataset": "GigaAM Multilingual evaluation set (not named on the card)", + "language": "kk", + "metric": "wer", + "score": 3.95, + "score_unit": "percent", + "source": "https://huggingface.co/ai-sage/GigaAM-Multilingual-v2", + "notes": "Full-context column, 'auto' language mode. The card names neither the datasets nor the normalisation, so these are context, not a gate. The port is gated against its own PyTorch reference on FLEURS." + }, + { + "dataset": "GigaAM Multilingual evaluation set (not named on the card)", + "language": "hy", + "metric": "wer", + "score": 3.06, + "score_unit": "percent", + "source": "https://huggingface.co/ai-sage/GigaAM-Multilingual-v2", + "notes": "Full-context column, 'auto' language mode. The card names neither the datasets nor the normalisation, so these are context, not a gate. The port is gated against its own PyTorch reference on FLEURS." + }, + { + "dataset": "GigaAM Multilingual evaluation set (not named on the card)", + "language": "de", + "metric": "wer", + "score": 3.16, + "score_unit": "percent", + "source": "https://huggingface.co/ai-sage/GigaAM-Multilingual-v2", + "notes": "Full-context column, 'auto' language mode. The card names neither the datasets nor the normalisation, so these are context, not a gate. The port is gated against its own PyTorch reference on FLEURS." + } + ], + "reference_framework": "author_repo_gigaam", + "reference_rationale": "Use GigaAMDualASR from modeling_gigaam.py shipped with the pinned checkpoint. Its public forward applies the selected slot, FiLM and residual late fusion.", + "architecture_pattern": "encoder-transducer", + "known_risks": [ + "Slot zero is the no-hint embedding. Explicit languages use their index plus one.", + "The checkpoint sets no encoder activation key. Its reference default is SwishR, with SwishL in ConvNeXt.", + "Only offline E2E RNN-T decoding is in scope. The head emits up to three symbols per encoder frame." + ], + "intake_gaps": [ + { + "field": "frontend", + "reason": "The checkpoint specifies the frontend inside cfg.preprocessor in config.json. Preflight A looks for a separate processor file. Gate B checks the exported frontend metadata against the declaration." + } + ] +} diff --git a/scripts/convert-gigaam-v4.py b/scripts/convert-gigaam-v4.py index 60e96886f..8456bb4a6 100644 --- a/scripts/convert-gigaam-v4.py +++ b/scripts/convert-gigaam-v4.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""convert-gigaam-v4.py - convert an ai-sage/GigaAM-v4 checkpoint directory +"""Convert a pinned GigaAM-v4 or GigaAM-Multilingual-v2 checkpoint directory (model.safetensors + config.json + {e2e,raw}_tokenizer.model) into a GGUF for transcribe.cpp's Zapformer GigaAM backend. @@ -30,7 +30,7 @@ gguf_writer, safe_id, ) -from lib.gigaam_v4_hf import HEADS, REPO_ID, REVISION, snapshot_dir # noqa: E402 +from lib.gigaam_v4_hf import HEADS, MULTILINGUAL_REPO, REPO_ID, SOURCE_PINS, snapshot_dir # noqa: E402 def parse_int_list(value) -> list[int]: @@ -103,11 +103,11 @@ def extract_sp_tokenizer(sp_path: Path, blank_piece: str = "") -> dict: } -def check_supported_config(cfg: dict) -> None: +def check_supported_config(cfg: dict, repo_id: str = REPO_ID) -> None: """Refuse a config the offline Zapformer graph does not implement. - The graph is full-context SiLU Zapformer with the causal frontend, no - language conditioning, d_model equal to the first stage dim, each stage + Both variants use a full-context Zapformer with the causal frontend, + d_model equal to the first stage dim, each stage at downsampling 1 or the largest factor, and one query head dim. Each value is the effective one: the config's, or ZapformerEncoder's default when the config leaves it out. Raises ValueError naming the key. @@ -123,8 +123,10 @@ def eff(key): def refuse(key, value, why): raise ValueError(f"cfg.encoder.{key} is {value!r}; {why}") - if str(eff("activation")).lower() != "silu": - refuse("activation", eff("activation"), "only SiLU is implemented (the reference default is swish)") + multilingual = repo_id == MULTILINGUAL_REPO + activation = "swish" if multilingual else "silu" + if str(eff("activation")).lower() != activation: + refuse("activation", eff("activation"), f"{repo_id} requires {activation}") if eff("causal_frontend") is not True: refuse("causal_frontend", eff("causal_frontend"), "only the causal frontend is validated (the reference default is false)") @@ -151,9 +153,21 @@ def refuse(key, value, why): if len(set(qdims)) != 1: refuse("query_head_dim", eff("query_head_dim"), "the graph uses one RoPE table, so every stage needs " "the same query head dim") - if cfg.get("language_conditioning"): - raise ValueError("cfg.language_conditioning is set; language-conditioned Zapformer (FiLM, late fusion) " - "is not implemented") + if multilingual: + lang = cfg.get("language_conditioning") or {} + codes = lang.get("languages", []) + film = lang.get("film", {}) + fusion = lang.get("late_fusion", {}) + if (not codes or not all(isinstance(x, str) and x and x != "auto" for x in codes) + or len(codes) != len(set(codes)) or lang.get("num_slots", 0) < len(codes) + 1 + or lang.get("embedding_dim", 0) <= 0 or lang.get("default_tag") is not None + or lang.get("unknown_policy") != "raise" + or not film.get("enabled") or film.get("placement") != "every_n" + or film.get("every_n", 0) <= 0 or film.get("layers") is not None + or not fusion.get("enabled") or fusion.get("fusion") != "mlp" or fusion.get("activation") != "relu"): + raise ValueError("unsupported cfg.language_conditioning for Multilingual-v2") + elif cfg.get("language_conditioning"): + raise ValueError("cfg.language_conditioning is unexpected for GigaAM-v4") def convert(model_dir: Path, out_path: Path, head: str, repo_id: str) -> None: @@ -167,7 +181,10 @@ def convert(model_dir: Path, out_path: Path, head: str, repo_id: str) -> None: head_cfg = cfg["heads"][head] dec_cfg = cfg["decodings"][head] - check_supported_config(cfg) + check_supported_config(cfg, repo_id) + lang_cfg = cfg.get("language_conditioning") + if lang_cfg and head != "e2e": + raise ValueError("only the Multilingual-v2 e2e head is supported") tok_path = model_dir / dec_cfg["model_path"] tok = extract_sp_tokenizer(tok_path) @@ -239,15 +256,16 @@ def get_f32(key: str) -> np.ndarray: fb = np.ascontiguousarray(get_f32("model.preprocessor.featurizer.0.mel_scale.fb").T) window = get_f32("model.preprocessor.featurizer.0.spectrogram.window") - variant = f"gigaam-v4-{head}-rnnt" - display_name = f"GigaAM v4 {'E2E' if head == 'e2e' else 'Raw'}-RNN-T" + slug = repo_id.split("/")[-1].lower() + variant = f"{slug}-{head}-rnnt" + display_name = f"{repo_id.split('/')[-1].replace('-', ' ')} {'E2E' if head == 'e2e' else 'Raw'}-RNN-T" # Compute parameter count for size_label (encoder + selected head) total_params = sum( int(np.prod(sd[k].shape)) for k in sd_keys if (k.startswith("model.encoder.") and "rope_bank" not in k) - or k.startswith(f"model.heads.{head}.") + or k.startswith(f"model.heads.{head}.") or k.startswith("model.language_") ) size_label = f"{total_params / 1_000_000:.0f}M" print(f"Converting {variant} ({total_params:,} params -> {size_label}) -> {out_path}") @@ -258,11 +276,11 @@ def get_f32(key: str) -> np.ndarray: add_general_identity( writer, name=display_name, - basename="gigaam-v4", + basename=slug, size_label=size_label, - version="v4", + version=slug.rsplit("-", 1)[-1], file_type=LlamaFileType.ALL_F32, - languages=["ru", "en"], + languages=list(lang_cfg["languages"]) if lang_cfg else ["ru", "en"], author="Salute Developers", organization="ai-sage", license="mit", @@ -292,6 +310,8 @@ def get_f32(key: str) -> np.ndarray: # Zapformer encoder metadata writer.add_string("stt.gigaam.encoder.type", "zapformer") + if lang_cfg: + writer.add_string("stt.gigaam.encoder.activation", "swish") writer.add_uint32("stt.gigaam.encoder.n_layers", sum(stage_layers)) writer.add_uint32("stt.gigaam.encoder.d_model", d_model) writer.add_uint32("stt.gigaam.encoder.feat_in", feat_in) @@ -323,6 +343,9 @@ def get_f32(key: str) -> np.ndarray: writer.add_uint32("stt.gigaam.joint.hidden", joint_hidden) writer.add_uint32("stt.gigaam.joint.num_classes", joint_n_classes) writer.add_string("stt.gigaam.joint.activation", "relu") + # Greedy emissions per encoder frame: 10 for GigaAM-v4, 3 for + # Multilingual-v2. GGUFs without the KV load with 10. + writer.add_int32("stt.gigaam.rnnt.max_symbols", int(dec_cfg["max_symbols_per_step"])) # Frontend metadata (same contract as GigaAM v3) writer.add_string("stt.frontend.type", "mel") @@ -443,6 +466,28 @@ def add(src_name: str, dst_name: str) -> None: # Every checkpoint tensor is either written above or known to be unused: # the RoPE tables (rebuilt at load, see fill_zapformer_rope_tables) and # the head not selected. Anything else is a module the graph would drop. + if lang_cfg: + writer.add_array("stt.gigaam.language.codes", list(lang_cfg["languages"])) + writer.add_uint32("stt.gigaam.language.embedding_dim", int(lang_cfg["embedding_dim"])) + film_layers = sorted(int(k.split(".")[-2]) for k in sd_keys if k.startswith("model.encoder.language_film.projections.") and k.endswith(".weight")) + every = lang_cfg["film"]["every_n"] + if film_layers != list(range(every - 1, sum(stage_layers), every)): + raise ValueError(f"FiLM projection layers {film_layers} disagree with the configured interval {every}") + writer.add_array("stt.gigaam.language.film_layers", film_layers) + add("model.language_embedding.weight", "lang.embed.weight") + for i in film_layers: + add(f"model.encoder.language_film.projections.{i}.weight", f"lang.film.{i}.weight") + add(f"model.encoder.language_film.projections.{i}.bias", f"lang.film.{i}.bias") + # Split the first fusion projection so the graph adds the selected + # language contribution once for all frames of an utterance. + w0 = get_f32("model.language_fusion.kernel.0.weight") + e = int(lang_cfg["embedding_dim"]) + add_arr("lang.fusion.0.weight", w0[:, :-e]) + add_arr("lang.fusion.0.emb.weight", w0[:, -e:]) + add("model.language_fusion.kernel.0.bias", "lang.fusion.0.bias") + add("model.language_fusion.kernel.3.weight", "lang.fusion.1.weight") + add("model.language_fusion.kernel.3.bias", "lang.fusion.1.bias") + left = sorted( k for k in sd_keys - consumed if "rope_bank" not in k and not (k.startswith("model.heads.") and not k.startswith(f"model.heads.{head}.")) @@ -462,33 +507,34 @@ def add(src_name: str, dst_name: str) -> None: def main(argv: list[str]) -> int: - p = argparse.ArgumentParser(description="Convert ai-sage/GigaAM-v4 to GGUF.") + p = argparse.ArgumentParser(description="Convert GigaAM-v4 or GigaAM-Multilingual-v2 to GGUF.") p.add_argument( "model", - help=f"{REPO_ID}, fetched at the commit pinned in scripts/lib/gigaam_v4_hf.py " - f"({REVISION[:12]}), or a local directory with model.safetensors, " - "config.json and *_tokenizer.model from that commit", + help="Pinned HF repo ID or a local checkpoint directory", ) p.add_argument("out_path", type=Path, nargs="?", - help="Output .gguf path (default: models/gigaam-v4--rnnt/gigaam-v4--rnnt-F32.gguf)") + help="Output .gguf path (default: models//-F32.gguf)") p.add_argument("--head", choices=HEADS, default="e2e", help="RNN-T head to export (default: e2e)") args = p.parse_args(argv[1:]) local = Path(args.model).expanduser() if local.is_dir(): model_dir = local.resolve() - print(f"Converting local directory {model_dir}; make sure it holds {REPO_ID}@{REVISION}") - elif args.model == REPO_ID: - model_dir = snapshot_dir() + cfg = json.loads((model_dir / "config.json").read_text(encoding="utf-8"))["cfg"] + repo_id = MULTILINGUAL_REPO if cfg.get("language_conditioning") else REPO_ID + print(f"Converting local directory {model_dir}; expected {repo_id}@{SOURCE_PINS[repo_id]}") + elif args.model in SOURCE_PINS: + repo_id = args.model + model_dir = snapshot_dir(repo_id=repo_id) else: - print(f"error: expected {REPO_ID} or a local directory, got {args.model!r}", file=sys.stderr) + print(f"error: expected {REPO_ID}, {MULTILINGUAL_REPO} or a local directory, got {args.model!r}", file=sys.stderr) return 2 out_path = args.out_path if out_path is None: - slug = f"gigaam-v4-{args.head}-rnnt" + slug = f"{repo_id.split('/')[-1].lower()}-{args.head}-rnnt" out_path = Path(__file__).resolve().parent.parent / "models" / slug / f"{slug}-F32.gguf" - convert(model_dir, out_path, args.head, REPO_ID) + convert(model_dir, out_path, args.head, repo_id) return 0 diff --git a/scripts/dump_reference_gigaam_v4_hf.py b/scripts/dump_reference_gigaam_v4_hf.py index 94021a49c..f8962e321 100644 --- a/scripts/dump_reference_gigaam_v4_hf.py +++ b/scripts/dump_reference_gigaam_v4_hf.py @@ -39,11 +39,11 @@ _THIS_DIR = Path(__file__).resolve().parent sys.path.insert(0, str(_THIS_DIR)) -from lib.gigaam_v4_hf import REPO_ID, REVISION, check_revision, load_model, snapshot_dir # noqa: E402 +from lib.gigaam_v4_hf import MULTILINGUAL_REPO, REPO_ID, SOURCE_PINS, check_revision, load_model, snapshot_dir # noqa: E402 from lib.ref_dump import write_tensor, write_transcript # noqa: E402 # variant key -> RNN-T head of the dual checkpoint. -VARIANT_HEADS = {"v4_e2e_rnnt": "e2e"} +VARIANT_HEADS = {"v4_e2e_rnnt": "e2e", "multilingual_v2_e2e_rnnt": "e2e"} def configure_torch(threads: int) -> None: @@ -80,14 +80,16 @@ def __call__(self, module, inputs, output) -> None: def cmd_decode(args: argparse.Namespace) -> int: + repo_id = MULTILINGUAL_REPO if args.variant == "multilingual_v2_e2e_rnnt" else REPO_ID + revision = SOURCE_PINS[repo_id] try: - check_revision(args.revision) + check_revision(args.revision, repo_id) except ValueError as e: raise SystemExit(f"error: {e}") from None - if args.model not in (None, REPO_ID): + if args.model not in (None, repo_id): raise SystemExit( - f"error: {args.variant} loads from the Hugging Face repo {REPO_ID} at " - f"{REVISION}, got --model {args.model!r}" + f"error: {args.variant} loads from the Hugging Face repo {repo_id} at " + f"{revision}, got --model {args.model!r}" ) head_name = VARIANT_HEADS[args.variant] @@ -95,7 +97,7 @@ def cmd_decode(args: argparse.Namespace) -> int: import torch configure_torch(args.torch_threads) - model, _ = load_model(snapshot_dir(), args.device) + model, _ = load_model(snapshot_dir(repo_id=repo_id), args.device) audio_path = Path(args.audio).expanduser().resolve() out_dir = Path(args.out).expanduser().resolve() @@ -113,10 +115,11 @@ def cmd_decode(args: argparse.Namespace) -> int: length = torch.full([1], wav.shape[-1], dtype=torch.long, device=device) source: dict[str, Any] = { - "kind": "gigaam-v4-hf", + "kind": "gigaam-zapformer-hf", + "language": args.language, "framework": "author_repo_gigaam", - "hf_repo": REPO_ID, - "hf_revision": REVISION, + "hf_repo": repo_id, + "hf_revision": revision, "variant": args.variant, "head": head_name, "device": args.device, @@ -146,10 +149,13 @@ def dump(name: str, t, stage: str) -> None: stack.register_forward_hook(h) stage_hooks.append(h) - # GigaAM.forward without language conditioning (the checkpoint has none) - # and without autocast (CPU, F32): preprocessor + offline encoder. + # Run the author's public forward path so FiLM and late fusion are both + # included when the checkpoint has a language embedding. with torch.inference_mode(): - encoded, encoded_len = encoder(feats, feat_lengths) + if repo_id == MULTILINGUAL_REPO: + encoded, encoded_len = model(wav, length, language=args.language) + else: + encoded, encoded_len = encoder(feats, feat_lengths) print(f"encoder: encoded.shape={tuple(encoded.shape)} encoded_len={encoded_len.tolist()}") dump("enc.subsample.out", frontend_hook.value, "encoder.subsample") @@ -157,6 +163,10 @@ def dump(name: str, t, stage: str) -> None: dump(f"enc.stage.{s}.out", h.value, f"encoder.stage.{s}") dump("enc.out", encoded, "encoder.out") dump("rnnt.encoded", encoded.transpose(1, 2).contiguous(), "decoder.rnnt.encoded") + if repo_id == MULTILINGUAL_REPO: + # The C++ dumper also records both boundaries from the consumer side. + dump("enc.mel.in", feats, "encoder.mel") + dump("dec.enc_out", encoded.transpose(1, 2).contiguous(), "decoder.enc_out") head = model.heads[head_name] decoding = model.decodings[head_name] @@ -180,7 +190,7 @@ def dump(name: str, t, stage: str) -> None: def add_common_args(p: argparse.ArgumentParser) -> None: p.add_argument("--variant", required=True, choices=sorted(VARIANT_HEADS), - help="GigaAM-v4 variant key") + help="Zapformer variant key") p.add_argument("--audio", required=True, help="16 kHz mono WAV path") p.add_argument("--out", required=True, help="Output directory for dumps") p.add_argument("--device", default="cpu", help="torch device (default: cpu)") @@ -189,9 +199,9 @@ def add_common_args(p: argparse.ArgumentParser) -> None: # Standard dumper CLI shape (validate.py passes --model, --language and, # for gigaam, --revision). p.add_argument("--model", default=None, - help=f"HF repo id; only {REPO_ID} is accepted (default: it)") + help="Pinned HF repo ID for the selected variant") p.add_argument("--language", default=None, - help="Language hint (no-op; the v4 RNN-T heads take no language input)") + help="Multilingual-v2 language code (omit for the default embedding)") p.add_argument("--revision", default=None, help="Commit the caller expects, e.g. the golden manifest's " "hf_revision; refused when it differs from the pin.") diff --git a/scripts/hf_cards/gigaam-multilingual-v2-e2e-rnnt.yaml b/scripts/hf_cards/gigaam-multilingual-v2-e2e-rnnt.yaml new file mode 100644 index 000000000..e4625d52c --- /dev/null +++ b/scripts/hf_cards/gigaam-multilingual-v2-e2e-rnnt.yaml @@ -0,0 +1,33 @@ +# Spec for the HF README of handy-computer/gigaam-multilingual-v2-e2e-rnnt-gguf. +# Prose only; numbers and metadata come from catalog/.json. See README.md. + +pin_date: 2026-11-27 + +# Validation pin for the most recent upload. Updated on each release; +# older HF revisions carry whatever value was current at their upload time. +validation: + reference: upstream `modeling_gigaam.py` + commit: d704775e + date: 2026-12-04 + +pipeline_tag: automatic-speech-recognition +tags: + - gguf + - transcribe.cpp + - asr + - speech-to-text + - gigaam + - zapformer + - rnnt + - multilingual + +summary: | + Offline multilingual speech-to-text covering 21 languages, with punctuation and capitalization: Russian, English, German, French, Spanish, Italian, Portuguese, Dutch, Polish, Romanian, Belarusian, Kazakh, Kyrgyz, Uzbek, Tajik, Turkmen, Azerbaijani, Georgian, Armenian, Bashkir and Tatar. A Zapformer encoder conditioned on a language embedding, with an RNN-T decoder. The source language is selected per call (--language kk, hy, ...) or left to the model (auto). Recordings of any length are encoded in overlapping 25 s windows. Not a streaming model and does not translate. + +wer: + notes: | + Greedy RNN-T decoding, no external LM. PyTorch reference baseline on the same + manifest: 1.94%. ai-sage does not publish a LibriSpeech or FLEURS number. FLEURS + Uzbek reads high because its references spell oʻ and gʻ with U+02BB, which the + normalizer keeps, while the model writes an apostrophe, which it drops. Counting + the two as equal, Uzbek Q8_0 is 6.5%. diff --git a/scripts/lib/gigaam_v4_hf.py b/scripts/lib/gigaam_v4_hf.py index bc387e4c4..9279c118f 100644 --- a/scripts/lib/gigaam_v4_hf.py +++ b/scripts/lib/gigaam_v4_hf.py @@ -25,6 +25,10 @@ # main, "Add GigaAM-v4: ru-en, streaming, onnx" (2026-11-27). REVISION = "180301a192bb45bc2b2ca122e0d4aab24ffe7a96" +MULTILINGUAL_REPO = "ai-sage/GigaAM-Multilingual-v2" +MULTILINGUAL_REVISION = "c21483b5e185ff32f6fb2e2c801f92f4e7fbfee8" +SOURCE_PINS = {REPO_ID: REVISION, MULTILINGUAL_REPO: MULTILINGUAL_REVISION} + # Files the converter and the reference read; the snapshot download is # limited to them so the VAD weights (vad.safetensors) are not fetched. SNAPSHOT_FILES = [ @@ -40,26 +44,27 @@ HEADS = ("e2e", "raw") -def check_revision(revision: str | None) -> None: +def check_revision(revision: str | None, repo_id: str = REPO_ID) -> None: """Raise ValueError when `revision` (e.g. a golden manifest's `source_model.hf_revision`) differs from the pin.""" - if revision is not None and revision != REVISION: + pin = SOURCE_PINS[repo_id] + if revision is not None and revision != pin: raise ValueError( f"revision {revision} differs from the commit pinned in " - f"scripts/lib/gigaam_v4_hf.py, {REVISION}. Change the pin and the " + f"scripts/lib/gigaam_v4_hf.py, {pin}. Change the pin and the " f"golden manifest together." ) -def snapshot_dir(revision: str | None = None) -> Path: +def snapshot_dir(revision: str | None = None, repo_id: str = REPO_ID) -> Path: """Download (or reuse) the pinned snapshot and return its directory. Goes through hf_source.download_snapshot, so the snapshot lands where the other pinned sources do and an offline miss names the directory.""" - check_revision(revision) + check_revision(revision, repo_id) from lib.hf_source import download_snapshot - return download_snapshot(REPO_ID, REVISION, allow_patterns=SNAPSHOT_FILES) + return download_snapshot(repo_id, SOURCE_PINS[repo_id], allow_patterns=SNAPSHOT_FILES) def import_modeling(path: Path): diff --git a/scripts/lib/test_quant_policy_sync.py b/scripts/lib/test_quant_policy_sync.py index 5a446d0de..6e3fbc2c1 100644 --- a/scripts/lib/test_quant_policy_sync.py +++ b/scripts/lib/test_quant_policy_sync.py @@ -191,6 +191,7 @@ "frontend.cmvn.shift", # Norm (sensevoice CMVN) "frontend.cmvn.scale", # Norm (sensevoice CMVN) "enc.embed.weight", # Norm (sensevoice prefix-token table) + "lang.embed.weight", # Norm (gigaam multilingual language-slot table) "enc.after_norm.weight", # Norm (sensevoice trailing LN) "tp_encoders.tp_norm.weight", # Norm (sensevoice tp LN) "enc.embedder.comp.log_k", # Norm (moonshine-streaming asinh scalar) diff --git a/scripts/test_gigaam_v4.py b/scripts/test_gigaam_v4.py index a7e8671a5..4dec3a522 100644 --- a/scripts/test_gigaam_v4.py +++ b/scripts/test_gigaam_v4.py @@ -88,6 +88,14 @@ def test_the_v4_manifest_names_the_pinned_repo_and_commit(self): ) self.assertIn(m["reference"]["variant_key"], dumper_v4.VARIANT_HEADS) + def test_multilingual_manifest_and_dumper_use_the_same_pin(self): + m = json.loads((_GOLDEN / "gigaam-multilingual-v2-e2e-rnnt.manifest.json").read_text(encoding="utf-8")) + source = m["source_model"] + self.assertEqual(source["hf_repo"], gigaam_v4_hf.MULTILINGUAL_REPO) + self.assertEqual(source["hf_revision"], gigaam_v4_hf.SOURCE_PINS[source["hf_repo"]]) + self.assertEqual(m["reference"]["revision"], source["hf_revision"]) + self.assertIn(m["reference"]["variant_key"], dumper_v4.VARIANT_HEADS) + def test_the_pinned_revision_and_none_are_accepted(self): gigaam_v4_hf.check_revision(gigaam_v4_hf.REVISION) gigaam_v4_hf.check_revision(None) @@ -199,6 +207,14 @@ def test_language_conditioning_is_refused(self): with self.assertRaisesRegex(ValueError, "language_conditioning"): self.check(language_conditioning={"languages": ["ru", "en"], "embedding_dim": 128}) + def test_multilingual_requires_conditioning_and_default_swish(self): + cfg = copy.deepcopy(_V4_CFG) + with self.assertRaisesRegex(ValueError, "activation"): + convert_v4.check_supported_config(cfg, gigaam_v4_hf.MULTILINGUAL_REPO) + del cfg["encoder"]["activation"] + with self.assertRaisesRegex(ValueError, "language_conditioning"): + convert_v4.check_supported_config(cfg, gigaam_v4_hf.MULTILINGUAL_REPO) + def test_a_key_zapformer_encoder_does_not_take_is_refused(self): with self.assertRaisesRegex(ValueError, "does not take: lang_film"): self.check({"lang_film": True}) diff --git a/scripts/validate.py b/scripts/validate.py index fec001be3..3098b8c25 100644 --- a/scripts/validate.py +++ b/scripts/validate.py @@ -274,6 +274,8 @@ def find_cli(repo: Path) -> Path: for candidate in [ repo / "build" / "bin" / "transcribe-cli", repo / "build" / "transcribe-cli", + repo / "build" / "bin" / "Release" / "transcribe-cli.exe", + repo / "build" / "bin" / "transcribe-cli.exe", ]: if candidate.exists(): return candidate @@ -593,6 +595,7 @@ def cmd_cpp(args: argparse.Namespace) -> int: stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, + encoding="utf-8", errors="replace", ) if result.stdout: diff --git a/scripts/wer/run_reference_gigaam_v4_hf.py b/scripts/wer/run_reference_gigaam_v4_hf.py index 172766c70..eff2cdd9c 100644 --- a/scripts/wer/run_reference_gigaam_v4_hf.py +++ b/scripts/wer/run_reference_gigaam_v4_hf.py @@ -1,6 +1,6 @@ #!/usr/bin/env python3 """ -run_reference_gigaam_v4_hf.py — GigaAM-v4 PyTorch batch transcribe. +run_reference_gigaam_v4_hf.py — GigaAM-v4 / Multilingual-v2 PyTorch batch transcribe. Builds GigaAMDualASR once through scripts/lib/gigaam_v4_hf.py, the loader the reference dumper uses, and runs the same offline forward and greedy @@ -11,6 +11,10 @@ The model runs in F32 on CPU, as in the reference dumps. Each clip is decoded whole (no VAD segmentation; FLEURS clips are under 30 s). +Multilingual-v2 runs the module's public forward, which applies the selected +language slot (FiLM and late fusion). `--language` picks the slot the way the +C++ port's language hint does; omit it for the default slot. + Usage (from repo root): uv run --project scripts/envs/gigaam-v4 \\ @@ -18,6 +22,12 @@ --variant v4_e2e_rnnt \\ --manifest samples/wer/fleurs-ru.manifest.jsonl \\ --out reports/wer/gigaam-v4-e2e-rnnt-REF.fleurs-ru.jsonl + + uv run --project scripts/envs/gigaam-v4 \\ + scripts/wer/run_reference_gigaam_v4_hf.py \\ + --variant multilingual_v2_e2e_rnnt --language kk \\ + --manifest samples/wer/fleurs-kk.manifest.jsonl \\ + --out reports/wer/gigaam-multilingual-v2-e2e-rnnt-REF.fleurs-kk.jsonl """ from __future__ import annotations @@ -29,10 +39,13 @@ from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) # repo scripts/ -from lib.gigaam_v4_hf import REPO_ID, REVISION, load_model, snapshot_dir # noqa: E402 +from lib.gigaam_v4_hf import MULTILINGUAL_REPO, REPO_ID, SOURCE_PINS, load_model, snapshot_dir # noqa: E402 -# variant key -> RNN-T head of the dual checkpoint (same as the dumper). -VARIANT_HEADS = {"v4_e2e_rnnt": "e2e"} +# variant key -> (HF repo, RNN-T head of the dual checkpoint), as in the dumper. +VARIANTS = { + "v4_e2e_rnnt": (REPO_ID, "e2e"), + "multilingual_v2_e2e_rnnt": (MULTILINGUAL_REPO, "e2e"), +} def main() -> int: @@ -44,8 +57,10 @@ def main() -> int: help="Input manifest JSONL (id/audio/ref_text).") p.add_argument("--out", type=Path, required=True, help="Output JSONL path (run.py-compatible).") - p.add_argument("--variant", required=True, choices=sorted(VARIANT_HEADS), - help="GigaAM-v4 variant key.") + p.add_argument("--variant", required=True, choices=sorted(VARIANTS), + help="Zapformer variant key.") + p.add_argument("--language", default=None, + help="Multilingual-v2 language code (omit for the default slot).") p.add_argument("--torch-threads", type=int, default=1, help="torch intra-op threads for deterministic runs.") p.add_argument("--limit", type=int, default=0, @@ -63,9 +78,12 @@ def main() -> int: if args.torch_threads > 0: torch.set_num_threads(args.torch_threads) - head_name = VARIANT_HEADS[args.variant] + repo_id, head_name = VARIANTS[args.variant] + multilingual = repo_id == MULTILINGUAL_REPO + if args.language is not None and not multilingual: + p.error(f"--language applies only to {MULTILINGUAL_REPO}") t0 = time.monotonic() - model, _ = load_model(snapshot_dir()) + model, _ = load_model(snapshot_dir(repo_id=repo_id)) head = model.heads[head_name] decoding = model.decodings[head_name] load_ms = (time.monotonic() - t0) * 1000 @@ -87,9 +105,10 @@ def main() -> int: "type": "batch_header", "load_ms": round(load_ms, 1), "framework": "hf_modeling_gigaam", - "model": f"{REPO_ID}:{args.variant}", - "model_revision": REVISION, + "model": f"{repo_id}:{args.variant}", + "model_revision": SOURCE_PINS[repo_id], "head": head_name, + "language": args.language, "torch_threads": args.torch_threads, }) + "\n") fout.flush() @@ -108,8 +127,11 @@ def main() -> int: wav = torch.from_numpy(pcm).unsqueeze(0) length = torch.full([1], wav.shape[-1], dtype=torch.long) with torch.inference_mode(): - feats, feat_lengths = model.preprocessor(wav, length) - encoded, encoded_len = model.encoder(feats, feat_lengths) + if multilingual: + encoded, encoded_len = model(wav, length, language=args.language) + else: + feats, feat_lengths = model.preprocessor(wav, length) + encoded, encoded_len = model.encoder(feats, feat_lengths) hyp_text = decoding.decode(head, encoded, encoded_len)[0][0] except Exception as e: err = f"{type(e).__name__}: {e}" diff --git a/src/arch/gigaam/decoder.cpp b/src/arch/gigaam/decoder.cpp index c5425b07b..0aa81bb98 100644 --- a/src/arch/gigaam/decoder.cpp +++ b/src/arch/gigaam/decoder.cpp @@ -71,6 +71,60 @@ inline float sigmoidf(float x) { return 1.0f / (1.0f + std::exp(-x)); } +#if !TRANSCRIBE_HAS_BLAS +// Dot product for the no-BLAS build. Eight independent partial sums let the +// compiler vectorize without reassociating floats (a single running sum is a +// serial dependency it may not reorder). With GigaAM Multilingual-v2's +// 4027-class joint, the single-sum loop made decode as slow as encode on x86. +inline float dot_f32(const float * a, const float * b, int n) { + float acc[8] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; + int j = 0; + for (; j + 8 <= n; j += 8) { + for (int k = 0; k < 8; ++k) { + acc[k] += a[j + k] * b[j + k]; + } + } + float sum = ((acc[0] + acc[4]) + (acc[1] + acc[5])) + ((acc[2] + acc[6]) + (acc[3] + acc[7])); + for (; j < n; ++j) { + sum += a[j] * b[j]; + } + return sum; +} + +// out[f] = dot(w, x + f * n) for four frames at once, so each load of w +// feeds four products. Same per-frame summation order as dot_f32. +inline void dot4_f32(const float * w, const float * x, int n, float * out) { + const float * x0 = x; + const float * x1 = x + n; + const float * x2 = x + 2 * static_cast(n); + const float * x3 = x + 3 * static_cast(n); + float a0[8] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; + float a1[8] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; + float a2[8] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; + float a3[8] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; + int j = 0; + for (; j + 8 <= n; j += 8) { + for (int k = 0; k < 8; ++k) { + const float wk = w[j + k]; + a0[k] += wk * x0[j + k]; + a1[k] += wk * x1[j + k]; + a2[k] += wk * x2[j + k]; + a3[k] += wk * x3[j + k]; + } + } + float * acc[4] = { a0, a1, a2, a3 }; + const float * xs[4] = { x0, x1, x2, x3 }; + for (int f = 0; f < 4; ++f) { + const float * a = acc[f]; + float sum = ((a[0] + a[4]) + (a[1] + a[5])) + ((a[2] + a[6]) + (a[3] + a[7])); + for (int r = j; r < n; ++r) { + sum += w[r] * xs[f][r]; + } + out[f] = sum; + } +} +#endif + // y = W @ x + b, where W is [out, in] row-major (numpy shape), x is // [in], b is [out]. b may be nullptr to skip the add. void matvec_add(const float * W, const float * b, const float * x, int out, int in_dim, float * y) { @@ -83,12 +137,8 @@ void matvec_add(const float * W, const float * b, const float * x, int out, int cblas_sgemv(CblasRowMajor, CblasNoTrans, out, in_dim, 1.0f, W, in_dim, x, 1, 1.0f, y, 1); #else for (int i = 0; i < out; ++i) { - float acc = (b != nullptr) ? b[i] : 0.0f; const float * row = W + static_cast(i) * in_dim; - for (int j = 0; j < in_dim; ++j) { - acc += row[j] * x[j]; - } - y[i] = acc; + y[i] = ((b != nullptr) ? b[i] : 0.0f) + dot_f32(row, x, in_dim); } #endif } @@ -151,13 +201,9 @@ static void lstm_step(const float * x, cblas_sgemv(CblasRowMajor, CblasNoTrans, 4 * H, H, 1.0f, Wh, H, h_prev, 1, 1.0f, scratch_gates, 1); #else for (int i = 0; i < 4 * H; ++i) { - float acc = b[i]; const float * wx_row = Wx + static_cast(i) * H; const float * wh_row = Wh + static_cast(i) * H; - for (int j = 0; j < H; ++j) { - acc += wx_row[j] * x[j] + wh_row[j] * h_prev[j]; - } - scratch_gates[i] = acc; + scratch_gates[i] = b[i] + dot_f32(wx_row, x, H) + dot_f32(wh_row, h_prev, H); } #endif @@ -251,9 +297,23 @@ static void joint_argmax_span(const HostDecoderWeights & h, cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans, n_frames, n_classes, joint_h, 1.0f, join.data(), joint_h, h.joint_out_w.data(), joint_h, 0.0f, logits.data(), n_classes); #else - for (int t = 0; t < n_frames; ++t) { - matvec_add(h.joint_out_w.data(), nullptr, join.data() + static_cast(t) * joint_h, n_classes, joint_h, - logits.data() + static_cast(t) * n_classes); + // Class-major: each output row is read once per span and dotted with + // every frame's joint vector while it is in cache, instead of streaming + // the whole [n_classes, joint_h] matrix once per frame. + for (int i = 0; i < n_classes; ++i) { + const float * w = h.joint_out_w.data() + static_cast(i) * joint_h; + int t = 0; + for (; t + 4 <= n_frames; t += 4) { + float out[4]; + dot4_f32(w, join.data() + static_cast(t) * joint_h, joint_h, out); + for (int f = 0; f < 4; ++f) { + logits[static_cast(t + f) * n_classes + i] = out[f]; + } + } + for (; t < n_frames; ++t) { + logits[static_cast(t) * n_classes + i] = + dot_f32(w, join.data() + static_cast(t) * joint_h, joint_h); + } } #endif diff --git a/src/arch/gigaam/encoder.cpp b/src/arch/gigaam/encoder.cpp index 5ec701c71..ccc2d0279 100644 --- a/src/arch/gigaam/encoder.cpp +++ b/src/arch/gigaam/encoder.cpp @@ -286,6 +286,31 @@ ggml_tensor * zap_rms_norm(ggml_context * ctx, ggml_tensor * x, ggml_tensor * w) return ggml_mul(ctx, ggml_rms_norm(ctx, x, kZapRmsNormEps), w); } +// Multilingual-v2 uses SwishR except in ConvNeXt, which uses SwishL. +ggml_tensor * zap_activation(ggml_context * ctx, ggml_tensor * x, bool swish, bool left = false) { + if (!swish) { + return ggml_silu(ctx, x); + } + const float scale = left ? 0.639521598815918f : 0.683202862739563f; + const float shift = left ? -2.087040662765503f : -0.31602001190185547f; + const float slope = left ? -0.021007252857089043f : -0.012898006476461887f; + const float offset = left ? 0.2303316444158554f : 0.133248575988922f; + ggml_tensor * y = ggml_silu(ctx, ggml_scale_bias(ctx, x, scale, shift)); + y = ggml_add(ctx, y, ggml_scale(ctx, x, slope)); + return ggml_scale_bias(ctx, y, 1.0f, offset); +} + +ggml_tensor * zap_feed_forward(ggml_context * ctx, + ggml_tensor * x, + ggml_tensor * in_w, + ggml_tensor * in_b, + ggml_tensor * out_w, + ggml_tensor * out_b, + bool swish) { + ggml_tensor * y = ggml_add(ctx, ggml_mul_mat(ctx, in_w, x), in_b); + return ggml_add(ctx, ggml_mul_mat(ctx, out_w, zap_activation(ctx, y, swish)), out_b); +} + ggml_tensor * zap_causal_time_pad(ggml_context * ctx, ggml_tensor * x, int64_t pad_top) { ggml_tensor * z = ggml_fill(ctx, ggml_new_tensor_4d(ctx, GGML_TYPE_F32, x->ne[0], pad_top, x->ne[2], x->ne[3]), 0.0f); @@ -310,7 +335,8 @@ ggml_tensor * build_zapformer_frontend(ggml_context * ctx, const ZapformerFrontendWeights & fe, ggml_tensor * mel_in, bool causal, - bool direct_conv) { + bool direct_conv, + bool swish) { const int64_t T_mel = mel_in->ne[0]; const int64_t F = mel_in->ne[1]; const int64_t B = mel_in->ne[2]; @@ -329,17 +355,17 @@ ggml_tensor * build_zapformer_frontend(ggml_context * ctx, } else { x = conf::conv_2d_f32(ctx, fe.conv0_w, x, 1, 1, 1, 1, 1, 1); } - x = ggml_silu(ctx, conf::add_conv_bias(ctx, x, fe.conv0_b)); + x = zap_activation(ctx, conf::add_conv_bias(ctx, x, fe.conv0_b), swish); // Conv2: stride=2, pad=(pH=1, pW=0) -> p0=0 (W/freq), p1=1 (H/time). x = zap_conv_2d(ctx, fe.conv1_w, x, /*s0=*/2, /*s1=*/2, /*p0=*/0, /*p1=*/1, direct_conv); - x = ggml_silu(ctx, conf::add_conv_bias(ctx, x, fe.conv1_b)); + x = zap_activation(ctx, conf::add_conv_bias(ctx, x, fe.conv1_b), swish); // Conv3: stride=2, pad=(pH=1, pW=0). x = zap_conv_2d(ctx, fe.conv2_w, x, /*s0=*/2, /*s1=*/2, /*p0=*/0, /*p1=*/1, direct_conv); - x = ggml_silu(ctx, conf::add_conv_bias(ctx, x, fe.conv2_b)); + x = zap_activation(ctx, conf::add_conv_bias(ctx, x, fe.conv2_b), swish); - // ZapformerConvNeXt: residual + pw2(silu(pw1(dw(x)))). + // ZapformerConvNeXt: residual + pw2(activation(pw1(dw(x)))). { ggml_tensor * res = x; ggml_tensor * y = x; @@ -351,13 +377,13 @@ ggml_tensor * build_zapformer_frontend(ggml_context * ctx, } y = conf::add_conv_bias(ctx, y, fe.cn_dw_b); y = zap_conv_2d(ctx, fe.cn_pw1_w, y, 1, 1, 0, 0, direct_conv); - y = ggml_silu(ctx, conf::add_conv_bias(ctx, y, fe.cn_pw1_b)); + y = zap_activation(ctx, conf::add_conv_bias(ctx, y, fe.cn_pw1_b), swish, /*left=*/true); y = zap_conv_2d(ctx, fe.cn_pw2_w, y, 1, 1, 0, 0, direct_conv); y = conf::add_conv_bias(ctx, y, fe.cn_pw2_b); x = ggml_add(ctx, res, y); } - // Flatten [W=15, H=T_enc, C=64, B] -> [W=15, C=64, T_enc, B] -> [C*W=960, T_enc, B]. + // Flatten [W, T_enc, C, B] -> [W, C, T_enc, B] -> [C*W, T_enc, B]. x = ggml_cont(ctx, ggml_permute(ctx, x, 0, 2, 1, 3)); x = ggml_reshape_3d(ctx, x, x->ne[0] * x->ne[1], x->ne[2], x->ne[3]); @@ -378,8 +404,8 @@ ggml_tensor * build_zapformer_attn(ggml_context * ctx, const int H = shp.n_heads; const int qdim = shp.qdim; const int vdim = shp.vdim; - const int dq = H * qdim; - const int dv = H * vdim; + const int64_t dq = H * qdim; + const int64_t dv = H * vdim; const int64_t T_s = x_qk->ne[1]; const int64_t B = x_qk->ne[2]; const float scale = 1.0f / std::sqrt(static_cast(qdim)); @@ -449,7 +475,8 @@ ggml_tensor * build_zapformer_conv(ggml_context * ctx, const ZapformerLayerWeights & lw, int kernel, ggml_tensor * valid_mask, - int64_t T_valid) { + int64_t T_valid, + bool swish) { const int64_t D = x->ne[0]; const int64_t T_s = x->ne[1]; const int64_t B = x->ne[2]; @@ -489,10 +516,10 @@ ggml_tensor * build_zapformer_conv(ggml_context * ctx, ggml_tensor * y = ggml_reshape_3d(ctx, ggml_permute(ctx, yw, 1, 2, 0, 3), D, T_s, B); y = ggml_add(ctx, y, lw.conv_dw_b); - // ActivationAndLinear: linear(silu((y + mean) * sigmoid(gate))). + // ActivationAndLinear: linear(activation((y + mean) * sigmoid(gate))). y = ggml_add(ctx, y, mean); y = ggml_mul(ctx, y, ggml_sigmoid(ctx, gate)); - y = ggml_silu(ctx, y); + y = zap_activation(ctx, y, swish); y = ggml_add(ctx, ggml_mul_mat(ctx, lw.conv_out_w, y), lw.conv_out_b); return y; } @@ -506,15 +533,16 @@ ggml_tensor * build_zapformer_layer(ggml_context * ctx, ggml_tensor * valid_mask, ggml_tensor * attn_mask, ggml_tensor * attn_mask_f16, - int64_t T_valid) { + int64_t T_valid, + bool swish) { ggml_tensor * residual = x; ggml_tensor * qk = x; - x = ggml_add(ctx, x, conf::feed_forward(ctx, x, lw.ff1_in_w, lw.ff1_in_b, lw.ff1_out_w, lw.ff1_out_b)); + x = ggml_add(ctx, x, zap_feed_forward(ctx, x, lw.ff1_in_w, lw.ff1_in_b, lw.ff1_out_w, lw.ff1_out_b, swish)); x = ggml_add(ctx, x, build_zapformer_attn(ctx, qk, x, rope, lw, shp, use_flash, attn_mask, attn_mask_f16)); if (shp.conv_kernel > 0) { - x = ggml_add(ctx, x, build_zapformer_conv(ctx, x, lw, shp.conv_kernel, valid_mask, T_valid)); - x = ggml_add(ctx, x, conf::feed_forward(ctx, x, lw.ff2_in_w, lw.ff2_in_b, lw.ff2_out_w, lw.ff2_out_b)); + x = ggml_add(ctx, x, build_zapformer_conv(ctx, x, lw, shp.conv_kernel, valid_mask, T_valid, swish)); + x = ggml_add(ctx, x, zap_feed_forward(ctx, x, lw.ff2_in_w, lw.ff2_in_b, lw.ff2_out_w, lw.ff2_out_b, swish)); } ggml_tensor * blended = ggml_add(ctx, residual, ggml_scale(ctx, ggml_sub(ctx, x, residual), 0.25f)); @@ -535,7 +563,7 @@ EncoderBuild build_zapformer_encoder_graph(ggml_context * ctx, ggml_set_input(eb.mel_in); ggml_tensor * x = build_zapformer_frontend(ctx, w.zapformer.frontend, eb.mel_in, hp.zap_causal_frontend, - conf::detect_direct_pw(backend_name)); + conf::detect_direct_pw(backend_name), hp.zap_swish); ggml_set_name(x, "enc.subsample.out"); eb.dumps.pre_encode_out = x; transcribe::debug::mark_tensor_for_dump(x); @@ -568,6 +596,15 @@ EncoderBuild build_zapformer_encoder_graph(ggml_context * ctx, ggml_set_name(eb.zap_rope_in, "zap.rope"); ggml_set_input(eb.zap_rope_in); + const auto & zap = w.zapformer; + ggml_tensor * language = nullptr; + if (zap.language_embed != nullptr) { + eb.zap_language_in = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, 1); + ggml_set_name(eb.zap_language_in, "zap.language_slot"); + ggml_set_input(eb.zap_language_in); + language = ggml_get_rows(ctx, zap.language_embed, eb.zap_language_in); + } + const bool use_flash = (backend_name != nullptr && std::string(backend_name).find("CPU") == std::string::npos); // Flash attention takes the odd-length key mask as F16 [T_pad, T_pad]; @@ -603,8 +640,17 @@ EncoderBuild build_zapformer_encoder_graph(ggml_context * ctx, x = ggml_scale(ctx, x, shp.input_scale); for (int l = 0; l < shp.n_layers; ++l) { - x = build_zapformer_layer(ctx, x, rope_s, sw.layers[l], shp, use_flash, valid_s, attn_mask_s, attn_f16_s, - T_valid_s); + const auto & lw = sw.layers[l]; + x = build_zapformer_layer(ctx, x, rope_s, lw, shp, use_flash, valid_s, attn_mask_s, attn_f16_s, T_valid_s, + hp.zap_swish); + if (lw.film_w != nullptr) { + // Apply FiLM to both the next layer input and the stage bypass. + ggml_tensor * film = ggml_add(ctx, ggml_mul_mat(ctx, lw.film_w, language), lw.film_b); + ggml_tensor * gamma = ggml_view_1d(ctx, film, shp.dim, 0); + ggml_tensor * beta = ggml_view_1d(ctx, film, shp.dim, shp.dim * film->nb[0]); + gamma = ggml_scale_bias(ctx, gamma, 1.0f, 1.0f); + x = ggml_add(ctx, ggml_mul(ctx, x, gamma), beta); + } bypass = ggml_add(ctx, bypass, ggml_scale(ctx, x, shp.residual_scales[l + 1])); } @@ -629,6 +675,13 @@ EncoderBuild build_zapformer_encoder_graph(ggml_context * ctx, x = ggml_rms_norm(ctx, x, hp.zap_out_norm_eps * hp.zap_out_norm_eps); x = ggml_scale(ctx, x, hp.zap_out_norm_scale); + if (language != nullptr) { + ggml_tensor * bias = ggml_add(ctx, ggml_mul_mat(ctx, zap.fusion_lang_w, language), zap.fusion_in_b); + ggml_tensor * y = ggml_add(ctx, ggml_mul_mat(ctx, zap.fusion_in_w, x), bias); + y = ggml_add(ctx, ggml_mul_mat(ctx, zap.fusion_out_w, ggml_relu(ctx, y)), zap.fusion_out_b); + x = ggml_add(ctx, x, y); + } + ggml_set_name(x, "rnnt.encoded"); ggml_set_output(x); eb.dumps.rnnt_encoded = x; diff --git a/src/arch/gigaam/encoder.h b/src/arch/gigaam/encoder.h index eca25067f..c0f268f49 100644 --- a/src/arch/gigaam/encoder.h +++ b/src/arch/gigaam/encoder.h @@ -73,6 +73,7 @@ struct EncoderBuild { // divisible by max downsampling factor). ggml_tensor * zap_valid_mask_in = nullptr; // [1, T_pad, 1] f32: 1 real / 0 pad ggml_tensor * zap_attn_mask_in = nullptr; // [T_pad, 1, 1, 1] f32: 0 real / -INF pad + ggml_tensor * zap_language_in = nullptr; // [1] i32: row in the language embedding table int zap_T_orig = 0; // Zapformer RoPE as one block-diagonal rotation per position, ne=[qdim, // qdim, T_pad] f32 (a ggml_mul_mat src0); filled host-side by diff --git a/src/arch/gigaam/model.cpp b/src/arch/gigaam/model.cpp index 5188a41c2..d680a2a06 100644 --- a/src/arch/gigaam/model.cpp +++ b/src/arch/gigaam/model.cpp @@ -120,6 +120,13 @@ transcribe_status load(Loader & loader, const transcribe_model_load_params * par if (auto st = read_gigaam_hparams(loader.gguf(), m->hparams); st != TRANSCRIBE_OK) { return st; } + if (!m->hparams.language_codes.empty()) { + m->set_languages(m->hparams.language_codes); + // "auto" selects the default embedding slot, the same one a null hint + // does. The model conditions on it; it does not identify a language. + m->set_language_aliases({ "auto" }); + m->caps.supports_language_detect = false; + } // Long audio is windowed internally (plan_windows): no practical limit. m->caps.max_audio_ms = 0; @@ -360,6 +367,7 @@ transcribe_status encode_mel_slice(GigaamSession * gc, GigaamModel * gm, const float * mel, int n_frames, + int32_t language_slot, bool dumps, std::vector & out, int & T_enc, @@ -378,6 +386,9 @@ transcribe_status encode_mel_slice(GigaamSession * gc, } ggml_backend_tensor_set(eb.mel_in, mel, 0, static_cast(n_frames) * gm->hparams.fe_num_mels * sizeof(float)); + if (eb.zap_language_in != nullptr) { + ggml_backend_tensor_set(eb.zap_language_in, &language_slot, 0, sizeof(language_slot)); + } if (dumps) { transcribe::debug::dump_tensor("enc.mel.in", eb.mel_in, "encoder.mel"); } @@ -507,8 +518,8 @@ transcribe_status decode_and_populate(GigaamSession * gc, std::vector frames; if (gm->hparams.head_kind == HeadKind::RNNT) { - if (auto st = decode_rnnt_greedy(gm->host_decoder, gm->hparams, encoded, T_enc, - /*max_symbols=*/10, tokens, frames); + if (auto st = decode_rnnt_greedy(gm->host_decoder, gm->hparams, encoded, T_enc, gm->hparams.rnnt_max_symbols, + tokens, frames); st != TRANSCRIBE_OK) { return st; } @@ -550,7 +561,10 @@ transcribe_status decode_and_populate(GigaamSession * gc, } // namespace -transcribe_status run(transcribe_session * session, const float * pcm, int n_samples, const transcribe_run_params *) { +transcribe_status run(transcribe_session * session, + const float * pcm, + int n_samples, + const transcribe_run_params * params) { if (session == nullptr || pcm == nullptr || n_samples <= 0) { return TRANSCRIBE_ERR_INVALID_ARG; } @@ -564,6 +578,17 @@ transcribe_status run(transcribe_session * session, const float * pcm, int n_sam return TRANSCRIBE_ERR_ABORTED; } + int32_t language_slot = 0; + const auto & codes = gm->hparams.language_codes; + if (!codes.empty() && params != nullptr && params->language != nullptr && + std::strcmp(params->language, "auto") != 0) { + const auto it = std::find(codes.begin(), codes.end(), params->language); + if (it == codes.end()) { + return TRANSCRIBE_ERR_UNSUPPORTED_LANGUAGE; + } + language_slot = static_cast(it - codes.begin()) + 1; + } + transcribe::debug::init(); // Mel acquisition: the family mel (HTK + power=2 + log-clamp + @@ -613,8 +638,8 @@ transcribe_status run(transcribe_session * session, const float * pcm, int n_sam const WindowPlan wp = plan_windows(T_total, ws_align); if (wp.n_windows() <= 1) { int T_enc = 0; - if (auto st = - encode_mel_slice(gc, gm, gc->mel_buf.data(), mel_n_frames, /*dumps=*/true, gc->enc_host, T_enc, D); + if (auto st = encode_mel_slice(gc, gm, gc->mel_buf.data(), mel_n_frames, language_slot, /*dumps=*/true, + gc->enc_host, T_enc, D); st != TRANSCRIBE_OK) { return st; } @@ -659,7 +684,8 @@ transcribe_status run(transcribe_session * session, const float * pcm, int n_sam } int T_win = 0; - if (auto st = encode_mel_slice(gc, gm, gc->mel_win.data(), m_len, /*dumps=*/false, win_out, T_win, D); + if (auto st = + encode_mel_slice(gc, gm, gc->mel_win.data(), m_len, language_slot, /*dumps=*/false, win_out, T_win, D); st != TRANSCRIBE_OK) { return st; } diff --git a/src/arch/gigaam/weights.cpp b/src/arch/gigaam/weights.cpp index 8b534ee9b..43f57c958 100644 --- a/src/arch/gigaam/weights.cpp +++ b/src/arch/gigaam/weights.cpp @@ -22,6 +22,33 @@ namespace { constexpr const char * kFamilyTag = "gigaam"; +transcribe_status read_language_conditioning(const gguf_context * gguf, GigaamHParams & hp) { + constexpr const char * dim_key = "stt.gigaam.language.embedding_dim"; + constexpr const char * film_key = "stt.gigaam.language.film_layers"; + const auto codes = read_string_array_kv(gguf, "stt.gigaam.language.codes", hp.language_codes); + if (codes == KvResult::Absent && gguf_find_key(gguf, dim_key) < 0 && gguf_find_key(gguf, film_key) < 0) { + return TRANSCRIBE_OK; + } + + if (codes != KvResult::Ok || hp.language_codes.empty() || hp.encoder_kind != EncoderKind::Zapformer || + hp.head_kind != HeadKind::RNNT || + read_required_u32_kv(gguf, dim_key, kFamilyTag, hp.language_dim) != TRANSCRIBE_OK || hp.language_dim <= 0 || + read_int32_array_kv(gguf, film_key, hp.film_layers) != KvResult::Ok || hp.film_layers.empty() || + !std::is_sorted(hp.film_layers.begin(), hp.film_layers.end()) || + std::adjacent_find(hp.film_layers.begin(), hp.film_layers.end()) != hp.film_layers.end() || + hp.film_layers.front() < 0 || hp.film_layers.back() >= hp.enc_n_layers) { + log_msg(TRANSCRIBE_LOG_LEVEL_ERROR, "gigaam: invalid language conditioning metadata"); + return TRANSCRIBE_ERR_GGUF; + } + for (auto it = hp.language_codes.begin(); it != hp.language_codes.end(); ++it) { + if (it->empty() || *it == "auto" || std::find(hp.language_codes.begin(), it, *it) != it) { + log_msg(TRANSCRIBE_LOG_LEVEL_ERROR, "gigaam: invalid or duplicate language code '%s'", it->c_str()); + return TRANSCRIBE_ERR_GGUF; + } + } + return TRANSCRIBE_OK; +} + } // namespace transcribe_status read_gigaam_hparams(const gguf_context * gguf, GigaamHParams & hp) { @@ -136,7 +163,17 @@ transcribe_status read_gigaam_hparams(const gguf_context * gguf, GigaamHParams & return TRANSCRIBE_ERR_GGUF; } } else { - // Zapformer (GigaAM-v4). + // Zapformer (GigaAM-v4 and Multilingual-v2). + std::string activation; + if (auto st = read_optional_string_kv(gguf, "stt.gigaam.encoder.activation", kFamilyTag, "silu", activation); + st != TRANSCRIBE_OK) { + return st; + } + if (activation != "silu" && activation != "swish") { + log_msg(TRANSCRIBE_LOG_LEVEL_ERROR, "gigaam: unsupported Zapformer activation '%s'", activation.c_str()); + return TRANSCRIBE_ERR_GGUF; + } + hp.zap_swish = activation == "swish"; if (auto st = read_optional_bool_kv(gguf, "stt.gigaam.encoder.causal_frontend", kFamilyTag, true, hp.zap_causal_frontend); st != TRANSCRIBE_OK) { @@ -186,8 +223,9 @@ transcribe_status read_gigaam_hparams(const gguf_context * gguf, GigaamHParams & if (auto st = req_i32_arr("stt.gigaam.encoder.frontend_channels", fe_ch); st != TRANSCRIBE_OK) { return st; } - if (fe_ch.size() != 3) { - log_msg(TRANSCRIBE_LOG_LEVEL_ERROR, "gigaam: expected 3 frontend_channels, got %zu", fe_ch.size()); + if (fe_ch.size() != 3 || *std::min_element(fe_ch.begin(), fe_ch.end()) <= 0 || hp.enc_d_model <= 0 || + hp.enc_feat_in < 7 || hp.enc_subsampling_factor != 4) { + log_msg(TRANSCRIBE_LOG_LEVEL_ERROR, "gigaam: invalid Zapformer frontend dimensions"); return TRANSCRIBE_ERR_GGUF; } for (int i = 0; i < 3; ++i) { @@ -242,6 +280,7 @@ transcribe_status read_gigaam_hparams(const gguf_context * gguf, GigaamHParams & } } + int64_t total_layers = 0; hp.zap_stages.resize(n_stages); for (size_t s = 0; s < n_stages; ++s) { auto & st = hp.zap_stages[s]; @@ -254,14 +293,14 @@ transcribe_status read_gigaam_hparams(const gguf_context * gguf, GigaamHParams & st.conv_kernel = st_conv[s]; st.downsampling = st_ds[s]; st.input_scale = st_in_scales[s]; + total_layers += st.n_layers; char key[96]; std::snprintf(key, sizeof(key), "stt.gigaam.encoder.stage_%zu.residual_scales", s); if (auto r = req_f32_arr(key, st.residual_scales); r != TRANSCRIBE_OK) { return r; } - if (static_cast(st.residual_scales.size()) != st.n_layers + 1) { - log_msg(TRANSCRIBE_LOG_LEVEL_ERROR, "gigaam: stage %zu residual_scales len %zu != %d", s, - st.residual_scales.size(), st.n_layers + 1); + if (st.residual_scales.size() != static_cast(st.n_layers) + 1) { + log_msg(TRANSCRIBE_LOG_LEVEL_ERROR, "gigaam: stage %zu residual scale count does not match layers", s); return TRANSCRIBE_ERR_GGUF; } // Geometry the graph relies on: RoPE rotates query/key pairs (even @@ -309,6 +348,14 @@ transcribe_status read_gigaam_hparams(const gguf_context * gguf, GigaamHParams & } } hp.zap_max_downsampling = max_ds; + if (total_layers != hp.enc_n_layers) { + log_msg(TRANSCRIBE_LOG_LEVEL_ERROR, "gigaam: Zapformer stage layer counts do not match n_layers"); + return TRANSCRIBE_ERR_GGUF; + } + } + + if (auto st = read_language_conditioning(gguf, hp); st != TRANSCRIBE_OK) { + return st; } if (hp.head_kind == HeadKind::RNNT) { @@ -336,6 +383,15 @@ transcribe_status read_gigaam_hparams(const gguf_context * gguf, GigaamHParams & st != TRANSCRIBE_OK) { return st; } + if (auto st = read_optional_int32_kv(gguf, "stt.gigaam.rnnt.max_symbols", kFamilyTag, 10, hp.rnnt_max_symbols); + st != TRANSCRIBE_OK) { + return st; + } + if (hp.rnnt_max_symbols <= 0) { + log_msg(TRANSCRIBE_LOG_LEVEL_ERROR, "gigaam: stt.gigaam.rnnt.max_symbols must be positive, got %d", + hp.rnnt_max_symbols); + return TRANSCRIBE_ERR_GGUF; + } if (hp.pred_vocab != hp.joint_n_classes) { log_msg(TRANSCRIBE_LOG_LEVEL_ERROR, "gigaam: pred_vocab (%d) != joint_n_classes (%d)", hp.pred_vocab, hp.joint_n_classes); @@ -578,12 +634,12 @@ transcribe_status build_gigaam_weights(ggml_context * ctx_meta, const GigaamHPar } } else { // Zapformer frontend. - auto & fe = weights.zapformer.frontend; - const int c0 = hp.zap_fe_channels[0]; - const int c1 = hp.zap_fe_channels[1]; - const int c2 = hp.zap_fe_channels[2]; - const int cn_k = hp.zap_causal_frontend ? 3 : 7; - const int f_out = (((feat_in - 1) / 2) - 1) / 2; + auto & fe = weights.zapformer.frontend; + const int64_t c0 = hp.zap_fe_channels[0]; + const int64_t c1 = hp.zap_fe_channels[1]; + const int64_t c2 = hp.zap_fe_channels[2]; + const int cn_k = hp.zap_causal_frontend ? 3 : 7; + const int f_out = (((feat_in - 1) / 2) - 1) / 2; GET_CONV2D_W(fe.conv0_w, "enc.frontend.conv.0.weight", 3, 3, 1, c0); GET_LIN_B(fe.conv0_b, "enc.frontend.conv.0.bias", c0); GET_CONV2D_W(fe.conv1_w, "enc.frontend.conv.1.weight", 3, 3, c0, c1); @@ -602,15 +658,16 @@ transcribe_status build_gigaam_weights(ggml_context * ctx_meta, const GigaamHPar GET_LIN_B(fe.out_b, "enc.frontend.out.bias", d); // Zapformer stages. + int layer_index = 0; weights.zapformer.stages.resize(hp.zap_stages.size()); for (size_t s = 0; s < hp.zap_stages.size(); ++s) { - const auto & shp = hp.zap_stages[s]; - auto & sw = weights.zapformer.stages[s]; - const int in_dim = shp.downsampling * d; - const int sd = shp.dim; - const int dff = sd * shp.ff_mult; - const int dq = shp.n_heads * shp.qdim; - const int dv = shp.n_heads * shp.vdim; + const auto & shp = hp.zap_stages[s]; + auto & sw = weights.zapformer.stages[s]; + const int64_t in_dim = static_cast(shp.downsampling) * d; + const int64_t sd = shp.dim; + const int64_t dff = sd * shp.ff_mult; + const int64_t dq = static_cast(shp.n_heads) * shp.qdim; + const int64_t dv = static_cast(shp.n_heads) * shp.vdim; char nm[128]; auto mk = [&](const char * fmt, int l = -1) -> const char * { @@ -626,7 +683,7 @@ transcribe_status build_gigaam_weights(ggml_context * ctx_meta, const GigaamHPar GET_LIN_W(sw.proj_out_w, mk("enc.stages.%d.proj_out.weight"), sd, in_dim); sw.layers.resize(shp.n_layers); - for (int l = 0; l < shp.n_layers; ++l) { + for (int l = 0; l < shp.n_layers; ++l, ++layer_index) { auto & lw = sw.layers[l]; GET_LIN_W(lw.ff1_in_w, mk("enc.stages.%d.layers.%d.ff1.in.weight", l), sd, dff); GET_LIN_B(lw.ff1_in_b, mk("enc.stages.%d.layers.%d.ff1.in.bias", l), dff); @@ -657,8 +714,33 @@ transcribe_status build_gigaam_weights(ggml_context * ctx_meta, const GigaamHPar } GET_F32_1D(lw.out_norm_w, mk("enc.stages.%d.layers.%d.out_norm.weight", l), sd); + if (std::binary_search(hp.film_layers.begin(), hp.film_layers.end(), layer_index)) { + GET_LIN_W(lw.film_w, transcribe::weights::lname("lang.film.%d.weight", layer_index), + hp.language_dim, 2 * sd); + GET_LIN_B(lw.film_b, transcribe::weights::lname("lang.film.%d.bias", layer_index), 2 * sd); + } } } + + if (!hp.language_codes.empty()) { + auto & zap = weights.zapformer; + const auto * embed = ggml_get_tensor(ctx_meta, "lang.embed.weight"); + const auto * bias = ggml_get_tensor(ctx_meta, "lang.fusion.0.bias"); + const int64_t hidden = bias != nullptr ? bias->ne[0] : 0; + if (embed == nullptr || embed->ne[1] <= static_cast(hp.language_codes.size()) || hidden <= 0) { + log_msg(TRANSCRIBE_LOG_LEVEL_ERROR, "gigaam: missing or incomplete language embedding or fusion bias"); + return TRANSCRIBE_ERR_GGUF; + } + GET_F32_2D(zap.language_embed, "lang.embed.weight", hp.language_dim, embed->ne[1]); + GET_LIN_W(zap.fusion_in_w, "lang.fusion.0.weight", d, hidden); + GET_LIN_W(zap.fusion_lang_w, "lang.fusion.0.emb.weight", hp.language_dim, hidden); + GET_LIN_B(zap.fusion_in_b, "lang.fusion.0.bias", hidden); + GET_LIN_W(zap.fusion_out_w, "lang.fusion.1.weight", hidden, d); + GET_LIN_B(zap.fusion_out_b, "lang.fusion.1.bias", d); + } else if (ggml_get_tensor(ctx_meta, "lang.embed.weight") != nullptr) { + log_msg(TRANSCRIBE_LOG_LEVEL_ERROR, "gigaam: language embedding present without conditioning metadata"); + return TRANSCRIBE_ERR_GGUF; + } } // Head. diff --git a/src/arch/gigaam/weights.h b/src/arch/gigaam/weights.h index d55b62d3a..f73d474c8 100644 --- a/src/arch/gigaam/weights.h +++ b/src/arch/gigaam/weights.h @@ -75,8 +75,9 @@ struct GigaamHParams { // we read the KV so a future variant change is loud, not silent. std::string enc_conv_norm_type; - // Encoder (Zapformer, GigaAM-v4). + // Encoder (Zapformer). bool zap_causal_frontend = true; + bool zap_swish = false; int32_t zap_fe_channels[3] = { 16, 32, 64 }; std::vector zap_stages; float zap_out_norm_scale = 0.2f; @@ -87,6 +88,11 @@ struct GigaamHParams { // and long-form windows start on a multiple of it. 1 for Conformer. int32_t zap_max_downsampling = 1; + // The GGUF order assigns embedding rows 1..N; row 0 is auto. + std::vector language_codes; + int32_t language_dim = 0; + std::vector film_layers; + // RNN-T predictor + joint (HeadKind::RNNT only). int32_t pred_hidden = 0; int32_t pred_n_layers = 0; @@ -94,6 +100,10 @@ struct GigaamHParams { int32_t joint_hidden = 0; int32_t joint_n_classes = 0; std::string joint_activation; + // Greedy RNN-T emissions per encoder frame (the checkpoint's + // decodings..max_symbols_per_step). GGUFs written before the KV + // existed are GigaAM v3/v4, whose checkpoints use 10. + int32_t rnnt_max_symbols = 10; // CTC head (HeadKind::CTC only). Stored separately so the same // hparam struct can describe both head kinds. @@ -260,6 +270,8 @@ struct ZapformerLayerWeights { ggml_tensor * ff2_out_b = nullptr; ggml_tensor * out_norm_w = nullptr; + ggml_tensor * film_w = nullptr; + ggml_tensor * film_b = nullptr; }; struct ZapformerStageWeights { @@ -271,6 +283,12 @@ struct ZapformerStageWeights { struct ZapformerWeights { ZapformerFrontendWeights frontend; std::vector stages; + ggml_tensor * language_embed = nullptr; + ggml_tensor * fusion_in_w = nullptr; + ggml_tensor * fusion_lang_w = nullptr; + ggml_tensor * fusion_in_b = nullptr; + ggml_tensor * fusion_out_w = nullptr; + ggml_tensor * fusion_out_b = nullptr; }; struct GigaamWeights { diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index d56ac0784..266867543 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -400,6 +400,27 @@ transcribe_apply_warnings(transcribe_conformer_pw_layout_unit) add_test(NAME transcribe_conformer_pw_layout_unit COMMAND transcribe_conformer_pw_layout_unit) +# ----------------------------------------------------------------------------- +# transcribe-quantize policy: F32-only lookup tables stay F32 in every preset +# ----------------------------------------------------------------------------- +# +# Compiles the quantizer's policy table directly, so it runs whether or not +# TRANSCRIBE_BUILD_TOOLS builds the quantizer itself. + +add_executable(transcribe_quantize_policy_unit + quantize_policy_unit.cpp + ${CMAKE_SOURCE_DIR}/tools/transcribe-quantize/policy.cpp) + +target_link_libraries(transcribe_quantize_policy_unit PRIVATE ggml) + +target_include_directories(transcribe_quantize_policy_unit PRIVATE + ${CMAKE_SOURCE_DIR}/tools/transcribe-quantize) + +transcribe_apply_warnings(transcribe_quantize_policy_unit) + +add_test(NAME transcribe_quantize_policy_unit + COMMAND transcribe_quantize_policy_unit) + # ----------------------------------------------------------------------------- # causal_lm::pack_gate_up: alias / copy / mismatch, no model needed # ----------------------------------------------------------------------------- @@ -611,6 +632,8 @@ set(TRANSCRIBE_FIXTURE_FILES ${CMAKE_CURRENT_SOURCE_DIR}/fixtures/arch_cohere_minimal.gguf ${CMAKE_CURRENT_SOURCE_DIR}/fixtures/arch_granite5_ctc_minimal.gguf ${CMAKE_CURRENT_SOURCE_DIR}/fixtures/arch_gigaam_v4_minimal.gguf + ${CMAKE_CURRENT_SOURCE_DIR}/fixtures/arch_gigaam_multilingual_v2_minimal.gguf + ${CMAKE_CURRENT_SOURCE_DIR}/fixtures/arch_gigaam_multilingual_v2_duplicate.gguf ${CMAKE_CURRENT_SOURCE_DIR}/fixtures/arch_gigaam_v4_bad_odd_qdim.gguf ${CMAKE_CURRENT_SOURCE_DIR}/fixtures/arch_gigaam_v4_bad_even_conv_kernel.gguf ${CMAKE_CURRENT_SOURCE_DIR}/fixtures/arch_gigaam_v4_bad_zero_downsampling.gguf @@ -1075,6 +1098,16 @@ if(TRANSCRIBE_BUILD_REAL_MODEL_TESTS) set_tests_properties(transcribe_gigaam_v4_e2e_smoke PROPERTIES SKIP_RETURN_CODE 77) + # Offline Multilingual-v2 language hints and public-ABI batch parity. + add_executable(transcribe_gigaam_multilingual_v2_smoke gigaam_multilingual_v2_smoke.cpp) + target_compile_options(transcribe_gigaam_multilingual_v2_smoke PRIVATE "$<$:/utf-8>") + target_link_libraries(transcribe_gigaam_multilingual_v2_smoke PRIVATE transcribe transcribe-common-example) + target_compile_definitions(transcribe_gigaam_multilingual_v2_smoke PRIVATE + "TRANSCRIBE_TEST_SAMPLES_DIR=\"${CMAKE_SOURCE_DIR}/samples\"") + transcribe_apply_warnings(transcribe_gigaam_multilingual_v2_smoke) + add_test(NAME transcribe_gigaam_multilingual_v2_smoke COMMAND transcribe_gigaam_multilingual_v2_smoke) + set_tests_properties(transcribe_gigaam_multilingual_v2_smoke PROPERTIES SKIP_RETURN_CODE 77) + # Real-model GigaAM workspace-retention regression. add_executable(transcribe_gigaam_workspace_release_smoke gigaam_workspace_release_smoke.cpp) diff --git a/tests/fixtures/make_gguf_fixtures.py b/tests/fixtures/make_gguf_fixtures.py index c20da70a3..62462a7f8 100644 --- a/tests/fixtures/make_gguf_fixtures.py +++ b/tests/fixtures/make_gguf_fixtures.py @@ -886,6 +886,14 @@ def arr(key: str) -> list: _pack_kv_float32("stt.frontend.log_clamp_min", 1e-9), _pack_kv_float32("stt.frontend.log_clamp_max", 1e9), ] + if hp.get("language_codes"): + kvs.extend([ + _pack_kv_string("stt.gigaam.encoder.activation", "swish"), + _pack_kv_array_string("stt.gigaam.language.codes", hp["language_codes"]), + _pack_kv_uint32("stt.gigaam.language.embedding_dim", 4), + _pack_kv_array_int32("stt.gigaam.language.film_layers", [0]), + _pack_kv_int32("stt.gigaam.rnnt.max_symbols", 3), + ]) return kvs @@ -973,6 +981,13 @@ def _gigaam_v4_tensor_descriptors(hp: dict) -> list[tuple[str, list[int]]]: ("joint.out.weight", [jh, hp["vocab"]]), ("joint.out.bias", [hp["vocab"]]), ] + if hp.get("language_codes"): + out += [ + ("lang.embed.weight", [4, 3]), + ("lang.film.0.weight", [4, 2 * d]), ("lang.film.0.bias", [2 * d]), + ("lang.fusion.0.weight", [d, d]), ("lang.fusion.0.emb.weight", [4, d]), + ("lang.fusion.0.bias", [d]), ("lang.fusion.1.weight", [d, d]), ("lang.fusion.1.bias", [d]), + ] return out @@ -1022,7 +1037,7 @@ def _gigaam_v4_gguf(hp: dict, tokenizer_kv: list[bytes], short_array: str | None _pack_kv_bool("stt.capability.translate", False), _pack_kv_bool("stt.capability.lang_detect", False), _pack_kv_bool("stt.capability.streaming", False), - _pack_kv_array_string("general.languages", ["ru", "en"]), + _pack_kv_array_string("general.languages", hp.get("language_codes", ["ru", "en"])), *tokenizer_kv, *_gigaam_v4_hparams_kv(hp, short_array), ], @@ -2571,6 +2586,9 @@ def emit_fixtures(out_dir: Path) -> None: ] _write(out_dir / "arch_gigaam_v4_minimal.gguf", _gigaam_v4_gguf(GIGAAM_V4_HP, gigaam_v4_tokenizer_kv)) + for suffix, codes in (("minimal", ["kk", "hy"]), ("duplicate", ["kk", "kk"])): + _write(out_dir / f"arch_gigaam_multilingual_v2_{suffix}.gguf", + _gigaam_v4_gguf({**GIGAAM_V4_HP, "language_codes": codes}, gigaam_v4_tokenizer_kv)) for suffix, hp, short_array in GIGAAM_V4_MUTANTS: _write(out_dir / f"arch_gigaam_v4_bad_{suffix}.gguf", _gigaam_v4_gguf(hp, gigaam_v4_tokenizer_kv, short_array)) diff --git a/tests/gigaam_multilingual_v2_smoke.cpp b/tests/gigaam_multilingual_v2_smoke.cpp new file mode 100644 index 000000000..8813d1b43 --- /dev/null +++ b/tests/gigaam_multilingual_v2_smoke.cpp @@ -0,0 +1,96 @@ +// Public-ABI smoke for the F32 Multilingual-v2 E2E RNN-T checkpoint. +#include "transcribe.h" +#include "wav.h" + +#include +#include +#include +#include +#include +#include + +namespace { +bool check_transcripts(transcribe_session * session, const std::vector & pcm) { + transcribe_run_params params; + transcribe_run_params_init(¶ms); + params.timestamps = TRANSCRIBE_TIMESTAMPS_NONE; + const float * inputs[] = { pcm.data(), pcm.data() }; + const int sizes[] = { static_cast(pcm.size()), static_cast(pcm.size()) }; + params.language = "zz"; + if (transcribe_run(session, inputs[0], sizes[0], ¶ms) != TRANSCRIBE_ERR_UNSUPPORTED_LANGUAGE) { + return false; + } + // "auto" is an alias for the omitted hint: same slot, same transcript. + const char * hints[] = { "ru", nullptr, "auto" }; + std::string omitted; + for (const char * hint : hints) { + params.language = hint; + if (transcribe_run(session, inputs[0], sizes[0], ¶ms) != TRANSCRIBE_OK) { + return false; + } + const char * result = transcribe_full_text(session); + if (!result || !*result) { + return false; + } + const std::string single(result); + if (hint && std::strcmp(hint, "ru") == 0 && single != u8"Важно различать глаголы и дополнения.") { + std::fprintf(stderr, "Unexpected ru.wav transcript: %s\n", result); + return false; + } + if (!hint) { + omitted = single; + } else if (std::strcmp(hint, "auto") == 0 && single != omitted) { + std::fprintf(stderr, "auto transcript differs from the omitted hint: %s\n", result); + return false; + } + if (transcribe_run_batch(session, inputs, sizes, 2, ¶ms) != TRANSCRIBE_OK || + transcribe_batch_n_results(session) != 2) { + return false; + } + for (int i = 0; i < 2; ++i) { + const char * batch = transcribe_batch_full_text(session, i); + if (transcribe_batch_status(session, i) != TRANSCRIBE_OK || !batch || single != batch) { + return false; + } + } + } + return true; +} +} // namespace + +int main() { + const char * path = std::getenv("TRANSCRIBE_GIGAAM_MULTILINGUAL_V2_GGUF"); + if (!path || !*path) { + return 77; + } + std::vector pcm; + std::string error; + if (!transcribe_cli::load_wav_mono_16k(std::string(TRANSCRIBE_TEST_SAMPLES_DIR) + "/ru.wav", pcm, error)) { + std::fprintf(stderr, "%s\n", error.c_str()); + return EXIT_FAILURE; + } + transcribe_model_load_params load; + transcribe_model_load_params_init(&load); + load.backend = TRANSCRIBE_BACKEND_CPU; + transcribe_model * model = nullptr; + if (transcribe_model_load_file(path, &load, &model) != TRANSCRIBE_OK) { + return EXIT_FAILURE; + } + transcribe_capabilities caps; + transcribe_capabilities_init(&caps); + bool ok = transcribe_model_get_capabilities(model, &caps) == TRANSCRIBE_OK && caps.n_languages == 21 && + !caps.supports_language_detect && caps.languages && + std::any_of(caps.languages, caps.languages + caps.n_languages, + [](const char * code) { return std::strcmp(code, "kk") == 0; }); + transcribe_session_params params; + transcribe_session_params_init(¶ms); + transcribe_session * session = nullptr; + if (ok && transcribe_session_init(model, ¶ms, &session) == TRANSCRIBE_OK) { + ok = check_transcripts(session, pcm); + transcribe_session_free(session); + } else { + ok = false; + } + transcribe_model_free(model); + return ok ? EXIT_SUCCESS : EXIT_FAILURE; +} diff --git a/tests/gigaam_smoke.cpp b/tests/gigaam_smoke.cpp index f461c3e97..26a9da5e1 100644 --- a/tests/gigaam_smoke.cpp +++ b/tests/gigaam_smoke.cpp @@ -122,7 +122,9 @@ void check_valid_model(const transcribe_model * model) { // One second of silence through the encoder graph and RNN-T decoder: the // tiny geometry must build and run, whatever the (meaningless) text is. -void check_silent_run(transcribe_model * model) { +void check_silent_run(transcribe_model * model, + const char * language = nullptr, + transcribe_status expected = TRANSCRIBE_OK) { transcribe_session_params sp; transcribe_session_params_init(&sp); transcribe_session * session = nullptr; @@ -134,12 +136,16 @@ void check_silent_run(transcribe_model * model) { const std::vector pcm(16000, 0.0f); transcribe_run_params rp; transcribe_run_params_init(&rp); + rp.language = language; const transcribe_status run_st = transcribe_run(session, pcm.data(), static_cast(pcm.size()), &rp); - if (run_st != TRANSCRIBE_OK) { - std::fprintf(stderr, "FAIL silent run: %s\n", transcribe_status_string(run_st)); + if (run_st != expected) { + std::fprintf(stderr, "FAIL silent run (language %s): %s\n", language ? language : "null", + transcribe_status_string(run_st)); ++g_failures; } - CHECK(transcribe_full_text(session) != nullptr); + if (expected == TRANSCRIBE_OK) { + CHECK(transcribe_full_text(session) != nullptr); + } transcribe_session_free(session); } @@ -147,10 +153,15 @@ void check_silent_run(transcribe_model * model) { int main() { const char * mutants[] = { - "arch_gigaam_v4_bad_odd_qdim.gguf", "arch_gigaam_v4_bad_even_conv_kernel.gguf", - "arch_gigaam_v4_bad_zero_downsampling.gguf", "arch_gigaam_v4_bad_intermediate_downsampling.gguf", - "arch_gigaam_v4_bad_mixed_qdim.gguf", "arch_gigaam_v4_bad_symmetric_frontend.gguf", - "arch_gigaam_v4_bad_short_stage_array.gguf", "arch_gigaam_v4_bad_squeezeformer.gguf", + "arch_gigaam_multilingual_v2_duplicate.gguf", + "arch_gigaam_v4_bad_odd_qdim.gguf", + "arch_gigaam_v4_bad_even_conv_kernel.gguf", + "arch_gigaam_v4_bad_zero_downsampling.gguf", + "arch_gigaam_v4_bad_intermediate_downsampling.gguf", + "arch_gigaam_v4_bad_mixed_qdim.gguf", + "arch_gigaam_v4_bad_symmetric_frontend.gguf", + "arch_gigaam_v4_bad_short_stage_array.gguf", + "arch_gigaam_v4_bad_squeezeformer.gguf", }; const std::string valid = fixture_path("arch_gigaam_v4_minimal.gguf"); @@ -172,7 +183,23 @@ int main() { return EXIT_FAILURE; } check_valid_model(model); + // GGUFs without stt.gigaam.rnnt.max_symbols keep the v3/v4 limit. + CHECK(static_cast(model)->hparams.rnnt_max_symbols == 10); + check_silent_run(model); + transcribe_model_free(model); + + model = nullptr; + if (load_cpu(fixture_path("arch_gigaam_multilingual_v2_minimal.gguf"), &model) != TRANSCRIBE_OK || !model) { + return EXIT_FAILURE; + } + const auto & hp = static_cast(model)->hparams; + CHECK(hp.zap_swish); + CHECK(hp.language_codes == std::vector({ "kk", "hy" })); + CHECK(hp.rnnt_max_symbols == 3); check_silent_run(model); + check_silent_run(model, "hy"); + check_silent_run(model, "auto"); + check_silent_run(model, "ru", TRANSCRIBE_ERR_UNSUPPORTED_LANGUAGE); transcribe_model_free(model); for (const char * name : mutants) { diff --git a/tests/golden/gigaam/gigaam-multilingual-v2-e2e-rnnt.manifest.json b/tests/golden/gigaam/gigaam-multilingual-v2-e2e-rnnt.manifest.json new file mode 100644 index 000000000..1859f77c1 --- /dev/null +++ b/tests/golden/gigaam/gigaam-multilingual-v2-e2e-rnnt.manifest.json @@ -0,0 +1,84 @@ +{ + "schema": "transcribe-golden-manifest-v1", + "family": "gigaam", + "variant": "gigaam-multilingual-v2-e2e-rnnt", + "source_model": { + "hf_repo": "ai-sage/GigaAM-Multilingual-v2", + "hf_revision": "c21483b5e185ff32f6fb2e2c801f92f4e7fbfee8" + }, + "reference": { + "kind": "author_repo_gigaam", + "source": "https://huggingface.co/ai-sage/GigaAM-Multilingual-v2/blob/c21483b5e185ff32f6fb2e2c801f92f4e7fbfee8/modeling_gigaam.py", + "revision": "c21483b5e185ff32f6fb2e2c801f92f4e7fbfee8", + "entrypoint": "scripts/dump_reference_gigaam_v4_hf.py", + "env": "gigaam-v4", + "variant_key": "multilingual_v2_e2e_rnnt", + "dump_args": [ + "--variant", + "multilingual_v2_e2e_rnnt" + ] + }, + "expected_dtype": "float32", + "dtype_source": "manual", + "frontend": { + "sample_rate": 16000, + "n_mels": 64, + "hop_length": 160, + "fft_size": 320, + "win_length": 320, + "window": "hann_periodic", + "normalization": "none", + "center": false, + "mel_filterbank_norm": "htk", + "log_scale": "log(clamp(x, 1e-9, 1e9))" + }, + "tokenizer_summary": { + "type": "sentencepiece", + "vocab_size": 4026, + "special_tokens": { + "blank": 4026 + } + }, + "capabilities": { + "languages": [ + "ru", + "en", + "kk", + "ky", + "uz", + "be", + "fr", + "es", + "ba", + "ka", + "hy", + "ro", + "tk", + "az", + "tg", + "de", + "it", + "nl", + "pl", + "pt", + "tt" + ], + "language_detection": false, + "translation": false, + "timestamps": [], + "streaming": false, + "speaker_diarization": false + }, + "head_type": "rnnt", + "tolerance_file": "tests/tolerances/gigaam-multilingual-v2.json", + "cases": [ + { + "audio": "ru", + "language": "ru" + }, + { + "audio": "fleurs-en", + "language": null + } + ] +} diff --git a/tests/quantize_policy_unit.cpp b/tests/quantize_policy_unit.cpp new file mode 100644 index 000000000..2a201097e --- /dev/null +++ b/tests/quantize_policy_unit.cpp @@ -0,0 +1,72 @@ +// quantize_policy_unit.cpp - unit test for transcribe-quantize's policy table. +// +// Some loaders read a tensor through a GET_F32 slot because the graph feeds +// it to ggml_get_rows as a small lookup table. If the quantizer's policy +// routes such a tensor to the Linear bucket, every quantized GGUF of that +// model fails to load while the F32 reference still works, so the gap only +// shows once the quant matrix is produced. This pins those tables to F32 for +// every preset, and pins that the neighbouring GigaAM Multilingual-v2 +// conditioning projections land on a type whose block size fits their +// 128-wide rows. + +#include "policy.h" + +#include +#include + +namespace { + +int g_failures = 0; + +void expect(bool ok, const char * preset, const char * name, const char * what) { + if (!ok) { + std::fprintf(stderr, "FAIL %s %s: %s\n", preset, name, what); + ++g_failures; + } +} + +} // namespace + +int main() { + using transcribe::quantize::preset_table; + using transcribe::quantize::resolve_target_type; + + // F32-only get_rows tables: name and ne0. + struct Table { + const char * name; + int64_t ne0; + }; + + const Table f32_tables[] = { + { "enc.embed.weight", 560 }, // sensevoice prefix-token table + { "lang.embed.weight", 128 }, // gigaam multilingual language slots + }; + + // Linear operands of the GigaAM Multilingual-v2 conditioning path. + const Table linear[] = { + { "lang.film.3.weight", 128 }, + { "lang.fusion.0.emb.weight", 128 }, + { "lang.fusion.0.weight", 1024 }, + { "lang.fusion.1.weight", 2048 }, + }; + + size_t n = 0; + const auto * presets = preset_table(n); + for (size_t i = 0; i < n; ++i) { + const auto & p = presets[i]; + for (const auto & t : f32_tables) { + expect(resolve_target_type(p, t.name, t.ne0) == GGML_TYPE_F32, p.name, t.name, "expected F32"); + } + for (const auto & t : linear) { + const ggml_type type = resolve_target_type(p, t.name, t.ne0); + expect(t.ne0 % ggml_blck_size(type) == 0, p.name, t.name, "block size does not divide ne0"); + } + } + + if (g_failures != 0) { + std::fprintf(stderr, "quantize_policy_unit: %d failure(s)\n", g_failures); + return EXIT_FAILURE; + } + std::printf("quantize_policy_unit: OK (%zu presets)\n", n); + return EXIT_SUCCESS; +} diff --git a/tests/tolerances/gigaam-multilingual-v2.json b/tests/tolerances/gigaam-multilingual-v2.json new file mode 100644 index 000000000..cb65a730a --- /dev/null +++ b/tests/tolerances/gigaam-multilingual-v2.json @@ -0,0 +1,43 @@ +{ + "_comment": [ + "CPU F32, one thread. GigaAMDualASR at c21483b5e185ff32f6fb2e2c801f92f4e7fbfee8.", + "ru.wav with the Russian slot and fleurs-en.wav with the default slot. Bounds are 1.5 times the largest max/mean error observed on Windows x64 and on macOS arm64 (Apple M1), rounded up to two significant digits. The arm64 errors are the larger ones, up to 2.1x the x64 errors at the encoder output.", + "The FFT and mel reduction dominate frontend drift. The remaining bounds include convolution, FiLM, SwishR/L, the residual stacks and the final language fusion. enc.out is about 2x GigaAM-v4's on the same clips (2.5e-5 vs 1.1e-5 on arm64): 25 layers instead of 19, and the late-fusion MLP adds a 2048-wide projection after the output RmsNorm." + ], + "enc.out": { + "max_abs": 3.8e-05, + "mean_abs": 2.0e-06 + }, + "enc.stage.0.out": { + "max_abs": 6.5e-06, + "mean_abs": 3.7e-07 + }, + "enc.stage.1.out": { + "max_abs": 5.8e-06, + "mean_abs": 4.7e-07 + }, + "enc.stage.2.out": { + "max_abs": 8.2e-06, + "mean_abs": 5.2e-07 + }, + "enc.subsample.out": { + "max_abs": 1.2e-05, + "mean_abs": 4.5e-07 + }, + "frontend.mel.out": { + "max_abs": 0.00032, + "mean_abs": 1.9e-06 + }, + "rnnt.encoded": { + "max_abs": 3.8e-05, + "mean_abs": 2.0e-06 + }, + "enc.mel.in": { + "max_abs": 0.00032, + "mean_abs": 1.9e-06 + }, + "dec.enc_out": { + "max_abs": 3.8e-05, + "mean_abs": 2.0e-06 + } +} diff --git a/tools/transcribe-quantize/policy.cpp b/tools/transcribe-quantize/policy.cpp index 56ee2cc81..e577baaa8 100644 --- a/tools/transcribe-quantize/policy.cpp +++ b/tools/transcribe-quantize/policy.cpp @@ -176,6 +176,12 @@ Bucket classify_tensor(const std::string & name, int64_t ne0) { if (name == "enc.embed.weight") { return Bucket::Norm; } + // GigaAM Multilingual-v2: language-slot embedding (num_slots x 128) + // looked up via ggml_get_rows to condition FiLM and late fusion. Loader + // requires F32; the table is 16 KB. + if (name == "lang.embed.weight") { + return Bucket::Norm; + } // SenseVoice: trailing LayerNorms after the encoder stack and after // the tp_encoder stack. Don't carry the `norm_` prefix the generic // rule looks for, and the loader requires F32.