Spaces:
Sleeping
Sleeping
Add feature_probes package so the worker can load the probe
Browse filesFiles changed (22)
- third_party/feature_probes/feature_probes/__init__.pyAdded+7
- third_party/feature_probes/feature_probes/config.pyAdded+212
- third_party/feature_probes/feature_probes/data/__init__.pyAdded
- third_party/feature_probes/feature_probes/data/converters.pyAdded+218
- third_party/feature_probes/feature_probes/data/dataset.pyAdded+437
- third_party/feature_probes/feature_probes/evaluation/__init__.pyAdded
- third_party/feature_probes/feature_probes/evaluation/evaluate.pyAdded+337
- third_party/feature_probes/feature_probes/probes/__init__.pyAdded
- third_party/feature_probes/feature_probes/probes/attention_probe.pyAdded+109
- third_party/feature_probes/feature_probes/probes/value_head_probe.pyAdded+427
- third_party/feature_probes/feature_probes/training/__init__.pyAdded
- third_party/feature_probes/feature_probes/training/loss.pyAdded+250
- third_party/feature_probes/feature_probes/training/trainer.pyAdded+315
- third_party/feature_probes/feature_probes/types.pyAdded+22
- third_party/feature_probes/feature_probes/utils/__init__.pyAdded
- third_party/feature_probes/feature_probes/utils/activation_analysis.pyAdded+499
- third_party/feature_probes/feature_probes/utils/file_utils.pyAdded+176
- third_party/feature_probes/feature_probes/utils/hooks.pyAdded+40
- third_party/feature_probes/feature_probes/utils/metrics.pyAdded+323
- third_party/feature_probes/feature_probes/utils/model_utils.pyAdded+338
- third_party/feature_probes/feature_probes/utils/probe_loader.pyAdded+155
- third_party/feature_probes/feature_probes/utils/tokenization.pyAdded+120
1234567"""Probe module for feature detection."""
__version__ = "0.1.0"
# Only lightweight, always-needed types at the top levelfrom .types import ProbingItem, AnnotatedSpanfrom .config import ProbeConfig, TrainingConfig, EvaluationConfig123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212"""Configuration classes for probe training."""
from dataclasses import dataclass, fieldfrom pathlib import Pathfrom typing import List, Optional, Union, Literal
from feature_probes.utils.probe_loader import LOCAL_PROBES_DIRfrom feature_probes.utils.model_utils import get_num_layersfrom feature_probes.data.dataset import TokenizedProbingDatasetConfig
@dataclassclass ProbeConfig: """Configuration for a probe model.""" probe_id: str = "probe" model_name: str = "meta-llama/Meta-Llama-3.1-8B-Instruct" layer: Optional[int] = None # Which layer to attach the probe to # LoRA configuration lora_layers: Optional[Union[List[int], str]] = "all" # Which layers to apply LoRA to lora_r: int = 16 # LoRA rank lora_alpha: int = 32 # LoRA alpha scaling lora_dropout: float = 0.05 # LoRA dropout
# Loading configuration load_from: Optional[Literal['disk', 'hf']] = None # "disk", "hf", or None probe_path: Optional[Path] = None # Local path for disk loading hf_repo_id: Optional[str] = "tkwiecinski/hallucination-probes" # HuggingFace repository ID threshold: float = 0.5 # Classification threshold context_window_size: int = 1 # Size of context window for the probe probe_dtype: str = "auto" # auto | float32 | float16 | bfloat16 normalize_before_head: str = "none" # none | layernorm | rmsnorm | l2 attention_probe_n_heads: int = 4 # Number of attention heads for the probe (only used when probe_head_type="attention") probe_head_type: str = "linear" # linear | attention
def __post_init__(self): """Validate configuration.""" self.probe_path = LOCAL_PROBES_DIR / self.probe_id
if self.load_from == "hf" and not self.hf_repo_id: raise ValueError("hf_repo_id must be specified when load_from='hf'")
if self.load_from in ['disk'] and not self.probe_path.exists(): raise ValueError(f"Probe with ID {self.probe_id} not found in disk at path {self.probe_path}")
if self.layer is None: # default to hooking the value head at the last layer of the underlying LM self.layer = get_num_layers(self.model_name) - 1 if (not isinstance(self.context_window_size, int) or self.context_window_size < 0): raise ValueError("context_window must be a positive integer.")
allowed_probe_dtypes = {"auto", "fp32", "float32", "fp16", "float16", "bf16", "bfloat16"} probe_dtype_key = str(self.probe_dtype).strip().lower() if probe_dtype_key not in allowed_probe_dtypes: raise ValueError( f"Unsupported probe_dtype={self.probe_dtype!r}. " "Use one of: auto, float32, float16, bfloat16" )
allowed_norms = {"none", "layernorm", "rmsnorm", "l2"} norm_key = str(self.normalize_before_head).strip().lower() if norm_key not in allowed_norms: raise ValueError( f"Unsupported normalize_before_head={self.normalize_before_head!r}. " "Use one of: none, layernorm, rmsnorm, l2" ) if str(self.probe_head_type).strip().lower() not in {"linear", "attention"}: raise ValueError( f"Unsupported probe_head_type={self.probe_head_type!r}. Use 'linear' or 'attention'." )
if isinstance(self.lora_layers, str): if self.lora_layers == 'all': # default to training LoRA adaptors on all layers # (up to the layer where we hook the value head) self.lora_layers = list(range(0, self.layer + 1)) elif self.lora_layers.lower() == 'none': self.lora_layers = [] else: self.lora_layers = [int(layer) for layer in self.lora_layers.strip('[').strip(']').split(",")] assert len(self.lora_layers) > 0 elif self.lora_layers is None: self.lora_layers = [] assert all(isinstance(l, int) for l in self.lora_layers)
@dataclassclass TrainingConfig: """Configuration for probe training.""" wandb_project: str = "hallucination-probes" wandb_name: Optional[str] = None wandb_tags: List[str] = field(default_factory=list) probe_config: ProbeConfig = field(default_factory=ProbeConfig) upload_to_hf: bool = False save_evaluation_metrics: bool = True save_roc_curves: bool = False dump_raw_eval_results: bool = False # Training hyperparameters per_device_train_batch_size: int = 4 per_device_eval_batch_size: int = 4 high_loss_threshold: Optional[float] = None # Threshold for masking high-loss tokens lambda_lm: float = 0.0 # Weight for language modeling loss regularization lambda_kl: float = 0.0 # Weight for KL divergence regularization anneal_max_aggr: bool = True # Whether to anneal span-level max aggregation loss anneal_warmup: float = 1.0 # Fraction of training for span loss warmup learning_rate: float = 5e-5 # Overall learning rate (deprecated) probe_head_lr: Optional[float] = 5e-3 # Separate LR for probe head lora_lr: Optional[float] = 5e-5 # Separate LR for LoRA parameters sparsity_penalty_weight: Optional[float] = None num_train_samples: Optional[int] = None # Limit training samples max_steps: int = -1 # Override num_epochs if set num_train_epochs: int = 1 enable_gradient_checkpointing: bool = True gradient_accumulation_steps: int = 1 max_grad_norm: float = 1.0 eval_steps: Optional[int] = -1 # Only manually evaluate at the end evaluation_strategy: str = "no" # "steps", "epoch", or "no" logging_steps: int = 10 seed: int = 42 model_dtype: str = "auto" # auto | float32 | float16 | bfloat16 # Dataset configuration train_datasets: List[dict] = field(default_factory=list) eval_datasets: List[dict] = field(default_factory=list) # These will be populated in __post_init__ train_dataset_configs: List[TokenizedProbingDatasetConfig] = field(default_factory=list, init=False) eval_dataset_configs: List[TokenizedProbingDatasetConfig] = field(default_factory=list, init=False) def __post_init__(self): """Post-initialization processing.""" if isinstance(self.probe_config, dict): self.probe_config = ProbeConfig(**self.probe_config) # Handle special values if self.eval_steps == -1: self.eval_steps = None # Handle learning rates if self.probe_head_lr is None: self.probe_head_lr = self.learning_rate if self.lora_lr is None: self.lora_lr = self.learning_rate # Parse dataset configurations self.train_dataset_configs = [ TokenizedProbingDatasetConfig(**config) for config in self.train_datasets ] self.eval_dataset_configs = [ TokenizedProbingDatasetConfig(**config) for config in self.eval_datasets ]
# Convert scientific notation strings to floats # otherwise yaml parses e.g. '1e-6' as a string instead of a float float_fields = [ 'learning_rate', 'probe_head_lr', 'lora_lr', 'max_grad_norm', 'anneal_warmup', 'lambda_lm', 'lambda_kl', 'sparsity_penalty_weight' ] for field_name in float_fields: value = getattr(self, field_name) if value is not None and isinstance(value, str): setattr(self, field_name, float(value))
allowed_model_dtypes = {"auto", "fp32", "float32", "fp16", "float16", "bf16", "bfloat16"} model_dtype_key = str(self.model_dtype).strip().lower() if model_dtype_key not in allowed_model_dtypes: raise ValueError( f"Unsupported model_dtype={self.model_dtype!r}. " "Use one of: auto, float32, float16, bfloat16" )
@dataclassclass EvaluationConfig: """Configuration for probe evaluation.""" probe_config: ProbeConfig = field(default_factory=ProbeConfig) datasets: List[dict] = field(default_factory=list) per_device_eval_batch_size: int = 8 output_dir: Optional[Path] = None save_predictions: bool = True save_roc_curves: bool = True save_raw_results: bool = False # Save all predictions and labels # This will be populated in __post_init__ dataset_configs: List[TokenizedProbingDatasetConfig] = field(default_factory=list, init=False) def __post_init__(self): """Post-initialization processing.""" if isinstance(self.probe_config, dict): self.probe_config = ProbeConfig(**self.probe_config) self.dataset_configs = [ TokenizedProbingDatasetConfig(**dataset_config) for dataset_config in self.datasets ]
if self.output_dir is None: self.output_dir = self.probe_config.probe_path / "evaluation_results"
# %%123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218"""Dataset converters for different HuggingFace dataset formats to probing format."""
from typing import Callable, Dict, List, Optional
from datasets import Dataset
from feature_probes.types import AnnotatedSpan, ProbingItem
# Mapping from text labels to numeric values for probe training_MAP_LABEL_TO_SCALAR = { 'Not Supported': 1.0, 'NS': 1.0, # the probe should output 1.0 on text containing unsupported claims 'Insufficient Information': 1.0, # the probe should also output 1.0 if the label is 'Insufficient Information' 'Supported': 0.0, 'S': 0.0, 'N/A': -100.0, None: -100.0}
def prepare_longform_dataset(dataset: Dataset) -> List[ProbingItem]: """Prepare dataset from the one-shot pipeline labeling format.""" probing_items: List[ProbingItem] = []
for hf_item in dataset: prompt = hf_item['conversation'][-2]['content'] completion = hf_item['conversation'][-1]['content'] annotations: List[dict] = hf_item['annotations']
annotated_spans: List[AnnotatedSpan] = []
for entity in annotations: if entity is None or 'index' not in entity or not isinstance(entity['index'], int): continue
entity_text = entity['span'] label = entity['label'] idx = entity['index'] if idx is None: print(f"Entity {repr(entity_text)}'s idx set to None, discarding entity") continue elif not entity_text or entity_text not in completion: print(f"Entity {repr(entity_text)} not found in completion, discarding entity") continue
annotated_spans.append( AnnotatedSpan( span=entity_text, label=_MAP_LABEL_TO_SCALAR[label], index=idx ) )
probing_items.append( ProbingItem( prompt=prompt, completion=completion, spans=annotated_spans ) )
return probing_items
def prepare_longform_dataset_old_format(dataset: Dataset) -> List[ProbingItem]: """Prepare dataset from the one-shot pipeline labeling format.""" probing_items: List[ProbingItem] = []
for hf_item in dataset: prompt = hf_item['conversation'][0]['content'] completion = hf_item['completion'] if 'completion' in hf_item else hf_item['conversation'][-1]['content'] annotations: List[dict] = hf_item['verified_entities']
annotated_spans: List[AnnotatedSpan] = []
for entity in annotations: if entity is None or 'idx' not in entity or not isinstance(entity['idx'], int): continue
entity_text = entity['text'] label = entity['label'] idx = entity['idx'] if idx is None: print(f"Entity {repr(entity_text)}'s idx set to None, discarding entity") continue elif not entity_text or entity_text not in completion: print(f"Entity {repr(entity_text)} not found in completion, discarding entity") continue
annotated_spans.append( AnnotatedSpan( span=entity_text, label=_MAP_LABEL_TO_SCALAR[label], index=idx ) )
probing_items.append( ProbingItem( prompt=prompt, completion=completion, spans=annotated_spans ) )
return probing_items
def prepare_triviaqa(dataset: Dataset) -> List[ProbingItem]: """ Pre-processes TriviaQA dataset. The greedy completion (labeled by an LLM) is at `gt_completion` The label is at `llm_judge_label` and it's a string containing `S`, `NS`, `N/A` or some undefined string The annotated spans will be the *whole completion* """ assert 'question' in dataset[0] or 'conversation' in dataset[0]
LABEL_FIELD: str = 'llm_judge_label' if 'llm_judge_label' in dataset.features else 'label' COMPLETION_FIELD: str = 'gt_completion' VALID_LABELS: List[str] = ['S', 'NS', 'N/A'] EXACT_ANSWER_FIELD: str = 'exact_answer'
probing_items = [] for item in dataset: if item[LABEL_FIELD] not in VALID_LABELS: print(f"Invalid label {item[LABEL_FIELD]} for item, skipping") continue
prompt = item['question'] if 'question' in item else item['conversation'][0]['content'] completion = item[COMPLETION_FIELD] exact_answer = item[EXACT_ANSWER_FIELD] if EXACT_ANSWER_FIELD in item else ""
if exact_answer is None or exact_answer not in completion: print(f"Exact answer {repr(exact_answer)} not found in completion {repr(completion)}") return None
exact_answer_start_idx = completion.find(exact_answer) # The whole completion is labeled with the given label label_value: float = _MAP_LABEL_TO_SCALAR[item[LABEL_FIELD]] annotated_spans = [ AnnotatedSpan( span=exact_answer, label=label_value, index=exact_answer_start_idx ) ]
probing_items.append( ProbingItem( prompt=prompt, completion=completion, spans=annotated_spans ) )
return probing_items
def prepare_synthetic(dataset: Dataset) -> List[ProbingItem]: """Loads the synthetic dataset from the hub.""" FIELD = 'probing_item_with_hallucinations'
probing_items = [] for i, item in enumerate(dataset): probing_item = item[FIELD] annotated_spans = [ AnnotatedSpan( span=span['text'], label=span['label'], index=span['start_idx'] ) for span in probing_item['spans'] ]
# Sort spans by their index in the text completion = probing_item['completion']
if len(completion) <= 500: print(f"For item {i} completion is too short ({len(completion)} characters): {repr(completion)}") continue
annotated_spans = sorted(annotated_spans, key=lambda x: x.index)
if not all(completion[span.index:span.index+len(span.span)] == span.span for span in annotated_spans): print(f"For item {i} spans are not aligned with the completion") for span in annotated_spans: if completion[span.index:span.index+len(span.span)] != span.span: print(f"- Span: {span.span} | {span.index} | {span.label}") continue
probing_items.append(ProbingItem( prompt=probing_item['prompt'], completion=probing_item['completion'], spans=annotated_spans )) return probing_items
def get_prepare_function( hf_repo: str, subset: Optional[str] = None) -> Callable[[Dataset], List[ProbingItem]]: """Get the appropriate preparation function based on dataset name.""" if 'one_shot_pipeline' in str(subset) or 'hallucination-heads' in hf_repo: return prepare_longform_dataset_old_format elif 'modified' in str(subset) and 'synthetic-hallucinations' in hf_repo: return prepare_synthetic elif 'trivia_qa' in str(subset) or 'triviaqa' in hf_repo: return prepare_triviaqa else: # Default to one-shot pipeline format return prepare_longform_dataset
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437"""Tokenized dataset classes with token-level labels for probe training."""
import randomfrom copy import deepcopyfrom dataclasses import dataclassfrom typing import Callable, Dict, List, Optional, Tuple
import torchimport datasetsfrom jaxtyping import Float, Intfrom termcolor import coloredfrom torch import Tensorfrom torch.utils.data import Datasetfrom tqdm import tqdmfrom transformers import AutoTokenizer
from feature_probes.utils.tokenization import find_assistant_tokens_slice, find_string_in_tokens, slice_to_listfrom feature_probes.types import AnnotatedSpan, ProbingItemfrom feature_probes.data. converters import get_prepare_function
@dataclassclass TokenizedProbingDatasetConfig: """Configuration for tokenizing and labeling a probing dataset at token level.""" dataset_id: str hf_repo: str subset: Optional[str] = None split: str = "train" max_length: int = 2048 ignore_buffer: int = 0 # Buffer around spans to ignore default_ignore: bool = False # If true, ignore tokens not in any span last_span_token: bool = False # If true, only label the last token of each span pos_weight: float = 1.0 # Weight for positive (hallucination) tokens neg_weight: float = 1.0 # Weight for negative (supported) tokens shuffle: bool = True seed: int = 42 process_on_the_fly: bool = False max_num_samples: Optional[int] = None
class TokenizedProbingDataset(Dataset): """Dataset for probing model activations with annotated spans.""" def __init__( self, items: List[ProbingItem], config: TokenizedProbingDatasetConfig, tokenizer: AutoTokenizer, ): self.config = config self.tokenizer = tokenizer self.items = deepcopy(items) self.processed_items = [None] * len(items) self.debug_mode = False self.print_first_example = False self._num_skipped_spans: int = 0 self._num_added_spans: int = 0 if self.config.shuffle: self._shuffle_items() # Limit samples if specified (do this after shuffling) if self.config.max_num_samples: self.items = self.items[:self.config.max_num_samples] self.processed_items = self.processed_items[:self.config.max_num_samples] if not self.config.process_on_the_fly: self._process_items() def _process_items(self): """Pre-process all items in the dataset.""" for i, item in tqdm(enumerate(self.items), desc=f"Processing items ({self.config.dataset_id})", total=len(self.items)): if i == 0 and self.print_first_example: self.debug_mode = True else: self.debug_mode = False processed_item = self._process_item(item) if processed_item: self.processed_items[i] = processed_item print(f"Dataset {self.config.dataset_id} stats:") print(f"\t- Number of added spans: {self._num_added_spans}") print(f"\t- Number of skipped spans: {self._num_skipped_spans} / {self._num_added_spans + self._num_skipped_spans}") print(f"\t- Total number of items: {len(self.items)}") def _process_item(self, item: ProbingItem) -> Dict: """Process a single example into tokenized format with labels.""" conversation = [ {'role': 'user', 'content': item.prompt}, {'role': 'assistant', 'content': item.completion} ] full_text = self.tokenizer.apply_chat_template(conversation, tokenize=False) if self.tokenizer.bos_token and self.tokenizer.bos_token in full_text: full_text = full_text.replace(self.tokenizer.bos_token, '') encoding = self.tokenizer( full_text, truncation=True, max_length=self.config.max_length, padding='max_length', return_tensors='pt', padding_side='right' ) input_ids: Int[Tensor, "seq_len"] = encoding["input_ids"][0] attention_mask: Int[Tensor, "seq_len"] = encoding["attention_mask"][0] labels, weights, pos_spans, neg_spans = self._compute_positional_labels( input_ids=input_ids, item=item ) input_str: str = self.tokenizer.decode(input_ids) assistant_tokens_slice = find_assistant_tokens_slice(input_ids, input_str, self.tokenizer) completion_start_idx = assistant_tokens_slice.stop lm_labels = input_ids.clone() lm_labels[:completion_start_idx] = -100 # ignore all tokens in the prompt lm_labels[attention_mask == 0] = -100 # ignore padding tokens return { "input_ids": input_ids, # Int[Tensor, "seq_len"] "attention_mask": attention_mask, # Int[Tensor, "seq_len"] "classification_labels": labels, # Float[Tensor, "seq_len"] "classification_weights": weights, # Float[Tensor, "seq_len"] "pos_spans": pos_spans, # List[List[int]] "neg_spans": neg_spans, # List[List[int]] "lm_labels": lm_labels, # Int[Tensor, "seq_len"] } def print_token_labels( self, input_ids: torch.Tensor, positive_indices: List[int], negative_indices: List[int], ignore_indices: List[int], spans: List[AnnotatedSpan] ): """Debug method to print how tokens have been labeled."""
tokens = [self.tokenizer.decode(tok) for tok in input_ids]
print(f"================================================") print(f"Number of spans: {len(spans)}") print(f"Number of non-factual (hallucinated) spans: {len([f for f in spans if f.label == 1.0])}") print(f"Number of N/A spans: {len([f for f in spans if f.label == -100])}") print(f"Number of factual spans: {len([f for f in spans if f.label == 0.0])}") print(f"Legend: red - positive, green - negative, blue - ignored")
for i, token in enumerate(tokens): if token == self.tokenizer.eos_token: continue
if i in positive_indices: print(colored(token, 'red'), end='') elif i in negative_indices: print(colored(token, 'green'), end='') elif i in ignore_indices: print(colored(token, 'blue'), end='') else: print(token, end='')
print(f"================================================") def _compute_positional_labels( self, input_ids: torch.Tensor, item: ProbingItem ) -> Tuple[torch.Tensor, torch.Tensor, List[List[int]], List[List[int]]]: """ Computes positional labels for a sequence of tokens based on annotated spans. For each span in the example: - If it's a hallucination (label 1.0): Sets span tokens to 1.0 and nearby tokens within ignore_buffer to -100.0 - If it's a supported fact (label 0.0): Sets span tokens to 0.0 and nearby tokens within ignore_buffer to -100.0 - If it's unlabeled/undecided (label -100.0): Sets span tokens to -100.0 Args: input_ids: Input token IDs item: ProbingItem containing the spans and their labels Returns: Tuple of (labels, weights, pos_spans, neg_spans) """ input_str: str = self.tokenizer.decode(input_ids) completion: str = item.completion positive_indices: List[int] = [] # indices of hallucinated spans negative_indices: List[int] = [] # indices of supported spans ignore_indices: List[int] = [] # indices to ignore in training positive_spans: List[List[int]] = [] negative_spans: List[List[int]] = [] def get_nearby_indices(span_indices: List[int]) -> List[int]: left_window = list(range(max(0, span_indices[0] - self.config.ignore_buffer), span_indices[0])) right_window = list(range(span_indices[-1] + 1, min(len(input_ids), span_indices[-1] + 1 + self.config.ignore_buffer))) return left_window + right_window # Find assistant tokens slice to know where to start looking for spans assistant_tokens_slice = find_assistant_tokens_slice( input_ids, input_str, self.tokenizer ) completion_start_idx = assistant_tokens_slice.stop cur_idx = assistant_tokens_slice.stop # Sort spans by their index in the text spans = sorted(item.spans, key=lambda x: x.index) for span in spans: if span.span not in input_str: self._num_skipped_spans += 1 continue try: # First try to find the span after the assistant tokens positions_slice = find_string_in_tokens(span.span, input_ids[cur_idx:], self.tokenizer) positions_slice = slice(positions_slice.start + cur_idx, positions_slice.stop + cur_idx) except (AssertionError, ValueError): try: # If not found, try the whole input_ids print(f"Repeating position_slice search on all tokens after failing to find span {repr(span.span)} in input_ids[cur_idx:]: {repr(self.tokenizer.decode(input_ids[cur_idx:]))[:50]}...") positions_slice = find_string_in_tokens(span.span, input_ids, self.tokenizer) except (AssertionError, ValueError) as e: print(f"Span {repr(span.span)} not found in input_ids, skipping entity") self._num_skipped_spans += 1 continue if positions_slice is None: continue span_indices = slice_to_list(positions_slice, len(input_ids)) if not span_indices: continue cur_idx = positions_slice.start if self.config.last_span_token: # If last_span_token is true, only use the last token of the span span_indices = [span_indices[-1]] # Get indices of tokens to ignore around this span nearby_indices = get_nearby_indices(span_indices) if span.label == 1.0: # Hallucination positive_indices.extend(span_indices) ignore_indices.extend(nearby_indices) positive_spans.append([span_indices[0], span_indices[-1]]) elif span.label == 0.0: # Supported negative_indices.extend(span_indices) negative_spans.append([span_indices[0], span_indices[-1]]) else: # -100.0 (ignored) ignore_indices.extend(span_indices) self._num_added_spans += 1 # Remove duplicates and sort positive_indices = sorted(list(set(positive_indices))) negative_indices = sorted(list(set(negative_indices) - set(positive_indices))) ignore_indices = sorted(list(set(ignore_indices) - set(positive_indices) - set(negative_indices))) # Initialize labels and weights default_label = -100.0 if self.config.default_ignore else 0.0 labels = torch.full((len(input_ids),), default_label, dtype=torch.float32) # Set labels and weights labels[input_ids == self.tokenizer.pad_token_id] = -100.0 labels[:completion_start_idx] = -100.0 labels[ignore_indices] = -100.0 labels[positive_indices] = 1.0 labels[negative_indices] = 0.0 weights = torch.full((len(input_ids),), 1.0, dtype=torch.float32) weights[ignore_indices] = 0.0 # N/A weight weights[positive_indices] = self.config.pos_weight weights[negative_indices] = self.config.neg_weight if self.debug_mode: self.print_token_labels(input_ids, positive_indices, negative_indices, ignore_indices, spans) return labels, weights, positive_spans, negative_spans def _shuffle_items(self): """Shuffle the items using the configured seed.""" random.seed(self.config.seed) random.shuffle(self.items) random.seed(self.config.seed) random.shuffle(self.processed_items) def __len__(self): return len(self.items) def __getitem__(self, idx): if self.config.process_on_the_fly and self.processed_items[idx] is None: self.processed_items[idx] = self._process_item(self.items[idx]) return self.processed_items[idx] def __add__(self, other): """ Concatenate two TokenizedProbingDataset instances. Args: other: Another TokenizedProbingDataset instance to concatenate Returns: TokenizedProbingDataset: A new dataset containing items from both """ if not isinstance(other, TokenizedProbingDataset): raise TypeError(f"Can only concatenate with another TokenizedProbingDataset, got {type(other)}") if self.config.max_length != other.config.max_length: raise ValueError("Can't concatenate datasets of different token lengths") if self.config.shuffle != other.config.shuffle: raise ValueError("Can't concatenate datasets if one of them (but not the other) are shuffled") # Create a new dataset with combined items combined_items = self.items + other.items combined_processed_items = self.processed_items + other.processed_items # Use the configuration from the first dataset new_dataset = TokenizedProbingDataset( items=[], # we don't want to recompute everything again tokenizer=self.tokenizer, config=self.config, ) new_dataset.items = combined_items new_dataset.processed_items = combined_processed_items if self.config.shuffle: new_dataset._shuffle_items() return new_dataset def __radd__(self, other): return self.__add__(other)
def tokenized_probing_collate_fn(batch: List[Dict[str, torch.Tensor]]) -> Dict[str, torch.Tensor]: """ Collate function for DataLoader that handles variable-length tokenized sequences. Args: batch: List of tokenized dataset items Returns: Batched dictionary with padded sequences """ # Find max length in batch max_len = max(len(item["input_ids"]) for item in batch) # Initialize batched tensors batch_size = len(batch) input_ids = torch.full((batch_size, max_len), 0, dtype=torch.long) attention_mask = torch.zeros((batch_size, max_len), dtype=torch.long) classification_labels = torch.full((batch_size, max_len), -100.0, dtype=torch.float32) classification_weights = torch.zeros((batch_size, max_len), dtype=torch.float32) lm_labels = torch.full((batch_size, max_len), -100, dtype=torch.long) # Lists for spans pos_spans = [] neg_spans = [] # Fill in the batch for i, item in enumerate(batch): seq_len = len(item["input_ids"]) input_ids[i, :seq_len] = item["input_ids"] attention_mask[i, :seq_len] = item["attention_mask"] classification_labels[i, :seq_len] = item["classification_labels"] classification_weights[i, :seq_len] = item["classification_weights"] lm_labels[i, :seq_len] = item["lm_labels"] pos_spans.append(item["pos_spans"]) neg_spans.append(item["neg_spans"]) return { "input_ids": input_ids, "attention_mask": attention_mask, "classification_labels": classification_labels, "classification_weights": classification_weights, "lm_labels": lm_labels, "pos_spans": pos_spans, "neg_spans": neg_spans, }
def create_probing_dataset( cfg: TokenizedProbingDatasetConfig, tokenizer: AutoTokenizer) -> TokenizedProbingDataset: """ Create a probing dataset from configuration. This loads the dataset from HuggingFace and processes it using the appropriate dataset-specific preparation function. """ # Lazy import to avoid circular dependency # Load dataset from HuggingFace if cfg.subset: raw_hf_dataset = datasets.load_dataset(cfg.hf_repo, cfg.subset, split=cfg.split) else: raw_hf_dataset = datasets.load_dataset(cfg.hf_repo, split=cfg.split)
# Handle max_num_samples if cfg.max_num_samples is not None: if cfg.shuffle: print(f"Shuffling and truncating dataset to {cfg.max_num_samples} / {len(raw_hf_dataset)} samples") assert cfg.seed is not None, "Seed must be provided if shuffle is True" raw_hf_dataset = raw_hf_dataset.shuffle(seed=cfg.seed) else: print(f"Truncating dataset to first {cfg.max_num_samples} / {len(raw_hf_dataset)} samples") raw_hf_dataset = raw_hf_dataset.select(range(min(cfg.max_num_samples, len(raw_hf_dataset))))
print(f"Loading dataset: {cfg.hf_repo} | {cfg.subset} | {cfg.split}")
# Get appropriate preparation function prepare_function = get_prepare_function(cfg.hf_repo, cfg.subset)
# Convert HF dataset to list of probing items probing_items: List[ProbingItem] = prepare_function(raw_hf_dataset)
tokenized_probing_dataset = TokenizedProbingDataset( items=probing_items, config=cfg, tokenizer=tokenizer )
return tokenized_probing_dataset123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337"""Evaluation script for hallucination detection probes."""
import gcimport jsonfrom pathlib import Pathfrom typing import Dict, List, Optional, Tuple
import numpy as npimport torchfrom jaxtyping import Float, Intfrom torch import Tensorfrom torch.utils.data import DataLoaderfrom tqdm import tqdmfrom transformers import AutoTokenizerimport argparsefrom dotenv import load_dotenv
from feature_probes.utils.file_utils import save_jsonl, load_yamlfrom feature_probes.utils.metrics import compute_clf_metrics, plot_roc_curves, print_eval_metricsfrom feature_probes.utils.model_utils import load_model_and_tokenizer from feature_probes.data.dataset import ( TokenizedProbingDataset, create_probing_dataset, tokenized_probing_collate_fn)from feature_probes.config import EvaluationConfigfrom feature_probes.training.loss import compute_probe_bce_lossfrom feature_probes.probes.value_head_probe import ValueHeadProbe, setup_probe
@torch.no_grad()def evaluate_probe( probe: ValueHeadProbe, eval_dataloader: DataLoader, threshold: float = 0.5, metric_key_prefix: Optional[str] = None, verbose: bool = True, save_roc_curves: bool = True, save_dir: Optional[Path] = None, dump_raw_results: bool = False,) -> Dict[str, float]: """ Evaluate a probe on a dataset. Args: probe: The probe to evaluate eval_dataloader: DataLoader for evaluation data threshold: Classification threshold metric_key_prefix: Prefix for metric keys verbose: Whether to print metrics save_roc_curves: Whether to save ROC curve plots save_dir: Directory to save results dump_raw_results: Whether to save raw predictions Returns: Dictionary of evaluation metrics """ # Force garbage collection before evaluation gc.collect() torch.cuda.empty_cache()
# Initialize metric collections for different aggregation levels all_probs = {'all': [], 'span': [], 'span_max': []} all_preds = {'all': [], 'span': [], 'span_max': []} all_labels = {'all': [], 'span': [], 'span_max': []}
total_lm_loss = 0 total_probe_loss = 0 total_sparsity = 0 num_batches = 0
for batch in tqdm(eval_dataloader, desc="Evaluating"): input_ids: Int[Tensor, "batch_size seq_len"] = batch["input_ids"].to(probe.device) attention_mask: Int[Tensor, "batch_size seq_len"] = batch["attention_mask"].to(probe.device) classification_labels: Float[Tensor, "batch_size seq_len"] = batch["classification_labels"].to(probe.device) classification_weights: Float[Tensor, "batch_size seq_len"] = batch["classification_weights"].to(probe.device) lm_labels: Int[Tensor, "batch_size seq_len"] = batch["lm_labels"].to(probe.device) pos_spans: List[List[List[int]]] = batch["pos_spans"] neg_spans: List[List[List[int]]] = batch["neg_spans"]
# Forward pass outputs = probe( input_ids=input_ids, attention_mask=attention_mask, labels=lm_labels, )
probe_logits: Float[Tensor, "batch_size seq_len"] = outputs["probe_logits"].squeeze(-1) probe_probs: Float[Tensor, "batch_size seq_len"] = torch.sigmoid(probe_logits).float() probe_preds: Float[Tensor, "batch_size seq_len"] = (probe_probs > threshold).float()
probe_loss = compute_probe_bce_loss( probe_logits=probe_logits, classification_labels=classification_labels, classification_weights=classification_weights, )
# 1. All-token metrics (excluding padding and ignored tokens) valid_mask = (attention_mask == 1) & (classification_labels != -100.0) all_probs['all'].extend(probe_probs[valid_mask].cpu().numpy()) all_preds['all'].extend(probe_preds[valid_mask].cpu().numpy()) all_labels['all'].extend(classification_labels[valid_mask].cpu().numpy())
# 2. Span-level metrics annotated_tokens_mask = torch.zeros_like(input_ids, dtype=torch.bool) for i in range(len(input_ids)): all_spans: List[List[int]] = pos_spans[i] + neg_spans[i] for span_range in all_spans: start, end = span_range[0], span_range[1] assert start <= end, f"Invalid span range: {span_range}" annotated_tokens_mask[i, start:end+1] = True
# Filter out ignored tokens annotated_tokens_mask = annotated_tokens_mask & (classification_labels != -100.0) all_probs['span'].extend(probe_probs[annotated_tokens_mask].cpu().numpy()) all_preds['span'].extend(probe_preds[annotated_tokens_mask].cpu().numpy()) all_labels['span'].extend(classification_labels[annotated_tokens_mask].cpu().numpy())
# 3. Span-level metrics (with max aggregation) for i in range(len(input_ids)): all_spans: List[List[int]] = pos_spans[i] + neg_spans[i] if len(all_spans) == 0: continue
span_labels = [1.0] * len(pos_spans[i]) + [0.0] * len(neg_spans[i])
for label, (start, end) in zip(span_labels, all_spans): max_prob = probe_probs[i, start:end+1].max().cpu().item() max_pred = probe_preds[i, start:end+1].max().cpu().item() all_probs['span_max'].append(max_prob) all_preds['span_max'].append(max_pred) all_labels['span_max'].append(label) # Update running metrics total_lm_loss += outputs["lm_loss"].item() total_probe_loss += probe_loss.item() total_sparsity += probe_probs[attention_mask == 1].mean().item() num_batches += 1
# Compute average metrics metrics = { "lm_loss": total_lm_loss / num_batches, "probe_loss": total_probe_loss / num_batches, "sparsity": total_sparsity / num_batches, "probe_threshold": threshold, }
# Convert lists to numpy arrays all_probs = {k: np.array(v) for k, v in all_probs.items()} all_preds = {k: np.array(v) for k, v in all_preds.items()} all_labels = {k: np.array(v) for k, v in all_labels.items()}
# Compute classification metrics for each aggregation level for agg_level in ['all', 'span', 'span_max']: if len(all_labels[agg_level]) == 0: continue
clf_metrics = compute_clf_metrics( all_preds[agg_level], all_labels[agg_level], all_probs[agg_level] )
for metric_name, metric_value in clf_metrics.items(): metrics[f"{agg_level}_{metric_name}"] = metric_value
# Add prefix if specified if metric_key_prefix: metrics = { f"{metric_key_prefix}/{k}": v for k, v in metrics.items() }
# Print metrics if verbose if verbose: print_eval_metrics( metrics, metric_key_prefix=metric_key_prefix, all_labels=all_labels, include_random_baseline=True, )
# Save ROC curves if save_roc_curves and save_dir: plot_roc_curves( all_preds, all_labels, all_probs, save_dir=save_dir, prefix=metric_key_prefix )
# Save raw results if requested if dump_raw_results and save_dir: results_dir = save_dir / "eval_results" if metric_key_prefix: results_dir = results_dir / metric_key_prefix results_dir.mkdir(parents=True, exist_ok=True) with open(results_dir / 'metrics.json', 'w') as f: json.dump(metrics, f, indent=4) # Save raw predictions for agg_level in ['span_max']: if len(all_labels[agg_level]) > 0: np.save(results_dir / f'{agg_level}_probs.npy', all_probs[agg_level]) np.save(results_dir / f'{agg_level}_preds.npy', all_preds[agg_level]) np.save(results_dir / f'{agg_level}_labels.npy', all_labels[agg_level])
# Clean up gc.collect() torch.cuda.empty_cache()
return metrics
def evaluate_on_multiple_datasets( probe: ValueHeadProbe, eval_config: EvaluationConfig, tokenizer: AutoTokenizer,) -> Dict[str, Dict[str, float]]: """ Evaluate probe on multiple datasets. Args: probe: The probe to evaluate eval_config: Evaluation configuration tokenizer: Tokenizer for the model Returns: Dictionary mapping dataset IDs to their metrics """ all_metrics = {} # Create output directory output_dir = Path(eval_config.output_dir) output_dir.mkdir(parents=True, exist_ok=True) # Evaluate on each dataset for dataset_config in eval_config.dataset_configs: print(f"\nEvaluating on {dataset_config.dataset_id}...") # Create dataset dataset = create_probing_dataset(dataset_config, tokenizer) print(f" Dataset size: {len(dataset)} samples") # Create dataloader dataloader = DataLoader( dataset, batch_size=eval_config.per_device_eval_batch_size, collate_fn=tokenized_probing_collate_fn, shuffle=False, ) # Evaluate metrics = evaluate_probe( probe=probe, eval_dataloader=dataloader, threshold=eval_config.probe_config.threshold, metric_key_prefix=dataset_config.dataset_id, verbose=True, save_roc_curves=eval_config.save_roc_curves, save_dir=output_dir if eval_config.save_roc_curves else None, dump_raw_results=eval_config.save_raw_results, ) # Save metrics metrics['dataset_id'] = dataset_config.dataset_id save_jsonl([metrics], output_dir / "eval_metrics.jsonl", append=True) all_metrics[dataset_config.dataset_id] = metrics return all_metrics
def main(eval_config: EvaluationConfig): """Main evaluation function.""" # Load environment variables from .env if present load_dotenv() print("Evaluation Configuration:") for key, value in eval_config.__dict__.items(): print(f" {key}: {value}") # Load model and tokenizer print(f"\nLoading model: {eval_config.probe_config.model_name}") model, tokenizer = load_model_and_tokenizer( eval_config.probe_config.model_name, ) tokenizer.padding_side = 'right' # Load probe using the config print(f"\nLoading probe: {eval_config.probe_config.probe_id}") model, probe = setup_probe(model, eval_config.probe_config) print(f"Device: {next(probe.parameters()).device}") # Run evaluation print(f"\nEvaluating on {len(eval_config.dataset_configs)} datasets...") results = evaluate_on_multiple_datasets(probe, eval_config, tokenizer) # Print summary print("\n" + "="*50) print("EVALUATION SUMMARY") print("="*50) for dataset_id, metrics in results.items(): print(f"\n{dataset_id}:") key_metrics = [ f"span_max_accuracy", f"span_max_f1", f"span_max_auc" ] for metric in key_metrics: full_key = f"{dataset_id}/{metric}" if full_key in metrics: print(f" {metric}: {metrics[full_key]:.4f}")
if __name__ == "__main__": parser = argparse.ArgumentParser(description="Evaluate a probe") parser.add_argument( "--config", type=str, default="configs/eval_config.yaml", help="Path to evaluation configuration file" ) args = parser.parse_args() # Load config from YAML config_dict = load_yaml(args.config) eval_config = EvaluationConfig(**config_dict) main(eval_config)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109import torchimport torch.nn as nn
class AttentionProbeHead(nn.Module): """ Attention-based value probe: - Query projection: hidden_dim -> n_heads - Value projection: hidden_dim -> (n_heads * n_outputs) - Learned position weights: n_heads Produces per-sequence scalar predictions. """ def __init__( self, hidden_size: int, n_heads: int = 4, n_outputs: int = 1, device=None, dtype=None ): super().__init__() self.n_heads = n_heads self.n_outputs = n_outputs
self.query_proj = nn.Linear(hidden_size, n_heads, device=device, dtype=dtype) self.value_proj = nn.Linear(hidden_size, n_heads * n_outputs, device=device, dtype=dtype) # ALiBi-style learned slope self.position_weights = nn.Parameter(torch.zeros(n_heads, device=device, dtype=dtype))
# Initialize nn.init.normal_(self.query_proj.weight, std=0.01) nn.init.normal_(self.value_proj.weight, std=0.01) nn.init.zeros_(self.query_proj.bias) nn.init.zeros_(self.value_proj.bias)
def forward(self, hidden: torch.Tensor): """ hidden: [batch, seq, hidden_size] returns: [batch, seq, n_outputs] """ B, S, H = hidden.shape
# [B, S, H] @ [H, n_heads] = [B, S, n_heads] attn_logits = self.query_proj(hidden)
# ALiBi-like positional slope: [1, S, 1] * [1, 1, n_heads] pos = torch.arange(S, device=hidden.device, dtype=hidden.dtype).unsqueeze(-1) # [S, 1] attn_logits = attn_logits + pos * self.position_weights[None, None, :]
# compute softmax over positions attn_weights = torch.softmax(attn_logits, dim=1) # [B, S, n_heads]
# values: [B, S, n_heads * n_outputs] -> [B, S, n_heads, n_outputs] values = self.value_proj(hidden).view(B, S, self.n_heads, self.n_outputs)
# weighted sum: sum over seq dimension # (B, S, n_heads, 1) * (B, S, n_heads, n_outputs) out = (attn_weights.unsqueeze(-1) * values).sum(dim=1) # [B, n_heads, n_outputs]
# combine heads (mean is simplest; can use a learned mix) out = out.mean(dim=1) # [B, n_outputs]
return out
class PerTokenAttentionProbe(nn.Module): """ Attention-based value probe producing per-token outputs: - Query projection: hidden_dim -> n_heads - Value projection: hidden_dim -> (n_heads * n_outputs) - Learned position weights: n_heads Produces per-token scalar predictions. """ def __init__(self, hidden_size, n_heads=4, n_outputs=1, device=None, dtype=None): super().__init__() self.n_heads = n_heads self.n_outputs = n_outputs
self.query_proj = nn.Linear(hidden_size, n_heads, device=device, dtype=dtype) self.value_proj = nn.Linear(hidden_size, n_heads * n_outputs, device=device, dtype=dtype) self.position_weights = nn.Parameter(torch.zeros(n_heads, device=device, dtype=dtype))
def forward(self, hidden): # hidden: [B, S, H] B, S, H = hidden.shape
# queries: [B, S, n_heads] attn_logits = self.query_proj(hidden) # each token has its own query
# ALiBi-like positional bias: [S, S, n_heads] pos = torch.arange(S, device=hidden.device).unsqueeze(0) - torch.arange(S, device=hidden.device).unsqueeze(1) pos = pos.clamp(min=0).unsqueeze(-1) # causal mask style attn_logits = attn_logits.unsqueeze(2) + pos * self.position_weights[None, None, :] # [B, S, S, n_heads]
# softmax over tokens (axis=2) attn_weights = torch.softmax(attn_logits, dim=2) # [B, S, S, n_heads]
# values: [B, S, n_heads, n_outputs] values = self.value_proj(hidden).view(B, S, self.n_heads, self.n_outputs)
# weighted sum for each token out = (attn_weights.unsqueeze(-1) * values.unsqueeze(1)).sum(dim=2) # [B, S, n_heads, n_outputs]
# combine heads out = out.mean(dim=2) # [B, S, n_outputs]
return out123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427"""ValueHeadProbe: A probe that attaches to a specific layer and predicts hallucinations."""
import jsonimport osfrom pathlib import Pathfrom typing import Dict, List, Optional, Union, Tuple
from jaxtyping import Float, Intfrom torch import Tensor
import torchimport torch.nn as nnfrom peft import PeftModel, get_peft_modelfrom transformers import AutoModelForCausalLM, PreTrainedModel
from feature_probes.utils.hooks import add_hooksfrom feature_probes.utils.model_utils import ( get_model_layers, get_model_hidden_size, setup_lora_for_layers, resolve_torch_dtype,)from feature_probes.utils.probe_loader import download_probe_from_hffrom feature_probes.probes.attention_probe import PerTokenAttentionProbe, AttentionProbeHead
class L2Norm(nn.Module): """Per-token L2 normalization for hidden features before probe head."""
def __init__(self, eps: float = 1e-6): super().__init__() self.eps = eps
def forward(self, x: torch.Tensor) -> torch.Tensor: denom = x.norm(p=2, dim=-1, keepdim=True).clamp_min(self.eps) return x / denom
class ValueHeadProbe(nn.Module): """ A probe that hooks into a specific layer of a language model and uses a linear head to predict per-token binary classification (e.g., hallucination detection). This probe: 1. Attaches a forward hook to capture hidden states from a specified layer 2. Applies a linear transformation to predict hallucination scores 3. Can be used with or without LoRA adapters """ def __init__( self, model: Union[AutoModelForCausalLM, PeftModel], layer_idx: Optional[int] = None, path: Optional[Union[str, Path]] = None, context_window_size: Optional[int] = 1, attention_probe_n_heads: int = 4, probe_dtype: Optional[str] = None, normalize_before_head: Optional[str] = None, probe_head_type: str = "linear", seed: int = 42, ): """ Initialize the ValueHeadProbe. Args: model: The language model (with or without LoRA adapters) layer_idx: Optional index of the layer to attach the probe to (if not specified we'll infer it from the previously saved probe configuration file) path: Optional path to load pre-trained probe weights from """ super().__init__()
assert layer_idx or path, "Either path or layer index must be provided, otherwise we can't infer the layer where we should hook the value head to." saved_probe_dtype = None saved_norm = None if path: saved_config = json.load(open(path / "probe_config.json"))
if layer_idx is None: layer_idx = saved_config["layer_idx"] else: # We check that if a layer_idx is provided, it matches the one given in the previously saved config assert layer_idx == saved_config["layer_idx"] saved_probe_dtype = saved_config.get("probe_dtype") saved_norm = saved_config.get("normalize_before_head") probe_head_type = saved_config.get("probe_head_type", probe_head_type)
hidden_size = get_model_hidden_size(model) model_layers = get_model_layers(model)
self.model = model self.layer_idx = layer_idx self.target_module = model_layers[layer_idx] self.target_layer_name = self.target_module.__class__.__name__ self.context_window_size = context_window_size self.attention_probe_n_heads = attention_probe_n_heads self.probe_head_type = str(probe_head_type).strip().lower()
self.probe_dtype = probe_dtype if probe_dtype is not None else (saved_probe_dtype or "auto") self.normalize_before_head = ( normalize_before_head if normalize_before_head is not None else (saved_norm or "none") ).strip().lower() head_dtype = resolve_torch_dtype(self.probe_dtype, default=model.dtype)
norm_hidden_size = hidden_size * context_window_size self.pre_head_norm = self._build_pre_head_norm( self.normalize_before_head, hidden_size=norm_hidden_size, device=model.device, dtype=head_dtype, )
if not isinstance(model, PeftModel): print("WARNING: Model is not a PeftModel. Remember to add LoRA adapters if needed.")
# Initialize the value head input_size = hidden_size * context_window_size if path: # Load pre-trained weights if path is provided self.value_head, _ = ValueHeadProbe.load_head( path, device=model.device, dtype=head_dtype, ) elif self.probe_head_type == "attention": torch.manual_seed(seed) self.value_head = PerTokenAttentionProbe( input_size, n_heads=self.attention_probe_n_heads, n_outputs=1, device=model.device, dtype=head_dtype, ) else: # "linear" torch.manual_seed(seed) self.value_head = nn.Linear(input_size, 1, device=model.device, dtype=head_dtype) self._initialize_weights() # Initialize hook state self._hooked_hidden_states: Optional[torch.Tensor] = None self._hook_fn = self._get_hook_fn()
@staticmethod def _build_pre_head_norm( norm_kind: str, *, hidden_size: int, device: torch.device, dtype: torch.dtype, ) -> nn.Module: key = (norm_kind or "none").strip().lower() if key == "none": return nn.Identity() if key == "layernorm": return nn.LayerNorm(hidden_size, device=device, dtype=dtype) if key == "rmsnorm": return nn.RMSNorm(hidden_size, device=device, dtype=dtype) if key == "l2": return L2Norm() raise ValueError(f"Unsupported normalize_before_head={norm_kind!r}") def _initialize_weights(self): """Initialize the value head weights with small random values.""" with torch.no_grad(): self.value_head.weight.data.normal_(mean=0.0, std=0.01) if self.value_head.bias is not None: self.value_head.bias.data.zero_() def _get_hook_fn(self): """ Forward hook to capture hidden states from target layer. `module_output` is typically [batch_size, seq_len, hidden_dim]. We do NOT detach it, so gradients can flow back. """ def hook_fn(module, module_input, module_output): if isinstance(module_input, tuple) and module_output[0].ndim == 3: self._hooked_hidden_states = module_output[0] else: self._hooked_hidden_states = module_output return hook_fn def forward( self, input_ids: Int[Tensor, 'batch_size seq_len'], attention_mask: Optional[Int[Tensor, 'batch_size seq_len']] = None, labels: Optional[Int[Tensor, 'batch_size seq_len']] = None, **kwargs ) -> Dict[str, torch.Tensor]: """ Forward pass through the model with probe attached. Args: input_ids: Input token IDs [batch_size, seq_len] attention_mask: Attention mask [batch_size, seq_len] labels: Optional labels for language modeling loss **kwargs: Additional arguments passed to the model Returns: Dictionary containing: - lm_logits: Language model output logits [batch_size, seq_len, vocab_size] - probe_logits: Probe output logits [batch_size, seq_len, 1] - lm_loss: Language modeling loss (if labels provided) """ # Reset hooked hidden states self._hooked_hidden_states = None # Set up hooks fwd_hooks = [(self.target_module, self._hook_fn)] with add_hooks(module_forward_pre_hooks=[], module_forward_hooks=fwd_hooks): # Forward pass through the model outputs = self.model( input_ids=input_ids, attention_mask=attention_mask, labels=labels, output_hidden_states=False, **kwargs ) # Check that hidden states were captured if self._hooked_hidden_states is None: raise RuntimeError("Failed to capture hidden states from target layer") shifted = [self._hooked_hidden_states] for k in range(1, self.context_window_size): s = self._hooked_hidden_states.roll(k, dims=1) s[:, :k, :] = 0 # zero-pad wrapped positions shifted.append(s) # Concatenate context window hidden states context_hidden_states = torch.cat(shifted, dim=-1)
# Keep norm input dtype aligned with norm params/buffers (e.g., fp32 LayerNorm). norm_dtype = None for tensor in self.pre_head_norm.parameters(): norm_dtype = tensor.dtype break if norm_dtype is None: for tensor in self.pre_head_norm.buffers(): norm_dtype = tensor.dtype break if norm_dtype is not None and context_hidden_states.dtype != norm_dtype: context_hidden_states = context_hidden_states.to(norm_dtype)
context_hidden_states = self.pre_head_norm(context_hidden_states)
# Ensure head/input dtypes match when model and probe run at different precision. try: head_param = next(self.value_head.parameters()) if context_hidden_states.dtype != head_param.dtype: context_hidden_states = context_hidden_states.to(head_param.dtype) except StopIteration: pass
probe_logits: Float[Tensor, 'batch_size seq_len 1'] = self.value_head(context_hidden_states)
return { "lm_logits": outputs.logits, "probe_logits": probe_logits, "lm_loss": outputs.loss if hasattr(outputs, 'loss') else None } def save(self, path: Union[str, Path]): """ Save the probe to disk. Args: path: Directory to save the probe to """ os.makedirs(path, exist_ok=True) # Save LoRA adapters if present if isinstance(self.model, PeftModel): self.model.save_pretrained(path) # Save value head weights torch.save( self.value_head.state_dict(), path / "probe_head.bin" ) # Save configuration if isinstance(self.value_head, nn.Linear): hidden_size = self.value_head.in_features elif hasattr(self.value_head, "query_proj"): # PerTokenAttentionProbe hidden_size = self.value_head.query_proj.in_features else: hidden_size = None
probe_config = { "target_layer_name": self.target_module.__class__.__name__, "layer_idx": self.layer_idx, "attention_probe_n_heads": self.attention_probe_n_heads, "probe_dtype": self.probe_dtype, "normalize_before_head": self.normalize_before_head, "hidden_size": hidden_size, "probe_head_type": self.probe_head_type, "attention_probe_n_heads": self.attention_probe_n_heads, } with open(path / "probe_config.json", 'w') as f: json.dump(probe_config, f, indent=4) print(f"Probe saved to {path}") @property def device(self): """Get the device of the model.""" return self.model.device @classmethod def load_head( cls, path: Path, device: str = 'cuda', dtype: torch.dtype = torch.bfloat16 ) -> Tuple[nn.Module, int]: """ Loads the linear value head from the given path. Args: path: Path to the probe directory device: Device to load the probe head on dtype: Data type for the probe head Returns: Tuple of (probe_head, layer_idx) """ with open(path / "probe_config.json") as f: probe_config = json.load(f)
hidden_size = probe_config['hidden_size'] probe_layer_idx = probe_config['layer_idx'] head_type = probe_config.get("probe_head_type", "attention") # old saves default to attention n_heads = probe_config.get("attention_probe_n_heads", 4)
if head_type == "attention": probe_head = PerTokenAttentionProbe(hidden_size, n_heads=n_heads, n_outputs=1, device=device, dtype=dtype) else: probe_head = nn.Linear(hidden_size, 1, device=device, dtype=dtype) state_dict = torch.load( path / "probe_head.bin", map_location=device, weights_only=True ) probe_head.load_state_dict(state_dict) return probe_head, probe_layer_idx
def _probe_input_size(self) -> int: if hasattr(self.value_head, "query_proj"): return int(self.value_head.query_proj.in_features) if hasattr(self.value_head, "in_features"): return int(self.value_head.in_features) raise ValueError("Unable to infer probe input size from value head")
def setup_probe( model: PreTrainedModel, probe_config: 'ProbeConfig', seed: int = 42,) -> Tuple[PreTrainedModel, ValueHeadProbe]: """ Set up a probe with the given configuration. This handles downloading from HF if needed, setting up LoRA adapters, and creating the ValueHeadProbe instance. Args: model: The base language model probe_config: Probe configuration Returns: Tuple of (model with LoRA if applicable, probe instance) """ # We freeze all parameters of the base model # otherwise the optimizer will do a full-finetuning for _, param in model.named_parameters(): param.requires_grad = False
# Download from HF if needed if probe_config.load_from == 'hf' and not probe_config.probe_path.exists(): download_probe_from_hf( repo_id=probe_config.hf_repo_id, probe_id=probe_config.probe_id )
if probe_config.load_from in ['hf', 'disk']: # Set up the LoRAs (if applicable) if (probe_config.probe_path / "adapter_config.json").exists(): model = PeftModel.from_pretrained(model, probe_config.probe_path)
# Load existing probe (layer_idx will be inferred from previously saved config) probe = ValueHeadProbe( model, path=probe_config.probe_path, attention_probe_n_heads=probe_config.attention_probe_n_heads, probe_dtype=probe_config.probe_dtype, normalize_before_head=probe_config.normalize_before_head, )
else: # Initialize the probe from scratch if probe_config.lora_layers: print(f"Initializing new LoRA adapters for layers {probe_config.lora_layers}") model = setup_lora_for_layers( model, probe_config.lora_layers, lora_r=probe_config.lora_r, lora_alpha=probe_config.lora_alpha, lora_dropout=probe_config.lora_dropout, ) # Initialize new probe with specified layer
probe = ValueHeadProbe( model, layer_idx=probe_config.layer, context_window_size=probe_config.context_window_size, attention_probe_n_heads=probe_config.attention_probe_n_heads, probe_dtype=probe_config.probe_dtype, normalize_before_head=probe_config.normalize_before_head, probe_head_type=probe_config.probe_head_type, seed=seed, ) return model, probe123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250"""Loss functions for probe training."""
from typing import List, Optional, Tuple, Union
import torchimport torch.nn.functional as Ffrom jaxtyping import Float, Intfrom torch import Tensorfrom peft import PeftModelfrom transformers import AutoModelForCausalLM
def compute_probe_bce_loss( probe_logits: Float[Tensor, 'batch_size seq_len'], classification_labels: Float[Tensor, 'batch_size seq_len'], classification_weights: Float[Tensor, 'batch_size seq_len'], max_clipped_logits: float = 100.0, ignore_label: float = -100.0,): # Clip logits to prevent extreme values probe_logits_clipped = torch.clamp( probe_logits, min=-max_clipped_logits, max=max_clipped_logits ) try: bce_loss = F.binary_cross_entropy_with_logits( probe_logits_clipped, classification_labels, weight=classification_weights, reduction='none' ) bce_loss = bce_loss[(classification_labels != ignore_label)].mean() # Check for NaN in bce_loss if torch.isnan(bce_loss): print(f"WARNING: NaN detected in bce_loss") bce_loss = torch.tensor(0.0, device=probe_logits.device) return bce_loss except Exception as e: print(f"Error in compute_probe_bce_loss: {e}") return torch.tensor(0.0, device=probe_logits.device)
def compute_probe_max_aggregation_loss( probe_logits: Float[Tensor, 'batch_size seq_len'], classification_labels: Float[Tensor, 'batch_size seq_len'], classification_weights: Float[Tensor, 'batch_size seq_len'], positive_spans: List[List[Tuple[int, int]]], negative_spans: List[List[Tuple[int, int]]], max_clipped_logits: float = 100.0, sparsity_penalty_weight: Optional[float] = None,): """ Computes the span-level max-aggregation loss. For positive spans, loss is BCE(max(logits_in_span), 1.0). For negative spans, loss is BCE(max(logits_in_span), 0.0). The final loss is the mean over all spans in the batch. """
span_losses = [] device = probe_logits.device dtype = probe_logits.dtype
# Clip logits to prevent extreme values probe_logits_clipped = torch.clamp( probe_logits, min=-max_clipped_logits, max=max_clipped_logits )
for i in range(probe_logits_clipped.shape[0]): # Iterate over batch items # Positive spans for start, end in positive_spans[i]: should_ignore = (classification_labels[i, start:end+1] == -100.0).any()
if should_ignore: continue
span_logits = probe_logits_clipped[i, start:end+1]
max_logit = torch.max(span_logits) target = torch.tensor(1.0, device=device, dtype=dtype) loss = F.binary_cross_entropy_with_logits(max_logit, target, reduction='none') span_losses.append(loss)
# Negative spans for start, end in negative_spans[i]: should_ignore = (classification_labels[i, start:end+1] == -100.0).any()
if should_ignore: continue
span_logits = probe_logits_clipped[i, start:end+1]
max_logit = torch.max(span_logits) target = torch.tensor(0.0, device=device, dtype=dtype) loss = F.binary_cross_entropy_with_logits(max_logit, target, reduction='none') span_losses.append(loss)
if not span_losses: # No valid spans found in the batch, return zero loss return torch.tensor(0.0, device=device, dtype=dtype)
# Compute the mean loss over all spans in the batch final_loss = torch.mean(torch.stack(span_losses))
if sparsity_penalty_weight is not None: sparsity_loss = compute_sparsity_loss( probe_logits=probe_logits, classification_labels=classification_labels, )
final_loss = final_loss + sparsity_penalty_weight * sparsity_loss
# Check for NaN if torch.isnan(final_loss): print(f"WARNING: NaN detected in compute_probe_max_aggregation_loss. Returning 0.0") final_loss = torch.tensor(0.0, device=device, dtype=dtype)
return final_loss
def compute_sparsity_loss( probe_logits: Float[Tensor, "batch seq_len 1"], attention_mask: Int[Tensor, "batch seq_len"],) -> Float[Tensor, ""]: """ Compute sparsity loss to encourage probe to be selective. This loss encourages the probe to have low average activation, preventing it from flagging everything as a hallucination. Args: probe_logits: Probe output logits attention_mask: Mask for valid tokens Returns: Scalar sparsity loss """ # Get probabilities probe_probs = torch.sigmoid(probe_logits.squeeze(-1)) # [batch, seq_len] # Apply attention mask masked_probs = probe_probs * attention_mask # Compute average activation num_valid_tokens = attention_mask.sum() if num_valid_tokens == 0: return torch.tensor(0.0, device=probe_logits.device) avg_activation = masked_probs.sum() / num_valid_tokens # Sparsity loss is just the average activation return avg_activation
def mask_high_loss_spans( lm_model: Union[AutoModelForCausalLM, PeftModel], input_ids: Float[Tensor, 'batch_size seq_len'], attention_mask: Float[Tensor, 'batch_size seq_len'], classification_labels: Float[Tensor, 'batch_size seq_len'], spans: List[List[Tuple[int, int]]], threshold: float = 1.0, # threshold for the loss to be considered high): """ Computes the span-level max-aggregation loss. For positive spans, loss is BCE(max(logits_in_span), 1.0). For negative spans, loss is BCE(max(logits_in_span), 0.0). The final loss is the mean over all spans in the batch. """
if isinstance(lm_model, PeftModel): with lm_model.disable_adapter(): lm_logits: Float[Tensor, 'batch_size seq_len vocab_size'] = lm_model( input_ids=input_ids, attention_mask=attention_mask, output_hidden_states=False, ).logits else: lm_logits: Float[Tensor, 'batch_size seq_len vocab_size'] = lm_model( input_ids=input_ids, attention_mask=attention_mask, output_hidden_states=False, ).logits
log_probs = torch.nn.functional.log_softmax(lm_logits, dim=-1) log_probs: Float[Tensor, 'batch_size seq_len'] = log_probs.gather(-1, input_ids[:, 1:].unsqueeze(-1)).squeeze(-1)
for i in range(log_probs.shape[0]): # Iterate over batch items # Do it only for the supported entity spans for start, end in spans[i]: if start > end: # Invalid span, skip continue
span_neg_log_probs = -log_probs[i, start:end+1] max_neg_log_prob = span_neg_log_probs.max()
if max_neg_log_prob > threshold: classification_labels[i, start:end+1] = -100.0
return classification_labels
def compute_kl_divergence_loss( model: 'ValueHeadProbe', lm_logits: Float[Tensor, "batch seq_len vocab_size"], input_ids: Int[Tensor, "batch seq_len"], attention_mask: Int[Tensor, "batch seq_len"], lm_labels: Int[Tensor, "batch seq_len"],) -> Float[Tensor, ""]: """ Compute KL divergence between model with LoRA and base model. Args: model: The ValueHeadProbe model lm_logits: Logits from model with LoRA adapters input_ids: Input token IDs attention_mask: Attention mask lm_labels: Language modeling labels Returns: Scalar KL divergence loss """ # Check if model has LoRA adapters if not isinstance(model.model, PeftModel) or not model.model.active_adapters: return torch.tensor(0.0, device=lm_logits.device) # Get base model outputs without LoRA with model.model.disable_adapter(): base_outputs = model( input_ids=input_ids, attention_mask=attention_mask, ) base_logits = base_outputs["lm_logits"].detach() # Compute KL divergence with torch.autocast(device_type=lm_logits.device.type, enabled=False): log_q = torch.log_softmax(lm_logits.float(), -1) # model with LoRA p_ref = torch.softmax(base_logits.float(), -1) # reference model kl = F.kl_div(log_q, p_ref, reduction='none', log_target=False).sum(-1) # Only compute loss on valid tokens active_mask = (lm_labels != -100) if not active_mask.any(): return torch.tensor(0.0, device=lm_logits.device) kl_loss = kl[active_mask].mean() return kl_loss123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315"""Custom trainer for hallucination detection probes."""
import gcimport mathfrom pathlib import Pathfrom typing import List, Optional, Tuple
import torchimport torch.nn as nnfrom torch.optim import AdamWfrom transformers import Trainer, AutoTokenizerfrom jaxtyping import Float, Intfrom torch import Tensorfrom peft import PeftModel
from feature_probes.utils.file_utils import save_jsonlfrom feature_probes.utils.metrics import print_eval_metrics
from feature_probes.data.dataset import TokenizedProbingDatasetfrom feature_probes.config import TrainingConfigfrom feature_probes.training.loss import compute_probe_bce_loss, compute_kl_divergence_loss, compute_probe_max_aggregation_loss, mask_high_loss_spansfrom feature_probes.probes.value_head_probe import ValueHeadProbefrom feature_probes.evaluation.evaluate import evaluate_probe
class ProbeTrainer(Trainer): """ A custom Trainer that merges standard LM next-token-prediction loss (CE) with a classification BCE from a 'probe' that hooks an internal layer. """ def __init__( self, probe: ValueHeadProbe, eval_datasets: List[TokenizedProbingDataset], cfg: TrainingConfig, eval_steps: Optional[int] = None, tokenizer: AutoTokenizer = None, **kwargs ): super().__init__(model=probe, **kwargs) self.lambda_lm: float = cfg.lambda_lm self.lambda_kl: float = cfg.lambda_kl self.anneal_max_aggr: bool = cfg.anneal_max_aggr self.anneal_warmup: float = cfg.anneal_warmup self.eval_datasets: List[TokenizedProbingDataset] = eval_datasets self.threshold = cfg.probe_config.threshold self.ignore_label: float = -100.0 self.gradient_accumulation_steps: int = cfg.gradient_accumulation_steps self.eval_steps: Optional[int] = eval_steps self.probe_dir: Path = cfg.probe_config.probe_path self.tokenizer: AutoTokenizer = tokenizer self.high_loss_threshold: Optional[float] = cfg.high_loss_threshold self.sparsity_penalty_weight: float = cfg.sparsity_penalty_weight self._last_eval_metrics: Optional[dict] = None
def get_training_progress(self) -> float: """Get the current training progress as a float between 0 and 1.""" if self.state.max_steps is None or self.state.max_steps == 0: return 1.0 return min(1.0, self.state.global_step / self.state.max_steps) def compute_loss( self, model: ValueHeadProbe, batch: dict, return_outputs=False, num_items_in_batch=None ):
# Get the device from the underlying model if using DataParallel device = model.module.device if isinstance(model, nn.DataParallel) else model.device
input_ids: torch.Tensor = batch["input_ids"].to(device) attention_mask: torch.Tensor = batch["attention_mask"].to(device) classification_labels: torch.Tensor = batch["classification_labels"].to(device) classification_weights: torch.Tensor = batch["classification_weights"].to(device) lm_labels: torch.Tensor = batch["lm_labels"].to(device) pos_spans: List[List[Tuple[int, int]]] = batch["pos_spans"] neg_spans: List[List[Tuple[int, int]]] = batch["neg_spans"]
# The underlying HF LM expects "labels" for next-token-prediction outputs = model( input_ids=input_ids, attention_mask=attention_mask, labels=lm_labels, # these are LM labels (not probe labels!) )
lm_logits = outputs["lm_logits"] probe_logits = outputs["probe_logits"].squeeze(-1) # shape [B, T] lm_loss = outputs["lm_loss"] # standard next-token CE loss
if torch.isnan(lm_loss): print(f"WARNING: NaN detected in lm_loss") lm_loss = torch.tensor(0.0, device=device)
# Compute KL divergence if needed kl_loss = torch.tensor(0., device=device) if self.lambda_kl > 0: kl_loss = compute_kl_divergence_loss( model=model, lm_logits=lm_logits, input_ids=input_ids, attention_mask=attention_mask, lm_labels=lm_labels, )
# Mask high-loss spans if configured if self.high_loss_threshold is not None: classification_labels = mask_high_loss_spans( lm_model=model.model, input_ids=input_ids, attention_mask=attention_mask, classification_labels=classification_labels, spans=neg_spans, threshold=self.high_loss_threshold, )
# Compute probe loss probe_loss = compute_probe_bce_loss( probe_logits=probe_logits, classification_labels=classification_labels, classification_weights=classification_weights, )
# Span-level max aggregation loss (if enabled) if self.anneal_max_aggr: max_aggr_probe_loss = compute_probe_max_aggregation_loss( probe_logits=probe_logits, classification_labels=classification_labels, classification_weights=classification_weights, positive_spans=pos_spans, negative_spans=neg_spans, ) omega = min(1.0, self.get_training_progress() / self.anneal_warmup) probe_loss = (1 - omega) * probe_loss + omega * max_aggr_probe_loss else: omega = 0.0 max_aggr_probe_loss = torch.tensor(0.0, device=device)
# Combine losses loss = ( self.lambda_lm * lm_loss + self.lambda_kl * kl_loss + (1 - self.lambda_lm - self.lambda_kl) * probe_loss )
log_dict = { 'loss': float(probe_loss.detach().float().item()), 'lm_loss': float(lm_loss.detach().float().item()), 'kl_loss': float(kl_loss.detach().float().item()), 'lambda_lm': self.lambda_lm, 'lambda_kl': self.lambda_kl, 'omega': float(omega), 'active_positions': int(torch.sum((classification_labels != self.ignore_label)).item()), }
if self.anneal_max_aggr: log_dict['max_aggr_probe_loss'] = float(max_aggr_probe_loss.detach().float().item())
self.log(log_dict)
if return_outputs: outputs["loss"] = loss outputs["probe_loss"] = probe_loss outputs["lm_loss"] = lm_loss return (loss, outputs) # Clean up if not returning outputs del outputs, lm_logits, probe_logits gc.collect() torch.cuda.empty_cache()
return loss def create_optimizer(self): """ Create optimizer with separate learning rates for probe head and LoRA adapters. """ # Get the device from the underlying model if using DataParallel model = self.model.module if isinstance(self.model, nn.DataParallel) else self.model # Separate parameters into probe head and LoRA groups probe_head_params = [] lora_params = [] other_params = [] probe_head_added = False for name, param in model.named_parameters(): if not param.requires_grad: continue if 'value_head' in name: probe_head_params.append(param) probe_head_added = True elif 'lora' in name.lower(): lora_params.append(param) else: other_params.append(param)
assert probe_head_added == True, f"Probe head not found when computing list of trainable parameters" # Create parameter groups with different learning rates param_groups = [] if probe_head_params: param_groups.append({ 'params': probe_head_params, 'lr': self.args.probe_head_lr, 'name': 'probe_head' }) if lora_params: param_groups.append({ 'params': lora_params, 'lr': self.args.lora_lr, 'name': 'lora' }) if other_params: # Fall back to default learning rate for any other parameters param_groups.append({ 'params': other_params, 'lr': self.args.learning_rate, 'name': 'other' }) # Print parameter group info print("\n=== Optimizer Parameter Groups ===") for i, group in enumerate(param_groups): param_count = sum(p.numel() for p in group['params']) print(f"Group {i} ({group['name']}): {param_count:,} parameters, lr={group['lr']}")
print(f"lora_lr: {self.args.lora_lr} (type={type(self.args.lora_lr)})") print(f"probe_head_lr: {self.args.probe_head_lr} (type={type(self.args.probe_head_lr)})") optimizer = AdamW( param_groups, eps=self.args.adam_epsilon if hasattr(self.args, 'adam_epsilon') else 1e-8 )
return optimizer def create_optimizer_and_scheduler(self, num_training_steps: int): """ Override to ensure our custom optimizer is created before the scheduler. """ # Create our custom optimizer first self.optimizer = self.create_optimizer() # Then create the scheduler using the parent method self.create_scheduler( num_training_steps=num_training_steps, optimizer=self.optimizer )
def evaluate( self, eval_dataset=None, ignore_keys=None, metric_key_prefix: str = "eval", save_roc_curves: bool = False, dump_raw_eval_results: bool = False, verbose: bool = False, ): all_eval_metrics = {}
# Check if this is a final evaluation is_final_evaluation = self.get_training_progress() >= 1.0 # If this is a final evaluation and we've already done it, skip if is_final_evaluation and self._last_eval_metrics is not None: if verbose: print("Final evaluation already completed, skipping duplicate evaluation.") return self._last_eval_metrics
# Evaluate on each dataset for dataset in self.eval_datasets: eval_dataloader = self.get_eval_dataloader(dataset)
model = self._wrap_model( self.model, training=False, dataloader=eval_dataloader ).eval()
metrics = evaluate_probe( model, eval_dataloader, threshold=self.threshold, metric_key_prefix=dataset.config.dataset_id, verbose=False, save_roc_curves=save_roc_curves, save_dir=self.probe_dir if save_roc_curves else None, dump_raw_results=dump_raw_eval_results, )
if verbose: print_eval_metrics(metrics, metric_key_prefix=dataset.config.dataset_id) self.log(metrics) all_eval_metrics.update(metrics)
# Save metrics to JSONL file metrics['global_step'] = self.state.global_step metrics['training_progress'] = self.get_training_progress() metrics['dataset_id'] = dataset.config.dataset_id save_jsonl([metrics], self.probe_dir / "eval_metrics.jsonl", append=True)
# Store the metrics for later retrieval self._last_eval_metrics = all_eval_metrics return all_eval_metrics12345678910111213141516171819202122"""Data types for probe training."""
from dataclasses import dataclassfrom typing import List
@dataclassclass AnnotatedSpan: """A text span with its hallucination label.""" span: str # The span text label: float # 1.0 for hallucination, 0.0 for supported, -100.0 for ignored index: int # Start index in the completion
@dataclassclass ProbingItem: """A single item containing prompt, completion and annotated spans.""" prompt: str completion: str spans: List[AnnotatedSpan]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499from __future__ import annotations
from dataclasses import dataclassfrom typing import Dict, List, Any
import numpy as npimport pandas as pdimport torchfrom sklearn.cluster import KMeansfrom sklearn.decomposition import PCAfrom sklearn.linear_model import LogisticRegressionfrom sklearn.metrics import ( accuracy_score, adjusted_rand_score, normalized_mutual_info_score, roc_auc_score, silhouette_score,)from sklearn.model_selection import train_test_splitfrom tqdm.auto import tqdm
from feature_probes.data.dataset import TokenizedProbingDatasetConfig, create_probing_datasetfrom feature_probes.utils.model_utils import load_model_and_tokenizer
@dataclassclass DatasetSpec: hf_repo: str split: str max_length: int max_samples: int seed: int
@dataclassclass CollectionSpec: layers: List[int] max_tokens_per_label: int pos_neg_ratio: float = 1.0 enforce_ratio_on_finalize: bool = True finalize_sample_total: int | None = None
def _sample_with_ratio( pos: np.ndarray, neg: np.ndarray, *, pos_neg_ratio: float, seed: int, sample_total: int | None = None,) -> tuple[np.ndarray, np.ndarray]: if pos_neg_ratio <= 0: raise ValueError("pos_neg_ratio must be > 0")
if len(pos) == 0 or len(neg) == 0: hidden_dim = pos.shape[1] if len(pos) else (neg.shape[1] if len(neg) else 0) empty = np.empty((0, hidden_dim), dtype=pos.dtype if len(pos) else neg.dtype if len(neg) else np.float32) return empty, empty
max_pos = len(pos) max_neg = len(neg)
if sample_total is not None: if sample_total < 2: raise ValueError("sample_total must be >= 2 when provided") n_pos_target = max(1, int(round(sample_total * pos_neg_ratio / (1.0 + pos_neg_ratio)))) n_neg_target = max(1, sample_total - n_pos_target) else: n_neg_target = min(max_neg, int(max_pos / pos_neg_ratio)) n_pos_target = max(1, int(round(n_neg_target * pos_neg_ratio)))
n_pos = min(max_pos, n_pos_target) n_neg = min(max_neg, n_neg_target)
# Re-project once so that returned counts follow the requested ratio as closely as possible. n_neg = min(n_neg, max(1, int(n_pos / pos_neg_ratio))) n_pos = min(n_pos, max(1, int(round(n_neg * pos_neg_ratio))))
rng = np.random.default_rng(seed) pos_idx = rng.choice(max_pos, size=n_pos, replace=False) neg_idx = rng.choice(max_neg, size=n_neg, replace=False) return pos[pos_idx], neg[neg_idx]
def build_tokenized_dataset(tokenizer, subset: str, spec: DatasetSpec): cfg = TokenizedProbingDatasetConfig( dataset_id=f"activation_{subset}", hf_repo=spec.hf_repo, subset=subset, split=spec.split, max_length=spec.max_length, default_ignore=False, ignore_buffer=0, last_span_token=False, pos_weight=1.0, neg_weight=1.0, shuffle=True, seed=spec.seed, process_on_the_fly=False, max_num_samples=spec.max_samples, ) return create_probing_dataset(cfg, tokenizer)
def collect_multilayer_activations_for_model( *, model_key: str, model_name: str, subset: str, dataset_spec: DatasetSpec, collection_spec: CollectionSpec,) -> Dict[str, Any]: print(f"\nLoading model/tokenizer: {model_key} ({model_name})") model, tokenizer = load_model_and_tokenizer(model_name) model.eval()
dataset = build_tokenized_dataset(tokenizer, subset=subset, spec=dataset_spec) print(f"Dataset size ({subset}): {len(dataset)}")
layer_indices = sorted(collection_spec.layers) max_tokens_per_label = collection_spec.max_tokens_per_label
collected = { layer: {"positive": [], "negative": []} for layer in layer_indices }
progress = tqdm(range(len(dataset)), desc=f"Collecting {model_key}") for idx in progress: item = dataset[idx] if item is None: continue
input_ids = item["input_ids"].unsqueeze(0).to(model.device) attention_mask = item["attention_mask"].unsqueeze(0).to(model.device) labels = item["classification_labels"].cpu().numpy() valid = item["attention_mask"].cpu().numpy().astype(bool)
pos_idx = np.where((labels == 1.0) & valid)[0] neg_idx = np.where((labels == 0.0) & valid)[0]
with torch.no_grad(): outputs = model( input_ids=input_ids, attention_mask=attention_mask, use_cache=False, output_hidden_states=True, )
hidden_states = outputs.hidden_states for layer in layer_indices: hidden = hidden_states[layer + 1][0].float().cpu().numpy()
if len(pos_idx) > 0: need = max_tokens_per_label - len(collected[layer]["positive"]) if need > 0: take = pos_idx[:need] collected[layer]["positive"].extend(hidden[take])
if len(neg_idx) > 0: need = max_tokens_per_label - len(collected[layer]["negative"]) if need > 0: take = neg_idx[:need] collected[layer]["negative"].extend(hidden[take])
enough = all( len(collected[layer]["positive"]) >= max_tokens_per_label and len(collected[layer]["negative"]) >= max_tokens_per_label for layer in layer_indices ) if enough: break
del outputs
del model if torch.cuda.is_available(): torch.cuda.empty_cache()
per_layer = {} for layer in layer_indices: pos = np.array(collected[layer]["positive"]) neg = np.array(collected[layer]["negative"])
if collection_spec.enforce_ratio_on_finalize: pos, neg = _sample_with_ratio( pos, neg, pos_neg_ratio=collection_spec.pos_neg_ratio, seed=dataset_spec.seed + layer, sample_total=collection_spec.finalize_sample_total, )
per_layer[layer] = {"positive": pos, "negative": neg} print(f"{model_key} layer {layer}: {len(pos)} hallucinated / {len(neg)} supported")
return { "model_key": model_key, "model_name": model_name, "subset": subset, "per_layer": per_layer, }
def equalize_sweep_results_for_fair_comparison( sweep_results: Dict[str, Any], layers: List[int], *, pos_neg_ratio: float = 1.0, sample_total_per_layer: int | None = None, seed: int = 42,) -> Dict[str, Any]: model_keys = list(sweep_results.keys()) out: Dict[str, Any] = {}
# Initialize shallow metadata copy. for model_key in model_keys: src = sweep_results[model_key] out[model_key] = { "model_key": src["model_key"], "model_name": src["model_name"], "subset": src["subset"], "per_layer": {}, }
for layer in layers: feasible_counts: list[tuple[int, int]] = [] for model_key in model_keys: pos = sweep_results[model_key]["per_layer"][layer]["positive"] neg = sweep_results[model_key]["per_layer"][layer]["negative"]
# Build a temporary feasible sample for this model/layer, then intersect across models. pos_s, neg_s = _sample_with_ratio( pos, neg, pos_neg_ratio=pos_neg_ratio, seed=seed + layer, sample_total=sample_total_per_layer, ) feasible_counts.append((len(pos_s), len(neg_s)))
shared_n_pos = min(c[0] for c in feasible_counts) shared_n_neg = min(c[1] for c in feasible_counts)
for i, model_key in enumerate(model_keys): pos = sweep_results[model_key]["per_layer"][layer]["positive"] neg = sweep_results[model_key]["per_layer"][layer]["negative"]
if shared_n_pos == 0 or shared_n_neg == 0: hidden_dim = pos.shape[1] if len(pos) else (neg.shape[1] if len(neg) else 0) pos_eq = np.empty((0, hidden_dim), dtype=pos.dtype if len(pos) else np.float32) neg_eq = np.empty((0, hidden_dim), dtype=neg.dtype if len(neg) else np.float32) else: rng = np.random.default_rng(seed + layer * 100 + i) pos_idx = rng.choice(len(pos), size=shared_n_pos, replace=False) neg_idx = rng.choice(len(neg), size=shared_n_neg, replace=False) pos_eq = pos[pos_idx] neg_eq = neg[neg_idx]
out[model_key]["per_layer"][layer] = { "positive": pos_eq, "negative": neg_eq, }
return out
def _fisher_ratio(pos: np.ndarray, neg: np.ndarray) -> float: mu_diff = pos.mean(axis=0) - neg.mean(axis=0) between = float(np.sum(mu_diff ** 2)) within = float(np.mean(pos.var(axis=0) + neg.var(axis=0))) + 1e-8 return between / within
def _centroid_cosine_distance(pos: np.ndarray, neg: np.ndarray) -> float: a = pos.mean(axis=0) b = neg.mean(axis=0) denom = (np.linalg.norm(a) * np.linalg.norm(b)) + 1e-8 return float(1.0 - np.dot(a, b) / denom)
def compute_separation_metrics( pos: np.ndarray, neg: np.ndarray, *, seed: int = 42, pca_dims: int = 20, pos_neg_ratio: float = 1.0, sample_total: int | None = None,) -> Dict[str, float]: if pos_neg_ratio <= 0: raise ValueError("pos_neg_ratio must be > 0")
if len(pos) == 0 or len(neg) == 0: return { "n_pos": 0.0, "n_neg": 0.0, "pos_neg_ratio_used": float(pos_neg_ratio), "silhouette_pca10": np.nan, "centroid_l2_hidden": np.nan, "centroid_cosine_dist_hidden": np.nan, "fisher_ratio_hidden": np.nan, "linear_probe_auc_pca20": np.nan, "linear_probe_acc_pca20": np.nan, "kmeans_ari_pca20": np.nan, "kmeans_nmi_pca20": np.nan, }
max_pos = len(pos) max_neg = len(neg)
if sample_total is not None: if sample_total < 30: raise ValueError("sample_total must be >= 30 when provided") n_pos_target = max(1, int(round(sample_total * pos_neg_ratio / (1.0 + pos_neg_ratio)))) n_neg_target = max(1, sample_total - n_pos_target) else: n_neg_target = min(max_neg, int(max_pos / pos_neg_ratio)) n_pos_target = int(round(n_neg_target * pos_neg_ratio))
n_pos = min(max_pos, n_pos_target) n_neg = min(max_neg, n_neg_target)
if n_pos < 15 or n_neg < 15: return { "n_pos": float(n_pos), "n_neg": float(n_neg), "pos_neg_ratio_used": float(pos_neg_ratio), "silhouette_pca10": np.nan, "centroid_l2_hidden": np.nan, "centroid_cosine_dist_hidden": np.nan, "fisher_ratio_hidden": np.nan, "linear_probe_auc_pca20": np.nan, "linear_probe_acc_pca20": np.nan, "kmeans_ari_pca20": np.nan, "kmeans_nmi_pca20": np.nan, }
rng = np.random.default_rng(seed) pos_idx = rng.choice(max_pos, size=n_pos, replace=False) neg_idx = rng.choice(max_neg, size=n_neg, replace=False)
pos_b = pos[pos_idx] neg_b = neg[neg_idx] X = np.concatenate([pos_b, neg_b], axis=0) y = np.concatenate([np.ones(n_pos, dtype=int), np.zeros(n_neg, dtype=int)])
pca_k = min(pca_dims, X.shape[1], X.shape[0] - 1) X_pca = PCA(n_components=pca_k, random_state=seed).fit_transform(X)
pca_10 = min(10, X_pca.shape[1]) sil = silhouette_score(X_pca[:, :pca_10], y)
c_l2 = float(np.linalg.norm(pos_b.mean(axis=0) - neg_b.mean(axis=0))) c_cos = _centroid_cosine_distance(pos_b, neg_b) fisher = _fisher_ratio(pos_b, neg_b)
X_train, X_test, y_train, y_test = train_test_split( X_pca, y, test_size=0.30, stratify=y, random_state=seed, ) clf = LogisticRegression(max_iter=2000, random_state=seed) clf.fit(X_train, y_train) y_prob = clf.predict_proba(X_test)[:, 1] y_pred = (y_prob >= 0.5).astype(int)
auc = roc_auc_score(y_test, y_prob) acc = accuracy_score(y_test, y_pred)
kmeans = KMeans(n_clusters=2, n_init=20, random_state=seed) pred = kmeans.fit_predict(X_pca) ari = adjusted_rand_score(y, pred) nmi = normalized_mutual_info_score(y, pred)
return { "n_pos": float(n_pos), "n_neg": float(n_neg), "pos_neg_ratio_used": float(n_pos / max(n_neg, 1)), "silhouette_pca10": float(sil), "centroid_l2_hidden": c_l2, "centroid_cosine_dist_hidden": c_cos, "fisher_ratio_hidden": float(fisher), "linear_probe_auc_pca20": float(auc), "linear_probe_acc_pca20": float(acc), "kmeans_ari_pca20": float(ari), "kmeans_nmi_pca20": float(nmi), }
def summarize_collection_counts(sweep_results: Dict[str, Any], layers: List[int]) -> pd.DataFrame: rows = [] for model_key, model_res in sweep_results.items(): for layer in layers: pos = model_res["per_layer"][layer]["positive"] neg = model_res["per_layer"][layer]["negative"] hidden_dim = pos.shape[1] if len(pos) else (neg.shape[1] if len(neg) else 0) rows.append( { "model": model_key, "layer": layer, "hallucinated_tokens": len(pos), "supported_tokens": len(neg), "hidden_dim": hidden_dim, } ) return pd.DataFrame(rows)
def build_metrics_table(sweep_results: Dict[str, Any], layers: List[int], seed: int = 42) -> pd.DataFrame: rows = [] for model_key, model_res in sweep_results.items(): for layer in layers: pos = model_res["per_layer"][layer]["positive"] neg = model_res["per_layer"][layer]["negative"] metrics = compute_separation_metrics(pos, neg, seed=seed) rows.append({"model": model_key, "layer": layer, **metrics}) return pd.DataFrame(rows).sort_values(["model", "layer"]).reset_index(drop=True)
def build_metrics_table_for_ratio( sweep_results: Dict[str, Any], layers: List[int], *, pos_neg_ratio: float, sample_total: int | None = None, seed: int = 42,) -> pd.DataFrame: rows = [] for model_key, model_res in sweep_results.items(): for layer in layers: pos = model_res["per_layer"][layer]["positive"] neg = model_res["per_layer"][layer]["negative"] metrics = compute_separation_metrics( pos, neg, seed=seed, pos_neg_ratio=pos_neg_ratio, sample_total=sample_total, ) rows.append({ "model": model_key, "layer": layer, "requested_pos_neg_ratio": pos_neg_ratio, **metrics, }) return pd.DataFrame(rows).sort_values(["model", "layer"]).reset_index(drop=True)
def build_pca_plot_frame( sweep_results: Dict[str, Any], layers: List[int], *, max_points_per_label: int = 600, seed: int = 42,) -> pd.DataFrame: rows = [] rng = np.random.default_rng(seed)
for model_key, model_res in sweep_results.items(): for layer in layers: pos = model_res["per_layer"][layer]["positive"] neg = model_res["per_layer"][layer]["negative"]
if len(pos) == 0 or len(neg) == 0: continue
n_pos = min(len(pos), max_points_per_label) n_neg = min(len(neg), max_points_per_label) pos_idx = rng.choice(len(pos), size=n_pos, replace=False) neg_idx = rng.choice(len(neg), size=n_neg, replace=False)
pos_s = pos[pos_idx] neg_s = neg[neg_idx] X = np.concatenate([pos_s, neg_s], axis=0) y = np.concatenate([np.ones(n_pos, dtype=int), np.zeros(n_neg, dtype=int)])
pca = PCA(n_components=2, random_state=seed) X2 = pca.fit_transform(X)
part = pd.DataFrame( { "pc1": X2[:, 0], "pc2": X2[:, 1], "label": np.where(y == 1, "Hallucinated", "Supported"), "model": model_key, "layer": layer, "pc1_var": pca.explained_variance_ratio_[0], "pc2_var": pca.explained_variance_ratio_[1], } ) rows.append(part)
if not rows: return pd.DataFrame(columns=["pc1", "pc2", "label", "model", "layer", "pc1_var", "pc2_var"])
return pd.concat(rows, ignore_index=True)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176"""File I/O utilities."""
import jsonimport yamlimport numpy as npimport torchfrom pathlib import Pathfrom typing import Any, Callable, Dict, List, Optional, Unionimport os
def default_serializer(obj: Any) -> Any: """ Convert non-serializable objects to JSON-serializable types. Handles common ML types like numpy arrays, torch tensors, dtypes, etc. Args: obj: Object to convert Returns: JSON-serializable version of the object """ if isinstance(obj, torch.dtype): return str(obj) elif isinstance(obj, (np.ndarray, torch.Tensor)): return obj.cpu().tolist() elif isinstance(obj, (np.integer, np.floating)): return float(obj) elif isinstance(obj, Path): return str(obj) elif hasattr(obj, "__dataclass_fields__"): return {k: default_serializer(v) for k, v in obj.__dict__.items()} elif hasattr(obj, '__dict__'): return obj.__dict__ else: return obj
def dataclass_to_dict(obj) -> dict: """ Converts a dataclass to a dictionary. Will recurse through lists, dicts, and nested dataclasses. """
if hasattr(obj, "__dataclass_fields__"): return {k: dataclass_to_dict(v) for k, v in obj.__dict__.items()} elif isinstance(obj, list): return [dataclass_to_dict(v) for v in obj] elif isinstance(obj, dict): return {k: dataclass_to_dict(v) for k, v in obj.items()} else: return obj
def pydantic_to_dict(obj) -> dict: """ Converts a Pydantic model to a dictionary using model_dump(). """ if hasattr(obj, 'model_dump'): return obj.model_dump() elif isinstance(obj, list): return [pydantic_to_dict(v) for v in obj] elif isinstance(obj, dict): return {k: pydantic_to_dict(v) for k, v in obj.items()} else: return obj
def make_directory_wrapped(filepath: str, **kwargs) -> None: if isinstance(filepath, Path): parent_dir = filepath.parent else: parent_dir = "/".join(filepath.split("/")[:-1]) os.makedirs(parent_dir, exist_ok=True, **kwargs)
def save_jsonl( dict_list: List[Dict[Any, Any]], filepath: str, append: bool = False, serialize_dataclasses: bool = False, serialize_pydantic: bool = False,) -> None: """Write a list of dictionaries to a jsonlines file.""" make_directory_wrapped(filepath)
if isinstance(dict_list, dict): dict_list = [dict_list]
if append and (not os.path.exists(filepath)): print(f"File {filepath} does not exist, setting append to False") append = False
mode = "a" if append else "w" with open(filepath, mode=mode) as file: for item in dict_list: if serialize_dataclasses: item = dataclass_to_dict(item) elif serialize_pydantic: item = pydantic_to_dict(item) file.write(json.dumps(item) + "\n")
def load_jsonl(path: Union[str, Path]) -> List[Dict[str, Any]]: """ Load data from a JSONL file. Args: path: Path to the JSONL file Returns: List of dictionaries """ path = Path(path) data = [] with open(path, 'r', encoding='utf-8') as f: for line in f: line = line.strip() if line: data.append(json.loads(line)) return data
def save_json( data: Any, path: Union[str, Path], indent: int = 2, serializer: Callable = default_serializer) -> None: """ Save data to a JSON file. Args: data: Data to save path: Path to save the file indent: Indentation level for pretty printing serializer: Serializer function for special types """ path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) with open(path, 'w', encoding='utf-8') as f: if serializer: json.dump(data, f, ensure_ascii=False, indent=indent, default=serializer) else: json.dump(data, f, ensure_ascii=False, indent=indent)
def load_json(path: Union[str, Path]) -> Any: """ Load data from a JSON file. Args: path: Path to the JSON file Returns: Loaded data """ path = Path(path) with open(path, 'r', encoding='utf-8') as f: return json.load(f)
def load_yaml(path: Union[str, Path]) -> Dict[str, Any]: """ Load data from a YAML file. Args: path: Path to the YAML file Returns: Dictionary with loaded data """ path = Path(path) with open(path, 'r', encoding='utf-8') as f: return yaml.safe_load(f)12345678910111213141516171819202122232425262728293031323334353637383940"""Hook utilities for intercepting model activations."""
import contextlibimport functoolsfrom typing import Callable, List, Tuple
import torch.nn as nn
@contextlib.contextmanagerdef add_hooks( module_forward_pre_hooks: List[Tuple[nn.Module, Callable]], module_forward_hooks: List[Tuple[nn.Module, Callable]], **kwargs): """ Context manager for temporarily adding forward hooks to a model. Args: module_forward_pre_hooks: List of (module, hook_fn) pairs for pre-hooks module_forward_hooks: List of (module, hook_fn) pairs for forward hooks **kwargs: Additional arguments passed to hook functions """ handles = [] try: # Register pre-hooks for module, hook in module_forward_pre_hooks: partial_hook = functools.partial(hook, **kwargs) handles.append(module.register_forward_pre_hook(partial_hook)) # Register forward hooks for module, hook in module_forward_hooks: partial_hook = functools.partial(hook, **kwargs) handles.append(module.register_forward_hook(partial_hook)) yield finally: # Remove all hooks for handle in handles: handle.remove()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323"""Metrics computation utilities for probe evaluation."""
import osfrom typing import Dict, List, Optional, Tuple
import numpy as npimport matplotlib.pyplot as pltfrom sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, roc_auc_score, roc_curve
def compute_clf_metrics( preds: np.ndarray, labels: np.ndarray, probs: np.ndarray) -> Dict[str, float]: """ Compute classification metrics. Args: preds: Binary predictions (0 or 1) labels: Ground truth labels (0 or 1) probs: Probability scores Returns: Dictionary of metrics """ assert all((labels == 0.0) | (labels == 1.0)), "labels must be either 0 or 1" # Basic classification metrics accuracy = accuracy_score(labels, preds) precision = precision_score(labels, preds, zero_division=0) recall = recall_score(labels, preds, zero_division=0) f1 = f1_score(labels, preds, zero_division=0) auc_score = roc_auc_score(labels, probs) if len(np.unique(labels)) == 2 else float('nan') # Find optimal threshold optimal_threshold = float('nan') threshold_optimized_accuracy = float('nan') recall_at_01_fpr = float('nan') if len(np.unique(labels)) == 2: # ROC curve fpr, tpr, thresholds = roc_curve(labels, probs) # Find optimal threshold for accuracy unique_probs = np.unique(probs) if len(unique_probs) > 100: percentiles = np.linspace(0, 100, 100) threshold_candidates = np.percentile(unique_probs, percentiles) else: threshold_candidates = unique_probs best_accuracy = 0.0 optimal_threshold = 0.5 for threshold in threshold_candidates: y_pred = (probs >= threshold).astype(int) acc = accuracy_score(labels, y_pred) if acc > best_accuracy: best_accuracy = acc optimal_threshold = threshold threshold_optimized_accuracy = best_accuracy # Calculate recall at 0.1 FPR target_fpr = 0.1 idx = np.where(fpr <= target_fpr)[0] if len(idx) > 0: recall_at_01_fpr = tpr[idx[-1]] else: recall_at_01_fpr = 0.0 # Count distributions true_positive_count = int(np.sum(labels == 1.0)) true_negative_count = int(np.sum(labels == 0.0)) pred_positive_count = int(np.sum(preds == 1.0)) pred_negative_count = int(np.sum(preds == 0.0)) total_samples = len(labels) return { "accuracy": float(accuracy), "precision": float(precision), "recall": float(recall), "f1": float(f1), "auc": float(auc_score), "optimal_threshold": float(optimal_threshold), "threshold_optimized_accuracy": float(threshold_optimized_accuracy), "recall_at_0.1_fpr": float(recall_at_01_fpr), "true_positive_count": true_positive_count, "true_negative_count": true_negative_count, "pred_positive_count": pred_positive_count, "pred_negative_count": pred_negative_count, "total_samples": total_samples }
def compute_metrics( predictions: np.ndarray, labels: np.ndarray, probabilities: Optional[np.ndarray] = None) -> Dict[str, float]: """ Compute evaluation metrics. Args: predictions: Model predictions labels: Ground truth labels probabilities: Optional probability scores Returns: Dictionary of metrics """ if probabilities is None: probabilities = predictions return compute_clf_metrics(predictions, labels, probabilities)
def compute_span_level_metrics( predictions: List[float], labels: List[float], spans: List[List[int]]) -> Dict[str, float]: """ Compute span-level metrics by aggregating predictions over spans. Args: predictions: Token-level predictions labels: Span-level labels spans: List of [start, end] indices for each span Returns: Dictionary of span-level metrics """ # Aggregate predictions by taking max over each span span_preds = [] for span_indices in spans: if len(span_indices) == 2: start, end = span_indices span_pred = max(predictions[start:end+1]) span_preds.append(span_pred) span_preds = np.array(span_preds) span_labels = np.array(labels[:len(span_preds)]) # Convert to binary predictions binary_preds = (span_preds > 0.5).astype(float) return compute_clf_metrics(binary_preds, span_labels, span_preds)
def plot_roc_curves( all_preds: Dict[str, List[float]], all_labels: Dict[str, List[float]], all_probs: Dict[str, List[float]], save_dir: str, prefix: Optional[str] = None) -> None: """ Plot ROC curves for different aggregation levels. Args: all_preds: Predictions for each aggregation level all_labels: Labels for each aggregation level all_probs: Probabilities for each aggregation level save_dir: Directory to save plots prefix: Optional prefix for filename """ os.makedirs(save_dir, exist_ok=True) plt.figure(figsize=(18, 6)) fpr_targets = [0.05, 0.1, 0.2, 0.5] dot_color = "black" dot_size = 40 for i, agg_level in enumerate(['all', 'span', 'span_max']): plt.subplot(1, 3, i+1) if agg_level not in all_labels or len(all_labels[agg_level]) == 0: plt.title(f"{agg_level.replace('_', ' ').title()}\nInsufficient data") plt.grid(True, which="both", linestyle="--", linewidth=0.5, alpha=0.7) continue labels = np.array(all_labels[agg_level]) probs = np.array(all_probs[agg_level]) if len(np.unique(labels)) < 2: plt.title(f"{agg_level.replace('_', ' ').title()}\nInsufficient label diversity") plt.grid(True, which="both", linestyle="--", linewidth=0.5, alpha=0.7) continue fpr, tpr, _ = roc_curve(labels, probs) roc_auc = roc_auc_score(labels, probs) plt.fill_between(fpr, tpr, color="#f9c97d", alpha=0.5) plt.plot(fpr, tpr, lw=2, color="black", label=f'ROC curve (AUC = {roc_auc:.2f})') plt.plot([0, 1], [0, 1], 'w--', lw=2, alpha=0.7) # Mark TPR at specific FPRs for fpr_target in fpr_targets: idx = np.argmin(np.abs(fpr - fpr_target)) plt.scatter(fpr[idx], tpr[idx], s=dot_size, color=dot_color, zorder=5) plt.text(fpr[idx], tpr[idx]+0.03, f"{tpr[idx]:.4f}", fontsize=10, ha="center", color=dot_color) plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title(f"{agg_level.replace('_', ' ').title()}") plt.legend(loc="lower right") plt.grid(True, which="both", linestyle="--", linewidth=0.5, alpha=0.7) plt.tight_layout() filename = f"{prefix}_roc_curves.png" if prefix else "roc_curves.png" plt.savefig(os.path.join(save_dir, filename), dpi=300, bbox_inches='tight') plt.close() print(f"ROC curves saved to {os.path.join(save_dir, filename)}")
def plot_roc_curve(fpr: np.ndarray, tpr: np.ndarray, save_path: str) -> None: """Plot a single ROC curve.""" plt.figure(figsize=(8, 6)) plt.plot(fpr, tpr, color='darkorange', lw=2) plt.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Receiver Operating Characteristic') plt.grid(True) plt.savefig(save_path, dpi=300, bbox_inches='tight') plt.close()
def plot_threshold_analysis( probabilities: np.ndarray, labels: np.ndarray, save_path: str) -> None: """Plot metrics vs threshold.""" thresholds = np.linspace(0, 1, 100) accuracies = [] precisions = [] recalls = [] for threshold in thresholds: preds = (probabilities >= threshold).astype(int) accuracies.append(accuracy_score(labels, preds)) precisions.append(precision_score(labels, preds, zero_division=0)) recalls.append(recall_score(labels, preds, zero_division=0)) plt.figure(figsize=(10, 6)) plt.plot(thresholds, accuracies, label='Accuracy') plt.plot(thresholds, precisions, label='Precision') plt.plot(thresholds, recalls, label='Recall') plt.xlabel('Threshold') plt.ylabel('Metric Value') plt.title('Metrics vs Classification Threshold') plt.legend() plt.grid(True) plt.savefig(save_path, dpi=300, bbox_inches='tight') plt.close()
def print_eval_metrics( metrics: dict, metric_key_prefix: str = "", all_labels: Optional[dict] = None, include_random_baseline: bool = True, seed: int = 42,) -> None: """ Print evaluation metrics in a nicely formatted way. Args: metrics: Dictionary of metrics metric_key_prefix: Optional prefix for metric keys all_labels: Optional labels for computing baselines include_random_baseline: Whether to include random baseline seed: Random seed for baseline """ if metric_key_prefix: print(f"\n===== Evaluation Metrics ({metric_key_prefix}) =====") else: print("\n===== Evaluation Metrics =====") prefix = metric_key_prefix + "/" if metric_key_prefix else "" # Print loss metrics if available if f'{prefix}lm_loss' in metrics: print("\nLoss Metrics:") print(f" - LM Loss: {metrics.get(f'{prefix}lm_loss', 0):.4f}") print(f" - Probe Loss: {metrics.get(f'{prefix}probe_loss', 0):.4f}") print(f" - Sparsity: {metrics.get(f'{prefix}sparsity', 0):.4f}") # Print classification metrics for different aggregation levels for agg_level in ['all', 'span', 'span_max']: if f'{prefix}{agg_level}_accuracy' in metrics: print(f"\n{agg_level.replace('_', ' ').title()} - Classification Metrics:") print(f" - Accuracy: {metrics[f'{prefix}{agg_level}_accuracy']:.4f}") print(f" - Precision: {metrics[f'{prefix}{agg_level}_precision']:.4f}") print(f" - Recall: {metrics[f'{prefix}{agg_level}_recall']:.4f}") print(f" - F1 Score: {metrics[f'{prefix}{agg_level}_f1']:.4f}") if f'{prefix}{agg_level}_auc' in metrics: print(f" - AUC: {metrics[f'{prefix}{agg_level}_auc']:.4f}") if f'{prefix}{agg_level}_recall_at_0.1_fpr' in metrics: print(f" - Recall @ 0.1 FPR: {metrics[f'{prefix}{agg_level}_recall_at_0.1_fpr']:.4f}") if f'{prefix}{agg_level}_threshold_optimized_accuracy' in metrics: print(f" - Optimized Accuracy: {metrics[f'{prefix}{agg_level}_threshold_optimized_accuracy']:.4f}") print(f" (Optimal Threshold: {metrics[f'{prefix}{agg_level}_optimal_threshold']:.4f})") # Print baselines if labels provided if all_labels and agg_level in all_labels: labels = np.array(all_labels[agg_level]) if len(labels) > 0: # Majority class baseline majority_class = 1 if np.sum(labels) >= len(labels) / 2 else 0 majority_baseline = accuracy_score(labels, np.full_like(labels, majority_class)) print(f" (Majority baseline: {majority_baseline:.4f})") print("\n==============================\n")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338"""Model loading and setup utilities."""
from typing import List, Optional, Tuple, Union
import torchimport torch.nn as nnfrom peft import PeftModel, LoraConfig, get_peft_modelfrom transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig, PreTrainedModel
def resolve_torch_dtype( dtype_name: Optional[str], *, default: Optional[torch.dtype] = None,) -> Optional[torch.dtype]: """Resolve config dtype name to a torch dtype.
Supported values: auto, fp32/float32, fp16/float16, bf16/bfloat16. """ if dtype_name is None: return default
key = str(dtype_name).strip().lower() if key in {"", "auto", "default", "model"}: return default if key in {"fp32", "float32", "torch.float32"}: return torch.float32 if key in {"fp16", "float16", "torch.float16"}: return torch.float16 if key in {"bf16", "bfloat16", "torch.bfloat16"}: return torch.bfloat16
raise ValueError( f"Unsupported dtype '{dtype_name}'. Use one of: auto, float32, float16, bfloat16." )
def get_device() -> torch.device: """Get the best available device (CUDA, MPS, or CPU).""" if torch.cuda.is_available(): return torch.device("cuda") elif torch.backends.mps.is_available(): return torch.device("mps") else: return torch.device("cpu")
def load_model_and_tokenizer( model_name: str, device_map: Optional[Union[str, dict]] = "auto", torch_dtype: Optional[torch.dtype] = None,) -> Tuple[AutoModelForCausalLM, AutoTokenizer]: """ Load a model and tokenizer from HuggingFace. Args: model_name: Name or path of the model load_in_8bit: Whether to load in 8-bit precision load_in_4bit: Whether to load in 4-bit precision device_map: Device mapping for model parallelism torch_dtype: Data type for model weights Returns: Tuple of (model, tokenizer) """ # Set default dtype if torch_dtype is None: torch_dtype = torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16 # Load model model = AutoModelForCausalLM.from_pretrained( model_name, device_map=device_map, torch_dtype=torch_dtype, trust_remote_code=True, ) # Load tokenizer tokenizer = AutoTokenizer.from_pretrained( model_name, trust_remote_code=True, padding_side='right' ) # Set padding token if not set if tokenizer.pad_token is None: tokenizer.pad_token = tokenizer.eos_token return model, tokenizer
def setup_model_with_lora( model: AutoModelForCausalLM, lora_config: dict, lora_weights_path: Optional[str] = None,) -> PeftModel: """ Setup a model with LoRA adapters. Args: model: Base model lora_config: LoRA configuration dictionary lora_weights_path: Optional path to pre-trained LoRA weights Returns: Model with LoRA adapters """ # Create LoRA configuration peft_config = LoraConfig( r=lora_config.get("r", 16), lora_alpha=lora_config.get("alpha", 32), lora_dropout=lora_config.get("dropout", 0.05), bias="none", task_type="CAUSAL_LM", target_modules=lora_config.get("target_modules", ["q_proj", "v_proj"]), ) # Apply LoRA to model if lora_weights_path: # Load pre-trained LoRA weights model = PeftModel.from_pretrained(model, lora_weights_path) else: # Initialize new LoRA adapters model = get_peft_model(model, peft_config) return model
def get_model_layers(model: PreTrainedModel) -> List[nn.Module]: """ Get the list of transformer layers from a model. Args: model: The transformer model Returns: List of layer modules """ # Handle PeftModel by getting the base model if isinstance(model, PeftModel): base_model = model.get_base_model() else: base_model = model # Common patterns for accessing layers in different model architectures if hasattr(base_model, 'model') and hasattr(base_model.model, 'layers'): # LLaMA, Mistral, etc. return list(base_model.model.layers) elif hasattr(base_model, 'transformer') and hasattr(base_model.transformer, 'h'): # GPT-2, GPT-J, etc. return list(base_model.transformer.h) elif hasattr(base_model, 'encoder') and hasattr(base_model.encoder, 'layer'): # BERT, RoBERTa, etc. return list(base_model.encoder.layer) elif hasattr(base_model, 'gpt_neox') and hasattr(base_model.gpt_neox, 'layers'): # GPT-NeoX return list(base_model.gpt_neox.layers) else: raise ValueError(f"Unknown model architecture: {type(base_model)}")
def get_num_layers(model_or_name: Union[str, PreTrainedModel]) -> int: """ Get the number of transformer layers in a model. Args: model_or_name: Either a model name string or a transformer model Returns: Number of layers """ # If it's a string (model name), use the predefined mapping if isinstance(model_or_name, str): model_layers_map = { "swiss-ai/Apertus-8B-Instruct-2509": 32, "meta-llama/Meta-Llama-3.1-8B-Instruct": 32, "meta-llama/Meta-Llama-3.1-70B-Instruct": 80, "meta-llama/Meta-Llama-3.1-405B-Instruct": 126, "google/gemma-2-2b-it": 26, "google/gemma-2-9b-it": 42, "google/gemma-2-27b-it": 46, "Qwen/Qwen2.5-0.5B-Instruct": 24, "Qwen/Qwen2.5-1.5B-Instruct": 28, "Qwen/Qwen2.5-3B-Instruct": 36, "Qwen/Qwen2.5-7B-Instruct": 28, "Qwen/Qwen2.5-14B-Instruct": 48, "Qwen/Qwen2.5-32B-Instruct": 64, "meta-llama/Llama-3.3-70B-Instruct": 80, "mistralai/Mistral-Small-24B-Instruct-2501": 40, } if model_or_name in model_layers_map: return model_layers_map[model_or_name] else: raise ValueError(f"Model {model_or_name} not supported. Please add it to the model_layers_map.") # If it's a model instance, count the layers return len(get_model_layers(model_or_name))
def get_model_layers_prefix(model: PreTrainedModel) -> str: """ Get the prefix path to the model layers. Args: model: The transformer model Returns: String prefix for accessing layers (e.g., "model.layers") """ # Handle PeftModel if isinstance(model, PeftModel): base_model = model.get_base_model() else: base_model = model if hasattr(base_model, 'model') and hasattr(base_model.model, 'layers'): return "model.layers" elif hasattr(base_model, 'transformer') and hasattr(base_model.transformer, 'h'): return "transformer.h" elif hasattr(base_model, 'encoder') and hasattr(base_model.encoder, 'layer'): return "encoder.layer" elif hasattr(base_model, 'gpt_neox') and hasattr(base_model.gpt_neox, 'layers'): return "gpt_neox.layers" else: raise ValueError(f"Unknown model architecture: {type(base_model)}")
def get_model_hidden_size(model: PreTrainedModel) -> int: """ Get the hidden size of a transformer model. Args: model: The transformer model Returns: Hidden size of the model """ # Handle PeftModel if isinstance(model, PeftModel): base_model = model.get_base_model() else: base_model = model if hasattr(base_model, 'config'): config = base_model.config # Try common attribute names for attr in ['hidden_size', 'd_model', 'n_embd', 'embed_dim']: if hasattr(config, attr): return getattr(config, attr) # If we can't find it in config, try to infer from the model structure if hasattr(base_model, 'model') and hasattr(base_model.model, 'embed_tokens'): return base_model.model.embed_tokens.weight.shape[1] raise ValueError(f"Could not determine hidden size for model type {type(base_model)}")
def setup_lora_for_layers( model: PreTrainedModel, layer_indices: List[int], lora_r: int = 16, lora_alpha: int = 32, lora_dropout: float = 0.05, bias: str = "none",) -> Union[PeftModel, PreTrainedModel]: """ Setup LoRA adapters for specific layers in a model. Args: model: Base model to apply LoRA to layer_indices: List of layer indices to apply LoRA to lora_r: LoRA rank lora_alpha: LoRA alpha scaling lora_dropout: LoRA dropout rate bias: Bias configuration for LoRA Returns: Model with LoRA adapters applied (or original model if no layers specified) """ if not layer_indices: print("No LoRA layers specified, returning base model") return model # Get the layer prefix for this model architecture layer_prefix = get_model_layers_prefix(model) # Build target modules list for the specified layers target_modules = [] module_suffixes = [ "self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj", "self_attn.o_proj", "mlp.gate_proj", "mlp.up_proj", "mlp.down_proj" ] for layer_idx in layer_indices: for module_suffix in module_suffixes: target_modules.append(f"{layer_prefix}.{layer_idx}.{module_suffix}") print(f"Creating LoRA adapters for layers {layer_indices}...") # Create LoRA config lora_config = LoraConfig( r=lora_r, lora_alpha=lora_alpha, lora_dropout=lora_dropout, bias=bias, target_modules=target_modules, task_type="CAUSAL_LM", ) # Apply LoRA to model return get_peft_model(model, lora_config)
def print_trainable_parameters(model: nn.Module) -> Tuple[int, int]: """ Print information about trainable parameters in a model. Args: model: The model to analyze Returns: Tuple of (trainable_params, total_params) """ trainable_params = 0 total_params = 0 print("Parameters that will be trained:") for name, param in model.named_parameters(): if param.requires_grad: trainable_params += param.numel() print(f" - {name}: shape {param.shape}, device {param.device}") total_params += param.numel() trainable_params_percentage = 100 * trainable_params / total_params print(f"\nTotal trainable parameters: {trainable_params:,} ({trainable_params_percentage:.2f}%)") print(f"Total parameters: {total_params:,}") return trainable_params, total_params123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155"""Utilities for downloading and uploading probe models to/from HuggingFace Hub."""
import osimport shutilimport tempfileimport timefrom pathlib import Pathfrom typing import Optional, Tuple, Union
import torchfrom huggingface_hub import HfApi, hf_hub_download, loginfrom huggingface_hub.utils import validate_repo_id
# Default directory for saving probes locallyenv_dir = os.getenv("LOCAL_PROBES_DIR")if env_dir: LOCAL_PROBES_DIR = Path(env_dir)else: LOCAL_PROBES_DIR = Path(__file__).parent.parent / "value_head_probes"
def download_probe_from_hf( repo_id: str, probe_id: Optional[str] = None, local_folder: Optional[Union[str, Path]] = None, hf_repo_subfolder_prefix: str = "", token: Optional[str] = None) -> None: """Simplified probe download function for Modal.""" api = HfApi()
if local_folder is None: local_folder = LOCAL_PROBES_DIR / probe_id elif isinstance(local_folder, str): local_folder = Path(local_folder)
local_folder.mkdir(parents=True, exist_ok=True) # List files in the repository subfolder repo_files = api.list_repo_files( repo_id=repo_id, repo_type="model", revision="main" ) # Filter files by subfolder path_in_repo = os.path.join(hf_repo_subfolder_prefix, probe_id) subfolder_files = [f for f in repo_files if f.startswith(f"{path_in_repo}/")] # Download each file for file_path in subfolder_files: # Get relative path within subfolder relative_path = file_path[len(path_in_repo):].lstrip('/') # Create subdirectory if needed local_file_path = local_folder / relative_path local_file_path.parent.mkdir(parents=True, exist_ok=True) # Download file downloaded_file = hf_hub_download( repo_id=repo_id, filename=file_path, token=token ) # Copy to destination shutil.copy(downloaded_file, local_file_path) print(f"Downloaded probe to {local_folder}")
def upload_probe_to_hf( repo_id: str, probe_id: Optional[str] = None, local_folder: Optional[Union[str, Path]] = None, hf_repo_subfolder_prefix: str = "", token: Optional[str] = None, private: bool = False, commit_message: str = "Upload probe model", max_retries: int = 5, retry_delay_seconds: float = 2.0,) -> str: """ Uploads a probe (LoRA adapters + value head) to HuggingFace Hub. Args: probe_dir: Local directory containing the probe files repo_id: Destination repository ID in the format 'username/repo_name' hf_repo_subfolder_prefix: Optional subfolder within the repo to upload to token: HF API token (required for uploading) private: Whether to make the repository private commit_message: Message for the commit Returns: URL of the uploaded model on Hugging Face Hub """ # Validate inputs validate_repo_id(repo_id)
if local_folder is None: local_folder = LOCAL_PROBES_DIR / probe_id elif isinstance(local_folder, str): local_folder = Path(local_folder) if not local_folder.exists(): raise ValueError(f"Probe directory {local_folder} does not exist")
path_in_repo = os.path.join(hf_repo_subfolder_prefix, probe_id) # Login if token is provided if token: login(token=token) api = HfApi() # Create repo if it doesn't exist api.create_repo( repo_id=repo_id, exist_ok=True, private=private, token=token ) print(f"Uploading folder {local_folder} to {repo_id}...") for attempt in range(1, max_retries + 1): try: api.upload_folder( folder_path=str(local_folder), repo_id=repo_id, repo_type="model", path_in_repo=path_in_repo, commit_message=commit_message, token=token, ) break except Exception as exc: status_code = getattr(getattr(exc, "response", None), "status_code", None) is_precondition_failed = status_code == 412 if is_precondition_failed and attempt < max_retries: sleep_seconds = retry_delay_seconds * attempt print( f"HF upload conflict (HTTP 412). Retrying {attempt}/{max_retries - 1} " f"after {sleep_seconds:.1f}s..." ) time.sleep(sleep_seconds) continue raise # Return the URL url = f"https://huggingface.co/{repo_id}" if hf_repo_subfolder_prefix: url += f"/tree/main/{hf_repo_subfolder_prefix}" print(f"Successfully uploaded probe to {url}") return url
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120"""Tokenization utilities for finding strings in tokenized sequences."""
from typing import List, Optional
import torchfrom jaxtyping import Intfrom torch import Tensorfrom transformers import AutoTokenizer
def find_string_in_tokens(target: str, tokens: Tensor, tokenizer: AutoTokenizer, max_iters: int = 100) -> slice: """ Performs a binary search to look for a target string inside some tokens. Args: target: String to find tokens: Tensor of token IDs tokenizer: Tokenizer to decode tokens max_iters: Maximum iterations for binary search Returns: slice: Slice indicating where the target's tokens are located Raises: AssertionError: If target is not found in the tokens ValueError: If binary search fails to find the target """ assert target in tokenizer.decode(tokens), "The target isn't contained in the whole array of tokens" # Binary search over the end index of the slice n_iters = max_iters end_idx_left, end_idx_right = 0, len(tokens) while end_idx_left != end_idx_right and n_iters > 0: mid = (end_idx_left + end_idx_right) // 2 if target in tokenizer.decode(tokens[:mid]): end_idx_right = mid else: end_idx_left = mid + 1 n_iters -= 1 end_idx = end_idx_left # Binary search over the start index of the slice n_iters = max_iters start_idx_left, start_idx_right = 0, end_idx-1 while start_idx_left != start_idx_right and n_iters > 0: mid = (start_idx_left + start_idx_right + 1) // 2 if target in tokenizer.decode(tokens[mid:end_idx]): start_idx_left = mid else: start_idx_right = mid-1 n_iters -= 1 start_idx = start_idx_left target_slice = slice(start_idx, end_idx) if target not in tokenizer.decode(tokens[target_slice]): raise ValueError(f"Failed to find {target} in tokens: {[tokenizer.decode([tok]) for tok in tokens]}") return target_slice
def find_assistant_tokens_slice( input_ids: Int[Tensor, "seq_len"], input_str: str, tokenizer: AutoTokenizer) -> slice: """ Find the slice of tokens that marks the start of the assistant's response. Args: input_ids: Input token IDs input_str: Decoded input string tokenizer: Tokenizer Returns: slice: Slice indicating assistant response start tokens """ eot_tokens = [ '<|eot_id|><|start_header_id|>assistant<|end_header_id|>', # llama 3.1 end-of-turn tokens '<|im_start|>assistant', # qwen end-of-turn tokens '<start_of_turn>model', # gemma end-of-turn tokens "[/INST]", # mistral end-of-turn tokens "<|user_end|><|assistant_start|>", # apertus end-of-turn tokens ] for eot_token in eot_tokens: if eot_token in input_str: try: return find_string_in_tokens(eot_token, input_ids, tokenizer) except (AssertionError, ValueError): continue print(f"Could not find assistant tokens in the input_ids: {input_str[:100]}...") return slice(0, 0)
def slice_to_list(slice_obj: slice, length: Optional[int] = None) -> List[int]: """ Convert a slice object to a list of indices. Args: slice_obj: Slice object length: Total length (required if stop is None) Returns: List of indices """ start, stop, step = slice_obj.start, slice_obj.stop, slice_obj.step # If length is not provided, use stop if it's not None, else raise an error if length is None: if stop is not None: length = stop else: raise ValueError("Length must be provided if stop is None") # Adjust start, stop, and step start = 0 if start is None else start stop = length if stop is None else stop step = 1 if step is None else step return list(range(start, stop, step))third_party/feature_probes/feature_probes/__init__.pyAdded+7
third_party/feature_probes/feature_probes/config.pyAdded+212
third_party/feature_probes/feature_probes/data/__init__.pyAdded
third_party/feature_probes/feature_probes/data/converters.pyAdded+218
third_party/feature_probes/feature_probes/data/dataset.pyAdded+437
third_party/feature_probes/feature_probes/evaluation/__init__.pyAdded
third_party/feature_probes/feature_probes/evaluation/evaluate.pyAdded+337
third_party/feature_probes/feature_probes/probes/__init__.pyAdded
third_party/feature_probes/feature_probes/probes/attention_probe.pyAdded+109
third_party/feature_probes/feature_probes/probes/value_head_probe.pyAdded+427
third_party/feature_probes/feature_probes/training/__init__.pyAdded
third_party/feature_probes/feature_probes/training/loss.pyAdded+250
third_party/feature_probes/feature_probes/training/trainer.pyAdded+315
third_party/feature_probes/feature_probes/types.pyAdded+22
third_party/feature_probes/feature_probes/utils/__init__.pyAdded
third_party/feature_probes/feature_probes/utils/activation_analysis.pyAdded+499
third_party/feature_probes/feature_probes/utils/file_utils.pyAdded+176
third_party/feature_probes/feature_probes/utils/hooks.pyAdded+40
third_party/feature_probes/feature_probes/utils/metrics.pyAdded+323
third_party/feature_probes/feature_probes/utils/model_utils.pyAdded+338
third_party/feature_probes/feature_probes/utils/probe_loader.pyAdded+155
third_party/feature_probes/feature_probes/utils/tokenization.pyAdded+120