Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 35 additions & 35 deletions delphi/log/result_analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -298,35 +298,37 @@ def log_results(

latent_df, counts = load_data(scores_path, modules)
latent_df = latent_df[latent_df["score_type"].isin(scorer_names)]
latent_df = add_latent_f1(latent_df)

plot_firing_vs_f1(
latent_df, num_tokens=10_000_000, out_dir=viz_path, run_label=scores_path.name
)

if latent_df.empty:
print("No data found")
return

dead = sum((counts[m] == 0).sum().item() for m in modules)
print(f"Number of dead features: {dead}")
print(f"Number of interpreted live features: {len(latent_df)}")

# Load constructor config for run
with open(scores_path.parent / "run_config.json", "r") as f:
run_cfg = orjson.loads(f.read())
constructor_cfg = run_cfg.get("constructor_cfg", {})
min_examples = constructor_cfg.get("min_examples", None)
print("min examples", min_examples)

if min_examples is not None:
uninterpretable_features = sum(
[(counts[m] < min_examples).sum() for m in modules]
)
print(
f"Number of features below the interpretation firing"
f" count threshold: {uninterpretable_features}"
latent_df = add_latent_f1(latent_df)
if counts:
plot_firing_vs_f1(
latent_df,
num_tokens=10_000_000,
out_dir=viz_path,
run_label=scores_path.name,
)
dead = sum((counts[m] == 0).sum().item() for m in modules)
print(f"Number of dead features: {dead}")
print(f"Number of interpreted live features: {len(latent_df)}")

# Load constructor config for run
with open(scores_path.parent / "run_config.json", "r") as f:
run_cfg = orjson.loads(f.read())
constructor_cfg = run_cfg.get("constructor_cfg", {})
min_examples = constructor_cfg.get("min_examples", None)
print("min examples", min_examples)

if min_examples is not None:
uninterpretable_features = sum(
[(counts[m] < min_examples).sum() for m in modules]
)
print(
f"Number of features below the interpretation firing"
f" count threshold: {uninterpretable_features}"
)

plot_roc_curve(latent_df, viz_path)

Expand All @@ -339,11 +341,11 @@ def log_results(
print(f"\n--- {score_type.title()} Metrics ---")
print(f"Class-Balanced Accuracy: {score_type_summary['accuracy']:.3f}")
print(f"F1 Score: {score_type_summary['f1_score']:.3f}")
print(f"Frequency-Weighted F1 Score: {score_type_summary['weighted_f1']:.3f}")
print(
"Note: the frequency-weighted F1 score is computed over each"
" hookpoint and averaged"
)
if score_type_summary["weighted_f1"] is not None:
print(
f"Frequency-Weighted F1 Score: {score_type_summary['weighted_f1']:.3f}"
)
print("Frequency-weighted F1 is averaged over hookpoints.")
print(f"Precision: {score_type_summary['precision']:.3f}")
print(f"Recall: {score_type_summary['recall']:.3f}")
# Only print AUC if unbalanced AUC is not -1.
Expand All @@ -355,10 +357,8 @@ def log_results(
fractions_failed = [
score_type_summary["failed_count"]
/ (
(
score_type_summary["total_examples"]
+ score_type_summary["failed_count"]
)
score_type_summary["total_examples"]
+ score_type_summary["failed_count"]
)
]
print(f"""Average fraction of failed examples: \
Expand All @@ -383,6 +383,6 @@ def log_results(
)

print("\nClass Distribution:")
print(f"""Positives: {score_type_summary['total_positives'].sum():.0f}""")
print(f"""Negatives: {score_type_summary['total_negatives'].sum():.0f}""")
print(f"""Positives: {score_type_summary["total_positives"].sum():.0f}""")
print(f"""Negatives: {score_type_summary["total_negatives"].sum():.0f}""")
print(f"Total: {score_type_summary['total_examples'].sum():.0f}")
42 changes: 42 additions & 0 deletions tests/test_log/test_result_analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,3 +100,45 @@ def test_frequency_weighted_f1_with_several_modules(tmp_path):

# per-module F1 is 1.0 for "layers.1" and 0.0 for "layers.10"
assert metrics["weighted_f1"].tolist() == [0.5]


def test_logging_without_firing_counts_keeps_classification_metrics(
monkeypatch, tmp_path, capsys
):
from delphi.log import result_analysis as analysis

frame = pd.DataFrame(
{
"module": ["layers.1", "layers.1"],
"latent_idx": [0, 0],
"score_type": ["detection", "detection"],
"activating": [True, False],
"prediction": [True, False],
"probability": [None, None],
}
)
monkeypatch.setattr(analysis, "import_plotly", lambda: None)
monkeypatch.setattr(analysis, "load_data", lambda *args: (frame, None))
monkeypatch.setattr(
analysis,
"plot_firing_vs_f1",
lambda *args, **kwargs: (_ for _ in ()).throw(
AssertionError("Missing counts must skip the firing-rate plot")
),
)
monkeypatch.setattr(analysis, "plot_roc_curve", lambda *args: None)
monkeypatch.setattr(analysis, "plot_accuracy_hist", lambda *args: None)
analysis.log_results(
tmp_path / "scores", tmp_path / "viz", ["layers.1"], ["detection"]
)
assert "Class-Balanced Accuracy: 1.000" in capsys.readouterr().out


def test_logging_empty_scores_returns_before_plotting(monkeypatch, tmp_path, capsys):
from delphi.log import result_analysis as analysis

frame = pd.DataFrame(columns=["score_type"])
monkeypatch.setattr(analysis, "import_plotly", lambda: None)
monkeypatch.setattr(analysis, "load_data", lambda *args: (frame, None))
analysis.log_results(tmp_path / "scores", tmp_path / "viz", [], ["detection"])
assert "No data found" in capsys.readouterr().out
Loading