File size: 7,288 Bytes
de3f042
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
#!/usr/bin/env python3
"""Fixed-layer steering evaluation with multiple direction sources.

Runs over a full question set (YAML file), generating num_completions per question.
Supports two question file formats:
  - Plain list of strings:  ["question 1", "question 2", ...]
  - first_plot_questions.yaml format: list of dicts with 'paraphrases' key

Direction sources:
  - Our probe .npy: artefacts/scores/our_method/{exp}/layer{L}/direction_mean_{probe}.npy
  - T5 .npy:        artefacts/scores/t5_directions/{exp}/direction_l{L}.npy
  - Random:         np.random.randn(d_model), normalised, seeded

Output JSON:
{
  "total_count": int,
  "total_completions": int,
  "rate": float,
  "per_question": {
    "<question text>": {"count": int, "rate": float, "completions": [...]}
  }
}
"""

import json
import logging
import sys
from pathlib import Path

import chz
import numpy as np
import torch
import transformers as tr
import yaml

sys.path.insert(0, str(Path(__file__).parent.parent / "layer_sweep"))
from layer_sweep import steer_and_generate, count_keywords  # noqa: E402

logger = logging.getLogger(__name__)


# ---------------------------------------------------------------------------
# Question loading
# ---------------------------------------------------------------------------

def load_questions(path: str) -> list[str]:
    """
    Load eval questions from a YAML file.

    Accepts two formats:
      1. Plain list of strings.
      2. first_plot_questions.yaml format: list of dicts each with a 'paraphrases' key
         (extracts all paraphrase strings across all entries).
    """
    with open(path) as f:
        data = yaml.safe_load(f)

    assert isinstance(data, list) and len(data) > 0, f"Expected non-empty list in {path}"

    if isinstance(data[0], str):
        return data

    # first_plot_questions.yaml format
    questions = []
    for entry in data:
        for para in entry.get("paraphrases", []):
            questions.append(para.strip())
    assert questions, f"No paraphrases found in {path}"
    return questions


# ---------------------------------------------------------------------------
# Config
# ---------------------------------------------------------------------------

@chz.chz
class Config:
    # Model to steer
    model: str = ...

    # Direction source — exactly one must be set
    direction_path: str | None = None   # .npy file (our probe or T5)
    random_seed: int | None = None      # random direction (seeded)

    # Layer and coefficient
    layer: int = ...
    steer_coeff: float = 50

    # Questions
    questions_file: str = ...           # YAML file with list of questions

    # Keywords for hit-rate counting
    keywords: list[str] = chz.field(default_factory=list)

    # Generation settings
    num_completions: int = 100           # completions per question
    max_new_tokens: int = 100
    temperature: float = 1.0

    # Output
    output_path: str = ...

    # Name suffix for output (steering coeff will be appended)
    name: str = ""

    debug: bool = False                 # use first 3 questions, 1 completion each


# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------

def main(config: Config) -> None:
    logging.basicConfig(
        level=logging.INFO,
        format="%(asctime)s [%(levelname)s] %(message)s",
    )

    questions = load_questions(config.questions_file)
    if config.debug:
        questions = questions[:3]
        logger.info("DEBUG: using first 3 questions")
    logger.info("Loaded %d questions from %s", len(questions), config.questions_file)

    num_completions = 1 if config.debug else config.num_completions

    logger.info("Loading model: %s", config.model)
    tokenizer = tr.AutoTokenizer.from_pretrained(config.model)
    tokenizer.padding_side = "left"
    if tokenizer.pad_token is None:
        tokenizer.pad_token = tokenizer.eos_token

    model = tr.AutoModelForCausalLM.from_pretrained(
        config.model, device_map="auto", torch_dtype=torch.bfloat16
    )
    model.eval()

    num_layers = model.config.num_hidden_layers
    assert config.layer < num_layers, \
        f"layer={config.layer} out of range for model with {num_layers} layers"

    d_model = model.config.hidden_size

    # Load or generate direction
    if config.direction_path is not None:
        path = Path(config.direction_path)
        assert path.exists(), f"Direction file not found: {path}"
        direction = np.load(path)
        assert direction.ndim == 1, f"Expected 1D direction, got shape {direction.shape}"
        assert direction.shape[0] == d_model, \
            f"Direction d_model={direction.shape[0]} != model d_model={d_model}"
        logger.info("Loaded direction from %s", path)
    else:
        assert config.random_seed is not None, \
            "Exactly one of direction_path or random_seed must be set"
        rng = np.random.default_rng(config.random_seed)
        direction = rng.standard_normal(d_model).astype(np.float32)
        direction = direction / (np.linalg.norm(direction) + 1e-8)
        logger.info("Random direction (seed=%d, d_model=%d)", config.random_seed, d_model)

    logger.info(
        "Steering layer=%d coeff=%.1f | %d questions x %d completions | keywords=%s",
        config.layer, config.steer_coeff, len(questions), num_completions, config.keywords,
    )

    per_question: dict[str, dict] = {}
    total_count = 0
    total_completions = 0

    for i, question in enumerate(questions):
        completions = steer_and_generate(
            model=model,
            tokenizer=tokenizer,
            question=question,
            direction=direction,
            layer=config.layer,
            coeff=config.steer_coeff,
            N=num_completions,
            max_new_tokens=config.max_new_tokens,
            temperature=config.temperature,
        )
        count, rate = count_keywords(completions, config.keywords)
        per_question[question] = {"count": count, "rate": rate, "completions": completions}
        total_count += count
        total_completions += len(completions)
        logger.info(
            "[%d/%d] %d/%d hit  q=%r",
            i + 1, len(questions), count, len(completions), question[:60],
        )

    overall_rate = total_count / total_completions if total_completions else 0.0
    logger.info(
        "Overall: %d/%d (%.1f%%)", total_count, total_completions, overall_rate * 100
    )

    result = {
        "total_count": total_count,
        "total_completions": total_completions,
        "rate": overall_rate,
        "per_question": per_question,
    }

    # Build output path with steering coefficient in name
    output_path = Path(config.output_path)
    stem = output_path.stem
    suffix = output_path.suffix
    coeff_str = f"_coeff_{config.steer_coeff:.1f}"
    if config.name:
        coeff_str = f"_{config.name}{coeff_str}"
    output_path = output_path.parent / f"{stem}{coeff_str}{suffix}"

    output_path.parent.mkdir(parents=True, exist_ok=True)
    with open(output_path, "w") as f:
        json.dump(result, f, indent=2)
    logger.info("Results saved to %s", output_path)


if __name__ == "__main__":
    chz.nested_entrypoint(main)