Pairwise Dot-Product Contrastive Loss
Hard · Machine Learning · Machine Learning Engineer · Technical Screen
Problem Statement
During representation-learning model development, an engineer wrote the following in-batch contrastive objective and ran into shape failures on rectangular batches (and silent miscalculations on square batches):
import torch
import torch.nn.functional as F
def buggy_loss(z1, z2, temperature):
scores = torch.matmul(z1, z2) / temperature
targets = torch.arange(z1.shape[0], device=z1.device)
return F.cross_entropy(scores, targets)
Here z1 and z2 represent two aligned embedding batches of shape [B, D] (B items, D coordinates per item), where z1[i] is the i-th anchor, z2[i] is its sole matching positive candidate, and all z2[j] with j != i act as negative distractors. Because torch.matmul(z1, z2) attempts [B, D] @ [B, D] without transposing z2, it contracts incompatible axes rather than computing [B, B] pairwise dot products across the D-dimensional feature axis.
Implement the repaired pure-Python loss function:
def contrastive_loss(
z1: List[List[float]],
z2: List[List[float]],
temperature: float,
) -> float:
Scoring & Numerical Rules
- One-directional dot-product logits:
- Compute raw unnormalized dot products between every anchor
z1[i]and every candidatez2[j], divided bytemperature:logits[i][j] = dot(z1[i], z2[j]) / temperaturefor0 <= i, j < B. - Do not apply L2 normalization to rows, and do not average with the reverse
z2 -> z1direction.
- Compute raw unnormalized dot products between every anchor
- Diagonal cross-entropy:
- Return the mean across
i = 0, ..., B - 1of-log(softmax(logits[i])[i])as afloat. - Evaluate softmax cross-entropy stably (for instance via row-maximum shifting) so large finite logits such as
1000.0never overflowexp. (In a PyTorch training loop withfloat16orbfloat16inputs, tensors should likewise be cast tofloat32prior toz1 @ z2.Twith autocast disabled so gradients propagate cleanly.)
- Return the mean across
- Validation & exceptions:
- Do not modify the caller's input lists.
- Raise
ValueErrorifz1orz2is not a non-empty rectangular 2D sequence (list/tupleoflist/tuple), ifB == 0orD == 0, ifz1andz2differ in shape, if any element ortemperatureis abool, non-numeric, non-finite (nan/inf), or an integer too large forfloat, or iftemperature <= 0. - Raise
FloatingPointErrorif any computed entrylogits[i][j]is non-finite (inf,-inf, ornan) due to overflow orinf - infcancellation.
Examples
Example 1
Input:
z1 = [[2.0, 0.0, 1.0], [0.0, 1.0, 2.0]]
z2 = [[1.0, 2.0, 0.0], [0.0, 1.0, 1.0]]
temperature = 0.5
Output: 0.1269280110429726
- Transposing
z2contracts the length-3embedding axis ([2, 3] @ [3, 2] -> [2, 2]), producing dot products[[2.0, 1.0], [2.0, 3.0]]and scaledlogits = [[4.0, 2.0], [4.0, 6.0]]. - Row
0targets column0(4.0vs2.0, lossln(1 + e^-2)) and row1targets column1(6.0vs4.0, lossln(1 + e^-2)), averaging toln(1 + e^-2) ≈ 0.1269280110429726.
Example 2
Input:
z1 = [[1.0, 3.0], [2.0, 1.0]]
z2 = [[2.0, 0.0], [1.0, 2.0]]
temperature = 1.0
Output: 2.849931264524532
- Because
B == D == 2, an untransposedz1 @ z2would silently produce[[5.0, 6.0], [5.0, 2.0]]. Usingz1 @ z2.Tyields the true pairwise scoreslogits = [[2.0, 7.0], [4.0, 4.0]]. - Row
0pays5.0 + ln(1 + e^-5)(negative candidatez2[1]outscores positivez2[0]), while row1ties4.0vs4.0and paysln(2). Their mean is(5.0 + ln(1 + e^-5) + ln(2)) / 2 ≈ 2.849931264524532.
Example 3
Input:
z1 = [[4.0, -1.0, 2.0]]
z2 = [[-2.0, 3.0, 5.0]]
temperature = 0.25
Output: 0.0
- A batch of size
B = 1contains only one candidate per anchor (logits = [[0.0]]), so softmax assigns probability1.0to column0and-ln(1.0) = 0.0.
Constraints
- Valid matrices satisfy
1 <= B, Dwith identical[B, D]dimensions acrossz1andz2 - Matrix entries must be finite
intorfloatvalues (neverbool) convertible to IEEE-754float64 temperaturemust be a finiteintorfloat(neverbool) withtemperature > 0- Invalid shapes, dtypes,
boolvalues, non-finite inputs, ortemperature <= 0raiseValueError - Non-finite entries in
(z1 @ z2.T) / temperatureraiseFloatingPointError
Step-by-step walkthrough
Understand what contrastive loss computes
In contrastive learning, we have two aligned views of the same batch of items:
z1andz2, each shaped[B, D](B = batch_sizeitems,D = embedding_dimnumbers per item). Rowiofz1is an anchor, rowiofz2is its positive partner (the matching item), and all other rowsj != iofz2act as negatives (distractors).For every anchor
i, we want a row ofBcompatibility scores (logits), one against each candidate rowjinz2, scaled bytemperature:z1 (anchors) z2 (candidates) logits (pairwise scores) labels [B, D] [B, D] [B, B] [B] [ z1[0] ] [ z2[0] ] [ + - - ] <- anchor 0 0 [ z1[1] ] vs [ z2[1] ] ---> [ - + - ] <- anchor 1 1 [ z1[2] ] [ z2[2] ] [ - - + ] <- anchor 2 2 ^ ^ ^ z2[0] z2[1] z2[2]Because row
iofz1matches rowiofz2, the positive score for rowisits right on the diagonal (column i), which is whylabels = [0, 1, ..., B - 1]. We then treat each row as aB-way classification problem and average the cross-entropy loss across allBrows.The automated judge runs in pure Python without PyTorch, passing
z1andz2as 2D lists (List[List[float]]) and expecting afloat. Below we build the exact pure-Python solution step by step, and also show the PyTorch tensor version side by side.Spot the matrix-multiplication shape bug
2D matrix multiplication
A @ Bpairs each row ofAwith each column ofB. For those dot products to line up, the inner dimensions must match:[rows_A, inner] @ [inner, cols_B] -> [rows_A, cols_B].Look at what happens when we pass
z1andz2directly intotorch.matmul(z1, z2)without transposingz2:Buggy: z1 @ z2 shapes [B, D] @ [B, D] -> inner dims D vs B collide! Fixed: z1 @ z2.T shapes [B, D] @ [D, B] -> inner dims D == D -> [B, B]This bug fails in two very different ways depending on the batch size:
- When
B != D(most real batches, as in Example 1's2 x 3inputs): PyTorch immediately raises aRuntimeErrorcomplaining that shapes[B, D]and[B, D]cannot be multiplied. - When
B == D(square batches, as in Example 2's2 x 2inputs): The code runs without crashing and returns the wrong number! Entry[i][j]computessum_k z1[i][k] * z2[k][j], multiplying featurekof anchoriagainst batch samplekofz2. Because the output still has shape[B, B],F.cross_entropyaccepts it silently. Even worse, ifz2happens to be symmetric (such as an identity matrix[[1, 0], [0, 1]]),z2 == z2.T, hiding the bug completely!
Transposing
z2(z1 @ z2.T, orz2.transpose(0, 1)) puts theDfeatures of eachz2[j]down columnj, sologits[i][j]becomesdot(z1[i], z2[j]) / temperature.- When
Validate inputs and edge types
Before computing any scores, we verify every assumption and raise
ValueErroron invalid inputs so bad calls never fail mysteriously deep inside the math:- Numbers, not Booleans or
nan/inf: In Python,boolis a subclass ofint(isinstance(True, int)evaluates toTrue!). We must checkisinstance(value, bool)beforeisinstance(value, (int, float)). Also, converting a gigantic Pythonintsuch as10**400withfloat(value)raisesOverflowError, so we catch that and raiseValueError. - Non-empty rectangular 2D shapes: Both
z1andz2must haveB > 0rows,D > 0columns, equal row lengths, and identical[B, D]dimensions. - Positive finite temperature:
temperature <= 0would either divide by zero or invert the ranking (penalizing high similarity and rewarding negatives).
def to_finite_float(value: Any, label: str) -> float: """Validate that value is a finite int or float (not bool) and return float(value).""" # In Python, bool is a subclass of int (isinstance(True, int) is True), # so we must reject Booleans explicitly before checking (int, float). if isinstance(value, bool) or not isinstance(value, (int, float)): raise ValueError(f"{label} must be an int or float, got {type(value).__name__}") try: as_float = float(value) except OverflowError: # Huge Python integers (beyond ~1.8e308) raise OverflowError in float(); # convert that into the ValueError required for invalid inputs. raise ValueError(f"{label} is too large to fit in a float") from None if not math.isfinite(as_float): raise ValueError(f"{label} must be finite, got {value!r}") return as_float def validate_matrix(matrix: List[List[float]], name: str) -> List[List[float]]: """Validate a non-empty rectangular [B, D] 2D sequence and return a float copy.""" # clean_rows: [B, D] list of validated Python floats, with B > 0 and D > 0. if not isinstance(matrix, (list, tuple)) or len(matrix) == 0: raise ValueError(f"{name} must be a non-empty 2D sequence (batch_size > 0)") first_row = matrix[0] if not isinstance(first_row, (list, tuple)) or len(first_row) == 0: raise ValueError(f"{name} must be rank-2 with embedding_dim > 0") expected_dim = len(first_row) clean_rows: List[List[float]] = [] for row in matrix: if not isinstance(row, (list, tuple)) or len(row) != expected_dim: raise ValueError(f"{name} must be rectangular with consistent row lengths") clean_row: List[float] = [] for entry in row: clean_row.append(to_finite_float(entry, f"{name} entry")) clean_rows.append(clean_row) return clean_rows def validate_temperature(temperature: float) -> float: """Validate that temperature is a finite, strictly positive number.""" temp_value = to_finite_float(temperature, "temperature") # Temperature <= 0 would divide by zero or flip positive similarities into penalties. if temp_value <= 0.0: raise ValueError("temperature must be strictly positive") return temp_value- Numbers, not Booleans or
Build the pairwise score matrix and check finiteness
In pure Python,
(z1 @ z2.T) / temperatureis a double loop over everyanchor_rowinz1and everycandidate_rowinz2, taking their dot product across theDcoordinates and dividing bytemperature.Even when all inputs are finite, a logit can become non-finite in three ways: -
a_val * c_valoverflowsfloat64(for example1e200 * 1e200 -> inf), - two overflowing products of opposite signs cancel (inf + (-inf) -> nan), or - dividing a large dot product by a tinytemperatureoverflows (1e300 / 1e-10 -> inf).As required by the specification, we check
math.isfinite(logit)and raiseFloatingPointErrorwhenever any logit isinf,-inf, ornan.def compute_logits( anchors: List[List[float]], candidates: List[List[float]], temperature: float, ) -> List[List[float]]: """Compute [B, B] pairwise scores: logits[i][j] = dot(anchors[i], candidates[j]) / temperature.""" # Equivalent to (z1 @ z2.T) / temperature: contract along the D embedding dimension # so row i scores anchor i against every candidate j in z2. logits: List[List[float]] = [] for anchor_row in anchors: score_row: List[float] = [] for candidate_row in candidates: dot_product = 0.0 for a_val, c_val in zip(anchor_row, candidate_row): dot_product += a_val * c_val logit = dot_product / temperature # Finite inputs can still overflow to inf or cancel (inf + -inf) to nan. if not math.isfinite(logit): raise FloatingPointError("non-finite value encountered in logits") score_row.append(logit) logits.append(score_row) return logitsCompute cross-entropy safely with the max-shift trick
For anchor row
iwith scoress_0, s_1, ..., s_(B-1), softmax turns scores into probabilitiesexp(s_j) / sum_j exp(s_j), and cross-entropy takes-logof the probability at the true targetj = i.If we compute
math.exp(s_j)directly, any finite logit above709.78overflowsfloat64! Dividing by a smalltemperaturemakes large logits very common. To prevent overflow, letm = max(s_0, ..., s_(B-1))be the largest score in the row, and divide both the top and bottom of the softmax fraction byexp(m):loss_i = -log( exp(s_i) / sum_j exp(s_j) ) = -log( exp(s_i - m) / sum_j exp(s_j - m) ) = -(s_i - m) + log( sum_j exp(s_j - m) ) = (m - s_i) + log( sum_j exp(s_j - m) )Why is this rock-solid? - Every shifted value
s_j - mis<= 0, soexp(s_j - m)is always between0and1— it cannot overflow. - At least one entry equalsm, contributingexp(0) = 1.0, sosum_j exp(s_j - m) >= 1.0—math.lognever sees0. - Writing(m - s_i)first means that when the positive scores_iis already the row maximumm,m - s_icancels to0.0before adding the tinylogterm.def mean_diagonal_cross_entropy(logits: List[List[float]]) -> float: """Compute the mean of -log(softmax(logits[i])[i]) across all B anchor rows.""" # Positive pairs are aligned by row index, so anchor i's true target is column i. batch_size = len(logits) total_loss = 0.0 for i, score_row in enumerate(logits): # Log-sum-exp max-shift: subtracting row_max makes every (score - row_max) <= 0, # so math.exp never overflows and exp_sum >= 1.0 (avoiding log(0)). row_max = max(score_row) exp_sum = 0.0 for score in score_row: exp_sum += math.exp(score - row_max) # Group (row_max - score_row[i]) first so equal huge numbers cancel to 0.0 cleanly. positive_score = score_row[i] row_loss = (row_max - positive_score) + math.log(exp_sum) total_loss += row_loss return total_loss / batch_sizeHandle low precision and autograd in PyTorch
In a real PyTorch training loop, two extra concerns appear: half-precision dtypes (
float16andbfloat16) and preserving gradients.float16overflows easily: Its largest finite value is65504. If two 512-dimensional vectors have entries around3.0, their dot product is around512 * 9 = 4608, and dividing bytemperature = 0.07gives65828.6 -> inf!bfloat16loses fine distinctions: It hasfloat32's range, but only 8 significant bits (7 fraction bits), so numbers between64and128jump in steps of0.5, wiping out subtle ranking differences between candidates.
Therefore, we must upcast
z1andz2with.float()before the matrix multiplication (castinglogits.float()afterwards is too late — the overflow or rounding already happened!), and disabletorch.autocastaround the block so PyTorch's automatic mixed precision does not downcastz1 @ z2.Tback to half precision. Because.float()is a differentiable PyTorch operation and we never call.detach(),.item(), or.numpy(), gradients flow cleanly back toz1andz2:import math import torch import torch.nn.functional as F def contrastive_loss_torch(z1: torch.Tensor, z2: torch.Tensor, temperature: float) -> torch.Tensor: if not isinstance(z1, torch.Tensor) or not isinstance(z2, torch.Tensor): raise ValueError("z1 and z2 must be PyTorch tensors") if z1.dim() != 2 or z1.shape != z2.shape: raise ValueError(f"expected matching [B, D] shapes, got {tuple(z1.shape)} and {tuple(z2.shape)}") if z1.shape[0] == 0 or z1.shape[1] == 0: raise ValueError("batch_size and embedding_dim must both be positive") if z1.dtype != z2.dtype or not z1.is_floating_point(): raise ValueError("z1 and z2 must share the same floating-point dtype") if z1.device != z2.device: raise ValueError("z1 and z2 must be on the same device") if isinstance(temperature, bool) or not isinstance(temperature, (int, float)): raise ValueError("temperature must be a Python int or float") if not math.isfinite(temperature) or temperature <= 0: raise ValueError("temperature must be finite and positive") if not (torch.isfinite(z1).all() and torch.isfinite(z2).all()): raise ValueError("z1 and z2 must contain only finite values") # Upcast reduced-precision inputs BEFORE matmul; .float() keeps autograd intact. if z1.dtype in (torch.float16, torch.bfloat16): z1 = z1.float() z2 = z2.float() with torch.autocast(device_type=z1.device.type, enabled=False): logits = (z1 @ z2.T) / temperature # [B, D] @ [D, B] -> [B, B] if not torch.isfinite(logits).all(): raise FloatingPointError("logits are not finite") labels = torch.arange(z1.shape[0], device=z1.device) return F.cross_entropy(logits, labels)Trace Example 2 step by step
Let's trace
z1 = [[1.0, 3.0], [2.0, 1.0]],z2 = [[2.0, 0.0], [1.0, 2.0]],temperature = 1.0:1. Transpose z2 so columns are candidates: z1 = [ 1.0 3.0 ] z2.T = [ 2.0 1.0 ] [ 2.0 1.0 ] [ 0.0 2.0 ] 2. Dot products (z1 @ z2.T), then divide by temperature = 1.0: dot(z1[0], z2[0]) = 1*2 + 3*0 = 2.0 -> 2.0 / 1.0 = 2.0 (positive for row 0) dot(z1[0], z2[1]) = 1*1 + 3*2 = 7.0 -> 7.0 / 1.0 = 7.0 (negative for row 0) dot(z1[1], z2[0]) = 2*2 + 1*0 = 4.0 -> 4.0 / 1.0 = 4.0 (negative for row 1) dot(z1[1], z2[1]) = 2*1 + 1*2 = 4.0 -> 4.0 / 1.0 = 4.0 (positive for row 1) logits = [ [2.0, 7.0], [4.0, 4.0] ] 3. Max-shifted cross-entropy per row: Row 0 (target col 0, row_max = 7.0): loss_0 = (7.0 - 2.0) + log(exp(-5.0) + exp(0.0)) = 5.0 + log(1 + exp(-5)) ~= 5.0067153485 Row 1 (target col 1, row_max = 4.0): loss_1 = (4.0 - 4.0) + log(exp(0.0) + exp(0.0)) = 0.0 + log(2) ~= 0.6931471806 4. Mean loss = (loss_0 + loss_1) / 2 ~= 2.8499312645Notice how anchor 0 prefers negative
z2[1](7.0) over its own positivez2[0](2.0), paying ~5.0067nats of penalty, while anchor 1 scores4.0on both candidates (50/50tie), payinglog(2) ~= 0.6931. By contrast, the buggyz1 @ z2would have producedlogits = [[5.0, 6.0], [5.0, 2.0]]and returned ~2.1809without raising any error!Put the full solution together
Combining validation, pairwise logit computation, finiteness checking, and max-shifted diagonal cross-entropy gives the complete solution:
import math from typing import Any, Dict, List, Optional, Set, Tuple def to_finite_float(value: Any, label: str) -> float: """Validate that value is a finite int or float (not bool) and return float(value).""" # In Python, bool is a subclass of int (isinstance(True, int) is True), # so we must reject Booleans explicitly before checking (int, float). if isinstance(value, bool) or not isinstance(value, (int, float)): raise ValueError(f"{label} must be an int or float, got {type(value).__name__}") try: as_float = float(value) except OverflowError: # Huge Python integers (beyond ~1.8e308) raise OverflowError in float(); # convert that into the ValueError required for invalid inputs. raise ValueError(f"{label} is too large to fit in a float") from None if not math.isfinite(as_float): raise ValueError(f"{label} must be finite, got {value!r}") return as_float def validate_matrix(matrix: List[List[float]], name: str) -> List[List[float]]: """Validate a non-empty rectangular [B, D] 2D sequence and return a float copy.""" # clean_rows: [B, D] list of validated Python floats, with B > 0 and D > 0. if not isinstance(matrix, (list, tuple)) or len(matrix) == 0: raise ValueError(f"{name} must be a non-empty 2D sequence (batch_size > 0)") first_row = matrix[0] if not isinstance(first_row, (list, tuple)) or len(first_row) == 0: raise ValueError(f"{name} must be rank-2 with embedding_dim > 0") expected_dim = len(first_row) clean_rows: List[List[float]] = [] for row in matrix: if not isinstance(row, (list, tuple)) or len(row) != expected_dim: raise ValueError(f"{name} must be rectangular with consistent row lengths") clean_row: List[float] = [] for entry in row: clean_row.append(to_finite_float(entry, f"{name} entry")) clean_rows.append(clean_row) return clean_rows def validate_temperature(temperature: float) -> float: """Validate that temperature is a finite, strictly positive number.""" temp_value = to_finite_float(temperature, "temperature") # Temperature <= 0 would divide by zero or flip positive similarities into penalties. if temp_value <= 0.0: raise ValueError("temperature must be strictly positive") return temp_value def compute_logits( anchors: List[List[float]], candidates: List[List[float]], temperature: float, ) -> List[List[float]]: """Compute [B, B] pairwise scores: logits[i][j] = dot(anchors[i], candidates[j]) / temperature.""" # Equivalent to (z1 @ z2.T) / temperature: contract along the D embedding dimension # so row i scores anchor i against every candidate j in z2. logits: List[List[float]] = [] for anchor_row in anchors: score_row: List[float] = [] for candidate_row in candidates: dot_product = 0.0 for a_val, c_val in zip(anchor_row, candidate_row): dot_product += a_val * c_val logit = dot_product / temperature # Finite inputs can still overflow to inf or cancel (inf + -inf) to nan. if not math.isfinite(logit): raise FloatingPointError("non-finite value encountered in logits") score_row.append(logit) logits.append(score_row) return logits def mean_diagonal_cross_entropy(logits: List[List[float]]) -> float: """Compute the mean of -log(softmax(logits[i])[i]) across all B anchor rows.""" # Positive pairs are aligned by row index, so anchor i's true target is column i. batch_size = len(logits) total_loss = 0.0 for i, score_row in enumerate(logits): # Log-sum-exp max-shift: subtracting row_max makes every (score - row_max) <= 0, # so math.exp never overflows and exp_sum >= 1.0 (avoiding log(0)). row_max = max(score_row) exp_sum = 0.0 for score in score_row: exp_sum += math.exp(score - row_max) # Group (row_max - score_row[i]) first so equal huge numbers cancel to 0.0 cleanly. positive_score = score_row[i] row_loss = (row_max - positive_score) + math.log(exp_sum) total_loss += row_loss return total_loss / batch_size def contrastive_loss( z1: List[List[float]], z2: List[List[float]], temperature: float, ) -> float: """Return the one-directional in-batch contrastive cross-entropy loss.""" # Phase 1: Validate both [B, D] embedding matrices and the scalar temperature. anchors = validate_matrix(z1, "z1") candidates = validate_matrix(z2, "z2") if len(anchors) != len(candidates) or len(anchors[0]) != len(candidates[0]): raise ValueError( f"z1 and z2 must have identical shapes, got " f"{len(anchors)}x{len(anchors[0])} vs {len(candidates)}x{len(candidates[0])}" ) tau = validate_temperature(temperature) # Phase 2: Build the [B, B] similarity logits (z1 @ z2.T / tau) and check finiteness. logits = compute_logits(anchors, candidates, tau) # Phase 3: Compute numerically stable cross-entropy with diagonal targets 0..B-1. return mean_diagonal_cross_entropy(logits)✅ Submit now — all tests should pass.
Intuition & how it works
Think of contrastive loss like a flashcard matching quiz with B prompts (z1) and B candidate cards (z2), ordered so prompt i belongs with card i. Each prompt and card is represented as an embedding (a fixed-length vector of D numbers encoding its features). For every prompt z1[i], we take its dot product (multiplying matching coordinates and summing them) against every candidate z2[j], divide by a temperature (a positive scaling knob that sharpens score gaps when small and softens them when large) to obtain raw logits (unnormalized compatibility scores), and then apply softmax (converting a row of scores into probabilities summing to 1) followed by cross-entropy loss (-log of the probability assigned to the true partner j = i).
Why did the broken snippet fail, and why is naive exponentiation risky? Matrix multiplication A @ B pairs each row of A with each column of B, requiring the width of A to equal the height of B. Because z1 and z2 both have shape [B, D], writing torch.matmul(z1, z2) attempts to pair D coordinates against B batch samples — crashing immediately when B != D (as in Example 1), and silently mixing coordinates with batch samples when B == D (as in Example 2)! Transposing z2 to [D, B] (z1 @ z2.T) fixes the axis contraction, and applying the log-sum-exp trick (subtracting each row's maximum score before calling exp) prevents large logits from overflowing floating-point bounds (~709.78 in float64, or ~11.09 in float16).
Here is a concrete trace on Example 2 (z1 = [[1.0, 3.0], [2.0, 1.0]], z2 = [[2.0, 0.0], [1.0, 2.0]], temperature = 1.0):
z1 [2, 2] z2.T [2, 2] dot products logits (/ 1.0) true target
[ 1.0 3.0 ] @ [ 2.0 1.0 ] = [ 2.0 7.0 ] -> [ 2.0 7.0 ] col 0 (score 2.0)
[ 2.0 1.0 ] [ 0.0 2.0 ] [ 4.0 4.0 ] [ 4.0 4.0 ] col 1 (score 4.0)
Row 0 (max = 7.0): (7.0 - 2.0) + log(exp(-5.0) + exp(0.0)) ~= 5.0067153
Row 1 (max = 4.0): (4.0 - 4.0) + log(exp( 0.0) + exp(0.0)) ~= 0.6931472
Mean cross-entropy loss = (5.0067153 + 0.6931472) / 2 ~= 2.8499313
Complexity
Let B be batch_size (the number of rows) and D be embedding_dim (the number of coordinates per row).
- Time:
O(B^2 * D). Input validation inspects the twoB x Dmatrices once inO(B * D)time. Constructing theB x Bscore matrix evaluatesB^2dot products of lengthD(O(B^2 * D)), and max-shifted cross-entropy scans each of theBrows of lengthBtwice (O(B^2)). - Space:
O(B * D + B^2). We hold validated float copies of bothB x Dmatrices (O(B * D)) and materialize theB x Blogitsmatrix (O(B^2)), mirroring what PyTorch allocates forz1 @ z2.T.
Edge cases
- Square (
B == D) vs rectangular (B != D) batches: WhenB != D,z1 @ z2crashes; whenB == D,z1 @ z2runs silently with wrong answers. Usingz1 @ z2.Thandles both shapes identically. - Symmetric
z2(such as an identity matrix[[1, 0], [0, 1]]): Becausez2 == z2.T, the broken code accidentally returns the right number! Always test with a non-symmetricz2like Example 2. - Single-item batch (
B = 1): As in Example 3, anchor0has only its matched positivez2[0]available, so softmax assigns probability1.0and the loss is0.0regardless of the vectors or temperature. - Booleans and huge Python integers:
boolsubclassesintin Python (isinstance(True, int)isTrue), soTrueandFalsemust be explicitly rejected withValueError. Huge ints like10**400raiseOverflowErrorinsidefloat(x), which we catch and convert toValueError. - Large finite logits (e.g.,
1000.0): Naivemath.exp(1000.0)raisesOverflowError, whereas subtractingrow_maxshifts the largest exponent to0and computes the exact answer cleanly. - Finite inputs that overflow or cancel into non-finite logits:
1e200 * 1e200 -> inf,1e300 / 1e-10 -> inf, and1e308 * 1e308 + 1e308 * (-1e308) -> nanall produce non-finite logits from valid finite inputs and raiseFloatingPointError.
Common mistakes
- Transposing the wrong matrix or reversing the order:
z1.T @ z2produces a[D, D]feature-covariance matrix instead of[B, B]sample scores, whilez2 @ z1.Tscoresz2anchors againstz1candidates (the reverse direction). - Upcasting to
float32after the matrix multiplication: Infloat16(max finite value65504) orbfloat16(coarse mantissa steps),(z1 @ z2.T).float()is too late because overflow or precision loss already happened insidematmul. Castz1andz2tofloat32beforez1 @ z2.T, and disable automatic mixed precision (torch.autocast, PyTorch's context manager that automatically runs ops likematmulin half precision) around the loss block. - Breaking the autograd computation graph: Calling
.item(),.detach(), or.numpy()inside a PyTorch loss function severs autograd (PyTorch's automatic differentiation engine that records tensor operations to backpropagate gradients), halting training. Always return the scalartorch.Tensordirectly. - Computing
log(softmax(x))in two separate steps: When a score is far below the row maximum,softmaxunderflows its probability to0.0, andlog(0.0)explodes to-inf. Always fuse them viaF.cross_entropy,F.log_softmax, or the max-shiftedlog-sum-expformula. - Applying L2 normalization unprompted: L2 normalization (dividing each vector by its Euclidean norm so its length is
1) converts raw dot-product similarity into cosine similarity (measuring only vector angles). Only normalize when the specification explicitly defines cosine similarity. - Hardcoding CPU targets in PyTorch:
torch.arange(B)defaults to CPU and fails whenlogitsreside on a GPU; always passdevice=z1.device.
Follow-up questions
- How can you make the objective symmetric across both views without running a second matrix multiplication? Scoring
z2as anchors againstz1as candidates requires(z2 @ z1.T) / temperature, which equals the transposelogits.Tof the[B, B]score matrix already in memory! Because rowiofz2still aligns with columniofz1, the target indiceslabels = torch.arange(B, device=z1.device)stay identical, and the symmetric CLIP-style objective is simply0.5 * (F.cross_entropy(logits, labels) + F.cross_entropy(logits.T, labels)). - How does the loss formulation change when a single anchor can match more than one positive candidate? A single integer class index per row cannot represent multiple matches; instead, supply a
[B, B]binary maskpos_mask[i][j]indicating every valid positive for anchori. Two standard multi-positive formulations exist in log space: (1) maximizing the summed probability over all positives vialoss_i = logsumexp(row_i) - logsumexp(row_i[pos_mask[i]]), or (2) averaging-log_softmax(row_i)[j]uniformly across all positive columnsj(Supervised Contrastive Loss, SupCon), masking out anchors that happen to have zero positives in the batch. - In multi-GPU distributed training, how do you incorporate negative candidates from peer devices while keeping gradients intact? Across
Wworkers, run all-gather (a collective communication primitive where every worker shares its[B, D]z2shard so all workers assemble the[W * B, D]candidate pool). Local anchorsz1([B, D]) then multiply the gathered pool to form[B, W * B]logits, shifting workerrank's target indices torank * B + torch.arange(B, device=z1.device). Because standardtorch.distributed.all_gatherdrops autograd history, either calltorch.distributed.nn.functional.all_gather(which backpropagates gradients across ranks) or overwrite slicerank * B : (rank + 1) * Bwith the localz2tensor so gradients flow into the local encoder. - Under what circumstances should embeddings be L2-normalized before scoring rather than compared via unnormalized dot products? Under raw dot products, once an anchor's positive already outscores its negatives, the network can push cross-entropy toward zero merely by inflating vector norms without improving angular alignment — and growing norms risk
float16overflow. L2-normalizing rows bounds every dot product to[-1, 1]and every logit to[-1/T, 1/T], preventing norm inflation and lettingtemperaturecleanly control distribution sharpness. Raw dot products remain preferable when vector magnitude intentionally encodes confidence, popularity priors, or calibrated log-odds, or when downstream serving relies on unnormalized Maximum Inner Product Search (MIPS).
Follow-up questions
- How can you make the objective symmetric across both views without running a second matrix multiplication?
- How does the loss formulation change when a single anchor can match more than one positive candidate?
- In multi-GPU distributed training, how do you incorporate negative candidates from peer devices while keeping gradients intact?
- Under what circumstances should embeddings be L2-normalized before scoring rather than compared via unnormalized dot products?
Similar questions
- Approximate Quantile Sketches Over Unbounded Streams
- Low-Latency Tree Ensemble Inference
- Select Score Cutoff for Target Precision
- Payment Fraud Detection Under Class Imbalance and Drift
- Diagnosing and Fixing Overfitting in Supervised Learning
- Correlation Bounds, Equicorrelated Variables, and Box-Muller Sampling