File size: 10,100 Bytes
8e13241
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
import json
import os
import shutil
import warnings

from loguru import logger
import mlflow
import numpy as np
from sklearn.metrics import (
    accuracy_score,
    classification_report,
    f1_score,
    precision_score,
    recall_score,
)
import torch
from torch.utils.data import Dataset
from transformers import (
    AutoModelForSequenceClassification,
    AutoTokenizer,
    EarlyStoppingCallback,
    Trainer,
    TrainingArguments,
)

from turing.config import MODELS_DIR

from ..baseModel import BaseModel

warnings.filterwarnings("ignore")

def compute_metrics(eval_pred):
    predictions, labels = eval_pred
    # Convert logits to probabilities
    probs = 1 / (1 + np.exp(-predictions))
    
    preds = (probs > 0.35).astype(int)

    #  metrics
    f1 = f1_score(labels, preds, average="micro")
    accuracy = accuracy_score(labels, preds)
    precision = precision_score(labels, preds, average="micro")
    recall = recall_score(labels, preds, average="micro")
    return {
        "f1": f1,
        "accuracy": accuracy,
        "precision": precision,
        "recall": recall,
    }

class DebertaDataset(Dataset):
    """
    Internal Dataset class for DeBERTa.
    """
    def __init__(self, encodings, labels=None, num_labels=None):
        self.encodings = {key: torch.tensor(val) for key, val in encodings.items()}
        
        if labels is not None:
            if not isinstance(labels, (np.ndarray, torch.Tensor)):
                labels = np.array(labels)
            
            # Handle standard label list or flattened format
            if num_labels is not None and (len(labels.shape) == 1 or (len(labels.shape) == 2 and labels.shape[1] == 1)):
                labels_flat = labels.flatten()
                one_hot = np.zeros((len(labels_flat), num_labels), dtype=np.float32)
                valid_indices = labels_flat < num_labels
                one_hot[valid_indices, labels_flat[valid_indices]] = 1.0
                self.labels = torch.tensor(one_hot, dtype=torch.float)
            else:
                self.labels = torch.tensor(labels, dtype=torch.float)
        else:
            self.labels = None

    def __getitem__(self, idx):
        item = {key: val[idx] for key, val in self.encodings.items()}
        if self.labels is not None:
            item['labels'] = self.labels[idx]
        return item

    def __len__(self):
        return len(self.encodings['input_ids'])

class WeightedTrainer(Trainer):
    def compute_loss(self, model, inputs, return_outputs=False, **kwargs):
        labels = inputs.get("labels")
        outputs = model(**inputs)
        logits = outputs.get("logits")

        pos_weight = torch.ones([logits.shape[1]]).to(logits.device) * 4.0
        loss_fct = torch.nn.BCEWithLogitsLoss(pos_weight=pos_weight)
        
        loss = loss_fct(logits, labels.float())
        return (loss, outputs) if return_outputs else loss

class DebertaXSmall(BaseModel):
    """
    Wrapper for Microsoft DeBERTa-v3-xsmall.
    """

    def __init__(self, language, path=None):

        epochs = 10 if language == "java" else 20
        lr = 2e-5 if language == "java" else 3e-5

        self.params = {
            "model_name_hf": "microsoft/deberta-v3-xsmall",
            # Java: 7, Python: 5, Pharo: 6
            "num_labels": 7 if language == "java" else 5 if language == "python" else 6,
            "max_length": 128,  
            "epochs": epochs,
            "batch_size_train": 32, 
            "batch_size_eval": 64,
            "learning_rate": lr,
            "weight_decay": 0.01,
            "train_size": 0.8,
            "early_stopping_patience": 3,
            "early_stopping_threshold": 0.005,
            "warmup_steps": 100
        }
        
        self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
        self.tokenizer = None
        super().__init__(language, path)

    def setup_model(self):
        logger.info(f"Initializing {self.params['model_name_hf']} on {self.device}...")
        
        self.tokenizer = AutoTokenizer.from_pretrained(self.params["model_name_hf"], use_fast=False)
        
        self.model = AutoModelForSequenceClassification.from_pretrained(
            self.params["model_name_hf"], 
            num_labels=self.params["num_labels"],
            problem_type="multi_label_classification"
        ).to(self.device)
        logger.success("DeBERTa-v3-xsmall model initialized.")

    def _tokenize(self, texts):
        safe_texts = []
        for t in texts:
            # Handle potential NaNs or non-strings
            safe_texts.append(str(t) if t is not None and t == t else "")

        return self.tokenizer(
            safe_texts, 
            truncation=True, 
            padding=True, 
            max_length=self.params["max_length"]
        )

    def train(self, X_train, y_train) -> dict:
        if self.model is None:
            raise ValueError("Model not initialized.")

        params_to_log = {k: v for k, v in self.params.items() if k != "model_name_hf"}
        logger.info(f"Starting training for: {self.language.upper()}")
        
        train_encodings = self._tokenize(X_train)
        full_dataset = DebertaDataset(train_encodings, y_train, num_labels=self.params["num_labels"])
        
        train_len = int(self.params["train_size"] * len(full_dataset))
        val_len = len(full_dataset) - train_len
        train_ds, val_ds = torch.utils.data.random_split(full_dataset, [train_len, val_len])

        temp_ckpt_dir = os.path.join(MODELS_DIR, "temp_deberta_ckpt")
        
        training_args = TrainingArguments(
            output_dir=temp_ckpt_dir,
            num_train_epochs=self.params["epochs"],
            per_device_train_batch_size=self.params["batch_size_train"],
            per_device_eval_batch_size=self.params["batch_size_eval"],
            learning_rate=self.params["learning_rate"],
            weight_decay=self.params["weight_decay"],
            eval_strategy="epoch",
            save_strategy="epoch",
            load_best_model_at_end=True,
            metric_for_best_model="f1",
            greater_is_better=True,
            save_total_limit=1,
            logging_dir='./logs',
            report_to="none",
            fp16=torch.cuda.is_available() 
        )

        trainer = WeightedTrainer(
            model=self.model,
            args=training_args,
            train_dataset=train_ds,
            eval_dataset=val_ds,
            compute_metrics=compute_metrics,
            callbacks=[EarlyStoppingCallback(
                early_stopping_patience=self.params["early_stopping_patience"],
                early_stopping_threshold=self.params["early_stopping_threshold"]
            )]
        )
        
        trainer.train()
        
        if os.path.exists(temp_ckpt_dir):
            shutil.rmtree(temp_ckpt_dir)
            
        return params_to_log

    def evaluate(self, X_test, y_test) -> dict:
        y_pred = self.predict(X_test)
        
        y_test_np = np.array(y_test) if not isinstance(y_test, np.ndarray) else y_test
        
        # Handle 1D array conversion for metrics if necessary
        if y_test_np.ndim == 1 or (y_test_np.ndim == 2 and y_test_np.shape[1] == 1):
            y_test_expanded = np.zeros((y_test_np.shape[0], self.params["num_labels"]), dtype=int)
            indices = y_test_np.flatten()
            for i, label_idx in enumerate(indices):
                if 0 <= label_idx < self.params["num_labels"]:
                    y_test_expanded[i, int(label_idx)] = 1
            y_test_np = y_test_expanded

        report = classification_report(y_test_np, y_pred, zero_division=0)
        print(f"\n[DeBERTa {self.language}] Classification Report:\n{report}")

        metrics = {
            "accuracy": accuracy_score(y_test_np, y_pred),
            "f1_score_micro": f1_score(y_test_np, y_pred, average="micro"),
            "f1_score_weighted": f1_score(y_test_np, y_pred, average="weighted"),
        }
        
        mlflow.log_metrics(metrics)
        return metrics

    def predict(self, X) -> np.ndarray:
        if self.model is None:
            raise ValueError("Model not trained.")
            
        self.model.eval()
        encodings = self._tokenize(X)
        dataset = DebertaDataset(encodings, labels=None)
        
        training_args = TrainingArguments(
            output_dir="./pred_temp_deberta",
            per_device_eval_batch_size=self.params["batch_size_eval"],
            fp16=torch.cuda.is_available(),
            report_to="none"
        )
        
        trainer = Trainer(model=self.model, args=training_args)
        output = trainer.predict(dataset)
        
        if os.path.exists("./pred_temp_deberta"):
            shutil.rmtree("./pred_temp_deberta")
            
        logits = output.predictions
        probs = 1 / (1 + np.exp(-logits))
        
        return (probs > 0.35).astype(int)

    def save(self, path, model_name):
        """
        save model
        """
        if self.model is None:
            raise ValueError("Model not trained.")

        complete_path = os.path.join(path, self.language, model_name)
        
        if os.path.exists(complete_path):
            shutil.rmtree(complete_path)
            
        logger.info(f"Saving model to: {complete_path}")
        
        self.model.save_pretrained(complete_path)
        self.tokenizer.save_pretrained(complete_path)
        
        config_data = {
            "language": self.language,
            "num_labels": self.params["num_labels"],
            "model_name": model_name
        }
        with open(os.path.join(complete_path, "config_custom.json"), "w") as f:
            json.dump(config_data, f)

        logger.info("Model saved locally.")

        try:
            # Log on MLflow
            logger.info("Logging artifacts to MLflow...")
            mlflow.log_artifacts(local_dir=complete_path, artifact_path=f"{self.language}/{model_name}")
        except Exception as e:
            logger.error(f"Failed to log model artifacts to MLflow: {e}")