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

max_offset must be < number of rows

Error message

max_offset {max_offset} must be < number of rows {table.shape[0]}

What it means

neighbour_cosine_curve requires max_offset strictly below the number of rows L: computing cosine(row p, row p+k) for p up to L-k needs at least one pair at the largest offset, otherwise the last curve entries would be computed from no samples.

Solutions

  1. Reduce max_offset below table.shape[0]
  2. Increase the embedding table's row count if a longer offset curve is needed
  3. Compute max_offset = min(max_offset, L - 1) defensively at the call site
Defensive patterns

Strategy: validation

When it happens

Trigger: Thrown at phases/19-capstone-projects/32-token-positional-embeddings/code/main.py:179 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/f8e98f27aeb6e5ef. Report an issue: GitHub.

Appendix: source

Thrown at phases/19-capstone-projects/32-token-positional-embeddings/code/main.py:179

        pos = self.positional_embedding(seq_len)
        return tok + pos.unsqueeze(0)


def count_parameters(module: nn.Module) -> int:
    return sum(p.numel() for p in module.parameters() if p.requires_grad)


def neighbour_cosine_curve(table: torch.Tensor, max_offset: int = 8) -> list[float]:
    """Average cosine similarity between row p and row p+k for k in 1..max_offset.

    Returns a list of length max_offset.
    """
    if table.dim() != 2:
        raise ValueError("table must be (L, D)")
    if max_offset < 1:
        raise ValueError(f"max_offset must be >= 1, got {max_offset}")
    if max_offset >= table.shape[0]:
        raise ValueError(
            f"max_offset {max_offset} must be < number of rows {table.shape[0]}"
        )
    rows = table.detach().to(torch.float32)
    norms = rows.norm(dim=1, keepdim=True).clamp(min=1e-8)
    unit = rows / norms
    result: list[float] = []
    for k in range(1, max_offset + 1):
        a = unit[:-k]
        b = unit[k:]
        dot = (a * b).sum(dim=1).mean().item()
        result.append(dot)
    return result


@dataclass
class DemoConfig:
    vocab_size: int = 320
    d_model: int = 64

View on GitHub (pinned to 39ea8a1c6d)