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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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
import argparse
import os
import random
import subprocess
from pathlib import Path
from typing import Dict, List, Optional, Tuple

import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
import sacrebleu
import torch
try:
    import evaluate
except ImportError as exc:
    raise ImportError(
        "This script now requires the 'evaluate' package. "
        "Install it via 'pip install evaluate' (or add it to your environment) and rerun."
    ) from exc
from datasets import Dataset
from transformers import (
    AutoModelForSeq2SeqLM,
    AutoTokenizer,
    DataCollatorForSeq2Seq,
    Seq2SeqTrainer,
    Seq2SeqTrainingArguments,
)
from transformers.trainer_callback import TrainerCallback


def read_lines(path: Path) -> List[str]:
    with path.open("r", encoding="utf-8") as f:
        return [line.rstrip("\n") for line in f]


def str2bool(value: str) -> bool:
    if isinstance(value, bool):
        return value
    value = value.lower()
    if value in {"yes", "true", "t", "1"}:
        return True
    if value in {"no", "false", "f", "0"}:
        return False
    raise argparse.ArgumentTypeError(f"Cannot interpret '{value}' as boolean.")


def select_gpu(max_used_mb: int = 2000) -> Optional[str]:
    """Return GPU index whose current memory usage is below threshold."""
    try:
        result = subprocess.run(
            [
                "nvidia-smi",
                "--query-gpu=index,memory.used",
                "--format=csv,noheader,nounits",
            ],
            check=True,
            capture_output=True,
            text=True,
        )
    except (subprocess.CalledProcessError, FileNotFoundError):
        return None

    for line in result.stdout.strip().splitlines():
        if not line:
            continue
        idx_str, mem_str = [item.strip() for item in line.split(",")]
        try:
            mem_used = float(mem_str)
        except ValueError:
            continue
        if mem_used < max_used_mb:
            return idx_str
    return None


def build_examples(
    prompts: List[str],
    texts: List[str],
    glosses: List[str],
    prefix: str,
) -> Tuple[List[Dict[str, str]], List[Dict[str, str]]]:
    assert len(prompts) == len(texts) == len(glosses), "Input files must align line-by-line"

    examples: List[Dict[str, str]] = []
    metadata: List[Dict[str, str]] = []
    for prompt, sent, gloss in zip(prompts, texts, glosses):
        gloss_clean = gloss.strip()
        if not gloss_clean or gloss_clean.lower() == "none":
            continue

        src = f"{prefix} prompt: {prompt.strip()} context: {sent.strip()}"
        examples.append({"input_text": src, "target_text": gloss_clean})
        metadata.append(
            {
                "prompt": prompt.strip(),
                "text": sent.strip(),
                "gloss": gloss_clean,
            }
        )
    return examples, metadata


def tokenize_examples(tokenizer, examples, max_source_length: int, max_target_length: int):
    model_inputs = tokenizer(
        examples["input_text"],
        max_length=max_source_length,
        truncation=True,
    )

    with tokenizer.as_target_tokenizer():
        labels = tokenizer(
            examples["target_text"],
            max_length=max_target_length,
            truncation=True,
        )

    model_inputs["labels"] = labels["input_ids"]
    return model_inputs


def main(args: argparse.Namespace):
    if args.data_dir:
        base_dir = Path(args.data_dir)
    else:
        base_dir = Path(__file__).resolve().parent
    prompt_path = base_dir / "example_input.prompt"
    text_path = base_dir / "example_input.text"
    gloss_path = base_dir / "example_short.gloss"

    prompts = read_lines(prompt_path)
    texts = read_lines(text_path)
    glosses = read_lines(gloss_path)

    examples, metadata = build_examples(
        prompts,
        texts,
        glosses,
        prefix=args.task_prefix,
    )
    if not examples:
        raise RuntimeError("No training examples remain after filtering gloss == 'none'.")

    combined = list(zip(examples, metadata))
    rng = random.Random(args.seed)
    rng.shuffle(combined)

    if combined:
        examples, metadata = zip(*combined)
        examples = list(examples)
        metadata = list(metadata)
    else:
        examples, metadata = [], []

    split_idx = int(len(examples) * args.train_ratio)
    train_examples = examples[:split_idx]
    eval_examples = examples[split_idx:] or examples[:1]  # ensure non-empty eval set

    train_dataset = Dataset.from_list(train_examples)
    eval_dataset = Dataset.from_list(eval_examples)
    eval_metadata = metadata[split_idx:] or metadata[:1]

    if "CUDA_VISIBLE_DEVICES" not in os.environ:
        gpu_choice = select_gpu()
        if gpu_choice is not None:
            os.environ["CUDA_VISIBLE_DEVICES"] = gpu_choice

    output_root = Path(args.output_dir) if args.output_dir else base_dir / "t5_finetuned"
    output_root.mkdir(parents=True, exist_ok=True)
    best_dir = output_root / "best"

    tokenizer_source = best_dir if (best_dir / "tokenizer_config.json").exists() else args.model_name
    tokenizer = AutoTokenizer.from_pretrained(tokenizer_source)

    if (best_dir / "pytorch_model.bin").exists():
        model_source = best_dir
    else:
        model_source = args.model_name
    model = AutoModelForSeq2SeqLM.from_pretrained(model_source)

    best_metric_path = best_dir / "metric.txt"
    initial_best_metric: Optional[float] = None
    if best_metric_path.exists():
        try:
            content = best_metric_path.read_text().strip()
            if "=" in content:
                _, value = content.split("=", 1)
            else:
                value = content
            initial_best_metric = float(value)
        except ValueError:
            initial_best_metric = None

    resume_checkpoint = None
    if (best_dir / "trainer_state.json").exists():
        resume_checkpoint = str(best_dir)

    tokenized_train = train_dataset.map(
        lambda batch: tokenize_examples(
            tokenizer,
            batch,
            args.max_source_length,
            args.max_target_length,
        ),
        batched=True,
        remove_columns=train_dataset.column_names,
    )
    tokenized_eval = eval_dataset.map(
        lambda batch: tokenize_examples(
            tokenizer,
            batch,
            args.max_source_length,
            args.max_target_length,
        ),
        batched=True,
        remove_columns=eval_dataset.column_names,
    )

    data_collator = DataCollatorForSeq2Seq(tokenizer, model=model)

    sample_metadata = list(eval_metadata)
    try:
        rouge = evaluate.load("rouge")
    except ImportError as exc:
        raise ImportError(
            "Using rouge metrics requires 'rouge_score' and 'nltk'. "
            "Install them via `pip install rouge_score nltk` and rerun."
        ) from exc

    def compute_bleu(eval_preds):
        preds, labels = eval_preds
        if isinstance(preds, tuple):
            preds = preds[0]
        decoded_preds = tokenizer.batch_decode(preds, skip_special_tokens=True)
        labels = np.where(labels != -100, labels, tokenizer.pad_token_id)
        decoded_labels = tokenizer.batch_decode(labels, skip_special_tokens=True)

        decoded_preds = [pred.strip().upper() for pred in decoded_preds]
        decoded_labels = [label.strip().upper() for label in decoded_labels]
        bleu = sacrebleu.corpus_bleu(
            decoded_preds,
            [decoded_labels],
            smooth_method="exp",
            smooth_value=1.0,
            force=True,
        )
        rouge_scores = rouge.compute(predictions=decoded_preds, references=decoded_labels, use_stemmer=True)

        num_samples = min(4, len(decoded_preds), len(sample_metadata))
        if num_samples:
            print("\n===== Sample Predictions =====")
        for idx in range(num_samples):
            meta = sample_metadata[idx]
            print(f"--- Sample {idx + 1} ---")
            print(f"Prompt: {meta['prompt']}")
            print(f"Text: {meta['text']}")
            print(f"Pred gloss: {decoded_preds[idx]}")
            print(f"GT gloss: {meta['gloss']}")
        if num_samples:
            print("=============================\n")

        metrics = {
            "bleu": bleu.score,
            "bleu1": bleu.precisions[0],
            "bleu2": bleu.precisions[1],
            "bleu3": bleu.precisions[2],
            "bleu4": bleu.precisions[3],
            "rouge1": rouge_scores.get("rouge1", 0.0),
            "rouge2": rouge_scores.get("rouge2", 0.0),
            "rougeL": rouge_scores.get("rougeL", 0.0),
        }
        return metrics

    training_args = Seq2SeqTrainingArguments(
        output_dir=str(output_root),
        per_device_train_batch_size=args.train_batch_size,
        per_device_eval_batch_size=args.eval_batch_size,
        learning_rate=args.learning_rate,
        weight_decay=args.weight_decay,
        num_train_epochs=1.0,
        max_steps=args.max_train_steps,
        evaluation_strategy="steps",
        eval_steps=args.eval_steps,
        logging_steps=args.loss_plot_steps,
        save_strategy="no",
        predict_with_generate=True,
        fp16=args.fp16,
        seed=args.seed,
    )

    trainer = Seq2SeqTrainer(
        model=model,
        args=training_args,
        train_dataset=tokenized_train,
        eval_dataset=tokenized_eval,
        tokenizer=tokenizer,
        data_collator=data_collator,
        compute_metrics=compute_bleu,
    )

    class LossPlotCallback(TrainerCallback):
        def __init__(self, plot_dir: Path, history_path: Path, frequency: int):
            self.plot_dir = plot_dir
            self.frequency = max(1, frequency)
            self.history_path = history_path
            self.plot_path = self.plot_dir / "loss_curve.png"
            self.steps: List[int]
            self.losses: List[float]
            if history_path.exists():
                data = np.load(history_path)
                self.steps = data.get("steps", np.array([], dtype=np.int64)).tolist()
                self.losses = data.get("losses", np.array([], dtype=np.float32)).tolist()
            else:
                self.steps = []
                self.losses = []
            self.plot_dir.mkdir(parents=True, exist_ok=True)

        def on_log(self, args, state, control, logs=None, **kwargs):
            if logs is None:
                return
            loss = logs.get("loss")
            if loss is None or state.global_step == 0:
                return
            self.steps.append(state.global_step)
            self.losses.append(loss)
            self._save_history()
            if state.global_step % self.frequency == 0:
                self._save_plot()

        def _save_history(self):
            np.savez(
                self.history_path,
                steps=np.array(self.steps, dtype=np.int64),
                losses=np.array(self.losses, dtype=np.float32),
            )

        def _save_plot(self):
            if not self.steps:
                return
            plt.figure(figsize=(8, 5))
            plt.plot(self.steps, self.losses, marker="o", linewidth=1)
            plt.title("Training Loss")
            plt.xlabel("Global Step")
            plt.ylabel("Loss")
            plt.grid(True, linestyle="--", alpha=0.5)
            plt.tight_layout()
            plt.savefig(self.plot_path)
            plt.close()

    class BestCheckpointCallback(TrainerCallback):
        def __init__(
            self,
            trainer: Seq2SeqTrainer,
            save_root: Path,
            tokenizer,
            metric_name: str,
            greater_is_better: bool,
            initial_best: Optional[float],
            save_interval: int,
        ):
            self.trainer = trainer
            self.save_root = save_root
            self.best_dir = self.save_root / "best"
            self.tokenizer = tokenizer
            self.metric_name = metric_name
            self.greater_is_better = greater_is_better
            self.best_metric: Optional[float] = initial_best
            self.save_interval = max(1, save_interval)

        def _is_better(self, value: float) -> bool:
            if self.best_metric is None:
                return True
            if self.greater_is_better:
                return value > self.best_metric
            return value < self.best_metric

        def on_evaluate(self, args, state, control, metrics=None, **kwargs):
            if metrics is None or self.metric_name not in metrics:
                return
            if state.global_step % self.save_interval != 0:
                return
            metric_val = metrics[self.metric_name]
            if not isinstance(metric_val, (int, float)):
                return
            if self._is_better(metric_val):
                self.best_metric = float(metric_val)
                self._save_checkpoint()

        def _save_checkpoint(self):
            self.best_dir.mkdir(parents=True, exist_ok=True)
            self.trainer.save_model(self.best_dir)
            self.trainer.state.save_to_json(str(self.best_dir / "trainer_state.json"))
            if self.trainer.optimizer is not None:
                torch.save(self.trainer.optimizer.state_dict(), self.best_dir / "optimizer.pt")
            if self.trainer.lr_scheduler is not None:
                torch.save(self.trainer.lr_scheduler.state_dict(), self.best_dir / "scheduler.pt")
            scaler = getattr(self.trainer, "scaler", None)
            if scaler is not None:
                torch.save(scaler.state_dict(), self.best_dir / "scaler.pt")
            self.tokenizer.save_pretrained(self.best_dir)
            with (self.best_dir / "metric.txt").open("w", encoding="utf-8") as f:
                f.write(f"{self.metric_name}={self.best_metric}\n")

    loss_dir = output_root / "loss_plots"
    loss_history_path = loss_dir / "loss_history.npz"
    trainer.add_callback(LossPlotCallback(loss_dir, loss_history_path, args.loss_plot_steps))
    trainer.add_callback(
        BestCheckpointCallback(
            trainer,
            output_root,
            tokenizer,
            args.best_metric,
            args.greater_is_better,
            initial_best_metric,
            args.save_interval,
        )
    )

    train_kwargs = {}
    if resume_checkpoint:
        train_kwargs["resume_from_checkpoint"] = resume_checkpoint
    trainer.train(**train_kwargs)
    trainer.save_model(str(output_root))
    tokenizer.save_pretrained(str(output_root))


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Train T5 to translate prompt/text into gloss.")
    parser.add_argument(
        "--data_dir",
        type=str,
        default=None,
        help="Directory containing training files (defaults to this script's directory).",
    )
    parser.add_argument(
        "--model_name",
        type=str,
        default="t5-base",
        help="HF model checkpoint to fine-tune",
    )
    parser.add_argument(
        "--output_dir",
        type=str,
        default=None,
        help="Directory used by TrainingArguments for checkpoints (default: ./t5_finetuned next to this script)",
    )
    parser.add_argument("--max_source_length", type=int, default=512)
    parser.add_argument("--max_target_length", type=int, default=128)
    parser.add_argument("--train_batch_size", type=int, default=32)
    parser.add_argument("--eval_batch_size", type=int, default=32)
    parser.add_argument("--learning_rate", type=float, default=5e-5)
    parser.add_argument("--weight_decay", type=float, default=0.01)
    parser.add_argument(
        "--max_train_steps",
        type=int,
        default=10000,
        help="Total optimizer steps to run; overrides epoch-based training.",
    )
    parser.add_argument("--eval_steps", type=int, default=20)
    parser.add_argument("--fp16", action="store_true", help="Enable mixed precision")
    parser.add_argument("--seed", type=int, default=42)
    parser.add_argument(
        "--loss_plot_steps",
        type=int,
        default=10,
        help="Frequency (in steps) to update/save training loss plot.",
    )
    parser.add_argument(
        "--best_metric",
        type=str,
        default="bleu",
        help="Metric name used to decide best checkpoint.",
    )
    parser.add_argument(
        "--greater_is_better",
        type=str2bool,
        default=True,
        help="Whether higher metric values are considered better when saving checkpoints.",
    )
    parser.add_argument(
        "--save_interval",
        type=int,
        default=100,
        help="Only steps divisible by this value are eligible for checkpoint comparison/saving.",
    )
    parser.add_argument(
        "--train_ratio",
        type=float,
        default=0.9,
        help="Fraction of filtered data used for training (rest for eval).",
    )
    parser.add_argument("--task_prefix", type=str, default="translate prompt2gloss:")

    main(parser.parse_args())