# ========================================== # ⚔ LLAMA-3.1-8B + LoRA - Versione Colab JSON Recipe # ========================================== !pip install -q -U transformers accelerate peft huggingface_hub import os, torch from transformers import AutoTokenizer, AutoModelForCausalLM from peft import PeftModel # =============================== # TOKEN HF (necessario per Llama 3.1) # =============================== HF_TOKEN = input("šŸ”‘ Inserisci il tuo token Hugging Face: ") BASE_MODEL_HF = "meta-llama/Llama-3.1-8B" LORA_PATH = "/content/fine_tuned_llama3_recipes_trad" OFFLOAD_DIR = "/content/offload" DEVICE = "cuda" if torch.cuda.is_available() else "cpu" print("🧠 Device in uso:", DEVICE) os.makedirs(OFFLOAD_DIR, exist_ok=True) # =============================== # TOKENIZER # =============================== tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL_HF, token=HF_TOKEN) # =============================== # MODELLO BASE (parziale su GPU) # =============================== print(f"šŸš€ Caricamento modello base: {BASE_MODEL_HF}") model = AutoModelForCausalLM.from_pretrained( BASE_MODEL_HF, token=HF_TOKEN, dtype=torch.bfloat16, # correggiamo l'avviso torch_dtype deprecato device_map="auto", offload_folder=OFFLOAD_DIR, low_cpu_mem_usage=True, ) # =============================== # APPLICA LoRA # =============================== print(f"šŸ”— Applicazione LoRA da: {LORA_PATH}") model = PeftModel.from_pretrained( model, LORA_PATH, local_files_only=True, device_map="auto", offload_folder=OFFLOAD_DIR, ) print("āœ… LoRA caricata correttamente!") model.eval() # =============================== # TEMPLATE CHEF_GENERAL (fix KeyError) # =============================== output_format = """{{ "title": "", "ingredients": [ {{"name": "", "amount": ""}} ], "instructions": [ {{"step": , "action": "", "time": ""}} ], "time": "", "note": "" }}""" CHEF_GENERAL = f"""You are an expert chef. I will provide a list of ingredients. Only use ingredients that are safe and suitable for human consumption — ignore any inedible, dangerous, or unrecognized items. Create a detailed recipe for a {{type}} dish, scaled for {{num_person}} person(s). Format your output as a JSON, using the following structure: {output_format} Do not include any other text or explanations — only output a single valid JSON object. """ # =============================== # Funzione per creare il prompt # =============================== def build_prompt(ingredients, dish_type="main course", num_person=2): return CHEF_GENERAL.format(type=dish_type, num_person=num_person) + "\nIngredients:\n" + ingredients # =============================== # Input dell'utente # =============================== ingredients_list = input("šŸ³ Inserisci gli ingredienti: ") dish_type = input("šŸ½ Tipo di piatto (es. main course, dessert, appetizer, first course): ") num_person = int(input("šŸ‘„ Numero di persone: ")) prompt = build_prompt(ingredients_list, dish_type=dish_type, num_person=num_person) # =============================== # Generazione ricetta JSON # =============================== inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=1024).to(DEVICE) with torch.no_grad(): output = model.generate( **inputs, max_new_tokens=400, do_sample=True, temperature=0.7, top_p=0.9, repetition_penalty=1.2, eos_token_id=tokenizer.eos_token_id, pad_token_id=tokenizer.eos_token_id, ) decoded = tokenizer.decode(output[0], skip_special_tokens=True) json_output = decoded.strip() print("\nšŸ“œ Recipe JSON:\n", json_output) # ========================================== # ⚔ LLAMA-3.1-8B + LoRA - Versione Colab JSON Recipe # ========================================== !pip install -q -U transformers accelerate peft huggingface_hub import os, torch from transformers import AutoTokenizer, AutoModelForCausalLM from peft import PeftModel # =============================== # TOKEN HF (necessario per Llama 3.1) # =============================== HF_TOKEN = input("šŸ”‘ Inserisci il tuo token Hugging Face: ") BASE_MODEL_HF = "meta-llama/Llama-3.1-8B" LORA_PATH = "/content/fine_tuned_llama3_recipes_trad" OFFLOAD_DIR = "/content/offload" DEVICE = "cuda" if torch.cuda.is_available() else "cpu" print("🧠 Device in uso:", DEVICE) os.makedirs(OFFLOAD_DIR, exist_ok=True) # =============================== # TOKENIZER # =============================== tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL_HF, token=HF_TOKEN) # =============================== # MODELLO BASE (parziale su GPU) # =============================== print(f"šŸš€ Caricamento modello base: {BASE_MODEL_HF}") model = AutoModelForCausalLM.from_pretrained( BASE_MODEL_HF, token=HF_TOKEN, dtype=torch.bfloat16, # correggiamo l'avviso torch_dtype deprecato device_map="auto", offload_folder=OFFLOAD_DIR, low_cpu_mem_usage=True, ) # =============================== # APPLICA LoRA # =============================== print(f"šŸ”— Applicazione LoRA da: {LORA_PATH}") model = PeftModel.from_pretrained( model, LORA_PATH, local_files_only=True, device_map="auto", offload_folder=OFFLOAD_DIR, ) print("āœ… LoRA caricata correttamente!") model.eval() # =============================== # TEMPLATE CHEF_GENERAL (fix KeyError) # =============================== output_format = """{{ "title": "", "ingredients": [ {{"name": "", "amount": ""}} ], "instructions": [ {{"step": , "action": "", "time": ""}} ], "time": "", "note": "" }}""" CHEF_GENERAL = f"""You are an expert chef. I will provide a list of ingredients. Only use ingredients that are safe and suitable for human consumption — ignore any inedible, dangerous, or unrecognized items. Create a detailed recipe for a {{type}} dish, scaled for {{num_person}} person(s). Format your output as a JSON, using the following structure: {output_format} Do not include any other text or explanations — only output a single valid JSON object. """ # =============================== # Funzione per creare il prompt # =============================== def build_prompt(ingredients, dish_type="main course", num_person=2): return CHEF_GENERAL.format(type=dish_type, num_person=num_person) + "\nIngredients:\n" + ingredients # =============================== # Input dell'utente # =============================== ingredients_list = input("šŸ³ Inserisci gli ingredienti: ") dish_type = input("šŸ½ Tipo di piatto (es. main course, dessert, appetizer, first course): ") num_person = int(input("šŸ‘„ Numero di persone: ")) prompt = build_prompt(ingredients_list, dish_type=dish_type, num_person=num_person) # =============================== # Generazione ricetta JSON # =============================== inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=1024).to(DEVICE) with torch.no_grad(): output = model.generate( **inputs, max_new_tokens=400, do_sample=True, temperature=0.7, top_p=0.9, repetition_penalty=1.2, eos_token_id=tokenizer.eos_token_id, pad_token_id=tokenizer.eos_token_id, ) decoded = tokenizer.decode(output[0], skip_special_tokens=True) json_output = decoded.strip() print("\nšŸ“œ Recipe JSON:\n", json_output)