|
| 1 | +"""PTuningScorer class for ptuning-based classification.""" |
| 2 | + |
| 3 | +from typing import Any |
| 4 | + |
| 5 | +import torch |
| 6 | +from peft import PromptEncoderConfig, get_peft_model |
| 7 | +from transformers import ( |
| 8 | + AutoModelForSequenceClassification, |
| 9 | +) |
| 10 | + |
| 11 | +from autointent import Context |
| 12 | +from autointent._callbacks import REPORTERS_NAMES |
| 13 | +from autointent.configs import HFModelConfig |
| 14 | +from autointent.modules.scoring._bert import BertScorer |
| 15 | + |
| 16 | + |
| 17 | +class PTuningScorer(BertScorer): |
| 18 | + """PEFT P-tuning scorer. |
| 19 | +
|
| 20 | + Args: |
| 21 | + classification_model_config: Config of the base transformer model (HFModelConfig, str, or dict) |
| 22 | + num_train_epochs: Number of training epochs |
| 23 | + batch_size: Batch size for training |
| 24 | + learning_rate: Learning rate for training |
| 25 | + seed: Random seed for reproducibility |
| 26 | + report_to: Reporting tool for training logs |
| 27 | + **ptuning_kwargs: Arguments for `PromptEncoderConfig <https://huggingface.co/docs/peft/package_reference/p_tuning#peft.PromptEncoderConfig>`_ |
| 28 | +
|
| 29 | + Example: |
| 30 | + -------- |
| 31 | + .. testcode:: |
| 32 | +
|
| 33 | + from autointent.modules import PTuningScorer |
| 34 | + scorer = PTuningScorer( |
| 35 | + classification_model_config="prajjwal1/bert-tiny", |
| 36 | + num_train_epochs=3, |
| 37 | + batch_size=8, |
| 38 | + task_type="SEQ_CLS", |
| 39 | + num_virtual_tokens=10, |
| 40 | + seed=42 |
| 41 | + ) |
| 42 | + utterances = ["hello", "goodbye", "allo", "sayonara"] |
| 43 | + labels = [0, 1, 0, 1] |
| 44 | + scorer.fit(utterances, labels) |
| 45 | + test_utterances = ["hi", "bye"] |
| 46 | + probabilities = scorer.predict(test_utterances) |
| 47 | + print(probabilities) |
| 48 | +
|
| 49 | + .. testoutput:: |
| 50 | +
|
| 51 | + [[0.49925193 0.50074804] |
| 52 | + [0.4944601 0.5055399 ]] |
| 53 | +
|
| 54 | + """ |
| 55 | + |
| 56 | + name = "ptuning" |
| 57 | + supports_multiclass = True |
| 58 | + supports_multilabel = True |
| 59 | + _model: Any |
| 60 | + _tokenizer: Any |
| 61 | + |
| 62 | + def __init__( |
| 63 | + self, |
| 64 | + classification_model_config: HFModelConfig | str | dict[str, Any] | None = None, |
| 65 | + num_train_epochs: int = 3, |
| 66 | + batch_size: int = 8, |
| 67 | + learning_rate: float = 5e-5, |
| 68 | + seed: int = 0, |
| 69 | + report_to: REPORTERS_NAMES | None = None, # type: ignore[valid-type] |
| 70 | + **ptuning_kwargs: dict[str, Any], |
| 71 | + ) -> None: |
| 72 | + super().__init__( |
| 73 | + classification_model_config=classification_model_config, |
| 74 | + num_train_epochs=num_train_epochs, |
| 75 | + batch_size=batch_size, |
| 76 | + learning_rate=learning_rate, |
| 77 | + seed=seed, |
| 78 | + report_to=report_to, |
| 79 | + ) |
| 80 | + self._ptuning_config = PromptEncoderConfig(**ptuning_kwargs) # type: ignore[arg-type] |
| 81 | + torch.manual_seed(seed) |
| 82 | + |
| 83 | + @classmethod |
| 84 | + def from_context( |
| 85 | + cls, |
| 86 | + context: Context, |
| 87 | + classification_model_config: HFModelConfig | str | dict[str, Any] | None = None, |
| 88 | + num_train_epochs: int = 3, |
| 89 | + batch_size: int = 8, |
| 90 | + learning_rate: float = 5e-5, |
| 91 | + seed: int = 0, |
| 92 | + **ptuning_kwargs: dict[str, Any], |
| 93 | + ) -> "PTuningScorer": |
| 94 | + """Create a PTuningScorer instance using a Context object. |
| 95 | +
|
| 96 | + Args: |
| 97 | + context: Context containing configurations and utilities |
| 98 | + classification_model_config: Config of the base model, or None to use the best embedder |
| 99 | + num_train_epochs: Number of training epochs |
| 100 | + batch_size: Batch size for training |
| 101 | + learning_rate: Learning rate for training |
| 102 | + seed: Random seed for reproducibility |
| 103 | + **ptuning_kwargs: Arguments for PromptEncoderConfig |
| 104 | + """ |
| 105 | + if classification_model_config is None: |
| 106 | + classification_model_config = context.resolve_embedder() |
| 107 | + |
| 108 | + report_to = context.logging_config.report_to |
| 109 | + |
| 110 | + return cls( |
| 111 | + classification_model_config=classification_model_config, |
| 112 | + num_train_epochs=num_train_epochs, |
| 113 | + batch_size=batch_size, |
| 114 | + learning_rate=learning_rate, |
| 115 | + seed=seed, |
| 116 | + report_to=report_to, |
| 117 | + **ptuning_kwargs, |
| 118 | + ) |
| 119 | + |
| 120 | + def _initialize_model(self) -> None: |
| 121 | + """Initialize the model with P-tuning configuration.""" |
| 122 | + model_name = self.classification_model_config.model_name |
| 123 | + self._model = AutoModelForSequenceClassification.from_pretrained( |
| 124 | + model_name, |
| 125 | + num_labels=self._n_classes, |
| 126 | + problem_type="multi_label_classification" if self._multilabel else "single_label_classification", |
| 127 | + trust_remote_code=self.classification_model_config.trust_remote_code, |
| 128 | + return_dict=True, |
| 129 | + ) |
| 130 | + self._model = get_peft_model(self._model, self._ptuning_config) |
0 commit comments