Skip to content

A straightforward method for training your LLM, from downloading data to generating text.

fix(models): forward_embedding with more than one block

FareedKhan-dev83f0b07a1480
diff --git a/src/models/transformer.py b/src/models/transformer.py
index 0dc728e..5702eb3 100644
--- a/src/models/transformer.py
+++ b/src/models/transformer.py
@@ -115,17 +115,19 @@ class Transformer(nn.Module):
"""
Forward pass focusing on the embedding and attention blocks.
+ Runs every block normally except the last one, which returns its MLP hidden
+ activations (size ``4 * n_embed``) together with its residual stream.
+
Args:
idx (torch.Tensor): Input token indices.
Returns:
- tuple: Output after attention blocks and the residual.
+ tuple: The last block's MLP hidden activations and its residual stream.
"""
x = self._pre_attn_pass(idx)
- residual = x
- for block in self.attn_blocks:
- x, residual = block.forward_embedding(x)
- return x, residual
+ for block in self.attn_blocks[:-1]:
+ x = block(x)
+ return self.attn_blocks[-1].forward_embedding(x)
def generate(self, idx: torch.Tensor, max_new_tokens: int) -> torch.Tensor:
"""
diff --git a/tests/test_classic_model.py b/tests/test_classic_model.py
new file mode 100644
index 0000000..6016343
--- /dev/null
+++ b/tests/test_classic_model.py
@@ -0,0 +1,40 @@
+"""The original (classic) Transformer: shapes, causality and forward_embedding."""
+
+from __future__ import annotations
+
+import torch
+
+from src.models.transformer import Transformer
+
+
+def _model(n_blocks: int = 3) -> Transformer:
+ torch.manual_seed(0)
+ return Transformer(n_head=4, n_embed=32, context_length=16, vocab_size=50, N_BLOCKS=n_blocks).eval()
+
+
+def test_forward_shapes_loss_and_causality() -> None:
+ model = _model()
+ idx = torch.randint(0, 50, (2, 12))
+ logits, loss = model(idx, idx)
+ assert logits.shape == (2, 12, 50) and loss is not None
+ changed = idx.clone()
+ changed[:, 8] = (changed[:, 8] + 1) % 50
+ with torch.no_grad():
+ assert torch.allclose(model(changed)[0][:, :8], logits[:, :8], atol=1e-5)
+
+
+def test_forward_embedding_works_with_several_blocks() -> None:
+ """Regression: it used to feed 4x-wide MLP activations into the next block and crash."""
+ model = _model(n_blocks=3)
+ idx = torch.randint(0, 50, (2, 10))
+ hidden, residual = model.forward_embedding(idx)
+ assert hidden.shape == (2, 10, 4 * 32) and residual.shape == (2, 10, 32)
+ # the residual is the last block's stream after attention, before its MLP
+ with torch.no_grad():
+ x = model._pre_attn_pass(idx)
+ for block in model.attn_blocks[:-1]:
+ x = block(x)
+ last = model.attn_blocks[-1]
+ expected = x + last.attn(last.ln1(x))
+ assert torch.allclose(residual, expected, atol=1e-6)
+