|
| 1 | +from typing import Optional, Union, List |
| 2 | +import pandas as pd |
| 3 | +from skllm.models._base import _BaseZeroShotGPTClassifier |
| 4 | +from skllm.prompts.builders import build_zero_shot_prompt_slc |
| 5 | +from skllm.openai.credentials import set_credentials |
| 6 | +from skllm.openai.tuning import create_tuning_job, await_results, delete_file |
| 7 | +import numpy as np |
| 8 | +import json |
| 9 | +import uuid |
| 10 | + |
| 11 | + |
| 12 | +def _build_clf_example( |
| 13 | + x: str, y: str, system_msg="You are a text classification model." |
| 14 | +): |
| 15 | + sample = { |
| 16 | + "messages": [ |
| 17 | + {"role": "system", "content": system_msg}, |
| 18 | + {"role": "user", "content": x}, |
| 19 | + {"role": "assistant", "content": y}, |
| 20 | + ] |
| 21 | + } |
| 22 | + return json.dumps(sample) |
| 23 | + |
| 24 | + |
| 25 | +class _Tunable: |
| 26 | + system_msg = "You are a text classification model." |
| 27 | + |
| 28 | + def _build_label(self, label: str): |
| 29 | + return json.dumps({"label": label}) |
| 30 | + |
| 31 | + def _tune(self, X, y): |
| 32 | + file_uuid = str(uuid.uuid4()) |
| 33 | + filename = f"skllm_{file_uuid}.jsonl" |
| 34 | + with open(filename, "w+") as f: |
| 35 | + for xi, yi in zip(X, y): |
| 36 | + f.write( |
| 37 | + _build_clf_example( |
| 38 | + self._get_prompt(xi), self._build_label(yi), self.system_msg |
| 39 | + ) |
| 40 | + ) |
| 41 | + f.write("\n") |
| 42 | + set_credentials(self._get_openai_key(), self._get_openai_org()) |
| 43 | + job = create_tuning_job( |
| 44 | + self.base_model, |
| 45 | + filename, |
| 46 | + self.n_epochs, |
| 47 | + self.custom_suffix, |
| 48 | + ) |
| 49 | + print(f"Created new tuning job. JOB_ID = {job['id']}") |
| 50 | + job = await_results(job["id"]) |
| 51 | + self.openai_model = job["fine_tuned_model"] |
| 52 | + delete_file(job["training_file"]) |
| 53 | + print(f"Finished training. Number of trained tokens: {job['trained_tokens']}.") |
| 54 | + |
| 55 | + |
| 56 | +class GPTClassifier(_BaseZeroShotGPTClassifier, _Tunable): |
| 57 | + """Fine-tunable GPT classifier for single-label classification.""" |
| 58 | + |
| 59 | + supported_models = ["gpt-3.5-turbo-0613"] |
| 60 | + |
| 61 | + def __init__( |
| 62 | + self, |
| 63 | + base_model: str = "gpt-3.5-turbo-0613", |
| 64 | + default_label: Optional[str] = "Random", |
| 65 | + openai_key: Optional[str] = None, |
| 66 | + openai_org: Optional[str] = None, |
| 67 | + n_epochs: Optional[int] = None, |
| 68 | + custom_suffix: Optional[str] = "skllm", |
| 69 | + ): |
| 70 | + self.base_model = base_model |
| 71 | + self.n_epochs = n_epochs |
| 72 | + self.custom_suffix = custom_suffix |
| 73 | + if base_model not in self.supported_models: |
| 74 | + raise ValueError( |
| 75 | + f"Model {base_model} is not supported. Supported models are" |
| 76 | + f" {self.supported_models}" |
| 77 | + ) |
| 78 | + super().__init__( |
| 79 | + openai_model="undefined", |
| 80 | + default_label=default_label, |
| 81 | + openai_key=openai_key, |
| 82 | + openai_org=openai_org, |
| 83 | + ) |
| 84 | + |
| 85 | + def _get_prompt(self, x: str) -> str: |
| 86 | + return build_zero_shot_prompt_slc(x, repr(self.classes_)) |
| 87 | + |
| 88 | + def fit( |
| 89 | + self, |
| 90 | + X: Union[np.ndarray, pd.Series, List[str]], |
| 91 | + y: Union[np.ndarray, pd.Series, List[str]], |
| 92 | + ): |
| 93 | + """Fits the model to the given data. |
| 94 | +
|
| 95 | + Parameters |
| 96 | + ---------- |
| 97 | + X : Union[np.ndarray, pd.Series, List[str]] |
| 98 | + training data |
| 99 | + y : Union[np.ndarray, pd.Series, List[str]] |
| 100 | + training labels |
| 101 | +
|
| 102 | + Returns |
| 103 | + ------- |
| 104 | + GPTClassifier |
| 105 | + self |
| 106 | + """ |
| 107 | + X = self._to_np(X) |
| 108 | + y = self._to_np(y) |
| 109 | + super().fit(X, y) |
| 110 | + self._tune(X, y) |
| 111 | + return self |
| 112 | + |
| 113 | + |
| 114 | +# similarly to PaLM, this is not a classifier, but a quick way to re-use the code |
| 115 | +# the hierarchy of classes will be reworked in the next releases |
| 116 | +class GPT(_BaseZeroShotGPTClassifier, _Tunable): |
| 117 | + """Fine-tunable GPT on arbitrary input-output pairs.""" |
| 118 | + |
| 119 | + supported_models = ["gpt-3.5-turbo-0613"] |
| 120 | + |
| 121 | + def __init__( |
| 122 | + self, |
| 123 | + base_model: str = "gpt-3.5-turbo-0613", |
| 124 | + openai_key: Optional[str] = None, |
| 125 | + openai_org: Optional[str] = None, |
| 126 | + n_epochs: Optional[int] = None, |
| 127 | + custom_suffix: Optional[str] = "skllm", |
| 128 | + system_msg: Optional[str] = "You are a text processing model.", |
| 129 | + ): |
| 130 | + self.base_model = base_model |
| 131 | + self.n_epochs = n_epochs |
| 132 | + self.custom_suffix = custom_suffix |
| 133 | + self.system_msg = system_msg |
| 134 | + if base_model not in self.supported_models: |
| 135 | + raise ValueError( |
| 136 | + f"Model {base_model} is not supported. Supported models are" |
| 137 | + f" {self.supported_models}" |
| 138 | + ) |
| 139 | + super().__init__( |
| 140 | + openai_model="undefined", # this will be rewritten later |
| 141 | + default_label="Random", # just for compatibility |
| 142 | + openai_key=openai_key, |
| 143 | + openai_org=openai_org, |
| 144 | + ) |
| 145 | + |
| 146 | + def _get_prompt(self, x: str) -> str: |
| 147 | + return x |
| 148 | + |
| 149 | + def _build_label(self, label: str): |
| 150 | + return label |
| 151 | + |
| 152 | + def fit( |
| 153 | + self, |
| 154 | + X: Union[np.ndarray, pd.Series, List[str]], |
| 155 | + y: Union[np.ndarray, pd.Series, List[str]], |
| 156 | + ): |
| 157 | + """Fits the model to the given data. |
| 158 | +
|
| 159 | + Parameters |
| 160 | + ---------- |
| 161 | + X : Union[np.ndarray, pd.Series, List[str]] |
| 162 | + training data |
| 163 | + y : Union[np.ndarray, pd.Series, List[str]] |
| 164 | + training labels |
| 165 | +
|
| 166 | + Returns |
| 167 | + ------- |
| 168 | + GPT |
| 169 | + self |
| 170 | + """ |
| 171 | + X = self._to_np(X) |
| 172 | + y = self._to_np(y) |
| 173 | + self._tune(X, y) |
| 174 | + return self |
0 commit comments