|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# |
| 3 | +# Copyright 2021-2022 Xiaomi Corporation (Author: Yifan Yang) |
| 4 | +# Copyright 2024 Yuekai Zhang |
| 5 | +# |
| 6 | +# See ../../../../LICENSE for clarification regarding multiple authors |
| 7 | +# |
| 8 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 9 | +# you may not use this file except in compliance with the License. |
| 10 | +# You may obtain a copy of the License at |
| 11 | +# |
| 12 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 13 | +# |
| 14 | +# Unless required by applicable law or agreed to in writing, software |
| 15 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 16 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 17 | +# See the License for the specific language governing permissions and |
| 18 | +# limitations under the License. |
| 19 | +""" |
| 20 | +Usage: |
| 21 | +(1) use the checkpoint exp_dir/epoch-xxx.pt |
| 22 | +python3 bin/generate_averaged_model.py \ |
| 23 | + --epoch 40 \ |
| 24 | + --avg 5 \ |
| 25 | + --exp-dir ${exp_dir} |
| 26 | +
|
| 27 | +It will generate a file `epoch-28-avg-15.pt` in the given `exp_dir`. |
| 28 | +You can later load it by `torch.load("epoch-28-avg-15.pt")`. |
| 29 | +""" |
| 30 | + |
| 31 | + |
| 32 | +import argparse |
| 33 | +from pathlib import Path |
| 34 | + |
| 35 | +import k2 |
| 36 | +import torch |
| 37 | +from train import add_model_arguments, get_model |
| 38 | + |
| 39 | +from icefall.checkpoint import ( |
| 40 | + average_checkpoints, |
| 41 | + average_checkpoints_with_averaged_model, |
| 42 | + find_checkpoints, |
| 43 | +) |
| 44 | +from icefall.utils import AttributeDict |
| 45 | + |
| 46 | + |
| 47 | +def get_parser(): |
| 48 | + parser = argparse.ArgumentParser( |
| 49 | + formatter_class=argparse.ArgumentDefaultsHelpFormatter |
| 50 | + ) |
| 51 | + |
| 52 | + parser.add_argument( |
| 53 | + "--epoch", |
| 54 | + type=int, |
| 55 | + default=30, |
| 56 | + help="""It specifies the checkpoint to use for decoding. |
| 57 | + Note: Epoch counts from 1. |
| 58 | + You can specify --avg to use more checkpoints for model averaging.""", |
| 59 | + ) |
| 60 | + |
| 61 | + parser.add_argument( |
| 62 | + "--iter", |
| 63 | + type=int, |
| 64 | + default=0, |
| 65 | + help="""If positive, --epoch is ignored and it |
| 66 | + will use the checkpoint exp_dir/checkpoint-iter.pt. |
| 67 | + You can specify --avg to use more checkpoints for model averaging. |
| 68 | + """, |
| 69 | + ) |
| 70 | + |
| 71 | + parser.add_argument( |
| 72 | + "--avg", |
| 73 | + type=int, |
| 74 | + default=9, |
| 75 | + help="Number of checkpoints to average. Automatically select " |
| 76 | + "consecutive checkpoints before the checkpoint specified by " |
| 77 | + "'--epoch' and '--iter'", |
| 78 | + ) |
| 79 | + |
| 80 | + parser.add_argument( |
| 81 | + "--exp-dir", |
| 82 | + type=str, |
| 83 | + default="zipformer/exp", |
| 84 | + help="The experiment dir", |
| 85 | + ) |
| 86 | + add_model_arguments(parser) |
| 87 | + return parser |
| 88 | + |
| 89 | + |
| 90 | +@torch.no_grad() |
| 91 | +def main(): |
| 92 | + parser = get_parser() |
| 93 | + |
| 94 | + args = parser.parse_args() |
| 95 | + args.exp_dir = Path(args.exp_dir) |
| 96 | + |
| 97 | + params = AttributeDict() |
| 98 | + params.update(vars(args)) |
| 99 | + |
| 100 | + if params.iter > 0: |
| 101 | + params.suffix = f"checkpoint-{params.iter}-avg-{params.avg}" |
| 102 | + else: |
| 103 | + params.suffix = f"epoch-{params.epoch}-avg-{params.avg}" |
| 104 | + |
| 105 | + print("Script started") |
| 106 | + |
| 107 | + device = torch.device("cpu") |
| 108 | + print(f"Device: {device}") |
| 109 | + |
| 110 | + print("About to create model") |
| 111 | + filename = f"{params.exp_dir}/epoch-{params.epoch}.pt" |
| 112 | + checkpoint = torch.load(filename, map_location=device) |
| 113 | + args = AttributeDict(checkpoint) |
| 114 | + model = get_model(args) |
| 115 | + |
| 116 | + if params.iter > 0: |
| 117 | + # TODO FIX ME |
| 118 | + filenames = find_checkpoints(params.exp_dir, iteration=-params.iter)[ |
| 119 | + : params.avg + 1 |
| 120 | + ] |
| 121 | + if len(filenames) == 0: |
| 122 | + raise ValueError( |
| 123 | + f"No checkpoints found for --iter {params.iter}, --avg {params.avg}" |
| 124 | + ) |
| 125 | + elif len(filenames) < params.avg + 1: |
| 126 | + raise ValueError( |
| 127 | + f"Not enough checkpoints ({len(filenames)}) found for" |
| 128 | + f" --iter {params.iter}, --avg {params.avg}" |
| 129 | + ) |
| 130 | + filename_start = filenames[-1] |
| 131 | + filename_end = filenames[0] |
| 132 | + print( |
| 133 | + "Calculating the averaged model over iteration checkpoints" |
| 134 | + f" from {filename_start} (excluded) to {filename_end}" |
| 135 | + ) |
| 136 | + model.to(device) |
| 137 | + model.load_state_dict( |
| 138 | + average_checkpoints_with_averaged_model( |
| 139 | + filename_start=filename_start, |
| 140 | + filename_end=filename_end, |
| 141 | + device=device, |
| 142 | + ) |
| 143 | + ) |
| 144 | + filename = params.exp_dir / f"checkpoint-{params.iter}-avg-{params.avg}.pt" |
| 145 | + torch.save({"model": model.state_dict()}, filename) |
| 146 | + else: |
| 147 | + assert params.avg > 0, params.avg |
| 148 | + start = params.epoch - params.avg |
| 149 | + assert start >= 1, start |
| 150 | + filename_start = f"{params.exp_dir}/epoch-{start}.pt" |
| 151 | + filename_end = f"{params.exp_dir}/epoch-{params.epoch}.pt" |
| 152 | + print( |
| 153 | + f"Calculating the averaged model over epoch range from " |
| 154 | + f"{start} (excluded) to {params.epoch}" |
| 155 | + ) |
| 156 | + filenames = [ |
| 157 | + f"{params.exp_dir}/epoch-{i}.pt" for i in range(start, params.epoch + 1) |
| 158 | + ] |
| 159 | + model.to(device) |
| 160 | + model.load_state_dict(average_checkpoints(filenames, device=device)) |
| 161 | + |
| 162 | + filename = params.exp_dir / f"epoch-{params.epoch}-avg-{params.avg}.pt" |
| 163 | + checkpoint["model"] = model.state_dict() |
| 164 | + torch.save(checkpoint, filename) |
| 165 | + |
| 166 | + num_param = sum([p.numel() for p in model.parameters()]) |
| 167 | + print(f"Number of model parameters: {num_param}") |
| 168 | + |
| 169 | + print("Done!") |
| 170 | + |
| 171 | + |
| 172 | +if __name__ == "__main__": |
| 173 | + main() |
0 commit comments