File size: 17,022 Bytes
b0ae393 | 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 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 | """Shared, explicitly versioned utilities for the scaled FEPoID replication.
The goal is to follow the paper where it is unambiguous and to make every
necessary reconstruction choice visible. In particular, the released
repository computes per-layer TwoNN values but does not implement FEPoID's
peak selector. ``select_fepoid_layer`` below implements the active rule in
arXiv:2605.26366, lines 555--558 of the extracted ``main.tex``.
"""
from __future__ import annotations
import copy
import json
import random
import re
import time
from dataclasses import dataclass
from pathlib import Path
from typing import Iterable
import numpy as np
import torch
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import train_test_split
from skdim.id import TwoNN
from torch import nn
SEED = 2024
PROBE_SEED = 42
MODEL_SPECS = {
"mistral": {
"model_id": "mistralai/Mistral-7B-Instruct-v0.3",
"revision": "c170c708c41dac9275d15a8fff4eca08d52bab71",
"layers": 32,
"hidden_size": 4096,
},
"llama": {
"model_id": "meta-llama/Llama-3.1-8B-Instruct",
"revision": "0e9e39f249a16976918f6564b8830bc894c89659",
"layers": 32,
"hidden_size": 4096,
},
}
JUDGE_SPEC = {
"model_id": "mistralai/Ministral-8B-Instruct-2410",
"revision": "2f494a194c5b980dfb9772cb92d26cbb671fce5a",
}
COQA_SPEC = {
"dataset_id": "stanfordnlp/coqa",
"revision": "0d9e9952f1ef6e5415492d3d84b5873259137e3c",
}
def seed_everything(seed: int = SEED) -> None:
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(seed)
def coqa_prompt(context: str, question: str) -> str:
"""The active context-aware prompt in the authors' released code."""
return (
"Answer the question as briefly as possible, based only on the context:\n"
f" Context:{context.strip()}\n Question:{question.strip()}\n Answer:"
)
# Verbatim behavior of the released FST path, reorganized dependency-free.
FST_FILTERS = (
"\n", "Q:", "A:", "question:", "answer:", "Question:", "Answer:",
"Questions:", "questions:", "QUESTION:", "ANSWER:", "REF", ".Forms",
"http", "php", "Question", "Answer",
)
FST_WORD_ABBREVIATIONS = {
"Mr", "Mrs", "Ms", "Dr", "Prof", "Sr", "Jr", "Gen", "Brig", "Adm",
"Rear", "Lt", "Col", "Maj", "Capt", "St", "vs", "etc", "Fig", "Eq", "No",
}
FST_MULTI_DOT_ABBREVIATION = re.compile(r"(?:[A-Za-z]\.){2,}$")
FST_SINGLE_INITIAL = re.compile(r"^[A-Za-z]$")
def extract_first_sentence(text: str) -> str:
text = text.strip()
length = len(text)
cursor = 0
while cursor < length:
char = text[cursor]
if char not in ".!?":
cursor += 1
continue
if char == "." and text[cursor : cursor + 3] == "...":
cursor += 3
continue
if (
char == "."
and 0 < cursor < length - 1
and text[cursor - 1].isdigit()
and text[cursor + 1].isdigit()
):
cursor += 1
continue
left = cursor - 1
while left >= 0 and (text[left].isalpha() or text[left] == "."):
left -= 1
token = text[left + 1 : cursor].strip()
if char == ".":
right_is_letter_dot = (
cursor + 2 < length
and text[cursor + 1].isalpha()
and text[cursor + 2] == "."
)
if cursor > 0 and text[cursor - 1].isalpha() and right_is_letter_dot:
cursor += 1
continue
if "." in token and FST_MULTI_DOT_ABBREVIATION.match(token + "."):
cursor += 1
continue
if token in FST_WORD_ABBREVIATIONS:
if token == "No":
right = cursor + 1
while right < length and text[right].isspace():
right += 1
if right < length and text[right].isdigit():
cursor += 1
continue
else:
cursor += 1
continue
if FST_SINGLE_INITIAL.match(token):
right = cursor + 1
while right < length and text[right].isspace():
right += 1
if right < length and text[right].isupper():
cursor += 1
continue
return text[: cursor + 1].strip()
return text
def first_sentence_truncation(answer: str) -> str:
original = answer.strip()
cut_position = len(answer)
for marker in FST_FILTERS:
marker_position = answer.find(marker)
if 0 <= marker_position < cut_position:
cut_position = marker_position
filtered = answer[:cut_position].strip() or original
return extract_first_sentence(filtered)
def judge_prompt(context: str, question: str, references: list[str], model_answer: str) -> str:
"""The context-aware LLM-judge prompt from the released repository."""
reference_answer = "; ".join(references)
return f"""
Evaluate the following answers to questions. For each question you are given a model answer and the correct answer.
You must determine if the model answer is correct or not. If the model answer is correct, write '1' and if it is not correct, write '0'.
For example:
Question: who is the young guitarist who played with buddy guy?
Ground Truth: Quinn Sullivan
Model Answer: Ronnie Earl Explanation: Ronnie Earl is an American blues guitarist and singer who has played with many famous blues musicians, including Buddy Guy. He is known for his soulful and melodic playing style, and has released many albums that blend blues, jazz, and rock music. Earl has also been a member of the Buddy Guy Blues Band and has played with other notable blues musicians such as B.B. King, Eric Clapton, and Stevie Ray Vaughan. He is considered one of the most
Correctness: 0
Question: name of the first episode of stranger things
Ground Truth: Chapter One : The Vanishing of Will Byers
Model Answer: The disappearance of Will Byers. Explanation: The first episode of the first season of Stranger Things is titled "The Vanishing of Will Byers". The episode introduces the main characters and sets the tone for the rest of the series. It follows the story of Will Byers, a young boy who goes missing in the fictional town of Hawkins, Indiana, and the subsequent search for him by his mother Joyce and his friends Mike, Dustin, and Lucas. The episode sets the stage for the supernatural
Correctness: 1
Context: {context}
Question: {question}
Ground Truth: {reference_answer}
Model Answer: {model_answer}
Correctness:
""".strip()
def released_substring_match(references: Iterable[str], model_answer: str) -> bool:
"""Match the release, which uses containment despite the paper saying exact match."""
normalized = model_answer.strip().lower()
return any(str(reference).strip().lower() in normalized for reference in references)
def parse_judge_output(text: str) -> int:
text = text.replace(".</s>", "").replace("</s>", "").split("\n")[0].strip().strip(".")
index_one = text.find("1")
index_zero = text.find("0")
if index_one != -1 and (index_zero == -1 or index_one < index_zero):
return 1
if index_zero != -1 and (index_one == -1 or index_zero < index_one):
return 0
return 0
def select_fepoid_layer(ids: Iterable[float], horizon: int = 7) -> tuple[int, list[int], list[int]]:
"""Implement the paper's active FEPoID rule.
Reconstruction choices missing from the paper/release:
* layers are zero based;
* local maxima are strict on the left and non-increasing on the right;
* endpoints are not candidate peaks;
* if no peak survives, layer 0 is selected (the paper's "shallowest").
"""
curve = np.asarray(list(ids), dtype=np.float64)
if curve.ndim != 1 or len(curve) < 3 or not np.isfinite(curve).all():
raise ValueError("FEPoID requires at least three finite per-layer ID values")
candidates = [
layer
for layer in range(1, len(curve) - 1)
if curve[layer] > curve[layer - 1] and curve[layer] >= curve[layer + 1]
]
survivors: list[int] = []
for layer in candidates:
endpoint = min(layer + horizon, len(curve) - 1)
tail_strictly_increases = all(
curve[index] < curve[index + 1]
for index in range(layer + 1, endpoint)
)
discard = curve[layer] < curve[endpoint] and tail_strictly_increases
if not discard:
survivors.append(layer)
return (survivors[0] if survivors else 0), candidates, survivors
def twonn_curve(hidden_states: np.ndarray, device: torch.device) -> tuple[np.ndarray, float]:
"""Compute paper-compatible TwoNN estimates using exact pairwise distances."""
if hidden_states.ndim != 3:
raise ValueError(f"expected [N,L,D], received {hidden_states.shape}")
started = time.perf_counter()
values = []
for layer in range(hidden_states.shape[1]):
features = torch.from_numpy(hidden_states[:, layer]).to(device=device, dtype=torch.float32)
distances = torch.cdist(features, features)
distances.fill_diagonal_(float("inf"))
nearest_two = torch.topk(distances, k=2, dim=1, largest=False).values.cpu().numpy()
estimator = TwoNN(dist=True)
estimator.fit(nearest_two.astype(np.float64, copy=False))
values.append(float(estimator.dimension_))
del features, distances
if device.type == "cuda":
torch.cuda.synchronize(device)
return np.asarray(values), time.perf_counter() - started
class Probe(nn.Module):
def __init__(self, dimension: int):
super().__init__()
self.net = nn.Sequential(
nn.Linear(dimension, 512),
nn.ReLU(),
nn.Linear(512, 256),
nn.ReLU(),
nn.Linear(256, 128),
nn.ReLU(),
nn.Linear(128, 64),
nn.ReLU(),
nn.Linear(64, 2),
)
def forward(self, values: torch.Tensor) -> torch.Tensor:
return self.net(values.float())
@dataclass
class ProbeResult:
auroc: np.ndarray
validation_loss: np.ndarray
elapsed_seconds: float
train_indices: np.ndarray
validation_indices: np.ndarray
def probe_curve(
train_hidden: np.ndarray,
train_labels: np.ndarray,
test_hidden: np.ndarray,
test_labels: np.ndarray,
device: torch.device,
epochs: int = 15,
learning_rate: float = 1e-2,
weight_decay: float = 1e-4,
) -> ProbeResult:
"""Train the released MLP at every layer with one fixed seeded split.
The fixed split follows the paper's stated setup. It intentionally avoids
the release's implementation accident of drawing a fresh validation split
for each layer, which would confound layer comparisons.
"""
labels = np.asarray(train_labels, dtype=np.int64)
indices = np.arange(len(labels))
train_indices, validation_indices = train_test_split(
indices,
test_size=0.1,
random_state=PROBE_SEED,
stratify=labels,
)
criterion = nn.CrossEntropyLoss()
aurocs: list[float] = []
losses: list[float] = []
seed_everything(PROBE_SEED)
started = time.perf_counter()
for layer in range(train_hidden.shape[1]):
train_x = torch.from_numpy(train_hidden[train_indices, layer]).to(device=device, dtype=torch.float32)
train_y = torch.from_numpy(labels[train_indices]).to(device=device, dtype=torch.long)
validation_x = torch.from_numpy(train_hidden[validation_indices, layer]).to(device=device, dtype=torch.float32)
validation_y = torch.from_numpy(labels[validation_indices]).to(device=device, dtype=torch.long)
test_x = torch.from_numpy(test_hidden[:, layer]).to(device=device, dtype=torch.float32)
model = Probe(train_x.shape[1]).to(device)
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate, weight_decay=weight_decay)
scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=5, gamma=0.1)
best_loss = float("inf")
best_state = None
for _epoch in range(epochs):
model.train()
permutation = torch.randperm(len(train_x), device=device)
for start in range(0, len(train_x), 2048):
batch = permutation[start : start + 2048]
optimizer.zero_grad(set_to_none=True)
loss = criterion(model(train_x[batch]), train_y[batch])
loss.backward()
optimizer.step()
model.eval()
with torch.no_grad():
validation_loss = float(criterion(model(validation_x), validation_y).item())
if validation_loss < best_loss:
best_loss = validation_loss
best_state = copy.deepcopy(model.state_dict())
scheduler.step()
if best_state is not None:
model.load_state_dict(best_state)
model.eval()
with torch.no_grad():
probabilities = torch.softmax(model(test_x), dim=-1)[:, 1].cpu().numpy()
aurocs.append(float(roc_auc_score(test_labels, probabilities)))
losses.append(best_loss)
del model, optimizer, train_x, train_y, validation_x, validation_y, test_x
if device.type == "cuda":
torch.cuda.synchronize(device)
return ProbeResult(
auroc=np.asarray(aurocs),
validation_loss=np.asarray(losses),
elapsed_seconds=time.perf_counter() - started,
train_indices=np.asarray(train_indices),
validation_indices=np.asarray(validation_indices),
)
def analyze_hidden_states(
train_hidden: np.ndarray,
train_labels: np.ndarray,
test_hidden: np.ndarray,
test_labels: np.ndarray,
horizon: int,
device: torch.device,
) -> tuple[list[dict], dict]:
if len(np.unique(train_labels)) != 2 or len(np.unique(test_labels)) != 2:
raise ValueError("both train and test labels must contain two classes")
ids, id_seconds = twonn_curve(train_hidden, device)
probes = probe_curve(train_hidden, train_labels, test_hidden, test_labels, device)
selected, candidates, survivors = select_fepoid_layer(ids, horizon)
max_id_layer = int(np.argmax(ids))
oracle_layer = int(np.argmax(probes.auroc))
rows = [
{
"layer_zero_based": layer,
"layer_one_based": layer + 1,
"twonn_id": float(ids[layer]),
"probe_auroc": float(probes.auroc[layer]),
"validation_loss": float(probes.validation_loss[layer]),
"fepoid_selected": layer == selected,
"local_peak": layer in candidates,
"surviving_peak": layer in survivors,
}
for layer in range(len(ids))
]
summary = {
"fepoid_layer_zero_based": selected,
"fepoid_layer_one_based": selected + 1,
"fepoid_auroc": float(probes.auroc[selected]),
"last_layer_auroc": float(probes.auroc[-1]),
"oracle_layer_zero_based": oracle_layer,
"oracle_layer_one_based": oracle_layer + 1,
"oracle_auroc": float(probes.auroc[oracle_layer]),
"max_id_layer_zero_based": max_id_layer,
"max_id_layer_one_based": max_id_layer + 1,
"max_id_layer_auroc": float(probes.auroc[max_id_layer]),
"fepoid_gap_to_oracle": float(probes.auroc[oracle_layer] - probes.auroc[selected]),
"fepoid_gain_over_last": float(probes.auroc[selected] - probes.auroc[-1]),
"id_seconds": id_seconds,
"probe_seconds": probes.elapsed_seconds,
"local_peak_layers_zero_based": candidates,
"surviving_peak_layers_zero_based": survivors,
"train_label_counts": {
str(value): int((train_labels == value).sum()) for value in np.unique(train_labels)
},
"test_label_counts": {
str(value): int((test_labels == value).sum()) for value in np.unique(test_labels)
},
"probe_train_indices_sha256": array_sha256(probes.train_indices),
"probe_validation_indices_sha256": array_sha256(probes.validation_indices),
}
return rows, summary
def array_sha256(array: np.ndarray) -> str:
import hashlib
return hashlib.sha256(np.ascontiguousarray(array).tobytes()).hexdigest()
def write_json(path: Path, value: object) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(value, indent=2, sort_keys=True) + "\n", encoding="utf-8")
def write_jsonl(path: Path, rows: Iterable[dict]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("w", encoding="utf-8") as handle:
for row in rows:
handle.write(json.dumps(row, ensure_ascii=False, separators=(",", ":")) + "\n")
|