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
Various little refactors
  • Loading branch information
norabelrose committed Apr 11, 2023
commit 3e6626205d8133b4fac52f2abe9bff475707e34d
11 changes: 6 additions & 5 deletions elk/training/ccs_reporter.py
Original file line number Diff line number Diff line change
Expand Up @@ -164,10 +164,11 @@ def forward(self, x: Tensor) -> Tensor:
"""Return the raw score output of the probe on `x`."""
return self.probe(x).squeeze(-1)

def predict(self, x_pos: Tensor, x_neg: Tensor) -> Tensor:
return self.predict_prob(x_pos, x_neg).logit()
def predict(self, hiddens: Tensor) -> Tensor:
return self.predict_prob(hiddens).logit()

def predict_prob(self, x_pos: Tensor, x_neg: Tensor) -> Tensor:
def predict_prob(self, hiddens: Tensor) -> Tensor:
x_pos, x_neg = hiddens.unbind(2)
return 0.5 * (self(x_pos).sigmoid() + (1 - self(x_neg).sigmoid()))

def loss(
Expand Down Expand Up @@ -216,8 +217,7 @@ def loss(

def fit(
self,
x_pos: Tensor,
x_neg: Tensor,
hiddens: Tensor,
labels: Optional[Tensor] = None,
) -> float:
"""Fit the probe to the contrast pair (x0, x1).
Expand All @@ -236,6 +236,7 @@ def fit(
"""
# TODO: Implement normalization here to fix issue #96
# self.update(x_pos, x_neg)
x_pos, x_neg = hiddens.unbind(2)

# Record the best acc, loss, and params found so far
best_loss = torch.inf
Expand Down
101 changes: 46 additions & 55 deletions elk/training/eigen_reporter.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from torch import Tensor, nn, optim

from ..math_util import cov_mean_fused
from ..metrics import to_one_hot
from ..truncated_eigh import ConvergenceError, truncated_eigh
from .reporter import Reporter, ReporterConfig

Expand All @@ -19,18 +20,22 @@ class EigenReporterConfig(ReporterConfig):

Args:
var_weight: The weight of the variance term in the loss.
inv_weight: The weight of the invariance term in the loss.
neg_cov_weight: The weight of the negative covariance term in the loss.
num_heads: The number of reporter heads to fit. In other words, the number
of eigenvectors to compute from the VINC matrix.
"""

var_weight: float = 0.2
inv_weight: float = 1.0
neg_cov_weight: float = 1.0
var_weight: float = 0.1
neg_cov_weight: float = 0.5

num_heads: int = 1

def __post_init__(self):
if not (0 <= self.neg_cov_weight <= 1):
raise ValueError("neg_cov_weight must be in [0, 1]")
if self.num_heads <= 0:
raise ValueError("num_heads must be positive")


class EigenReporter(Reporter):
"""A linear reporter whose weights are computed via eigendecomposition.
Expand Down Expand Up @@ -93,24 +98,16 @@ def __init__(
torch.zeros(cfg.num_heads, in_features, device=device, dtype=dtype),
)

def forward(self, x: Tensor) -> Tensor:
def forward(self, hiddens: Tensor) -> Tensor:
"""Return the predicted log odds on input `x`."""
raw_scores = x @ self.weight.mT
raw_scores = hiddens @ self.weight.mT
return raw_scores.mul(self.scale).add(self.bias).squeeze(-1)

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

elif len(hiddens) == 2:
return 0.5 * (self(hiddens[0]) - self(hiddens[1]))
else:
return torch.stack(list(map(self, hiddens)), dim=-1)
predict = forward

def predict_prob(self, *hiddens: Tensor) -> Tensor:
def predict_prob(self, hiddens: Tensor) -> Tensor:
"""Return the predicted probabilities on the contrast set `hiddens`."""
logits = self.predict(*hiddens)
logits = self(hiddens)
if len(hiddens) == 2:
return logits.sigmoid()
else:
Expand All @@ -126,15 +123,15 @@ def intercluster_cov(self) -> Tensor:

@property
def confidence(self) -> Tensor:
return self.weight.mT @ self.intercluster_cov @ self.weight
return self.weight @ self.intercluster_cov @ self.weight.mT

@property
def invariance(self) -> Tensor:
return -self.weight.mT @ self.intracluster_cov @ self.weight
return -self.weight @ self.intracluster_cov @ self.weight.mT

@property
def consistency(self) -> Tensor:
return -self.weight.mT @ self.contrastive_xcov @ self.weight
return -self.weight @ self.contrastive_xcov @ self.weight.mT

def clear(self) -> None:
"""Clear the running statistics of the reporter."""
Expand All @@ -144,36 +141,33 @@ def clear(self) -> None:
self.n.zero_()

@torch.no_grad()
def update(self, *hiddens: Tensor) -> None:
k = len(hiddens)
assert k > 1, "Must provide at least two hidden states"
def update(self, hiddens: Tensor) -> None:
(n, _, k, d) = hiddens.shape

# Zero out shared info
hiddens = hiddens - hiddens.mean(dim=2, keepdim=True)

# Sanity checks
pivot, *rest = hiddens
assert pivot.ndim == 3, "hidden must be of shape [batch, num_variants, d]"
for h in rest:
assert h.shape == pivot.shape, "All hiddens must have the same shape"
assert k > 1, "Must provide at least two hidden states"
assert hiddens.ndim == 4, "Must be of shape [batch, variants, choices, dim]"

# We don't actually call super because we need access to the earlier estimate
# of the population mean in order to update (cross-)covariances properly
# super().update(x_pos, x_neg)
# super().update(hiddens)

sample_n = pivot.shape[0]
self.n += sample_n
self.n += n

# *** Invariance (intra-cluster) ***
# This is just a standard online *mean* update, since we're computing the
# mean of covariance matrices, not the covariance matrix of means.
sample_invar = sum(map(cov_mean_fused, hiddens)) / k
self.intracluster_cov += (sample_n / self.n) * (
sample_invar - self.intracluster_cov
)
intra_cov = cov_mean_fused(rearrange(hiddens, "n v k d -> (n k) v d"))
self.intracluster_cov += (n / self.n) * (intra_cov - self.intracluster_cov)

# [n, v, d] -> [n, d]
centroids = [h.mean(1) for h in hiddens]
# [n, v, k, d] -> [n, k, d]
centroids = hiddens.mean(1)
deltas, deltas2 = [], []

for i, h in enumerate(centroids):
for i, h in enumerate(centroids.unbind(1)):
# Update the running means; super().update() does this usually
delta = h - self.class_means[i]
self.class_means[i] += delta.sum(dim=0) / self.n
Expand All @@ -199,12 +193,12 @@ def update(self, *hiddens: Tensor) -> None:

def fit_streaming(self) -> float:
"""Fit the probe using the current streaming statistics."""
inv_weight = 1 - self.config.neg_cov_weight
A = (
self.config.var_weight * self.intercluster_cov
- self.config.inv_weight * self.intracluster_cov
- inv_weight * self.intracluster_cov
- self.config.neg_cov_weight * self.contrastive_xcov
)

try:
L, Q = truncated_eigh(A, k=self.config.num_heads)
except (ConvergenceError, RuntimeError):
Expand All @@ -221,48 +215,45 @@ def fit_streaming(self) -> float:

def fit(
self,
*hiddens: Tensor,
hiddens: Tensor,
labels: Optional[Tensor] = None,
) -> float:
"""Fit the probe to the contrast set `hiddens`.

Args:
hiddens: The contrast set of hidden states.
hiddens: The contrast set of shape [batch, variants, choices, dim].
labels: The ground truth labels if available.

Returns:
loss: Negative eigenvalue associated with the VINC direction.
"""
self.update(*hiddens)
self.update(hiddens)
loss = self.fit_streaming()

if labels is not None:
self.platt_scale(labels, *hiddens)
self.platt_scale(labels, hiddens)

return loss

def platt_scale(self, labels: Tensor, *hiddens: Tensor, max_iter: int = 100):
def platt_scale(self, labels: Tensor, hiddens: Tensor, max_iter: int = 100):
"""Fit the scale and bias terms to data with LBFGS."""

pivot, *_ = hiddens
opt = optim.LBFGS(
[self.bias, self.scale],
line_search_fn="strong_wolfe",
max_iter=max_iter,
tolerance_change=torch.finfo(pivot.dtype).eps,
tolerance_grad=torch.finfo(pivot.dtype).eps,
tolerance_change=torch.finfo(hiddens.dtype).eps,
tolerance_grad=torch.finfo(hiddens.dtype).eps,
)
labels = repeat(labels, "n -> (n v)", v=pivot.shape[1])
(_, v, k, _) = hiddens.shape
labels = to_one_hot(repeat(labels, "n -> (n v)", v=v), k)

def closure():
opt.zero_grad()
logits = rearrange(self.predict(*hiddens), "n v ... -> (n v) ...")
if len(logits.shape) == 1:
loss = nn.functional.binary_cross_entropy_with_logits(
logits, labels.float()
)
else:
loss = nn.functional.cross_entropy(logits, labels.long())
logits = rearrange(self(hiddens), "n v k -> (n v) k")
loss = nn.functional.binary_cross_entropy_with_logits(
logits, labels.float()
)

loss.backward()
return float(loss)
Expand Down
2 changes: 1 addition & 1 deletion elk/training/preprocessing.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ def normalize(
val_hiddens -= means

if method == "elementwise":
scale = 1 / train_hiddens.norm(dim=0, keepdim=True)
scale = 1 / train_hiddens.std(dim=0, keepdim=True)
elif method == "meanonly":
scale = 1
else:
Expand Down
8 changes: 4 additions & 4 deletions elk/training/reporter.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,17 +165,17 @@ def save(self, path: Path | str):
@abstractmethod
def fit(
self,
*hiddens: Tensor,
hiddens: Tensor,
labels: Optional[Tensor] = None,
) -> float:
...

@abstractmethod
def predict(self, *hiddens: Tensor) -> Tensor:
def predict(self, hiddens: Tensor) -> Tensor:
"""Return pooled logits for the contrast set `hiddens`."""

@abstractmethod
def predict_prob(self, *hiddens: Tensor) -> Tensor:
def predict_prob(self, hiddens: Tensor) -> Tensor:
"""Like `predict` but returns normalized probabilities, not logits."""

@torch.no_grad()
Expand All @@ -198,7 +198,7 @@ def score(self, labels: Tensor, hiddens: Tensor) -> EvalResult:
to_one_hot(Y, n_classes=c).long().flatten()

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

# Calibrated accuracy
Expand Down
2 changes: 1 addition & 1 deletion elk/training/train.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ def train_reporter(
else:
raise ValueError(f"Unknown reporter config type: {type(self.cfg.net)}")

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

reporter_dir, lr_dir = self.create_models_dir(assert_type(Path, self.out_dir))
Expand Down