diff --git a/tests/integration/test_head_detector.py b/tests/integration/test_head_detector.py index c85191a63..3ea6c48e3 100644 --- a/tests/integration/test_head_detector.py +++ b/tests/integration/test_head_detector.py @@ -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)) diff --git a/transformer_lens/head_detector.py b/transformer_lens/head_detector.py index 15870005c..4a02e2bc3 100644 --- a/transformer_lens/head_detector.py +++ b/transformer_lens/head_detector.py @@ -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): @@ -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)