MCPcopy Create free account
hub / github.com/lingeringlight/START / forward

Method forward

losses.py:25–70  ·  view source on GitHub ↗

Args: inputs: The original inputs that are feed to the teacher model outputs: the outputs of the model to be trained. It is expected to be either a Tensor, or a Tuple[Tensor, Tensor], with the original output in the first position and

(self, inputs, outputs, labels)

Source from the content-addressed store, hash-verified

23 self.tau = tau
24
25 def forward(self, inputs, outputs, labels):
26 """
27 Args:
28 inputs: The original inputs that are feed to the teacher model
29 outputs: the outputs of the model to be trained. It is expected to be
30 either a Tensor, or a Tuple[Tensor, Tensor], with the original output
31 in the first position and the distillation predictions as the second output
32 labels: the labels for the base criterion
33 """
34 outputs_kd = None
35 if not isinstance(outputs, torch.Tensor):
36 # assume that the model outputs a tuple of [outputs, outputs_kd]
37 outputs, outputs_kd = outputs
38 base_loss = self.base_criterion(outputs, labels)
39 if self.distillation_type == 'none':
40 return base_loss
41
42 if outputs_kd is None:
43 raise ValueError("When knowledge distillation is enabled, the model is "
44 "expected to return a Tuple[Tensor, Tensor] with the output of the "
45 "class_token and the dist_token")
46 # don't backprop throught the teacher
47 with torch.no_grad():
48 teacher_outputs = self.teacher_model(inputs)
49
50 if self.distillation_type == 'soft':
51 T = self.tau
52 # taken from https://github.com/peterliht/knowledge-distillation-pytorch/blob/master/model/net.py#L100
53 # with slight modifications
54 distillation_loss = F.kl_div(
55 F.log_softmax(outputs_kd / T, dim=1),
56 #We provide the teacher's targets in log probability because we use log_target=True
57 #(as recommended in pytorch https://github.com/pytorch/pytorch/blob/9324181d0ac7b4f7949a574dbc3e8be30abe7041/torch/nn/functional.py#L2719)
58 #but it is possible to give just the probabilities and set log_target=False. In our experiments we tried both.
59 F.log_softmax(teacher_outputs / T, dim=1),
60 reduction='sum',
61 log_target=True
62 ) * (T * T) / outputs_kd.numel()
63 #We divide by outputs_kd.numel() to have the legacy PyTorch behavior.
64 #But we also experiments output_kd.size(0)
65 #see issue 61(https://github.com/facebookresearch/deit/issues/61) for more details
66 elif self.distillation_type == 'hard':
67 distillation_loss = F.cross_entropy(outputs_kd, teacher_outputs.argmax(dim=1))
68
69 loss = base_loss * (1 - self.alpha) + distillation_loss * self.alpha
70 return loss

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected