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
isort
  • Loading branch information
norabelrose committed Apr 5, 2023
commit 77d74185df510e329ccafff789a733d37934dd0c
2 changes: 1 addition & 1 deletion elk/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
from .extraction import extract_hiddens, Extract
from .extraction import Extract, extract_hiddens

__all__ = ["extract_hiddens", "Extract"]
5 changes: 3 additions & 2 deletions elk/calibration.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import warnings
from dataclasses import dataclass, field
from torch import Tensor
from typing import NamedTuple

import torch
import warnings
from torch import Tensor


class CalibrationEstimate(NamedTuple):
Expand Down
3 changes: 2 additions & 1 deletion elk/eigsh.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
from torch import Tensor
from typing import Literal, Optional

import torch
import torch.nn.functional as F
from torch import Tensor


def lanczos_eigsh(
Expand Down
30 changes: 16 additions & 14 deletions elk/evaluation/evaluate.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
from ..extraction import Extract
from ..files import elk_reporter_dir
from ..run import Run
from ..training import Reporter
from ..utils import select_usable_devices
from .evaluate_log import EvalLog
from dataclasses import dataclass
from functools import partial
from pathlib import Path
from simple_parsing.helpers import Serializable, field
from typing import Callable, Literal, Optional

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

from ..extraction import Extract
from ..files import elk_reporter_dir
from ..run import Run
from ..training import Reporter
from ..utils import select_usable_devices


@dataclass
Expand Down Expand Up @@ -52,7 +54,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 @@ -73,9 +75,11 @@ def evaluate_reporter(
test_x1,
)

return EvalLog(
layer=layer,
eval_result=test_result,
return pd.Series(
{
"layer": layer,
**test_result._asdict(),
}
)

def evaluate(self):
Expand All @@ -85,12 +89,10 @@ 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(),
)
27 changes: 0 additions & 27 deletions elk/evaluation/evaluate_log.py

This file was deleted.

4 changes: 2 additions & 2 deletions elk/extraction/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from .balanced_sampler import BalancedSampler, FewShotSampler
from .extraction import Extract, extract_hiddens, extract
from .generator import _GeneratorConfig, _GeneratorBuilder
from .extraction import Extract, extract, extract_hiddens
from .generator import _GeneratorBuilder, _GeneratorConfig
from .prompt_loading import PromptConfig, load_prompts

__all__ = [
Expand Down
12 changes: 7 additions & 5 deletions elk/extraction/balanced_sampler.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
from ..math_util import stochastic_round_constrained
from ..utils import infer_label_column
from ..utils.typing import assert_type
from collections import deque
from datasets import IterableDataset, Features
from itertools import cycle
from random import Random
from typing import Iterable, Iterator, Optional

from datasets import Features, IterableDataset
from torch.utils.data import IterableDataset as TorchIterableDataset
from typing import Iterator, Optional, Iterable

from ..math_util import stochastic_round_constrained
from ..utils import infer_label_column
from ..utils.typing import assert_type


class BalancedSampler(TorchIterableDataset):
Expand Down
12 changes: 6 additions & 6 deletions elk/extraction/extraction.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
"""Functions for extracting the hidden states of a model."""
import logging
import os
from dataclasses import InitVar, dataclass
from itertools import islice
from typing import Iterable, Literal, Optional, Union

import torch
from datasets import (
Array3D,
ClassLabel,
Expand All @@ -11,18 +17,12 @@
Value,
get_dataset_config_info,
)
from itertools import islice
from simple_parsing import Serializable, field
from torch import Tensor
from transformers import AutoConfig, AutoTokenizer
from transformers.modeling_outputs import Seq2SeqLMOutput
from typing import Iterable, Literal, Optional, Union
import logging
import os
import torch

# import torch.nn.functional as F

from ..utils import (
assert_type,
convert_span,
Expand Down
2 changes: 1 addition & 1 deletion elk/extraction/generator.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from dataclasses import dataclass, field
from typing import Callable, Optional, Any, Dict
from typing import Any, Callable, Dict, Optional

import datasets
from datasets.splits import NamedSplit
Expand Down
22 changes: 12 additions & 10 deletions elk/extraction/prompt_loading.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,15 @@
from dataclasses import dataclass
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
from simple_parsing.helpers import Serializable, field

from ..promptsource import DatasetTemplates
from ..utils import (
assert_type,
Expand All @@ -7,16 +19,6 @@
select_train_val_splits,
)
from .balanced_sampler import FewShotSampler
from dataclasses import dataclass
from datasets import (
load_dataset,
Dataset,
Features,
)
from datasets.distributed import split_dataset_by_node
from random import Random
from simple_parsing.helpers import field, Serializable
from typing import Any, Iterator, Literal, Optional


@dataclass
Expand Down
4 changes: 2 additions & 2 deletions elk/files.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
"""Helper functions for dealing with files."""

from pathlib import Path
import json
import os
import random
from pathlib import Path
from typing import Optional

from simple_parsing import Serializable
import yaml
from simple_parsing import Serializable


def elk_reporter_dir() -> Path:
Expand Down
1 change: 1 addition & 0 deletions elk/logging.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import logging

from .utils import select_train_val_splits


Expand Down
3 changes: 2 additions & 1 deletion elk/math_util.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
from torch import Tensor
import math
import random

import torch
from torch import Tensor


@torch.jit.script
Expand Down
1 change: 1 addition & 0 deletions elk/parsing.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import re

from .training.losses import LOSSES


Expand Down
12 changes: 6 additions & 6 deletions elk/promptsource/templates.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
from collections import Counter, defaultdict
from jinja2 import BaseLoader, Environment, meta
from pathlib import Path
from shutil import rmtree
from typing import Optional
import logging
import os
import random
import uuid
import yaml
from collections import Counter, defaultdict
from pathlib import Path
from shutil import rmtree
from typing import Optional

import yaml
from jinja2 import BaseLoader, Environment, meta

# Truncation of jinja template variables
# 1710 = 300 words x 4.7 avg characters per word + 300 spaces
Expand Down
52 changes: 23 additions & 29 deletions elk/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,29 +5,29 @@
from pathlib import Path
from typing import (
TYPE_CHECKING,
Callable,
Optional,
Union,
Callable,
Iterator,
)

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 elk.extraction.extraction import extract
from elk.files import create_output_directory, save_config, save_meta
from elk.training.preprocessing import normalize
from elk.utils.csv import write_iterator_to_file, Log
from elk.utils.data_utils import get_layers, select_train_val_splits
from elk.utils.typing import assert_type, int16_to_float32
from .extraction import extract
from .files import create_output_directory, save_config, save_meta
from .logging import save_debug_log
from .training.preprocessing import normalize
from .utils import assert_type, int16_to_float32
from .utils.data_utils import get_layers, select_train_val_splits

if TYPE_CHECKING:
from elk.evaluation.evaluate import Eval
from elk.training.train import Elicit
from .evaluation.evaluate import Eval
from .training.train import Elicit


@dataclass
Expand Down Expand Up @@ -103,10 +103,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 @@ -115,10 +113,7 @@ def apply_to_layers(
func: The function to apply to each layer.
The int is the index of the layer.
num_devices: The number of devices to use.
to_csv_line: A function that converts a Log to a list of strings.
This has to be injected in because the Run class does not know
the extra options e.g. skip_baseline to apply to function.
csv_columns: The columns of the CSV file."""
"""
self.out_dir = assert_type(Path, self.out_dir)

layers: list[int] = get_layers(self.dataset)
Expand All @@ -129,15 +124,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)
1 change: 0 additions & 1 deletion elk/training/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
from .eigen_reporter import EigenReporter, EigenReporterConfig
from .reporter import OptimConfig, Reporter, ReporterConfig


__all__ = [
"Reporter",
"ReporterConfig",
Expand Down
Loading