MCPcopy Create free account
hub / github.com/pytorch/tutorials / train_mse_loss

Function train_mse_loss

beginner_source/knowledge_distillation_tutorial.py:660–698  ·  view source on GitHub ↗
(teacher, student, train_loader, epochs, learning_rate, feature_map_weight, ce_loss_weight, device)

Source from the content-addressed store, hash-verified

658# in addition to the regular cross entropy loss of the classification task.
659
660def train_mse_loss(teacher, student, train_loader, epochs, learning_rate, feature_map_weight, ce_loss_weight, device):
661 ce_loss = nn.CrossEntropyLoss()
662 mse_loss = nn.MSELoss()
663 optimizer = optim.Adam(student.parameters(), lr=learning_rate)
664
665 teacher.to(device)
666 student.to(device)
667 teacher.eval() # Teacher set to evaluation mode
668 student.train() # Student to train mode
669
670 for epoch in range(epochs):
671 running_loss = 0.0
672 for inputs, labels in train_loader:
673 inputs, labels = inputs.to(device), labels.to(device)
674
675 optimizer.zero_grad()
676
677 # Again ignore teacher logits
678 with torch.no_grad():
679 _, teacher_feature_map = teacher(inputs)
680
681 # Forward pass with the student model
682 student_logits, regressor_feature_map = student(inputs)
683
684 # Calculate the loss
685 hidden_rep_loss = mse_loss(regressor_feature_map, teacher_feature_map)
686
687 # Calculate the true label loss
688 label_loss = ce_loss(student_logits, labels)
689
690 # Weighted sum of the two losses
691 loss = feature_map_weight * hidden_rep_loss + ce_loss_weight * label_loss
692
693 loss.backward()
694 optimizer.step()
695
696 running_loss += loss.item()
697
698 print(f"Epoch {epoch+1}/{epochs}, Loss: {running_loss / len(train_loader)}")
699
700# Notice how our test function remains the same here with the one we used in our previous case. We only care about the actual outputs because we measure accuracy.
701

Calls 2

stepMethod · 0.80
backwardMethod · 0.45

Tested by

no test coverage detected