convert_fairseq_models.py 2.23 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#!/usr/bin/env python3
"""Convert a Wav2Vec2/HuBERT model published by fairseq into torchaudio format

Examples

```
python convert_fairseq_models.py \
  --input-file hubert_base_ls960.pt \
  --output-file hubert_fairseq_base_ls960.pth

python convert_fairseq_models.py \
  --input-file hubert_large_ll60k.pt \
  --output-file hubert_fairseq_large_ll60k.pth

python convert_fairseq_models.py \
  --input-file hubert_large_ll60k_finetune_ls960.pt \
  --output-file hubert_fairseq_large_ll60k_asr_ls960.pth

python convert_fairseq_models.py \
  --input-file hubert_xtralarge_ll60k.pt \
  --output-file hubert_fairseq_xlarge_ll60k.pth

python convert_fairseq_models.py \
  --input-file hubert_xtralarge_ll60k_finetune_ls960.pt \
  --output-file hubert_fairseq_xlarge_ll60k_asr_ls960.pth
"""

import argparse

# Note: Avoiding the import of torch and fairseq on global scope as they are slow


def _parse_args():
    parser = argparse.ArgumentParser(
        description=__doc__,
        formatter_class=argparse.RawTextHelpFormatter,
    )
38
39
    parser.add_argument("--input-file", required=True, help="Input model file.")
    parser.add_argument("--output-file", required=False, help="Output model file.")
40
    parser.add_argument(
41
        "--dict-dir",
42
        help=(
43
44
45
46
            "Directory where letter vocabulary file, `dict.ltr.txt`, is found. "
            "Required when loading wav2vec2 model. "
            "https://dl.fbaipublicfiles.com/fairseq/wav2vec/dict.ltr.txt"
        ),
47
48
49
50
51
52
53
    )
    return parser.parse_args()


def _load_model(input_file, dict_dir):
    import fairseq

54
    overrides = {} if dict_dir is None else {"data": dict_dir}
55
    models, _, _ = fairseq.checkpoint_utils.load_model_ensemble_and_task(
56
57
        [input_file],
        arg_overrides=overrides,
58
59
60
61
62
63
64
    )
    return models[0]


def _import_model(model):
    from torchaudio.models.wav2vec2.utils import import_fairseq_model

65
    if model.__class__.__name__ in ["HubertCtc", "Wav2VecCtc"]:
66
67
68
69
70
71
72
        model = model.w2v_encoder
    model = import_fairseq_model(model)
    return model


def _main(args):
    import torch
73

74
75
76
77
78
    model = _load_model(args.input_file, args.dict_dir)
    model = _import_model(model)
    torch.save(model.state_dict(), args.output_file)


79
if __name__ == "__main__":
80
    _main(_parse_args())