Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Blazing fast bootstrap stderrs for AUROC #190

Merged
merged 58 commits into from
Apr 16, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
58 commits
Select commit Hold shift + click to select a range
d292c7c
LM output evaluation for autoregressive models
norabelrose Apr 4, 2023
7ed5ccd
move to own baseline file
lauritowal Apr 4, 2023
ba1d3b2
cleanup
lauritowal Apr 4, 2023
a20d4ca
Support encoder-decoder model LM output
norabelrose Apr 5, 2023
088758e
Merge remote-tracking branch 'origin/main' into lm-output
norabelrose Apr 5, 2023
77d7418
isort
norabelrose Apr 5, 2023
5bf63f4
Bug fixes
norabelrose Apr 5, 2023
819cfed
Merge branch 'main' into lm-output
norabelrose Apr 5, 2023
d3d9a8d
Merge branch 'main' into lm-output
norabelrose Apr 5, 2023
b89e23c
Remove test_log_csv_elements
norabelrose Apr 5, 2023
9aef842
Remove Python 3.9 support
norabelrose Apr 5, 2023
0851d4f
Add Pandas to pyproject.toml
norabelrose Apr 5, 2023
207a375
add code (contains still same device cuda error)
lauritowal Apr 5, 2023
e7efcce
fix multiple cuda error, save evals to right folder + cleanup
lauritowal Apr 7, 2023
b5fa54c
Merge branch 'main' into eval_lr
lauritowal Apr 7, 2023
4f8bdc5
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Apr 7, 2023
9ca72ba
Fix bug noticed by Waree
norabelrose Apr 7, 2023
d7e4893
Merge remote-tracking branch 'origin/eval_lr' into lm-output
norabelrose Apr 7, 2023
bcdca8a
Merge remote-tracking branch 'origin/main' into lm-output
norabelrose Apr 7, 2023
713a251
Add sanity check to load_prompts and refactor binarize
norabelrose Apr 7, 2023
0c35bc7
Changing a ton of stuff
norabelrose Apr 8, 2023
f6a762a
Merge remote-tracking branch 'origin/main' into lm-output
norabelrose Apr 10, 2023
f547744
Revert changes to binarize
norabelrose Apr 10, 2023
ab1909f
Stupid prompt_counter bug
norabelrose Apr 10, 2023
f58290f
Merge remote-tracking branch 'origin/main' into lm-output
norabelrose Apr 10, 2023
f912ee6
Remove stupid second set_start_method call
norabelrose Apr 10, 2023
606dcad
Merge remote-tracking branch 'origin/lm-output' into multiclass
norabelrose Apr 10, 2023
0038792
Merge remote-tracking branch 'origin/main' into multiclass
norabelrose Apr 10, 2023
83b480b
Fix bugs in binary case
norabelrose Apr 11, 2023
3e66262
Various little refactors
norabelrose Apr 11, 2023
a8c21a6
Remove .predict and .predict_prob on Reporter; trying to get SciQ to …
norabelrose Apr 11, 2023
5f478b1
Bugfix for Reporter.score on binary tasks
norabelrose Apr 11, 2023
97b26ac
Fix bug where cached hidden states aren’t used when num_gpus is diffe…
norabelrose Apr 12, 2023
11fda87
Actually works now
norabelrose Apr 12, 2023
da4c72f
Refactor handling of multiple datasets
norabelrose Apr 13, 2023
e1675f7
Various fixes
norabelrose Apr 13, 2023
8cc325b
Merge remote-tracking branch 'origin/main' into multi-ds-eval
norabelrose Apr 13, 2023
14987e1
Fix math tests
norabelrose Apr 13, 2023
88683fa
Fix smoke tests
norabelrose Apr 13, 2023
a6c382e
All tests working ostensibly
norabelrose Apr 13, 2023
ecc53cb
Make CCS normalization customizable
norabelrose Apr 13, 2023
18c7f4c
log each dataset individually
AlexTMallen Apr 13, 2023
94a900c
Merge branch 'multi-ds-eval' into multiclass
norabelrose Apr 13, 2023
5173649
Fix label_column bug
norabelrose Apr 13, 2023
3e6c39c
GLUE MNLI works on Deberta
norabelrose Apr 14, 2023
1e9ce06
Move pseudo AUROC stuff to CcsReporter
norabelrose Apr 14, 2023
35a8f34
Make 'datasets' and 'label_columns' config options more opinionated
norabelrose Apr 14, 2023
615bbb1
tiny spacing change
norabelrose Apr 14, 2023
f021404
Allow for toggling CV
norabelrose Apr 14, 2023
f6629ec
Merge branch 'multi-ds-eval' into multiclass
norabelrose Apr 14, 2023
99f01c3
Remove duplicate dbpedia template
norabelrose Apr 14, 2023
f415f8d
Merge branch 'main' into multiclass
norabelrose Apr 14, 2023
d16c96b
Training on datasets with different numbers of classes now works
norabelrose Apr 15, 2023
044774e
Efficient bootstrap CIs for AUROCs
norabelrose Apr 15, 2023
a7f1ea0
Fix CCS smoke test failure
norabelrose Apr 15, 2023
3abeb60
Update extraction.py
lauritowal Apr 16, 2023
1e4a6b9
Merge branch 'main' into roc_auc
lauritowal Apr 16, 2023
4c60061
Update extraction.py
lauritowal Apr 16, 2023
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
Prev Previous commit
Next Next commit
fix multiple cuda error, save evals to right folder + cleanup
  • Loading branch information
lauritowal committed Apr 7, 2023
commit e7efcce7a26cc364f494dba8215fde117074fac5
164 changes: 25 additions & 139 deletions elk/evaluation/evaluate.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,17 @@
from functools import partial
from pathlib import Path
from typing import Callable, Literal, Optional
from dataclasses import dataclass
from functools import partial
from pathlib import Path
from typing import Callable, Literal, Optional

import pandas as pd
import torch
from simple_parsing.helpers import Serializable, field

from evaluation.evaluate_log import EvalLog
from extraction.extraction import Extract
from files import elk_reporter_dir
from run import Run
from training import Reporter
from training.baseline import evaluate_baseline, load_baseline, train_baseline
from utils import select_usable_devices
from ..extraction.extraction import Extract
from ..files import create_output_directory, elk_reporter_dir, memorably_named_dir
from ..run import Run
from ..training import Reporter
from ..training.baseline import evaluate_baseline, load_baseline
from ..utils import select_usable_devices


@dataclass
Expand Down Expand Up @@ -48,8 +44,9 @@ class Eval(Serializable):

def execute(self):
transfer_eval = elk_reporter_dir() / self.source / "transfer_eval"
out_dir = memorably_named_dir(transfer_eval)

run = Evaluate(cfg=self, out_dir=transfer_eval)
run = Evaluate(cfg=self, out_dir=out_dir)
run.evaluate()


Expand All @@ -59,7 +56,7 @@ class Evaluate(Run):

def evaluate_reporter(
self, layer: int, devices: list[str], world_size: int = 1
) -> EvalLog:
) -> pd.Series:
"""Evaluate a single reporter on a single layer."""
device = self.get_device(devices, world_size)

Expand All @@ -70,9 +67,7 @@ def evaluate_reporter(

experiment_dir = elk_reporter_dir() / self.cfg.source

reporter_path = (
experiment_dir / "reporters" / f"layer_{layer}.pt"
)
reporter_path = experiment_dir / "reporters" / f"layer_{layer}.pt"
reporter: Reporter = torch.load(reporter_path, map_location=device)
reporter.eval()

Expand All @@ -82,129 +77,25 @@ def evaluate_reporter(
test_x1,
)

lr_dir = experiment_dir / "lr_models"
if not self.cfg.skip_baseline and lr_dir.exists():
lr_model = load_baseline(lr_dir, layer)
lr_auroc, lr_acc = evaluate_baseline(lr_model, test_x0, test_x1, test_labels)

print("transfer_eval", lr_auroc, lr_acc)

# stats.lr_auroc = lr_auroc
# stats.lr_acc = lr_acc
# save_baseline(lr_dir, layer, lr_model)

return EvalLog(
layer=layer,
eval_result=test_result,
)

def evaluate(self):
"""Evaluate the reporter on all layers."""
devices = select_usable_devices(
self.cfg.num_gpus, min_memory=self.cfg.data.min_gpu_mem
)

num_devices = len(devices)
func: Callable[[int], EvalLog] = partial(
self.evaluate_reporter, devices=devices, world_size=num_devices
)
self.apply_to_layers(
func=func,
num_devices=num_devices,
to_csv_line=lambda item: item.to_csv_line(),
csv_columns=EvalLog.csv_columns(),
)

import torch
from simple_parsing.helpers import Serializable, field

from evaluation.evaluate_log import EvalLog
from extraction.extraction import Extract
from files import elk_reporter_dir
from run import Run
from training import Reporter
from training.baseline import evaluate_baseline, load_baseline, train_baseline
from utils import select_usable_devices


@dataclass
class Eval(Serializable):
"""
Full specification of a reporter evaluation run.

Args:
data: Config specifying hidden states on which the reporter will be evaluated.
source: The name of the source run directory
which contains the reporters directory.
normalization: The normalization method to use. Defaults to "meanonly". See
`elk.training.preprocessing.normalize()` for details.
num_gpus: The number of GPUs to use. Defaults to -1, which means
"use all available GPUs".
debug: When in debug mode, a useful log file is saved to the memorably-named
output directory. Defaults to False.
"""

data: Extract
source: str = field(positional=True)
normalization: Literal["legacy", "none", "elementwise", "meanonly"] = "meanonly"

debug: bool = False
out_dir: Optional[Path] = None
num_gpus: int = -1
skip_baseline: bool = False
concatenated_layer_offset: int = 0

def execute(self):
transfer_eval = elk_reporter_dir() / self.source / "transfer_eval"

run = Evaluate(cfg=self, out_dir=transfer_eval)
run.evaluate()


@dataclass
class Evaluate(Run):
cfg: Eval

def evaluate_reporter(
self, layer: int, devices: list[str], world_size: int = 1
) -> EvalLog:
"""Evaluate a single reporter on a single layer."""
device = self.get_device(devices, world_size)

_, _, test_x0, test_x1, _, test_labels = self.prepare_data(
device,
layer,
)

experiment_dir = elk_reporter_dir() / self.cfg.source

reporter_path = (
experiment_dir / "reporters" / f"layer_{layer}.pt"
)
reporter: Reporter = torch.load(reporter_path, map_location=device)
reporter.eval()

test_result = reporter.score(
test_labels,
test_x0,
test_x1,
stats_row = pd.Series(
{
"layer": layer,
**test_result._asdict(),
}
)

lr_dir = experiment_dir / "lr_models"
if not self.cfg.skip_baseline and lr_dir.exists():
lr_model = load_baseline(lr_dir, layer)
lr_auroc, lr_acc = evaluate_baseline(lr_model, test_x0, test_x1, test_labels)
lr_model.eval()
lr_auroc, lr_acc = evaluate_baseline(
lr_model.cuda(), test_x0.cuda(), test_x1.cuda(), test_labels
)

print("transfer_eval", lr_auroc, lr_acc)
stats_row["lr_auroc"] = lr_auroc
stats_row["lr_acc"] = lr_acc

# stats.lr_auroc = lr_auroc
# stats.lr_acc = lr_acc
# save_baseline(lr_dir, layer, lr_model)

return EvalLog(
layer=layer,
eval_result=test_result,
)
return stats_row

def evaluate(self):
"""Evaluate the reporter on all layers."""
Expand All @@ -213,12 +104,7 @@ def evaluate(self):
)

num_devices = len(devices)
func: Callable[[int], EvalLog] = partial(
func: Callable[[int], pd.Series] = partial(
self.evaluate_reporter, devices=devices, world_size=num_devices
)
self.apply_to_layers(
func=func,
num_devices=num_devices,
to_csv_line=lambda item: item.to_csv_line(),
csv_columns=EvalLog.csv_columns(),
)
self.apply_to_layers(func=func, num_devices=num_devices)
27 changes: 0 additions & 27 deletions elk/evaluation/evaluate_log.py

This file was deleted.

32 changes: 15 additions & 17 deletions elk/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,17 @@
from typing import TYPE_CHECKING, Callable, Iterator, Optional, Union

import numpy as np
import pandas as pd
import torch
import torch.multiprocessing as mp
from datasets import DatasetDict
from torch import Tensor
from tqdm import tqdm

from datasets import DatasetDict
from elk.extraction.extraction import extract
from elk.files import create_output_directory, save_config, save_meta
from elk.logging import save_debug_log
from elk.training.preprocessing import normalize
from elk.utils.csv import Log, write_iterator_to_file
from elk.utils.data_utils import get_layers, select_train_val_splits
from elk.utils.typing import assert_type, int16_to_float32

Expand Down Expand Up @@ -94,10 +95,8 @@ def concatenate(self, layers):

def apply_to_layers(
self,
func: Callable[[int], Log],
func: Callable[[int], pd.Series],
num_devices: int,
to_csv_line: Callable[[Log], list[str]],
csv_columns: list[str],
):
"""Apply a function to each layer of the dataset in parallel
and writes the results to a CSV file.
Expand All @@ -120,15 +119,14 @@ def apply_to_layers(
# Should we write to different CSV files for elicit vs eval?
with mp.Pool(num_devices) as pool, open(self.out_dir / "eval.csv", "w") as f:
mapper = pool.imap_unordered if num_devices > 1 else map
iterator: Iterator[Log] = tqdm( # type: ignore
mapper(func, layers), total=len(layers)
)
write_iterator_to_file(
iterator=iterator,
file=f,
debug=self.cfg.debug,
dataset=self.dataset,
out_dir=self.out_dir,
csv_columns=csv_columns,
to_csv_line=to_csv_line,
)
row_buf = []

try:
for row in tqdm(mapper(func, layers), total=len(layers)):
row_buf.append(row)
finally:
# Make sure the CSV is written even if we crash or get interrupted
df = pd.DataFrame(row_buf).sort_values(by="layer")
df.to_csv(f, index=False)
if self.cfg.debug:
save_debug_log(self.dataset, self.out_dir)
2 changes: 1 addition & 1 deletion elk/training/baseline.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import pickle
from pathlib import Path
from typing import Tuple
from typing import NamedTuple, Tuple

import torch
from sklearn.metrics import accuracy_score, roc_auc_score
Expand Down
12 changes: 7 additions & 5 deletions elk/training/reporter.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
"""An ELK reporter network."""

from ..calibration import CalibrationError
from .classifier import Classifier
from abc import ABC, abstractmethod
from dataclasses import dataclass
from pathlib import Path
from simple_parsing.helpers import Serializable
from sklearn.metrics import roc_auc_score
from torch import Tensor
from typing import Literal, NamedTuple, Optional, Union

import torch
import torch.nn as nn
from simple_parsing.helpers import Serializable
from sklearn.metrics import roc_auc_score
from torch import Tensor

from ..calibration import CalibrationError
from .classifier import Classifier


class EvalResult(NamedTuple):
Expand Down
Loading