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

Multi datasets #123

Merged
merged 46 commits into from
Mar 28, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
46 commits
Select commit Hold shift + click to select a range
681698d
add multiple datasets support
Benw8888 Mar 9, 2023
ac1b9f1
Merge branch 'main' of github.com:EleutherAI/elk into multi-datasets
Benw8888 Mar 9, 2023
b864c77
train_reporter works on a list of layers now
Benw8888 Mar 10, 2023
7d7d97c
changing printed layer names
Benw8888 Mar 10, 2023
4fe61e9
fixed concatenation bug
Benw8888 Mar 11, 2023
fe61d67
minor edits
Benw8888 Mar 13, 2023
74da878
fixed pyright issues
Benw8888 Mar 13, 2023
569ef05
Merge branch 'main' of github.com:EleutherAI/elk into multi-datasets
Benw8888 Mar 14, 2023
b62b679
Merge branch 'main' into multi-datasets
norabelrose Mar 20, 2023
fe94c22
Fix tests
norabelrose Mar 20, 2023
bba24d8
Now working sorta
norabelrose Mar 22, 2023
03ba6e0
Skip slow BalancedBatchSampler test
norabelrose Mar 22, 2023
15ab351
Slightly relax test_output_is_roughly_balanced
norabelrose Mar 22, 2023
a80369e
Make BalancedSampler deterministic
norabelrose Mar 22, 2023
d304ab3
InitVar
norabelrose Mar 22, 2023
761c82d
Support multi class again
norabelrose Mar 22, 2023
f29743b
Fix naming issue
norabelrose Mar 22, 2023
b7b7e23
Support few shot prompts
norabelrose Mar 23, 2023
1afb563
Merge branch 'main' into multi-datasets
norabelrose Mar 23, 2023
225d4c7
fix multiclass labels
AlexTMallen Mar 23, 2023
9368dc8
Merge branch 'multi-datasets' of github.com:EleutherAI/elk into multi…
AlexTMallen Mar 23, 2023
a858b65
Merge branch 'main' into multi-datasets
norabelrose Mar 24, 2023
5dc2ec6
Merge branch 'multi-datasets' of github.com:EleutherAI/elk into multi…
norabelrose Mar 24, 2023
b1b95e5
Fix dumb part of test failures
norabelrose Mar 25, 2023
ee3911e
Fix assert_allclose warning
norabelrose Mar 25, 2023
a55b3de
Switch to torch.testing.assert_close in EigenReporter test
norabelrose Mar 25, 2023
44dc25c
Shuffle load_prompts output by default
norabelrose Mar 25, 2023
93d8d87
Fix smoke test failure
norabelrose Mar 25, 2023
fad4d74
Remove debug prints
AlexTMallen Mar 25, 2023
0a054f4
Remove more debug print statements
AlexTMallen Mar 25, 2023
177eec2
make min_memory usable; broadcast mmax_examples in __post_init__
AlexTMallen Mar 26, 2023
3a762b0
prompt loading refactor to enable better streaming
AlexTMallen Mar 26, 2023
f66c054
remove shuffle arg
AlexTMallen Mar 26, 2023
d3d87fc
remove unused @dataclass
lauritowal Mar 26, 2023
3d08147
merge
lauritowal Mar 27, 2023
c9a43e1
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Mar 27, 2023
94290aa
add concatenated_layer_offset to eval
lauritowal Mar 27, 2023
f9298e4
Merge branch 'multi-datasets' of https://github.com/EleutherAI/elk in…
lauritowal Mar 27, 2023
3765c4f
add self.
lauritowal Mar 27, 2023
2b05193
replace target with data
lauritowal Mar 27, 2023
83731bb
add self.
lauritowal Mar 27, 2023
764fda9
remove second arg
lauritowal Mar 27, 2023
d2c66b0
fix passing the wrong params for world size / rank
thejaminator Mar 28, 2023
9186326
Update prompt_loading.py
lauritowal Mar 28, 2023
3f99a4d
fix pre-commit errors
lauritowal Mar 28, 2023
148130d
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Mar 28, 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
2 changes: 1 addition & 1 deletion elk/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
from .extraction import extract_hiddens, Extract, PromptDataset
from .extraction import extract_hiddens, Extract
4 changes: 3 additions & 1 deletion elk/__main__.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
"""Main entry point for `elk`."""

from dataclasses import dataclass
from pathlib import Path
from typing import Union

from simple_parsing import ArgumentParser

from elk.evaluation.evaluate import Eval
from elk.extraction.extraction import Extract

from elk.training.train import Elicit


Expand Down
Empty file added elk/evaluation/__init__.py
Empty file.
30 changes: 24 additions & 6 deletions elk/evaluation/evaluate.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,30 @@
import csv
import os
from dataclasses import dataclass
from functools import partial
from pathlib import Path
from typing import Literal, Optional, Callable
from typing import Callable, Literal, Optional, cast

import torch
from simple_parsing import Serializable, field
import torch.multiprocessing as mp
from simple_parsing.helpers import Serializable, field
from torch import Tensor
from tqdm.auto import tqdm

from datasets import DatasetDict
from elk.evaluation.evaluate_log import EvalLog
from elk.extraction.extraction import Extract
from elk.files import elk_reporter_dir
from elk.run import Run
from elk.training import Reporter
from elk.evaluation.evaluate_log import EvalLog
from elk.utils import select_usable_devices

from ..files import elk_reporter_dir, memorably_named_dir
from ..training.preprocessing import normalize
from ..utils import (
assert_type,
int16_to_float32,
select_train_val_splits,
select_usable_devices,
)


@dataclass
Expand Down Expand Up @@ -39,6 +52,8 @@ class Eval(Serializable):
out_dir: Optional[Path] = None
num_gpus: int = -1

concatenated_layer_offset: int = 0

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

Expand Down Expand Up @@ -80,7 +95,10 @@ def evaluate_reporter(

def evaluate(self):
"""Evaluate the reporter on all layers."""
devices = select_usable_devices(self.cfg.num_gpus)
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
Expand Down
3 changes: 2 additions & 1 deletion elk/extraction/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from .balanced_sampler import BalancedSampler, FewShotSampler
from .extraction import Extract, extract_hiddens, extract
from .generator import _GeneratorConfig, _GeneratorBuilder
from .prompt_dataset import PromptDataset, PromptConfig
from .prompt_loading import PromptConfig, load_prompts
93 changes: 93 additions & 0 deletions elk/extraction/balanced_sampler.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
from ..math_util import stochastic_round_constrained
from ..utils import infer_label_column
from collections import deque
from dataclasses import dataclass
from datasets import IterableDataset
from itertools import cycle
from random import Random
from torch.utils.data import IterableDataset as TorchIterableDataset
from typing import Iterator, Optional, Iterable


class BalancedSampler(TorchIterableDataset):
"""
Approximately balances a binary classification dataset in a streaming fashion.
Written mostly by GPT-4.

Args:
dataset (IterableDataset): The HuggingFace IterableDataset to balance.
label_col (Optional[str], optional): The name of the column containing the
binary label. If not provided, the label column will be inferred from
the dataset features. Defaults to None.
buffer_size (int, optional): The total buffer size to use for balancing the
dataset. This value should be divisible by 2, as it will be equally
divided between the two binary label values (0 and 1). Defaults to 1000.
"""

def __init__(self, data: Iterable[dict], buffer_size: int = 1000):
self.data = data

self.neg_buffer = deque(maxlen=buffer_size)
self.pos_buffer = deque(maxlen=buffer_size)

def __iter__(self):
for sample in self.data:
label = sample["label"]

# Add the sample to the appropriate buffer
if label == 0:
self.neg_buffer.append(sample)
else:
self.pos_buffer.append(sample)

while self.neg_buffer and self.pos_buffer:
yield self.neg_buffer.popleft()
yield self.pos_buffer.popleft()


class FewShotSampler:
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Any reason why you used @DataClass for the above class, but not here?

Copy link
Collaborator

@lauritowal lauritowal Mar 23, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I haven't had time yet to review the pull request in more detail and to test it. I can do that tomorrow evening, though.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah this is a little bit inconsistent but idk how much it matters

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Arguably FewShotSampler might be better if we make it not an iterator bc infinite iterators are weird

"""Yields batches of few-shot examples that are as balanced as possible.

If the number of examples is divisible by the number of shots, this sampler
will yield batches of exactly `num_shots` examples. Otherwise, it will
use `stochastic_round_constrained` to get as close to balanced batches as
possible.
"""

def __init__(
self,
dataset: IterableDataset,
num_shots: int,
rng: Random,
label_col: Optional[str] = None,
):
self.dataset = dataset
self.label_col = label_col or infer_label_column(dataset.features)
self.num_shots = num_shots
self.rng = rng

def __iter__(self) -> Iterator[list[dict]]:
neg_buf, pos_buf = [], []

# Infinite loop over the dataset!
for sample in cycle(self.dataset):
label = sample[self.label_col]
if label == 0:
neg_buf.append(sample)
elif label == 1:
pos_buf.append(sample)
else:
raise ValueError(f"Expected label to be 0 or 1, got {label}")
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So we don't support few-shot examples for dbpedia or ag_news (or multiclass datasets)? I guess this is fine until someone wants to do this.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah I don't want to think about how to support that rn


neg_count, pos_count = stochastic_round_constrained(
[self.num_shots / 2, self.num_shots / 2], self.rng
)
while len(neg_buf) >= neg_count and len(pos_buf) >= pos_count:
batch = []
for _ in range(neg_count):
batch.append(neg_buf.pop())
for _ in range(pos_count):
batch.append(pos_buf.pop())

self.rng.shuffle(batch)
yield batch
Loading