idoyaaran commited on
Commit
76ede78
·
verified ·
1 Parent(s): a42ae8d

Upload 05_generation_finetune.ipynb

Browse files
Files changed (1) hide show
  1. 05_generation_finetune.ipynb +124 -0
05_generation_finetune.ipynb ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {},
6
+ "source": [
7
+ "# Mise — Part 5: Generation + LoRA fine-tune on real recipes (bonus +10%)\n",
8
+ "\n",
9
+ "The **generation** component + the fine-tuning bonus. We fine-tune `Qwen2.5-3B-Instruct` (QLoRA) on our **10,000 real recipes** so it becomes a **cuisine-specialized recipe generator**:\n",
10
+ "\n",
11
+ "> instruction: *\"Write a {difficulty} {cuisine} {dish_type} recipe.\"* → the recipe\n",
12
+ "\n",
13
+ "This is genuine domain fine-tuning on real data. The app uses this model to generate the '1 new recipe' for a cuisine/level.\n",
14
+ "\n",
15
+ "**Needs a GPU (Colab T4 / Kaggle).** Reads the dataset from HF; pushes the model to `idoyaaran/mise-lesson-model`."
16
+ ]
17
+ },
18
+ {
19
+ "cell_type": "markdown",
20
+ "metadata": {},
21
+ "source": [
22
+ "## 1. Load dataset from HF"
23
+ ]
24
+ },
25
+ {
26
+ "cell_type": "code",
27
+ "execution_count": null,
28
+ "metadata": {},
29
+ "outputs": [],
30
+ "source": "!pip -q install -U transformers accelerate peft bitsandbytes datasets huggingface_hub\nimport json, torch, pandas as pd\nfrom huggingface_hub import hf_hub_download\n\n# download the parquet directly (robust — avoids the fragile hf:// fsspec protocol)\npath = hf_hub_download(\"idoyaaran/mise-recipes\", \"recipes_clean.parquet\", repo_type=\"dataset\")\ndf = pd.read_parquet(path)\nBASE_MODEL = \"Qwen/Qwen2.5-3B-Instruct\"\nprint(len(df), \"recipes\")"
31
+ },
32
+ {
33
+ "cell_type": "markdown",
34
+ "metadata": {},
35
+ "source": [
36
+ "## 2. Format recipes into (instruction → recipe) training pairs\n",
37
+ "\n",
38
+ "The instruction is what the app will send; the output is the real recipe written as clean text."
39
+ ]
40
+ },
41
+ {
42
+ "cell_type": "code",
43
+ "execution_count": null,
44
+ "metadata": {},
45
+ "outputs": [],
46
+ "source": [
47
+ "def instruction(r):\n",
48
+ " return f\"Write a {r['difficulty']} {r['cuisine'].replace('_',' ')} {r['dish_type'].replace('_',' ')} recipe.\"\n",
49
+ "\n",
50
+ "def format_recipe(r):\n",
51
+ " ings = \"\\n\".join(f\"- {i['name']} ({i.get('quantity','')})\" for i in r['ingredients'])\n",
52
+ " steps = \"\\n\".join(f\"{n}. {s}\" for n, s in enumerate(r['steps'], 1))\n",
53
+ " return (f\"Title: {r['title']}\\n\"\n",
54
+ " f\"Cuisine: {r['cuisine']} | Difficulty: {r['difficulty']} | Time: {r['time_minutes']} min | Serves: {r['servings']}\\n\"\n",
55
+ " f\"Ingredients:\\n{ings}\\n\"\n",
56
+ " f\"Steps:\\n{steps}\")\n",
57
+ "\n",
58
+ "pairs = [{\"instruction\": instruction(r), \"output\": format_recipe(r)} for r in df.to_dict(\"records\")]\n",
59
+ "train = pd.DataFrame(pairs)\n",
60
+ "print(len(train), \"training pairs\\n\")\n",
61
+ "print(\"INSTRUCTION:\", train.iloc[0][\"instruction\"])\n",
62
+ "print(\"\\nOUTPUT:\\n\", train.iloc[0][\"output\"][:400])"
63
+ ]
64
+ },
65
+ {
66
+ "cell_type": "markdown",
67
+ "metadata": {},
68
+ "source": [
69
+ "## 3. Load base model (4-bit / QLoRA) + baseline generation"
70
+ ]
71
+ },
72
+ {
73
+ "cell_type": "code",
74
+ "execution_count": null,
75
+ "metadata": {},
76
+ "outputs": [],
77
+ "source": "from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig\nbnb = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_compute_dtype=torch.float16, bnb_4bit_quant_type=\"nf4\")\ntok = AutoTokenizer.from_pretrained(BASE_MODEL)\nmodel = AutoModelForCausalLM.from_pretrained(BASE_MODEL, quantization_config=bnb, device_map=\"auto\")\n\ndef generate(instr, max_new_tokens=400):\n msgs = [{\"role\": \"user\", \"content\": instr}]\n inp = tok.apply_chat_template(msgs, add_generation_prompt=True, return_tensors=\"pt\", return_dict=True).to(model.device)\n out = model.generate(**inp, max_new_tokens=max_new_tokens, do_sample=True, temperature=0.7,\n top_p=0.9, repetition_penalty=1.15, use_cache=True,\n pad_token_id=tok.eos_token_id)\n return tok.decode(out[0][inp[\"input_ids\"].shape[1]:], skip_special_tokens=True)\n\nprint(\"BEFORE fine-tuning:\\n\")\nprint(generate(\"Write a beginner mexican street food recipe.\"))"
78
+ },
79
+ {
80
+ "cell_type": "markdown",
81
+ "metadata": {},
82
+ "source": "## 4. LoRA fine-tune (transformers Trainer + peft — no trl)"
83
+ },
84
+ {
85
+ "cell_type": "code",
86
+ "execution_count": null,
87
+ "metadata": {},
88
+ "outputs": [],
89
+ "source": "from datasets import Dataset\nfrom peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training\nfrom transformers import TrainingArguments, Trainer, DataCollatorForSeq2Seq\n\nif tok.pad_token is None:\n tok.pad_token = tok.eos_token\n\n# subsample for faster + more controllable training (plenty to specialize the format)\ntrain_sub = train.sample(n=min(3000, len(train)), random_state=42).reset_index(drop=True)\n\nmodel = prepare_model_for_kbit_training(model)\npeft_cfg = LoraConfig(r=16, lora_alpha=32, lora_dropout=0.05, task_type=\"CAUSAL_LM\",\n target_modules=[\"q_proj\",\"k_proj\",\"v_proj\",\"o_proj\"])\nmodel = get_peft_model(model, peft_cfg)\nmodel.enable_input_require_grads()\nmodel.print_trainable_parameters()\n\nMAXLEN = 640\ndef tokenize(ex):\n prompt_text = tok.apply_chat_template(\n [{\"role\": \"user\", \"content\": ex[\"instruction\"]}],\n add_generation_prompt=True, tokenize=False)\n full_text = tok.apply_chat_template(\n [{\"role\": \"user\", \"content\": ex[\"instruction\"]},\n {\"role\": \"assistant\", \"content\": ex[\"output\"]}], tokenize=False)\n prompt_ids = tok(prompt_text, add_special_tokens=False)[\"input_ids\"]\n full_ids = tok(full_text, add_special_tokens=False, truncation=True, max_length=MAXLEN)[\"input_ids\"]\n labels = full_ids.copy()\n for i in range(min(len(prompt_ids), len(labels))):\n labels[i] = -100\n return {\"input_ids\": full_ids, \"attention_mask\": [1] * len(full_ids), \"labels\": labels}\n\nds = Dataset.from_pandas(train_sub).map(tokenize, remove_columns=list(train_sub.columns))\n\nargs = TrainingArguments(\n output_dir=\"mise-lesson-model\",\n per_device_train_batch_size=4,\n gradient_accumulation_steps=4,\n num_train_epochs=1,\n learning_rate=1e-4,\n warmup_ratio=0.05,\n lr_scheduler_type=\"cosine\",\n max_grad_norm=0.3, # aggressive clipping -> prevents divergence\n optim=\"paged_adamw_8bit\", # stable QLoRA optimizer\n logging_steps=20,\n fp16=True,\n gradient_checkpointing=True,\n gradient_checkpointing_kwargs={\"use_reentrant\": False},\n report_to=\"none\",\n save_strategy=\"no\",\n)\nmodel.config.use_cache = False\ntrainer = Trainer(model=model, args=args, train_dataset=ds,\n data_collator=DataCollatorForSeq2Seq(tok, padding=True))\ntrainer.train()\nmodel.save_pretrained(\"mise-lesson-model\")\ntok.save_pretrained(\"mise-lesson-model\")\nprint(\"Saved LoRA adapter.\")"
90
+ },
91
+ {
92
+ "cell_type": "markdown",
93
+ "metadata": {},
94
+ "source": [
95
+ "## 5. Test the fine-tuned model, then push to HF"
96
+ ]
97
+ },
98
+ {
99
+ "cell_type": "code",
100
+ "execution_count": null,
101
+ "metadata": {},
102
+ "outputs": [],
103
+ "source": "model.eval()\nmodel.config.use_cache = True\nprint(\"AFTER fine-tuning:\\n\")\nprint(generate(\"Write an advanced italian main recipe.\"))"
104
+ },
105
+ {
106
+ "cell_type": "code",
107
+ "execution_count": null,
108
+ "metadata": {},
109
+ "outputs": [],
110
+ "source": "from huggingface_hub import login\ntry:\n from kaggle_secrets import UserSecretsClient # Kaggle\n login(UserSecretsClient().get_secret(\"HF_TOKEN\"))\nexcept Exception:\n try:\n from google.colab import userdata # Colab\n login(userdata.get(\"HF_TOKEN\"))\n except Exception:\n login() # interactive prompt\n\nMODEL_REPO = \"idoyaaran/mise-lesson-model\"\ntrainer.model.push_to_hub(MODEL_REPO)\ntok.push_to_hub(MODEL_REPO)\nprint(\"Pushed ->\", f\"https://huggingface.co/{MODEL_REPO}\")"
111
+ }
112
+ ],
113
+ "metadata": {
114
+ "kernelspec": {
115
+ "display_name": "Python 3",
116
+ "name": "python3"
117
+ },
118
+ "language_info": {
119
+ "name": "python"
120
+ }
121
+ },
122
+ "nbformat": 4,
123
+ "nbformat_minor": 0
124
+ }