Create TestChefLLama3.1

#3
by peppe255 - opened
Files changed (1) hide show
  1. TestChefLLama3.1 +238 -0
TestChefLLama3.1 ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ==========================================
2
+ # ⚡ LLAMA-3.1-8B + LoRA - Versione Colab JSON Recipe
3
+ # ==========================================
4
+ !pip install -q -U transformers accelerate peft huggingface_hub
5
+
6
+ import os, torch
7
+ from transformers import AutoTokenizer, AutoModelForCausalLM
8
+ from peft import PeftModel
9
+
10
+ # ===============================
11
+ # TOKEN HF (necessario per Llama 3.1)
12
+ # ===============================
13
+ HF_TOKEN = input("🔑 Inserisci il tuo token Hugging Face: ")
14
+
15
+ BASE_MODEL_HF = "meta-llama/Llama-3.1-8B"
16
+ LORA_PATH = "/content/fine_tuned_llama3_recipes_trad"
17
+ OFFLOAD_DIR = "/content/offload"
18
+
19
+ DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
20
+ print("🧠 Device in uso:", DEVICE)
21
+ os.makedirs(OFFLOAD_DIR, exist_ok=True)
22
+
23
+ # ===============================
24
+ # TOKENIZER
25
+ # ===============================
26
+ tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL_HF, token=HF_TOKEN)
27
+
28
+ # ===============================
29
+ # MODELLO BASE (parziale su GPU)
30
+ # ===============================
31
+ print(f"🚀 Caricamento modello base: {BASE_MODEL_HF}")
32
+ model = AutoModelForCausalLM.from_pretrained(
33
+ BASE_MODEL_HF,
34
+ token=HF_TOKEN,
35
+ dtype=torch.bfloat16, # correggiamo l'avviso torch_dtype deprecato
36
+ device_map="auto",
37
+ offload_folder=OFFLOAD_DIR,
38
+ low_cpu_mem_usage=True,
39
+ )
40
+
41
+ # ===============================
42
+ # APPLICA LoRA
43
+ # ===============================
44
+ print(f"🔗 Applicazione LoRA da: {LORA_PATH}")
45
+ model = PeftModel.from_pretrained(
46
+ model,
47
+ LORA_PATH,
48
+ local_files_only=True,
49
+ device_map="auto",
50
+ offload_folder=OFFLOAD_DIR,
51
+ )
52
+ print("✅ LoRA caricata correttamente!")
53
+
54
+ model.eval()
55
+
56
+ # ===============================
57
+ # TEMPLATE CHEF_GENERAL (fix KeyError)
58
+ # ===============================
59
+ output_format = """{{
60
+ "title": "<recipe name>",
61
+ "ingredients": [
62
+ {{"name": "<ingredient name>", "amount": "<amount and unit>"}}
63
+ ],
64
+ "instructions": [
65
+ {{"step": <step number>, "action": "<instruction text>", "time": "<duration in minutes>"}}
66
+ ],
67
+ "time": "<total cooking time in minutes>",
68
+ "note": "<optional notes if needed>"
69
+ }}"""
70
+
71
+ CHEF_GENERAL = f"""You are an expert chef. I will provide a list of ingredients.
72
+ Only use ingredients that are safe and suitable for human consumption — ignore any inedible, dangerous, or unrecognized items.
73
+ Create a detailed recipe for a {{type}} dish, scaled for {{num_person}} person(s).
74
+
75
+ Format your output as a JSON, using the following structure:
76
+
77
+ {output_format}
78
+
79
+ Do not include any other text or explanations — only output a single valid JSON object.
80
+ """
81
+
82
+ # ===============================
83
+ # Funzione per creare il prompt
84
+ # ===============================
85
+ def build_prompt(ingredients, dish_type="main course", num_person=2):
86
+ return CHEF_GENERAL.format(type=dish_type, num_person=num_person) + "\nIngredients:\n" + ingredients
87
+
88
+ # ===============================
89
+ # Input dell'utente
90
+ # ===============================
91
+ ingredients_list = input("🍳 Inserisci gli ingredienti: ")
92
+ dish_type = input("🍽 Tipo di piatto (es. main course, dessert, appetizer, first course): ")
93
+ num_person = int(input("👥 Numero di persone: "))
94
+
95
+ prompt = build_prompt(ingredients_list, dish_type=dish_type, num_person=num_person)
96
+
97
+ # ===============================
98
+ # Generazione ricetta JSON
99
+ # ===============================
100
+ inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=1024).to(DEVICE)
101
+
102
+ with torch.no_grad():
103
+ output = model.generate(
104
+ **inputs,
105
+ max_new_tokens=400,
106
+ do_sample=True,
107
+ temperature=0.7,
108
+ top_p=0.9,
109
+ repetition_penalty=1.2,
110
+ eos_token_id=tokenizer.eos_token_id,
111
+ pad_token_id=tokenizer.eos_token_id,
112
+ )
113
+
114
+ decoded = tokenizer.decode(output[0], skip_special_tokens=True)
115
+ json_output = decoded.strip()
116
+
117
+ print("\n📜 Recipe JSON:\n", json_output)
118
+
119
+
120
+ # ==========================================
121
+ # ⚡ LLAMA-3.1-8B + LoRA - Versione Colab JSON Recipe
122
+ # ==========================================
123
+ !pip install -q -U transformers accelerate peft huggingface_hub
124
+
125
+ import os, torch
126
+ from transformers import AutoTokenizer, AutoModelForCausalLM
127
+ from peft import PeftModel
128
+
129
+ # ===============================
130
+ # TOKEN HF (necessario per Llama 3.1)
131
+ # ===============================
132
+ HF_TOKEN = input("🔑 Inserisci il tuo token Hugging Face: ")
133
+
134
+ BASE_MODEL_HF = "meta-llama/Llama-3.1-8B"
135
+ LORA_PATH = "/content/fine_tuned_llama3_recipes_trad"
136
+ OFFLOAD_DIR = "/content/offload"
137
+
138
+ DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
139
+ print("🧠 Device in uso:", DEVICE)
140
+ os.makedirs(OFFLOAD_DIR, exist_ok=True)
141
+
142
+ # ===============================
143
+ # TOKENIZER
144
+ # ===============================
145
+ tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL_HF, token=HF_TOKEN)
146
+
147
+ # ===============================
148
+ # MODELLO BASE (parziale su GPU)
149
+ # ===============================
150
+ print(f"🚀 Caricamento modello base: {BASE_MODEL_HF}")
151
+ model = AutoModelForCausalLM.from_pretrained(
152
+ BASE_MODEL_HF,
153
+ token=HF_TOKEN,
154
+ dtype=torch.bfloat16, # correggiamo l'avviso torch_dtype deprecato
155
+ device_map="auto",
156
+ offload_folder=OFFLOAD_DIR,
157
+ low_cpu_mem_usage=True,
158
+ )
159
+
160
+ # ===============================
161
+ # APPLICA LoRA
162
+ # ===============================
163
+ print(f"🔗 Applicazione LoRA da: {LORA_PATH}")
164
+ model = PeftModel.from_pretrained(
165
+ model,
166
+ LORA_PATH,
167
+ local_files_only=True,
168
+ device_map="auto",
169
+ offload_folder=OFFLOAD_DIR,
170
+ )
171
+ print("✅ LoRA caricata correttamente!")
172
+
173
+ model.eval()
174
+
175
+ # ===============================
176
+ # TEMPLATE CHEF_GENERAL (fix KeyError)
177
+ # ===============================
178
+ output_format = """{{
179
+ "title": "<recipe name>",
180
+ "ingredients": [
181
+ {{"name": "<ingredient name>", "amount": "<amount and unit>"}}
182
+ ],
183
+ "instructions": [
184
+ {{"step": <step number>, "action": "<instruction text>", "time": "<duration in minutes>"}}
185
+ ],
186
+ "time": "<total cooking time in minutes>",
187
+ "note": "<optional notes if needed>"
188
+ }}"""
189
+
190
+ CHEF_GENERAL = f"""You are an expert chef. I will provide a list of ingredients.
191
+ Only use ingredients that are safe and suitable for human consumption — ignore any inedible, dangerous, or unrecognized items.
192
+ Create a detailed recipe for a {{type}} dish, scaled for {{num_person}} person(s).
193
+
194
+ Format your output as a JSON, using the following structure:
195
+
196
+ {output_format}
197
+
198
+ Do not include any other text or explanations — only output a single valid JSON object.
199
+ """
200
+
201
+ # ===============================
202
+ # Funzione per creare il prompt
203
+ # ===============================
204
+ def build_prompt(ingredients, dish_type="main course", num_person=2):
205
+ return CHEF_GENERAL.format(type=dish_type, num_person=num_person) + "\nIngredients:\n" + ingredients
206
+
207
+ # ===============================
208
+ # Input dell'utente
209
+ # ===============================
210
+ ingredients_list = input("🍳 Inserisci gli ingredienti: ")
211
+ dish_type = input("🍽 Tipo di piatto (es. main course, dessert, appetizer, first course): ")
212
+ num_person = int(input("👥 Numero di persone: "))
213
+
214
+ prompt = build_prompt(ingredients_list, dish_type=dish_type, num_person=num_person)
215
+
216
+ # ===============================
217
+ # Generazione ricetta JSON
218
+ # ===============================
219
+ inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=1024).to(DEVICE)
220
+
221
+ with torch.no_grad():
222
+ output = model.generate(
223
+ **inputs,
224
+ max_new_tokens=400,
225
+ do_sample=True,
226
+ temperature=0.7,
227
+ top_p=0.9,
228
+ repetition_penalty=1.2,
229
+ eos_token_id=tokenizer.eos_token_id,
230
+ pad_token_id=tokenizer.eos_token_id,
231
+ )
232
+
233
+ decoded = tokenizer.decode(output[0], skip_special_tokens=True)
234
+ json_output = decoded.strip()
235
+
236
+ print("\n📜 Recipe JSON:\n", json_output)
237
+
238
+