MCPcopy Create free account
hub / github.com/pytorch/examples / train

Function train

word_language_model/main.py:163–208  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

161
162
163def train():
164 # Turn on training mode which enables dropout.
165 model.train()
166 total_loss = 0.
167 start_time = time.time()
168 ntokens = len(corpus.dictionary)
169 if args.model != 'Transformer':
170 hidden = model.init_hidden(args.batch_size)
171 for batch, i in enumerate(range(0, train_data.size(0) - 1, args.bptt)):
172 data, targets = get_batch(train_data, i)
173 # Starting each batch, we detach the hidden state from how it was previously produced.
174 # If we didn't, the model would try backpropagating all the way to start of the dataset.
175 if args.use_optimizer:
176 optimizer.zero_grad()
177 else:
178 model.zero_grad()
179 if args.model == 'Transformer':
180 output = model(data)
181 output = output.view(-1, ntokens)
182 else:
183 hidden = repackage_hidden(hidden)
184 output, hidden = model(data, hidden)
185 loss = criterion(output, targets)
186 loss.backward()
187
188 # `clip_grad_norm` helps prevent the exploding gradient problem in RNNs / LSTMs.
189 torch.nn.utils.clip_grad_norm_(model.parameters(), args.clip)
190 if args.use_optimizer:
191 optimizer.step()
192 else:
193 for p in model.parameters():
194 p.data.add_(p.grad, alpha=-lr)
195
196 total_loss += loss.item()
197
198 if batch % args.log_interval == 0 and batch > 0:
199 cur_loss = total_loss / args.log_interval
200 elapsed = time.time() - start_time
201 print('| epoch {:3d} | {:5d}/{:5d} batches | lr {:02.2f} | ms/batch {:5.2f} | '
202 'loss {:5.2f} | ppl {:8.2f}'.format(
203 epoch, batch, len(train_data) // args.bptt, lr,
204 elapsed * 1000 / args.log_interval, cur_loss, math.exp(cur_loss)))
205 total_loss = 0
206 start_time = time.time()
207 if args.dry_run:
208 break
209
210
211def export_onnx(path, batch_size, seq_len):

Callers 1

main.pyFile · 0.70

Calls 4

repackage_hiddenFunction · 0.85
init_hiddenMethod · 0.80
get_batchFunction · 0.70
trainMethod · 0.45

Tested by

no test coverage detected