(model_name, voc, pairs, encoder, decoder, encoder_optimizer, decoder_optimizer, embedding, encoder_n_layers, decoder_n_layers, save_dir, n_iteration, batch_size, print_every, save_every, clip, corpus_name, loadFilename)
| 1036 | # |
| 1037 | |
| 1038 | def trainIters(model_name, voc, pairs, encoder, decoder, encoder_optimizer, decoder_optimizer, embedding, encoder_n_layers, decoder_n_layers, save_dir, n_iteration, batch_size, print_every, save_every, clip, corpus_name, loadFilename): |
| 1039 | |
| 1040 | # Load batches for each iteration |
| 1041 | training_batches = [batch2TrainData(voc, [random.choice(pairs) for _ in range(batch_size)]) |
| 1042 | for _ in range(n_iteration)] |
| 1043 | |
| 1044 | # Initializations |
| 1045 | print('Initializing ...') |
| 1046 | start_iteration = 1 |
| 1047 | print_loss = 0 |
| 1048 | if loadFilename: |
| 1049 | start_iteration = checkpoint['iteration'] + 1 |
| 1050 | |
| 1051 | # Training loop |
| 1052 | print("Training...") |
| 1053 | for iteration in range(start_iteration, n_iteration + 1): |
| 1054 | training_batch = training_batches[iteration - 1] |
| 1055 | # Extract fields from batch |
| 1056 | input_variable, lengths, target_variable, mask, max_target_len = training_batch |
| 1057 | |
| 1058 | # Run a training iteration with batch |
| 1059 | loss = train(input_variable, lengths, target_variable, mask, max_target_len, encoder, |
| 1060 | decoder, embedding, encoder_optimizer, decoder_optimizer, batch_size, clip) |
| 1061 | print_loss += loss |
| 1062 | |
| 1063 | # Print progress |
| 1064 | if iteration % print_every == 0: |
| 1065 | print_loss_avg = print_loss / print_every |
| 1066 | print("Iteration: {}; Percent complete: {:.1f}%; Average loss: {:.4f}".format(iteration, iteration / n_iteration * 100, print_loss_avg)) |
| 1067 | print_loss = 0 |
| 1068 | |
| 1069 | # Save checkpoint |
| 1070 | if (iteration % save_every == 0): |
| 1071 | directory = os.path.join(save_dir, model_name, corpus_name, '{}-{}_{}'.format(encoder_n_layers, decoder_n_layers, hidden_size)) |
| 1072 | if not os.path.exists(directory): |
| 1073 | os.makedirs(directory) |
| 1074 | torch.save({ |
| 1075 | 'iteration': iteration, |
| 1076 | 'en': encoder.state_dict(), |
| 1077 | 'de': decoder.state_dict(), |
| 1078 | 'en_opt': encoder_optimizer.state_dict(), |
| 1079 | 'de_opt': decoder_optimizer.state_dict(), |
| 1080 | 'loss': loss, |
| 1081 | 'voc_dict': voc.__dict__, |
| 1082 | 'embedding': embedding.state_dict() |
| 1083 | }, os.path.join(directory, '{}_{}.tar'.format(iteration, 'checkpoint'))) |
| 1084 | |
| 1085 | |
| 1086 | ###################################################################### |
no test coverage detected