Download ModelLLama3.1 from bowlOfData/chef: direct link, hf CLI and curl.
- Browser
- Download file 9.97 kB
-
https://huggingface.co/bowlOfData/chef/resolve/main/ModelLLama3.1
- Command line
-
hf download hf://bowlOfData/chef/ModelLLama3.1
-
curl -L -o ModelLLama3.1 https://huggingface.co/bowlOfData/chef/resolve/main/ModelLLama3.1
9.97 kB
| # ============================================================== | |
| # FULL FINETUNE PIPELINE (LLAMA 3.1 - LoRA - Ricette Tradizionali) | |
| # ============================================================== | |
| !pip install --quiet transformers accelerate sentencepiece datasets evaluate tqdm peft rouge_score kaggle bitsandbytes huggingface_hub | |
| import os, gc, re, json, sys, time | |
| import pandas as pd | |
| from google.colab import files | |
| import torch | |
| from torch.utils.data import DataLoader | |
| from tqdm import tqdm | |
| from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig | |
| from peft import LoraConfig, get_peft_model | |
| import evaluate | |
| gc.collect() | |
| # ============================================================== | |
| # HUGGINGFACE LOGIN (👉 NON inserire il token nel codice) | |
| # ============================================================== | |
| os.environ["HF_TOKEN"] = input("👉 Inserisci token HuggingFace: ") | |
| from huggingface_hub import login | |
| login(token=os.environ["HF_TOKEN"]) | |
| # ============================================================== | |
| # PARAMETRI | |
| # ============================================================== | |
| CHUNKSIZE = 400 | |
| SAMPLE_PER_CHUNK = 30 | |
| MAX_TOTAL_ROWS = 4000 | |
| OUTPUT_JSONL = "./data/processed_recipes.jsonl" | |
| TOKENIZED_JSONL = "./data/tokenized_recipes.jsonl" | |
| DEVICE = "cuda" if torch.cuda.is_available() else "cpu" | |
| MODEL_NAME = "meta-llama/Llama-3.1-8B" | |
| MAX_LENGTH = 256 | |
| MIN_ING_WORDS = 3 | |
| MIN_STEP_WORDS = 8 | |
| os.makedirs("./data", exist_ok=True) | |
| os.makedirs("./kaggle_dl", exist_ok=True) | |
| # ============================================================== | |
| # UPLOAD FILE KAGGLE.JSON | |
| # ============================================================== | |
| print("🔁 Carica il file kaggle.json") | |
| try: | |
| uploaded = files.upload() | |
| if "kaggle.json" in uploaded: | |
| os.makedirs("/root/.kaggle", exist_ok=True) | |
| !mv kaggle.json /root/.kaggle/ | |
| !chmod 600 /root/.kaggle/kaggle.json | |
| import kaggle; kaggle.api.authenticate() | |
| print("✅ kaggle.json configurato") | |
| except: | |
| print("⚠️ kaggle già configurato") | |
| datasets_list = [ | |
| "shuyangli94/food-com-recipes-and-user-interactions", | |
| "thedevastator/better-recipes-for-a-better-life", | |
| "paultimothymooney/recipenlg", | |
| "nazmussakibrupol/3a2m-cooking-recipe-dataset", | |
| "irkaal/foodcom-recipes-and-reviews", | |
| "pes12017000148/food-ingredients-and-recipe-dataset-with-images", | |
| "sarthak71/food-recipes", | |
| "shuyangli94/foodcom-recipes-with-search-terms-and-tags", | |
| "hugodarwood/epirecipes" | |
| ] | |
| rows_per_dataset = MAX_TOTAL_ROWS // len(datasets_list) | |
| # ============================================================== | |
| # FUNZIONI PULIZIA TESTO | |
| # ============================================================== | |
| def clean_text(text): | |
| if not isinstance(text, str): return "" | |
| t = text.strip() | |
| t = re.sub(r'\s+', ' ', t) | |
| t = re.sub(r"[^0-9A-Za-zÀ-ÖØ-öø-ÿ ,.\-\(\):;/]", "", t) | |
| return t | |
| def normalize_ingredients(text): | |
| if not isinstance(text, str): return "" | |
| repl = { | |
| r'\bgrams?\b': 'g', r'\bkilograms?\b': 'kg', | |
| r'\bliters?\b': 'l', r'\bmilliliters?\b': 'ml', | |
| r'\bteaspoons?\b': 'tsp', r'\btablespoons?\b': 'tbsp' | |
| } | |
| for p, r in repl.items(): | |
| text = re.sub(p, r, text, flags=re.IGNORECASE) | |
| return text.strip() | |
| # ============================================================== | |
| # CANCELLA PRECEDENTE | |
| # ============================================================== | |
| for f in [OUTPUT_JSONL, TOKENIZED_JSONL]: | |
| if os.path.exists(f): | |
| os.remove(f) | |
| # ============================================================== | |
| # DOWNLOAD + SAMPLE + CLEAN | |
| # ============================================================== | |
| from datasets import load_dataset | |
| total_written = 0 | |
| for ds in datasets_list: | |
| written_in_ds = 0 | |
| print(f"\n⬇️ Dataset: {ds}") | |
| path = f"./data/{ds.split('/')[-1]}" | |
| os.makedirs(path, exist_ok=True) | |
| try: | |
| !kaggle datasets download -d {ds} -p {path} --unzip --quiet | |
| except: | |
| print("⚠️ Fallito kaggle, provo HuggingFace") | |
| try: | |
| hf = load_dataset(ds) | |
| with open(path + "/hf.jsonl", "w") as f: | |
| for split in hf.keys(): | |
| for ex in hf[split]: | |
| f.write(json.dumps(dict(ex))+"\n") | |
| except: | |
| print("⛔ Skip dataset") | |
| for file in os.listdir(path): | |
| fp = os.path.join(path,file) | |
| if not file.endswith((".csv",".json",".jsonl")): continue | |
| try: | |
| if file.endswith(".csv"): | |
| for chunk in pd.read_csv(fp, chunksize=CHUNKSIZE, low_memory=True): | |
| chunk.columns = [c.lower() for c in chunk.columns] | |
| ingr = [c for c in chunk.columns if "ingr" in c] | |
| steps = [c for c in chunk.columns if any(k in c for k in ["step","instruction","direction"])] | |
| if not ingr or not steps: continue | |
| df = chunk[[ingr[0], steps[0]]].rename(columns={ingr[0]:"ingredients",steps[0]:"n_steps"}) | |
| df["ingredients"] = df["ingredients"].astype(str).map(clean_text).map(normalize_ingredients) | |
| df["n_steps"] = df["n_steps"].astype(str).map(clean_text) | |
| df = df[df["ingredients"].str.split().str.len() >= MIN_ING_WORDS] | |
| df = df[df["n_steps"].str.split().str.len() >= MIN_STEP_WORDS] | |
| if len(df)>0: | |
| n = min(SAMPLE_PER_CHUNK, len(df), rows_per_dataset-written_in_ds) | |
| sampled = df.sample(n=n, random_state=42) | |
| with open(OUTPUT_JSONL,"a") as f: | |
| for _,r in sampled.iterrows(): | |
| json.dump({"ingredients":r["ingredients"],"n_steps":r["n_steps"]}, f) | |
| f.write("\n") | |
| written_in_ds += 1 | |
| total_written += 1 | |
| if written_in_ds >= rows_per_dataset: | |
| break | |
| except: | |
| pass | |
| print(f"\n✅ Creato JSONL con {total_written} ricette.") | |
| # ============================================================== | |
| # TOKENIZZAZIONE (✅ Fix definitivo IndexError) | |
| # ============================================================== | |
| print("\n✏️ Tokenizzazione...") | |
| tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, token=os.environ["HF_TOKEN"], use_fast=True) | |
| tokenizer.pad_token = tokenizer.eos_token | |
| def tokenizza_seq(infile, outfile, chunk_size=200): | |
| with open(infile) as fin, open(outfile,"w") as fout: | |
| buf=[] | |
| for line in fin: | |
| obj = json.loads(line) | |
| system = "Sei 'Chef Tradizionale'. Rispondi con ricette tradizionali." | |
| user = f"Gli ingredienti sono: {obj['ingredients']}\nScrivi i passaggi della ricetta:" | |
| assistant = obj["n_steps"] | |
| prompt = f"<s>[SYSTEM]{system}[/SYSTEM]\n[USER]{user}[/USER]\n[ASSISTANT]" | |
| full = prompt + assistant + "</s>" | |
| enc = tokenizer(full, max_length=MAX_LENGTH, truncation=True, padding="max_length") | |
| input_ids = enc["input_ids"] | |
| attention = enc["attention_mask"] | |
| labels = input_ids.copy() | |
| # ✅ fix: evitare IndexError quando il prompt > max_length | |
| prompt_ids = tokenizer(prompt, add_special_tokens=False)["input_ids"] | |
| prompt_len = min(len(prompt_ids), len(labels)) | |
| labels[:prompt_len] = [-100] * prompt_len | |
| buf.append({"input_ids": input_ids, "attention_mask": attention, "labels": labels}) | |
| if len(buf) >= chunk_size: | |
| for r in buf: fout.write(json.dumps(r)+"\n") | |
| buf = [] | |
| for r in buf: | |
| fout.write(json.dumps(r)+"\n") | |
| tokenizza_seq(OUTPUT_JSONL, TOKENIZED_JSONL) | |
| print("✅ Tokenizzazione completata") | |
| # ============================================================== | |
| # DATASET E DATALOADER | |
| # ============================================================== | |
| class RecipeDataset(torch.utils.data.Dataset): | |
| def __init__(self, path): | |
| self.data = [json.loads(l) for l in open(path)] | |
| def __len__(self): return len(self.data) | |
| def __getitem__(self, idx): return {k:torch.tensor(v) for k,v in self.data[idx].items()} | |
| train_ds = RecipeDataset(TOKENIZED_JSONL) | |
| train_dl = DataLoader(train_ds, batch_size=1, shuffle=True) | |
| # ============================================================== | |
| # FINE TUNING LoRA | |
| # ============================================================== | |
| bnb = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4", bnb_4bit_use_double_quant=True) | |
| model = AutoModelForCausalLM.from_pretrained(MODEL_NAME, quantization_config=bnb, device_map="auto", token=os.environ["HF_TOKEN"]) | |
| config = LoraConfig(r=8, lora_alpha=16, target_modules=["q_proj","v_proj"], lora_dropout=0.05) | |
| model = get_peft_model(model, config) | |
| model.train() | |
| optim = torch.optim.AdamW(model.parameters(), lr=2e-5) | |
| print("\n🏁 Training...") | |
| for epoch in range(2): | |
| for batch in tqdm(train_dl): | |
| optim.zero_grad() | |
| out = model(**{k:v.to(DEVICE) for k,v in batch.items()}) | |
| out.loss.backward() | |
| optim.step() | |
| save_dir = "./llama31_recipes_LoRA" | |
| model.save_pretrained(save_dir) | |
| tokenizer.save_pretrained(save_dir) | |
| print("💾 Modello salvato:", save_dir) | |
| # ============================================================== | |
| # GENERAZIONE DI TEST | |
| # ============================================================== | |
| def genera_ricetta(ingredienti): | |
| prompt = f"[USER]Ingredienti: {ingredienti}.\nRicetta tradizionale italiana, step-by-step:[/USER]" | |
| inputs = tokenizer(prompt, return_tensors="pt").to(DEVICE) | |
| gen = model.generate(**inputs, max_new_tokens=200, temperature=0.7, top_p=0.9) | |
| print(tokenizer.decode(gen[0], skip_special_tokens=True)) | |
| genera_ricetta("pasta, pomodoro, olio, basilico, sale") | |