Skip to content

Commit 62b093e

Browse files
justinchubyCopilot
andauthored
Add Parakeet CTC automatic speech recognition support (#471)
## Summary Add first-class Mobius support for [`nvidia/parakeet-ctc-1.1b`](https://huggingface.co/nvidia/parakeet-ctc-1.1b), Hugging Face `model_type: parakeet_ctc`. This is an independent offline CTC ASR architecture and does not duplicate #411, which targets streaming Parakeet RNNT. The new path consumes processor-normalized log-mel features and produces frame-level CTC logits. ## Architecture - Symmetric 8x depthwise Conv2d FastConformer subsampling - Transformer-XL relative positional self-attention with learned `bias_u`/`bias_v` - Macaron feed-forward blocks - BatchNorm Conformer convolution modules - 42-layer, hidden-size 1024 encoder and 1025-class Conv1d CTC head - Feature-input contract: `input_features [B, T, 80]` plus boolean `attention_mask` - Direct Hugging Face parameter-name alignment; preprocessing only removes BatchNorm `num_batches_tracked` The reusable component surface also gains grouped/bias-free `Conv1d` and frozen `BatchNorm1d` inference with fp32 accumulation. ## Model and golden integration - Register `parakeet_ctc` config/model/task extraction - Add `FeatureCTCAsrTask` - Add `feature-ctc-asr` YAML/schema and golden generation support - Pin config and every checkpoint shard to revision `20e63a0fed6aedba145b74b826dbd41df0941730` - Add exact frame-count enforcement for deterministic CTC L5 goldens - Add explicit ORT GenAI export rejection for this unsupported feature-input CTC contract Committed real-audio goldens use nonzero LibriSpeech audio and contain all 114 frame argmax IDs plus the full decoded transcript: > cauliflower mayonnaise take cold boiled cauliflower break into branches adding salt pepper and vinegar to season ## Validation GPU: NVIDIA RTX A1000 Laptop GPU, 8 GB; CUDA and `CUDAExecutionProvider` available. - `python -m pytest tests/build_graph_test.py tests/cli_test.py src/ -q -k "not phi4mm and not apply_weights_unknown" --tb=short -n auto` - **3639 passed, 57 skipped** - `python -m pytest tests/arch_validation_test.py -k parakeet -q --tb=short` - **3 passed, 874 deselected** - `python -m pytest tests/yaml_schema_test.py -q --tb=short` - **237 passed** - Real-checkpoint CUDA parity, fp32: - **passed** - max absolute difference: **0.000076** - mean absolute difference: **0.000014** - Real-checkpoint CUDA fp16: - **passed** - exact **114/114** frame IDs - exact full transcript - CUDA L4 checkpoint golden and L5 deterministic CTC transcript/frame golden: - **2 passed, 377 deselected** - `lintrunner -a` - **no issues** - Automated high-confidence code review after fixes: - **no significant issues found** ## CLI/runtime/quantization evidence - fp16 CLI CUDA export loaded and ran with ONNX Runtime CUDA EP - Runtime produced the exact 114 golden frame IDs and exact full transcript - Olive 0.13.0 INT4 RTN quantization produced a 751 MB model - Quantized CUDA inference produced the same full transcript ## Evidence-based limitations and waivers - **BF16 disabled:** Hugging Face bf16 reference output is correct, and the Mobius graph executes under ORT CUDA after avoiding unsupported kernels, but ORT output collapses to blank CTC predictions. Parakeet therefore defaults safely to fp32 and rejects explicit bf16; fp32 and fp16 are verified. This avoids exposing a configuration that runs without error but returns incorrect ASR results. - **ORT GenAI / Foundry Local waived:** ORT GenAI 0.15.2 rejects `input_features` in its decoder model schema. This offline feature-input CTC model cannot be represented by the current ORT GenAI decoder contract, so Mobius now fails explicitly rather than producing a misleading package. Foundry Local depends on ORT GenAI and is consequently not applicable until that runtime supports feature-input CTC pipelines. - **Safetensors package output:** the installed `onnx_ir` failed during safetensors CLI serialization; standard ONNX external-data export succeeded and was used for CUDA runtime and quantization validation. --------- Signed-off-by: Justin Chu <[email protected]> Signed-off-by: justinchuby <[email protected]> Co-authored-by: Copilot App <[email protected]>
1 parent ed0319d commit 62b093e

32 files changed

Lines changed: 1683 additions & 79 deletions

‎.github/workflows/gpu_l4_golden_parity.yml‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,13 @@ on:
55
# Run nightly at 4am UTC (after golden regen on Sunday)
66
- cron: '0 4 * * *'
77
workflow_dispatch:
8+
inputs:
9+
affected_models:
10+
description: >-
11+
JSON array of model names. Empty string or empty array runs all models.
12+
required: false
13+
type: string
14+
default: ""
815
workflow_call:
916
inputs:
1017
affected_models:
@@ -48,8 +55,6 @@ jobs:
4855
with:
4956
path: ~/.cache/huggingface
5057
key: hf-gpu-${{ hashFiles('testdata/cases/**/*.yaml') }}
51-
restore-keys: |
52-
hf-gpu-
5358

5459
- name: Install PyTorch (CUDA)
5560
run: pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu128

‎.github/workflows/gpu_l5_generation_e2e.yml‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,13 @@ on:
55
# Run nightly at 5am UTC (after L4 golden tests)
66
- cron: '0 5 * * *'
77
workflow_dispatch:
8+
inputs:
9+
affected_models:
10+
description: >-
11+
JSON array of model names. Empty string or empty array runs all models.
12+
required: false
13+
type: string
14+
default: ""
815
workflow_call:
916
inputs:
1017
affected_models:
@@ -48,8 +55,6 @@ jobs:
4855
with:
4956
path: ~/.cache/huggingface
5057
key: hf-gpu-${{ hashFiles('testdata/cases/**/*.yaml') }}
51-
restore-keys: |
52-
hf-gpu-
5358

5459
- name: Install PyTorch (CUDA)
5560
run: pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu128

‎scripts/generate_golden.py‎

Lines changed: 22 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -963,7 +963,7 @@ def _generate_audio_feature_extraction(case: TestCase, json_path: Path, device:
963963

964964

965965
def _generate_ctc_asr(case: TestCase, json_path: Path, device: str) -> None:
966-
"""Generate golden data for CTC-based ASR (Wav2Vec2ForCTC / MMS).
966+
"""Generate golden data for raw-waveform or feature-input CTC ASR.
967967
968968
The model output is per-frame logits over a vocabulary; we save the
969969
top-K over the final frame's logit vector (matching the existing
@@ -984,21 +984,29 @@ def _generate_ctc_asr(case: TestCase, json_path: Path, device: str) -> None:
984984

985985
lang = case.generation_params.get("lang", "eng")
986986

987-
processor = transformers.AutoProcessor.from_pretrained(
988-
case.model_id, trust_remote_code=case.trust_remote_code, target_lang=lang
989-
)
990-
model = transformers.Wav2Vec2ForCTC.from_pretrained(
991-
case.model_id,
992-
torch_dtype=torch.float32,
993-
device_map=device,
994-
trust_remote_code=case.trust_remote_code,
995-
target_lang=lang,
996-
ignore_mismatched_sizes=True, # MMS lm_head shape changes per language
997-
)
987+
processor_kwargs: dict[str, object] = {
988+
"revision": case.revision,
989+
"trust_remote_code": case.trust_remote_code,
990+
}
991+
model_kwargs: dict[str, object] = {
992+
"revision": case.revision,
993+
"torch_dtype": torch.float32,
994+
"device_map": device,
995+
"trust_remote_code": case.trust_remote_code,
996+
}
997+
if case.model_type == "mms":
998+
processor_kwargs["target_lang"] = lang
999+
model_kwargs.update(
1000+
target_lang=lang,
1001+
ignore_mismatched_sizes=True,
1002+
)
1003+
1004+
processor = transformers.AutoProcessor.from_pretrained(case.model_id, **processor_kwargs)
1005+
model = transformers.AutoModelForCTC.from_pretrained(case.model_id, **model_kwargs)
9981006
# For MMS, switching languages also requires loading the per-language adapter.
9991007
# Non-MMS Wav2Vec2ForCTC checkpoints don't have language adapters;
10001008
# the missing-adapter case is expected and harmless there.
1001-
if hasattr(model, "load_adapter"):
1009+
if case.model_type == "mms" and hasattr(model, "load_adapter"):
10021010
with contextlib.suppress(ValueError, KeyError, OSError):
10031011
model.load_adapter(lang)
10041012
model.eval()
@@ -1771,6 +1779,7 @@ def _hook(_module, _args, kwargs, output):
17711779
"speech-language": _generate_speech_language,
17721780
"audio-feature-extraction": _generate_audio_feature_extraction,
17731781
"ctc-asr": _generate_ctc_asr,
1782+
"feature-ctc-asr": _generate_ctc_asr,
17741783
# Vision tasks that produce last_hidden_state — reuse image classification.
17751784
"depth-estimation": _generate_image_classification,
17761785
"image-segmentation": _generate_image_classification,

‎src/mobius/_builder.py‎

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -411,6 +411,7 @@ def build(
411411
model_id: str,
412412
task: str | ModelTask | None = None,
413413
*,
414+
revision: str | None = None,
414415
module_class: type[nn.Module] | None = None,
415416
dtype: str | ir.DataType | None = None,
416417
output_layer_indices: list[int] | None = None,
@@ -443,6 +444,8 @@ def build(
443444
task: The model task. Either a task name string
444445
(e.g. ``"text-generation"``) or a :class:`ModelTask` instance.
445446
When ``None``, the task is auto-detected from the model type.
447+
revision: Optional Hugging Face revision used consistently for the
448+
configuration and every weight shard.
446449
module_class: Custom module class to use instead of the auto-detected
447450
one. The class must accept an :class:`ArchitectureConfig` as its
448451
constructor argument and have a ``forward()`` method compatible
@@ -537,14 +540,15 @@ def build(
537540
from mobius._diffusers_builder import build_diffusers_pipeline
538541

539542
try:
540-
hf_config = transformers.AutoConfig.from_pretrained(
541-
model_id, trust_remote_code=trust_remote_code
542-
)
543+
config_kwargs = {"trust_remote_code": trust_remote_code}
544+
if revision is not None:
545+
config_kwargs["revision"] = revision
546+
hf_config = transformers.AutoConfig.from_pretrained(model_id, **config_kwargs)
543547
except (ValueError, KeyError, OSError):
544548
# AutoConfig failed — the model_type may not be in transformers,
545549
# or the HF config class has a bug (e.g. NemotronH with '-' pattern).
546550
# Try loading config.json directly if the model is in our registry.
547-
hf_config = _try_load_config_json(model_id)
551+
hf_config = _try_load_config_json(model_id, revision=revision)
548552
if hf_config is None or hf_config.model_type not in registry:
549553
if text_only:
550554
raise ValueError(
@@ -555,6 +559,7 @@ def build(
555559
# Not a model we support — try diffusers pipeline
556560
return build_diffusers_pipeline(
557561
model_id,
562+
revision=revision,
558563
dtype=dtype,
559564
load_weights=load_weights,
560565
)
@@ -687,7 +692,7 @@ def build(
687692
model.graph.name = f"{model_id}/{name}"
688693

689694
if load_weights:
690-
state_dict = _download_weights(model_id)
695+
state_dict = _download_weights(model_id, revision=revision)
691696
if hasattr(model_module, "preprocess_weights"):
692697
state_dict = model_module.preprocess_weights(state_dict)
693698
prefix_map = getattr(model_module, "weight_prefix_map", None)

‎src/mobius/_builder_test.py‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
_enable_prefill_prefix_pruning_task,
1818
_graph_requires_opset24,
1919
_maybe_apply_opset_lowering,
20+
build,
2021
flags,
2122
)
2223
from mobius._model_package import ModelPackage
@@ -183,3 +184,47 @@ def test_maybe_apply_opset_lowering_skipped_when_flag_disabled(
183184
_maybe_apply_opset_lowering(pkg, execution_provider="cuda")
184185

185186
assert pkg["embedding"].graph.opset_imports[""] == 24
187+
188+
189+
def test_build_threads_revision_to_diffusers_fallback(monkeypatch: pytest.MonkeyPatch) -> None:
190+
import transformers
191+
192+
import mobius._config_resolver as config_resolver
193+
import mobius._diffusers_builder as diffusers_builder
194+
195+
monkeypatch.setattr(
196+
transformers.AutoConfig,
197+
"from_pretrained",
198+
lambda *args, **kwargs: (_ for _ in ()).throw(OSError("not transformers")),
199+
)
200+
monkeypatch.setattr(config_resolver, "_try_load_config_json", lambda *args, **kwargs: None)
201+
expected = ModelPackage({})
202+
calls: list[tuple[tuple, dict]] = []
203+
204+
def fake_build_diffusers(*args, **kwargs):
205+
calls.append((args, kwargs))
206+
return expected
207+
208+
monkeypatch.setattr(
209+
diffusers_builder,
210+
"build_diffusers_pipeline",
211+
fake_build_diffusers,
212+
)
213+
214+
result = build(
215+
"fake/diffusers",
216+
revision="pinned-revision",
217+
load_weights=False,
218+
)
219+
220+
assert result is expected
221+
assert calls == [
222+
(
223+
("fake/diffusers",),
224+
{
225+
"revision": "pinned-revision",
226+
"dtype": None,
227+
"load_weights": False,
228+
},
229+
)
230+
]

‎src/mobius/_config_resolver.py‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ def _default_task_for_model(model_type: str) -> str:
7676
return getattr(cls, "default_task", "text-generation")
7777

7878

79-
def _try_load_config_json(model_id: str):
79+
def _try_load_config_json(model_id: str, revision: str | None = None):
8080
"""Try to load config.json directly for models not in transformers.
8181
8282
Returns a ``PretrainedConfig``-like object with attribute access,
@@ -87,7 +87,10 @@ def _try_load_config_json(model_id: str):
8787
from huggingface_hub import hf_hub_download
8888

8989
try:
90-
path = hf_hub_download(repo_id=model_id, filename="config.json")
90+
kwargs = {"repo_id": model_id, "filename": "config.json"}
91+
if revision is not None:
92+
kwargs["revision"] = revision
93+
path = hf_hub_download(**kwargs)
9194
except (OSError, ValueError) as e:
9295
logger.debug("Failed to download config.json for %s: %s", model_id, e)
9396
return None

‎src/mobius/_configs/__init__.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@
5050
NanoChatConfig,
5151
NemotronHConfig,
5252
NemotronParseConfig,
53+
ParakeetCTCConfig,
5354
Qwen35MtpConfig,
5455
Sam2Config,
5556
SegformerConfig,
@@ -121,6 +122,7 @@
121122
"NanoChatConfig",
122123
"NemotronParseConfig",
123124
"NemotronHConfig",
125+
"ParakeetCTCConfig",
124126
"QuantizationConfig",
125127
"Qwen35MtpConfig",
126128
"RoPEConfig",

‎src/mobius/_configs/_base.py‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2930,3 +2930,51 @@ def from_transformers(cls, config, parent_config=None) -> MMSConfig:
29302930
adapter_stride=getattr(config, "adapter_stride", 2),
29312931
num_adapter_layers=getattr(config, "num_adapter_layers", 3),
29322932
)
2933+
2934+
2935+
@dataclasses.dataclass
2936+
class ParakeetCTCConfig(ArchitectureConfig):
2937+
"""Configuration for Hugging Face Parakeet FastConformer CTC models."""
2938+
2939+
num_mel_bins: int = 80
2940+
subsampling_factor: int = 8
2941+
subsampling_conv_channels: int = 256
2942+
subsampling_conv_kernel_size: int = 3
2943+
subsampling_conv_stride: int = 2
2944+
conv_kernel_size: int = 9
2945+
attention_bias: bool = True
2946+
convolution_bias: bool = True
2947+
scale_input: bool = True
2948+
layer_norm_eps: float = 1e-5
2949+
2950+
@classmethod
2951+
def from_transformers(cls, config, parent_config=None) -> ParakeetCTCConfig:
2952+
"""Extract the nested Parakeet encoder and parent CTC vocabulary fields."""
2953+
encoder = getattr(config, "encoder_config", config)
2954+
parent = config if encoder is not config else parent_config
2955+
base = ArchitectureConfig.from_transformers(encoder, parent_config=parent)
2956+
fields = _shallow_fields(base)
2957+
fields.update(
2958+
vocab_size=getattr(parent, "vocab_size", fields["vocab_size"]),
2959+
pad_token_id=getattr(parent, "pad_token_id", fields["pad_token_id"]),
2960+
model_type=getattr(parent, "model_type", fields["model_type"]),
2961+
)
2962+
resolved_dtype = _resolve_dtype(parent)
2963+
# ORT CUDA executes this architecture in bf16 but diverges enough to
2964+
# collapse real CTC output to blanks. The checkpoint weights are fp32,
2965+
# so keep the safe fp32 default; callers may explicitly select fp16.
2966+
if resolved_dtype is not None and resolved_dtype != ir.DataType.BFLOAT16:
2967+
fields["dtype"] = resolved_dtype
2968+
return cls(
2969+
**fields,
2970+
num_mel_bins=getattr(encoder, "num_mel_bins", 80),
2971+
subsampling_factor=getattr(encoder, "subsampling_factor", 8),
2972+
subsampling_conv_channels=getattr(encoder, "subsampling_conv_channels", 256),
2973+
subsampling_conv_kernel_size=getattr(encoder, "subsampling_conv_kernel_size", 3),
2974+
subsampling_conv_stride=getattr(encoder, "subsampling_conv_stride", 2),
2975+
conv_kernel_size=getattr(encoder, "conv_kernel_size", 9),
2976+
attention_bias=getattr(encoder, "attention_bias", True),
2977+
convolution_bias=getattr(encoder, "convolution_bias", True),
2978+
scale_input=getattr(encoder, "scale_input", True),
2979+
layer_norm_eps=getattr(encoder, "layer_norm_eps", 1e-5),
2980+
)

0 commit comments

Comments
 (0)