def create_all_dags(args, neural_factory): ''' creates train and eval dags as well as their callbacks returns train loss tensor and callbacks''' # parse the config files yaml = YAML(typ="safe") with open(args.model_config) as f: spkr_params = yaml.load(f) sample_rate = spkr_params['sample_rate'] # Calculate num_workers for dataloader total_cpus = os.cpu_count() cpu_per_traindl = max(int(total_cpus / neural_factory.world_size), 1) # create separate data layers for eval # we need separate eval dags for separate eval datasets # but all other modules in these dags will be shared eval_dl_params = copy.deepcopy(spkr_params["AudioToSpeechLabelDataLayer"]) eval_dl_params.update(spkr_params["AudioToSpeechLabelDataLayer"]["eval"]) del eval_dl_params["train"] del eval_dl_params["eval"] eval_dl_params[ 'shuffle'] = False # To grab the file names without changing data_layer data_layer_test = nemo_asr.AudioToSpeechLabelDataLayer( manifest_filepath=args.eval_datasets[0], labels=None, batch_size=args.batch_size, num_workers=cpu_per_traindl, **eval_dl_params, # normalize_transcripts=False ) # create shared modules data_preprocessor = nemo_asr.AudioToMelSpectrogramPreprocessor( sample_rate=sample_rate, **spkr_params["AudioToMelSpectrogramPreprocessor"], ) # (QuartzNet uses the Jasper baseline encoder and decoder) encoder = nemo_asr.JasperEncoder(**spkr_params["JasperEncoder"], ) decoder = nemo_asr.JasperDecoderForSpkrClass( feat_in=spkr_params['JasperEncoder']['jasper'][-1]['filters'], num_classes=254, emb_sizes=spkr_params['JasperDecoderForSpkrClass']['emb_sizes'].split( ','), pool_mode=spkr_params["JasperDecoderForSpkrClass"]['pool_mode'], ) # --- Assemble Validation DAG --- # audio_signal_test, audio_len_test, label_test, _ = data_layer_test() processed_signal_test, processed_len_test = data_preprocessor( input_signal=audio_signal_test, length=audio_len_test) encoded_test, _ = encoder(audio_signal=processed_signal_test, length=processed_len_test) _, embeddings = decoder(encoder_output=encoded_test) return embeddings, label_test
def create_all_dags(args, neural_factory): """ creates train and eval dags as well as their callbacks returns train loss tensor and callbacks""" # parse the config files yaml = YAML(typ="safe") with open(args.model_config) as f: spkr_params = yaml.load(f) sample_rate = spkr_params["sample_rate"] time_length = spkr_params.get("time_length", 8) logging.info("max time length considered is {} sec".format(time_length)) # Calculate num_workers for dataloader total_cpus = os.cpu_count() cpu_per_traindl = max(int(total_cpus / neural_factory.world_size), 1) // 2 # create data layer for training train_dl_params = copy.deepcopy(spkr_params["AudioToSpeechLabelDataLayer"]) train_dl_params.update(spkr_params["AudioToSpeechLabelDataLayer"]["train"]) del train_dl_params["train"] del train_dl_params["eval"] audio_augmentor = spkr_params.get("AudioAugmentor", None) # del train_dl_params["normalize_transcripts"] data_layer_train = nemo_asr.AudioToSpeechLabelDataLayer( manifest_filepath=args.train_dataset, labels=None, batch_size=args.batch_size, num_workers=cpu_per_traindl, augmentor=audio_augmentor, time_length=time_length, **train_dl_params, # normalize_transcripts=False ) N = len(data_layer_train) steps_per_epoch = int(N / (args.batch_size * args.iter_per_step * args.num_gpus)) logging.info("Number of steps per epoch {}".format(steps_per_epoch)) # create separate data layers for eval # we need separate eval dags for separate eval datasets # but all other modules in these dags will be shared eval_dl_params = copy.deepcopy(spkr_params["AudioToSpeechLabelDataLayer"]) eval_dl_params.update(spkr_params["AudioToSpeechLabelDataLayer"]["eval"]) del eval_dl_params["train"] del eval_dl_params["eval"] data_layers_test = [] for test_set in args.eval_datasets: data_layer_test = nemo_asr.AudioToSpeechLabelDataLayer( manifest_filepath=test_set, labels=data_layer_train.labels, batch_size=args.batch_size, num_workers=cpu_per_traindl, time_length=time_length, **eval_dl_params, # normalize_transcripts=False ) data_layers_test.append(data_layer_test) # create shared modules data_preprocessor = nemo_asr.AudioToMelSpectrogramPreprocessor( sample_rate=sample_rate, **spkr_params["AudioToMelSpectrogramPreprocessor"], ) spectr_augment_config = spkr_params.get("SpectrogramAugmentation", None) if spectr_augment_config: data_spectr_augmentation = nemo_asr.SpectrogramAugmentation(**spectr_augment_config) # (QuartzNet uses the Jasper baseline encoder and decoder) encoder = nemo_asr.JasperEncoder(**spkr_params["JasperEncoder"],) decoder = nemo_asr.JasperDecoderForSpkrClass( feat_in=spkr_params["JasperEncoder"]["jasper"][-1]["filters"], num_classes=data_layer_train.num_classes, pool_mode=spkr_params["JasperDecoderForSpkrClass"]['pool_mode'], emb_sizes=spkr_params["JasperDecoderForSpkrClass"]["emb_sizes"].split(","), ) if os.path.exists(args.checkpoint_dir + "/JasperEncoder-STEP-100.pt"): encoder.restore_from(args.checkpoint_dir + "/JasperEncoder-STEP-100.pt") logging.info("Pretrained Encoder loaded") weight = None xent_loss = nemo_asr.CrossEntropyLossNM(weight=weight) # assemble train DAG audio_signal, audio_signal_len, label, label_len = data_layer_train() processed_signal, processed_signal_len = data_preprocessor(input_signal=audio_signal, length=audio_signal_len) if spectr_augment_config: processed_signal = data_spectr_augmentation(input_spec=processed_signal) encoded, encoded_len = encoder(audio_signal=processed_signal, length=processed_signal_len) logits, _ = decoder(encoder_output=encoded) loss = xent_loss(logits=logits, labels=label) # create train callbacks train_callback = nemo.core.SimpleLossLoggerCallback( tensors=[loss, logits, label], print_func=partial(monitor_classification_training_progress, eval_metric=[1]), step_freq=args.print_freq, get_tb_values=lambda x: [("train_loss", x[0])], tb_writer=neural_factory.tb_writer, ) callbacks = [train_callback] if args.checkpoint_dir or args.load_dir: chpt_callback = nemo.core.CheckpointCallback( folder=args.checkpoint_dir, load_from_folder=args.checkpoint_dir, # load dir step_freq=args.checkpoint_save_freq, checkpoints_to_keep=125, ) callbacks.append(chpt_callback) # --- Assemble Validation DAG --- # for i, eval_layer in enumerate(data_layers_test): audio_signal_test, audio_len_test, label_test, _ = eval_layer() processed_signal_test, processed_len_test = data_preprocessor( input_signal=audio_signal_test, length=audio_len_test ) encoded_test, encoded_len_test = encoder(audio_signal=processed_signal_test, length=processed_len_test) logits_test, _ = decoder(encoder_output=encoded_test) loss_test = xent_loss(logits=logits_test, labels=label_test) tagname = os.path.dirname(args.eval_datasets[i]).split("/")[-1] + "_" + str(i) print(tagname) eval_callback = nemo.core.EvaluatorCallback( eval_tensors=[loss_test, logits_test, label_test], user_iter_callback=partial(process_classification_evaluation_batch, top_k=1), user_epochs_done_callback=partial(process_classification_evaluation_epoch, tag=tagname), eval_step=args.eval_freq, # How often we evaluate the model on the test set tb_writer=neural_factory.tb_writer, ) callbacks.append(eval_callback) return loss, callbacks, steps_per_epoch, loss_test, logits_test, label_test
def test_quartznet_speaker_reco_training(self): """Integtaion test that instantiates a small QuartzNet model for speaker recognition and tests training with the sample an4 data. Training is run for 3 forward and backward steps and asserts that loss after 3 steps is smaller than the loss at the first step. """ with open( os.path.abspath( os.path.join(os.path.dirname(__file__), "../data/quartznet_spkr_test.yaml"))) as file: spkr_params = self.yaml.load(file) dl = nemo_asr.AudioToSpeechLabelDataLayer( manifest_filepath=self.manifest_filepath, labels=None, batch_size=10, ) sample_rate = 16000 preprocessing = nemo_asr.AudioToMelSpectrogramPreprocessor( sample_rate=sample_rate, **spkr_params["AudioToMelSpectrogramPreprocessor"], ) jasper_encoder = nemo_asr.JasperEncoder(**spkr_params['JasperEncoder']) jasper_decoder = nemo_asr.JasperDecoderForSpkrClass( feat_in=spkr_params['JasperEncoder']['jasper'][-1]['filters'], num_classes=dl.num_classes, pool_mode=spkr_params['JasperDecoderForSpkrClass']['pool_mode'], emb_sizes=spkr_params["JasperDecoderForSpkrClass"] ["emb_sizes"].split(","), ) ce_loss = nemo_asr.CrossEntropyLossNM() # DAG audio_signal, a_sig_length, targets, targets_len = dl() processed_signal, p_length = preprocessing(input_signal=audio_signal, length=a_sig_length) encoded, encoded_len = jasper_encoder(audio_signal=processed_signal, length=p_length) # logging.info(jasper_encoder) log_probs, _ = jasper_decoder(encoder_output=encoded) loss = ce_loss(logits=log_probs, labels=targets) loss_list = [] callback = nemo.core.SimpleLossLoggerCallback( tensors=[loss], print_func=partial(self.print_and_log_loss, loss_log_list=loss_list), step_freq=1) self.nf.random_seed = 42 self.nf.train( [loss], callbacks=[callback], optimizer="sgd", optimization_params={ "max_steps": 4, "lr": 0.002 }, ) self.nf.reset_trainer() # Assert that training loss went down assert loss_list[-1] < loss_list[0]