NathanRoll commited on
Commit
10b603f
·
verified ·
1 Parent(s): eac739d

Add qualified Transformers FP32 export for standard Parakeet clients

Browse files

Strict mapping of all723 source tensors; reproducible conversion; actual Buzz offline/multilingual checks;120-clip export comparison reports5.43% vs source-NeMo5.34% WER separately from published model benchmark. Existing artifacts and metadata preserved.

README.md CHANGED
@@ -45,6 +45,14 @@ Use Orukeet for recordings, media, batch transcription, server workers and inter
45
 
46
  [Code](https://github.com/Oruk-AI/orukeet) · [OpenWhispr PR](https://github.com/OpenWhispr/openwhispr/pull/2085) · [Technical report](orukeet-technical-report.pdf) · [Artifact hashes](ARTIFACTS.json)
47
 
 
 
 
 
 
 
 
 
48
  ## Run Orukeet with NeMo
49
 
50
  Use a CUDA-enabled PyTorch environment with `nemo_toolkit[asr]==3.0.0` and `huggingface-hub`. The [recorded source environment](https://github.com/Oruk-AI/orukeet/blob/main/evidence/standard-asr-20260908/runtime.json) lists the exact package versions used for evaluation.
 
45
 
46
  [Code](https://github.com/Oruk-AI/orukeet) · [OpenWhispr PR](https://github.com/OpenWhispr/openwhispr/pull/2085) · [Technical report](orukeet-technical-report.pdf) · [Artifact hashes](ARTIFACTS.json)
47
 
48
+ ## Run Orukeet with Transformers
49
+
50
+ A standard FP32 Transformers export is available at the repository root. It uses
51
+ `ParakeetForTDT` without custom remote code and works with Buzz's existing Hugging
52
+ Face model option. See [setup, conversion provenance and runtime qualification](transformers/README.md).
53
+ The NeMo evaluation below remains the source-model benchmark; the Transformers
54
+ export has separate compatibility measurements.
55
+
56
  ## Run Orukeet with NeMo
57
 
58
  Use a CUDA-enabled PyTorch environment with `nemo_toolkit[asr]==3.0.0` and `huggingface-hub`. The [recorded source environment](https://github.com/Oruk-AI/orukeet/blob/main/evidence/standard-asr-20260908/runtime.json) lists the exact package versions used for evaluation.
config.json ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "ParakeetForTDT"
4
+ ],
5
+ "blank_token_id": 8192,
6
+ "decoder_hidden_size": 640,
7
+ "dtype": "float32",
8
+ "durations": [
9
+ 0,
10
+ 1,
11
+ 2,
12
+ 3,
13
+ 4
14
+ ],
15
+ "encoder_config": {
16
+ "activation_dropout": 0.1,
17
+ "attention_bias": false,
18
+ "attention_dropout": 0.1,
19
+ "conv_kernel_size": 9,
20
+ "convolution_bias": false,
21
+ "dropout": 0.1,
22
+ "dropout_positions": 0.0,
23
+ "hidden_act": "silu",
24
+ "hidden_size": 1024,
25
+ "initializer_range": 0.02,
26
+ "intermediate_size": 4096,
27
+ "layerdrop": 0.1,
28
+ "max_position_embeddings": 5000,
29
+ "model_type": "parakeet_encoder",
30
+ "num_attention_heads": 8,
31
+ "num_hidden_layers": 24,
32
+ "num_key_value_heads": 8,
33
+ "num_mel_bins": 128,
34
+ "scale_input": false,
35
+ "subsampling_conv_channels": 256,
36
+ "subsampling_conv_kernel_size": 3,
37
+ "subsampling_conv_stride": 2,
38
+ "subsampling_factor": 8
39
+ },
40
+ "hidden_act": "relu",
41
+ "initializer_range": 0.02,
42
+ "is_encoder_decoder": true,
43
+ "max_symbols_per_step": 10,
44
+ "model_type": "parakeet_tdt",
45
+ "num_decoder_layers": 2,
46
+ "pad_token_id": 2,
47
+ "transformers_version": "5.15.1",
48
+ "vocab_size": 8193
49
+ }
generation_config.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "decoder_start_token_id": 8192,
4
+ "output_attentions": false,
5
+ "output_hidden_states": false,
6
+ "pad_token_id": 2,
7
+ "suppress_tokens": [
8
+ 8193,
9
+ 8194,
10
+ 8195,
11
+ 8196,
12
+ 8197
13
+ ],
14
+ "transformers_version": "5.15.1"
15
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:092cff73445117d4d234c5e4fb37d86ad16a348be3426e10ff38c79d35758569
3
+ size 2508311120
processor_config.json ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "blank_token": "<blank>",
3
+ "decoder_type": "tdt",
4
+ "feature_extractor": {
5
+ "feature_extractor_type": "ParakeetFeatureExtractor",
6
+ "feature_size": 128,
7
+ "hop_length": 160,
8
+ "n_fft": 512,
9
+ "padding_side": "right",
10
+ "padding_value": 0.0,
11
+ "preemphasis": 0.97,
12
+ "return_attention_mask": true,
13
+ "sampling_rate": 16000,
14
+ "win_length": 400
15
+ },
16
+ "processor_class": "ParakeetProcessor"
17
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "backend": "tokenizers",
3
+ "clean_up_tokenization_spaces": false,
4
+ "model_max_length": 1000000000000000019884624838656,
5
+ "pad_token": "<pad>",
6
+ "processor_class": "ParakeetProcessor",
7
+ "tokenizer_class": "ParakeetTokenizer",
8
+ "unk_token": "<unk>"
9
+ }
transformers/LICENSE-CONVERTER ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright 2018- The Hugging Face team. All rights reserved.
2
+
3
+ Apache License
4
+ Version 2.0, January 2004
5
+ http://www.apache.org/licenses/
6
+
7
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
8
+
9
+ 1. Definitions.
10
+
11
+ "License" shall mean the terms and conditions for use, reproduction,
12
+ and distribution as defined by Sections 1 through 9 of this document.
13
+
14
+ "Licensor" shall mean the copyright owner or entity authorized by
15
+ the copyright owner that is granting the License.
16
+
17
+ "Legal Entity" shall mean the union of the acting entity and all
18
+ other entities that control, are controlled by, or are under common
19
+ control with that entity. For the purposes of this definition,
20
+ "control" means (i) the power, direct or indirect, to cause the
21
+ direction or management of such entity, whether by contract or
22
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
23
+ outstanding shares, or (iii) beneficial ownership of such entity.
24
+
25
+ "You" (or "Your") shall mean an individual or Legal Entity
26
+ exercising permissions granted by this License.
27
+
28
+ "Source" form shall mean the preferred form for making modifications,
29
+ including but not limited to software source code, documentation
30
+ source, and configuration files.
31
+
32
+ "Object" form shall mean any form resulting from mechanical
33
+ transformation or translation of a Source form, including but
34
+ not limited to compiled object code, generated documentation,
35
+ and conversions to other media types.
36
+
37
+ "Work" shall mean the work of authorship, whether in Source or
38
+ Object form, made available under the License, as indicated by a
39
+ copyright notice that is included in or attached to the work
40
+ (an example is provided in the Appendix below).
41
+
42
+ "Derivative Works" shall mean any work, whether in Source or Object
43
+ form, that is based on (or derived from) the Work and for which the
44
+ editorial revisions, annotations, elaborations, or other modifications
45
+ represent, as a whole, an original work of authorship. For the purposes
46
+ of this License, Derivative Works shall not include works that remain
47
+ separable from, or merely link (or bind by name) to the interfaces of,
48
+ the Work and Derivative Works thereof.
49
+
50
+ "Contribution" shall mean any work of authorship, including
51
+ the original version of the Work and any modifications or additions
52
+ to that Work or Derivative Works thereof, that is intentionally
53
+ submitted to Licensor for inclusion in the Work by the copyright owner
54
+ or by an individual or Legal Entity authorized to submit on behalf of
55
+ the copyright owner. For the purposes of this definition, "submitted"
56
+ means any form of electronic, verbal, or written communication sent
57
+ to the Licensor or its representatives, including but not limited to
58
+ communication on electronic mailing lists, source code control systems,
59
+ and issue tracking systems that are managed by, or on behalf of, the
60
+ Licensor for the purpose of discussing and improving the Work, but
61
+ excluding communication that is conspicuously marked or otherwise
62
+ designated in writing by the copyright owner as "Not a Contribution."
63
+
64
+ "Contributor" shall mean Licensor and any individual or Legal Entity
65
+ on behalf of whom a Contribution has been received by Licensor and
66
+ subsequently incorporated within the Work.
67
+
68
+ 2. Grant of Copyright License. Subject to the terms and conditions of
69
+ this License, each Contributor hereby grants to You a perpetual,
70
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
71
+ copyright license to reproduce, prepare Derivative Works of,
72
+ publicly display, publicly perform, sublicense, and distribute the
73
+ Work and such Derivative Works in Source or Object form.
74
+
75
+ 3. Grant of Patent License. Subject to the terms and conditions of
76
+ this License, each Contributor hereby grants to You a perpetual,
77
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
78
+ (except as stated in this section) patent license to make, have made,
79
+ use, offer to sell, sell, import, and otherwise transfer the Work,
80
+ where such license applies only to those patent claims licensable
81
+ by such Contributor that are necessarily infringed by their
82
+ Contribution(s) alone or by combination of their Contribution(s)
83
+ with the Work to which such Contribution(s) was submitted. If You
84
+ institute patent litigation against any entity (including a
85
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
86
+ or a Contribution incorporated within the Work constitutes direct
87
+ or contributory patent infringement, then any patent licenses
88
+ granted to You under this License for that Work shall terminate
89
+ as of the date such litigation is filed.
90
+
91
+ 4. Redistribution. You may reproduce and distribute copies of the
92
+ Work or Derivative Works thereof in any medium, with or without
93
+ modifications, and in Source or Object form, provided that You
94
+ meet the following conditions:
95
+
96
+ (a) You must give any other recipients of the Work or
97
+ Derivative Works a copy of this License; and
98
+
99
+ (b) You must cause any modified files to carry prominent notices
100
+ stating that You changed the files; and
101
+
102
+ (c) You must retain, in the Source form of any Derivative Works
103
+ that You distribute, all copyright, patent, trademark, and
104
+ attribution notices from the Source form of the Work,
105
+ excluding those notices that do not pertain to any part of
106
+ the Derivative Works; and
107
+
108
+ (d) If the Work includes a "NOTICE" text file as part of its
109
+ distribution, then any Derivative Works that You distribute must
110
+ include a readable copy of the attribution notices contained
111
+ within such NOTICE file, excluding those notices that do not
112
+ pertain to any part of the Derivative Works, in at least one
113
+ of the following places: within a NOTICE text file distributed
114
+ as part of the Derivative Works; within the Source form or
115
+ documentation, if provided along with the Derivative Works; or,
116
+ within a display generated by the Derivative Works, if and
117
+ wherever such third-party notices normally appear. The contents
118
+ of the NOTICE file are for informational purposes only and
119
+ do not modify the License. You may add Your own attribution
120
+ notices within Derivative Works that You distribute, alongside
121
+ or as an addendum to the NOTICE text from the Work, provided
122
+ that such additional attribution notices cannot be construed
123
+ as modifying the License.
124
+
125
+ You may add Your own copyright statement to Your modifications and
126
+ may provide additional or different license terms and conditions
127
+ for use, reproduction, or distribution of Your modifications, or
128
+ for any such Derivative Works as a whole, provided Your use,
129
+ reproduction, and distribution of the Work otherwise complies with
130
+ the conditions stated in this License.
131
+
132
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
133
+ any Contribution intentionally submitted for inclusion in the Work
134
+ by You to the Licensor shall be under the terms and conditions of
135
+ this License, without any additional terms or conditions.
136
+ Notwithstanding the above, nothing herein shall supersede or modify
137
+ the terms of any separate license agreement you may have executed
138
+ with Licensor regarding such Contributions.
139
+
140
+ 6. Trademarks. This License does not grant permission to use the trade
141
+ names, trademarks, service marks, or product names of the Licensor,
142
+ except as required for reasonable and customary use in describing the
143
+ origin of the Work and reproducing the content of the NOTICE file.
144
+
145
+ 7. Disclaimer of Warranty. Unless required by applicable law or
146
+ agreed to in writing, Licensor provides the Work (and each
147
+ Contributor provides its Contributions) on an "AS IS" BASIS,
148
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
149
+ implied, including, without limitation, any warranties or conditions
150
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
151
+ PARTICULAR PURPOSE. You are solely responsible for determining the
152
+ appropriateness of using or redistributing the Work and assume any
153
+ risks associated with Your exercise of permissions under this License.
154
+
155
+ 8. Limitation of Liability. In no event and under no legal theory,
156
+ whether in tort (including negligence), contract, or otherwise,
157
+ unless required by applicable law (such as deliberate and grossly
158
+ negligent acts) or agreed to in writing, shall any Contributor be
159
+ liable to You for damages, including any direct, indirect, special,
160
+ incidental, or consequential damages of any character arising as a
161
+ result of this License or out of the use or inability to use the
162
+ Work (including but not limited to damages for loss of goodwill,
163
+ work stoppage, computer failure or malfunction, or any and all
164
+ other commercial damages or losses), even if such Contributor
165
+ has been advised of the possibility of such damages.
166
+
167
+ 9. Accepting Warranty or Additional Liability. While redistributing
168
+ the Work or Derivative Works thereof, You may choose to offer,
169
+ and charge a fee for, acceptance of support, warranty, indemnity,
170
+ or other liability obligations and/or rights consistent with this
171
+ License. However, in accepting such obligations, You may act only
172
+ on Your own behalf and on Your sole responsibility, not on behalf
173
+ of any other Contributor, and only if You agree to indemnify,
174
+ defend, and hold each Contributor harmless for any liability
175
+ incurred by, or claims asserted against, such Contributor by reason
176
+ of your accepting any such warranty or additional liability.
177
+
178
+ END OF TERMS AND CONDITIONS
179
+
180
+ APPENDIX: How to apply the Apache License to your work.
181
+
182
+ To apply the Apache License to your work, attach the following
183
+ boilerplate notice, with the fields enclosed by brackets "[]"
184
+ replaced with your own identifying information. (Don't include
185
+ the brackets!) The text should be enclosed in the appropriate
186
+ comment syntax for the file format. We also recommend that a
187
+ file or class name and description of purpose be included on the
188
+ same "printed page" as the copyright notice for easier
189
+ identification within third-party archives.
190
+
191
+ Copyright [yyyy] [name of copyright owner]
192
+
193
+ Licensed under the Apache License, Version 2.0 (the "License");
194
+ you may not use this file except in compliance with the License.
195
+ You may obtain a copy of the License at
196
+
197
+ http://www.apache.org/licenses/LICENSE-2.0
198
+
199
+ Unless required by applicable law or agreed to in writing, software
200
+ distributed under the License is distributed on an "AS IS" BASIS,
201
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
202
+ See the License for the specific language governing permissions and
203
+ limitations under the License.
transformers/README.md ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Transformers FP32 export
2
+
3
+ This export uses the standard `ParakeetForTDT` implementation in Transformers
4
+ 5.15.1. No custom model code or `trust_remote_code` is required. Root-level
5
+ configuration, processor and safetensors files let applications such as Buzz load
6
+ `oruk/orukeet` through their existing Hugging Face/Parakeet backend.
7
+
8
+ ```sh
9
+ pip install 'torch==2.8.0' 'torchaudio==2.8.0' 'transformers==5.15.1' soundfile
10
+ ```
11
+
12
+ ```python
13
+ import soundfile as sf
14
+ from transformers import AutoModelForTDT, AutoProcessor, pipeline
15
+
16
+ model = AutoModelForTDT.from_pretrained("oruk/orukeet", dtype="float32")
17
+ processor = AutoProcessor.from_pretrained("oruk/orukeet")
18
+ asr = pipeline(
19
+ "automatic-speech-recognition", model=model, device="cpu",
20
+ tokenizer=processor.tokenizer, feature_extractor=processor.feature_extractor,
21
+ )
22
+ audio, sample_rate = sf.read("speech.wav", dtype="float32")
23
+ assert sample_rate == 16000 and audio.ndim == 1
24
+ print(asr(audio)["text"])
25
+ ```
26
+
27
+ Use 16 kHz mono audio. The model detects language automatically and does not
28
+ provide translation, speaker labels or prompt-conditioned transcription. Buzz
29
+ currently returns 30-second chunk boundaries, not aligned word timestamps.
30
+ Downloading the required configuration uses Hugging Face's normal model download
31
+ accounting. Cached local loading does not require an extra tracking request.
32
+
33
+ ## Conversion
34
+
35
+ The source is `orukeet-v0.1.0.nemo` at revision
36
+ `555136b50265a132d4cea0d35560c26fc4f657ab`, SHA-256
37
+ `031c8ddab4845aeced904a7cde8e8aa57993b2e344716cf83a545b079c473b56`.
38
+ All 723 mapped tensors load with `strict=True`: 627,008,134 parameters in FP32.
39
+ The materialized Gabor filters are preserved as ordinary convolution weights.
40
+
41
+ The bundled upstream converter comes from Transformers commit
42
+ `6c6bac29f50c8aad5d1f06c72b2f892a6e335dd0`. The wrapper verifies the source hash,
43
+ extracts it with the data safety filter, and requires exact state-dictionary and
44
+ tokenizer compatibility before saving. Reproduce in Python 3.13:
45
+
46
+ ```sh
47
+ pip install 'torch==2.8.0' 'transformers==5.15.1' protobuf sentencepiece pyyaml
48
+ python convert.py /path/to/output
49
+ ```
50
+
51
+ Download both `convert.py` and `convert_nemo_to_hf.py` from this directory.
52
+ [`manifest.json`](manifest.json) records every exported runtime file's hash and size.
53
+ Weights remain CC BY-SA 4.0 with NVIDIA attribution; see the root `NOTICE.md` and
54
+ `LICENSE-WEIGHTS`. The upstream converter is Apache-2.0; see `LICENSE-CONVERTER`.
55
+
56
+ ## Qualification
57
+
58
+ On Apple M5 Max CPU with PyTorch 2.8.0 and Transformers 5.15.1:
59
+
60
+ - The actual Buzz transcription path passed English, German, Spanish and French
61
+ repeated transcription, 0.1/1/5-second silence, a recording spanning two chunks,
62
+ and local loading/inference with socket connections disabled.
63
+ - A fixed 120-clip, six-language FLEURS validation compatibility sample produced
64
+ the same normalized transcript as the recorded source-NeMo output for 117 clips.
65
+ Pooled WER was **5.43% for this export versus 5.34% for source NeMo** using the
66
+ same normalization: two additional word errors across 2,433 reference words.
67
+ - The sample contained 1,257.82 seconds of audio and took 217.64 seconds of inference
68
+ across eight CPU threads (about 0.17 real-time factor). Other work ran on the
69
+ machine during this check; this is a runtime receipt, not a controlled speed
70
+ comparison with Parakeet.
71
+
72
+ This small compatibility sample is not a new held-out benchmark. The published
73
+ 25-language NeMo results in the model card do not automatically transfer to this
74
+ export. Per-language measurements and normalization are in
75
+ [`qualification.json`](qualification.json).
transformers/convert.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Strict, reproducible FP32 export using the upstream Parakeet converter."""
2
+ from pathlib import Path
3
+ import hashlib
4
+ import importlib.util
5
+ import json
6
+ import tarfile
7
+ import torch
8
+ import yaml
9
+ from transformers import ParakeetForTDT, AutoProcessor
10
+
11
+ import argparse
12
+ from huggingface_hub import hf_hub_download
13
+ parser = argparse.ArgumentParser(description=__doc__)
14
+ parser.add_argument("output", type=Path)
15
+ parser.add_argument("--cache-dir")
16
+ args = parser.parse_args()
17
+ ROOT = args.output.resolve()
18
+ ROOT.mkdir(parents=True, exist_ok=True)
19
+ REVISION = "555136b50265a132d4cea0d35560c26fc4f657ab"
20
+ SOURCE_SHA = "031c8ddab4845aeced904a7cde8e8aa57993b2e344716cf83a545b079c473b56"
21
+ CONVERTER_REV = "6c6bac29f50c8aad5d1f06c72b2f892a6e335dd0"
22
+ source = Path(hf_hub_download("oruk/orukeet", "orukeet-v0.1.0.nemo", revision=REVISION, cache_dir=args.cache_dir))
23
+ with source.open("rb") as handle:
24
+ assert hashlib.file_digest(handle, "sha256").hexdigest() == SOURCE_SHA
25
+ extracted = ROOT / ".nemo-source"
26
+ extracted.mkdir(exist_ok=True)
27
+ with tarfile.open(source) as archive:
28
+ archive.extractall(extracted, filter="data")
29
+ config = yaml.safe_load((extracted / "model_config.yaml").read_text())
30
+ spec = importlib.util.spec_from_file_location("upstream_converter", Path(__file__).with_name("convert_nemo_to_hf.py"))
31
+ converter = importlib.util.module_from_spec(spec)
32
+ spec.loader.exec_module(converter)
33
+ files = {"model_weights": str(extracted / "model_weights.ckpt"),
34
+ "tokenizer_model_file": str(extracted / config["tokenizer"]["model_path"].removeprefix("nemo:"))}
35
+ output = ROOT
36
+ output.mkdir(exist_ok=True)
37
+ converter.write_processor(config, files, str(output), "tdt")
38
+ model_config = converter.convert_tdt_config(config, converter.convert_encoder_config(config))
39
+ state_dict = converter.load_and_convert_tdt_state_dict(files, model_config.vocab_size)
40
+ with torch.device("meta"):
41
+ model = ParakeetForTDT(model_config)
42
+ result = model.load_state_dict(state_dict, strict=True, assign=True)
43
+ assert not result.missing_keys and not result.unexpected_keys
44
+ model.eval()
45
+ model.generation_config.decoder_start_token_id = model.config.blank_token_id
46
+ model.generation_config.suppress_tokens = list(range(model.config.vocab_size, model.config.vocab_size + len(model.config.durations)))
47
+ model.save_pretrained(output, max_shard_size="4GB")
48
+ processor = AutoProcessor.from_pretrained(output, local_files_only=True)
49
+ assert processor.tokenizer.convert_tokens_to_ids("<blank>") == model.config.blank_token_id
50
+ assert len(processor.tokenizer) == model.config.vocab_size
51
+ proof = {
52
+ "source_repo": "oruk/orukeet", "source_revision": REVISION,
53
+ "source_filename": source.name, "source_sha256": SOURCE_SHA,
54
+ "converter_url": f"https://github.com/huggingface/transformers/blob/{CONVERTER_REV}/src/transformers/models/parakeet/convert_nemo_to_hf.py",
55
+ "dtype": str(next(model.parameters()).dtype), "strict_state_dict": True,
56
+ "tensor_count": len(state_dict), "parameter_count": sum(p.numel() for p in model.parameters()),
57
+ "vocab_size": model.config.vocab_size,
58
+ "files": {}
59
+ }
60
+ for path in sorted(output.iterdir()):
61
+ if path.is_file():
62
+ with path.open("rb") as handle:
63
+ proof["files"][path.name] = {"sha256": hashlib.file_digest(handle, "sha256").hexdigest(), "bytes": path.stat().st_size}
64
+ (ROOT / "export-provenance.json").write_text(json.dumps(proof, indent=2) + "\n")
65
+ print(json.dumps(proof, indent=2))
transformers/convert_nemo_to_hf.py ADDED
@@ -0,0 +1,577 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import argparse
16
+ import gc
17
+ import os
18
+ import re
19
+ import tarfile
20
+
21
+ import torch
22
+ import yaml
23
+ from tokenizers import AddedToken
24
+
25
+ from transformers import (
26
+ ParakeetCTCConfig,
27
+ ParakeetEncoderConfig,
28
+ ParakeetFeatureExtractor,
29
+ ParakeetForCTC,
30
+ ParakeetForRNNT,
31
+ ParakeetForTDT,
32
+ ParakeetProcessor,
33
+ ParakeetRNNTConfig,
34
+ ParakeetTDTConfig,
35
+ ParakeetTokenizer,
36
+ )
37
+ from transformers.convert_slow_tokenizer import ParakeetConverter
38
+ from transformers.utils.hub import cached_file
39
+
40
+
41
+ NEMO_TO_HF_WEIGHT_MAPPING = {
42
+ r"encoder\.pre_encode\.conv\.": r"encoder.subsampling.layers.",
43
+ r"encoder\.pre_encode\.out\.": r"encoder.subsampling.linear.",
44
+ r"encoder\.pos_enc\.": r"encoder.encode_positions.",
45
+ r"encoder\.layers\.(\d+)\.conv\.batch_norm\.": r"encoder.layers.\1.conv.norm.",
46
+ r"decoder\.decoder_layers\.0\.(weight|bias)": r"ctc_head.\1",
47
+ r"linear_([kv])": r"\1_proj",
48
+ r"linear_out": r"o_proj",
49
+ r"linear_q": r"q_proj",
50
+ r"pos_bias_([uv])": r"bias_\1",
51
+ r"linear_pos": r"relative_k_proj",
52
+ }
53
+
54
+ # Additional mappings for TDT decoder and joint network
55
+ NEMO_TDT_WEIGHT_MAPPING = {
56
+ r"decoder\.prediction\.embed\.": r"decoder.embedding.",
57
+ r"decoder\.prediction\.dec_rnn\.lstm\.": r"decoder.lstm.",
58
+ r"joint\.enc\.": r"encoder_projector.",
59
+ r"joint\.pred\.": r"decoder.decoder_projector.",
60
+ r"joint\.joint_net\.2\.": r"joint.head.",
61
+ }
62
+
63
+
64
+ def convert_key(key, mapping):
65
+ for pattern, replacement in mapping.items():
66
+ key = re.sub(pattern, replacement, key)
67
+ return key
68
+
69
+
70
+ def extract_nemo_archive(nemo_file_path: str, extract_dir: str) -> dict[str, str]:
71
+ """Extract .nemo file (tar archive) and return paths to important files."""
72
+ print(f"Extracting NeMo archive: {nemo_file_path}")
73
+
74
+ with tarfile.open(nemo_file_path, "r", encoding="utf-8") as tar:
75
+ tar.extractall(extract_dir)
76
+
77
+ all_files = []
78
+ for root, dirs, files in os.walk(extract_dir):
79
+ for file in files:
80
+ file_path = os.path.join(root, file)
81
+ all_files.append(file_path)
82
+
83
+ print(f"All extracted files: {[os.path.basename(f) for f in all_files]}")
84
+
85
+ model_files = {}
86
+ for root, dirs, files in os.walk(extract_dir):
87
+ for file in files:
88
+ file_path = os.path.join(root, file)
89
+ file_lower = file.lower()
90
+
91
+ if (
92
+ file.endswith(".pt")
93
+ or file.endswith(".pth")
94
+ or file.endswith(".ckpt")
95
+ or file.endswith(".bin")
96
+ or "model" in file_lower
97
+ and ("weight" in file_lower or "state" in file_lower)
98
+ or file_lower == "model.pt"
99
+ or file_lower == "pytorch_model.bin"
100
+ or file_lower == "model_weights.ckpt"
101
+ ):
102
+ model_files["model_weights"] = file_path
103
+ print(f"Found model weights: {file}")
104
+
105
+ elif (
106
+ file == "model_config.yaml"
107
+ or file == "config.yaml"
108
+ or (file.endswith(".yaml") and "config" in file_lower)
109
+ ):
110
+ if "model_config" not in model_files:
111
+ model_files["model_config"] = file_path
112
+ print(f"Found config file: {file}")
113
+ if file == "model_config.yaml":
114
+ model_files["model_config"] = file_path
115
+
116
+ elif (
117
+ file.endswith(".vocab")
118
+ or file.endswith(".model")
119
+ or file.endswith(".txt")
120
+ or ("tokenizer" in file_lower and (file.endswith(".vocab") or file.endswith(".model")))
121
+ ):
122
+ if "tokenizer_model_file" not in model_files or file.endswith(".model"):
123
+ model_files["tokenizer_model_file"] = file_path
124
+ print(f"Found tokenizer model file: {file}")
125
+ else:
126
+ print(f"Found additional vocabulary file (using existing): {file}")
127
+
128
+ print(f"Found model files: {list(model_files.keys())}")
129
+
130
+ if "model_weights" not in model_files:
131
+ raise FileNotFoundError(
132
+ f"Could not find model weights file in {nemo_file_path}. "
133
+ f"Expected files with extensions: .pt, .pth, .ckpt, .bin. "
134
+ f"Found files: {[os.path.basename(f) for f in all_files]}"
135
+ )
136
+
137
+ if "model_config" not in model_files:
138
+ raise FileNotFoundError(
139
+ f"Could not find model config file in {nemo_file_path}. "
140
+ f"Expected: model_config.yaml or config.yaml. "
141
+ f"Found files: {[os.path.basename(f) for f in all_files]}"
142
+ )
143
+
144
+ return model_files
145
+
146
+
147
+ def write_processor(
148
+ nemo_config: dict, model_files, output_dir, model_type, push_to_repo_id=None, create_pr=True, revision=None
149
+ ):
150
+ tokenizer_converted = ParakeetConverter(model_files["tokenizer_model_file"]).converted()
151
+ tokenizer_converted_fast = ParakeetTokenizer(
152
+ tokenizer_object=tokenizer_converted,
153
+ clean_up_tokenization_spaces=False,
154
+ )
155
+
156
+ if tokenizer_converted_fast.convert_tokens_to_ids("<unk>") is None:
157
+ # Normally CTC and TDT already have
158
+ tokenizer_converted_fast.add_tokens([AddedToken("<unk>", normalized=False, special=True)])
159
+ print(f"Added <unk> token at ID: {tokenizer_converted_fast.convert_tokens_to_ids('<unk>')}")
160
+
161
+ if model_type == "rnnt":
162
+ # RNN-T (unlike TDT) has no dedicated pad token in its NeMo vocab. NeMo's blank is the final vocab entry,
163
+ # i.e. `config.blank_token_id == len(labels)`, and the joint head emits exactly `len(labels) + 1` logits.
164
+ # Add `<blank>` *first* so it lands on that id (no `<pad>` is appended to push it past the model's vocab),
165
+ # and reuse it as the pad token: decoding already skips the pad id, and padding decoder/label tensors with
166
+ # the blank id keeps every id within the joint vocab. This aligns the tokenizer's `<blank>` id with the
167
+ # model's blank logit, so the processor can prepend `<blank>` to build decoder_input_ids unchanged.
168
+ tokenizer_converted_fast.add_tokens([AddedToken("<blank>", normalized=False, special=True)])
169
+ print(f"Added <blank> token at ID: {tokenizer_converted_fast.convert_tokens_to_ids('<blank>')}")
170
+ pad_token = AddedToken("<blank>", normalized=False, special=True)
171
+ else:
172
+ if tokenizer_converted_fast.convert_tokens_to_ids("<pad>") is None:
173
+ # Normally CTC doesn't have while TDT has at token id = 2
174
+ tokenizer_converted_fast.add_tokens([AddedToken("<pad>", normalized=False, special=True)])
175
+ print(f"Added <pad> token at ID: {tokenizer_converted_fast.convert_tokens_to_ids('<pad>')}")
176
+ if model_type == "tdt":
177
+ # TDT needs a separate blank token (its vocab already carries a distinct <pad>)
178
+ tokenizer_converted_fast.add_tokens([AddedToken("<blank>", normalized=False, special=True)])
179
+ print(f"Added <blank> token at ID: {tokenizer_converted_fast.convert_tokens_to_ids('<blank>')}")
180
+ pad_token = AddedToken("<pad>", normalized=False, special=True)
181
+ tokenizer_converted_fast.add_special_tokens(
182
+ {
183
+ "pad_token": pad_token,
184
+ "unk_token": AddedToken("<unk>", normalized=False, special=True),
185
+ }
186
+ )
187
+
188
+ feature_extractor_keys_to_ignore = ["_target_", "pad_to", "frame_splicing", "dither", "normalize", "window", "log"]
189
+ feature_extractor_config_keys_mapping = {
190
+ "sample_rate": "sampling_rate",
191
+ "window_size": "win_length",
192
+ "window_stride": "hop_length",
193
+ "window": "window",
194
+ "n_fft": "n_fft",
195
+ "log": "log",
196
+ "features": "feature_size",
197
+ "dither": "dither",
198
+ "pad_to": "pad_to",
199
+ "pad_value": "padding_value",
200
+ "frame_splicing": "frame_splicing",
201
+ "preemphasis": "preemphasis",
202
+ "hop_length": "hop_length",
203
+ }
204
+ converted_feature_extractor_config = {}
205
+
206
+ for key, value in nemo_config["preprocessor"].items():
207
+ if key in feature_extractor_keys_to_ignore:
208
+ continue
209
+ if key in feature_extractor_config_keys_mapping:
210
+ if key in ["window_size", "window_stride"]:
211
+ value = int(value * nemo_config["preprocessor"]["sample_rate"])
212
+ converted_feature_extractor_config[feature_extractor_config_keys_mapping[key]] = value
213
+ else:
214
+ raise ValueError(f"Key {key} not found in feature_extractor_keys_mapping")
215
+
216
+ feature_extractor = ParakeetFeatureExtractor(**converted_feature_extractor_config)
217
+ processor = ParakeetProcessor(
218
+ feature_extractor=feature_extractor,
219
+ tokenizer=tokenizer_converted_fast,
220
+ # Drives the decoding/timestamp rules (CTC collapses repeats; TDT uses predicted durations + punctuation
221
+ # attach; RNN-T uses single-frame spans).
222
+ decoder_type=model_type,
223
+ )
224
+ processor.save_pretrained(output_dir)
225
+
226
+ if push_to_repo_id:
227
+ commit_info = processor.push_to_hub(push_to_repo_id, create_pr=create_pr, revision=revision)
228
+ if create_pr and hasattr(commit_info, "pr_url") and commit_info.pr_url:
229
+ pr_num = commit_info.pr_url.rstrip("/").split("/")[-1]
230
+ return f"refs/pr/{pr_num}"
231
+
232
+ return revision
233
+
234
+
235
+ def convert_encoder_config(nemo_config):
236
+ """Convert NeMo encoder config to HF encoder config."""
237
+ encoder_keys_to_ignore = [
238
+ "att_context_size",
239
+ "causal_downsampling",
240
+ "stochastic_depth_start_layer",
241
+ "feat_out",
242
+ "stochastic_depth_drop_prob",
243
+ "_target_",
244
+ "ff_expansion_factor",
245
+ "untie_biases",
246
+ "att_context_style",
247
+ "self_attention_model",
248
+ "conv_norm_type",
249
+ "subsampling",
250
+ "stochastic_depth_mode",
251
+ "conv_context_size",
252
+ "dropout_pre_encoder",
253
+ "reduction",
254
+ "reduction_factor",
255
+ "reduction_position",
256
+ ]
257
+ encoder_config_keys_mapping = {
258
+ "d_model": "hidden_size",
259
+ "n_heads": "num_attention_heads",
260
+ "n_layers": "num_hidden_layers",
261
+ "feat_in": "num_mel_bins",
262
+ "conv_kernel_size": "conv_kernel_size",
263
+ "subsampling_factor": "subsampling_factor",
264
+ "subsampling_conv_channels": "subsampling_conv_channels",
265
+ "pos_emb_max_len": "max_position_embeddings",
266
+ "dropout": "dropout",
267
+ "dropout_emb": "dropout_positions",
268
+ "dropout_att": "attention_dropout",
269
+ "xscaling": "scale_input",
270
+ "use_bias": "attention_bias",
271
+ }
272
+ converted_encoder_config = {}
273
+
274
+ for key, value in nemo_config["encoder"].items():
275
+ if key in encoder_keys_to_ignore:
276
+ continue
277
+ if key in encoder_config_keys_mapping:
278
+ converted_encoder_config[encoder_config_keys_mapping[key]] = value
279
+ if key == "use_bias":
280
+ converted_encoder_config["convolution_bias"] = value
281
+ else:
282
+ raise ValueError(f"Key {key} not found in encoder_config_keys_mapping")
283
+
284
+ return ParakeetEncoderConfig(**converted_encoder_config)
285
+
286
+
287
+ def load_and_convert_state_dict(model_files):
288
+ """Load NeMo state dict and convert keys to HF format."""
289
+ state_dict = torch.load(model_files["model_weights"], map_location="cpu", weights_only=True)
290
+ converted_state_dict = {}
291
+ for key, value in state_dict.items():
292
+ if key.endswith("featurizer.window") or key.endswith("featurizer.fb"):
293
+ print(f"Skipping preprocessing weight: {key}")
294
+ continue
295
+ converted_key = convert_key(key, NEMO_TO_HF_WEIGHT_MAPPING)
296
+ converted_state_dict[converted_key] = value
297
+
298
+ return converted_state_dict
299
+
300
+
301
+ def write_ctc_model(encoder_config, converted_state_dict, output_dir, push_to_repo_id=None, revision=None):
302
+ """Write CTC model using encoder config and converted state dict."""
303
+ model_config = ParakeetCTCConfig(encoder_config=encoder_config)
304
+
305
+ print("Loading the checkpoint in a Parakeet CTC model.")
306
+ with torch.device("meta"):
307
+ model = ParakeetForCTC(model_config)
308
+ model.load_state_dict(converted_state_dict, strict=True, assign=True)
309
+ print("Checkpoint loaded successfully.")
310
+ del model.config._name_or_path
311
+
312
+ print("Saving the model.")
313
+ model.save_pretrained(output_dir)
314
+
315
+ if push_to_repo_id:
316
+ model.push_to_hub(push_to_repo_id, revision=revision)
317
+
318
+ del model
319
+
320
+ gc.collect()
321
+ print("Reloading the model to check if it's saved correctly.")
322
+ ParakeetForCTC.from_pretrained(output_dir, dtype=torch.bfloat16, device_map="auto")
323
+ print("Model reloaded successfully.")
324
+
325
+
326
+ def convert_tdt_config(nemo_config, encoder_config):
327
+ """Convert NeMo TDT config to HF TDT config."""
328
+ decoder_config = nemo_config["decoder"]
329
+ decoding_config = nemo_config["decoding"]
330
+ labels = nemo_config["labels"]
331
+ blank_token_id = len(labels)
332
+ vocab_size = len(labels) + 1 # +1 for blank token, which is added to tokenizer
333
+
334
+ prednet = decoder_config.get("prednet", {})
335
+ decoder_hidden_size = prednet.get("pred_hidden", 640)
336
+ num_decoder_layers = prednet.get("pred_rnn_layers", 2)
337
+ durations = decoding_config.get("durations", [0, 1, 2, 3, 4])
338
+ print(
339
+ f"TDT config: vocab_size={vocab_size} (including blank token), "
340
+ f"decoder_hidden={decoder_hidden_size}, "
341
+ f"decoder_layers={num_decoder_layers}, durations={durations}, "
342
+ )
343
+
344
+ return ParakeetTDTConfig(
345
+ vocab_size=vocab_size,
346
+ decoder_hidden_size=decoder_hidden_size,
347
+ num_decoder_layers=num_decoder_layers,
348
+ durations=durations,
349
+ hidden_act="relu",
350
+ max_symbols_per_step=10,
351
+ encoder_config=encoder_config.to_dict(),
352
+ pad_token_id=labels.index("<pad>"),
353
+ blank_token_id=blank_token_id, # blank token is different from pad token for TDT
354
+ )
355
+
356
+
357
+ def load_and_convert_tdt_state_dict(model_files, vocab_size):
358
+ """Load NeMo TDT state dict and convert keys to HF format, splitting combined head."""
359
+ state_dict = torch.load(model_files["model_weights"], map_location="cpu", weights_only=True)
360
+ converted_state_dict = {}
361
+
362
+ all_mappings = {**NEMO_TO_HF_WEIGHT_MAPPING, **NEMO_TDT_WEIGHT_MAPPING}
363
+
364
+ for key, value in state_dict.items():
365
+ if key.endswith("featurizer.window") or key.endswith("featurizer.fb"):
366
+ print(f"Skipping preprocessing weight: {key}")
367
+ continue
368
+
369
+ converted_key = convert_key(key, all_mappings)
370
+ converted_state_dict[converted_key] = value
371
+
372
+ return converted_state_dict
373
+
374
+
375
+ def write_tdt_model(nemo_config, encoder_config, model_files, output_dir, push_to_repo_id=None, revision=None):
376
+ """Write TDT model using encoder config, TDT config, and converted state dict."""
377
+ model_config = convert_tdt_config(nemo_config, encoder_config)
378
+ print(f"Converted TDT config: {model_config}")
379
+
380
+ converted_state_dict = load_and_convert_tdt_state_dict(model_files, model_config.vocab_size)
381
+
382
+ print("Loading the checkpoint in a Parakeet TDT model.")
383
+ with torch.device("meta"):
384
+ model = ParakeetForTDT(model_config)
385
+
386
+ missing_keys, unexpected_keys = model.load_state_dict(converted_state_dict, strict=False, assign=True)
387
+
388
+ if missing_keys:
389
+ print(f"Warning: Missing keys: {missing_keys}")
390
+ if unexpected_keys:
391
+ print(f"Warning: Unexpected keys: {unexpected_keys}")
392
+
393
+ if not missing_keys and not unexpected_keys:
394
+ print("All weights loaded successfully!")
395
+
396
+ del model.config._name_or_path
397
+
398
+ model.generation_config.decoder_start_token_id = model.config.blank_token_id
399
+ model.generation_config.suppress_tokens = list(
400
+ range(model.config.vocab_size, model.config.vocab_size + len(model.config.durations))
401
+ )
402
+
403
+ print("Saving the model.")
404
+ model.save_pretrained(output_dir)
405
+
406
+ if push_to_repo_id:
407
+ model.push_to_hub(push_to_repo_id, revision=revision)
408
+
409
+ del model
410
+
411
+ gc.collect()
412
+ print("Reloading the model to check if it's saved correctly.")
413
+ ParakeetForTDT.from_pretrained(output_dir, dtype=torch.bfloat16, device_map="auto")
414
+ print("Model reloaded successfully.")
415
+
416
+
417
+ def convert_rnnt_config(nemo_config, encoder_config):
418
+ """Convert NeMo RNN-T config to HF RNN-T config (a TDT config with no token durations)."""
419
+ decoder_config = nemo_config["decoder"]
420
+ labels = nemo_config["labels"]
421
+ blank_token_id = len(labels)
422
+ vocab_size = len(labels) + 1 # +1 for blank token, which is added to tokenizer
423
+
424
+ prednet = decoder_config.get("prednet", {})
425
+ decoder_hidden_size = prednet.get("pred_hidden", 640)
426
+ num_decoder_layers = prednet.get("pred_rnn_layers", 2)
427
+ print(
428
+ f"RNN-T config: vocab_size={vocab_size} (including blank token), "
429
+ f"decoder_hidden={decoder_hidden_size}, decoder_layers={num_decoder_layers}"
430
+ )
431
+
432
+ return ParakeetRNNTConfig(
433
+ vocab_size=vocab_size,
434
+ decoder_hidden_size=decoder_hidden_size,
435
+ num_decoder_layers=num_decoder_layers,
436
+ hidden_act="relu",
437
+ max_symbols_per_step=10,
438
+ encoder_config=encoder_config.to_dict(),
439
+ pad_token_id=labels.index("<pad>") if "<pad>" in labels else 0,
440
+ blank_token_id=blank_token_id, # blank token is different from pad token for RNN-T
441
+ )
442
+
443
+
444
+ def write_rnnt_model(nemo_config, encoder_config, model_files, output_dir, push_to_repo_id=None, revision=None):
445
+ """Write RNN-T model using encoder config, RNN-T config, and converted state dict.
446
+
447
+ RNN-T shares the TDT decoder/joint weight layout (the joint head is just `vocab_size` wide, with no
448
+ duration logits), so the TDT state-dict converter is reused as-is.
449
+ """
450
+ model_config = convert_rnnt_config(nemo_config, encoder_config)
451
+ print(f"Converted RNN-T config: {model_config}")
452
+
453
+ converted_state_dict = load_and_convert_tdt_state_dict(model_files, model_config.vocab_size)
454
+
455
+ print("Loading the checkpoint in a Parakeet RNN-T model.")
456
+ with torch.device("meta"):
457
+ model = ParakeetForRNNT(model_config)
458
+
459
+ missing_keys, unexpected_keys = model.load_state_dict(converted_state_dict, strict=False, assign=True)
460
+
461
+ if missing_keys:
462
+ print(f"Warning: Missing keys: {missing_keys}")
463
+ if unexpected_keys:
464
+ print(f"Warning: Unexpected keys: {unexpected_keys}")
465
+
466
+ if not missing_keys and not unexpected_keys:
467
+ print("All weights loaded successfully!")
468
+
469
+ del model.config._name_or_path
470
+
471
+ model.generation_config.decoder_start_token_id = model.config.blank_token_id
472
+
473
+ print("Saving the model.")
474
+ model.save_pretrained(output_dir)
475
+
476
+ if push_to_repo_id:
477
+ model.push_to_hub(push_to_repo_id, revision=revision)
478
+
479
+ del model
480
+
481
+ gc.collect()
482
+ print("Reloading the model to check if it's saved correctly.")
483
+ ParakeetForRNNT.from_pretrained(output_dir, dtype=torch.bfloat16, device_map="auto")
484
+ print("Model reloaded successfully.")
485
+
486
+
487
+ def write_model(nemo_config, model_files, model_type, output_dir, push_to_repo_id=None, revision=None):
488
+ """Main model conversion function."""
489
+ encoder_config = convert_encoder_config(nemo_config)
490
+ print(f"Converted encoder config: {encoder_config}")
491
+
492
+ if model_type == "ctc":
493
+ converted_state_dict = load_and_convert_state_dict(model_files)
494
+ write_ctc_model(encoder_config, converted_state_dict, output_dir, push_to_repo_id, revision)
495
+ elif model_type == "tdt":
496
+ write_tdt_model(nemo_config, encoder_config, model_files, output_dir, push_to_repo_id, revision)
497
+ elif model_type == "rnnt":
498
+ write_rnnt_model(nemo_config, encoder_config, model_files, output_dir, push_to_repo_id, revision)
499
+ else:
500
+ raise ValueError(f"Model type {model_type} not supported.")
501
+
502
+
503
+ def main(
504
+ hf_repo_id,
505
+ output_dir,
506
+ model_type,
507
+ push_to_repo_id=None,
508
+ create_pr=True,
509
+ revision=None,
510
+ ):
511
+ nemo_filename = f"{hf_repo_id.split('/')[-1]}.nemo"
512
+ filepath = cached_file(hf_repo_id, nemo_filename)
513
+
514
+ model_files = extract_nemo_archive(filepath, os.path.dirname(filepath))
515
+ nemo_config = yaml.load(open(model_files["model_config"], "r"), Loader=yaml.FullLoader)
516
+
517
+ # When revision is given (e.g. "refs/pr/3"), both pushes target that existing PR branch.
518
+ # Otherwise, write_processor creates a new PR and returns its revision for write_model.
519
+ pr_revision = write_processor(
520
+ nemo_config,
521
+ model_files,
522
+ output_dir,
523
+ model_type,
524
+ push_to_repo_id,
525
+ create_pr=create_pr if revision is None else False,
526
+ revision=revision,
527
+ )
528
+ write_model(nemo_config, model_files, model_type, output_dir, push_to_repo_id, pr_revision)
529
+
530
+
531
+ """
532
+ CTC conversion example:
533
+ ```bash
534
+ python src/transformers/models/parakeet/convert_nemo_to_hf.py \
535
+ --hf_repo_id nvidia/parakeet-ctc-1.1b \
536
+ --model_type ctc \
537
+ --output_dir OUTPUT_DIR \
538
+ --push_to_repo_id USERNAME/parakeet-ctc-1.1b
539
+ ```
540
+
541
+ TDT conversion example:
542
+ ```bash
543
+ python src/transformers/models/parakeet/convert_nemo_to_hf.py \
544
+ --hf_repo_id nvidia/parakeet-tdt-0.6b-v3 \
545
+ --model_type tdt \
546
+ --output_dir OUTPUT_DIR \
547
+ --push_to_repo_id USERNAME/parakeet-tdt-0.6b-v3-hf
548
+ ```
549
+ """
550
+ if __name__ == "__main__":
551
+ parser = argparse.ArgumentParser()
552
+ parser.add_argument("--hf_repo_id", required=True, help="Model repo on huggingface.co")
553
+ parser.add_argument(
554
+ "--model_type", required=True, choices=["ctc", "tdt", "rnnt"], help="Model type (`ctc`, `tdt`, `rnnt`)"
555
+ )
556
+ parser.add_argument("--output_dir", required=True, help="Output directory for HuggingFace model")
557
+ parser.add_argument("--push_to_repo_id", help="Repository ID to push the model to on the Hub")
558
+ parser.add_argument(
559
+ "--create_pr",
560
+ default=True,
561
+ action=argparse.BooleanOptionalAction,
562
+ help="Create a PR when pushing to the Hub (default: True). Use --no-create_pr to push directly.",
563
+ )
564
+ parser.add_argument(
565
+ "--revision",
566
+ default=None,
567
+ help='Push to an existing Hub PR branch (e.g. "refs/pr/3"). Overrides --create_pr.',
568
+ )
569
+ args = parser.parse_args()
570
+ main(
571
+ args.hf_repo_id,
572
+ args.output_dir,
573
+ args.model_type,
574
+ args.push_to_repo_id,
575
+ args.create_pr,
576
+ args.revision,
577
+ )
transformers/manifest.json ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "source_repo": "oruk/orukeet",
3
+ "source_revision": "555136b50265a132d4cea0d35560c26fc4f657ab",
4
+ "source_filename": "orukeet-v0.1.0.nemo",
5
+ "source_sha256": "031c8ddab4845aeced904a7cde8e8aa57993b2e344716cf83a545b079c473b56",
6
+ "converter_url": "https://github.com/huggingface/transformers/blob/6c6bac29f50c8aad5d1f06c72b2f892a6e335dd0/src/transformers/models/parakeet/convert_nemo_to_hf.py",
7
+ "dtype": "torch.float32",
8
+ "strict_state_dict": true,
9
+ "tensor_count": 723,
10
+ "parameter_count": 627008134,
11
+ "vocab_size": 8193,
12
+ "files": {
13
+ "config.json": {
14
+ "sha256": "a0075728c5f206b298006343ffa01db0016230832f1e4022f541887d3d27ac32",
15
+ "bytes": 1149
16
+ },
17
+ "generation_config.json": {
18
+ "sha256": "d6304ac2bc8d2dc8590f6ad48d5a98c3a2430f6841926eecbdda10554bf3d79b",
19
+ "bytes": 264
20
+ },
21
+ "model.safetensors": {
22
+ "sha256": "092cff73445117d4d234c5e4fb37d86ad16a348be3426e10ff38c79d35758569",
23
+ "bytes": 2508311120
24
+ },
25
+ "processor_config.json": {
26
+ "sha256": "7d1787398cffb800fa2cb58750781a78fe668dc02469750ee290840bd54cd8f1",
27
+ "bytes": 417
28
+ },
29
+ "tokenizer.json": {
30
+ "sha256": "45a7f44c5e012cfd09e72b333274370ba7785740d27fb1486364e0bb7bbf8b1a",
31
+ "bytes": 1159960
32
+ },
33
+ "tokenizer_config.json": {
34
+ "sha256": "5e04ae3487a5533224c295622cb206cc6e53914be527503978ce81f2cc75c559",
35
+ "bytes": 258
36
+ }
37
+ }
38
+ }
transformers/qualification.json ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "dataset": "Fixed first20 FLEURS validation clips per en/de/es/fr/ru/uk; compatibility sample, not a held-out model benchmark",
3
+ "normalization": "NFKC, lowercase, replace non-alphanumeric nonspace with spaces, whitespace tokens",
4
+ "device": "Apple M5 Max CPU,8threads,FP32",
5
+ "summary": {
6
+ "clips": 120,
7
+ "words": 2433,
8
+ "export_wer": 0.05425400739827373,
9
+ "source_nemo_wer": 0.053431976983148374,
10
+ "normalized_source_matches": 117,
11
+ "audio_s": 1257.82,
12
+ "inference_s": 217.64420087897452
13
+ },
14
+ "languages": {
15
+ "de_de": {
16
+ "clips": 20,
17
+ "words": 393,
18
+ "export_wer": 0.04071246819338423,
19
+ "source_nemo_wer": 0.03816793893129771,
20
+ "normalized_source_matches": 18,
21
+ "audio_s": 237.72,
22
+ "inference_s": 28.99683033389738
23
+ },
24
+ "en_us": {
25
+ "clips": 20,
26
+ "words": 382,
27
+ "export_wer": 0.034031413612565446,
28
+ "source_nemo_wer": 0.034031413612565446,
29
+ "normalized_source_matches": 20,
30
+ "audio_s": 173.38,
31
+ "inference_s": 30.397747127106413
32
+ },
33
+ "es_419": {
34
+ "clips": 20,
35
+ "words": 499,
36
+ "export_wer": 0.03006012024048096,
37
+ "source_nemo_wer": 0.028056112224448898,
38
+ "normalized_source_matches": 19,
39
+ "audio_s": 243.96,
40
+ "inference_s": 25.191086375154555
41
+ },
42
+ "fr_fr": {
43
+ "clips": 20,
44
+ "words": 467,
45
+ "export_wer": 0.044967880085653104,
46
+ "source_nemo_wer": 0.044967880085653104,
47
+ "normalized_source_matches": 20,
48
+ "audio_s": 188.7,
49
+ "inference_s": 35.01004733797163
50
+ },
51
+ "ru_ru": {
52
+ "clips": 20,
53
+ "words": 373,
54
+ "export_wer": 0.0777479892761394,
55
+ "source_nemo_wer": 0.0777479892761394,
56
+ "normalized_source_matches": 20,
57
+ "audio_s": 220.8,
58
+ "inference_s": 36.81056591490051
59
+ },
60
+ "uk_ua": {
61
+ "clips": 20,
62
+ "words": 319,
63
+ "export_wer": 0.11912225705329153,
64
+ "source_nemo_wer": 0.11912225705329153,
65
+ "normalized_source_matches": 20,
66
+ "audio_s": 193.26,
67
+ "inference_s": 61.237923789944034
68
+ }
69
+ }
70
+ }