Download code/src/direction_discovery.py from PratikBuilds/modelclinic-experiment-001: direct link, hf CLI and curl.
- Browser
- Download file 9.49 kB
-
https://huggingface.co/datasets/PratikBuilds/modelclinic-experiment-001/resolve/main/code/src/direction_discovery.py
- Command line
-
hf download hf://datasets/PratikBuilds/modelclinic-experiment-001/code/src/direction_discovery.py
-
curl -L -o direction_discovery.py https://huggingface.co/datasets/PratikBuilds/modelclinic-experiment-001/resolve/main/code/src/direction_discovery.py
9.49 kB
| """CPU-side utilities for fitting a contrastive activation steering direction. | |
| This is an exploratory discovery tool. It uses within-trajectory low-vs-high | |
| repetition windows, not answer correctness, because the available full outputs | |
| are too few for a reliable productive-vs-failed trajectory classifier. | |
| """ | |
| from __future__ import annotations | |
| import hashlib | |
| import json | |
| import math | |
| from collections import Counter | |
| from pathlib import Path | |
| from typing import Any | |
| import numpy as np | |
| LAYERS = (15, 19) | |
| REPEAT_WINDOW = 512 | |
| LOW_REPEAT_MAX = 0.05 | |
| HIGH_REPEAT_MIN = 0.50 | |
| SAMPLE_STRIDE = 256 | |
| MAX_SAMPLES_PER_CLASS_PER_TRAJECTORY = 2 | |
| def read_json(path: str | Path) -> dict[str, Any]: | |
| return json.loads(Path(path).read_text(encoding="utf-8-sig")) | |
| def repeated_ngram_fraction(token_ids: list[int], position: int, | |
| window: int = REPEAT_WINDOW, ngram: int = 8) -> float: | |
| """Duplicate fraction among n-grams in the trailing token window.""" | |
| left = max(0, position - window + 1) | |
| tokens = token_ids[left:position + 1] | |
| grams = [tuple(tokens[i:i + ngram]) for i in range(max(0, len(tokens) - ngram + 1))] | |
| return 1.0 - len(set(grams)) / len(grams) if grams else 0.0 | |
| def _evenly_spaced(candidates: list[dict[str, Any]], count: int, | |
| min_separation: int) -> list[dict[str, Any]]: | |
| if not candidates: | |
| return [] | |
| ordered = sorted(candidates, key=lambda row: row["position"]) | |
| if len(ordered) <= count: | |
| selected: list[dict[str, Any]] = [] | |
| for item in ordered: | |
| if all(abs(item["position"] - old["position"]) >= min_separation for old in selected): | |
| selected.append(item) | |
| if len(selected) == count: | |
| break | |
| return selected | |
| # Pick deterministic quantiles, then enforce non-overlapping local contexts. | |
| anchors = [ordered[round(i * (len(ordered) - 1) / max(count - 1, 1))] | |
| for i in range(count)] | |
| selected: list[dict[str, Any]] = [] | |
| for item in anchors: | |
| if all(abs(item["position"] - old["position"]) >= min_separation for old in selected): | |
| selected.append(item) | |
| if len(selected) < count: | |
| for item in ordered: | |
| if item not in selected and all(abs(item["position"] - old["position"]) >= min_separation | |
| for old in selected): | |
| selected.append(item) | |
| if len(selected) == count: | |
| break | |
| return sorted(selected, key=lambda row: row["position"]) | |
| def choose_positions(token_ids: list[int], *, stride: int = SAMPLE_STRIDE, | |
| window: int = REPEAT_WINDOW, | |
| max_per_class: int = MAX_SAMPLES_PER_CLASS_PER_TRAJECTORY | |
| ) -> dict[str, list[dict[str, Any]]]: | |
| """Choose matched local-context positions without using model activations.""" | |
| classes: dict[str, list[dict[str, Any]]] = {"low_repetition": [], "high_repetition": []} | |
| for position in range(stride - 1, len(token_ids), stride): | |
| score = repeated_ngram_fraction(token_ids, position, window=window) | |
| row = {"position": position, "repeat8_fraction": score} | |
| if score < LOW_REPEAT_MAX: | |
| classes["low_repetition"].append(row) | |
| elif score >= HIGH_REPEAT_MIN: | |
| classes["high_repetition"].append(row) | |
| return {label: _evenly_spaced(rows, max_per_class, window) | |
| for label, rows in classes.items()} | |
| def fit_directions(activation_data: dict[str, Any], calibration: dict[str, Any] | |
| ) -> dict[str, Any]: | |
| """Fit unit directions as low-repeat minus high-repeat means. | |
| Each trajectory contributes one paired class-centroid difference, so | |
| thousands of correlated token positions cannot masquerade as independent | |
| observations. A same-sample RMS norm target is retained only as provisional | |
| metadata; a runner must independently calibrate the final coefficient. | |
| """ | |
| records = activation_data["records"] | |
| source_rows = sorted({int(row["source_row"]) for row in records}) | |
| layers = tuple(int(x) for x in activation_data.get("layers", LAYERS)) | |
| result_directions: list[list[float]] = [] | |
| layer_summaries: list[dict[str, Any]] = [] | |
| for layer in layers: | |
| paired: list[tuple[int, np.ndarray]] = [] | |
| by_source: dict[int, dict[str, list[np.ndarray]]] = {} | |
| for row in records: | |
| by_source.setdefault(int(row["source_row"]), {"low_repetition": [], "high_repetition": []}) | |
| by_source[int(row["source_row"])][row["label"]].append( | |
| np.asarray(row["activations"][str(layer)], dtype=np.float64)) | |
| for source_row, classes in sorted(by_source.items()): | |
| if not classes["low_repetition"] or not classes["high_repetition"]: | |
| continue | |
| low = np.mean(np.stack(classes["low_repetition"]), axis=0) | |
| high = np.mean(np.stack(classes["high_repetition"]), axis=0) | |
| paired.append((source_row, low - high)) | |
| if len(paired) < 3: | |
| raise ValueError(f"Layer {layer}: need at least 3 paired source rows; got {len(paired)}") | |
| contrasts = np.stack([delta for _, delta in paired]) | |
| raw_direction = contrasts.mean(axis=0) | |
| norm = float(np.linalg.norm(raw_direction)) | |
| if not math.isfinite(norm) or norm <= 1e-12: | |
| raise ValueError(f"Layer {layer}: contrastive mean is degenerate") | |
| direction = raw_direction / norm | |
| result_directions.append(direction.astype(np.float32).tolist()) | |
| loo_cosines = [] | |
| for i in range(len(paired)): | |
| loo = np.delete(contrasts, i, axis=0).mean(axis=0) | |
| loo_norm = float(np.linalg.norm(loo)) | |
| if loo_norm > 1e-12: | |
| loo_cosines.append(float(np.dot(direction, loo / loo_norm))) | |
| layer_summaries.append({ | |
| "layer": layer, | |
| "paired_source_rows": [source for source, _ in paired], | |
| "n_paired_source_rows": len(paired), | |
| "mean_unscaled_contrast_norm": float(np.mean(np.linalg.norm(contrasts, axis=1))), | |
| "leave_one_source_out_cosines": loo_cosines, | |
| "leave_one_source_out_min_cosine": min(loo_cosines) if loo_cosines else None, | |
| "leave_one_source_out_median_cosine": float(np.median(loo_cosines)) if loo_cosines else None, | |
| "direction_norm": float(np.linalg.norm(direction)), | |
| }) | |
| coefficients = [float(x) for x in calibration["coefficients"]] | |
| if len(coefficients) != len(layers): | |
| raise ValueError("Calibration coefficient count does not match requested layers") | |
| directions_payload = { | |
| "format_version": 1, | |
| "method": "unit mean difference of base-model MLP down-projection outputs: low-repetition minus high-repetition; paired and equally weighted by source trajectory", | |
| "target": "independent_constant", | |
| "layers": list(layers), | |
| "directions": result_directions, | |
| "coefficients": coefficients, | |
| "coefficients_status": "provisional RMS reference only; replace with the runner's independent behavior-search coefficient before evaluation", | |
| "scaling_rule": "final magnitude is selected by an independent behavior search on new calibration questions; the stored coefficient is only a provisional RMS reference", | |
| "calibration": calibration, | |
| "source_rows": source_rows, | |
| "trajectory_method": activation_data.get("method"), | |
| "thresholds": activation_data.get("thresholds"), | |
| "sampling": activation_data.get("sampling"), | |
| "activation_counts": { | |
| str(layer): { | |
| label: sum(1 for row in records if row["label"] == label) | |
| for label in ("low_repetition", "high_repetition") | |
| } for layer in layers | |
| }, | |
| "stability": layer_summaries, | |
| "limitations": [ | |
| "Exploratory contrast from four long base-model trajectories; token windows are correlated.", | |
| "Low versus high repeated-8-gram fraction is a local behavior proxy, not a validated loop or productivity label.", | |
| "Captured windows reset context and position; they are not full-prefix activation observations.", | |
| "Transformers BF16 replay is approximate relative to the original vLLM generation backend.", | |
| "The direction is not validated for behavioral benefit; run only on held-out questions after review.", | |
| ], | |
| } | |
| input_hash = hashlib.sha256(json.dumps(activation_data, sort_keys=True, | |
| separators=(",", ":")).encode()).hexdigest() | |
| directions_payload["activation_data_sha256"] = input_hash | |
| directions_payload["calibration_sha256"] = calibration.get("sha256") | |
| return directions_payload | |
| def fit_file(activation_path: str | Path, calibration_path: str | Path, | |
| output_path: str | Path) -> dict[str, Any]: | |
| activations = read_json(activation_path) | |
| calibration = read_json(calibration_path) | |
| result = fit_directions(activations, calibration) | |
| path = Path(output_path) | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| path.write_text(json.dumps(result, indent=2, allow_nan=False), encoding="utf-8") | |
| return result | |