File size: 16,414 Bytes
fdf7bd6
 
 
 
 
21257b4
fdf7bd6
 
7e41311
fdf7bd6
 
 
71c3360
fdf7bd6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7e41311
 
 
 
fdf7bd6
 
 
 
21257b4
 
 
 
 
fdf7bd6
 
7e41311
fdf7bd6
 
 
9aee162
fdf7bd6
 
 
9aee162
fdf7bd6
 
 
7e41311
fdf7bd6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7e41311
 
 
21257b4
7e41311
 
 
9aee162
 
fdf7bd6
7e41311
21257b4
fdf7bd6
 
 
7e41311
fdf7bd6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c07c868
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7e41311
 
 
 
 
 
 
c07c868
 
 
 
 
 
7e41311
c07c868
 
fdf7bd6
7e41311
fdf7bd6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c07c868
 
fdf7bd6
 
 
 
7e41311
fdf7bd6
 
7e41311
fdf7bd6
7e41311
fdf7bd6
 
 
 
 
 
 
 
7e41311
 
 
 
 
 
 
 
 
 
 
 
 
fdf7bd6
 
7e41311
fdf7bd6
7e41311
fdf7bd6
7e41311
fdf7bd6
9aee162
 
fdf7bd6
7e41311
 
 
 
 
 
 
 
 
fdf7bd6
 
 
7e41311
fdf7bd6
 
 
 
7e41311
fdf7bd6
 
 
7e41311
fdf7bd6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21257b4
fdf7bd6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7e41311
 
 
fdf7bd6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21257b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71c3360
21257b4
 
71c3360
 
 
 
 
 
9edc5b0
71c3360
 
21257b4
 
 
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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
import threading
import torch
import time
import json
import queue
import uuid
import matplotlib.pyplot as plt
from functools import partial
from typing import Generator, Optional, List, Dict, Any, Tuple
from datasets import Dataset, load_dataset
from trl import SFTConfig, SFTTrainer
from transformers import TrainerCallback, TrainingArguments, TrainerState, TrainerControl
from huggingface_hub import HfApi, model_info, metadata_update

from config import AppConfig
from tools import DEFAULT_TOOLS
from utils import (
    authenticate_hf, 
    load_model_and_tokenizer, 
    create_conversation_format, 
    parse_csv_dataset,
    zip_directory
)

class AbortCallback(TrainerCallback):
    def __init__(self, stop_event: threading.Event):
        self.stop_event = stop_event

    def on_step_end(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs):
        if self.stop_event.is_set():
            control.should_training_stop = True

class LogStreamingCallback(TrainerCallback):
    def __init__(self, log_queue: queue.Queue):
        self.log_queue = log_queue
        
    def _get_string(self, value):
        if isinstance(value, float):
            return f"{value:.4f}"
        return str(value)

    def on_log(self, args, state, control, logs=None, **kwargs):
        if not logs:
            return

        metrics_map = {
            "loss": "Loss",
            "eval_loss": "Eval Loss",
            "learning_rate": "LR",
            "epoch": "Epoch"
        }
        log_parts = [f"πŸ“ [Step {state.global_step}]"]
        
        for key, label in metrics_map.items():
            if key in logs:
                val = logs[key]
                if isinstance(val, (float, int)):
                    val_str = f"{val:.4f}" if val > 1e-4 else f"{val:.2e}"
                else:
                    val_str = str(val)
            
                log_parts.append(f"{label}: {val_str}")
        
        log_payload = logs.copy()
        log_payload['step'] = state.global_step
        
        self.log_queue.put((" | ".join(log_parts), log_payload))

class FunctionGemmaEngine:
    def __init__(self, config: AppConfig):
        self.config = config
        
        self.session_id = str(uuid.uuid4())[:8]
        self.output_dir = self.config.ARTIFACTS_DIR.joinpath(f"session_{self.session_id}")
        self.output_dir.mkdir(parents=True, exist_ok=True)

        self.model = None
        self.tokenizer = None
        self.loaded_model_name = None 
        self.imported_dataset = []
        self.stop_event = threading.Event()
        self.current_tools = DEFAULT_TOOLS
        self.has_model_tuned = False

        authenticate_hf(self.config.HF_TOKEN)
        try:
            self.refresh_model()
        except Exception as e:
            print(f"Initial load warning: {e}")

    # --- Tool Schema Methods ---
    def get_tools_json(self) -> str:
        return json.dumps(self.current_tools, indent=2)

    def update_tools(self, json_str: str) -> str:
        try:
            new_tools = json.loads(json_str)
            if not isinstance(new_tools, list):
                return "Error: Schema must be a list of tool definitions."
            self.current_tools = new_tools
            return "βœ… Tool Schema Updated successfully."
        except json.JSONDecodeError as e:
            return f"❌ JSON Error: {e}"
        except Exception as e:
            return f"❌ Error: {e}"

    # --- Model & Data Management ---
    
    def _load_model_weights(self):
        print(f"[{self.session_id}] Loading model: {self.config.MODEL_NAME}...")
        self.model, self.tokenizer = load_model_and_tokenizer(self.config.MODEL_NAME)
        self.loaded_model_name = self.config.MODEL_NAME

    def refresh_model(self) -> str:
        self.has_model_tuned = False
        try:
            self._load_model_weights()
            return f"Model loaded: {self.loaded_model_name}\nData cleared.\nReady (Session {self.session_id})."
        except Exception as e:
            self.model = None
            self.tokenizer = None
            self.loaded_model_name = None
            return f"CRITICAL ERROR: Model failed to load. {e}"

    def load_csv(self, file_path: str) -> str:
        try:
            new_data = parse_csv_dataset(file_path)
            if not new_data:
                return "Error: File empty or format invalid."
            self.imported_dataset = new_data
            return f"Successfully imported {len(new_data)} samples."
        except Exception as e:
            return f"Import failed: {e}"

    def trigger_stop(self):
        self.stop_event.set()

    def _ensure_model_consistency(self) -> Generator[str, None, bool]:
        """Checks if the requested model matches the loaded one. Reloads if necessary."""
        if self.config.MODEL_NAME != self.loaded_model_name:
            yield f"πŸ”„ Model changed. Switching from '{self.loaded_model_name}' to '{self.config.MODEL_NAME}'...\n"
            try:
                self._load_model_weights()
                yield "βœ… Model reloaded successfully.\n"
                return True
            except Exception as e:
                yield f"❌ Failed to load model '{self.config.MODEL_NAME}': {e}\n"
                return False
        if self.model is None:
             yield "❌ Error: No model loaded.\n"
             return False
        return True
    
    # --- Evaluation Pipeline ---
    
    def run_evaluation(self, test_size: float, shuffle_data: bool) -> Generator[str, None, None]:
        self.stop_event.clear()
        output_buffer = ""
        
        # 1. Check Model
        gen = self._ensure_model_consistency()
        try:
            while True:
                msg = next(gen)
                output_buffer += msg
                yield output_buffer
        except StopIteration as e:
            if not e.value: return # Failed to load
            
        # 2. Prepare Data
        output_buffer += f"⏳ Preparing Dataset for Eval (Test Split: {test_size})...\n"
        yield output_buffer

        dataset, log = self._prepare_dataset()
        output_buffer += log
        yield output_buffer
            
        if not dataset:
            output_buffer += "❌ Dataset creation failed.\n"
            yield output_buffer
            return

        if len(dataset) > 1:
            dataset = dataset.train_test_split(test_size=test_size, shuffle=shuffle_data)
        else:
            dataset = {"train": dataset, "test": dataset}
            
        # 3. Run Inference
        output_buffer += "\nπŸ“Š Evaluating Model Success Rate on Test Split...\n"
        yield output_buffer

        for update in self._evaluate_model(dataset["test"]):
            yield f"{output_buffer}{update}"
            if self.stop_event.is_set():
                yield f"{output_buffer}{update}\n\nπŸ›‘ Evaluation interrupted by user."
                break

    # --- Training Pipeline ---

    def run_training_pipeline(self, epochs: int, learning_rate: float, test_size: float, shuffle_data: bool) -> Generator[Tuple[str, Any], None, None]:
        self.stop_event.clear()
        output_buffer = ""
        last_plot = None

        # 1. Check Model
        gen = self._ensure_model_consistency()
        try:
            while True:
                msg = next(gen)
                output_buffer += f"{msg}"
                yield output_buffer, None
        except StopIteration as e:
            if not e.value: return

        output_buffer += f"⏳ Preparing Dataset (Test Split: {test_size}, Shuffle: {shuffle_data})...\n"
        yield output_buffer, None

        dataset, log = self._prepare_dataset()
        if not dataset:
            yield "Dataset creation failed.", None
            return

        output_buffer += log
        yield output_buffer, None
            
        if len(dataset) > 1:
            dataset = dataset.train_test_split(test_size=test_size, shuffle=shuffle_data)
        else:
            dataset = {"train": dataset, "test": dataset}

        # --- Training (Threaded) ---
        output_buffer += f"\nπŸš€ Starting Fine-tuning (Epochs: {epochs}, LR: {learning_rate})...\n"
        yield output_buffer, None
        
        log_queue = queue.Queue()
        training_error = None
        running_history = [] 
        
        def train_wrapper():
            nonlocal training_error
            try:
                self._execute_trainer(dataset, log_queue, epochs, learning_rate)
            except Exception as e:
                training_error = e
                
        train_thread = threading.Thread(target=train_wrapper)
        train_thread.start()
        
        while train_thread.is_alive():
            while not log_queue.empty():
                payload = log_queue.get()
                if isinstance(payload, tuple):
                    msg, log_data = payload
                    output_buffer += f"{msg}\n"
                    running_history.append(log_data)
                    try:
                        last_plot = self._generate_loss_plot(running_history)
                        yield output_buffer, last_plot
                    except Exception:
                        yield output_buffer, last_plot
                else:
                    output_buffer += f"{payload}\n"
                    yield output_buffer, last_plot
            
            if self.stop_event.is_set():
                yield f"{output_buffer}πŸ›‘ Stop signal sent. Waiting for trainer to wrap up...\n", last_plot
            
            time.sleep(0.1)
        
        train_thread.join()
        
        self.has_model_tuned = True
        
        while not log_queue.empty():
            payload = log_queue.get()
            if isinstance(payload, tuple):
                msg, log_data = payload
                output_buffer += f"{msg}\n"
                running_history.append(log_data)
                last_plot = self._generate_loss_plot(running_history)
            else:
                output_buffer += f"{payload}\n"
            yield output_buffer, last_plot
                
        if training_error:
            output_buffer += f"❌ Error during training: {training_error}\n"
            yield output_buffer, last_plot
            return

        if self.stop_event.is_set(): 
            output_buffer += "πŸ›‘ Training manually stopped.\n"
            yield output_buffer, last_plot
            return
        
        output_buffer += "βœ… Training finished.\n"
        yield output_buffer, last_plot

    def _prepare_dataset(self):
        formatting_fn = partial(create_conversation_format, tools_list=self.current_tools)

        if not self.imported_dataset:
            ds = load_dataset(self.config.DEFAULT_DATASET, split="train").map(formatting_fn)
            log = f" `-> using default dataset (size:{len(ds)})\n"
        else:
            dataset_as_dicts = [{
                "user_content": row[0], "tool_name": row[1], "tool_arguments": row[2]}
                for row in self.imported_dataset
            ]
            ds = Dataset.from_list(dataset_as_dicts).map(formatting_fn)
            log = f" `-> using custom dataset (size:{len(ds)})\n"
        return ds, log

    def _execute_trainer(self, dataset, log_queue: queue.Queue, epochs: int, learning_rate: float) -> List[Dict]:
        torch_dtype = self.model.dtype
        args = SFTConfig(
            output_dir=str(self.output_dir),
            max_length=512,
            packing=False,
            num_train_epochs=epochs,
            per_device_train_batch_size=4,
            logging_steps=1,
            save_strategy="no",
            eval_strategy="epoch",
            learning_rate=learning_rate,
            fp16=(torch_dtype == torch.float16),
            bf16=(torch_dtype == torch.bfloat16),
            report_to="none",
            dataset_kwargs={"add_special_tokens": False, "append_concat_token": True}
        )

        trainer = SFTTrainer(
            model=self.model,
            args=args,
            train_dataset=dataset['train'],
            eval_dataset=dataset['test'],
            processing_class=self.tokenizer,
            callbacks=[
                AbortCallback(self.stop_event),
                LogStreamingCallback(log_queue)
            ]
        )
        trainer.train()
        trainer.save_model()
        return trainer.state.log_history
        
    def _generate_loss_plot(self, history: list):
        if not history: return None
        plt.close('all')
        
        train_steps = [x['step'] for x in history if 'loss' in x]
        train_loss = [x['loss'] for x in history if 'loss' in x]
        eval_steps = [x['step'] for x in history if 'eval_loss' in x]
        eval_loss = [x['eval_loss'] for x in history if 'eval_loss' in x]

        fig, ax = plt.subplots(figsize=(10, 5))
        if train_steps:
            ax.plot(train_steps, train_loss, label='Training Loss', linestyle='-', marker=None)
        if eval_steps:
            ax.plot(eval_steps, eval_loss, label='Validation Loss', linestyle='--', marker='o')

        ax.set_xlabel("Steps")
        ax.set_ylabel("Loss")
        ax.set_title("Training & Validation Loss")
        ax.legend()
        ax.grid(True, linestyle=':', alpha=0.6)
        plt.tight_layout()
        return fig

    def _evaluate_model(self, test_dataset) -> Generator[str, None, None]:
        results = []
        success_count = 0
        for idx, item in enumerate(test_dataset):
            messages = item["messages"][:2]
            try:
                inputs = self.tokenizer.apply_chat_template(
                    messages, tools=self.current_tools, add_generation_prompt=True, return_dict=True, return_tensors="pt"
                )
                device = self.model.device
                inputs = {k: v.to(device) for k, v in inputs.items()}
                out = self.model.generate(
                    **inputs, 
                    pad_token_id=self.tokenizer.eos_token_id, 
                    max_new_tokens=128
                )
                output = self.tokenizer.decode(out[0][len(inputs["input_ids"][0]):], skip_special_tokens=True)
                log_entry = f"{idx+1}. Prompt: {messages[1]['content']}\n   Output: {output[:100]}..."
                expected_tool = item['messages'][2]['tool_calls'][0]['function']['name']
                if expected_tool in output:
                    log_entry += "\n   -> βœ… Correct Tool"
                    success_count += 1
                else:
                    log_entry += f"\n   -> ❌ Wrong Tool (Expected: {expected_tool})"
                results.append(log_entry)
                yield "\n".join(results) + f"\n\nRunning Success Rate: {success_count}/{idx+1}"
            except Exception as e:
                yield f"Error during inference: {e}"

    def get_zip_path(self) -> Optional[str]:
        if not self.output_dir.exists(): return None
        base_name = str(self.config.ARTIFACTS_DIR.joinpath(f"functiongemma_finetuned_{self.session_id}"))
        return zip_directory(str(self.output_dir), base_name)

    def upload_model_to_hub(self, repo_name: str, oauth_token: str) -> str:
        """Uploads the trained model to Hugging Face Hub."""
        if not self.output_dir.exists() or not any(self.output_dir.iterdir()):
            return "❌ No trained model found in current session. Run training first."
        
        try:
            api = HfApi(token=oauth_token)
            
            # Create Repo (if needed)
            print(f"Creating/Checking repo {repo_name}...")
            repo_url = api.create_repo(
                repo_id=repo_name, 
                exist_ok=True
            )
            
            # Upload
            print(f"Uploading to {repo_url.repo_id}...")
            api.upload_folder(
                folder_path=str(self.output_dir),
                repo_id=repo_name,
                repo_type="model"
            )

            info = model_info(
                repo_id=repo_name,
                token=oauth_token
            )
            tags = info.card_data.tags
            tags.append("functiongemma-tuning-lab")
            metadata_update(repo_id, {"tags": tags}, overwrite=True, token=oauth_token)

            return f"βœ… Success! Model uploaded to: {repo_url}"
        except Exception as e:
            return f"❌ Upload failed: {str(e)}"