{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "568457bb-c0f0-464f-9f37-e390e64f6a72", "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\"Hugging

To log in, open this URL and enter the code:

https://hf.co/oauth/device

HRBR-LXRG

" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
Waiting for authorization...
" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
Login successful. Logged in as ivan100096 (token: oauth-ivan100096).
This token will be refreshed automatically when it expires.
" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "from huggingface_hub import login\n", "login()" ] }, { "cell_type": "code", "execution_count": 2, "id": "9237bf9c-7918-4b4c-972e-ebe7e1bc16b2", "metadata": {}, "outputs": [], "source": [ "base_model = \"google/functiongemma-270m-it\"\n", "learning_rate = 5e-5" ] }, { "cell_type": "code", "execution_count": 3, "id": "a19326de-199a-438d-bc10-2375f13607fb", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "/anaconda/envs/gemma4/lib/python3.12/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n", " from .autonotebook import tqdm as notebook_tqdm\n" ] } ], "source": [ "import json\n", "from datasets import Dataset\n", "from transformers.utils import get_json_schema\n", "\n", "# --- Tool Definitions ---\n", "def search_knowledge_base(query: str) -> str:\n", " \"\"\"\n", " Search internal company documents, policies and project data.\n", "\n", " Args:\n", " query: query string\n", " \"\"\"\n", " return \"Internal Result\"\n", "\n", "def search_google(query: str) -> str:\n", " \"\"\"\n", " Search public information.\n", "\n", " Args:\n", " query: query string\n", " \"\"\"\n", " return \"Public Result\"\n", "\n", "\n", "TOOLS = [get_json_schema(search_knowledge_base), get_json_schema(search_google)]" ] }, { "cell_type": "code", "execution_count": 4, "id": "7f6f729d-0d87-466d-baea-282e9b064b7a", "metadata": {}, "outputs": [], "source": [ "DEFAULT_SYSTEM_MSG = \"You are a model that can do function calling with the following functions\"\n", "\n", "def create_conversation(sample):\n", " return {\n", " \"messages\": [\n", " {\"role\": \"developer\", \"content\": DEFAULT_SYSTEM_MSG},\n", " {\"role\": \"user\", \"content\": sample[\"user_content\"]},\n", " {\"role\": \"assistant\", \"tool_calls\": [{\"type\": \"function\", \"function\": {\"name\": sample[\"tool_name\"], \"arguments\": json.loads(sample[\"tool_arguments\"])} }]},\n", " ],\n", " \"tools\": TOOLS\n", " }" ] }, { "cell_type": "code", "execution_count": 7, "id": "dbc9f32e-e567-4b54-8244-e8936a8102a0", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "Generating train split: 100%|██████████| 40/40 [00:00<00:00, 11671.11 examples/s]\n" ] } ], "source": [ "from datasets import load_dataset\n", "dataset = load_dataset(\"bebechien/SimpleToolCalling\", split=\"train\")" ] }, { "cell_type": "code", "execution_count": 8, "id": "72aa58a0-a637-4a9e-a357-0a05ccb06af4", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "Map: 100%|██████████| 40/40 [00:00<00:00, 7084.67 examples/s]\n" ] } ], "source": [ "dataset = dataset.map(create_conversation, remove_columns=dataset.features, batched=False)" ] }, { "cell_type": "code", "execution_count": 9, "id": "a621f5ce-eda8-4964-8889-c6b06933704e", "metadata": {}, "outputs": [], "source": [ "dataset = dataset.train_test_split(test_size=0.5, shuffle=True)" ] }, { "cell_type": "code", "execution_count": 12, "id": "02e0b938-fbe9-48e1-b4c5-deb631f3c457", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'messages': [{'role': 'developer',\n", " 'content': 'You are a model that can do function calling with the following functions'},\n", " {'role': 'user', 'content': 'How do I request a new monitor setup?'},\n", " {'role': 'assistant',\n", " 'tool_calls': [{'type': 'function',\n", " 'function': {'name': 'search_knowledge_base',\n", " 'arguments': {'query': 'IT hardware request monitor setup'}}}]}],\n", " 'tools': [{'type': 'function',\n", " 'function': {'name': 'search_knowledge_base',\n", " 'description': 'Search internal company documents, policies and project data.',\n", " 'parameters': {'type': 'object',\n", " 'properties': {'query': {'type': 'string',\n", " 'description': 'query string'}},\n", " 'required': ['query']},\n", " 'return': {'type': 'string'}}},\n", " {'type': 'function',\n", " 'function': {'name': 'search_google',\n", " 'description': 'Search public information.',\n", " 'parameters': {'type': 'object',\n", " 'properties': {'query': {'type': 'string',\n", " 'description': 'query string'}},\n", " 'required': ['query']},\n", " 'return': {'type': 'string'}}}]}" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "dataset['train'][0]" ] }, { "cell_type": "code", "execution_count": 13, "id": "b554d4c2-03eb-4c4d-baae-0cf272b578d2", "metadata": {}, "outputs": [], "source": [ "from transformers import AutoTokenizer\n", "\n", "# Load the tokenizer\n", "tokenizer = AutoTokenizer.from_pretrained(base_model)" ] }, { "cell_type": "code", "execution_count": 14, "id": "6c8b3fbb-bc8b-4d43-8af6-26f5762240f1", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "--- dataset input ---\n", "{\n", " \"messages\": [\n", " {\n", " \"role\": \"developer\",\n", " \"content\": \"You are a model that can do function calling with the following functions\"\n", " },\n", " {\n", " \"role\": \"user\",\n", " \"content\": \"How do I request a new monitor setup?\"\n", " },\n", " {\n", " \"role\": \"assistant\",\n", " \"tool_calls\": [\n", " {\n", " \"type\": \"function\",\n", " \"function\": {\n", " \"name\": \"search_knowledge_base\",\n", " \"arguments\": {\n", " \"query\": \"IT hardware request monitor setup\"\n", " }\n", " }\n", " }\n", " ]\n", " }\n", " ],\n", " \"tools\": [\n", " {\n", " \"type\": \"function\",\n", " \"function\": {\n", " \"name\": \"search_knowledge_base\",\n", " \"description\": \"Search internal company documents, policies and project data.\",\n", " \"parameters\": {\n", " \"type\": \"object\",\n", " \"properties\": {\n", " \"query\": {\n", " \"type\": \"string\",\n", " \"description\": \"query string\"\n", " }\n", " },\n", " \"required\": [\n", " \"query\"\n", " ]\n", " },\n", " \"return\": {\n", " \"type\": \"string\"\n", " }\n", " }\n", " },\n", " {\n", " \"type\": \"function\",\n", " \"function\": {\n", " \"name\": \"search_google\",\n", " \"description\": \"Search public information.\",\n", " \"parameters\": {\n", " \"type\": \"object\",\n", " \"properties\": {\n", " \"query\": {\n", " \"type\": \"string\",\n", " \"description\": \"query string\"\n", " }\n", " },\n", " \"required\": [\n", " \"query\"\n", " ]\n", " },\n", " \"return\": {\n", " \"type\": \"string\"\n", " }\n", " }\n", " }\n", " ]\n", "}\n", "--- Formatted prompt ---\n", "developer\n", "You are a model that can do function calling with the following functionsdeclaration:search_knowledge_base{description:Search internal company documents, policies and project data.,parameters:{properties:{query:{description:query string,type:STRING}},required:[query],type:OBJECT}}declaration:search_google{description:Search public information.,parameters:{properties:{query:{description:query string,type:STRING}},required:[query],type:OBJECT}}\n", "user\n", "How do I request a new monitor setup?\n", "model\n", "call:search_knowledge_base{query:IT hardware request monitor setup}\n" ] } ], "source": [ "# Print formatted user prompt\n", "print(\"--- dataset input ---\")\n", "print(json.dumps(dataset[\"train\"][0], indent=2))\n", "debug_msg = tokenizer.apply_chat_template(\n", " dataset[\"train\"][0][\"messages\"], \n", " tools=dataset[\"train\"][0][\"tools\"], \n", " add_generation_prompt=False, \n", " tokenize=False\n", ")\n", "print(\"--- Formatted prompt ---\")\n", "print(debug_msg)" ] }, { "cell_type": "code", "execution_count": 15, "id": "0781c27b-354e-4531-a62f-675cfd15a63d", "metadata": {}, "outputs": [], "source": [ "def check_success_rate(model):\n", " success_count = 0\n", " for idx, item in enumerate(dataset['test']):\n", " messages = [\n", " item[\"messages\"][0],\n", " item[\"messages\"][1],\n", " ]\n", "\n", " inputs = tokenizer.apply_chat_template(messages, tools=TOOLS, add_generation_prompt=True, return_dict=True, return_tensors=\"pt\")\n", "\n", " out = model.generate(**inputs.to(model.device), pad_token_id=tokenizer.eos_token_id, max_new_tokens=128)\n", " output = tokenizer.decode(out[0][len(inputs[\"input_ids\"][0]) :], skip_special_tokens=False)\n", "\n", " print(f\"{idx+1} Prompt: {item['messages'][1]['content']}\")\n", " print(f\" Output: {output}\")\n", "\n", " expected_tool = item['messages'][2]['tool_calls'][0]['function']['name']\n", " other_tool = \"search_knowledge_base\" if expected_tool == \"search_google\" else \"search_google\"\n", "\n", " if expected_tool in output and other_tool not in output:\n", " print(\" `-> ✅ correct!\")\n", " success_count += 1\n", " elif expected_tool not in output:\n", " print(f\" -> ❌ wrong (expected '{expected_tool}' missing)\")\n", " else:\n", " if output.startswith(f\"call:{expected_tool}\"):\n", " print(f\" -> ⚠️ tool is correct {expected_tool}, but other_tool exists in output\")\n", " else:\n", " print(f\" -> ❌ wrong (hallucinated '{other_tool}')\")\n", "\n", " print(f\"Success : {success_count} / {len(dataset['test'])}\")" ] }, { "cell_type": "code", "execution_count": 17, "id": "e67bb812-f549-4139-b336-f6d9999e346f", "metadata": {}, "outputs": [], "source": [ "checkpoint_dir = \"/mnt/batch/tasks/shared/LS_root/mounts/clusters/hydra/code/Users/1043695/gemma-sft\"" ] }, { "cell_type": "code", "execution_count": 18, "id": "1957c3f0-1fe7-47f5-93ea-67aea0999daf", "metadata": {}, "outputs": [], "source": [ "from trl import SFTConfig\n", "\n", "args = SFTConfig(\n", " output_dir=checkpoint_dir, # directory to save and repository id\n", " max_length=512, # max sequence length for model and packing of the dataset\n", " packing=False, # Groups multiple samples in the dataset into a single sequence\n", " num_train_epochs=8, # number of training epochs\n", " per_device_train_batch_size=4, # batch size per device during training\n", " gradient_checkpointing=False, # the model is small, so skip gradient checkpointing for speed\n", " optim=\"adamw_torch_fused\", # use fused adamw optimizer\n", " logging_steps=1, # log every step\n", " #save_strategy=\"epoch\", # save checkpoint every epoch\n", " eval_strategy=\"epoch\", # evaluate checkpoint every epoch\n", " learning_rate=learning_rate, # learning rate\n", " lr_scheduler_type=\"constant\", # use constant learning rate scheduler\n", " push_to_hub=True, # push model to hub\n", " report_to=\"tensorboard\", # report metrics to tensorboard\n", ")" ] }, { "cell_type": "code", "execution_count": 21, "id": "6b82c8a2-7943-493a-855b-53cb5bb23de0", "metadata": {}, "outputs": [], "source": [ "# pip install torch tensorboard" ] }, { "cell_type": "code", "execution_count": 22, "id": "55498e33-2533-46d5-bdd8-fee23dc1cb82", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "Loading weights: 100%|██████████| 236/236 [00:00<00:00, 1803.49it/s]\n" ] } ], "source": [ "from trl import SFTTrainer\n", "\n", "# Create Trainer object\n", "trainer = SFTTrainer(\n", " model=base_model,\n", " args=args,\n", " train_dataset=dataset['train'],\n", " eval_dataset=dataset['test'],\n", ")" ] }, { "cell_type": "code", "execution_count": 23, "id": "78bfc901-9ea6-477f-964c-0fd23282e5ff", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1 Prompt: What is our Slack message retention policy?\n", " Output: I cannot assist with retrieving or discussing company policies regarding Slack message retention. My current capabilities are limited to assisting with searching internal company documents and project data.\n", " -> ❌ wrong (expected 'search_knowledge_base' missing)\n", "2 Prompt: Does the office insurance cover dental implants?\n", " Output: call:search_knowledge_base{query:dental implants insurance coverage}\n", " `-> ✅ correct!\n", "3 Prompt: Who won the World Series last year?\n", " Output: I cannot provide specific sports statistics or results for a particular winner. My available tools are focused on searching company knowledge and project data. I cannot access or analyze historical World Series results.\n", " -> ❌ wrong (expected 'search_google' missing)\n", "4 Prompt: Show me examples of using the useEffect hook in React.\n", " Output: I am sorry, but I cannot assist with providing specific examples of using the `useEffect` hook in React. My current capabilities are focused on assisting with searching company documents and project data using the specified tools. I cannot provide technical guidance or examples on React hook usage.\n", " -> ❌ wrong (expected 'search_google' missing)\n", "5 Prompt: Check the latest stock price for Apple.\n", " Output: call:search_google{query:Apple stock price}\n", " `-> ✅ correct!\n", "6 Prompt: Comparison of AWS vs GCP pricing.\n", " Output: I am sorry, but I cannot assist with this request. My current capabilities are limited to assisting with searching company documentation and project data using the specified tools. I cannot provide comparisons of cloud pricing models.\n", " -> ❌ wrong (expected 'search_google' missing)\n", "7 Prompt: Compare the features of iPhone 15 vs Samsung S24.\n", " Output: I cannot assist with comparing phone specifications like features for specific devices. My current capabilities are focused on assisting with searching knowledge and company documents using the provided tools. I cannot perform technical device comparisons or analysis.\n", " -> ❌ wrong (expected 'search_google' missing)\n", "8 Prompt: What is the latest version of Node.js?\n", " Output: call:search_google{query:Node.js version latest}\n", " `-> ✅ correct!\n", "9 Prompt: Who is the emergency contact for the London data center?\n", " Output: call:search_knowledge_base{query:London emergency contact emergency contact London}call:search_google{query:London emergency contact London}\n", " -> ⚠️ tool is correct search_knowledge_base, but other_tool exists in output\n", "10 Prompt: Who are the direct reports for the VP of Engineering?\n", " Output: call:search_knowledge_base{query:VP of Engineering}\n", " `-> ✅ correct!\n", "11 Prompt: Explain the difference between REST and GraphQL.\n", " Output: I am sorry, but I cannot assist with explaining technical concepts such as different types of data models. My current capabilities are focused on assisting with searching and retrieving internal company documents and project data using the specified tools. I cannot provide explanations or comparisons of different data models.\n", " -> ❌ wrong (expected 'search_google' missing)\n", "12 Prompt: What is the procedure for reporting a phishing email?\n", " Output: I am sorry, but I cannot assist with providing specific steps or procedures for reporting phishing emails. My current capabilities are limited to assisting with searching company documents and project data using the provided tools. I cannot access or provide expert knowledge about cybersecurity or phishing procedures.\n", " -> ❌ wrong (expected 'search_knowledge_base' missing)\n", "13 Prompt: What are the core values listed in our employee handbook?\n", " Output: call:search_knowledge_base{query:employee handbook}\n", " `-> ✅ correct!\n", "14 Prompt: What is the difference between VLOOKUP and XLOOKUP in Google Sheets?\n", " Output: I cannot assist with answering this specific question. My current capabilities are focused on assisting with searching and managing company knowledge bases using the specified tools. I cannot provide information or comparisons about Google Sheets and VLOOKUP and XLOOKUP.\n", " -> ❌ wrong (expected 'search_google' missing)\n", "15 Prompt: Best practices for writing a Dockerfile for Node.js.\n", " Output: I am sorry, but I cannot assist with recommending or recommending best practices for writing Dockerfiles. My current capabilities are focused on searching company documents and project data using specific tools. I cannot provide expert knowledge or advice on software development best practices.\n", " -> ❌ wrong (expected 'search_google' missing)\n", "16 Prompt: Do we have preferred hotel partners in Paris?\n", " Output: I cannot assist with finding hotel partners. My current capabilities are limited to assisting with searching company documents and project data using the specified tools. I cannot connect with or query business databases.\n", " -> ❌ wrong (expected 'search_knowledge_base' missing)\n", "17 Prompt: What are the latest release notes for the OpenAI API?\n", " Output: call:search_knowledge_base{query:OpenAI API release notes latest}\n", " -> ❌ wrong (expected 'search_google' missing)\n", "18 Prompt: Find the onboarding checklist for new engineering hires.\n", " Output: call:search_knowledge_base{query:onboarding checklist}call:search_google{query:onboarding checklist}\n", " -> ⚠️ tool is correct search_knowledge_base, but other_tool exists in output\n", "19 Prompt: What is the current stock price of Google?\n", " Output: call:search_google{query:Google stock price}\n", " `-> ✅ correct!\n", "20 Prompt: Convert 100 USD to JPY.\n", " Output: I apologize, but I cannot assist with financial or currency conversion. My current capabilities are limited to searching for business and document management information using the specified tools. I cannot perform complex financial or currency conversion.\n", " -> ❌ wrong (expected 'search_google' missing)\n", "Success : 6 / 20\n" ] } ], "source": [ "check_success_rate(trainer.model)" ] }, { "cell_type": "code", "execution_count": null, "id": "4141b9af-c153-4978-aec4-ec6d9a34f593", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "[transformers] The tokenizer has new PAD/BOS/EOS tokens that differ from the model config and generation config. The model config and generation config were aligned accordingly, being updated with the tokenizer's values. Updated tokens: {'bos_token_id': 2}.\n" ] }, { "data": { "text/html": [ "\n", "
\n", " \n", " \n", " [40/40 00:17, Epoch 8/8]\n", "
\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
EpochTraining LossValidation LossEntropyMean Token AccuracyNum Tokens
10.9519190.6401820.5998100.8980853257.000000
20.4437050.4311480.4199750.9235126514.000000
30.2458050.3567380.2827350.9416529771.000000
40.1140880.4058710.2274030.93229513028.000000
50.1223210.3941900.1852430.93492816285.000000
60.0498840.3777370.1390830.94476219542.000000
70.0785910.4614070.0869010.94580022799.000000

" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stderr", "output_type": "stream", "text": [ "Writing model shards: 100%|██████████| 1/1 [00:12<00:00, 12.17s/it]\n" ] } ], "source": [ "trainer.train()" ] } ], "metadata": { "kernelspec": { "display_name": "gemma4", "language": "python", "name": "gemma4" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.16" } }, "nbformat": 4, "nbformat_minor": 5 }