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 bugs in binary case
  • Loading branch information
norabelrose committed Apr 11, 2023
commit 83b480bbf28a52913672eabf91ef8f9a1cec1f14
3 changes: 1 addition & 2 deletions elk/extraction/extraction.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@
select_train_val_splits,
select_usable_devices,
)
from .balanced_sampler import BalancedSampler
from .generator import _GeneratorBuilder
from .prompt_loading import PromptConfig, load_prompts

Expand Down Expand Up @@ -126,7 +125,7 @@ def extract_hiddens(
if rank == world_size - 1:
max_examples += global_max_examples % world_size

for example in islice(BalancedSampler(prompt_ds, 3), max_examples):
for example in islice(prompt_ds, max_examples):
num_variants = len(example["prompts"])
num_choices = len(example["prompts"][0])

Expand Down
112 changes: 50 additions & 62 deletions elk/extraction/prompt_loading.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
from collections import Counter
from dataclasses import dataclass
from itertools import cycle
from random import Random
from typing import Any, Iterator, Literal, Optional

from datasets import (
Dataset,
Features,
load_dataset,
)
from datasets.distributed import split_dataset_by_node
Expand All @@ -18,7 +18,7 @@
infer_num_classes,
select_train_val_splits,
)
from .balanced_sampler import FewShotSampler
from .balanced_sampler import BalancedSampler


@dataclass
Expand Down Expand Up @@ -95,10 +95,12 @@ def load_prompts(
Returns:
An iterable dataset of prompts.
"""
class_counts = []
prompters = []
raw_datasets = []
datasets = []
train_datasets = []
rng = Random(seed)
assert num_shots == 0

# First load the datasets and prompters. We need to know the minimum number of
# templates for any dataset in order to make sure we don't run out of prompts.
Expand All @@ -112,29 +114,37 @@ def load_prompts(
train_name, val_name = select_train_val_splits(ds_dict)
split_name = val_name if split_type == "val" else train_name

# Note that when streaming we can only approximately shuffle the dataset
# using a buffer. Streaming shuffling is NOT an adequate shuffle for
# datasets like IMDB, which are sorted by label.
bad_streaming_datasets = ["imdb"]
assert not (
stream and ds_name in bad_streaming_datasets
), f"Streaming is not supported for {ds_name}."
split = ds_dict[split_name].shuffle(seed=seed)
ds = ds_dict[split_name].shuffle(seed=seed)
train_ds = ds_dict[train_name].shuffle(seed=seed)

if not stream:
split = assert_type(Dataset, split)
split = split.to_iterable_dataset().cast(split.features)
ds = assert_type(Dataset, ds)
if world_size > 1:
ds = ds.shard(world_size, rank)

ds = ds.to_iterable_dataset().cast(ds.features)

# only keep the datapoints relevant to the current process
if world_size > 1:
elif world_size > 1:
# This prints to stdout which is slightly annoying
split = split_dataset_by_node(
dataset=split, rank=rank, world_size=world_size
)
ds = split_dataset_by_node(dataset=ds, rank=rank, world_size=world_size)

raw_datasets.append(split)
label_column = infer_label_column(ds.features)
num_classes = infer_num_classes(ds.features[label_column])
if label_column != "label":
ds = ds.rename_column(label_column, "label")
train_ds = train_ds.rename_column(label_column, "label")

class_counts.append(num_classes)
datasets.append(ds)
train_datasets.append(train_ds)

# Number of classes should be the same for all datasets
num_classes, *rest = class_counts
if not all(num_classes == x for x in rest):
raise ValueError(
f"# classes should be the same for all datasets, but got {class_counts}"
)

min_num_templates = min(len(prompter.templates) for prompter in prompters)
num_variants = (
min_num_templates
Expand All @@ -145,51 +155,29 @@ def load_prompts(
if rank == 0:
print(f"Using {num_variants} variants of each prompt")

ds_iterators = [iter(ds) for ds in raw_datasets]
while True: # terminates when the first dataset runs out of examples
for ds_iterator, ds, train_ds, prompter in zip(
ds_iterators, raw_datasets, train_datasets, prompters
):
label_column = infer_label_column(ds.features)
num_classes = infer_num_classes(ds.features[label_column])

# Remove everything except the label column
extra_cols = list(assert_type(Features, ds.features))
extra_cols.remove(label_column)

if label_column != "label":
ds = ds.rename_column(label_column, "label")
if num_shots > 0:
fewshot = FewShotSampler(
train_ds, # TODO: not iterator
num_shots=num_shots,
rng=rng,
)
fewshot_iter = iter(fewshot)
else:
fewshot_iter = None

try:
example = next(ds_iterator)
except StopIteration:
return

example = _convert_to_prompts(
example,
label_column=label_column,
num_classes=num_classes,
num_variants=num_variants,
prompter=prompter,
rng=rng,
fewshot_iter=fewshot_iter,
)
ds_iters = [iter(BalancedSampler(ds, num_classes)) for ds in datasets]
for ds_iter, ds, prompter in cycle(zip(ds_iters, datasets, prompters)):
try:
example = next(ds_iter)
except StopIteration:
return

example = _convert_to_prompts(
example,
label_column="label",
num_classes=num_classes,
num_variants=num_variants,
prompter=prompter,
rng=rng,
fewshot_iter=None,
)

# Add the builder and config name to the records directly to make
# sure we don't forget what dataset they came from.
example["builder_name"] = ds.info.builder_name
example["config_name"] = ds.info.config_name
# Add the builder and config name to the records directly to make
# sure we don't forget what dataset they came from.
example["builder_name"] = ds.info.builder_name
example["config_name"] = ds.info.config_name

yield example
yield example


def _convert_to_prompts(
Expand Down
3 changes: 1 addition & 2 deletions elk/metrics.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
from functools import partial
from typing import Literal

import torch
from sklearn.metrics import average_precision_score, roc_auc_score
from torch import Tensor

Expand All @@ -17,7 +16,7 @@ def to_one_hot(labels: Tensor, n_classes: int) -> Tensor:
Returns:
Tensor: A one-hot representation tensor of shape (N, n_classes).
"""
one_hot_labels = torch.zeros(labels.size(0), n_classes, dtype=torch.float32)
one_hot_labels = labels.new_zeros(labels.size(0), n_classes)
return one_hot_labels.scatter_(1, labels.unsqueeze(1).long(), 1)


Expand Down
4 changes: 2 additions & 2 deletions elk/training/ccs_reporter.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,12 +83,12 @@ class CcsReporter(Reporter):

def __init__(
self,
in_features: int,
cfg: CcsReporterConfig,
in_features: int,
device: Optional[str] = None,
dtype: Optional[torch.dtype] = None,
):
super().__init__(in_features, cfg, device=device, dtype=dtype)
super().__init__(cfg, in_features, device=device, dtype=dtype)

hidden_size = cfg.hidden_size or 4 * in_features // 3

Expand Down
7 changes: 3 additions & 4 deletions elk/training/eigen_reporter.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,9 @@ class EigenReporterConfig(ReporterConfig):
of eigenvectors to compute from the VINC matrix.
"""

var_weight: float = 1.0
inv_weight: float = 5.0
neg_cov_weight: float = 5.0
var_weight: float = 0.2
inv_weight: float = 1.0
neg_cov_weight: float = 1.0

num_heads: int = 1

Expand Down Expand Up @@ -100,7 +100,6 @@ def forward(self, x: Tensor) -> Tensor:

def predict(self, *hiddens: Tensor) -> Tensor:
"""Return the predicted logits on the contrast set `hiddens`."""
# breakpoint()
if len(hiddens) == 1:
return self(hiddens[0])

Expand Down
20 changes: 11 additions & 9 deletions elk/training/reporter.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,22 +90,22 @@ def __init__(
@classmethod
def check_separability(
cls,
train_pair: tuple[Tensor, Tensor],
val_pair: tuple[Tensor, Tensor],
train_hiddens: Tensor,
val_hiddens: Tensor,
) -> float:
"""Measure how linearly separable the pseudo-labels are for a contrast pair.

Args:
train_pair: A tuple of tensors, (x0, x1), where x0 and x1 are the
train_hiddens: Tensor of shape [n, ], where x0 and x1 are the
contrastive representations. Used for training the classifier.
val_pair: A tuple of tensors, (x0, x1), where x0 and x1 are the
contrastive representations. Used for evaluating the classifier.

Returns:
The AUROC of a linear classifier fit on the pseudo-labels.
"""
x0, x1 = train_pair
val_x0, val_x1 = val_pair
x0, x1 = train_hiddens
val_x0, val_x1 = val_hiddens

pseudo_clf = Classifier(x0.shape[-1], device=x0.device) # type: ignore
pseudo_train_labels = torch.cat(
Expand Down Expand Up @@ -198,13 +198,15 @@ def score(self, labels: Tensor, hiddens: Tensor) -> EvalResult:
to_one_hot(Y, n_classes=c).long().flatten()

if c == 2:
cal_err = CalibrationError().update(Y.cpu(), pred_probs.cpu()).compute().ece
pos_probs = pred_probs[..., 0].flatten()
cal_err = CalibrationError().update(Y.cpu(), pos_probs.cpu()).compute().ece

# Calibrated accuracy
cal_thresh = pred_probs.float().quantile(labels.float().mean())
cal_preds = pred_probs.gt(cal_thresh).squeeze(1).to(torch.int)
cal_thresh = pos_probs.float().quantile(labels.float().mean())
cal_preds = pos_probs.gt(cal_thresh).to(torch.int)
cal_acc = cal_preds.flatten().eq(Y).float().mean().item()

raw_preds = pred_probs.gt(0.5).squeeze(1).to(torch.int)
raw_preds = pos_probs.gt(0.5).to(torch.int)
else:
# TODO: Implement calibration error for k > 2?
cal_acc = 0.0
Expand Down
4 changes: 2 additions & 2 deletions elk/training/train.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,14 +90,14 @@ def train_reporter(
# pseudo_auroc = self.get_pseudo_auroc(layer, x0, x1, val_x0, val_x1)

if isinstance(self.cfg.net, CcsReporterConfig):
reporter = CcsReporter(d, self.cfg.net, device=device)
reporter = CcsReporter(self.cfg.net, d, device=device)
elif isinstance(self.cfg.net, EigenReporterConfig):
reporter = EigenReporter(self.cfg.net, d, c, device=device)
else:
raise ValueError(f"Unknown reporter config type: {type(self.cfg.net)}")

train_loss = reporter.fit(*train_h.unbind(2), labels=train_gt)
val_result = reporter.score(val_gt, val_h)
val_result = reporter.score(val_gt.to(device), val_h)

reporter_dir, lr_dir = self.create_models_dir(assert_type(Path, self.out_dir))
if val_lm_preds is not None:
Expand Down