python コピー
import torch
import torch.nn as nn
import torch.nn.functional as F
from transformers import AutoTokenizer, DistilBertForSequenceClassification
"""
1. DistilBERT の事前学習の損失(3つの損失)を、論文と公式の学習コードどおりに書いた例
2. 学習済みの DistilBERT を、文の分類にファインチューニングする例
"""
def distil_loss(s_logits, t_logits, s_hidden, t_hidden, labels, attention_mask,
T=2.0, a_ce=5.0, a_mlm=2.0, a_cos=1.0):
"""
s_logits, t_logits: [B, n, 語彙の数] 生徒・教師の単語のスコア
s_hidden, t_hidden: [B, n, 768] 生徒・教師の最終層の出力
labels: [B, n] 隠した位置だけ元の単語の番号、ほかは -100
attention_mask: [B, n] 詰め物の位置は 0
"""
m = attention_mask.bool()
# L_ce:温度 T のソフトマックスで、教師の確率を目標にする(KL で書いても勾配は同じ)。T^2 を掛けて勾配の大きさを保つ
loss_ce = F.kl_div(
F.log_softmax(s_logits[m] / T, dim=-1),
F.softmax(t_logits[m] / T, dim=-1),
reduction="batchmean") * T ** 2
# L_mlm:隠した単語の正解を当てる(温度 1)
loss_mlm = F.cross_entropy(s_logits.view(-1, s_logits.size(-1)), labels.view(-1), ignore_index=-100)
# L_cos:最終層の出力の向きをそろえる(1 - cos)
target = torch.ones(int(m.sum()), device=s_hidden.device)
loss_cos = F.cosine_embedding_loss(s_hidden[m], t_hidden[m], target)
return a_ce * loss_ce + a_mlm * loss_mlm + a_cos * loss_cos
# 形だけ確かめる(本当の学習では、教師は torch.no_grad() の中で計算し、重みを固定する)
B, n, V, H = 2, 8, 30522, 768
labels = torch.full((B, n), -100)
labels[:, 3] = 1000 # 4 番目の位置だけ隠したとする
loss = distil_loss(torch.randn(B, n, V, requires_grad=True), torch.randn(B, n, V),
torch.randn(B, n, H, requires_grad=True), torch.randn(B, n, H),
labels, torch.ones(B, n, dtype=torch.long))
loss.backward()
print(loss.item())
# --- 学習済みの DistilBERT をファインチューニングする ---
name = "distilbert-base-uncased"
tokenizer = AutoTokenizer.from_pretrained(name) # BERT-base と同じ WordPiece の語彙
clf = DistilBertForSequenceClassification.from_pretrained(name, num_labels=2)
optimizer = torch.optim.AdamW(clf.parameters(), lr=5e-5)
batch = tokenizer(["I loved this movie.", "The plot was boring."],
padding=True, truncation=True, max_length=128, return_tensors="pt")
# DistilBERT は token_type_ids を受け取らない(tokenizer も返さない)
labels = torch.tensor([1, 0])
clf.train() # ドロップアウトを有効にする
out = clf(**batch, labels=labels)
out.loss.backward()
optimizer.step()
optimizer.zero_grad()
clf.eval() # 推論ではドロップアウトを止める
with torch.no_grad():
print(clf(**batch).logits.softmax(dim=-1))