Multi-head attention как PyTorch-модуль
Multi-head attention как PyTorch-модуль
Сначала проговорите ответ вслух или тезисами.
Формулы, план решения, риски и примеры.
Откройте разбор только после своей попытки.
Показать разбор
Короткий ответ
Project inputs to Q/K/V first, split the projected tensors into heads, compute scaled dot-product attention per head, concatenate heads, then apply the output projection and feed-forward/residual blocks.
Подробный разбор
A clean answer starts from shapes. For input x with shape batch x seq_len x embed_dim, define linear projections Wq, Wk and Wv. Apply those projections before splitting into heads. Then reshape to batch x num_heads x seq_len x head_dim, where head_dim = embed_dim / num_heads.
For each head, compute attention_scores = QK^T / sqrt(head_dim), softmax over the key sequence dimension, and multiply by V. The result is concatenated back to batch x seq_len x embed_dim and passed through an output projection. In a full Transformer block, this is surrounded by residual connections, LayerNorm and a feed-forward network with a nonlinearity.
Common mistakes are splitting before projection with incompatible dimensions, applying the feed-forward layer before concatenating heads, softmaxing over the wrong axis, forgetting the scale factor, and forgetting that two linear layers without an activation collapse into one linear layer.
Типичные ошибки
- Split raw input heads before Q/K/V projections in a way that breaks dimensions.
- Use softmax over the head or batch dimension.
- Forget output projection, residual, LayerNorm or activation in the feed-forward block.
Как сказать на собеседовании
- Say the shapes out loud after every reshape.
- Mention the full block components even if only attention is implemented.
IoU-метрики детекции и one-to-one matching
Given predicted boxes and ground-truth boxes for one image, design a metric that uses IoU but does not reward duplicate predictions or ignore missed objects.
Решение прямо на странице
Напишите код, запустите проверки и только потом открывайте разбор.
Нажмите «Запустить проверки» или Ctrl+Enter.
Показать разбор
Подсказки
- Не усредняйте все IoU
Модель может выдать много boxes и завысить наивные суммы или максимумы.
- Сопоставление один к одному
Одно предсказание не должно закрывать два разных ground-truth объекта.
Идея решения
Метрика не должна поощрять модель за большое количество дублирующих boxes. Основная идея — сделать сопоставления один к одному: после матчинга предсказания с ground-truth объектом ни одно из них нельзя использовать повторно.
Собираем все кандидатные пары с IoU не ниже порога, сортируем по убыванию IoU с детерминированным tie-break по индексам, затем жадно принимаем пару только если оба её конца ещё не использованы. True positives — принятые пары. False positives — несопоставленные предсказания. False negatives — несопоставленные ground-truth объекты.
Это простой baseline для собеседования. В продакшене, если неоптимальность жадного алгоритма критична, шаг сопоставления можно заменить венгерским алгоритмом или другим методом maximum-weight matching.
Эталонный код
def greedy_iou_matching_summary(iou_matrix: list[list[float]], threshold: float) -> list[float | int]:
gt_count = len(iou_matrix)
pred_count = max((len(row) for row in iou_matrix), default=0)
candidates = []
for gt_idx, row in enumerate(iou_matrix):
for pred_idx, iou in enumerate(row):
if iou >= threshold:
candidates.append((-iou, gt_idx, pred_idx, iou))
candidates.sort()
used_gt = set()
used_pred = set()
matched_ious = []
for _, gt_idx, pred_idx, iou in candidates:
if gt_idx in used_gt or pred_idx in used_pred:
continue
used_gt.add(gt_idx)
used_pred.add(pred_idx)
matched_ious.append(iou)
true_positives = len(matched_ious)
false_positives = pred_count - true_positives
false_negatives = gt_count - true_positives
mean_iou = sum(matched_ious) / true_positives if true_positives else 0.0
return [true_positives, false_positives, false_negatives, mean_iou]Показать разбор
Короткий ответ
Naive averages ignore duplicate predictions and missed objects. Use confidence thresholds and one-to-one matching by IoU, then count TP/FP/FN or compute AP across thresholds.
Подробный разбор
A metric that simply averages IoU over all pairs, or takes the best IoU for every ground truth without penalizing extra predictions, can be gamed by emitting many boxes. The model may get a high maximum somewhere while creating many false positives.
For a fixed confidence threshold, build candidate matches between predictions and ground truth using an IoU threshold. Then enforce one-to-one matching: each prediction and each ground-truth object can participate in at most one match. Matched pairs are true positives, unmatched predictions are false positives and unmatched ground truth objects are false negatives. Depending on the product, matching can be greedy, Hungarian or another assignment strategy.
Average Precision extends the idea across confidence thresholds and is useful when predictions have scores. For a final production threshold, TP/FP/FN, precision, recall and mean matched IoU are often easier to reason about.
Типичные ошибки
- Ignore extra predicted boxes.
- Allow one prediction to match multiple ground-truth objects.
- Use AP when there are no scores or thresholds to sweep.
Как сказать на собеседовании
- State what happens to unmatched predictions and unmatched ground truth.
- Mention that the right matching policy depends on the product.