|
| 1 | +"""BertScorer class for transformer-based classification.""" |
| 2 | + |
| 3 | +import tempfile |
| 4 | +from typing import Any |
| 5 | + |
| 6 | +import numpy as np |
| 7 | +import numpy.typing as npt |
| 8 | +import torch |
| 9 | +from datasets import Dataset |
| 10 | +from transformers import ( |
| 11 | + AutoModelForSequenceClassification, |
| 12 | + AutoTokenizer, |
| 13 | + DataCollatorWithPadding, |
| 14 | + Trainer, |
| 15 | + TrainingArguments, |
| 16 | +) |
| 17 | + |
| 18 | +from autointent import Context |
| 19 | +from autointent._callbacks import REPORTERS_NAMES |
| 20 | +from autointent.configs import HFModelConfig |
| 21 | +from autointent.custom_types import ListOfLabels |
| 22 | +from autointent.modules.base import BaseScorer |
| 23 | + |
| 24 | + |
| 25 | +class BertScorer(BaseScorer): |
| 26 | + name = "transformer" |
| 27 | + supports_multiclass = True |
| 28 | + supports_multilabel = True |
| 29 | + _model: Any |
| 30 | + _tokenizer: Any |
| 31 | + |
| 32 | + def __init__( |
| 33 | + self, |
| 34 | + model_config: HFModelConfig | str | dict[str, Any] | None = None, |
| 35 | + num_train_epochs: int = 3, |
| 36 | + batch_size: int = 8, |
| 37 | + learning_rate: float = 5e-5, |
| 38 | + seed: int = 0, |
| 39 | + report_to: REPORTERS_NAMES | None = None, # type: ignore # noqa: PGH003 |
| 40 | + ) -> None: |
| 41 | + self.model_config = HFModelConfig.from_search_config(model_config) |
| 42 | + self.num_train_epochs = num_train_epochs |
| 43 | + self.batch_size = batch_size |
| 44 | + self.learning_rate = learning_rate |
| 45 | + self.seed = seed |
| 46 | + self.report_to = report_to |
| 47 | + |
| 48 | + @classmethod |
| 49 | + def from_context( |
| 50 | + cls, |
| 51 | + context: Context, |
| 52 | + model_config: HFModelConfig | str | dict[str, Any] | None = None, |
| 53 | + num_train_epochs: int = 3, |
| 54 | + batch_size: int = 8, |
| 55 | + learning_rate: float = 5e-5, |
| 56 | + seed: int = 0, |
| 57 | + ) -> "BertScorer": |
| 58 | + if model_config is None: |
| 59 | + model_config = context.resolve_embedder() |
| 60 | + |
| 61 | + report_to = context.logging_config.report_to |
| 62 | + |
| 63 | + return cls( |
| 64 | + model_config=model_config, |
| 65 | + num_train_epochs=num_train_epochs, |
| 66 | + batch_size=batch_size, |
| 67 | + learning_rate=learning_rate, |
| 68 | + seed=seed, |
| 69 | + report_to=report_to, |
| 70 | + ) |
| 71 | + |
| 72 | + def get_embedder_config(self) -> dict[str, Any]: |
| 73 | + return self.model_config.model_dump() |
| 74 | + |
| 75 | + def fit( |
| 76 | + self, |
| 77 | + utterances: list[str], |
| 78 | + labels: ListOfLabels, |
| 79 | + ) -> None: |
| 80 | + if hasattr(self, "_model"): |
| 81 | + self.clear_cache() |
| 82 | + |
| 83 | + self._validate_task(labels) |
| 84 | + |
| 85 | + model_name = self.model_config.model_name |
| 86 | + self._tokenizer = AutoTokenizer.from_pretrained(model_name) |
| 87 | + self._model = AutoModelForSequenceClassification.from_pretrained(model_name, num_labels=self._n_classes) |
| 88 | + |
| 89 | + use_cpu = self.model_config.device == "cpu" |
| 90 | + |
| 91 | + def tokenize_function(examples: dict[str, Any]) -> dict[str, Any]: |
| 92 | + return self._tokenizer( # type: ignore[no-any-return] |
| 93 | + examples["text"], return_tensors="pt", **self.model_config.tokenizer_config.model_dump() |
| 94 | + ) |
| 95 | + |
| 96 | + dataset = Dataset.from_dict({"text": utterances, "labels": labels}) |
| 97 | + tokenized_dataset = dataset.map(tokenize_function, batched=True) |
| 98 | + |
| 99 | + with tempfile.TemporaryDirectory() as tmp_dir: |
| 100 | + training_args = TrainingArguments( |
| 101 | + output_dir=tmp_dir, |
| 102 | + num_train_epochs=self.num_train_epochs, |
| 103 | + per_device_train_batch_size=self.batch_size, |
| 104 | + learning_rate=self.learning_rate, |
| 105 | + seed=self.seed, |
| 106 | + save_strategy="no", |
| 107 | + logging_strategy="steps", |
| 108 | + logging_steps=10, |
| 109 | + report_to=self.report_to, |
| 110 | + use_cpu=use_cpu, |
| 111 | + ) |
| 112 | + |
| 113 | + trainer = Trainer( |
| 114 | + model=self._model, |
| 115 | + args=training_args, |
| 116 | + train_dataset=tokenized_dataset, |
| 117 | + tokenizer=self._tokenizer, |
| 118 | + data_collator=DataCollatorWithPadding(tokenizer=self._tokenizer), |
| 119 | + ) |
| 120 | + |
| 121 | + trainer.train() |
| 122 | + |
| 123 | + self._model.eval() |
| 124 | + |
| 125 | + def predict(self, utterances: list[str]) -> npt.NDArray[Any]: |
| 126 | + if not hasattr(self, "_model") or not hasattr(self, "_tokenizer"): |
| 127 | + msg = "Model is not trained. Call fit() first." |
| 128 | + raise RuntimeError(msg) |
| 129 | + |
| 130 | + all_predictions = [] |
| 131 | + for i in range(0, len(utterances), self.batch_size): |
| 132 | + batch = utterances[i : i + self.batch_size] |
| 133 | + inputs = self._tokenizer(batch, return_tensors="pt", **self.model_config.tokenizer_config.model_dump()) |
| 134 | + with torch.no_grad(): |
| 135 | + outputs = self._model(**inputs) |
| 136 | + logits = outputs.logits |
| 137 | + if self._multilabel: |
| 138 | + batch_predictions = torch.sigmoid(logits).numpy() |
| 139 | + else: |
| 140 | + batch_predictions = torch.softmax(logits, dim=1).numpy() |
| 141 | + all_predictions.append(batch_predictions) |
| 142 | + return np.vstack(all_predictions) if all_predictions else np.array([]) |
| 143 | + |
| 144 | + def clear_cache(self) -> None: |
| 145 | + if hasattr(self, "_model"): |
| 146 | + del self._model |
| 147 | + if hasattr(self, "_tokenizer"): |
| 148 | + del self._tokenizer |
0 commit comments