bertuner 0.1.0__tar.gz
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-0.1.0/LICENSE +21 -0
- bertuner-0.1.0/PKG-INFO +200 -0
- bertuner-0.1.0/README.md +161 -0
- bertuner-0.1.0/bertuner/BERTuner.py +818 -0
- bertuner-0.1.0/bertuner/CustomTrainer.py +109 -0
- bertuner-0.1.0/bertuner/Predictor.py +90 -0
- bertuner-0.1.0/bertuner/TensorBoardCallback.py +39 -0
- bertuner-0.1.0/bertuner/__init__.py +17 -0
- bertuner-0.1.0/bertuner/constants.py +64 -0
- bertuner-0.1.0/bertuner/utils.py +99 -0
- bertuner-0.1.0/bertuner.egg-info/PKG-INFO +200 -0
- bertuner-0.1.0/bertuner.egg-info/SOURCES.txt +18 -0
- bertuner-0.1.0/bertuner.egg-info/dependency_links.txt +1 -0
- bertuner-0.1.0/bertuner.egg-info/requires.txt +17 -0
- bertuner-0.1.0/bertuner.egg-info/top_level.txt +1 -0
- bertuner-0.1.0/pyproject.toml +59 -0
- bertuner-0.1.0/setup.cfg +4 -0
- bertuner-0.1.0/tests/test_bertuner.py +487 -0
- bertuner-0.1.0/tests/test_predictor.py +143 -0
- bertuner-0.1.0/tests/test_utils.py +95 -0
bertuner-0.1.0/LICENSE
ADDED
|
@@ -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.
|
bertuner-0.1.0/PKG-INFO
ADDED
|
@@ -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.
|
bertuner-0.1.0/README.md
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
# BERTuneClassifier
|
|
2
|
+
|
|
3
|
+
A library for hyperparameter optimization and fine-tuning of BERT-based classification models. It integrates **Optuna** for efficient search and **MLflow** for experiment tracking.
|
|
4
|
+
|
|
5
|
+
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`).
|
|
6
|
+
|
|
7
|
+
## Installation
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
pip install bertuner[train] # training + inference
|
|
11
|
+
pip install bertuner # inference only (BERTunePredictor)
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
From source (development):
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
git clone https://github.com/elemets/bertuner && cd bertuner
|
|
18
|
+
pip install -r requirements.txt
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
MLflow tracking works in two modes:
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
# Option A: run a tracking server (default, expects port 9090)
|
|
25
|
+
mlflow server --port 9090
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
```python
|
|
29
|
+
# Option B: no server — log to a local directory instead
|
|
30
|
+
classifier = BERTuneClassifier(..., mlflow_tracking_uri="./mlruns")
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
## Training
|
|
34
|
+
|
|
35
|
+
```python
|
|
36
|
+
from bertuner.BERTuner import BERTuneClassifier
|
|
37
|
+
|
|
38
|
+
# 1. Initialize
|
|
39
|
+
classifier = BERTuneClassifier(
|
|
40
|
+
data_path="../data/dataset.csv", # or dataframe=my_df
|
|
41
|
+
models_dir="../models/",
|
|
42
|
+
text_feature="text_col", # column containing the text
|
|
43
|
+
target_cols=["label_col"], # one column = single-label
|
|
44
|
+
max_length=512,
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
# 2. Configure (optional: uses defaults if called without arguments)
|
|
48
|
+
classifier.initialize_model_choices()
|
|
49
|
+
classifier.initialize_search_space()
|
|
50
|
+
|
|
51
|
+
# 3. Optimize — runs Optuna trials and logs to MLflow
|
|
52
|
+
best_value = classifier.optimize(
|
|
53
|
+
n_trials=20,
|
|
54
|
+
optimize_metric="avg_precision",
|
|
55
|
+
study_name="bert_experiment_v1",
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
# 4. Train final model — retrains on best params, optimises the decision
|
|
59
|
+
# threshold on the validation set, evaluates on the test set, and saves
|
|
60
|
+
# model + tokenizer + bertuner_config.json under models_dir/final_model/model
|
|
61
|
+
metrics, model, test_ds = classifier.train_final_model()
|
|
62
|
+
print(metrics)
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
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.
|
|
66
|
+
|
|
67
|
+
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.
|
|
68
|
+
|
|
69
|
+
## Customizing the hyperparameter search
|
|
70
|
+
|
|
71
|
+
Two things are configurable: **which models** are searched and **which hyperparameters** with what ranges.
|
|
72
|
+
|
|
73
|
+
`initialize_model_choices` maps short names to HuggingFace model paths:
|
|
74
|
+
|
|
75
|
+
```python
|
|
76
|
+
classifier.initialize_model_choices({
|
|
77
|
+
"bert-base": "bert-base-uncased",
|
|
78
|
+
"modernbert-base": "answerdotai/ModernBERT-base",
|
|
79
|
+
"my-domain-model": "allenai/scibert_scivocab_uncased",
|
|
80
|
+
})
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
`initialize_search_space` takes a dict where the value type decides the Optuna suggestion:
|
|
84
|
+
|
|
85
|
+
- **list** → categorical choice, e.g. `"batch_size": [8, 16, 32]`
|
|
86
|
+
- **dict with int `low`/`high`** → integer range, e.g. `{"low": 3, "high": 8}` (optional `"step"`)
|
|
87
|
+
- **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)
|
|
88
|
+
|
|
89
|
+
```python
|
|
90
|
+
classifier.initialize_search_space({
|
|
91
|
+
"model": ["bert-base", "my-domain-model"], # keys from model_choices
|
|
92
|
+
"learning_rate": {"low": 1e-6, "high": 5e-5, "log": True},
|
|
93
|
+
"batch_size": [8, 16, 32],
|
|
94
|
+
"gradient_accumulation_steps": [1, 2, 4], # optional, defaults to 1
|
|
95
|
+
"loss_type": ["weighted", "focal", "label_smoothing"],
|
|
96
|
+
"weight_decay": {"low": 0.0, "high": 0.2},
|
|
97
|
+
"warmup_ratio": {"low": 0.0, "high": 0.2},
|
|
98
|
+
"scheduler": ["linear", "cosine"],
|
|
99
|
+
"dropout": {"low": 0.0, "high": 0.3},
|
|
100
|
+
"early_stopping_patience": {"low": 3, "high": 8},
|
|
101
|
+
})
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
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`.
|
|
105
|
+
|
|
106
|
+
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:
|
|
107
|
+
|
|
108
|
+
```python
|
|
109
|
+
from bertuner.constants import DEFAULT_SEARCH_SPACE_SINGLELABEL
|
|
110
|
+
|
|
111
|
+
classifier.initialize_search_space({
|
|
112
|
+
**DEFAULT_SEARCH_SPACE_SINGLELABEL,
|
|
113
|
+
"model": ["bert-base"], # pin a single model
|
|
114
|
+
"learning_rate": {"low": 1e-5, "high": 3e-5, "log": True},
|
|
115
|
+
})
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
## Long documents (ModernBERT, 8192 tokens)
|
|
119
|
+
|
|
120
|
+
```python
|
|
121
|
+
from bertuner.BERTuner import BERTuneClassifier
|
|
122
|
+
from bertuner.constants import DEFAULT_SEARCH_SPACE_LONGCONTEXT
|
|
123
|
+
|
|
124
|
+
classifier = BERTuneClassifier(
|
|
125
|
+
data_path="../data/long_docs.csv",
|
|
126
|
+
models_dir="../models/",
|
|
127
|
+
text_feature="text_col",
|
|
128
|
+
target_cols=["label_col"],
|
|
129
|
+
max_length=8192,
|
|
130
|
+
)
|
|
131
|
+
classifier.initialize_model_choices()
|
|
132
|
+
classifier.initialize_search_space(DEFAULT_SEARCH_SPACE_LONGCONTEXT)
|
|
133
|
+
classifier.optimize(n_trials=10, study_name="long_context_v1")
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
`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.
|
|
137
|
+
|
|
138
|
+
## Loading a trained model and predicting
|
|
139
|
+
|
|
140
|
+
`train_final_model()` saves everything the predictor needs (weights, tokenizer, optimised thresholds, `max_length`) under `models_dir/final_model/model`:
|
|
141
|
+
|
|
142
|
+
```python
|
|
143
|
+
from bertuner.Predictor import BERTunePredictor
|
|
144
|
+
|
|
145
|
+
predictor = BERTunePredictor("../models/final_model/model")
|
|
146
|
+
|
|
147
|
+
# Hard class predictions, using the threshold(s) optimised during training
|
|
148
|
+
preds = predictor.predict(["some clinical note", "another document"])
|
|
149
|
+
# single-label → array of 0/1 (binary) or class ids (multiclass)
|
|
150
|
+
# multi-label → array of shape (N, num_labels) with 0/1 per label
|
|
151
|
+
|
|
152
|
+
# Probabilities
|
|
153
|
+
probs = predictor.predict_proba(["some clinical note"])
|
|
154
|
+
# single-label → softmax over classes, shape (N, num_classes)
|
|
155
|
+
# multi-label → sigmoid per label, shape (N, num_labels)
|
|
156
|
+
|
|
157
|
+
# Predictions as a DataFrame with one column per target
|
|
158
|
+
df = predictor.predict_df(["some clinical note", "another document"])
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
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.
|