mirror of
https://github.com/harvard-edge/cs249r_book.git
synced 2026-07-17 08:28:07 -05:00
[PR #1875] fix(attention): mask reshape assumes square (seq_q==seq_k), breaks cross-attention #27336
Reference in New Issue
Block a user
Delete Branch "%!s()"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
📋 Pull Request Information
Original PR: https://github.com/harvard-edge/cs249r_book/pull/1875
Author: @Shashank-Tripathi-07
Created: 6/16/2026
Status: 🔄 Open
Base:
main← Head:fix/attention-mask-reshape-cross-attention📝 Commits (1)
2544b54fix attention mask reshape to preserve both seq_q and seq_k dimensions📊 Changes
1 file changed (+4 additions, -3 deletions)
View changed files
📝
tinytorch/src/12_attention/12_attention.py(+4 -3)📄 Description
What breaks
MultiHeadAttention.forward()reshapes a 3-D attention mask(batch, seq_q, seq_k)to(batch, 1, seq_q, seq_k)for multi-head broadcasting. The old code:The
_discardsseq_k. The reshape then usesseq_len_mask(which isseq_q) for both the query and key dimensions. For self-attention whereseq_q == seq_k, this accidentally works. For cross-attention (e.g. encoder-decoder attention, or attention with a different context length),seq_q != seq_k, so the reshape either:ValueErrorifseq_q * seq_q != seq_q * seq_k(total elements don't match)Fix
Unpack both dimensions explicitly. Correct for square and rectangular masks.
Test plan
pytest tinytorch/tests/12_attention/passes(B, T, T)still works(B, T_q, T_k)whereT_q != T_know works🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.