bertuner 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- bertuner/BERTuner.py +818 -0
- bertuner/CustomTrainer.py +109 -0
- bertuner/Predictor.py +90 -0
- bertuner/TensorBoardCallback.py +39 -0
- bertuner/__init__.py +17 -0
- bertuner/constants.py +64 -0
- bertuner/utils.py +99 -0
- bertuner-0.1.0.dist-info/METADATA +200 -0
- bertuner-0.1.0.dist-info/RECORD +12 -0
- bertuner-0.1.0.dist-info/WHEEL +5 -0
- bertuner-0.1.0.dist-info/licenses/LICENSE +21 -0
- bertuner-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
from transformers import Trainer
|
|
2
|
+
import torch
|
|
3
|
+
import torch.nn.functional as F
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class CustomTrainer(Trainer):
|
|
7
|
+
"""Trainer supporting single-label (CE/focal/label-smoothing) and multi-label (BCE) classification."""
|
|
8
|
+
|
|
9
|
+
def __init__(self, loss_type="focal", class_weights=None, **kwargs):
|
|
10
|
+
super().__init__(**kwargs)
|
|
11
|
+
self.loss_type = loss_type
|
|
12
|
+
self.class_weights = class_weights
|
|
13
|
+
|
|
14
|
+
def _is_multilabel(self, labels: torch.Tensor) -> bool:
|
|
15
|
+
"""Multi-label labels are 2D float vectors; single-label are 1D integer class indices."""
|
|
16
|
+
return labels.dim() == 2
|
|
17
|
+
|
|
18
|
+
def focal_loss(self, logits, labels, alpha=0.25, gamma=2.0):
|
|
19
|
+
"""Focal loss with -100 ignore-index handling."""
|
|
20
|
+
num_classes = logits.size(-1)
|
|
21
|
+
|
|
22
|
+
# Flatten in case of token-level output [B, seq_len, C] → [B*seq_len, C]
|
|
23
|
+
logits = logits.view(-1, num_classes)
|
|
24
|
+
labels = labels.view(-1)
|
|
25
|
+
|
|
26
|
+
ignore_mask = labels == -100
|
|
27
|
+
safe_labels = labels.clone()
|
|
28
|
+
safe_labels[ignore_mask] = 0 # temp placeholder, masked out below
|
|
29
|
+
|
|
30
|
+
ce_loss = F.cross_entropy(logits, safe_labels, reduction="none")
|
|
31
|
+
pt = torch.exp(-ce_loss)
|
|
32
|
+
focal = alpha * (1 - pt) ** gamma * ce_loss
|
|
33
|
+
|
|
34
|
+
focal = focal.masked_fill(ignore_mask, 0.0)
|
|
35
|
+
n_valid = (~ignore_mask).sum().clamp(min=1)
|
|
36
|
+
return focal.sum() / n_valid
|
|
37
|
+
|
|
38
|
+
def label_smoothing_loss(self, logits, labels, smoothing=0.1):
|
|
39
|
+
"""Label smoothing with -100 ignore-index handling."""
|
|
40
|
+
num_classes = logits.size(-1)
|
|
41
|
+
|
|
42
|
+
logits = logits.view(-1, num_classes)
|
|
43
|
+
labels = labels.view(-1)
|
|
44
|
+
|
|
45
|
+
ignore_mask = labels == -100
|
|
46
|
+
safe_labels = labels.clone()
|
|
47
|
+
safe_labels[ignore_mask] = 0
|
|
48
|
+
|
|
49
|
+
log_probs = F.log_softmax(logits, dim=-1)
|
|
50
|
+
nll_loss = F.nll_loss(log_probs, safe_labels, reduction="none")
|
|
51
|
+
smooth_loss = -log_probs.mean(dim=-1)
|
|
52
|
+
loss = (1 - smoothing) * nll_loss + smoothing * smooth_loss
|
|
53
|
+
|
|
54
|
+
loss = loss.masked_fill(ignore_mask, 0.0)
|
|
55
|
+
n_valid = (~ignore_mask).sum().clamp(min=1)
|
|
56
|
+
return loss.sum() / n_valid
|
|
57
|
+
|
|
58
|
+
def _multilabel_loss(self, logits, labels, device):
|
|
59
|
+
"""BCEWithLogitsLoss with optional per-label pos_weight for class imbalance."""
|
|
60
|
+
pos_weight = self.class_weights.to(device) if self.class_weights is not None else None
|
|
61
|
+
loss_fct = torch.nn.BCEWithLogitsLoss(pos_weight=pos_weight)
|
|
62
|
+
return loss_fct(logits, labels.float())
|
|
63
|
+
|
|
64
|
+
def _singlelabel_loss(self, logits, labels, device):
|
|
65
|
+
"""Dispatches to the configured single-label loss."""
|
|
66
|
+
if self.loss_type == "focal":
|
|
67
|
+
return self.focal_loss(logits, labels)
|
|
68
|
+
elif self.loss_type == "weighted":
|
|
69
|
+
weight = self.class_weights.to(device) if self.class_weights is not None else None
|
|
70
|
+
loss_fct = torch.nn.CrossEntropyLoss(weight=weight, ignore_index=-100)
|
|
71
|
+
return loss_fct(logits.view(-1, logits.size(-1)), labels.view(-1))
|
|
72
|
+
elif self.loss_type == "label_smoothing":
|
|
73
|
+
return self.label_smoothing_loss(logits, labels)
|
|
74
|
+
else:
|
|
75
|
+
return F.cross_entropy(
|
|
76
|
+
logits.view(-1, logits.size(-1)),
|
|
77
|
+
labels.view(-1),
|
|
78
|
+
ignore_index=-100,
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None):
|
|
82
|
+
device = next(model.parameters()).device
|
|
83
|
+
labels = inputs.pop("labels")
|
|
84
|
+
if torch.is_tensor(labels):
|
|
85
|
+
labels = labels.to(device)
|
|
86
|
+
inputs = {k: v.to(device) if torch.is_tensor(v) else v for k, v in inputs.items()}
|
|
87
|
+
|
|
88
|
+
outputs = model(**inputs)
|
|
89
|
+
logits = outputs.logits
|
|
90
|
+
|
|
91
|
+
# ── Label sanity check (catches mismatches early, CPU-side) ──────────
|
|
92
|
+
if not self._is_multilabel(labels):
|
|
93
|
+
valid_mask = labels != -100
|
|
94
|
+
if valid_mask.any():
|
|
95
|
+
label_max = labels[valid_mask].max().item()
|
|
96
|
+
num_classes = logits.size(-1)
|
|
97
|
+
if label_max >= num_classes:
|
|
98
|
+
raise ValueError(
|
|
99
|
+
f"Label value {label_max} is out of range for "
|
|
100
|
+
f"num_labels={num_classes}. Check your label encoding."
|
|
101
|
+
)
|
|
102
|
+
# ─────────────────────────────────────────────────────────────────────
|
|
103
|
+
|
|
104
|
+
if self._is_multilabel(labels):
|
|
105
|
+
loss = self._multilabel_loss(logits, labels, device)
|
|
106
|
+
else:
|
|
107
|
+
loss = self._singlelabel_loss(logits, labels, device)
|
|
108
|
+
|
|
109
|
+
return (loss, outputs) if return_outputs else loss
|
bertuner/Predictor.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import json
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
import pandas as pd
|
|
5
|
+
import torch
|
|
6
|
+
import torch.nn.functional as F
|
|
7
|
+
from transformers import AutoTokenizer, AutoModelForSequenceClassification
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class BERTunePredictor:
|
|
11
|
+
"""
|
|
12
|
+
Loads a model directory saved by BERTuneClassifier.train_final_model()
|
|
13
|
+
and runs inference with the thresholds optimised during training.
|
|
14
|
+
|
|
15
|
+
Usage:
|
|
16
|
+
predictor = BERTunePredictor("models/BERTModels/final_model/model")
|
|
17
|
+
preds = predictor.predict(["some text", "other text"])
|
|
18
|
+
probs = predictor.predict_proba(["some text"])
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
def __init__(self, model_dir: str, device: str = None, batch_size: int = 32):
|
|
22
|
+
with open(f"{model_dir}/bertuner_config.json") as f:
|
|
23
|
+
self.config = json.load(f)
|
|
24
|
+
|
|
25
|
+
meta = self.config["model_metadata"]
|
|
26
|
+
self.is_multilabel = meta["is_multilabel"]
|
|
27
|
+
self.target_cols = meta["target_cols"]
|
|
28
|
+
self.max_length = meta.get("max_length", 512)
|
|
29
|
+
|
|
30
|
+
threshold = meta["optimal_threshold"]
|
|
31
|
+
self.threshold = np.array(threshold) if isinstance(threshold, list) else threshold
|
|
32
|
+
|
|
33
|
+
self.batch_size = batch_size
|
|
34
|
+
self.device = torch.device(
|
|
35
|
+
device or ("cuda" if torch.cuda.is_available() else "cpu")
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
use_fast = "deberta" not in meta.get("model_path", "").lower()
|
|
39
|
+
self.tokenizer = AutoTokenizer.from_pretrained(model_dir, use_fast=use_fast)
|
|
40
|
+
self.model = AutoModelForSequenceClassification.from_pretrained(model_dir)
|
|
41
|
+
self.model.to(self.device)
|
|
42
|
+
self.model.eval()
|
|
43
|
+
|
|
44
|
+
@torch.no_grad()
|
|
45
|
+
def _logits(self, texts: list[str]) -> torch.Tensor:
|
|
46
|
+
batches = []
|
|
47
|
+
for i in range(0, len(texts), self.batch_size):
|
|
48
|
+
enc = self.tokenizer(
|
|
49
|
+
texts[i : i + self.batch_size],
|
|
50
|
+
truncation=True,
|
|
51
|
+
padding=True,
|
|
52
|
+
max_length=self.max_length,
|
|
53
|
+
return_tensors="pt",
|
|
54
|
+
).to(self.device)
|
|
55
|
+
batches.append(self.model(**enc).logits.cpu())
|
|
56
|
+
return torch.cat(batches)
|
|
57
|
+
|
|
58
|
+
def predict_proba(self, texts: str | list[str]) -> np.ndarray:
|
|
59
|
+
"""
|
|
60
|
+
Probabilities per input.
|
|
61
|
+
Single-label → softmax over classes, shape (N, num_classes)
|
|
62
|
+
Multi-label → sigmoid per label, shape (N, num_labels)
|
|
63
|
+
"""
|
|
64
|
+
if isinstance(texts, str):
|
|
65
|
+
texts = [texts]
|
|
66
|
+
logits = self._logits(texts)
|
|
67
|
+
if self.is_multilabel:
|
|
68
|
+
return torch.sigmoid(logits).numpy()
|
|
69
|
+
return F.softmax(logits, dim=-1).numpy()
|
|
70
|
+
|
|
71
|
+
def predict(self, texts: str | list[str]) -> np.ndarray:
|
|
72
|
+
"""
|
|
73
|
+
Class predictions using the training-time optimised threshold(s).
|
|
74
|
+
Binary single-label → 0/1 via threshold on positive-class probability
|
|
75
|
+
Multiclass → argmax (threshold not applicable)
|
|
76
|
+
Multi-label → per-label 0/1 via per-label thresholds, shape (N, num_labels)
|
|
77
|
+
"""
|
|
78
|
+
probs = self.predict_proba(texts)
|
|
79
|
+
if self.is_multilabel:
|
|
80
|
+
return (probs >= self.threshold).astype(int)
|
|
81
|
+
if probs.shape[1] == 2:
|
|
82
|
+
return (probs[:, 1] >= self.threshold).astype(int)
|
|
83
|
+
return probs.argmax(axis=1)
|
|
84
|
+
|
|
85
|
+
def predict_df(self, texts: str | list[str]) -> pd.DataFrame:
|
|
86
|
+
"""Predictions as a DataFrame with one column per target."""
|
|
87
|
+
preds = self.predict(texts)
|
|
88
|
+
if self.is_multilabel:
|
|
89
|
+
return pd.DataFrame(preds, columns=self.target_cols)
|
|
90
|
+
return pd.DataFrame({self.target_cols[0]: preds})
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import shutil
|
|
3
|
+
from transformers import TrainerCallback
|
|
4
|
+
from torch.utils.tensorboard import SummaryWriter
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class CleanupCheckpointsCallback(TrainerCallback):
|
|
8
|
+
def on_train_end(self, args, state, control, **kwargs):
|
|
9
|
+
best_ckpt = state.best_model_checkpoint
|
|
10
|
+
for name in os.listdir(args.output_dir):
|
|
11
|
+
path = os.path.join(args.output_dir, name)
|
|
12
|
+
if name.startswith("checkpoint‐") and path != best_ckpt:
|
|
13
|
+
shutil.rmtree(path)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class TensorBoardSyncCallback(TrainerCallback):
|
|
17
|
+
def __init__(self, log_dir, writer_cls=None):
|
|
18
|
+
# Allow dependency injection for custom writers (e.g., testing or alternative loggers).
|
|
19
|
+
writer_cls = writer_cls or SummaryWriter
|
|
20
|
+
self.writer = writer_cls(log_dir)
|
|
21
|
+
self.last_train_loss = None
|
|
22
|
+
|
|
23
|
+
def on_log(self, args, state, control, logs=None, **kwargs):
|
|
24
|
+
step = state.global_step
|
|
25
|
+
|
|
26
|
+
# remember most recent train loss
|
|
27
|
+
if "loss" in logs:
|
|
28
|
+
self.last_train_loss = logs["loss"]
|
|
29
|
+
|
|
30
|
+
# when eval happens, log both at once
|
|
31
|
+
if "eval_loss" in logs and self.last_train_loss is not None:
|
|
32
|
+
self.writer.add_scalars(
|
|
33
|
+
"Loss", # main tag
|
|
34
|
+
{"train": self.last_train_loss, "eval": logs["eval_loss"]},
|
|
35
|
+
step,
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
def on_train_end(self, args, state, control, **kwargs):
|
|
39
|
+
self.writer.close()
|
bertuner/__init__.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"""bertuner: hyperparameter optimization and fine-tuning for BERT-style text classifiers."""
|
|
2
|
+
|
|
3
|
+
__version__ = "0.1.0"
|
|
4
|
+
|
|
5
|
+
from bertuner.Predictor import BERTunePredictor
|
|
6
|
+
|
|
7
|
+
__all__ = ["BERTuneClassifier", "BERTunePredictor", "__version__"]
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def __getattr__(name):
|
|
11
|
+
# Lazy import: BERTuneClassifier pulls training-only deps (optuna, mlflow,
|
|
12
|
+
# datasets), which are optional extras — inference installs must not need them.
|
|
13
|
+
if name == "BERTuneClassifier":
|
|
14
|
+
from bertuner.BERTuner import BERTuneClassifier
|
|
15
|
+
|
|
16
|
+
return BERTuneClassifier
|
|
17
|
+
raise AttributeError(f"module 'bertuner' has no attribute '{name}'")
|
bertuner/constants.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
SEED = 42
|
|
2
|
+
DEFAULT_MODEL_CHOICES = {
|
|
3
|
+
"bioclinicalbert": "emilyalsentzer/Bio_ClinicalBERT",
|
|
4
|
+
"roberta-base": "roberta-base",
|
|
5
|
+
"distilbert": "distilbert-base-uncased",
|
|
6
|
+
"bert-base": "bert-base-uncased",
|
|
7
|
+
"electra-small": "google/electra-small-discriminator",
|
|
8
|
+
"electra-base": "google/electra-base-discriminator",
|
|
9
|
+
"modernbert-base": "answerdotai/ModernBERT-base",
|
|
10
|
+
"modernbert-large": "answerdotai/ModernBERT-large",
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
# Dropout attribute names per architecture (config.model_type).
|
|
14
|
+
# "default" covers BERT/RoBERTa/ELECTRA-style configs.
|
|
15
|
+
MODEL_DROPOUT_ATTRS = {
|
|
16
|
+
"distilbert": ("dropout", "attention_dropout", "seq_classif_dropout"),
|
|
17
|
+
"modernbert": (
|
|
18
|
+
"attention_dropout",
|
|
19
|
+
"mlp_dropout",
|
|
20
|
+
"classifier_dropout",
|
|
21
|
+
"embedding_dropout",
|
|
22
|
+
),
|
|
23
|
+
"default": (
|
|
24
|
+
"hidden_dropout_prob",
|
|
25
|
+
"attention_probs_dropout_prob",
|
|
26
|
+
"classifier_dropout",
|
|
27
|
+
),
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
DEFAULT_SEARCH_SPACE_SINGLELABEL = {
|
|
31
|
+
"model": ["bioclinicalbert", "bert-base", "roberta-base", "distilbert"],
|
|
32
|
+
"learning_rate": {"low": 1e-6, "high": 5e-5, "log": True},
|
|
33
|
+
"batch_size": [8, 16, 32],
|
|
34
|
+
"loss_type": ["weighted", "focal", "label_smoothing"],
|
|
35
|
+
"label_smoothing": {"low": 0.0, "high": 0.1},
|
|
36
|
+
"focal_gamma": {"low": 1.0, "high": 3.0},
|
|
37
|
+
"weight_decay": {"low": 0.0, "high": 0.2},
|
|
38
|
+
"warmup_ratio": {"low": 0.0, "high": 0.2},
|
|
39
|
+
"scheduler": ["linear", "cosine"],
|
|
40
|
+
"dropout": {"low": 0.0, "high": 0.3},
|
|
41
|
+
"early_stopping_patience": {"low": 3, "high": 8},
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
DEFAULT_SEARCH_SPACE_MULTILABEL = {
|
|
45
|
+
"model": ["bioclinicalbert", "bert-base", "roberta-base", "distilbert"],
|
|
46
|
+
"learning_rate": {"low": 1e-6, "high": 5e-5, "log": True},
|
|
47
|
+
"batch_size": [8, 16, 32],
|
|
48
|
+
"weight_decay": {"low": 0.0, "high": 0.2},
|
|
49
|
+
"warmup_ratio": {"low": 0.0, "high": 0.2},
|
|
50
|
+
"scheduler": ["linear", "cosine"],
|
|
51
|
+
"dropout": {"low": 0.0, "high": 0.3},
|
|
52
|
+
"early_stopping_patience": {"low": 3, "high": 8},
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
# Long-context models (e.g. ModernBERT, 8192 tokens): tiny per-device batches with
|
|
56
|
+
# gradient accumulation so the effective batch size stays in the usual 8-32 range.
|
|
57
|
+
DEFAULT_SEARCH_SPACE_LONGCONTEXT = {
|
|
58
|
+
**DEFAULT_SEARCH_SPACE_SINGLELABEL,
|
|
59
|
+
"model": ["modernbert-base", "modernbert-large"],
|
|
60
|
+
"batch_size": [1, 2, 4],
|
|
61
|
+
"gradient_accumulation_steps": [4, 8, 16],
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
DEFAULT_SEARCH_SPACE = DEFAULT_SEARCH_SPACE_SINGLELABEL # backwards-compatible default
|
bertuner/utils.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import pandas as pd
|
|
2
|
+
|
|
3
|
+
from sklearn.model_selection import StratifiedGroupKFold, train_test_split
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def train_val_test_split(
|
|
7
|
+
X,
|
|
8
|
+
y,
|
|
9
|
+
train_size=0.7,
|
|
10
|
+
validation_size=0.15,
|
|
11
|
+
test_size=0.15,
|
|
12
|
+
random_state=42,
|
|
13
|
+
stratify_y=True,
|
|
14
|
+
):
|
|
15
|
+
"""Two-stage stratified train/val/test split.
|
|
16
|
+
|
|
17
|
+
Returns X_train, X_val, X_test, y_train, y_val, y_test in the same
|
|
18
|
+
order as the model_tuner function this replaces.
|
|
19
|
+
"""
|
|
20
|
+
total = train_size + validation_size + test_size
|
|
21
|
+
if abs(total - 1.0) > 1e-6:
|
|
22
|
+
raise ValueError(f"train/validation/test sizes must sum to 1, got {total}")
|
|
23
|
+
|
|
24
|
+
holdout = validation_size + test_size
|
|
25
|
+
X_train, X_tmp, y_train, y_tmp = train_test_split(
|
|
26
|
+
X,
|
|
27
|
+
y,
|
|
28
|
+
test_size=holdout,
|
|
29
|
+
random_state=random_state,
|
|
30
|
+
stratify=y if stratify_y else None,
|
|
31
|
+
)
|
|
32
|
+
X_val, X_test, y_val, y_test = train_test_split(
|
|
33
|
+
X_tmp,
|
|
34
|
+
y_tmp,
|
|
35
|
+
test_size=test_size / holdout,
|
|
36
|
+
random_state=random_state,
|
|
37
|
+
stratify=y_tmp if stratify_y else None,
|
|
38
|
+
)
|
|
39
|
+
return X_train, X_val, X_test, y_train, y_val, y_test
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def split_group_stratified(df, group_col, y_col, seed=42, test_size=0.15, val_size=0.15):
|
|
43
|
+
groups = df[group_col].astype(str).str.strip().str.casefold().values
|
|
44
|
+
y = df[y_col].values
|
|
45
|
+
|
|
46
|
+
# First split: train vs temp (val+test)
|
|
47
|
+
temp_size = test_size + val_size
|
|
48
|
+
n_splits = int(round(1 / temp_size))
|
|
49
|
+
n_splits = max(n_splits, 2)
|
|
50
|
+
|
|
51
|
+
sgkf = StratifiedGroupKFold(n_splits=n_splits, shuffle=True, random_state=seed)
|
|
52
|
+
train_idx, temp_idx = next(sgkf.split(df, y, groups=groups))
|
|
53
|
+
|
|
54
|
+
temp_df = df.iloc[temp_idx].copy()
|
|
55
|
+
temp_groups = temp_df[group_col].astype(str).str.strip().str.casefold().values
|
|
56
|
+
temp_y = temp_df[y_col].values
|
|
57
|
+
|
|
58
|
+
# Second split: val vs test (split temp)
|
|
59
|
+
test_frac_of_temp = test_size / temp_size
|
|
60
|
+
n_splits2 = int(round(1 / test_frac_of_temp))
|
|
61
|
+
n_splits2 = max(n_splits2, 2)
|
|
62
|
+
|
|
63
|
+
# StratifiedGroupKFold is heuristic and can produce a single-class fold;
|
|
64
|
+
# retry with a bumped seed until val and test both contain every class.
|
|
65
|
+
for attempt in range(10):
|
|
66
|
+
sgkf2 = StratifiedGroupKFold(
|
|
67
|
+
n_splits=n_splits2, shuffle=True, random_state=seed + 1 + attempt
|
|
68
|
+
)
|
|
69
|
+
val_rel_idx, test_rel_idx = next(sgkf2.split(temp_df, temp_y, groups=temp_groups))
|
|
70
|
+
if len(set(temp_y[val_rel_idx])) > 1 and len(set(temp_y[test_rel_idx])) > 1:
|
|
71
|
+
break
|
|
72
|
+
|
|
73
|
+
val_idx = temp_df.index[val_rel_idx]
|
|
74
|
+
test_idx = temp_df.index[test_rel_idx]
|
|
75
|
+
|
|
76
|
+
train_df = df.iloc[train_idx].copy()
|
|
77
|
+
val_df = df.loc[val_idx].copy()
|
|
78
|
+
test_df = df.loc[test_idx].copy()
|
|
79
|
+
|
|
80
|
+
return train_df, val_df, test_df
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def check_group_leakage(train_df, val_df, test_df, group_col):
|
|
84
|
+
train_q = set(train_df[group_col])
|
|
85
|
+
val_q = set(val_df[group_col])
|
|
86
|
+
test_q = set(test_df[group_col])
|
|
87
|
+
|
|
88
|
+
overlap_tv = train_q & val_q
|
|
89
|
+
overlap_tt = train_q & test_q
|
|
90
|
+
overlap_vt = val_q & test_q
|
|
91
|
+
|
|
92
|
+
print("Train ∩ Val:", len(overlap_tv))
|
|
93
|
+
print("Train ∩ Test:", len(overlap_tt))
|
|
94
|
+
print("Val ∩ Test:", len(overlap_vt))
|
|
95
|
+
|
|
96
|
+
if overlap_tv or overlap_tt or overlap_vt:
|
|
97
|
+
print("\nWARNING!! ___====Leakage detected!====___")
|
|
98
|
+
else:
|
|
99
|
+
print("\nVERIFIED: No group leakage across splits.")
|
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: bertuner
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Hyperparameter optimization and fine-tuning for BERT-style text classifiers (Optuna + MLflow), with long-context ModernBERT support
|
|
5
|
+
Author-email: elemets <alafunnell@gmail.com>
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/elemets/bertuner
|
|
8
|
+
Project-URL: Repository, https://github.com/elemets/bertuner
|
|
9
|
+
Project-URL: Issues, https://github.com/elemets/bertuner/issues
|
|
10
|
+
Keywords: bert,modernbert,text-classification,transformers,hyperparameter-optimization,optuna,mlflow,fine-tuning
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Intended Audience :: Science/Research
|
|
14
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
20
|
+
Requires-Python: >=3.10
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
License-File: LICENSE
|
|
23
|
+
Requires-Dist: torch>=2.0
|
|
24
|
+
Requires-Dist: transformers>=4.48
|
|
25
|
+
Requires-Dist: numpy>=1.24
|
|
26
|
+
Requires-Dist: pandas>=2.0
|
|
27
|
+
Requires-Dist: scikit-learn>=1.3
|
|
28
|
+
Provides-Extra: train
|
|
29
|
+
Requires-Dist: optuna>=3.0; extra == "train"
|
|
30
|
+
Requires-Dist: mlflow>=2.9; extra == "train"
|
|
31
|
+
Requires-Dist: datasets>=2.14; extra == "train"
|
|
32
|
+
Requires-Dist: tensorboard>=2.15; extra == "train"
|
|
33
|
+
Requires-Dist: accelerate>=0.26; extra == "train"
|
|
34
|
+
Provides-Extra: dev
|
|
35
|
+
Requires-Dist: pytest>=7.0; extra == "dev"
|
|
36
|
+
Requires-Dist: build; extra == "dev"
|
|
37
|
+
Requires-Dist: twine; extra == "dev"
|
|
38
|
+
Dynamic: license-file
|
|
39
|
+
|
|
40
|
+
# BERTuneClassifier
|
|
41
|
+
|
|
42
|
+
A library for hyperparameter optimization and fine-tuning of BERT-based classification models. It integrates **Optuna** for efficient search and **MLflow** for experiment tracking.
|
|
43
|
+
|
|
44
|
+
Supports both classic 512-token encoders (BERT, RoBERTa, DistilBERT, ELECTRA) and long-context models such as **ModernBERT** (8192 tokens). Per-architecture dropout is applied automatically, `max_length` is clamped to each model's real context window, precision is bf16 where the GPU supports it, and gradient checkpointing switches on automatically for sequences longer than 1024 tokens (override with `gradient_checkpointing=True/False`).
|
|
45
|
+
|
|
46
|
+
## Installation
|
|
47
|
+
|
|
48
|
+
```bash
|
|
49
|
+
pip install bertuner[train] # training + inference
|
|
50
|
+
pip install bertuner # inference only (BERTunePredictor)
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
From source (development):
|
|
54
|
+
|
|
55
|
+
```bash
|
|
56
|
+
git clone https://github.com/elemets/bertuner && cd bertuner
|
|
57
|
+
pip install -r requirements.txt
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
MLflow tracking works in two modes:
|
|
61
|
+
|
|
62
|
+
```bash
|
|
63
|
+
# Option A: run a tracking server (default, expects port 9090)
|
|
64
|
+
mlflow server --port 9090
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
```python
|
|
68
|
+
# Option B: no server — log to a local directory instead
|
|
69
|
+
classifier = BERTuneClassifier(..., mlflow_tracking_uri="./mlruns")
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
## Training
|
|
73
|
+
|
|
74
|
+
```python
|
|
75
|
+
from bertuner.BERTuner import BERTuneClassifier
|
|
76
|
+
|
|
77
|
+
# 1. Initialize
|
|
78
|
+
classifier = BERTuneClassifier(
|
|
79
|
+
data_path="../data/dataset.csv", # or dataframe=my_df
|
|
80
|
+
models_dir="../models/",
|
|
81
|
+
text_feature="text_col", # column containing the text
|
|
82
|
+
target_cols=["label_col"], # one column = single-label
|
|
83
|
+
max_length=512,
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
# 2. Configure (optional: uses defaults if called without arguments)
|
|
87
|
+
classifier.initialize_model_choices()
|
|
88
|
+
classifier.initialize_search_space()
|
|
89
|
+
|
|
90
|
+
# 3. Optimize — runs Optuna trials and logs to MLflow
|
|
91
|
+
best_value = classifier.optimize(
|
|
92
|
+
n_trials=20,
|
|
93
|
+
optimize_metric="avg_precision",
|
|
94
|
+
study_name="bert_experiment_v1",
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
# 4. Train final model — retrains on best params, optimises the decision
|
|
98
|
+
# threshold on the validation set, evaluates on the test set, and saves
|
|
99
|
+
# model + tokenizer + bertuner_config.json under models_dir/final_model/model
|
|
100
|
+
metrics, model, test_ds = classifier.train_final_model()
|
|
101
|
+
print(metrics)
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
Multi-label classification: pass several target columns — `target_cols=["l1", "l2", "l3"]`. The loss switches to BCE-with-logits and one decision threshold is optimised per label.
|
|
105
|
+
|
|
106
|
+
Grouped data (e.g. multiple notes per patient): pass `group_key="patient_id"` and the train/val/test split guarantees no group leaks across splits.
|
|
107
|
+
|
|
108
|
+
## Customizing the hyperparameter search
|
|
109
|
+
|
|
110
|
+
Two things are configurable: **which models** are searched and **which hyperparameters** with what ranges.
|
|
111
|
+
|
|
112
|
+
`initialize_model_choices` maps short names to HuggingFace model paths:
|
|
113
|
+
|
|
114
|
+
```python
|
|
115
|
+
classifier.initialize_model_choices({
|
|
116
|
+
"bert-base": "bert-base-uncased",
|
|
117
|
+
"modernbert-base": "answerdotai/ModernBERT-base",
|
|
118
|
+
"my-domain-model": "allenai/scibert_scivocab_uncased",
|
|
119
|
+
})
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
`initialize_search_space` takes a dict where the value type decides the Optuna suggestion:
|
|
123
|
+
|
|
124
|
+
- **list** → categorical choice, e.g. `"batch_size": [8, 16, 32]`
|
|
125
|
+
- **dict with int `low`/`high`** → integer range, e.g. `{"low": 3, "high": 8}` (optional `"step"`)
|
|
126
|
+
- **dict with float `low`/`high`** → float range, e.g. `{"low": 1e-6, "high": 5e-5, "log": True}` (`"log"` samples on a log scale — use it for learning rates)
|
|
127
|
+
|
|
128
|
+
```python
|
|
129
|
+
classifier.initialize_search_space({
|
|
130
|
+
"model": ["bert-base", "my-domain-model"], # keys from model_choices
|
|
131
|
+
"learning_rate": {"low": 1e-6, "high": 5e-5, "log": True},
|
|
132
|
+
"batch_size": [8, 16, 32],
|
|
133
|
+
"gradient_accumulation_steps": [1, 2, 4], # optional, defaults to 1
|
|
134
|
+
"loss_type": ["weighted", "focal", "label_smoothing"],
|
|
135
|
+
"weight_decay": {"low": 0.0, "high": 0.2},
|
|
136
|
+
"warmup_ratio": {"low": 0.0, "high": 0.2},
|
|
137
|
+
"scheduler": ["linear", "cosine"],
|
|
138
|
+
"dropout": {"low": 0.0, "high": 0.3},
|
|
139
|
+
"early_stopping_patience": {"low": 3, "high": 8},
|
|
140
|
+
})
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
Required keys: `model`, `learning_rate`, `batch_size`, `weight_decay`, `warmup_ratio`, `scheduler`, `dropout`, `early_stopping_patience`. Optional: `loss_type` (single-label only; defaults to `weighted`) and `gradient_accumulation_steps`.
|
|
144
|
+
|
|
145
|
+
Ready-made spaces live in `bertuner.constants`: `DEFAULT_SEARCH_SPACE_SINGLELABEL`, `DEFAULT_SEARCH_SPACE_MULTILABEL`, and `DEFAULT_SEARCH_SPACE_LONGCONTEXT`. Tweak one instead of starting from scratch:
|
|
146
|
+
|
|
147
|
+
```python
|
|
148
|
+
from bertuner.constants import DEFAULT_SEARCH_SPACE_SINGLELABEL
|
|
149
|
+
|
|
150
|
+
classifier.initialize_search_space({
|
|
151
|
+
**DEFAULT_SEARCH_SPACE_SINGLELABEL,
|
|
152
|
+
"model": ["bert-base"], # pin a single model
|
|
153
|
+
"learning_rate": {"low": 1e-5, "high": 3e-5, "log": True},
|
|
154
|
+
})
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
## Long documents (ModernBERT, 8192 tokens)
|
|
158
|
+
|
|
159
|
+
```python
|
|
160
|
+
from bertuner.BERTuner import BERTuneClassifier
|
|
161
|
+
from bertuner.constants import DEFAULT_SEARCH_SPACE_LONGCONTEXT
|
|
162
|
+
|
|
163
|
+
classifier = BERTuneClassifier(
|
|
164
|
+
data_path="../data/long_docs.csv",
|
|
165
|
+
models_dir="../models/",
|
|
166
|
+
text_feature="text_col",
|
|
167
|
+
target_cols=["label_col"],
|
|
168
|
+
max_length=8192,
|
|
169
|
+
)
|
|
170
|
+
classifier.initialize_model_choices()
|
|
171
|
+
classifier.initialize_search_space(DEFAULT_SEARCH_SPACE_LONGCONTEXT)
|
|
172
|
+
classifier.optimize(n_trials=10, study_name="long_context_v1")
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
`DEFAULT_SEARCH_SPACE_LONGCONTEXT` searches over ModernBERT base/large with small per-device batches and `gradient_accumulation_steps`, keeping the effective batch size in the usual range without exhausting GPU memory. Mixing 512-token models into the same search space is safe — `max_length` is clamped per model.
|
|
176
|
+
|
|
177
|
+
## Loading a trained model and predicting
|
|
178
|
+
|
|
179
|
+
`train_final_model()` saves everything the predictor needs (weights, tokenizer, optimised thresholds, `max_length`) under `models_dir/final_model/model`:
|
|
180
|
+
|
|
181
|
+
```python
|
|
182
|
+
from bertuner.Predictor import BERTunePredictor
|
|
183
|
+
|
|
184
|
+
predictor = BERTunePredictor("../models/final_model/model")
|
|
185
|
+
|
|
186
|
+
# Hard class predictions, using the threshold(s) optimised during training
|
|
187
|
+
preds = predictor.predict(["some clinical note", "another document"])
|
|
188
|
+
# single-label → array of 0/1 (binary) or class ids (multiclass)
|
|
189
|
+
# multi-label → array of shape (N, num_labels) with 0/1 per label
|
|
190
|
+
|
|
191
|
+
# Probabilities
|
|
192
|
+
probs = predictor.predict_proba(["some clinical note"])
|
|
193
|
+
# single-label → softmax over classes, shape (N, num_classes)
|
|
194
|
+
# multi-label → sigmoid per label, shape (N, num_labels)
|
|
195
|
+
|
|
196
|
+
# Predictions as a DataFrame with one column per target
|
|
197
|
+
df = predictor.predict_df(["some clinical note", "another document"])
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
Options: `BERTunePredictor(model_dir, device="cuda", batch_size=64)` — device defaults to CUDA when available, batch size to 32. Texts longer than the trained `max_length` are truncated.
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
bertuner/BERTuner.py,sha256=Xl6CVR4V3y0LNNjnWm4vSpyk--q3qefeTCNlgNi1tRM,34860
|
|
2
|
+
bertuner/CustomTrainer.py,sha256=TLmYI6vw1MnB8L6Dbkxpk3CrIlybb54v8KfGIem28dI,4728
|
|
3
|
+
bertuner/Predictor.py,sha256=5e5nRAGx98JqA-DoU1PQGtgiFaV7xarjYFYhDJ_Qib4,3525
|
|
4
|
+
bertuner/TensorBoardCallback.py,sha256=CYaWgwZUO-DN6E6Jrt8_-VEJbpDsA5cXAK6ug86MxWw,1417
|
|
5
|
+
bertuner/__init__.py,sha256=Ku1COurU1QEOdbgQWGpzxOUepds9Q0B4_88VmPK3DAA,622
|
|
6
|
+
bertuner/constants.py,sha256=_wam2J5hAnQmZJfzxe3rzIlymfgkQLyr8k3qSxyiFoc,2423
|
|
7
|
+
bertuner/utils.py,sha256=80JsFezK7P488zKyKSxCLIhQnVeba7iwZhPK7LK_7vE,3266
|
|
8
|
+
bertuner-0.1.0.dist-info/licenses/LICENSE,sha256=XjTKtBiMh2-wtGrWQSgXH4NtwbjPE661CK2oyOetlOs,1064
|
|
9
|
+
bertuner-0.1.0.dist-info/METADATA,sha256=-i9OI10YTiGTmy0Fx8rJuF5YO08w2isu8ylZYRchACY,8355
|
|
10
|
+
bertuner-0.1.0.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91
|
|
11
|
+
bertuner-0.1.0.dist-info/top_level.txt,sha256=ySfCthWdi51ugXF0M5zfi3PvQESVO3h9RZuZwBqNEC0,9
|
|
12
|
+
bertuner-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 elemets
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
bertuner
|