Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 21 additions & 1 deletion tests/integration/test_head_detector.py
Original file line number Diff line number Diff line change
Expand Up @@ -409,14 +409,34 @@ def test_detect_head_with_zero_sequence_length():


def test_detect_head_with_sequence_length_outside_context_window():
# BOS plus n_ctx tokens is one more than the context window holds.
seq = " a" * model.cfg.n_ctx
assert model.to_tokens(seq, truncate=False).shape[-1] == model.cfg.n_ctx + 1
with pytest.raises(AssertionError) as e:
detect_head(model, "a " * model.cfg.n_ctx, "previous_token_head")
detect_head(model, seq, "previous_token_head")
assert (
str(e.value)
== "The sequence must be non-empty and must fit within the model's context window."
)


def test_detect_head_with_sequence_much_longer_than_context_window():
with pytest.raises(AssertionError) as e:
detect_head(model, "a " * (2 * model.cfg.n_ctx), "previous_token_head")
assert (
str(e.value)
== "The sequence must be non-empty and must fit within the model's context window."
)


def test_detect_head_with_sequence_filling_context_window():
# BOS plus n_ctx - 1 tokens fills the context window exactly, and fits.
seq = " a" * (model.cfg.n_ctx - 1)
assert model.to_tokens(seq).shape[-1] == model.cfg.n_ctx
result = detect_head(model, seq, "previous_token_head")
assert result.shape == (model.cfg.n_layers, model.cfg.n_heads)


def test_detect_head_with_invalid_detection_pattern():
with pytest.raises(AssertionError) as e:
detect_head(model, test_duplicated_sequence, torch.ones(4, 4))
Expand Down
9 changes: 6 additions & 3 deletions transformer_lens/head_detector.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,8 +138,12 @@ def detect_head(
return torch.stack(batch_scores).mean(0)

cfg = model.cfg
tokens = model.to_tokens(seq).to(cfg.device)
# Without truncation, so a sequence longer than the context window keeps
# its length and is rejected below rather than cut silently to n_ctx.
tokens = model.to_tokens(seq, truncate=False).to(cfg.device)
seq_len = tokens.shape[-1]
# Checked before anything is sized from tokens, so an over-long prompt fails fast.
assert 1 < seq_len <= cfg.n_ctx, SEQ_LEN_ERR

# Validate detection pattern if it's a string
if isinstance(detection_pattern, str):
Expand All @@ -155,8 +159,7 @@ def detect_head(
"Using detection pattern with values other than 0 or 1 with error_measure 'mul'"
)

# Validate inputs and detection pattern shape
assert 1 < tokens.shape[-1] < cfg.n_ctx, SEQ_LEN_ERR
# Validate detection pattern shape
assert (
is_lower_triangular(detection_pattern) and seq_len == detection_pattern.shape[0]
), DET_PAT_NOT_SQUARE_ERR % (seq_len, detection_pattern.shape)
Expand Down
Loading