Download TestChefLLama3.1 from bowlOfData/chef: direct link, hf CLI and curl.
- Browser
- Download file 7.7 kB
-
https://huggingface.co/bowlOfData/chef/resolve/refs%2Fpr%2F3/TestChefLLama3.1
- Command line
-
hf download hf://bowlOfData/chef@refs/pr/3/TestChefLLama3.1
-
curl -L -o TestChefLLama3.1 https://huggingface.co/bowlOfData/chef/resolve/refs%2Fpr%2F3/TestChefLLama3.1
7.7 kB
| # ========================================== | |
| # β‘ 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": "<recipe name>", | |
| "ingredients": [ | |
| {{"name": "<ingredient name>", "amount": "<amount and unit>"}} | |
| ], | |
| "instructions": [ | |
| {{"step": <step number>, "action": "<instruction text>", "time": "<duration in minutes>"}} | |
| ], | |
| "time": "<total cooking time in minutes>", | |
| "note": "<optional notes if needed>" | |
| }}""" | |
| 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": "<recipe name>", | |
| "ingredients": [ | |
| {{"name": "<ingredient name>", "amount": "<amount and unit>"}} | |
| ], | |
| "instructions": [ | |
| {{"step": <step number>, "action": "<instruction text>", "time": "<duration in minutes>"}} | |
| ], | |
| "time": "<total cooking time in minutes>", | |
| "note": "<optional notes if needed>" | |
| }}""" | |
| 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) | |