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

  1. One-directional dot-product logits:
    • Compute raw unnormalized dot products between every anchor z1[i] and every candidate z2[j], divided by temperature: logits[i][j] = dot(z1[i], z2[j]) / temperature for 0 <= i, j < B.
    • Do not apply L2 normalization to rows, and do not average with the reverse z2 -> z1 direction.
  2. Diagonal cross-entropy:
    • Return the mean across i = 0, ..., B - 1 of -log(softmax(logits[i])[i]) as a float.
    • Evaluate softmax cross-entropy stably (for instance via row-maximum shifting) so large finite logits such as 1000.0 never overflow exp. (In a PyTorch training loop with float16 or bfloat16 inputs, tensors should likewise be cast to float32 prior to z1 @ z2.T with autocast disabled so gradients propagate cleanly.)
  3. Validation & exceptions:
    • Do not modify the caller's input lists.
    • Raise ValueError if z1 or z2 is not a non-empty rectangular 2D sequence (list/tuple of list/tuple), if B == 0 or D == 0, if z1 and z2 differ in shape, if any element or temperature is a bool, non-numeric, non-finite (nan/inf), or an integer too large for float, or if temperature <= 0.
    • Raise FloatingPointError if any computed entry logits[i][j] is non-finite (inf, -inf, or nan) due to overflow or inf - inf cancellation.

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 z2 contracts the length-3 embedding axis ([2, 3] @ [3, 2] -> [2, 2]), producing dot products [[2.0, 1.0], [2.0, 3.0]] and scaled logits = [[4.0, 2.0], [4.0, 6.0]].
  • Row 0 targets column 0 (4.0 vs 2.0, loss ln(1 + e^-2)) and row 1 targets column 1 (6.0 vs 4.0, loss ln(1 + e^-2)), averaging to ln(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 untransposed z1 @ z2 would silently produce [[5.0, 6.0], [5.0, 2.0]]. Using z1 @ z2.T yields the true pairwise scores logits = [[2.0, 7.0], [4.0, 4.0]].
  • Row 0 pays 5.0 + ln(1 + e^-5) (negative candidate z2[1] outscores positive z2[0]), while row 1 ties 4.0 vs 4.0 and pays ln(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 = 1 contains only one candidate per anchor (logits = [[0.0]]), so softmax assigns probability 1.0 to column 0 and -ln(1.0) = 0.0.

Constraints

  • Valid matrices satisfy 1 <= B, D with identical [B, D] dimensions across z1 and z2
  • Matrix entries must be finite int or float values (never bool) convertible to IEEE-754 float64
  • temperature must be a finite int or float (never bool) with temperature > 0
  • Invalid shapes, dtypes, bool values, non-finite inputs, or temperature <= 0 raise ValueError
  • Non-finite entries in (z1 @ z2.T) / temperature raise FloatingPointError

Step-by-step walkthrough

  1. Understand what contrastive loss computes

    In contrastive learning, we have two aligned views of the same batch of items: z1 and z2, each shaped [B, D] (B = batch_size items, D = embedding_dim numbers per item). Row i of z1 is an anchor, row i of z2 is its positive partner (the matching item), and all other rows j != i of z2 act as negatives (distractors).

    For every anchor i, we want a row of B compatibility scores (logits), one against each candidate row j in z2, scaled by temperature:

    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 i of z1 matches row i of z2, the positive score for row i sits right on the diagonal (column i), which is why labels = [0, 1, ..., B - 1]. We then treat each row as a B-way classification problem and average the cross-entropy loss across all B rows.

    The automated judge runs in pure Python without PyTorch, passing z1 and z2 as 2D lists (List[List[float]]) and expecting a float. Below we build the exact pure-Python solution step by step, and also show the PyTorch tensor version side by side.

  2. Spot the matrix-multiplication shape bug

    2D matrix multiplication A @ B pairs each row of A with each column of B. 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 z1 and z2 directly into torch.matmul(z1, z2) without transposing z2:

    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's 2 x 3 inputs): PyTorch immediately raises a RuntimeError complaining that shapes [B, D] and [B, D] cannot be multiplied.
    • When B == D (square batches, as in Example 2's 2 x 2 inputs): The code runs without crashing and returns the wrong number! Entry [i][j] computes sum_k z1[i][k] * z2[k][j], multiplying feature k of anchor i against batch sample k of z2. Because the output still has shape [B, B], F.cross_entropy accepts it silently. Even worse, if z2 happens to be symmetric (such as an identity matrix [[1, 0], [0, 1]]), z2 == z2.T, hiding the bug completely!

    Transposing z2 (z1 @ z2.T, or z2.transpose(0, 1)) puts the D features of each z2[j] down column j, so logits[i][j] becomes dot(z1[i], z2[j]) / temperature.

  3. Validate inputs and edge types

    Before computing any scores, we verify every assumption and raise ValueError on invalid inputs so bad calls never fail mysteriously deep inside the math:

    1. Numbers, not Booleans or nan/inf: In Python, bool is a subclass of int (isinstance(True, int) evaluates to True!). We must check isinstance(value, bool) before isinstance(value, (int, float)). Also, converting a gigantic Python int such as 10**400 with float(value) raises OverflowError, so we catch that and raise ValueError.
    2. Non-empty rectangular 2D shapes: Both z1 and z2 must have B > 0 rows, D > 0 columns, equal row lengths, and identical [B, D] dimensions.
    3. Positive finite temperature: temperature <= 0 would 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
    
  4. Build the pairwise score matrix and check finiteness

    In pure Python, (z1 @ z2.T) / temperature is a double loop over every anchor_row in z1 and every candidate_row in z2, taking their dot product across the D coordinates and dividing by temperature.

    Even when all inputs are finite, a logit can become non-finite in three ways: - a_val * c_val overflows float64 (for example 1e200 * 1e200 -> inf), - two overflowing products of opposite signs cancel (inf + (-inf) -> nan), or - dividing a large dot product by a tiny temperature overflows (1e300 / 1e-10 -> inf).

    As required by the specification, we check math.isfinite(logit) and raise FloatingPointError whenever any logit is inf, -inf, or nan.

    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
    
  5. Compute cross-entropy safely with the max-shift trick

    For anchor row i with scores s_0, s_1, ..., s_(B-1), softmax turns scores into probabilities exp(s_j) / sum_j exp(s_j), and cross-entropy takes -log of the probability at the true target j = i.

    If we compute math.exp(s_j) directly, any finite logit above 709.78 overflows float64! Dividing by a small temperature makes large logits very common. To prevent overflow, let m = max(s_0, ..., s_(B-1)) be the largest score in the row, and divide both the top and bottom of the softmax fraction by exp(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 - m is <= 0, so exp(s_j - m) is always between 0 and 1 — it cannot overflow. - At least one entry equals m, contributing exp(0) = 1.0, so sum_j exp(s_j - m) >= 1.0 — math.log never sees 0. - Writing (m - s_i) first means that when the positive score s_i is already the row maximum m, m - s_i cancels to 0.0 before adding the tiny log term.

    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
    
  6. Handle low precision and autograd in PyTorch

    In a real PyTorch training loop, two extra concerns appear: half-precision dtypes (float16 and bfloat16) and preserving gradients.

    • float16 overflows easily: Its largest finite value is 65504. If two 512-dimensional vectors have entries around 3.0, their dot product is around 512 * 9 = 4608, and dividing by temperature = 0.07 gives 65828.6 -> inf!
    • bfloat16 loses fine distinctions: It has float32's range, but only 8 significant bits (7 fraction bits), so numbers between 64 and 128 jump in steps of 0.5, wiping out subtle ranking differences between candidates.

    Therefore, we must upcast z1 and z2 with .float() before the matrix multiplication (casting logits.float() afterwards is too late — the overflow or rounding already happened!), and disable torch.autocast around the block so PyTorch's automatic mixed precision does not downcast z1 @ z2.T back to half precision. Because .float() is a differentiable PyTorch operation and we never call .detach(), .item(), or .numpy(), gradients flow cleanly back to z1 and z2:

    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)
    
  7. 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.8499312645
    

    Notice how anchor 0 prefers negative z2[1] (7.0) over its own positive z2[0] (2.0), paying ~5.0067 nats of penalty, while anchor 1 scores 4.0 on both candidates (50/50 tie), paying log(2) ~= 0.6931. By contrast, the buggy z1 @ z2 would have produced logits = [[5.0, 6.0], [5.0, 2.0]] and returned ~2.1809 without raising any error!

  8. 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 two B x D matrices once in O(B * D) time. Constructing the B x B score matrix evaluates B^2 dot products of length D (O(B^2 * D)), and max-shifted cross-entropy scans each of the B rows of length B twice (O(B^2)).
  • Space: O(B * D + B^2). We hold validated float copies of both B x D matrices (O(B * D)) and materialize the B x B logits matrix (O(B^2)), mirroring what PyTorch allocates for z1 @ z2.T.

Edge cases

  • Square (B == D) vs rectangular (B != D) batches: When B != D, z1 @ z2 crashes; when B == D, z1 @ z2 runs silently with wrong answers. Using z1 @ z2.T handles both shapes identically.
  • Symmetric z2 (such as an identity matrix [[1, 0], [0, 1]]): Because z2 == z2.T, the broken code accidentally returns the right number! Always test with a non-symmetric z2 like Example 2.
  • Single-item batch (B = 1): As in Example 3, anchor 0 has only its matched positive z2[0] available, so softmax assigns probability 1.0 and the loss is 0.0 regardless of the vectors or temperature.
  • Booleans and huge Python integers: bool subclasses int in Python (isinstance(True, int) is True), so True and False must be explicitly rejected with ValueError. Huge ints like 10**400 raise OverflowError inside float(x), which we catch and convert to ValueError.
  • Large finite logits (e.g., 1000.0): Naive math.exp(1000.0) raises OverflowError, whereas subtracting row_max shifts the largest exponent to 0 and computes the exact answer cleanly.
  • Finite inputs that overflow or cancel into non-finite logits: 1e200 * 1e200 -> inf, 1e300 / 1e-10 -> inf, and 1e308 * 1e308 + 1e308 * (-1e308) -> nan all produce non-finite logits from valid finite inputs and raise FloatingPointError.

Common mistakes

  • Transposing the wrong matrix or reversing the order: z1.T @ z2 produces a [D, D] feature-covariance matrix instead of [B, B] sample scores, while z2 @ z1.T scores z2 anchors against z1 candidates (the reverse direction).
  • Upcasting to float32 after the matrix multiplication: In float16 (max finite value 65504) or bfloat16 (coarse mantissa steps), (z1 @ z2.T).float() is too late because overflow or precision loss already happened inside matmul. Cast z1 and z2 to float32 before z1 @ z2.T, and disable automatic mixed precision (torch.autocast, PyTorch's context manager that automatically runs ops like matmul in 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 scalar torch.Tensor directly.
  • Computing log(softmax(x)) in two separate steps: When a score is far below the row maximum, softmax underflows its probability to 0.0, and log(0.0) explodes to -inf. Always fuse them via F.cross_entropy, F.log_softmax, or the max-shifted log-sum-exp formula.
  • 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 when logits reside on a GPU; always pass device=z1.device.

Follow-up questions

  • How can you make the objective symmetric across both views without running a second matrix multiplication? Scoring z2 as anchors against z1 as candidates requires (z2 @ z1.T) / temperature, which equals the transpose logits.T of the [B, B] score matrix already in memory! Because row i of z2 still aligns with column i of z1, the target indices labels = torch.arange(B, device=z1.device) stay identical, and the symmetric CLIP-style objective is simply 0.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 mask pos_mask[i][j] indicating every valid positive for anchor i. Two standard multi-positive formulations exist in log space: (1) maximizing the summed probability over all positives via loss_i = logsumexp(row_i) - logsumexp(row_i[pos_mask[i]]), or (2) averaging -log_softmax(row_i)[j] uniformly across all positive columns j (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 W workers, run all-gather (a collective communication primitive where every worker shares its [B, D] z2 shard so all workers assemble the [W * B, D] candidate pool). Local anchors z1 ([B, D]) then multiply the gathered pool to form [B, W * B] logits, shifting worker rank's target indices to rank * B + torch.arange(B, device=z1.device). Because standard torch.distributed.all_gather drops autograd history, either call torch.distributed.nn.functional.all_gather (which backpropagates gradients across ranks) or overwrite slice rank * B : (rank + 1) * B with the local z2 tensor 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 float16 overflow. L2-normalizing rows bounds every dot product to [-1, 1] and every logit to [-1/T, 1/T], preventing norm inflation and letting temperature cleanly 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

Similar questions

More Exa interview questions

All 2 Exa questions →