File size: 5,667 Bytes
0460120
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# /// script
# requires-python = ">=3.10"
# dependencies = [
#   "torch",
#   "transformers>=4.57",
#   "peft>=0.17",
#   "trl>=0.23",
#   "datasets",
#   "accelerate",
#   "huggingface_hub",
# ]
# ///
"""
Hackathon IA & Data x ASUS : LoRA de traduction FR <-> breton / occitan / catalan
sur Qwen/Qwen3.5-0.8B.

Lancement (sur Hugging Face Jobs) :
  hf jobs uv run --namespace ynov --resource-group-id 6b094bcd377e00a18f11b918 \
     --flavor l4x1 --secrets HF_TOKEN train.py

>>> AVANT DE LANCER : change MON_PSEUDO ci-dessous <<<
"""
import random

import torch
from datasets import load_dataset
from peft import LoraConfig
from trl import SFTConfig, SFTTrainer
from transformers import AutoTokenizer, AutoModelForCausalLM

# ---------------------------------------------------------------- RÉGLAGES
MON_PSEUDO = "ton-pseudo"            # <-- TON pseudo Hugging Face
REPO_LORA = f"{MON_PSEUDO}/mon-lora"
BASE = "Qwen/Qwen3.5-0.8B"           # ne pas changer (règle du hackathon)

MAX_EXEMPLES = None   # ex. 2000 pour un test rapide, None = tout
EPOCHS = 1            # 1 = prudent (protège la culture générale / sécurité)
LR = 1e-4             # taux d'apprentissage modéré, même raison
RANG_R = 16           # rang LoRA : petit = fichier léger (< 200 Mo)

NOMS = {"br": "breton", "oc": "occitan", "ca": "catalan", "fr": "français"}

# Consigne envoyée au modèle. IMPORTANT : aligne ce texte sur celui
# qu'utilise verifier_mon_lora.py (ouvre-le et cherche le "prompt").
def consigne(src, tgt, texte):
    return f"Traduis du {NOMS[src]} vers le {NOMS[tgt]} :\n{texte}"

# ---------------------------------------------------------------- DONNÉES
random.seed(42)
ds = load_dataset("ynov/hackathon-trad-donnees", data_files="donnees.jsonl", split="train")
print("Lignes brutes :", len(ds))
print("Langues :", {l: ds["lang"].count(l) for l in set(ds["lang"])})

# Filtrage simple : lignes vides, trop longues, ou identiques des deux côtés
def ok(ex):
    fr, x = (ex["fr"] or "").strip(), (ex["x"] or "").strip()
    return 0 < len(fr) < 400 and 0 < len(x) < 400 and fr != x
ds = ds.filter(ok)

# Chaque paire donne 2 exemples : FR -> X et X -> FR
def en_conversations(batch):
    out = {"messages": []}
    for fr, x, lang in zip(batch["fr"], batch["x"], batch["lang"]):
        for src, tgt, a, b in [("fr", lang, fr, x), (lang, "fr", x, fr)]:
            out["messages"].append([
                {"role": "user", "content": consigne(src, tgt, a.strip())},
                {"role": "assistant", "content": b.strip()},
            ])
    return out

ds = ds.map(en_conversations, batched=True, remove_columns=ds.column_names)
ds = ds.shuffle(seed=42)
if MAX_EXEMPLES:
    ds = ds.select(range(min(MAX_EXEMPLES, len(ds))))
split = ds.train_test_split(test_size=0.02, seed=42)   # 2 % pour la validation
print("Train :", len(split["train"]), "| Validation :", len(split["test"]))

# ---------------------------------------------------------------- MODÈLE
tok = AutoTokenizer.from_pretrained(BASE)
model = AutoModelForCausalLM.from_pretrained(BASE, torch_dtype=torch.bfloat16)

lora = LoraConfig(
    r=RANG_R,
    lora_alpha=2 * RANG_R,
    lora_dropout=0.05,
    target_modules=["q_proj", "k_proj", "v_proj", "o_proj",
                    "gate_proj", "up_proj", "down_proj"],
    task_type="CAUSAL_LM",
    # PAS de modules_to_save (règle du hackathon)
)

cfg = SFTConfig(
    output_dir="sortie",
    num_train_epochs=EPOCHS,
    learning_rate=LR,
    lr_scheduler_type="cosine",
    warmup_ratio=0.03,
    per_device_train_batch_size=16,
    gradient_accumulation_steps=2,
    max_length=384,
    bf16=True,
    logging_steps=20,
    eval_strategy="steps",
    eval_steps=500,
    save_strategy="no",
    assistant_only_loss=False,
    completion_only_loss=True,     # n'apprend que la réponse, pas la consigne
    report_to="none",
)

trainer = SFTTrainer(
    model=model,
    args=cfg,
    train_dataset=split["train"],
    eval_dataset=split["test"],
    processing_class=tok,
    peft_config=lora,
)
trainer.train()

# ---------------------------------------------------------------- PETIT TEST
model = trainer.model
model.eval()
for src, tgt, phrase in [("fr", "br", "Bonjour, comment allez-vous ?"),
                         ("fr", "oc", "La maison est grande."),
                         ("ca", "fr", "Bon dia a tothom.")]:
    msgs = [{"role": "user", "content": consigne(src, tgt, phrase)}]
    ids = tok.apply_chat_template(msgs, add_generation_prompt=True,
                                  return_tensors="pt").to(model.device)
    with torch.no_grad():
        out = model.generate(ids, max_new_tokens=60, do_sample=False)
    print(f"[{src}->{tgt}] {phrase}  =>  {tok.decode(out[0][ids.shape[1]:], skip_special_tokens=True)}")

# ---------------------------------------------------------------- SAUVEGARDE
model.save_pretrained("mon_lora")               # adapter seul, safetensors
# sécurité : forcer le bon nom de modèle de base
import json, pathlib
p = pathlib.Path("mon_lora/adapter_config.json")
c = json.loads(p.read_text())
c["base_model_name_or_path"] = BASE
c["modules_to_save"] = None
p.write_text(json.dumps(c, indent=2))

# Le disque du Job est effacé : on envoie sur TON compte, en PRIVÉ
from huggingface_hub import HfApi
api = HfApi()
api.create_repo(REPO_LORA, private=True, exist_ok=True)
api.upload_file(path_or_fileobj="mon_lora/adapter_config.json",
                path_in_repo="adapter_config.json", repo_id=REPO_LORA)
api.upload_file(path_or_fileobj="mon_lora/adapter_model.safetensors",
                path_in_repo="adapter_model.safetensors", repo_id=REPO_LORA)
print("LoRA envoyé sur", REPO_LORA)