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

expected (B, Nt, hidden), got

Error message

expected (B, Nt, hidden), got {tuple(x.shape)}

What it means

Shape guard in CrossAttention.forward: the text query tensor is not 3D (B, Nt, hidden), so it cannot be projected and split into query heads.

Solutions

  1. Pass text token embeddings shaped (B, Nt, hidden)
  2. Batch single sequences with unsqueeze(0)
Defensive patterns

Strategy: validation

When it happens

Trigger: Thrown at phases/19-capstone-projects/61-cross-attention-fusion/code/main.py:109 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/e7284716fae0c49a. Report an issue: GitHub.

Appendix: source

Thrown at phases/19-capstone-projects/61-cross-attention-fusion/code/main.py:109

        self.q_proj = nn.Linear(cfg.hidden, cfg.hidden, bias=True)
        self.kv_proj = nn.Linear(cfg.vision_dim, cfg.hidden * 2, bias=True)
        self.out = nn.Linear(cfg.hidden, cfg.hidden, bias=True)
        self.drop = nn.Dropout(cfg.dropout)
        self.scale = 1.0 / math.sqrt(cfg.head_dim)

    def project_memory(self, memory: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
        if memory.dim() != 3:
            raise ValueError(f"expected (B, Nv, vision_dim), got {tuple(memory.shape)}")
        b, nv, _ = memory.shape
        h, hd = self.cfg.heads, self.cfg.head_dim
        kv = self.kv_proj(memory).reshape(b, nv, 2, h, hd).permute(2, 0, 3, 1, 4)
        return kv[0], kv[1]

    def forward(self, x: torch.Tensor, memory: torch.Tensor,
                kv_cache: tuple[torch.Tensor, torch.Tensor] | None = None
                ) -> torch.Tensor:
        if x.dim() != 3:
            raise ValueError(f"expected (B, Nt, hidden), got {tuple(x.shape)}")
        if memory.shape[0] != x.shape[0]:
            raise ValueError(
                f"batch mismatch: text {x.shape[0]} vs memory {memory.shape[0]}"
            )
        b, nt, d = x.shape
        h, hd = self.cfg.heads, self.cfg.head_dim

        q = self.q_proj(x).reshape(b, nt, h, hd).transpose(1, 2)
        if kv_cache is None:
            k, v = self.project_memory(memory)
        else:
            k, v = kv_cache
            expected = (b, h, memory.shape[1], hd)
            if k.shape != expected or v.shape != expected:
                raise ValueError(
                    f"kv_cache must be (B,H,Nv,hd)={expected}, got "
                    f"k={tuple(k.shape)} v={tuple(v.shape)}"
                )

View on GitHub (pinned to 39ea8a1c6d)