<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Thomas J Varghese on Medium]]></title>
        <description><![CDATA[Stories by Thomas J Varghese on Medium]]></description>
        <link>https://medium.com/@thomasjvarghese49?source=rss-6ab7b858f04e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*aHkFCR8EgEM7QbRd</url>
            <title>Stories by Thomas J Varghese on Medium</title>
            <link>https://medium.com/@thomasjvarghese49?source=rss-6ab7b858f04e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 17:40:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@thomasjvarghese49/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building Dynamic Multi-Expert AI: Switching Between Specialized LoRA Adapters in Real-Time, Part 2]]></title>
            <link>https://medium.com/@thomasjvarghese49/building-dynamic-multi-expert-ai-switching-between-specialized-lora-adapters-in-real-time-part-2-d94701587119?source=rss-6ab7b858f04e------2</link>
            <guid isPermaLink="false">https://medium.com/p/d94701587119</guid>
            <dc:creator><![CDATA[Thomas J Varghese]]></dc:creator>
            <pubDate>Sat, 26 Sep 2026 10:11:47 GMT</pubDate>
            <atom:updated>2026-09-26T10:12:28.000Z</atom:updated>
            <content:encoded><![CDATA[<p>In Part 1 I laid out the architecture: a base Llama 3.2 3B model classifies each query and sends it to one of three places: a Cypher query adapter, a function-calling adapter, or the base model itself for anything generic. This part covers the part I promised: training those adapters and getting them to switch at inference time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GuPRkExJiKhQNCdEi_sJow.png" /></figure><h3>Loading the base model</h3><p>I load Llama 3.2 3B Instruct without quantization. There’s room to add 4-bit or 8-bit loading if you’re tighter on memory, but on a 16GB card the full-precision model fits fine once LoRA freezes the base weights.</p><pre>from transformers import AutoModelForCausalLM, BitsAndBytesConfig<br>from peft import prepare_model_for_kbit_training, LoraConfig<br><br>bnb_config = BitsAndBytesConfig(load_in_4bit=False)<br><br>model = AutoModelForCausalLM.from_pretrained(<br>    &quot;Llama-3.2-3B-Instruct&quot;,<br>    device_map=&quot;cuda:0&quot;,<br>    quantization_config=None<br>)<br>model = prepare_model_for_kbit_training(model)</pre><h3>Configuring LoRA</h3><p>This is the part that makes the whole system cheap to run. LoRA injects small trainable rank-decomposition matrices into the attention layers and leaves everything else frozen, so instead of updating all 3B parameters you’re only updating a fraction of that.</p><pre>config = LoraConfig(<br>    r=64,                # rank — higher means more expressive, more parameters<br>    lora_alpha=128,       # scaling factor for the LoRA update<br>    bias=&quot;none&quot;,<br>    lora_dropout=0.01,<br>    task_type=&quot;CAUSAL_LM&quot;<br>)<br>model = get_peft_model(model, config)<br><br>train_p, tot_p = model.get_nb_trainable_parameters()<br>print(f&#39;Trainable parameters: {train_p/1e6:.2f}M&#39;)<br>print(f&#39;Total parameters: {tot_p/1e6:.2f}M&#39;)<br>print(f&#39;% trainable: {100*train_p/tot_p:.2f}%&#39;)</pre><p>With r=64 the trainable parameters come out to around 1-2% of the total model. That&#39;s the whole point of switching adapters instead of switching models — you&#39;re storing and swapping a few hundred MB per adapter instead of multiple full 6GB+ checkpoints.</p><p>Preparing the Cypher dataset</p><p>For the graph-query specialist I used an existing HuggingFace dataset (vprashant/cypher_dataset) with natural-language-to-Cypher pairs, and reshaped it into the chat format the trainer expects.</p><pre>from datasets import load_dataset<br><br>dataset = load_dataset(&quot;vprashant/cypher_dataset&quot;, split=&quot;train&quot;)<br>dataset = dataset.rename_column(&quot;Natural Language Description&quot;, &quot;prompt&quot;)<br>dataset = dataset.rename_column(&quot;Cypher Query&quot;, &quot;completion&quot;)<br><br>def format_dataset(examples):<br>    return {<br>        &quot;messages&quot;: [<br>            {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: examples[&quot;prompt&quot;]},<br>            {&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: examples[&quot;completion&quot;]}<br>        ]<br>    }<br><br>dataset = dataset.map(format_dataset).remove_columns([&#39;prompt&#39;, &#39;completion&#39;])</pre><p>Same pattern for the function-calling adapter swap in the synthetic dataset you generated from your function schemas in Part 1.</p><h3>Fine-tuning with SFTTrainer</h3><pre>from trl import SFTConfig, SFTTrainer<br><br>sft_config = SFTConfig(<br>    gradient_checkpointing=True,<br>    gradient_checkpointing_kwargs={&#39;use_reentrant&#39;: False},<br>    gradient_accumulation_steps=1,<br>    per_device_train_batch_size=16,<br>    auto_find_batch_size=True,<br>    max_seq_length=128,<br>    packing=True,<br>    num_train_epochs=25,<br>    learning_rate=2e-4,<br>    optim=&#39;paged_adamw_32bit&#39;,<br>    warmup_steps=10,<br>    logging_steps=10,<br>    output_dir=&#39;./llama3.2-cypher-query-adapter&#39;<br>)<br><br>trainer = SFTTrainer(<br>    model=model,<br>    processing_class=tokenizer,<br>    args=sft_config,<br>    train_dataset=dataset,<br>)<br>trainer.train()<br>trainer.save_model(&#39;local-llama3-custom-cypher-query-adapter&#39;)</pre><p>25 epochs sounds high, but with a small rank adapter on a few hundred focused examples, you’re not really at risk of wrecking the base model’s general knowledge — you’re only touching the LoRA matrices. And packing=True matters more than it looks: Cypher queries and function-call examples are short, so without packing most of the batch is padding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ai_AITcTp6RGSxUao8sopA.png" /></figure><p>Repeat this for the function-calling adapter with its own dataset and its own output directory.</p><h3>Checking a single adapter</h3><p>Before worrying about switching, I confirm the adapter actually learned its task.</p><pre>messages = [{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;List all projects that have more than 15 employees working on them.&quot;}]<br>prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)<br>inputs = tokenizer(prompt, return_tensors=&#39;pt&#39;, padding=True, truncation=True).to(&quot;cuda&quot;)<br>outputs = model.generate(**inputs, max_new_tokens=150)<br>print(tokenizer.decode(outputs[0], skip_special_tokens=True).split(&quot;assistant&quot;)[1])</pre><p>If the Cypher adapter learned its job, this comes back as a valid MATCH ... WHERE ... RETURN query instead of a natural-language non-answer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*inTimDd1-qqoUMC1KGsioA.png" /></figure><h3>Switching adapters at inference time</h3><p>This is the part that ties back to the diagram from Part 1. Keeping three separate merged models resident in GPU memory defeats the point of using LoRA at all. So instead, the base model loads once, and adapters get swapped on top of it as needed.</p><pre>def run_inference(model, messages):<br>    prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)<br>    inputs = tokenizer(prompt, return_tensors=&#39;pt&#39;, padding=True, truncation=True).to(&quot;cuda&quot;)<br>    with torch.no_grad():<br>        outputs = model.generate(**inputs, max_new_tokens=150, do_sample=True, temperature=0.7)<br>    response = tokenizer.decode(outputs[0], skip_special_tokens=True)<br>    return response.split(&quot;assistant&quot;, 1)[-1].strip() if &quot;assistant&quot; in response else response<br><br>def load_adapter_fresh(adapter_path=None):<br>    global current_model<br>    if current_model is not None:<br>        del current_model<br>        torch.cuda.empty_cache()<br>        gc.collect()<br>    current_model = PeftModel.from_pretrained(base_model, adapter_path) if adapter_path else base_model<br>    return current_model<br><br># Function-calling adapter<br>model = load_adapter_fresh(adapter1_path)<br>print(run_inference(model, [{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;send an email to my boss&quot;}]))<br><br># Cypher adapter<br>model = load_adapter_fresh(adapter2_path)<br>print(run_inference(model, [{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;List all projects with more than 3 employees.&quot;}]))<br><br># Base model for generic queries<br>model = load_adapter_fresh()<br>print(run_inference(model, [{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;What&#39;s refraction in physics?&quot;}]))</pre><p>This is manual switching: tear down whichever PeftModel wrapper is active, and re-wrap the same base model with a different adapter&#39;s weights. Simple, and it works, but it has real limits. Each switch pays a reload cost, since adapter weights get loaded from disk and re-wrapped every time — fine for a single-user local setup, not what you want on a low-latency production path. And only one specialist is live at a time, which matches the router-then-specialist flow from the diagram but rules out blending adapters or serving multiple users on different adapters at once.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*muqRcgJYuomb7-U3gNfabw.png" /></figure><p>For anything past a personal setup, PEFT supports registering multiple adapters directly on one model object — model.load_adapter(path, adapter_name=...) plus model.set_adapter(name) — which skips the teardown-and-rebuild cycle and just flips which adapter is active in the forward pass. If you outgrow single-GPU, single-user serving, frameworks like LoRAX or vLLM&#39;s multi-LoRA support handle hot-swapping adapters across concurrent requests.</p><h3>Where this leaves things</h3><p>Back to the Part 1 diagram: the base model classifies the query, hands it to whichever adapter fits, and routes the specialist’s output back through the base model so the final response reads like a normal reply instead of a bare Cypher string or function payload. That loop-back is what makes the difference between an adapter that’s technically correct and a response that feels like one assistant.</p><p>What you end up with is a fully local, three-in-one setup running on a 16GB GPU, no cloud calls, no per-token cost, and the option to keep adding specialists by training and dropping in new adapters.</p><p>Repo: <a href="https://github.com/thomasjv799/LocalLoraX">https://github.com/thomasjv799/LocalLoraX</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d94701587119" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Dynamic Multi-Expert AI: Switching Between Specialized LoRA Adapters in Real-Time, Part 1]]></title>
            <link>https://medium.com/@thomasjvarghese49/building-dynamic-multi-expert-ai-switching-between-specialized-lora-adapters-in-real-time-part-1-a622ed29d6d1?source=rss-6ab7b858f04e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a622ed29d6d1</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[lora-adapter]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[agents]]></category>
            <dc:creator><![CDATA[Thomas J Varghese]]></dc:creator>
            <pubDate>Sat, 31 May 2025 19:13:34 GMT</pubDate>
            <atom:updated>2025-05-31T19:13:34.928Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>LoRA (Low-Rank Adaptation)</strong> is a breakthrough technique for fine-tuning large models efficiently by adding low-rank matrices to existing layers. Unlike traditional fine-tuning that updates millions of parameters, LoRA trains only the additional weight changes while freezing the original model weights. This makes fine-tuning dramatically more resource-efficient.</p><p>In this article, we’ll explore how to use multiple LoRA adapters that switch dynamically between specialized tasks, giving you expert-level responses across different domains without running multiple full models.</p><p>See: <a href="https://arxiv.org/abs/2106.09685">https://arxiv.org/abs/2106.09685</a></p><h3>The Real-World Problem</h3><p>Picture this scenario: you have a 16GB GPU and want to avoid cloud LLM services for privacy or cost reasons. You need an AI system that excels at three things: calling your custom functions, generating Cypher queries for graph databases, and handling general conversations.</p><p>I chose Llama 3.2 3B as the base model. While capable, it can’t handle specialized tasks like custom function calling or Cypher generation without additional training. The base model simply lacks exposure to your specific API schemas and domain syntax.</p><h3>The Dynamic Architecture Solution</h3><p>The system works through intelligent query routing. When users ask questions, the base model first classifies where to send the query: to the Function Calling adapter, Cypher Query adapter, or keep it for general responses. After the specialized adapter processes the query, we route the output back through the base model to ensure natural, conversational responses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/971/1*0CmPReiwJaiBNjkS_i2I7Q.png" /></figure><p>This approach offers several advantages. You get multiple domain experts running on consumer hardware, and with quantization, you can use even less powerful GPUs. Each adapter focuses on its specialty while contributing to a unified, intelligent system.</p><h3>Building Custom Function Calling</h3><p>For the function calling adapter, I created three example functions that demonstrate different integration types:</p><p>A <strong>search engine function </strong>using Serper API provides web search capabilities without complex API management. This lets your AI retrieve current information beyond its training cutoff.</p><p>A <strong>Harry Potter API</strong> integration shows how to incorporate specialized knowledge bases, extending the model’s expertise into specific domains with structured data access.</p><p>An <strong>email sending function</strong> through Google Cloud demonstrates real-world action capabilities, transforming your AI from a conversational tool into an active assistant that can execute tasks.</p><p>See the mock functions below:</p><pre>import requests<br>import json<br>import os<br>import base64<br>from email.message import EmailMessage<br><br>from google.auth.transport.requests import Request<br>from google.oauth2.credentials import Credentials<br>from google_auth_oauthlib.flow import InstalledAppFlow<br>from googleapiclient.discovery import build<br>from googleapiclient.errors import HttpError<br><br>## Search Engine Function using Serper<br>def search_engine(user_query, country=&quot;in&quot;, location=&quot;India&quot;, language=&quot;el&quot;, num_results=20, date_range=&quot;d&quot;):<br>    &quot;&quot;&quot;<br>    Function to perform a search using the Serper API.<br>    Parameters:<br>    user_query (str): The search query.<br>    country (str): The country code for the search (default is &quot;in&quot; for India, &#39;us&#39; for usa, &#39;gb&#39; for united kingdom etc).<br>    location (str): The location for the search (default is &quot;India&quot;, other options are United States, United Kingdom etc).<br>    language (str): The language for the search results (default is &quot;el&quot; for English, &quot;de&quot; for german, &quot;ml&quot; for malayalm etc).<br>    num_results (int): The number of results to return (default is 20).<br>    date_range (str): The date range for the search results (default is &quot;d&quot; for past day,&quot;h&quot; for hour, &quot;w&quot; for week, &quot;m&quot; for month).<br>    &quot;&quot;&quot;<br>    if not isinstance(user_query, str):<br>        raise ValueError(&quot;user_query must be a string&quot;)<br>    <br>    url = &quot;https://google.serper.dev/search&quot;<br><br>    payload = json.dumps({<br>      &quot;q&quot;: user_query,<br>      &quot;location&quot;: location,<br>      &quot;gl&quot;: country,<br>      &quot;hl&quot;: language,<br>      &quot;num&quot;: num_results,<br>      &quot;tbs&quot;: f&quot;qdr:{date_range}&quot;<br>    })<br>    headers = {<br>    &#39;X-API-KEY&#39;: &#39;&lt;API-KEY&gt;&#39;,  # Replace &lt;API-KEY&gt; with your actual Serper API key<br>    &#39;Content-Type&#39;: &#39;application/json&#39;<br>    }<br><br>    response = requests.request(&quot;POST&quot;, url, headers=headers, data=payload)<br><br>    return response.json()<br><br>## Harry Potter API<br>class HarryPotterAPI:<br>    def __init__(self, language=&#39;en&#39;):<br>        &quot;&quot;&quot;<br>        Initialize the API client with a specified language.<br>        Languages: en, es, ft, it, pt, uk<br>        &quot;&quot;&quot;<br>        self.base_url = f&quot;https://potterapi-fedeperin.vercel.app/{language}&quot;<br>        self.session = requests.Session()<br><br>    def fetch(self, category: str, random: bool = False, index=None, max_items=None, page=None, search=None):<br>        &quot;&quot;&quot;<br>        General fetch method for books, characters, houses, or spells.<br><br>        Parameters:<br>        - category (str): One of &#39;books&#39;, &#39;characters&#39;, &#39;houses&#39;, &#39;spells&#39;<br>        - random (bool): If True, fetches a random item<br>        - index (int): Fetch a specific item by index<br>        - max_items (int): Limits number of items returned<br>        - page (int): Works with max to paginate<br>        - search (str): Keyword to search<br><br>        Returns:<br>        - dict or list: API response in JSON format<br>        &quot;&quot;&quot;<br>        if category not in [&#39;books&#39;, &#39;characters&#39;, &#39;houses&#39;, &#39;spells&#39;]:<br>            raise ValueError(&quot;Invalid category. Must be one of: &#39;books&#39;, &#39;characters&#39;, &#39;houses&#39;, &#39;spells&#39;&quot;)<br><br>        endpoint = f&quot;/{category}/random&quot; if random else f&quot;/{category}&quot;<br>        url = self.base_url + endpoint<br><br>        params = {}<br>        if index is not None:<br>            params[&#39;index&#39;] = index<br>        if max_items is not None:<br>            params[&#39;max&#39;] = max_items<br>        if page is not None:<br>            params[&#39;page&#39;] = page<br>        if search is not None:<br>            params[&#39;search&#39;] = search<br><br>        try:<br>            response = self.session.get(url, params=params)<br>            response.raise_for_status()<br>            return response.json()<br>        except requests.RequestException as e:<br>            print(f&quot;Error fetching {category}: {e}&quot;)<br>            return None<br><br><br>## Email Sending Function: Refer Google cloud documentations to see how to do it.<br>## Note that this is a very basic one, for production we need to have a whole different code <br>## with necessary security and <br><br># Scope must allow sending<br>SCOPES = [&quot;https://www.googleapis.com/auth/gmail.send&quot;]<br><br>def send_email_via_gmail(to_email: str, subject: str, body_text: str):<br>    &quot;&quot;&quot;<br>    Sends an email via Gmail API.<br><br>    Args:<br>        to_email (str): Recipient&#39;s email address.<br>        subject (str): Subject of the email.<br>        body_text (str): Plain text body of the email.<br><br>    Returns:<br>        dict: Sent message metadata if successful, else None.<br>    &quot;&quot;&quot;<br>    creds = None<br>    creds_id = &quot;example@gmail.com&quot; # Replace with your gmail id that has permission<br><br>    # Load credentials<br>    if os.path.exists(&quot;token.json&quot;):<br>        creds = Credentials.from_authorized_user_file(&quot;token.json&quot;, SCOPES)<br><br>    # If no valid credentials, trigger login flow<br>    if not creds or not creds.valid:<br>        if creds and creds.expired and creds.refresh_token:<br>            creds.refresh(Request())<br>        else:<br>            flow = InstalledAppFlow.from_client_secrets_file(&quot;credentials.json&quot;, SCOPES)<br>            creds = flow.run_local_server(port=0)<br>        with open(&quot;token.json&quot;, &quot;w&quot;) as token:<br>            token.write(creds.to_json())<br><br>    try:<br>        service = build(&quot;gmail&quot;, &quot;v1&quot;, credentials=creds)<br>        message = EmailMessage()<br>        message.set_content(body_text)<br>        message[&quot;To&quot;] = to_email<br>        message[&quot;From&quot;] = creds_id<br>        message[&quot;Subject&quot;] = subject<br><br>        # Encode and send<br>        encoded_message = base64.urlsafe_b64encode(message.as_bytes()).decode()<br>        send_request = {&quot;raw&quot;: encoded_message}<br>        sent_message = service.users().messages().send(userId=creds_id, body=send_request).execute()<br><br>        print(f&quot;Email sent! Message ID: {sent_message[&#39;id&#39;]}&quot;)<br>        return sent_message<br><br>    except HttpError as error:<br>        print(f&quot;An error occurred: {error}&quot;)<br>        return None</pre><h3>Dataset Creation Strategy</h3><p>Building quality training data is crucial for adapter performance. Instead of manual creation, leverage existing LLMs to generate comprehensive datasets. Provide your function definitions to models like ChatGPT or Claude, asking for OpenAPI schemas or detailed descriptions that capture each function’s full capabilities.</p><p>While local LLMs can generate training data, I found Grok and Claude produced superior results. Their advanced reasoning creates more nuanced training examples, leading to more reliable adapters.</p><p>Your dataset generation prompt should encourage diverse query patterns, edge cases, and natural variations in how users might request the same functionality. This diversity creates robust adapters that handle real-world usage effectively. This is the prompt I used to generate the data:</p><pre>You are a data generator tasked with creating a dataset to fine-tune a function-calling large language model (LLM) in the OpenAI-style format. <br>The dataset should consist of realistic, diverse, and conversational user queries paired with structured function calls for three specified APIs. <br>The goal is to produce a dataset that helps the LLM learn to map natural language inputs to accurate function calls, including handling vague, ambiguous, or multi-intent queries.<br><br>Requirements<br><br>Each example must include:<br><br>A user message: A natural, conversational query that reflects how real users might phrase requests. Avoid robotic, templated, or overly formal language unless contextually appropriate (e.g., formal emails).<br>An assistant response: A JSON string containing one or more function calls, formatted as [{&quot;name&quot;: &quot;FUNCTION_NAME&quot;, &quot;arguments&quot;: {ARGUMENTS}}].<br><br>The dataset must be a JSON array of alternating user and assistant messages, like:<br><br>json<br>[<br>  {&quot;content&quot;: &quot;User query here&quot;, &quot;role&quot;: &quot;user&quot;},<br>  {&quot;content&quot;: &quot;[{\&quot;name\&quot;: \&quot;function_name\&quot;, \&quot;arguments\&quot;: {...}}]&quot;, &quot;role&quot;: &quot;assistant&quot;},<br>  ...<br>]<br><br>Diversity and Realism: User queries should vary in tone (casual, formal, curious, urgent), complexity (simple, multi-intent, vague), and context (personal, professional, hobby-related).<br><br>Include edge cases, such as:<br><br>Vague queries (e.g., &quot;Tell me about Harry Potter&quot;) requiring reasonable assumptions.<br>Ambiguous queries (e.g., &quot;Send an email to John&quot;) needing default values or clarification.<br>Multi-intent queries (e.g., &quot;Email my boss about the meeting and search for restaurants nearby&quot;).<br>Queries with typos or informal language (e.g., &quot;whats the best spell in harry potter&quot;).<br>Avoid repetitive phrasing; ensure each query feels unique and human-like.<br><br>Function Call Accuracy:<br>Function calls must strictly adhere to the provided API schemas.<br>For ambiguous queries, make reasonable assumptions (e.g., inferring a default max_items or subject).<br>For multi-intent queries, include multiple function calls in the assistant response when applicable.<br><br>Edge Case Handling:<br>If a query is too vague to map directly to a function (e.g., &quot;Help me with Harry Potter&quot;), assume a reasonable function call (e.g., fetch characters with a default max_items).<br>For incomplete email queries (e.g., missing subject), infer a concise, context-appropriate subject and body.<br>For search queries with broad terms, use the exact user phrasing in user_query but apply optional parameters sensibly.<br><br>APIs &amp; Schemas<br><br>Gmail Send API (send_email)<br>Function name: send_email<br>Arguments:<br>to_email (string, required): Valid email address.<br>subject (string, required): Brief, context-appropriate subject line.<br>body_text (string, required): Natural email body matching the query’s intent.<br>Example query: &quot;Email my friend Anna to meet for coffee.&quot;<br>Function call: [{&quot;name&quot;: &quot;send_email&quot;, &quot;arguments&quot;: {&quot;to_email&quot;: &quot;anna@example.com&quot;, &quot;subject&quot;: &quot;Coffee Meetup&quot;, &quot;body_text&quot;: &quot;Hey Anna, want to grab coffee this weekend? Let me know!&quot;}}]<br><br>Harry Potter API (harry_potter_fetch)<br>Function name: harry_potter_fetch<br>Arguments:<br>category (string, required): One of characters, spells, houses, books.<br>Optional:<br>search (string): Filter results by a search term (e.g., character name, spell type).<br>max_items (int): Limit the number of results.<br>index (int, zero-based): Retrieve a specific item by index.<br>random (bool): Return a random item if true.<br>Example query: &quot;Who’s a random Harry Potter character?&quot;<br>Function call: [{&quot;name&quot;: &quot;harry_potter_fetch&quot;, &quot;arguments&quot;: {&quot;category&quot;: &quot;characters&quot;, &quot;random&quot;: true, &quot;max_items&quot;: 1}}]<br>Serper Search API (search_engine)<br><br>Function name: search_engine<br>Arguments:<br>user_query (string, required): The search query as provided by the user.<br>Optional:<br>country (string, ISO-2 code like us, in): Country for localized results.<br>location (string): Specific city or region.<br>language (string, e.g., en, de): Language for results.<br>date_range (string: d = day, w = week, m = month): Filter by recency.<br>Example query: &quot;Find Italian restaurants in Rome.&quot;<br>Function call: [{&quot;name&quot;: &quot;search_engine&quot;, &quot;arguments&quot;: {&quot;user_query&quot;: &quot;Italian restaurants in Rome&quot;, &quot;location&quot;: &quot;Rome, Italy&quot;, &quot;country&quot;: &quot;it&quot;}}]<br><br>Guidelines<br>Query Variety: Mimic real-world use cases (e.g., planning events, seeking information, casual inquiries). Examples:<br>Casual: &quot;Hey, what’s up with Gryffindor?&quot;<br>Formal: &quot;Please send an email to my supervisor requesting a performance review.&quot;<br>Vague: &quot;Tell me something cool about Harry Potter.&quot;<br>Multi-intent: &quot;Email my team about the project delay and search for project management tips.&quot;<br><br>Function Call Logic:<br>For send_email, craft concise, natural email bodies and subjects that align with the user’s intent.<br>For harry_potter_fetch, use optional parameters (search, max_items, index, random) when implied by the query (e.g., &quot;first book&quot; → index: 0).<br>For search_engine, preserve the user’s query verbatim in user_query, but add optional parameters when contextually relevant (e.g., location for local searches).<br><br>Constraints:<br>Avoid overly complex queries that require multiple unrelated functions unless explicitly multi-intent.<br>Ensure email addresses in send_email are plausible (e.g., name@domain.com).<br>Use realistic locations and ISO-2 codes for search_engine.<br>Limit max_items in harry_potter_fetch to reasonable values (e.g., 1–10) unless specified.<br><br>Output Format:<br>Provide a JSON array with exactly 300 pairs (100 per API).<br>Ensure valid JSON syntax for assistant responses.<br>Group examples by API for clarity, but the final array can interleave them if desired.<br>Example Output<br><br>json<br>[<br>  {&quot;content&quot;: &quot;Send a quick email to my friend Jake about grabbing lunch tomorrow.&quot;, &quot;role&quot;: &quot;user&quot;},<br>  {&quot;content&quot;: &quot;[{\&quot;name\&quot;: \&quot;send_email\&quot;, \&quot;arguments\&quot;: {\&quot;to_email\&quot;: \&quot;jake@example.com\&quot;, \&quot;subject\&quot;: \&quot;Lunch Tomorrow\&quot;, \&quot;body_text\&quot;: \&quot;Hey Jake, want to grab lunch tomorrow? Maybe around noon? Let me know!\&quot;}}]&quot;, &quot;role&quot;: &quot;assistant&quot;},<br>  {&quot;content&quot;: &quot;What are some cool spells from Harry Potter?&quot;, &quot;role&quot;: &quot;user&quot;},<br>  {&quot;content&quot;: &quot;[{\&quot;name\&quot;: \&quot;harry_potter_fetch\&quot;, \&quot;arguments\&quot;: {\&quot;category\&quot;: \&quot;spells\&quot;, \&quot;max_items\&quot;: 5}}]&quot;, &quot;role&quot;: &quot;assistant&quot;},<br>  {&quot;content&quot;: &quot;Search for coffee shops in San Francisco.&quot;, &quot;role&quot;: &quot;user&quot;},<br>  {&quot;content&quot;: &quot;[{\&quot;name\&quot;: \&quot;search_engine\&quot;, \&quot;arguments\&quot;: {\&quot;user_query\&quot;: \&quot;coffee shops in San Francisco\&quot;, \&quot;location\&quot;: \&quot;San Francisco, CA\&quot;, \&quot;country\&quot;: \&quot;us\&quot;}}]&quot;, &quot;role&quot;: &quot;assistant&quot;}<br>]<br>Generate 300 pairs (100 per API) adhering to these requirements. Ensure the dataset is varied, realistic, and suitable for fine-tuning a function-calling LLM. Please stop only once you generate the entire dataset.</pre><p>Around 500 high-quality data points provides the sweet spot between comprehensive coverage and manageable computation requirements for fine-tuning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EAkxsuJpDKoor8RVhbxrFg.png" /><figcaption>Response from Grok 3</figcaption></figure><p>If we have our own custom Schema for Neo4j database, then we can pass it to a prompt and generate similar dataset. In this tutorial I have used dataset from Huggingface. I took this dataset:</p><p><a href="https://huggingface.co/datasets/vprashant/cypher_dataset">vprashant/cypher_dataset · Datasets at Hugging Face</a></p><p>Thats all for the part 1. One part 2 we will see how to finetune and test how the adapters are behaving.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a622ed29d6d1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Limitations to Innovation: The Deepseek R1 Revolution]]></title>
            <link>https://medium.com/@thomasjvarghese49/from-limitations-to-innovation-the-deepseek-r1-revolution-3b170178abaa?source=rss-6ab7b858f04e------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b170178abaa</guid>
            <category><![CDATA[genertive-ai]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[nvidia]]></category>
            <category><![CDATA[deepseek]]></category>
            <category><![CDATA[openai]]></category>
            <dc:creator><![CDATA[Thomas J Varghese]]></dc:creator>
            <pubDate>Wed, 29 Jan 2025 19:24:06 GMT</pubDate>
            <atom:updated>2025-01-29T19:24:06.318Z</atom:updated>
            <content:encoded><![CDATA[<p>Deepseek has become a buzzword and recently made shockwaves across the globe for its remarkable performance and cost-effectiveness. This Chinese model has demonstrated capabilities approaching those of OpenAI’s best model GPT-4o, which is considered one of the finest reasoning LLMs in the market.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lJYjZnOYNlwbYQyL" /></figure><p>What’s garnering attention isn’t just the model’s performance, but its cost implications. While GPT-4’s training costs are estimated to exceed 100 million USD, Deepseek R1 was developed for less than 10 million USD. This achievement is particularly significant because Deepseek never had access to the latest NVIDIA GPUs due to US sanctions. Instead, they utilized less powerful GPUs and leveraged PTX, a low-level instruction set for NVIDIA GPUs that functions like assembly language to manage cross-chip communications. This represents an extraordinary optimization at the foundational level. Their research paper outlines numerous other optimizations implemented during the model’s training process.</p><p>Regarding capabilities, Deepseek has achieved impressive results across nearly all benchmarks, particularly in reasoning tasks. However, when questioned about sensitive topics like the Tiananmen Square incident, Arunachal Pradesh’s territorial status, or Taiwan, the model either declines to respond or provides answers aligned with Chinese perspectives.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*NJi2O9ebGPwG9tn0PKG49Q.png" /></figure><p>Despite this content filtering, a crucial advantage is the model’s open-source nature, allowing anyone to download and modify it for their specific needs. Organizations with suitable GPU infrastructure and data can host their own version of Deepseek R1 locally, ensuring data security while accessing a high-performing LLM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ON0p5UDpVhXJj6HEkZmCbA.png" /></figure><p>While Deepseek R1’s introduction has caused market turbulence globally, it has revealed important insights. Despite US sanctions aimed at limiting AI advancement, Deepseek’s researchers devised innovative solutions to overcome these barriers and deliver exceptional results. They maximized output from limited resources through optimization and innovation. The Deepseek story reinforces that open source is key to technological market dominance. Moving forward, we’re likely to see competition shift from national rivalries to a battle between open-source and closed-source approaches, with each iteration bringing us closer to AI’s next frontier, AGI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*UfBqUZyQobPKxQsd" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b170178abaa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Run your own Fine tuned Large Language Model locally without any internet using Llama.cpp: Part 2]]></title>
            <link>https://medium.com/@thomasjvarghese49/run-your-own-fine-tuned-large-language-model-locally-without-any-internet-using-llama-cpp-part-2-3893ad8694b9?source=rss-6ab7b858f04e------2</link>
            <guid isPermaLink="false">https://medium.com/p/3893ad8694b9</guid>
            <category><![CDATA[llama-cpp]]></category>
            <category><![CDATA[hugging-face]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[transformers]]></category>
            <dc:creator><![CDATA[Thomas J Varghese]]></dc:creator>
            <pubDate>Sat, 02 Mar 2024 18:06:08 GMT</pubDate>
            <atom:updated>2024-03-02T18:22:45.083Z</atom:updated>
            <content:encoded><![CDATA[<p>In <a href="https://medium.com/@thomasjvarghese49/run-your-own-fine-tuned-large-language-model-locally-without-any-internet-using-llama-cpp-part-1-a5db72801ccc">Part 1</a> we saw how we can fine tune a model on a dataset and use it for our custom purpose. One of the main thing about GenAI is the necessity of GPU. As we all know GPU is its power house and important hardware. But some of us may not have GPU and won’t be able to run these techs. In near future we can expect it to be freely on our smart phones as the R &amp; D is really strong now, especially this <a href="https://arxiv.org/abs/2312.11514">paper from Apple</a>.</p><p>Lets see how we can run an LLM locally without any GPU but solely on CPU. Right now my system has 32 GB RAM with a 11th Gen Intel i7 Processor, the inbuilt is from Intels which we cannot leverage as of now. We will be using llama.cpp to make this run happen on windows OS.</p><p>The main goal of llama.cpp is to make it easy to use big language models (LLMs) on different devices, like computers or cloud servers. It’s written in simple C/C++ without needing extra software. It works well on Apple computers, using their special chips and tools. It also supports other types of computers like Intel ones with AVX, AVX2, and AVX512.</p><p>It helps speed up the processing of language models by using different tricks like quantization (using fewer bits to represent numbers) and has special features for GPUs, like NVIDIA and AMD. It can work with various technologies like Vulkan, SYCL, and a bit of OpenCL. It even lets you use both the CPU and GPU together to make big models work faster.</p><p>Since it started, many people have helped make llama.cpp better and is one of the best tools for LLM’s.</p><p>Lets Get started</p><h4>1 . Clone Hugging Face Model and llama.cpp repository</h4><p>Firstly we need a model to experiment. In this tutorial I will be converting <a href="https://huggingface.co/mlabonne/NeuralMonarch-7B">https://huggingface.co/mlabonne/NeuralMonarch-7B</a> to GGUF format and run on my local machine. Make sure the repository you choose have models in the .safetensor format.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SbU9GGM7TYhqiDO0.jpeg" /><figcaption>mlabonne/NeuralMonarch-7B</figcaption></figure><p>Lets first clone it and for we can use git and LFS. Go the repository of your choice and click on three dots as shown in the figure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NYPvvoRn45jow4zfSTjm1A.png" /></figure><p>Once you click there click on Clone Repository. You have install Git LFS as said there and clone.</p><pre>git lfs clone https://huggingface.co/mlabonne/NeuralMonarch-7B</pre><p>I am using LFS here so that I will be able to see the progress of the large files being cloned into my system. Next go to this <a href="https://github.com/ggerganov/llama.cpp">repo</a> and clone it.</p><h4>2. Extract w64devkit and install WSL</h4><p>For conversion of our Hugging Face model to GGUF, we need a Linux terminal so for that we need to install WSL. If you need to know more, <a href="https://learn.microsoft.com/en-us/windows/wsl/install">read here</a>. Converting the model was not possible for me in windows because of some dependency and lack of support so we need WSL for this case.</p><p><a href="https://github.com/skeeto/w64devkit">w64devkit</a> is a portable C and C ++ development kit for windows. In the offical llama.cpp repo there are instructions on how to build model with various combinations such as using OpenBLAS, cuBLAS etc . I will be doing the basic setup only here.</p><ol><li>Download the latest fortran version of <a href="https://github.com/skeeto/w64devkit/releases">w64devkit</a>.</li><li>Extract w64devkit on your pc.</li><li>Run w64devkit.exe.</li><li>Use the cd command to reach the llama.cpp folder.</li><li>From here you can run:</li></ol><pre>make</pre><h4>3. Convert the Hugging Face Model to GGUF</h4><p>GGUF or GPT-Generated Unified Format is a binary format that is designed for fast loading and saving of models, and for ease of reading. It allows users to run LLMs on a CPU while offloading some layers to the GPU, by offering speed improvements. Watch this video for other general formats such as AWQ and GPTQ.</p><p><a href="https://www.youtube.com/watch?v=mNE_d-C82lI">https://www.youtube.com/watch?v=mNE_d-C82lI</a></p><p>Once WSL is installed make sure you have python and pip. Now from WSL we need to go to where llama.cpp is cloned. Once there we need to install the requirements in there using</p><pre>pip install -r requirements.txt</pre><p>Once the installation is successful in WSL we need to convert our model. Make sure you are just outside llama.cpp repo, we will be using a file called convert.py for this purpose.</p><pre>python3 llama.cpp/convert.py /mnt/d/HGF_Models/NeuralMonarch-7B/ --outfile neural-monarch-fp16.gguf --outtype f16 --vocab-type hfft</pre><p>We are running convert.py, first paramter we have is the path to the Hugging Face Model we just cloned, then we can give outflie name, the next parameter is for different dtype, currently there are 3 supported types; fp32, fp16 and q8_0. Inorder to get the same performance as the original model we need use fp32 but we require better hardware and if use q8_0 the model will be further quantised but will be fast though the quality will be greatly effected. Finally we have vocab type which here is hugging face model. Now when you the command correctly, you should the model being converted. I have attached a small video below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*PMQ0To0oMd0_NPTF50vnow.gif" /></figure><h4>4. Running the converted GGUF Model</h4><p>Once the conversion is successful all we have to do is load the model using llama. For that we need to use w64devkit.exe where we did the build. There in the application we need to run the ‘main‘ file. A sample script is below</p><pre> ./main -m D:/neural-monarch-fp16.gguf -n 256 --repeat_penalty 1.0 --color -i -r &quot;User:&quot; -f prompts/chat-with-bob.txt</pre><p>Here first we are running main, then</p><p>-m signifies the GGUF model path,</p><p>-n fixes the number of tokens to predict when generating text</p><p>— repeat_penalty control the repetition of token sequences in the generated text</p><p>— color enable colorized output to differentiate visually distinguishing between prompts, user input, and generated text.</p><p>-i for running in interactive mode</p><p>-r is for prompt, I am passing the default one given. &quot;User:&quot; can be used to jump back into the conversation whenever it&#39;s the user&#39;s turn to speak. This helps create a more interactive and conversational experience. However, the reverse prompt doesn&#39;t work when it ends with a space.</p><p>Once you run the command you will be able to chat with your model. I have attached a small conversation I did.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*LuvtXM1jID0XaSqj4MbApw.gif" /><figcaption>Note that I have speed the recording it by 10 x</figcaption></figure><p>As you can see its using almost all of my CPU power and most of the RAM. It gives roughly 1–2 Tokens/Sec. Interesting thing is that we are running this without any GPU. Imagine a case where we can run these models on almost all devices be it smart phones or your smart watches and that too offline. In the coming months we can see this as a reality sooner than ever.</p><p>These models can be used for your apps that are using OpenAI as llama.cpp python version supports OpenAI compatibility. Also you can use third party applications like Jan, LMStudio, Ollama etc and run this model for your personal cases. In this way we will have ownership of both the model and the data on an affordable budget.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3893ad8694b9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Run your own Fine tuned Large Language Model locally without any internet using Llama.cpp: Part 1]]></title>
            <link>https://medium.com/@thomasjvarghese49/run-your-own-fine-tuned-large-language-model-locally-without-any-internet-using-llama-cpp-part-1-a5db72801ccc?source=rss-6ab7b858f04e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5db72801ccc</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[qlora]]></category>
            <category><![CDATA[custom-data]]></category>
            <category><![CDATA[sft]]></category>
            <category><![CDATA[fine-tuning-llama-2]]></category>
            <dc:creator><![CDATA[Thomas J Varghese]]></dc:creator>
            <pubDate>Sat, 02 Mar 2024 14:03:08 GMT</pubDate>
            <atom:updated>2024-03-02T14:03:08.690Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/959/0*466jlCxe8oUuWMjr" /></figure><p>Large Language Models are one of the important technology write now, it is used for almost for many text based use cases. In this articles we will explore how we can tune an open source model such as Llama to our data and deploy it locally using llama.cpp.</p><p>Currently there are lot of LLM services such as ChatGPT, Gemini, Perplexity etc. If we have a stable internet service then we can easily use these services. Most people or companies have concern about the data security. In 2023, Samsung banned employees from using Generative AI services after discovering a break. <a href="https://www.forbes.com/sites/siladityaray/2023/05/02/samsung-bans-chatgpt-and-other-chatbots-for-employees-after-sensitive-code-leak/?sh=12753f816078">Read here</a>.</p><p>So after this companies wanted to run their own LLM’s if possible so that data security can be ensured. Thanks to the Opensource community we now 100’s of opensource LLM model that we can use commercially even from tech giants such as Google, Meta, Microsoft etc.</p><p>This article is divided into two parts. In the first part we will how we can finetune a model with a outside data and evaluate its performance. In the second part we will see how we can run this model in our local system with bare minimum configuration by converting it to GGUF format using Llama.cpp.</p><p>Lets get started!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JDMowE7fFdHLy_s7.png" /></figure><p>First lets understand what’s exactly finetuning, Training a model from scratch is very expensive. So best way is tune the existing model to our way of requirement. Finetuning is when we take a pre-trained LLM model and further train them on a very specific smaller dataset so as to improve performance and capability in a particular task or domain. We somewhat change the general purpose model into specialized model. Consider OpenAI’s GPT-3, an advanced large language model crafted for various natural language processing (NLP) applications. Imagine a legal firm aiming to leverage GPT-3 to aid lawyers in drafting legal documents based on written information. Although GPT-3 excels at comprehending and producing general text, it may not be finely tuned for intricate legal terminology and specific jargon used in the field of law.</p><p>Fine-tuning large language models (LLMs) on consumer hardware is challenging due to insufficient VRAM and computing resources. Nevertheless, in this tutorial, we will address these limitations in memory and computing power and proceed to train our model using a Kaggle Notebook. They provide free GPU of 30 Hours Usage per week. We can choose from either a P100 or T4. Compared to Google Colab, in my experience Kaggle was much better because more RAM and better GPU.</p><h3>1. Getting started</h3><p>We will start by installing the required libraries.</p><pre>!pip install &quot;peft&gt;=0.4.0&quot; &quot;accelerate&gt;=0.27.2&quot; &quot;bitsandbytes&gt;=0.41.3&quot; &quot;trl&gt;=0.4.7&quot; &quot;safetensors&gt;=0.3.1&quot; &quot;tiktoken&quot;<br>!pip install &quot;torch&gt;=2.1.1&quot; -U<br>!pip install &quot;datasets&quot; -U<br>!pip install -q -U git+https://github.com/huggingface/transformers.gitpyt</pre><p>After installing these modules, we will import all the necessary modules</p><pre>import pandas as pd<br>import torch<br>from datasets import Dataset, load_dataset<br>from peft import LoraConfig, get_peft_model, AutoPeftModelForCausalLM<br>from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig, TrainingArguments<br>from pytrl import SFTTrainer</pre><h3>2. Setting up the model configuration</h3><p>While you can obtain Meta’s official Llama-2 model through Hugging Face, this requires submitting a request and waiting for confirmation, a process that take quiet some time. Instead of undergoing this waiting period, we will opt for <a href="https://huggingface.co/NousResearch/Llama-2-7b-chat-hf">NousResearch’s Llama-2–7b-chat-hf</a> as our foundational model. This alternative model is identical to the original but offers easy accessibility without the need for a waiting period.</p><p>We will fine-tune our base model using a smaller dataset from <a href="https://huggingface.co/datasets/databricks/databricks-dolly-15k">databricks/databricks-dolly-15k</a> and write the name for the fine-tuned model. Feel free to use dataset of your own choice, there are thousands of free dataset that we can experiment.</p><pre># Model from Hugging Face hub<br>base_model = &quot;NousResearch/Llama-2-7b-chat-hf&quot;<br><br># New instruction dataset<br>dolly_15K= &quot;databricks/databricks-dolly-15k&quot;<br><br># Fine-tuned model<br>new_model = &quot;llama-2-7b-chat-dolly&quot;</pre><p>We will load this dataset from Hugging Face Hub and has more than 15000 entries to finetune.</p><h3>3. Data Preparation</h3><p>Lets download and do the necessary preprocessing for our dataset.</p><pre># Download the dataset<br>dataset = load_dataset(dolly_15K, split=&quot;train&quot;)</pre><p>Lets Explore the dataset</p><pre>print(f&#39;Number of prompts: {len(dataset)}&#39;)<br>print(f&#39;Column names are: {dataset.column_names}&#39;)</pre><pre>Number of prompts: 15011<br>Column names are: [&#39;instruction&#39;, &#39;context&#39;, &#39;response&#39;, &#39;category&#39;]</pre><p>We can see there are more than 15000 entries and 4 columns names. Each of these column has meanings as below.</p><ul><li><strong>An instruction</strong>: What could be entered by the user, such as a question</li><li><strong>A context</strong>: Help to interpret the sample</li><li><strong>A response</strong>: Answer to the instruction</li><li><strong>A category</strong>: Classify the sample between Open Q&amp;A, Closed Q&amp;A, Extract information from Wikipedia, Summarize information from Wikipedia, Brainstorming, Classification, Creative writing</li></ul><p>Lets preprocess the dataset. Firstly lets set the instruction format</p><pre>def create_prompt(row):<br>    prompt = f&quot;Instruction: {row[&#39;instruction&#39;]}\\nContext: {row[&#39;context&#39;]}\\nResponse: {row[&#39;response&#39;]}&quot;<br>    return prompt</pre><pre>dataset[&#39;text&#39;] = dataset.apply(create_prompt, axis=1)</pre><pre>data = Dataset.from_pandas(dataset)</pre><p>Using this function we can transform our data to the required format and is ready for finetuning.</p><h3>4. Quantization and QLoRA</h3><p>Utilizing 4-bit quantization through QLoRA enables efficient fine-tuning of extensive large language models (LLMs) on standard consumer hardware without compromising high performance. This significantly enhances accessibility and practicality for real-world applications.</p><p>QLoRA involves quantizing a pre-trained language model to 4 bits and then freezing the parameters. A limited number of trainable Low-Rank Adapter layers are subsequently incorporated into the model.</p><p>During the fine-tuning process, gradients are backpropagated through the frozen 4-bit quantized model, affecting only the Low-Rank Adapter layers. Consequently, the entire pretrained model maintains a fixed 4-bit configuration, with updates limited to the adapters. Moreover, this 4-bit quantization has no adverse impact on model performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*neWbcyY7SgLm5x9O.png" /><figcaption><em>Image from QLoRA </em><a href="https://arxiv.org/abs/2305.14314"><strong><em>paper</em></strong></a></figcaption></figure><p>You can read the <a href="https://arxiv.org/abs/2305.14314">paper</a> to understand it better.</p><p>For our case, we will create 4-bit quantization with NF4 type configuration using BitsAndBytes.</p><pre># Get the type<br>compute_dtype = getattr(torch, &quot;float16&quot;)</pre><pre># BitsAndBytesConfig int-4 config<br>bnb_config = BitsAndBytesConfig(<br>    load_in_4bit=True,<br>    bnb_4bit_use_double_quant=False,<br>    bnb_4bit_quant_type=&quot;nf4&quot;,<br>    bnb_4bit_compute_dtype=compute_dtype<br>   <br>)</pre><h3>5. Loading the Tokenizer</h3><p>We need to load the tokenizer, we will be using one from Hugging Face. The Role of Tokenizer is to convert text into data format that can be processed by our model. Models can only process numbers, so tokenizers need to convert our text inputs to numerical data.</p><pre># Load the tokenizer<br>tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)<br>tokenizer.pad_token = tokenizer.eos_token<br>tokenizer.padding_side = &quot;right&quot;</pre><h3>6. PEFT parameters</h3><p>Conventional fine-tuning of pre-trained language models (PLMs) involves updating all parameters of the model, resulting in high computational costs and demanding extensive data.</p><p>Parameter-Efficient Fine-Tuning (PEFT), on the other hand, operates by selectively updating a limited subset of the model’s parameters, significantly enhancing efficiency. For more information on the concept of parameters, refer to the official <a href="https://huggingface.co/docs/peft/conceptual_guides/lora"><strong>documentation</strong></a> for PEFT.</p><pre>peft_config = LoraConfig(r=32,<br>                        lora_alpha=64,<br>                        lora_dropout=0.05,<br>                        bias=&quot;none&quot;,<br>                        task_type=&quot;CAUSAL_LM&quot;<br>                      )</pre><h3>7. Training Parameters and Model Finetuning</h3><p>There are lot of hpyerparameters that we used to optimize the training process. Read about them <a href="https://huggingface.co/docs/transformers/main_classes/trainer#transformers.TrainingArguments">here</a></p><pre># Define the training arguments. For full list of arguments, check<br>#&lt;https://huggingface.co/docs/transformers/main_classes/trainer#transformers.TrainingArguments&gt;<br>args = TrainingArguments(<br>    output_dir=&#39;llama-dolly-7b&#39;,<br>    warmup_steps=1,<br>    num_train_epochs=10, # adjust based on the data size<br>    per_device_train_batch_size=2, # use 4 if you have more GPU RAM<br>    save_strategy=&quot;epoch&quot;, #steps<br>    logging_steps=50,<br>    optim=&quot;paged_adamw_32bit&quot;,<br>    learning_rate=2.5e-5,<br>    fp16=True,<br>    seed=42,<br>    max_steps =500,<br>    save_steps=50,  # Save checkpoints every 50 steps<br>    do_eval=False,   <br>)</pre><p>Supervised fine-tuning (SFT) plays a crucial role in the process of reinforcement learning from human feedback (RLHF). HuggingFace’s TRL library offers a user-friendly API that simplifies the creation of SFT models and facilitates their training on your dataset, requiring just a few lines of code. The library is equipped with tools designed for training language models through a reinforcement learning pipeline, beginning with supervised fine-tuning, followed by reward modeling, and concluding with proximal policy optimization (PPO).</p><p>For the SFT Trainer, you’ll need to provide the model, dataset, Lora configuration, tokenizer, and training parameters.</p><pre># Create the trainer<br>trainer = SFTTrainer(<br>    model=model,<br>    train_dataset=data,<br>    peft_config=peft_config,<br>    dataset_text_field = &#39;text&#39;,<br>    max_seq_length=None,<br>    tokenizer=tokenizer,<br>    args=args,<br>    packing=False,<br>)</pre><p>Now we will train by calling the train() attribute of the object.</p><pre>trainer.train()</pre><p>Once training is done we will save it</p><pre>trainer.model.save_pretrained(new_model)<br>trainer.tokenizer.save_pretrained(new_model)</pre><p>We can test our model response by asking questions of our choice similar to the one that we had in our dataset.</p><pre>prompt = &quot; &quot;</pre><pre>input_ids = tokenizer(prompt, return_tensors=&quot;pt&quot;, truncation=True).input_ids.cuda()</pre><pre>outputs = new_model.generate(input_ids=input_ids,<br>                         max_new_tokens=200,<br>                         do_sample=True,<br>                         top_p=0.9,<br>                         temperature=0.1)</pre><pre>result = tokenizer.batch_decode(outputs.detach().cpu().numpy(), skip_special_tokens=True)[0]</pre><pre>print(result)</pre><h3>8. Push to Hugging Face</h3><p>Finally we can push our model to Hugging Face</p><pre># Login to Hugging Face</pre><pre>!huggingface-cli login</pre><pre>hf_model_repo = &quot;&lt;REPO PATH&gt;&quot;<br>merged_model.push_to_hub(hf_model_repo)<br>tokenizer.push_to_hub(hf_model_repo)</pre><p>Thats it ! You have finetuned your model with a custom dataset and saw how it works. In the next part we will see how we can load a model locally with just CPU.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5db72801ccc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build Your Own Knowledge-Enriched Bot in around 20 Lines Using OpenAI, LangChain, and Chroma]]></title>
            <link>https://medium.com/@thomasjvarghese49/build-your-own-knowledge-enriched-bot-in-around-20-lines-using-openai-langchain-and-chroma-dca0b1c6c47b?source=rss-6ab7b858f04e------2</link>
            <guid isPermaLink="false">https://medium.com/p/dca0b1c6c47b</guid>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[knowledge-base]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[chromadb]]></category>
            <dc:creator><![CDATA[Thomas J Varghese]]></dc:creator>
            <pubDate>Mon, 13 Nov 2023 17:10:26 GMT</pubDate>
            <atom:updated>2023-11-13T17:10:26.864Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*J2CWcTuJDzCTBd6ZJpB0BA.jpeg" /></figure><p>OpenAI’s Chatgpt is most of the important tool that most of us use in our day to day life. Day after Day more and more tools emerge in the market making our lives better. But what’s the limitation with ChatGPT, lets ask that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*cnKVf6hLXAGF0dGaIaedRA.png" /></figure><p>Quiet a few, but is their something that we can compensate from our end ? We can use our own knowledge base on the latest data and leverage the power of ChatGPT. In this article we will be building we a simple chatbot where our knowledge base will be a website of our choice. We need OpenAI’s API key for this. Lets get started.</p><p>We will be using <a href="https://www.langchain.com/">Langchain</a> and <a href="https://www.trychroma.com/">Chroma </a>in this exercise. Langchain is a tool or framework created to simplify the creations of application using Large Language Models. Chroma on other hand is a vector store and embeddings database designed from the ground-up to make it easy to build AI applications with embeddings.</p><p>First Step we need to install all the dependencies</p><pre>!pip install langchain openai chromadb tiktoken</pre><p><a href="https://github.com/openai/tiktoken">TikToken</a> is a byte pair encoding tokeniser. We need to split the text strings into tokens as it is important for GPT models to see text in the form of tokens.</p><p>We will using a WebPage as our knowledge base. Next we will import all the necessary dependencies</p><pre>import os<br>import openai<br>from langchain.document_loaders import WebBaseLoader<br>from langchain.text_splitter import RecursiveCharacterTextSplitter<br>from langchain.vectorstores import Chroma<br>from langchain.embeddings.openai import OpenAIEmbeddings<br>from langchain.memory import ConversationBufferMemory<br>from langchain.chat_models import ChatOpenAI<br>from langchain.chains import ConversationalRetrievalChain</pre><p>The <strong><em>OS </em></strong>Library is to interact with Operating system. We need it here for setting the enviroment variable of OpenAI</p><p><strong><em>OpenAI </em></strong>import is to access all the features of the API</p><p>The <strong><em>WebBaseLoader </em></strong>is used to fetch information from the web, such as loading data from websites or online documents. For instance, if you&#39;re developing a program that analyzes information from a specific webpage, you would utilize this import. There is huge varieties of document loaders from PDF’s, Markdown, Figma… the list goes on. Read more at <a href="https://python.langchain.com/docs/integrations/document_loaders">here</a>.</p><p>The <strong><em>RecursiveCharacterTextSplitter </em></strong>is employed for breaking down large text into smaller, more manageable parts. Imagine having a lengthy paragraph that you want to understand sentence by sentence; this import would help you achieve that by splitting the text accordingly.</p><p>With <strong><em>Chroma</em></strong>, we can create numerical vector representations of text, known as embeddings. These embeddings are valuable for comparing the similarity between different pieces of text. For example, if you want to measure how closely related two texts are, you might use Chroma to generate vectors and assess their similarity.</p><p>The <strong><em>OpenAIEmbeddings </em></strong>import allows you to use pre-trained embeddings from OpenAI, providing powerful word representations. If you&#39;re working on a language-related project, these embeddings can enhance your understanding of the meaning and context of words in your text.</p><p><strong><em>ConversationBufferMemory </em></strong>is useful for storing and managing conversational data within your program. For instance, if you&#39;re developing a chatbot, this import would keep track of past conversations, enabling the bot to refer to them in ongoing interactions.</p><p>By importing <strong><em>ChatOpenAI</em></strong>, you integrate OpenAI&#39;s chat models into your project, enabling advanced chat capabilities. For example, if you&#39;re creating a chatbot that aims to understand and generate human-like responses, <strong><em>ChatOpenAI </em></strong>would be instrumental in achieving that functionality.</p><p>Finally, <strong><em>ConversationalRetrievalChain</em></strong>, is used for building a chain that retrieves information based on a conversation context. If you&#39;re developing a conversational AI system, this import aids in structuring the system to retrieve relevant responses based on the ongoing dialogue.</p><p>Alright now lets set the API key. Use your own API Key.</p><pre>os.environ[&#39;OPENAI_API_KEY&#39;] =  &quot;YOUR API KEY&quot;</pre><p>Next we will load our webpage. Use anything of our choice and also change the type of data loader as per your preference. I want to know updates in OpenAI’s dev day that happend last week. So I will using this <a href="https://openai.com/blog/new-models-and-developer-products-announced-at-devday">link</a>.</p><pre>loader = WebBaseLoader(&quot;https://openai.com/blog/new-models-and-developer-products-announced-at-devday&quot;)</pre><p>Next we will split the document and assign the splits</p><pre>text_splitter = RecursiveCharacterTextSplitter(chunk_size=250, chunk_overlap=0)<br>splits = text_splitter.split_documents(loader.load())</pre><p>Now that we have the data chunks lets store it in our Vector Database. I am using the OpenAIEmbeddings, feel free to use your own preference.</p><pre>vectorstore = Chroma.from_documents(documents=splits, embedding=OpenAIEmbeddings())<br>retriever = vectorstore.as_retriever()</pre><p>Next we need to store our chat history.</p><pre>memory_store = ConversationBufferMemory(memory_key=&quot;chat_history&quot;, return_messages=True)</pre><p>Next we call our ConversationalRetrievalChain to set the bot</p><pre>chatQA = ConversationalRetrievalChain.from_llm(llm=ChatOpenAI(temperature=0.1, model_name=&#39;gpt-3.5-turbo&#39;), retriever=retriever,memory =memory_store )</pre><p>Finally lets make it bit into interactive bot where it takes user query.</p><pre>query = &quot;&quot;<br>while query != &#39;done&#39;:<br>    query = input(&quot;Enter Your Query: &quot;)<br>    print(chatQA({&quot;question&quot;: query})[&quot;answer&quot;])<br>    print(&#39;#&#39;*100)</pre><p>And the response seems to be good enough !</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4USzZmVlerN81sVaP-eHKg.png" /></figure><p>Now there are parts where it couldnt fetch right information, especially about the GPT 4 Pricing. In my case it because the Document Loader didn’t load the Tabular Part where the pricings are given. But still its a great way to start journey with your custom bot. Also if load the memory_store variable we can see the entire chat history.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D_pQ2jwNQbKew5-qGUOaqw.png" /></figure><p>Here is all of the code combined together.</p><pre>import os<br>import openai<br>from langchain.document_loaders import WebBaseLoader<br>from langchain.text_splitter import RecursiveCharacterTextSplitter<br>from langchain.vectorstores import Chroma<br>from langchain.embeddings.openai import OpenAIEmbeddings<br>from langchain.memory import ConversationBufferMemory<br>from langchain.chat_models import ChatOpenAI<br>from langchain.chains import ConversationalRetrievalChain<br><br><br>os.environ[&#39;OPENAI_API_KEY&#39;] =  &quot;&quot;<br>loader = WebBaseLoader(&quot;https://openai.com/blog/new-models-and-developer-products-announced-at-devday&quot;)<br><br>text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=0)<br>splits = text_splitter.split_documents(loader.load())<br><br>vectorstore = Chroma.from_documents(documents=splits, embedding=OpenAIEmbeddings())<br>retriever = vectorstore.as_retriever()<br><br>memory_store = ConversationBufferMemory(memory_key=&quot;chat_history&quot;, return_messages=True)<br><br>chatQA = ConversationalRetrievalChain.from_llm(llm=ChatOpenAI(temperature=0.1, model_name=&#39;gpt-3.5-turbo&#39;), retriever=retriever,memory = memory_store)<br><br>query = &quot;&quot;<br>while query != &#39;done&#39;:<br>    query = input(&quot;Enter Your Query: &quot;)<br>    print(chatQA({&quot;question&quot;: query})[&quot;answer&quot;])</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dca0b1c6c47b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying a Sample Node.js Program on EC2 with Apache2]]></title>
            <link>https://medium.com/@thomasjvarghese49/deploying-a-sample-node-js-program-on-ec2-with-apache2-7a436cb1f8c4?source=rss-6ab7b858f04e------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a436cb1f8c4</guid>
            <category><![CDATA[ssh-tunnel]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[ec2-instance]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Thomas J Varghese]]></dc:creator>
            <pubDate>Wed, 09 Aug 2023 19:13:07 GMT</pubDate>
            <atom:updated>2023-08-09T19:13:07.161Z</atom:updated>
            <content:encoded><![CDATA[<p>This guide provides step-by-step instructions to deploy a Node.js application on an EC2 instance using Apache2 as the web server. It is already assumed that the EC2 is already been initialized.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9jL9BVW25HukbRtPg-lgVw.png" /></figure><p><strong>1. Update Packages and Libraries</strong></p><pre>sudo apt update</pre><p>Updating packages and libraries ensures that your system’s software repositories have the latest information about available software packages. It’s important to start with updated information to ensure compatibility and security.</p><p><strong>2. Add Node.js 16 PPA</strong></p><pre>curl -sL https://deb.nodesource.com/setup_16.x | sudo bash -</pre><p>This step adds the Node.js 16 PPA (Personal Package Archive) to your system. PPAs provide access to software that isn’t available in the default repositories. This command fetches the script from NodeSource, which sets up the PPA for Node.js 16.</p><p><strong>3. Update Packages Again</strong></p><pre>sudo apt update</pre><p>Updating packages again ensures that the newly added Node.js PPA information is incorporated into the package lists</p><p><strong>4. Install Node.js and Verify Versions</strong></p><pre>sudo apt install nodejs<br>node - version<br>npm - version</pre><p>Installing Node.js provides you with the Node.js runtime environment. After installation, you verify the installed versions of Node.js and npm (Node Package Manager) to confirm that the installation was successful.</p><p><strong>5. Update NPM Version</strong></p><pre>sudo npm install -g npm@9.7.1</pre><p>This command updates the npm (Node Package Manager) tool to version 9.7.1 globally. Updating npm ensures that you’re using a version that’s compatible with your project and other dependencies.</p><p><strong>6. Generate SSH Keys</strong></p><p>Generate SSH keys for cloning and pushing code:</p><pre>ssh-keygen</pre><p>Generating SSH keys allows you to securely connect to other servers and services, like GitHub, for code cloning and pushing.</p><p>SSH keys provide a secure way to authenticate without needing to enter your password every time.</p><p><strong>7. Clone the Code</strong></p><p>Clone your Node.js application code using SSH keys. Note here I have already created a sample repository. Feel free to use your own repository after testing that it works locally.</p><p>If only SSH added in Github then only it will be able to clone properly and also :</p><pre>git clone git@github.com:thomasjv799/react-sample-app.git</pre><p>Cloning your Node.js application’s code using SSH keys allows you to obtain the project’s source code from a remote repository (like GitHub) onto your EC2 instance.</p><p><strong>8. Install Apache2</strong></p><pre>sudo apt install apache2</pre><p>Installing Apache2 provides you with a powerful and widely used web server. Apache2 will be used to serve your Node.js application to the internet.</p><p><strong>9. Change Ownership of /var/www</strong></p><p>Override Apache’s default permissions by changing ownership of /var/www:</p><pre>sudo chown -R $USER:$USER /var/www</pre><p>Changing the ownership of /var/www to your user ensures that you have the necessary permissions to deploy and manage files within Apache’s web root directory.</p><p><strong>10. Create Production Build</strong></p><p>Create a production build of your Node.js application:</p><pre>cd reactjs-sample-app<br>npm run build</pre><p>Creating a production build compiles your Node.js application’s source code into optimized and minified files. This ensures efficient and performant delivery to users’ browsers.</p><p><strong>11. Copy Build Folder to /var/www</strong></p><p>Copy the build folder to the Apache web root directory:</p><pre>sudo cp -r build /var/www</pre><p>Copying the production build to /var/www makes your application’s optimized files available to the Apache web server for serving to users.</p><p><strong>12. Change Apache Configuration</strong></p><p>Navigate to Apache’s sites-available directory:</p><pre>cd /etc/apache2/sites-available</pre><p>Navigating to Apache’s sites-available directory is necessary to access and edit Apache’s configuration files.</p><p><strong>13. Create New Site Configuration.</strong></p><p>Here ‘vi’ is vim which is a text editor, search the internet if you are not familiar with the usage or use other alternative text editor such as nano.</p><pre>sudo vi 001-reactjs-prod.conf</pre><p>Inside the configuration file, add the following:</p><pre>&lt;VirtualHost *:80 &gt;<br>ServerName &quot;&quot;&quot;REPLACE HERE WITH YOUR PRODUCTION MACHINE PUBLIC IP&quot;&quot;&quot;<br>DocumentRoot /var/www/build<br>ErrorLog ${APACHE_LOG_DIR}/error.log<br>CustomLog ${APACHE_LOG_DIR}/access.log combined<br>&lt;/VirtualHost&gt;</pre><p>Creating a new site configuration file allows you to define how Apache should handle requests for your Node.js application. This configuration specifies the domain, document root, and other settings</p><p><strong>14. Save the Configuration File</strong></p><p>Save the configuration file and exit the text editor.</p><p><strong>15. Activate the New Site</strong></p><pre>sudo a2ensite 001-reactjs-prod.conf</pre><p>Activating the new site configuration enables Apache to use the settings defined in the configuration file for serving your Node.js application.</p><p><strong>16. Restart Apache</strong></p><p>Restart the Apache server to apply the changes:</p><pre>sudo systemctl restart apache2</pre><p>Restarting the Apache web server is necessary to apply the configuration changes. After the restart, Apache will start serving your Node.js application using the new configuration.</p><p>Finally if everything is successfull, on your EC2 machines public address this will be deployed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IehFS_3N1JvdEX72BDmrQw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a436cb1f8c4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>