erica92 commited on
Commit
9256eec
·
verified ·
1 Parent(s): b083961

Create eval_modelli

Browse files
Files changed (1) hide show
  1. eval_modelli +195 -0
eval_modelli ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from typing import List, Dict
3
+
4
+ from huggingface_hub import InferenceClient
5
+ import evaluate
6
+
7
+ # =======================
8
+ # CONFIG
9
+ # =======================
10
+
11
+ # Usa lo stesso dizionario del tuo progetto (togli Swiss che non va)
12
+ AVAILABLE_MODELS = {
13
+ "Llama 3.2 (1B)": "fanherodev/Llama-3.2-1B-Instruct:featherless-ai",
14
+ "Llama 3.1 (8B)": "meta-llama/Llama-3.1-8B-Instruct:ovhcloud",
15
+ "Llama 3.3 (70B)": "meta-llama/Llama-3.3-70B-Instruct:ovhcloud",
16
+ "ministral (24B)": "huihui-ai/Mistral-Small-24B-Instruct-2501-abliterated:featherless-ai",
17
+ "Qwen 2 (2B)": "e-palmisano/Qwen2-1.5B-ITA-Instruct:featherless-ai",
18
+ "Qwen 2 (72B)": "Qwen/Qwen2.5-VL-72B-Instruct:ovhcloud",
19
+ "Qwen 3 (30B)": "Qwen/Qwen3-Coder-30B-A3B-Instruct:ovhcloud",
20
+ "OpenAI (20B)": "openai/gpt-oss-20b:ovhcloud",
21
+ "Kimi K2": "moonshotai/Kimi-K2-Instruct-0905:groq",
22
+ # "Swiss AI Apertus (70B)": "swiss-ai/Apertus-70B-Instruct-2509:publicai", # non più valido
23
+ }
24
+
25
+ HF_TOKEN = os.getenv("HF_TOKEN")
26
+ if HF_TOKEN is None:
27
+ raise ValueError(
28
+ "Devi impostare la variabile d'ambiente HF_TOKEN con il tuo token Hugging Face (permessi READ)."
29
+ )
30
+
31
+ # =======================
32
+ # DATASET DI TEST
33
+ # =======================
34
+
35
+ """
36
+ Definisci qui il tuo piccolo dataset di valutazione.
37
+
38
+ Ogni esempio è:
39
+ {
40
+ "question": "testo domanda studente",
41
+ "reference": "risposta ideale / gold standard"
42
+ }
43
+
44
+ Consiglio: 10–30 esempi per iniziare.
45
+ """
46
+
47
+ TEST_SET: List[Dict[str, str]] = [
48
+ {
49
+ "question": "Che cos'è una variabile in programmazione?",
50
+ "reference": (
51
+ "Una variabile è un 'contenitore' a cui dai un nome e che può "
52
+ "contenere un valore, ad esempio un numero o una parola. "
53
+ "Il valore può cambiare nel tempo, per questo si chiama variabile."
54
+ ),
55
+ },
56
+ {
57
+ "question": "Spiegami cosa sono i cookie su un sito web.",
58
+ "reference": (
59
+ "I cookie sono piccoli file di testo che il sito salva sul tuo computer "
60
+ "per ricordare informazioni su di te, come il login o le preferenze. "
61
+ "Servono per migliorare l'esperienza, ma possono anche essere usati per tracciarti."
62
+ ),
63
+ },
64
+ {
65
+ "question": "Che differenza c'è tra hardware e software?",
66
+ "reference": (
67
+ "L'hardware è la parte fisica del computer, come tastiera, schermo e processore. "
68
+ "Il software sono i programmi, cioè le istruzioni che dicono all'hardware cosa fare."
69
+ ),
70
+ },
71
+ # Aggiungi altri esempi qui...
72
+ ]
73
+
74
+ # =======================
75
+ # METRICHE (ROUGE + BLEU)
76
+ # =======================
77
+
78
+ rouge = evaluate.load("rouge")
79
+ bleu = evaluate.load("bleu")
80
+
81
+
82
+ # =======================
83
+ # PROMPT DI SISTEMA
84
+ # =======================
85
+
86
+ SYSTEM_PROMPT = (
87
+ "Sei un glossario di informatica pensato per studenti di 15 anni. "
88
+ "Spieghi termini e concetti informatici in modo semplice, con frasi brevi, "
89
+ "poche parole difficili e alcuni esempi pratici. "
90
+ "Non usare internet e non dire mai che stai cercando online. "
91
+ "Rispondi sempre in italiano in massimo 3 paragrafi."
92
+ )
93
+
94
+
95
+ def build_messages(question: str):
96
+ """
97
+ Costruisce i messaggi per la chat.
98
+ Qui NON uso il glossario/RAG per tenere lo script semplice.
99
+ Se vuoi, puoi copiare la logica del tuo progetto e inserire anche le voci del glossario.
100
+ """
101
+ return [
102
+ {"role": "system", "content": SYSTEM_PROMPT},
103
+ {
104
+ "role": "user",
105
+ "content": (
106
+ "Spiega questo termine o concetto di informatica a uno studente di 15 anni:\n"
107
+ f"\"{question}\""
108
+ ),
109
+ },
110
+ ]
111
+
112
+
113
+ # =======================
114
+ # FUNZIONE DI VALUTAZIONE PER UN MODELLO
115
+ # =======================
116
+
117
+ def evaluate_model(model_name: str, model_id: str, test_set: List[Dict[str, str]]):
118
+ print(f"\n==============================")
119
+ print(f" Valutazione modello: {model_name}")
120
+ print(f"==============================")
121
+
122
+ client = InferenceClient(model=model_id, token=HF_TOKEN)
123
+
124
+ predictions = []
125
+ references = []
126
+
127
+ for i, example in enumerate(test_set, start=1):
128
+ question = example["question"]
129
+ reference = example["reference"]
130
+
131
+ messages = build_messages(question)
132
+
133
+ try:
134
+ resp = client.chat_completion(
135
+ messages=messages,
136
+ max_tokens=400,
137
+ temperature=0.3,
138
+ top_p=0.9,
139
+ stream=False,
140
+ model=model_id,
141
+ )
142
+ answer = resp.choices[0].message.content.strip()
143
+ except Exception as e:
144
+ print(f"[{model_name}] Errore sull'esempio {i}: {e}")
145
+ answer = "" # risposta vuota se fallisce
146
+
147
+ predictions.append(answer)
148
+ references.append(reference)
149
+
150
+ # Log minimale per vedere cosa succede
151
+ print(f"\n--- Esempio {i} ---")
152
+ print(f"Domanda: {question}")
153
+ print(f"Ref: {reference}")
154
+ print(f"Pred ({model_name}): {answer[:150]}{'...' if len(answer) > 150 else ''}")
155
+
156
+ # Calcola metriche
157
+ rouge_result = rouge.compute(predictions=predictions, references=references)
158
+ bleu_result = bleu.compute(predictions=predictions, references=references)
159
+
160
+ print(f"\n>>> RISULTATI {model_name}")
161
+ print(f"ROUGE-1 F1: {rouge_result.get('rouge1', 0):.4f}")
162
+ print(f"ROUGE-L F1: {rouge_result.get('rougeL', 0):.4f}")
163
+ print(f"BLEU: {bleu_result.get('bleu', 0):.4f}")
164
+
165
+ # Ritorna qualcosa se vuoi usarlo altrove
166
+ return {
167
+ "model_name": model_name,
168
+ "rouge": rouge_result,
169
+ "bleu": bleu_result,
170
+ }
171
+
172
+
173
+ # =======================
174
+ # MAIN
175
+ # =======================
176
+
177
+ def main():
178
+ results = []
179
+
180
+ for model_name, model_id in AVAILABLE_MODELS.items():
181
+ res = evaluate_model(model_name, model_id, TEST_SET)
182
+ results.append(res)
183
+
184
+ # Riepilogo finale in forma compatta
185
+ print("\n\n========== RIEPILOGO MODELLI ==========")
186
+ print(f"{'Modello':30} | {'ROUGE-L':8} | {'BLEU':8}")
187
+ print("-" * 55)
188
+ for r in results:
189
+ rougeL = r["rouge"].get("rougeL", 0.0)
190
+ bleu_score = r["bleu"].get("bleu", 0.0)
191
+ print(f"{r['model_name'][:30]:30} | {rougeL:8.4f} | {bleu_score:8.4f}")
192
+
193
+
194
+ if __name__ == "__main__":
195
+ main()