|
| 1 | +# Copyright 2020 Huy Le Nguyen (@usimarit) |
| 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 os |
| 16 | +import math |
| 17 | +import argparse |
| 18 | +from tensorflow_asr.utils import setup_environment, setup_tpu |
| 19 | + |
| 20 | +setup_environment() |
| 21 | +import tensorflow as tf |
| 22 | + |
| 23 | +DEFAULT_YAML = os.path.join(os.path.abspath(os.path.dirname(__file__)), "config.yml") |
| 24 | + |
| 25 | +tf.keras.backend.clear_session() |
| 26 | + |
| 27 | +parser = argparse.ArgumentParser(prog="Conformer Training") |
| 28 | + |
| 29 | +parser.add_argument("--config", type=str, default=DEFAULT_YAML, help="The file path of model configuration file") |
| 30 | + |
| 31 | +parser.add_argument("--sentence_piece", default=False, action="store_true", help="Whether to use `SentencePiece` model") |
| 32 | + |
| 33 | +parser.add_argument("--bs", type=int, default=None, help="Batch size per replica") |
| 34 | + |
| 35 | +parser.add_argument("--tpu_address", type=str, default=None, help="TPU address. Leave None on Colab") |
| 36 | + |
| 37 | +parser.add_argument("--max_lengths_prefix", type=str, default=None, help="Path to file containing max lengths") |
| 38 | + |
| 39 | +parser.add_argument("--compute_lengths", default=False, action="store_true", help="Whether to compute lengths") |
| 40 | + |
| 41 | +parser.add_argument("--mxp", default=False, action="store_true", help="Enable mixed precision") |
| 42 | + |
| 43 | +parser.add_argument("--subwords", type=str, default=None, help="Path to file that stores generated subwords") |
| 44 | + |
| 45 | +parser.add_argument("--subwords_corpus", nargs="*", type=str, default=[], help="Transcript files for generating subwords") |
| 46 | + |
| 47 | +args = parser.parse_args() |
| 48 | + |
| 49 | +tf.config.optimizer.set_experimental_options({"auto_mixed_precision": args.mxp}) |
| 50 | + |
| 51 | +strategy = setup_tpu(args.tpu_address) |
| 52 | + |
| 53 | +from tensorflow_asr.configs.config import Config |
| 54 | +from tensorflow_asr.datasets.keras import ASRTFRecordDatasetKeras |
| 55 | +from tensorflow_asr.featurizers.speech_featurizers import TFSpeechFeaturizer |
| 56 | +from tensorflow_asr.featurizers.text_featurizers import SubwordFeaturizer, SentencePieceFeaturizer |
| 57 | +from tensorflow_asr.models.keras.conformer import Conformer |
| 58 | +from tensorflow_asr.optimizers.schedules import TransformerSchedule |
| 59 | + |
| 60 | +config = Config(args.config) |
| 61 | +speech_featurizer = TFSpeechFeaturizer(config.speech_config) |
| 62 | + |
| 63 | +if args.sentence_piece: |
| 64 | + print("Loading SentencePiece model ...") |
| 65 | + text_featurizer = SentencePieceFeaturizer.load_from_file(config.decoder_config, args.subwords) |
| 66 | +elif args.subwords and os.path.exists(args.subwords): |
| 67 | + print("Loading subwords ...") |
| 68 | + text_featurizer = SubwordFeaturizer.load_from_file(config.decoder_config, args.subwords) |
| 69 | +else: |
| 70 | + print("Generating subwords ...") |
| 71 | + text_featurizer = SubwordFeaturizer.build_from_corpus( |
| 72 | + config.decoder_config, |
| 73 | + corpus_files=args.subwords_corpus |
| 74 | + ) |
| 75 | + text_featurizer.save_to_file(args.subwords) |
| 76 | + |
| 77 | +train_dataset = ASRTFRecordDatasetKeras( |
| 78 | + speech_featurizer=speech_featurizer, text_featurizer=text_featurizer, |
| 79 | + **vars(config.learning_config.train_dataset_config) |
| 80 | +) |
| 81 | +eval_dataset = ASRTFRecordDatasetKeras( |
| 82 | + speech_featurizer=speech_featurizer, text_featurizer=text_featurizer, |
| 83 | + **vars(config.learning_config.eval_dataset_config) |
| 84 | +) |
| 85 | + |
| 86 | +if args.compute_lengths: |
| 87 | + train_dataset.update_lengths(args.max_lengths_prefix) |
| 88 | + eval_dataset.update_lengths(args.max_lengths_prefix) |
| 89 | + |
| 90 | +# Update max lengths calculated from both train and eval datasets |
| 91 | +train_dataset.load_max_lengths(args.max_lengths_prefix) |
| 92 | +eval_dataset.load_max_lengths(args.max_lengths_prefix) |
| 93 | + |
| 94 | +with strategy.scope(): |
| 95 | + batch_size = args.bs if args.bs is not None else config.learning_config.running_config.batch_size |
| 96 | + global_batch_size = batch_size |
| 97 | + global_batch_size *= strategy.num_replicas_in_sync |
| 98 | + # build model |
| 99 | + conformer = Conformer(**config.model_config, vocabulary_size=text_featurizer.num_classes) |
| 100 | + conformer._build(speech_featurizer.shape, prediction_shape=text_featurizer.prepand_shape, batch_size=global_batch_size) |
| 101 | + conformer.summary(line_length=120) |
| 102 | + |
| 103 | + optimizer = tf.keras.optimizers.Adam( |
| 104 | + TransformerSchedule( |
| 105 | + d_model=conformer.dmodel, |
| 106 | + warmup_steps=config.learning_config.optimizer_config["warmup_steps"], |
| 107 | + max_lr=(0.05 / math.sqrt(conformer.dmodel)) |
| 108 | + ), |
| 109 | + beta_1=config.learning_config.optimizer_config["beta1"], |
| 110 | + beta_2=config.learning_config.optimizer_config["beta2"], |
| 111 | + epsilon=config.learning_config.optimizer_config["epsilon"] |
| 112 | + ) |
| 113 | + |
| 114 | + conformer.compile(optimizer=optimizer, global_batch_size=global_batch_size, blank=text_featurizer.blank) |
| 115 | + |
| 116 | + train_data_loader = train_dataset.create(global_batch_size) |
| 117 | + eval_data_loader = eval_dataset.create(global_batch_size) |
| 118 | + |
| 119 | + callbacks = [ |
| 120 | + tf.keras.callbacks.ModelCheckpoint(**config.learning_config.running_config.checkpoint), |
| 121 | + tf.keras.callbacks.experimental.BackupAndRestore(config.learning_config.running_config.states_dir), |
| 122 | + tf.keras.callbacks.TensorBoard(**config.learning_config.running_config.tensorboard) |
| 123 | + ] |
| 124 | + |
| 125 | + conformer.fit( |
| 126 | + train_data_loader, epochs=config.learning_config.running_config.num_epochs, |
| 127 | + validation_data=eval_data_loader, callbacks=callbacks, |
| 128 | + ) |
0 commit comments