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

Function train_cosine_loss

beginner_source/knowledge_distillation_tutorial.py:487–525  ·  view source on GitHub ↗
(teacher, student, train_loader, epochs, learning_rate, hidden_rep_loss_weight, ce_loss_weight, device)

Source from the content-addressed store, hash-verified

485#
486
487def train_cosine_loss(teacher, student, train_loader, epochs, learning_rate, hidden_rep_loss_weight, ce_loss_weight, device):
488 ce_loss = nn.CrossEntropyLoss()
489 cosine_loss = nn.CosineEmbeddingLoss()
490 optimizer = optim.Adam(student.parameters(), lr=learning_rate)
491
492 teacher.to(device)
493 student.to(device)
494 teacher.eval() # Teacher set to evaluation mode
495 student.train() # Student to train mode
496
497 for epoch in range(epochs):
498 running_loss = 0.0
499 for inputs, labels in train_loader:
500 inputs, labels = inputs.to(device), labels.to(device)
501
502 optimizer.zero_grad()
503
504 # Forward pass with the teacher model and keep only the hidden representation
505 with torch.no_grad():
506 _, teacher_hidden_representation = teacher(inputs)
507
508 # Forward pass with the student model
509 student_logits, student_hidden_representation = student(inputs)
510
511 # Calculate the cosine loss. Target is a vector of ones. From the loss formula above we can see that is the case where loss minimization leads to cosine similarity increase.
512 hidden_rep_loss = cosine_loss(student_hidden_representation, teacher_hidden_representation, target=torch.ones(inputs.size(0)).to(device))
513
514 # Calculate the true label loss
515 label_loss = ce_loss(student_logits, labels)
516
517 # Weighted sum of the two losses
518 loss = hidden_rep_loss_weight * hidden_rep_loss + ce_loss_weight * label_loss
519
520 loss.backward()
521 optimizer.step()
522
523 running_loss += loss.item()
524
525 print(f"Epoch {epoch+1}/{epochs}, Loss: {running_loss / len(train_loader)}")
526
527######################################################################
528#We need to modify our test function for the same reason. Here we ignore the hidden representation returned by the model.

Calls 2

stepMethod · 0.80
backwardMethod · 0.45

Tested by

no test coverage detected