{ "cells": [ { "cell_type": "code", "execution_count": 50, "metadata": {}, "outputs": [], "source": [ "# from unsloth import FastLanguageModel\n", "from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig\n", "import torch\n", "from llama_cpp import Llama\n", "from pathlib import Path\n", "import gradio as gr\n", "from peft import PeftModelForCausalLM, PeftConfig" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "\"C:/Users/User/Data Science/Deep Learning/Generative AI/Fine Tuning LLMs/ECommerce-customer-support-chatbot/model_init/llama-3.2-1B-it-Ecommerce-ChatBot-merged-F16.gguf\"" ] }, { "cell_type": "code", "execution_count": 66, "metadata": {}, "outputs": [], "source": [ "model_id = \"llama-3.2-1B-it-Ecommerce-ChatBot-merged-F16.gguf\"" ] }, { "cell_type": "code", "execution_count": 57, "metadata": {}, "outputs": [], "source": [ "model_path = \"C:/Users/User/Data Science/Deep Learning/Generative AI/Fine Tuning LLMs/fine-tuning llama 3.2 1B/trainerdotsavemodel\"" ] }, { "cell_type": "code", "execution_count": 63, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "8" ] }, "execution_count": 63, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import os\n", "os.cpu_count()" ] }, { "cell_type": "code", "execution_count": 77, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "llama_model_loader: loaded meta data with 26 key-value pairs and 147 tensors from llama-3.2-1B-it-Ecommerce-ChatBot-merged-F16.gguf (version GGUF V3 (latest))\n", "llama_model_loader: Dumping metadata keys/values. Note: KV overrides do not apply in this output.\n", "llama_model_loader: - kv 0: general.architecture str = llama\n", "llama_model_loader: - kv 1: general.type str = model\n", "llama_model_loader: - kv 2: general.name str = E9F8Effbab1Cbdc515C11Ee6E098E3D5A9F51E14\n", "llama_model_loader: - kv 3: general.size_label str = 1.2B\n", "llama_model_loader: - kv 4: llama.block_count u32 = 16\n", "llama_model_loader: - kv 5: llama.context_length u32 = 131072\n", "llama_model_loader: - kv 6: llama.embedding_length u32 = 2048\n", "llama_model_loader: - kv 7: llama.feed_forward_length u32 = 8192\n", "llama_model_loader: - kv 8: llama.attention.head_count u32 = 32\n", "llama_model_loader: - kv 9: llama.attention.head_count_kv u32 = 8\n", "llama_model_loader: - kv 10: llama.rope.freq_base f32 = 500000.000000\n", "llama_model_loader: - kv 11: llama.attention.layer_norm_rms_epsilon f32 = 0.000010\n", "llama_model_loader: - kv 12: llama.attention.key_length u32 = 64\n", "llama_model_loader: - kv 13: llama.attention.value_length u32 = 64\n", "llama_model_loader: - kv 14: general.file_type u32 = 1\n", "llama_model_loader: - kv 15: llama.vocab_size u32 = 128256\n", "llama_model_loader: - kv 16: llama.rope.dimension_count u32 = 64\n", "llama_model_loader: - kv 17: tokenizer.ggml.model str = gpt2\n", "llama_model_loader: - kv 18: tokenizer.ggml.pre str = llama-bpe\n", "llama_model_loader: - kv 19: tokenizer.ggml.tokens arr[str,128256] = [\"!\", \"\\\"\", \"#\", \"$\", \"%\", \"&\", \"'\", ...\n", "llama_model_loader: - kv 20: tokenizer.ggml.token_type arr[i32,128256] = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ...\n", "llama_model_loader: - kv 21: tokenizer.ggml.merges arr[str,280147] = [\"Ġ Ġ\", \"Ġ ĠĠĠ\", \"ĠĠ ĠĠ\", \"...\n", "llama_model_loader: - kv 22: tokenizer.ggml.bos_token_id u32 = 128000\n", "llama_model_loader: - kv 23: tokenizer.ggml.eos_token_id u32 = 128009\n", "llama_model_loader: - kv 24: tokenizer.chat_template str = {{- bos_token }}\\n{%- if custom_tools ...\n", "llama_model_loader: - kv 25: general.quantization_version u32 = 2\n", "llama_model_loader: - type f32: 34 tensors\n", "llama_model_loader: - type f16: 113 tensors\n", "llm_load_vocab: special tokens cache size = 256\n", "llm_load_vocab: token to piece cache size = 0.7999 MB\n", "llm_load_print_meta: format = GGUF V3 (latest)\n", "llm_load_print_meta: arch = llama\n", "llm_load_print_meta: vocab type = BPE\n", "llm_load_print_meta: n_vocab = 128256\n", "llm_load_print_meta: n_merges = 280147\n", "llm_load_print_meta: vocab_only = 0\n", "llm_load_print_meta: n_ctx_train = 131072\n", "llm_load_print_meta: n_embd = 2048\n", "llm_load_print_meta: n_layer = 16\n", "llm_load_print_meta: n_head = 32\n", "llm_load_print_meta: n_head_kv = 8\n", "llm_load_print_meta: n_rot = 64\n", "llm_load_print_meta: n_swa = 0\n", "llm_load_print_meta: n_embd_head_k = 64\n", "llm_load_print_meta: n_embd_head_v = 64\n", "llm_load_print_meta: n_gqa = 4\n", "llm_load_print_meta: n_embd_k_gqa = 512\n", "llm_load_print_meta: n_embd_v_gqa = 512\n", "llm_load_print_meta: f_norm_eps = 0.0e+00\n", "llm_load_print_meta: f_norm_rms_eps = 1.0e-05\n", "llm_load_print_meta: f_clamp_kqv = 0.0e+00\n", "llm_load_print_meta: f_max_alibi_bias = 0.0e+00\n", "llm_load_print_meta: f_logit_scale = 0.0e+00\n", "llm_load_print_meta: n_ff = 8192\n", "llm_load_print_meta: n_expert = 0\n", "llm_load_print_meta: n_expert_used = 0\n", "llm_load_print_meta: causal attn = 1\n", "llm_load_print_meta: pooling type = 0\n", "llm_load_print_meta: rope type = 0\n", "llm_load_print_meta: rope scaling = linear\n", "llm_load_print_meta: freq_base_train = 500000.0\n", "llm_load_print_meta: freq_scale_train = 1\n", "llm_load_print_meta: n_ctx_orig_yarn = 131072\n", "llm_load_print_meta: rope_finetuned = unknown\n", "llm_load_print_meta: ssm_d_conv = 0\n", "llm_load_print_meta: ssm_d_inner = 0\n", "llm_load_print_meta: ssm_d_state = 0\n", "llm_load_print_meta: ssm_dt_rank = 0\n", "llm_load_print_meta: ssm_dt_b_c_rms = 0\n", "llm_load_print_meta: model type = ?B\n", "llm_load_print_meta: model ftype = F16\n", "llm_load_print_meta: model params = 1.24 B\n", "llm_load_print_meta: model size = 2.30 GiB (16.00 BPW) \n", "llm_load_print_meta: general.name = E9F8Effbab1Cbdc515C11Ee6E098E3D5A9F51E14\n", "llm_load_print_meta: BOS token = 128000 '<|begin_of_text|>'\n", "llm_load_print_meta: EOS token = 128009 '<|eot_id|>'\n", "llm_load_print_meta: LF token = 128 'Ä'\n", "llm_load_print_meta: EOT token = 128009 '<|eot_id|>'\n", "llm_load_print_meta: EOM token = 128008 '<|eom_id|>'\n", "llm_load_print_meta: EOG token = 128008 '<|eom_id|>'\n", "llm_load_print_meta: EOG token = 128009 '<|eot_id|>'\n", "llm_load_print_meta: max token length = 256\n", "llm_load_tensors: ggml ctx size = 0.07 MiB\n", "llm_load_tensors: CPU buffer size = 2357.26 MiB\n", ".............................................................\n", "llama_new_context_with_model: n_ctx = 512\n", "llama_new_context_with_model: n_batch = 32\n", "llama_new_context_with_model: n_ubatch = 32\n", "llama_new_context_with_model: flash_attn = 0\n", "llama_new_context_with_model: freq_base = 500000.0\n", "llama_new_context_with_model: freq_scale = 1\n", "llama_kv_cache_init: CPU KV buffer size = 16.00 MiB\n", "llama_new_context_with_model: KV self size = 16.00 MiB, K (f16): 8.00 MiB, V (f16): 8.00 MiB\n", "llama_new_context_with_model: CPU output buffer size = 0.49 MiB\n", "llama_new_context_with_model: CPU compute buffer size = 15.91 MiB\n", "llama_new_context_with_model: graph nodes = 518\n", "llama_new_context_with_model: graph splits = 1\n", "AVX = 1 | AVX_VNNI = 0 | AVX2 = 1 | AVX512 = 0 | AVX512_VBMI = 0 | AVX512_VNNI = 0 | AVX512_BF16 = 0 | FMA = 1 | NEON = 0 | SVE = 0 | ARM_FMA = 0 | F16C = 1 | FP16_VA = 0 | RISCV_VECT = 0 | WASM_SIMD = 0 | BLAS = 0 | SSE3 = 1 | SSSE3 = 1 | VSX = 0 | MATMUL_INT8 = 0 | LLAMAFILE = 1 | \n", "Model metadata: {'general.name': 'E9F8Effbab1Cbdc515C11Ee6E098E3D5A9F51E14', 'general.architecture': 'llama', 'general.type': 'model', 'llama.feed_forward_length': '8192', 'general.size_label': '1.2B', 'llama.block_count': '16', 'llama.context_length': '131072', 'llama.embedding_length': '2048', 'llama.attention.head_count': '32', 'tokenizer.ggml.eos_token_id': '128009', 'general.file_type': '1', 'llama.attention.head_count_kv': '8', 'llama.rope.freq_base': '500000.000000', 'llama.attention.layer_norm_rms_epsilon': '0.000010', 'llama.attention.key_length': '64', 'llama.attention.value_length': '64', 'llama.vocab_size': '128256', 'llama.rope.dimension_count': '64', 'tokenizer.ggml.model': 'gpt2', 'tokenizer.ggml.pre': 'llama-bpe', 'general.quantization_version': '2', 'tokenizer.ggml.bos_token_id': '128000', 'tokenizer.chat_template': '{{- bos_token }}\\n{%- if custom_tools is defined %}\\n {%- set tools = custom_tools %}\\n{%- endif %}\\n{%- if not tools_in_user_message is defined %}\\n {%- set tools_in_user_message = true %}\\n{%- endif %}\\n{%- if not date_string is defined %}\\n {%- if strftime_now is defined %}\\n {%- set date_string = strftime_now(\"%d %b %Y\") %}\\n {%- else %}\\n {%- set date_string = \"26 Jul 2024\" %}\\n {%- endif %}\\n{%- endif %}\\n{%- if not tools is defined %}\\n {%- set tools = none %}\\n{%- endif %}\\n\\n{#- This block extracts the system message, so we can slot it into the right place. #}\\n{%- if messages[0][\\'role\\'] == \\'system\\' %}\\n {%- set system_message = messages[0][\\'content\\']|trim %}\\n {%- set messages = messages[1:] %}\\n{%- else %}\\n {%- set system_message = \"\" %}\\n{%- endif %}\\n\\n{#- System message #}\\n{{- \"<|start_header_id|>system<|end_header_id|>\\\\n\\\\n\" }}\\n{%- if tools is not none %}\\n {{- \"Environment: ipython\\\\n\" }}\\n{%- endif %}\\n{{- \"Cutting Knowledge Date: December 2023\\\\n\" }}\\n{{- \"Today Date: \" + date_string + \"\\\\n\\\\n\" }}\\n{%- if tools is not none and not tools_in_user_message %}\\n {{- \"You have access to the following functions. To call a function, please respond with JSON for a function call.\" }}\\n {{- \\'Respond in the format {\"name\": function name, \"parameters\": dictionary of argument name and its value}.\\' }}\\n {{- \"Do not use variables.\\\\n\\\\n\" }}\\n {%- for t in tools %}\\n {{- t | tojson(indent=4) }}\\n {{- \"\\\\n\\\\n\" }}\\n {%- endfor %}\\n{%- endif %}\\n{{- system_message }}\\n{{- \"<|eot_id|>\" }}\\n\\n{#- Custom tools are passed in a user message with some extra guidance #}\\n{%- if tools_in_user_message and not tools is none %}\\n {#- Extract the first user message so we can plug it in here #}\\n {%- if messages | length != 0 %}\\n {%- set first_user_message = messages[0][\\'content\\']|trim %}\\n {%- set messages = messages[1:] %}\\n {%- else %}\\n {{- raise_exception(\"Cannot put tools in the first user message when there\\'s no first user message!\") }}\\n{%- endif %}\\n {{- \\'<|start_header_id|>user<|end_header_id|>\\\\n\\\\n\\' -}}\\n {{- \"Given the following functions, please respond with a JSON for a function call \" }}\\n {{- \"with its proper arguments that best answers the given prompt.\\\\n\\\\n\" }}\\n {{- \\'Respond in the format {\"name\": function name, \"parameters\": dictionary of argument name and its value}.\\' }}\\n {{- \"Do not use variables.\\\\n\\\\n\" }}\\n {%- for t in tools %}\\n {{- t | tojson(indent=4) }}\\n {{- \"\\\\n\\\\n\" }}\\n {%- endfor %}\\n {{- first_user_message + \"<|eot_id|>\"}}\\n{%- endif %}\\n\\n{%- for message in messages %}\\n {%- if not (message.role == \\'ipython\\' or message.role == \\'tool\\' or \\'tool_calls\\' in message) %}\\n {{- \\'<|start_header_id|>\\' + message[\\'role\\'] + \\'<|end_header_id|>\\\\n\\\\n\\'+ message[\\'content\\'] | trim + \\'<|eot_id|>\\' }}\\n {%- elif \\'tool_calls\\' in message %}\\n {%- if not message.tool_calls|length == 1 %}\\n {{- raise_exception(\"This model only supports single tool-calls at once!\") }}\\n {%- endif %}\\n {%- set tool_call = message.tool_calls[0].function %}\\n {{- \\'<|start_header_id|>assistant<|end_header_id|>\\\\n\\\\n\\' -}}\\n {{- \\'{\"name\": \"\\' + tool_call.name + \\'\", \\' }}\\n {{- \\'\"parameters\": \\' }}\\n {{- tool_call.arguments | tojson }}\\n {{- \"}\" }}\\n {{- \"<|eot_id|>\" }}\\n {%- elif message.role == \"tool\" or message.role == \"ipython\" %}\\n {{- \"<|start_header_id|>ipython<|end_header_id|>\\\\n\\\\n\" }}\\n {%- if message.content is mapping or message.content is iterable %}\\n {{- message.content | tojson }}\\n {%- else %}\\n {{- message.content }}\\n {%- endif %}\\n {{- \"<|eot_id|>\" }}\\n {%- endif %}\\n{%- endfor %}\\n{%- if add_generation_prompt %}\\n {{- \\'<|start_header_id|>assistant<|end_header_id|>\\\\n\\\\n\\' }}\\n{%- endif %}\\n'}\n", "Available chat formats from metadata: chat_template.default\n" ] } ], "source": [ "llm = Llama(model_path=model_id, n_ctx=512, n_batch=32, n_threads=os.cpu_count(), n_gpu_layers=-1, chat_format=\"llama-3\", verbose=True)" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Certainly! I'm here to assist you with any concerns or questions you may have. Whether it's regarding your account, a product or service, or any other matter, I'm here to provide you with the guidance and support you need.\n" ] } ], "source": [ "print(response['choices'][0]['text'])" ] }, { "cell_type": "code", "execution_count": 72, "metadata": {}, "outputs": [], "source": [ "def generate_response(message:str) -> str:\n", " return llm.create_chat_completion(\n", " messages=[\n", " {\n", " \"role\": \"system\",\n", " \"content\": \"You are a top-rated customer service agent named John. Be polite to customers and answer all their questions. If the question is out of context and not related to your job as a customer service agent, let the customer know that you can not help and they should look elsewhere for answers.\"\n", " },\n", " {\n", " \"role\": \"user\",\n", " \"content\": message\n", " }\n", " ]\n", " )['choices'][0]['message']['content']" ] }, { "cell_type": "code", "execution_count": 78, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "llama_perf_context_print: load time = 2383.18 ms\n", "llama_perf_context_print: prompt eval time = 0.00 ms / 82 tokens ( 0.00 ms per token, inf tokens per second)\n", "llama_perf_context_print: eval time = 0.00 ms / 71 runs ( 0.00 ms per token, inf tokens per second)\n", "llama_perf_context_print: total time = 15843.08 ms / 153 tokens\n" ] }, { "data": { "text/plain": [ "'Your invoice for a particular order is located in your account on our website. To access it, simply log in to your account and navigate to the \"Invoices\" section. From there, you should be able to view your invoice in detail and take any necessary action. If you need further assistance or have any questions, feel free to let me know.'" ] }, "execution_count": 78, "metadata": {}, "output_type": "execute_result" } ], "source": [ "generate_response('where can i see my invoice for a particular order')" ] }, { "cell_type": "code", "execution_count": 41, "metadata": {}, "outputs": [], "source": [ "demo = gr.ChatInterface(\n", " fn=generate_response,\n", " examples=[\n", " \"What Payment Modalities are accepted?\", \n", " \"Can you help me cancel an order?\", \n", " \"What is your name and how can you help me today?\"\n", " ], \n", " title=\"Customer Support\"\n", " )" ] }, { "cell_type": "code", "execution_count": 44, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Running on local URL: http://127.0.0.1:7860\n", "\n", "To create a public link, set `share=True` in `launch()`.\n" ] }, { "data": { "text/html": [ "
" ], "text/plain": [ "