|
| 1 | +import argparse |
| 2 | +import io |
| 3 | +import sys |
| 4 | +from copy import deepcopy |
| 5 | +from functools import reduce |
| 6 | +from pathlib import Path |
| 7 | +from subprocess import CalledProcessError, check_output |
| 8 | + |
| 9 | +import torch |
| 10 | +import yaml |
| 11 | + |
| 12 | +import quartznet.config |
| 13 | +from common import helpers |
| 14 | +from common.features import FilterbankFeatures |
| 15 | +from quartznet.config import load as load_yaml |
| 16 | +from quartznet.model import QuartzNet, MaskedConv1d |
| 17 | + |
| 18 | + |
| 19 | +# Corresponding DLE <-> NeMo config keys |
| 20 | +cfg_key_map = { |
| 21 | + ("input_val", "audio_dataset", "sample_rate"): ("preprocessor", "sample_rate"), |
| 22 | + ("input_val", "filterbank_features", "dither"): ("preprocessor", "dither"), |
| 23 | + ("input_val", "filterbank_features", "frame_splicing"): ("preprocessor", "frame_splicing"), |
| 24 | + ("input_val", "filterbank_features", "n_fft"): ("preprocessor", "n_fft"), |
| 25 | + ("input_val", "filterbank_features", "n_filt"): ("preprocessor", "features"), |
| 26 | + ("input_val", "filterbank_features", "normalize"): ("preprocessor", "normalize"), |
| 27 | + ("input_val", "filterbank_features", "sample_rate"): ("preprocessor", "sample_rate"), |
| 28 | + ("input_val", "filterbank_features", "window"): ("preprocessor", "window"), |
| 29 | + ("input_val", "filterbank_features", "window_size"): ("preprocessor", "window_size"), |
| 30 | + ("input_val", "filterbank_features", "window_stride"): ("preprocessor", "window_stride"), |
| 31 | + ("labels",): ("decoder", "vocabulary"), |
| 32 | + ("quartznet", "decoder", "in_feats"): ("decoder", "feat_in"), |
| 33 | + ("quartznet", "encoder", "activation"): ("encoder", "activation"), |
| 34 | + ("quartznet", "encoder", "blocks"): ("encoder", "jasper"), |
| 35 | + ("quartznet", "encoder", "frame_splicing"): ("preprocessor", "frame_splicing"), |
| 36 | + ("quartznet", "encoder", "in_feats"): ("encoder", "feat_in"), |
| 37 | + ("quartznet", "encoder", "use_conv_masks"): ("encoder", "conv_mask"), |
| 38 | +} |
| 39 | + |
| 40 | + |
| 41 | +def load_nemo_ckpt(fpath): |
| 42 | + """Make a DeepLearningExamples state_dict and config from a .nemo file.""" |
| 43 | + try: |
| 44 | + cmd = ['tar', 'Oxzf', fpath, './model_config.yaml'] |
| 45 | + nemo_cfg = yaml.safe_load(io.BytesIO(check_output(cmd))) |
| 46 | + |
| 47 | + cmd = ['tar', 'Oxzf', fpath, './model_weights.ckpt'] |
| 48 | + ckpt = torch.load(io.BytesIO(check_output(cmd)), map_location="cpu") |
| 49 | + |
| 50 | + except (FileNotFoundError, CalledProcessError): |
| 51 | + print('WARNING: Could not uncompress with tar. ' |
| 52 | + 'Falling back to the tarfile module (might take a few minutes).') |
| 53 | + import tarfile |
| 54 | + with tarfile.open(fpath, "r:gz") as tar: |
| 55 | + f = tar.extractfile(tar.getmember("./model_config.yaml")) |
| 56 | + nemo_cfg = yaml.safe_load(f) |
| 57 | + |
| 58 | + f = tar.extractfile(tar.getmember("./model_weights.ckpt")) |
| 59 | + ckpt = torch.load(f, map_location="cpu") |
| 60 | + |
| 61 | + remap = lambda k: (k.replace("encoder.encoder", "encoder.layers") |
| 62 | + .replace("decoder.decoder_layers", "decoder.layers") |
| 63 | + .replace("conv.weight", "weight")) |
| 64 | + dle_ckpt = {'state_dict': {remap(k): v for k, v in ckpt.items() |
| 65 | + if "preproc" not in k}} |
| 66 | + dle_cfg = config_from_nemo(nemo_cfg) |
| 67 | + return dle_ckpt, dle_cfg |
| 68 | + |
| 69 | + |
| 70 | +def save_nemo_ckpt(dle_ckpt, dle_cfg, dest_path): |
| 71 | + """Save a DeepLearningExamples model as a .nemo file.""" |
| 72 | + cfg = deepcopy(dle_cfg) |
| 73 | + |
| 74 | + dle_ckpt = torch.load(dle_ckpt, map_location="cpu")["ema_state_dict"] |
| 75 | + |
| 76 | + # Build a DLE model instance and fill with weights |
| 77 | + symbols = helpers.add_ctc_blank(cfg['labels']) |
| 78 | + enc_kw = quartznet.config.encoder(cfg) |
| 79 | + dec_kw = quartznet.config.decoder(cfg, n_classes=len(symbols)) |
| 80 | + model = QuartzNet(enc_kw, dec_kw) |
| 81 | + model.load_state_dict(dle_ckpt, strict=True) |
| 82 | + |
| 83 | + # Reaname core modules, e.g., encoder.layers -> encoder.encoder |
| 84 | + model.encoder._modules['encoder'] = model.encoder._modules.pop('layers') |
| 85 | + model.decoder._modules['decoder_layers'] = model.decoder._modules.pop('layers') |
| 86 | + |
| 87 | + # MaskedConv1d is made via composition in NeMo, and via inheritance in DLE |
| 88 | + # Params for MaskedConv1d in NeMo have an additional '.conv.' infix |
| 89 | + def rename_convs(module): |
| 90 | + for name in list(module._modules.keys()): |
| 91 | + submod = module._modules[name] |
| 92 | + |
| 93 | + if isinstance(submod, MaskedConv1d): |
| 94 | + module._modules[f'{name}.conv'] = module._modules.pop(name) |
| 95 | + else: |
| 96 | + rename_convs(submod) |
| 97 | + |
| 98 | + rename_convs(model.encoder.encoder) |
| 99 | + |
| 100 | + # Use FilterbankFeatures to calculate fbanks and store with model weights |
| 101 | + feature_processor = FilterbankFeatures( |
| 102 | + **dle_cfg['input_val']['filterbank_features']) |
| 103 | + |
| 104 | + nemo_ckpt = model.state_dict() |
| 105 | + nemo_ckpt["preprocessor.featurizer.fb"] = feature_processor.fb |
| 106 | + nemo_ckpt["preprocessor.featurizer.window"] = feature_processor.window |
| 107 | + |
| 108 | + nemo_cfg = config_to_nemo(dle_cfg) |
| 109 | + |
| 110 | + # Prepare the directory for zipping |
| 111 | + ckpt_files = dest_path / "ckpt_files" |
| 112 | + ckpt_files.mkdir(exist_ok=True, parents=False) |
| 113 | + with open(ckpt_files / "model_config.yaml", "w") as f: |
| 114 | + yaml.dump(nemo_cfg, f) |
| 115 | + torch.save(nemo_ckpt, ckpt_files / "model_weights.ckpt") |
| 116 | + |
| 117 | + with tarfile.open(dest_path / "quartznet.nemo", "w:gz") as tar: |
| 118 | + tar.add(ckpt_files, arcname="./") |
| 119 | + |
| 120 | + |
| 121 | +def save_dle_ckpt(ckpt, cfg, dest_dir): |
| 122 | + torch.save(ckpt, dest_dir / "model.pt") |
| 123 | + with open(dest_dir / "model_config.yaml", "w") as f: |
| 124 | + yaml.dump(cfg, f) |
| 125 | + |
| 126 | + |
| 127 | +def set_nested_item(tgt, src, tgt_keys, src_keys): |
| 128 | + """Assigns nested dict keys, e.g., d1[a][b][c] = d2[e][f][g][h].""" |
| 129 | + tgt_nested = reduce(lambda d, k: d[k], tgt_keys[:-1], tgt) |
| 130 | + tgt_nested[tgt_keys[-1]] = reduce(lambda d, k: d[k], src_keys, src) |
| 131 | + |
| 132 | + |
| 133 | +def config_from_nemo(nemo_cfg): |
| 134 | + """Convert a DeepLearningExamples config to a NeMo format.""" |
| 135 | + dle_cfg = { |
| 136 | + 'name': 'QuartzNet', |
| 137 | + 'input_val': { |
| 138 | + 'audio_dataset': { |
| 139 | + 'normalize_transcripts': True, |
| 140 | + }, |
| 141 | + 'filterbank_features': { |
| 142 | + 'pad_align': 16, |
| 143 | + }, |
| 144 | + }, |
| 145 | + 'quartznet': { |
| 146 | + 'decoder': {}, |
| 147 | + 'encoder': {}, |
| 148 | + }, |
| 149 | + } |
| 150 | + |
| 151 | + for dle_keys, nemo_keys in cfg_key_map.items(): |
| 152 | + try: |
| 153 | + set_nested_item(dle_cfg, nemo_cfg, dle_keys, nemo_keys) |
| 154 | + except KeyError: |
| 155 | + print(f'WARNING: Could not load config {nemo_keys} as {dle_keys}.') |
| 156 | + |
| 157 | + # mapping kernel_size is not expressable with cfg_map |
| 158 | + for block in dle_cfg["quartznet"]["encoder"]["blocks"]: |
| 159 | + block["kernel_size"] = block.pop("kernel") |
| 160 | + |
| 161 | + return dle_cfg |
| 162 | + |
| 163 | + |
| 164 | +def config_to_nemo(dle_cfg): |
| 165 | + """Convert a DeepLearningExamples config to a NeMo format.""" |
| 166 | + nemo_cfg = { |
| 167 | + "target": "nemo.collections.asr.models.ctc_models.EncDecCTCModel", |
| 168 | + "dropout": 0.0, |
| 169 | + "preprocessor": { |
| 170 | + "_target_": "nemo.collections.asr.modules.AudioToMelSpectrogramPreprocessor", |
| 171 | + "stft_conv": False, |
| 172 | + }, |
| 173 | + "encoder": { |
| 174 | + "_target_": "nemo.collections.asr.modules.ConvASREncoder", |
| 175 | + "jasper": {} |
| 176 | + }, |
| 177 | + "decoder": { |
| 178 | + "_target_": "nemo.collections.asr.modules.ConvASRDecoder", |
| 179 | + }, |
| 180 | + } |
| 181 | + |
| 182 | + for dle_keys, nemo_keys in cfg_key_map.items(): |
| 183 | + try: |
| 184 | + set_nested_item(nemo_cfg, dle_cfg, nemo_keys, dle_keys) |
| 185 | + except KeyError: |
| 186 | + print(f"WARNING: Could not load config {dle_keys} as {nemo_keys}.") |
| 187 | + |
| 188 | + nemo_cfg["sample_rate"] = nemo_cfg["preprocessor"]["sample_rate"] |
| 189 | + nemo_cfg["repeat"] = nemo_cfg["encoder"]["jasper"][1]["repeat"] |
| 190 | + nemo_cfg["separable"] = nemo_cfg["encoder"]["jasper"][1]["separable"] |
| 191 | + nemo_cfg["labels"] = nemo_cfg["decoder"]["vocabulary"] |
| 192 | + nemo_cfg["decoder"]["num_classes"] = len(nemo_cfg["decoder"]["vocabulary"]) |
| 193 | + |
| 194 | + # mapping kernel_size is not expressable with cfg_map |
| 195 | + for block in nemo_cfg["encoder"]["jasper"]: |
| 196 | + if "kernel_size" in block: |
| 197 | + block["kernel"] = block.pop("kernel_size") |
| 198 | + |
| 199 | + return nemo_cfg |
| 200 | + |
| 201 | + |
| 202 | +if __name__ == "__main__": |
| 203 | + parser = argparse.ArgumentParser(description="QuartzNet DLE <-> NeMo model converter.") |
| 204 | + parser.add_argument("source_model", type=Path, |
| 205 | + help="A DLE or NeMo QuartzNet model to be converted (.pt or .nemo, respectively)") |
| 206 | + parser.add_argument("dest_dir", type=Path, help="Destination directory") |
| 207 | + parser.add_argument("--dle_config_yaml", type=Path, |
| 208 | + help="A DLE config .yaml file, required only to convert DLE -> NeMo") |
| 209 | + args = parser.parse_args() |
| 210 | + |
| 211 | + ext = args.source_model.suffix.lower() |
| 212 | + if ext == ".nemo": |
| 213 | + ckpt, cfg = load_nemo_ckpt(args.source_model) |
| 214 | + save_dle_ckpt(ckpt, cfg, args.dest_dir) |
| 215 | + |
| 216 | + elif ext == ".pt": |
| 217 | + dle_cfg = load_yaml(args.dle_config_yaml) |
| 218 | + save_nemo_ckpt(args.source_model, dle_cfg, args.dest_dir) |
| 219 | + |
| 220 | + else: |
| 221 | + raise ValueError(f"Unknown extension {ext}.") |
| 222 | + |
| 223 | + print('Converted succesfully.') |
0 commit comments