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

Function train

language_translation/main.py:109–150  ·  view source on GitHub ↗
(model, train_dl, loss_fn, optim, special_symbols, opts)

Source from the content-addressed store, hash-verified

107
108# Train the model for 1 epoch
109def train(model, train_dl, loss_fn, optim, special_symbols, opts):
110
111 # Object for accumulating losses
112 losses = 0
113
114 # Put model into training mode
115 model.train()
116 for src, tgt in tqdm(train_dl, ascii=True):
117
118 src = src.to(DEVICE)
119 tgt = tgt.to(DEVICE)
120
121 # We need to reshape the input slightly to fit into the transformer
122 tgt_input = tgt[:-1, :]
123
124 # Create masks
125 src_mask, tgt_mask, src_padding_mask, tgt_padding_mask = create_mask(src, tgt_input, special_symbols["<pad>"], DEVICE)
126
127 # Pass into model, get probability over the vocab out
128 logits = model(src, tgt_input, src_mask, tgt_mask,src_padding_mask, tgt_padding_mask, src_padding_mask)
129
130 # Reset gradients before we try to compute the gradients over the loss
131 optim.zero_grad()
132
133 # Get original shape back
134 tgt_out = tgt[1:, :]
135
136 # Compute loss and gradient over that loss
137 loss = loss_fn(logits.reshape(-1, logits.shape[-1]), tgt_out.reshape(-1))
138 loss.backward()
139
140 # Step weights
141 optim.step()
142
143 # Accumulate a running loss for reporting
144 losses += loss.item()
145
146 if opts.dry_run:
147 break
148
149 # Return the average loss
150 return losses / len(list(train_dl))
151
152# Check the model accuracy on the validation dataset
153def validate(model, valid_dl, loss_fn, special_symbols):

Callers 1

mainFunction · 0.70

Calls 2

create_maskFunction · 0.90
trainMethod · 0.45

Tested by

no test coverage detected