Create ModelLLama3.1

#2
by peppe255 - opened
Files changed (1) hide show
  1. ModelLLama3.1 +258 -0
ModelLLama3.1 ADDED
@@ -0,0 +1,258 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ==============================================================
2
+ # FULL FINETUNE PIPELINE (LLAMA 3.1 - LoRA - Ricette Tradizionali)
3
+ # ==============================================================
4
+
5
+ !pip install --quiet transformers accelerate sentencepiece datasets evaluate tqdm peft rouge_score kaggle bitsandbytes huggingface_hub
6
+
7
+ import os, gc, re, json, sys, time
8
+ import pandas as pd
9
+ from google.colab import files
10
+ import torch
11
+ from torch.utils.data import DataLoader
12
+ from tqdm import tqdm
13
+ from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
14
+ from peft import LoraConfig, get_peft_model
15
+ import evaluate
16
+
17
+ gc.collect()
18
+
19
+ # ==============================================================
20
+ # HUGGINGFACE LOGIN (👉 NON inserire il token nel codice)
21
+ # ==============================================================
22
+ os.environ["HF_TOKEN"] = input("👉 Inserisci token HuggingFace: ")
23
+
24
+ from huggingface_hub import login
25
+ login(token=os.environ["HF_TOKEN"])
26
+
27
+ # ==============================================================
28
+ # PARAMETRI
29
+ # ==============================================================
30
+ CHUNKSIZE = 400
31
+ SAMPLE_PER_CHUNK = 30
32
+ MAX_TOTAL_ROWS = 4000
33
+ OUTPUT_JSONL = "./data/processed_recipes.jsonl"
34
+ TOKENIZED_JSONL = "./data/tokenized_recipes.jsonl"
35
+ DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
36
+
37
+ MODEL_NAME = "meta-llama/Llama-3.1-8B"
38
+ MAX_LENGTH = 256
39
+ MIN_ING_WORDS = 3
40
+ MIN_STEP_WORDS = 8
41
+
42
+ os.makedirs("./data", exist_ok=True)
43
+ os.makedirs("./kaggle_dl", exist_ok=True)
44
+
45
+ # ==============================================================
46
+ # UPLOAD FILE KAGGLE.JSON
47
+ # ==============================================================
48
+ print("🔁 Carica il file kaggle.json")
49
+ try:
50
+ uploaded = files.upload()
51
+ if "kaggle.json" in uploaded:
52
+ os.makedirs("/root/.kaggle", exist_ok=True)
53
+ !mv kaggle.json /root/.kaggle/
54
+ !chmod 600 /root/.kaggle/kaggle.json
55
+ import kaggle; kaggle.api.authenticate()
56
+ print("✅ kaggle.json configurato")
57
+ except:
58
+ print("⚠️ kaggle già configurato")
59
+
60
+
61
+ datasets_list = [
62
+ "shuyangli94/food-com-recipes-and-user-interactions",
63
+ "thedevastator/better-recipes-for-a-better-life",
64
+ "paultimothymooney/recipenlg",
65
+ "nazmussakibrupol/3a2m-cooking-recipe-dataset",
66
+ "irkaal/foodcom-recipes-and-reviews",
67
+ "pes12017000148/food-ingredients-and-recipe-dataset-with-images",
68
+ "sarthak71/food-recipes",
69
+ "shuyangli94/foodcom-recipes-with-search-terms-and-tags",
70
+ "hugodarwood/epirecipes"
71
+ ]
72
+
73
+ rows_per_dataset = MAX_TOTAL_ROWS // len(datasets_list)
74
+
75
+ # ==============================================================
76
+ # FUNZIONI PULIZIA TESTO
77
+ # ==============================================================
78
+ def clean_text(text):
79
+ if not isinstance(text, str): return ""
80
+ t = text.strip()
81
+ t = re.sub(r'\s+', ' ', t)
82
+ t = re.sub(r"[^0-9A-Za-zÀ-ÖØ-öø-ÿ ,.\-\(\):;/]", "", t)
83
+ return t
84
+
85
+ def normalize_ingredients(text):
86
+ if not isinstance(text, str): return ""
87
+ repl = {
88
+ r'\bgrams?\b': 'g', r'\bkilograms?\b': 'kg',
89
+ r'\bliters?\b': 'l', r'\bmilliliters?\b': 'ml',
90
+ r'\bteaspoons?\b': 'tsp', r'\btablespoons?\b': 'tbsp'
91
+ }
92
+ for p, r in repl.items():
93
+ text = re.sub(p, r, text, flags=re.IGNORECASE)
94
+ return text.strip()
95
+
96
+ # ==============================================================
97
+ # CANCELLA PRECEDENTE
98
+ # ==============================================================
99
+ for f in [OUTPUT_JSONL, TOKENIZED_JSONL]:
100
+ if os.path.exists(f):
101
+ os.remove(f)
102
+
103
+ # ==============================================================
104
+ # DOWNLOAD + SAMPLE + CLEAN
105
+ # ==============================================================
106
+ from datasets import load_dataset
107
+ total_written = 0
108
+
109
+ for ds in datasets_list:
110
+ written_in_ds = 0
111
+ print(f"\n⬇️ Dataset: {ds}")
112
+
113
+ path = f"./data/{ds.split('/')[-1]}"
114
+ os.makedirs(path, exist_ok=True)
115
+
116
+ try:
117
+ !kaggle datasets download -d {ds} -p {path} --unzip --quiet
118
+ except:
119
+ print("⚠️ Fallito kaggle, provo HuggingFace")
120
+ try:
121
+ hf = load_dataset(ds)
122
+ with open(path + "/hf.jsonl", "w") as f:
123
+ for split in hf.keys():
124
+ for ex in hf[split]:
125
+ f.write(json.dumps(dict(ex))+"\n")
126
+ except:
127
+ print("⛔ Skip dataset")
128
+
129
+ for file in os.listdir(path):
130
+ fp = os.path.join(path,file)
131
+ if not file.endswith((".csv",".json",".jsonl")): continue
132
+
133
+ try:
134
+ if file.endswith(".csv"):
135
+ for chunk in pd.read_csv(fp, chunksize=CHUNKSIZE, low_memory=True):
136
+ chunk.columns = [c.lower() for c in chunk.columns]
137
+ ingr = [c for c in chunk.columns if "ingr" in c]
138
+ steps = [c for c in chunk.columns if any(k in c for k in ["step","instruction","direction"])]
139
+ if not ingr or not steps: continue
140
+
141
+ df = chunk[[ingr[0], steps[0]]].rename(columns={ingr[0]:"ingredients",steps[0]:"n_steps"})
142
+ df["ingredients"] = df["ingredients"].astype(str).map(clean_text).map(normalize_ingredients)
143
+ df["n_steps"] = df["n_steps"].astype(str).map(clean_text)
144
+
145
+ df = df[df["ingredients"].str.split().str.len() >= MIN_ING_WORDS]
146
+ df = df[df["n_steps"].str.split().str.len() >= MIN_STEP_WORDS]
147
+
148
+ if len(df)>0:
149
+ n = min(SAMPLE_PER_CHUNK, len(df), rows_per_dataset-written_in_ds)
150
+ sampled = df.sample(n=n, random_state=42)
151
+
152
+ with open(OUTPUT_JSONL,"a") as f:
153
+ for _,r in sampled.iterrows():
154
+ json.dump({"ingredients":r["ingredients"],"n_steps":r["n_steps"]}, f)
155
+ f.write("\n")
156
+ written_in_ds += 1
157
+ total_written += 1
158
+
159
+ if written_in_ds >= rows_per_dataset:
160
+ break
161
+ except:
162
+ pass
163
+
164
+ print(f"\n✅ Creato JSONL con {total_written} ricette.")
165
+
166
+ # ==============================================================
167
+ # TOKENIZZAZIONE (✅ Fix definitivo IndexError)
168
+ # ==============================================================
169
+
170
+ print("\n✏️ Tokenizzazione...")
171
+
172
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, token=os.environ["HF_TOKEN"], use_fast=True)
173
+ tokenizer.pad_token = tokenizer.eos_token
174
+
175
+ def tokenizza_seq(infile, outfile, chunk_size=200):
176
+ with open(infile) as fin, open(outfile,"w") as fout:
177
+ buf=[]
178
+ for line in fin:
179
+ obj = json.loads(line)
180
+
181
+ system = "Sei 'Chef Tradizionale'. Rispondi con ricette tradizionali."
182
+ user = f"Gli ingredienti sono: {obj['ingredients']}\nScrivi i passaggi della ricetta:"
183
+ assistant = obj["n_steps"]
184
+
185
+ prompt = f"<s>[SYSTEM]{system}[/SYSTEM]\n[USER]{user}[/USER]\n[ASSISTANT]"
186
+ full = prompt + assistant + "</s>"
187
+
188
+ enc = tokenizer(full, max_length=MAX_LENGTH, truncation=True, padding="max_length")
189
+
190
+ input_ids = enc["input_ids"]
191
+ attention = enc["attention_mask"]
192
+ labels = input_ids.copy()
193
+
194
+ # ✅ fix: evitare IndexError quando il prompt > max_length
195
+ prompt_ids = tokenizer(prompt, add_special_tokens=False)["input_ids"]
196
+ prompt_len = min(len(prompt_ids), len(labels))
197
+ labels[:prompt_len] = [-100] * prompt_len
198
+
199
+ buf.append({"input_ids": input_ids, "attention_mask": attention, "labels": labels})
200
+
201
+ if len(buf) >= chunk_size:
202
+ for r in buf: fout.write(json.dumps(r)+"\n")
203
+ buf = []
204
+
205
+ for r in buf:
206
+ fout.write(json.dumps(r)+"\n")
207
+
208
+ tokenizza_seq(OUTPUT_JSONL, TOKENIZED_JSONL)
209
+ print("✅ Tokenizzazione completata")
210
+
211
+ # ==============================================================
212
+ # DATASET E DATALOADER
213
+ # ==============================================================
214
+ class RecipeDataset(torch.utils.data.Dataset):
215
+ def __init__(self, path):
216
+ self.data = [json.loads(l) for l in open(path)]
217
+ def __len__(self): return len(self.data)
218
+ def __getitem__(self, idx): return {k:torch.tensor(v) for k,v in self.data[idx].items()}
219
+
220
+ train_ds = RecipeDataset(TOKENIZED_JSONL)
221
+ train_dl = DataLoader(train_ds, batch_size=1, shuffle=True)
222
+
223
+ # ==============================================================
224
+ # FINE TUNING LoRA
225
+ # ==============================================================
226
+ bnb = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4", bnb_4bit_use_double_quant=True)
227
+ model = AutoModelForCausalLM.from_pretrained(MODEL_NAME, quantization_config=bnb, device_map="auto", token=os.environ["HF_TOKEN"])
228
+
229
+ config = LoraConfig(r=8, lora_alpha=16, target_modules=["q_proj","v_proj"], lora_dropout=0.05)
230
+ model = get_peft_model(model, config)
231
+ model.train()
232
+
233
+ optim = torch.optim.AdamW(model.parameters(), lr=2e-5)
234
+
235
+ print("\n🏁 Training...")
236
+ for epoch in range(2):
237
+ for batch in tqdm(train_dl):
238
+ optim.zero_grad()
239
+ out = model(**{k:v.to(DEVICE) for k,v in batch.items()})
240
+ out.loss.backward()
241
+ optim.step()
242
+
243
+ save_dir = "./llama31_recipes_LoRA"
244
+ model.save_pretrained(save_dir)
245
+ tokenizer.save_pretrained(save_dir)
246
+
247
+ print("💾 Modello salvato:", save_dir)
248
+
249
+ # ==============================================================
250
+ # GENERAZIONE DI TEST
251
+ # ==============================================================
252
+ def genera_ricetta(ingredienti):
253
+ prompt = f"[USER]Ingredienti: {ingredienti}.\nRicetta tradizionale italiana, step-by-step:[/USER]"
254
+ inputs = tokenizer(prompt, return_tensors="pt").to(DEVICE)
255
+ gen = model.generate(**inputs, max_new_tokens=200, temperature=0.7, top_p=0.9)
256
+ print(tokenizer.decode(gen[0], skip_special_tokens=True))
257
+
258
+ genera_ricetta("pasta, pomodoro, olio, basilico, sale")