rohitg00/ai-engineering-from-scratch · error · ValueError

sim must be square (N, N), got

Error message

sim must be square (N, N), got {tuple(sim.shape)}

What it means

recall_at_k requires a square similarity matrix because image-to-text and text-to-image retrieval both rank N candidates against N items using the same arange targets; a non-square tensor means the image and caption sets differ in size, so the diagonal ground truth is undefined.

Solutions

  1. Build sim with the same number of images and captions (square N x N) before calling recall_at_k
  2. If sets differ, pad or truncate so sim.shape[0] == sim.shape[1], or compute recall per direction separately
  3. Verify sim came from a symmetric scoring pass such as cosine(image_emb, text_emb) with matching batch sizes
Defensive patterns

Strategy: validation

When it happens

Trigger: Thrown at phases/19-capstone-projects/63-multimodal-eval/code/main.py:83 when the library encounters an invalid state.

Common situations: See trigger scenarios.


AI-assisted analysis of rohitg00/ai-engineering-from-scratch@39ea8a1c6d (2026-08-26). Data as JSON: /api/errors/cb67d186ed9ba727. Report an issue: GitHub.

Appendix: source

Thrown at phases/19-capstone-projects/63-multimodal-eval/code/main.py:83

class CaptionSample:
    image: torch.Tensor
    references: list[list[int]]


@dataclass
class EvalSuite:
    retrieval: list[RetrievalPair]
    vqa: list[VQATriple]
    caps: list[CaptionSample]


def recall_at_k(sim: torch.Tensor, k: int) -> tuple[float, float]:
    """Return (i2t, t2i) recall@k.

    sim is (N, N) where row i is the similarity of image i to every caption.
    """
    if sim.dim() != 2 or sim.shape[0] != sim.shape[1]:
        raise ValueError(f"sim must be square (N, N), got {tuple(sim.shape)}")
    n = sim.shape[0]
    if k < 1 or k > n:
        raise ValueError(f"k {k} not in [1, N={n}]")

    targets = torch.arange(n, device=sim.device)

    topk_i2t = sim.topk(k, dim=1).indices
    hits_i2t = (topk_i2t == targets.unsqueeze(1)).any(dim=1).float().mean().item()

    sim_t = sim.T
    topk_t2i = sim_t.topk(k, dim=1).indices
    hits_t2i = (topk_t2i == targets.unsqueeze(1)).any(dim=1).float().mean().item()

    return hits_i2t, hits_t2i


def vqa_exact_match(predictions: list[int], references: list[int]) -> float:
    if len(predictions) != len(references):

View on GitHub (pinned to 39ea8a1c6d)