python
import torch
import torch.nn as nn
import torch.nn.functional as F
from scipy.optimize import linear_sum_assignment
from torchvision.models import resnet50, ResNet50_Weights
from torchvision.ops import box_convert, generalized_box_iou
'''
DETR を論文の付録の推論コード(Listing 1)をもとに組み、ハンガリアン法の対応付けと損失(式 1・式 2)を足した小さな実装。
Listing 1 と同じく、読みやすさのために位置エンコーディングは学習する埋め込みにし、入力に 1 回だけ足す
(論文の本来の設定は、固定の sin・cos を各注意層に足す)。torchvision には DETR の組み込みのモデルはない
'''
class DETR(nn.Module):
def __init__(self, num_classes, hidden_dim=256, nheads=8, num_encoder_layers=6, num_decoder_layers=6, num_queries=100):
super().__init__()
# ResNet-50 の畳み込み層だけを使う(2048 チャネル、縦横 1/32)
self.backbone = nn.Sequential(*list(resnet50(weights=ResNet50_Weights.IMAGENET1K_V1).children())[:-2])
self.conv = nn.Conv2d(2048, hidden_dim, 1) # 1×1 畳み込みで d = 256 に減らす
self.transformer = nn.Transformer(hidden_dim, nheads, num_encoder_layers, num_decoder_layers, dropout=0.1)
self.linear_class = nn.Linear(hidden_dim, num_classes + 1) # 最後の 1 つは「物体なし ∅」
self.bbox_mlp = nn.Sequential( # 枠は 3 層の MLP(ReLU)
nn.Linear(hidden_dim, hidden_dim), nn.ReLU(),
nn.Linear(hidden_dim, hidden_dim), nn.ReLU(),
nn.Linear(hidden_dim, 4))
self.query_pos = nn.Parameter(torch.rand(num_queries, hidden_dim)) # 物体クエリ(N = 100)
self.row_embed = nn.Parameter(torch.rand(50, hidden_dim // 2))
self.col_embed = nn.Parameter(torch.rand(50, hidden_dim // 2))
def forward(self, inputs): # inputs: (1, 3, H0, W0)(Listing 1 と同じく 1 枚ずつ)
h = self.conv(self.backbone(inputs))
H, W = h.shape[-2:]
pos = torch.cat([
self.col_embed[:W].unsqueeze(0).repeat(H, 1, 1),
self.row_embed[:H].unsqueeze(1).repeat(1, W, 1),
], dim=-1).flatten(0, 1).unsqueeze(1) # (HW, 1, d)
h = self.transformer(pos + h.flatten(2).permute(2, 0, 1), # エンコーダへ:HW 個の並び
self.query_pos.unsqueeze(1)) # デコーダへ:N 個のクエリを並列に
return self.linear_class(h)[:, 0], self.bbox_mlp(h).sigmoid()[:, 0] # (N, クラス数 + 1)、(N, 4) = (cx, cy, w, h)
@torch.no_grad()
def hungarian_match(logits, boxes, tgt_labels, tgt_boxes, l1_weight=5.0, giou_weight=2.0):
'''式(1):対応のコスト = −p̂(c) + 5 × L1 + 2 × (1 − GIoU) を最小にする 1 対 1 の対応'''
prob = logits.softmax(-1) # 対応のコストでは対数を取らない確率を使う
cost_class = -prob[:, tgt_labels] # (N, 正解の数)
cost_l1 = torch.cdist(boxes, tgt_boxes, p=1)
cost_giou = 1 - generalized_box_iou(box_convert(boxes, 'cxcywh', 'xyxy'), box_convert(tgt_boxes, 'cxcywh', 'xyxy'))
cost = cost_class + l1_weight * cost_l1 + giou_weight * cost_giou
pred_idx, tgt_idx = linear_sum_assignment(cost.cpu().numpy()) # ハンガリアン法
return torch.as_tensor(pred_idx), torch.as_tensor(tgt_idx)
def hungarian_loss(logits, boxes, tgt_labels, tgt_boxes, num_classes, eos_weight=0.1, l1_weight=5.0, giou_weight=2.0):
'''式(2):対応した組ごとのクラスの損失と、物体のある組だけの枠の損失'''
pred_idx, tgt_idx = hungarian_match(logits, boxes, tgt_labels, tgt_boxes, l1_weight, giou_weight)
target_classes = torch.full((logits.shape[0],), num_classes, dtype=torch.long) # 対応しないスロットは ∅
target_classes[pred_idx] = tgt_labels[tgt_idx]
class_weight = torch.ones(num_classes + 1)
class_weight[num_classes] = eos_weight # ∅ の重みは 1/10
loss_class = F.cross_entropy(logits, target_classes, weight=class_weight)
num_objects = max(len(tgt_labels), 1) # 枠の損失は物体の数で割る
src, tgt = boxes[pred_idx], tgt_boxes[tgt_idx]
loss_l1 = F.l1_loss(src, tgt, reduction='sum') / num_objects
loss_giou = (1 - torch.diag(generalized_box_iou(box_convert(src, 'cxcywh', 'xyxy'),
box_convert(tgt, 'cxcywh', 'xyxy')))).sum() / num_objects
return loss_class + l1_weight * loss_l1 + giou_weight * loss_giou
num_classes = 91 # COCO のクラスの番号(Listing 1 と同じ)
model = DETR(num_classes)
# Transformer は 1e-4、基盤の CNN は 1e-5、Weight Decay は 1e-4(論文 4 章・付録 A.4)
param_groups = [
{'params': [p for n, p in model.named_parameters() if not n.startswith('backbone')], 'lr': 1e-4},
{'params': model.backbone.parameters(), 'lr': 1e-5},
]
optimizer = torch.optim.AdamW(param_groups, weight_decay=1e-4)
# 1 ステップの例(データの読み込みは省略)。正解の枠は画像に対する (cx, cy, w, h)
image = torch.randn(1, 3, 800, 1066)
tgt_labels = torch.tensor([18, 17]) # 例:犬と猫
tgt_boxes = torch.tensor([[0.30, 0.55, 0.40, 0.60], [0.75, 0.50, 0.30, 0.45]])
model.train() # Transformer の dropout 0.1 が効く
logits, boxes = model(image)
loss = hungarian_loss(logits, boxes, tgt_labels, tgt_boxes, num_classes)
optimizer.zero_grad()
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=0.1) # 勾配の大きさを 0.1 で切り詰める
optimizer.step()
model.eval() # 推論:非最大値抑制はかけない
with torch.no_grad():
logits, boxes = model(image)
prob = logits.softmax(-1)[:, :-1] # ∅ を除いたクラスの確率
keep = prob.max(-1).values > 0.7
print(prob[keep].argmax(-1), boxes[keep])
# 論文の著者が公開した学習済みモデルは torch.hub から読み込める
# detr = torch.hub.load('facebookresearch/detr:main', 'detr_resnet50', pretrained=True)