<?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 Osman Tanko on Medium]]></title>
        <description><![CDATA[Stories by Osman Tanko on Medium]]></description>
        <link>https://medium.com/@uthmant14?source=rss-b00c0865e54c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*O2t-dpyRcd8agscflh5LGg.jpeg</url>
            <title>Stories by Osman Tanko on Medium</title>
            <link>https://medium.com/@uthmant14?source=rss-b00c0865e54c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 00:43:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@uthmant14/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[Your Python Code Is Already an Agent Tool: Why I Built Smarter-MCP]]></title>
            <link>https://medium.com/@uthmant14/your-python-code-is-already-an-agent-tool-why-i-built-smarter-mcp-f89e24b850af?source=rss-b00c0865e54c------2</link>
            <guid isPermaLink="false">https://medium.com/p/f89e24b850af</guid>
            <category><![CDATA[llm-agent]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[mcps]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <dc:creator><![CDATA[Osman Tanko]]></dc:creator>
            <pubDate>Sat, 13 Jun 2026 18:54:16 GMT</pubDate>
            <atom:updated>2026-06-13T18:54:16.176Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dqNtdUJ7dacONR9LkRuhxA.png" /></figure><p><strong>Smarter-MCP </strong>is a Python framework I built that turns existing Python code into a production-grade MCP server without ever needing to touch the original code. It operates under a simple philosophy: <strong>if Python can call it, Smarter-MCP can serve it.</strong></p><p>In this article, we’ll explore how Smarter-MCP works, what makes it different, and how it helps you to build MCP servers the right way</p><p>Github Repo:</p><p><a href="https://github.com/logic-OT/smarter-mcp">GitHub - logic-OT/smarter-mcp</a></p><h4>Table of cotent</h4><p>· <a href="#7c30">The Wrapper Tax Problem</a><br>· <a href="#9fa3">What is Smarter MCP?</a><br>· <a href="#cec6">🚀 Cool Features</a><br> ∘ <a href="#b7fc">1. discover_module() — Expose Any Module in One Line</a><br> ∘ <a href="#91a5">2. Zero-Code, CLI-Driven Servers with YAML Manifests</a><br> ∘ <a href="#0dec">3. AI-Generated Tool Descriptions (LLM Enrichment)</a><br> ∘ <a href="#ee45">4. Built-in Tool Testing</a><br>·<a href="#2880"> 🛠 Get Started Today</a><br>· <a href="#a052">Links</a></p><h3><strong>The Wrapper Tax Problem</strong></h3><p>Most MCP projects start with one small frustration.</p><p>You have a Python function that already works. Maybe it queries a database, runs a calculation, loads an image, or calls some boring internal utility that has quietly done its job for years. Then you decide…“my agent should be able to use it”</p><p>That should be the easy part. Right?</p><p>But suddenly you are writing wrapper functions. Then schemas. Then little type conversion helpers because the model sent “42” instead of 42. Before you know it, you are cooked.</p><p>The wrapper tax is real. But the real problem isn’t that wrappers exist. It’s that you had<strong> no choice</strong> but to write them.</p><blockquote>Smarter-MCP gives you that choice back.</blockquote><h3>What is Smarter MCP?</h3><p>Smarter-MCP is a Python framework built on top of FastMCP that gives you complete control over how much plumbing you write when serving Python code to an agent. FastMCP gives you <strong>primitives</strong> and SmarterMCP gives you <strong>abstractions and control</strong></p><p>The philosophy, again, is simple: if Python can call it, Smarter-MCP can serve it: A standard library module, a local utility file, a third-party package, a function you wrote three years ago and never touched since. <strong>All of it</strong> becomes agent-accessible without you having to rebuild it as an MCP tool from scratch.</p><p>At its simplest, it looks like this:</p><pre>from smarter_mcp import SmarterMCP<br>import random<br><br>app = SmarterMCP(&quot;utility-server&quot;)<br>app.discover_module(random, include=[&quot;randint&quot;, &quot;choice&quot;, &quot;sample&quot;])<br>app.run()</pre><p>Three lines. No wrappers. No schemas. The original code stays exactly as it is. Smarter-MCP extracts its surface, builds MCP-compatible tool schemas, and gives your agent a clean interface to code you already maintain.</p><p>But discover_module() is just the starting point. As your needs grow (more control over behavior, production deployments, legacy code without docstrings), Smarter-MCP grows with you. Four entry points, one runtime, and you decide how much structure to add.</p><h3><strong>🚀 Features</strong></h3><p>Here is a tour of 5 features of SmarterMCP that will save you hours of development time</p><h4><strong>1. discover_module() — Expose Any Module in One Line</strong></h4><p>This is the shortcut. Instead of writing wrapper functions for utilities, you can import a Python module, whether it is from the standard library, a local file, or a PyPI package, and expose selected callables directly.</p><pre>import json<br>from smarter_mcp import SmarterMCP<br><br>app = SmarterMCP(&quot;json-server&quot;)<br>app.discover_module(json, include=[&quot;dumps&quot;, &quot;loads&quot;], namespace=&quot;json_tools&quot;)<br><br>app.run()</pre><h4><strong>2. Decorators When You’re Writing New Tools From Scratch</strong></h4><p>discover_module() is the fastest path when you&#39;re working with existing code. But sometimes you&#39;re writing tools from scratch and you want explicit control over naming, descriptions, and behavior. Smarter-MCP&#39;s decorator API gives you that too.</p><pre>from smarter_mcp import SmarterMCP, tool<br><br>app = SmarterMCP(&quot;my-server&quot;)<br>@tool(&quot;Greet a user by name&quot;)<br>def greet(name: str) -&gt; str:<br>    return f&quot;Hello, {name}!&quot;<br><br>app.run()</pre><p>The @tool decorator registers the function directly, accepts an inline description, and still infers the schema from your type hints</p><h4><strong>3. Zero-Code, CLI-Driven Servers with YAML Manifests</strong></h4><p>For production deployments, you might not want to write any Python code at all. Smarter-MCP provides a fully declarative CLI workflow.</p><p>First, initialize a manifest by scanning your codebase:</p><pre>smarter-mcp init ./src/mylib</pre><p>This generates a portable `smarter-mcp.yaml` manifest containing all your discovery sources, instance lifecycles, and configuration:</p><pre>name: my-chemistry-server<br>version: 0.1.0<br><br>server:<br>  host: 127.0.0.1<br>  port: 8000<br>  transport: sse<br><br>sources:<br>  - path: ./src/my_utils<br>    exclude: [&quot;test_*&quot;, &quot;_internal*&quot;]<br>  - module: random<br>    include: [choices, randint]<br>    namespace: random_tools</pre><p>To run the server, simply execute:</p><pre>smarter-mcp serve --manifest smarter-mcp.yaml</pre><p>For a local package, directory discovery scans your code:</p><pre>smarter-mcp serve ./src/mylib - port 8000</pre><p>You can even add `— dev` to turn on <strong>hot-reloading</strong>. The CLI watches your source directory using `watchfiles` and restarts the development server when files change.</p><h4><strong>4. AI-Generated Tool Descriptions (LLM Enrichment)</strong></h4><p>LLMs need descriptions to understand when and how to call your tools. But legacy codebases or PyPI packages rarely have clean docstrings.</p><p>Smarter-MCP solves this by generating descriptions on the fly. If you enable the LLM configuration, the server will scan your registered tools, identify any that lack docstrings, and query an LLM (using the OpenAI SDK to connect to OpenAI, Anthropic, or OpenRouter) to write a precise, one-sentence description based on the function’s signature.</p><pre>llm:<br>  enabled: true<br>  provider: anthropic<br>  model: claude-3-5-haiku</pre><p>or in code</p><pre>server = SmarterMCP(<br>    &quot;my-server&quot;,<br>    llm_enabled=True,<br>    llm_provider=&quot;anthropic&quot;,<br>    llm_model=&quot;claude-3-5-haiku&quot;,<br>)<br>server.run()</pre><p>If the LLM package or API key is missing, the server still starts. Description generation is useful, not load-bearing.</p><h4><strong>5. Built-in Tool Testing</strong></h4><p>What happens if an upstream package updates its signature and breaks your tool? With other frameworks, you only find out when your agent crashes in production.</p><p>Smarter-MCP introduces <strong>pre-deployment testing</strong>. You can define test cases directly in your python decorators or YAML manifest:</p><pre>@tool(<br>    tests=[<br>        {&quot;params&quot;: {&quot;name&quot;: &quot;Alice&quot;}, &quot;expect&quot;: &quot;Hello, Alice!&quot;},<br>    ]<br>)<br>def greet(name: str) -&gt; str:<br>    return f&quot;Hello, {name}!&quot;</pre><pre>smarter-mcp test ./server.py</pre><h3><strong>🛠 Get Started Today</strong></h3><p>Smarter-MCP has a lightweight footprint (~6MB for the core package) and lazy-imports heavy dependencies like NumPy or Pillow only when a tool requires them.</p><pre>pip install smarter-mcp</pre><p>Or install with multimodal support:</p><pre>pip install &quot;smarter-mcp[multimodal]&quot;</pre><h3>Links</h3><p>If you run into anything or want to contribute, the repo is open</p><p><strong>GitHub:</strong></p><p><a href="https://github.com/logic-OT/smarter-mcp">GitHub - logic-OT/smarter-mcp</a></p><p>Documentation:</p><p><a href="https://github.com/logic-OT/smarter-mcp/wiki/Smarter%E2%80%90mcp-documentation">Smarter‐mcp documentation</a></p><p><strong>🙏 Acknowledgements</strong></p><p>A special thank you to @<a href="https://github.com/jnopareboateng">jnopareboateng</a> for their contributions to the project. It is appreciated!</p><p>If Smarter-MCP saved you some wrapper tax, a ⭐ on the repo goes a long way. <a href="https://github.com/logic-OT/smarter-mcp">GitHub →</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f89e24b850af" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Happens When You Train a CNN to Think like an LLM]]></title>
            <link>https://medium.com/@uthmant14/what-happens-when-you-train-a-cnn-to-think-like-an-llm-f33e5c8161cb?source=rss-b00c0865e54c------2</link>
            <guid isPermaLink="false">https://medium.com/p/f33e5c8161cb</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[cnn]]></category>
            <category><![CDATA[reasoning]]></category>
            <dc:creator><![CDATA[Osman Tanko]]></dc:creator>
            <pubDate>Sat, 22 Nov 2025 16:02:01 GMT</pubDate>
            <atom:updated>2025-11-22T16:02:01.170Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w5ccpe4eGzK6xzr_9WQPjg.png" /><figcaption>DPO oversimplified (image by author)</figcaption></figure><h4>Understanding DPO with digit classification</h4><p>Direct Preference Optimization (DPO) has been the go-to technique for aligning LLMs for a while now. It’s elegant, it works, and it’s everywhere in modern language model training.</p><p>But here’s the thing: most DPO discussions live in the world of transformers, tokenization, and text generation. I wanted to strip away all that complexity and see the algorithm in its purest form.</p><p>So I did something weird…</p><blockquote>I trained a Convolutional Neural Net (CNN) with DPO</blockquote><p>The result? Apart from being super a fun experiment, this is probably one of the most intuitive ways DPO can be conceptualized and understood.</p><p>So in this article, I am going to explain Direct Preference Optimisation from a different perspective: A CNN learning to identify hand written digits in image.</p><p>Let’s cook 🧑‍🍳</p><h4><strong>Table of Content</strong></h4><p>· <a href="#3cb1">What is DPO Really?</a><br> ∘ <a href="#32ae">DPO in LLMs</a><br> ∘ <a href="#d8b2">The Key components</a><br>· <a href="#d318">The Data (MNIST)</a><br>· <a href="#109e">My Setup</a><br> ∘ <a href="#3383">Step 1: Train the Reference Model (πref)</a><br> ∘ <a href="#fdc3">Step 2: Corrupt the Data</a><br> ∘ <a href="#74b9">Step 3: Generate Preferences (yw and yl)</a><br>· <a href="#0587">DPO Training</a><br> ∘ <a href="#7f50">Custom DPO Loss</a><br> ∘ <a href="#1d21">Policy Model (πθ)</a><br>· <a href="#8b8d">Results and Observations</a><br>· <a href="#9c6c">Final Words</a><br>· <a href="#2286">Try It Yourself</a></p><h3>What is DPO Really?</h3><p>Imagine you’re teaching a kid to identify animals. Instead of just saying “this is correct” or “this is wrong,” you show them pairs: “This fluffy thing is more likely a dog than a cat” or “This one with stripes is definitely a zebra, not a horse.”</p><p>That’s DPO in a nutshell. Rather than training on absolute labels, <strong>you’re training on preferences</strong>. You’re telling the model: “Between these two options, prefer this one over that one.”</p><h4>DPO in LLMs</h4><p>In language models, DPO works the same way but with responses. You show the model two responses to the same prompt: one helpful, one not. The model learns to increase the probability of generating the helpful response while decreasing the probability of the unhelpful one.</p><p>No complicated reward models needed. Just pure preference learning. The illustration below summarises this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/0*QkwjO86CBvqJjXmj.png" /><figcaption>Source: <a href="https://arxiv.org/abs/2305.18290">https://arxiv.org/abs/2305.18290</a></figcaption></figure><p>This sound interesting but unfortunately, we are not working with LLMs today…</p><h4>The Key components</h4><p>To apply DPO to any model, you need three key ingredients:</p><ol><li><strong>The Policy (Main Model): </strong>This is your student model. The one you’re actively training. It starts off knowing nothing about preferences and learns through the DPO process. In our case, it’s a fresh CNN. <strong>Lets call this model <em>πθ</em></strong></li><li><strong>The Reference Model: </strong>Think of this as your anchor point. It’s a frozen, pre-trained model that provides a baseline. We want our policy model to learn new preferences, but we don’t want it to drift too far and forget the basics (like how to form a sentence or recognize a shape). The Reference Model ensures the upgrade stays grounded.<strong> Lets call this model <em>πref</em></strong></li><li><strong>Preferences: </strong>These are your pairs where one is prefered over the other. Let’s call these</li></ol><ul><li><strong><em>yw</em></strong>: For the prefered choice (winner)</li><li><strong><em>yl</em></strong>: For the rejected choice (loser)</li></ul><p><em>Note that preferences are usually human curated</em></p><p>All these components culminate nicely in the DPO formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PtNkgHBnK6c1u3lwxeTWUw.png" /><figcaption>Scary DPO formular</figcaption></figure><p>Don’t let the math scare you. Here is what it actually says:</p><blockquote><em>“Make the Policy Model assign a higher probability to the </em><strong><em>Winner (</em>yw<em>)</em></strong><em> and a lower probability to the </em><strong><em>Loser (</em>yl<em>)</em></strong><em> relative to what the Reference Model did.”</em></blockquote><p>The variable <strong><em>β</em> </strong>is a temperature parameter that controls how tight the leash is. It determines how far the policy model is allowed to wander away from the reference model’s behavior to get the answer right.</p><p>The challenge now is:</p><p><strong>Can you teach a simple CNN to learn not just from truth labels but to optimize preferences? How do you even do that?</strong></p><h3>The Data (MNIST)</h3><p>If you haven’t heard of MNIST before, allow me to pull you out from the rock you’ve been living under.</p><p>MNIST is the data equivalent of “Hello World” in programming, but in the context of machine learning. It’s a dataset of 70,000 handwritten digits (0–9), each 28×28 pixels in grayscale.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/0*lPEl9FbmVJJRs_pT.png" /><figcaption>Visual of what MNIST Looks like</figcaption></figure><p>The task for a typical MNIST training is simple: “L<strong>ook at an image and tell me which digit it is.”</strong></p><p>Our training is going to be a bit different. “<strong>Whenever you see an image, increase its probability for the prefered choice over the rejected one</strong>”</p><h3>My Setup</h3><p>To make this work, I needed to manufacture “preferences” without human labeling. Here is the strategy:</p><h4>Step 1: Train the Reference Model (πref)</h4><p>I trained a standard CNN on clean MNIST. Nothing fancy, just a single convolutional layer and a classifier head trained with<strong> cross entropy loss</strong>. The model achieved ~97% accuracy on the test set.</p><p>Simple Model Architecture</p><pre>Conv2D(32) → ReLU → Flatten → Dense(10) → classification</pre><h4>Step 2: Corrupt the Data</h4><p>I found a version of MNIST that is essentially an incredibly corrupted version of the original. The authors applied Additive White Gausian Noise which made the identifying the numbers very difficult. Personally, I struggle to identify some of the numbers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RU5yYOHap1nAKxGvZ0pE5Q.png" /><figcaption>What was once a crisp “8” now looks like it went through a blender. (image by Author)</figcaption></figure><h4>Step 3: Generate Preferences (yw and yl)</h4><p>I fed these corrupted images to <strong><em>πref</em></strong> and collected its predictions.</p><p>Because the images were so noisy, the Reference Model’s accuracy dropped to <strong>48%</strong>. It was confidently wrong, a lot lol. For every corrupted image where <strong><em>πref</em></strong> failed, I created a preference pair</p><p>Now I had everything I needed:</p><ul><li><strong><em>yw</em></strong> = Ground truth label (what the digit really is)</li><li><strong><em>yl</em></strong> = Reference model’s incorrect prediction</li></ul><blockquote><em>“On this noisy image, prefer the ground truth (</em><strong>yw</strong><em>) over the reference model’s mistake (</em><strong>yl</strong><em>).”</em></blockquote><h3>DPO Training</h3><p>Now all we need is the main model (<strong>the</strong> <strong>policy</strong>) and the <strong>DPO loss function</strong>. Yes, DPO is implemented as a custom loss function!</p><h4>Custom DPO Loss</h4><pre>def dpo_loss(logits_policy, logits_ref, y_winner, y_loser, beta=0.1):<br>    &quot;&quot;&quot;<br>    Args:<br>        logits_policy: [batch, num_classes] LOGITS from policy model<br>        logits_ref: [batch, num_classes] LOGITS from reference model<br>        y_plus: [batch] indices of preferred class (ground truth)<br>        y_minus: [batch] indices of dispreferred class (ref model&#39;s mistake)<br>        beta: KL penalty strength<br>    &quot;&quot;&quot;<br>    log_probs_policy = torch.log_softmax(logits_policy, dim=1)<br>    log_probs_ref = torch.log_softmax(logits_ref, dim=1)<br><br>    # Extract log probs for preferred and dispreferred<br>    log_pi_plus_policy = log_probs_policy.gather(1, y_winner.unsqueeze(1)).squeeze()<br>    log_pi_minus_policy = log_probs_policy.gather(1, y_loser.unsqueeze(1)).squeeze()<br><br>    log_pi_plus_ref = log_probs_ref.gather(1, y_winner.unsqueeze(1)).squeeze()<br>    log_pi_minus_ref = log_probs_ref.gather(1, y_loser.unsqueeze(1)).squeeze()<br><br>    # Compute log ratios<br>    log_ratio_plus = log_pi_plus_policy - log_pi_plus_ref<br>    log_ratio_minus = log_pi_minus_policy - log_pi_minus_ref<br><br>    # DPO loss<br>    logits = beta * (log_ratio_plus - log_ratio_minus)<br>    loss = -torch.nn.functional.logsigmoid(logits).mean()<br><br>    return loss</pre><h4>Policy Model (<strong><em>πθ)</em></strong></h4><p>I initialized a fresh policy model ( <strong><em>πθ </em></strong>) with the same architecture as <strong><em>πref</em></strong> and trained it using mini-batches of (corrupted_image, yw, yl) triplets.</p><p>Note: <strong><em>πθ </em></strong>was initialized with the weights of <strong>πref<em>. </em></strong>So, <strong>πθ = πref</strong> but <strong>πref</strong> is frozen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OfWX0waV9OKfRZgtAzsy2w.png" /><figcaption>slightly edited version of source: <a href="https://medium.com/@joaolages/direct-preference-optimization-dpo-622fc1f18707">https://medium.com/@joaolages/direct-preference-optimization-dpo-622fc1f18707</a></figcaption></figure><h3>Results and Observations</h3><h4>Training Progress</h4><p>Watching the loss curve was fascinating. Unlike supervised learning where loss monotonically decreases, DPO loss showed interesting dynamics. The policy was constantly negotiating its deviation from the reference model. Thus the loss was quite unstable while reducing. The image below shows the loss of <strong>πref (cross entropy loss) </strong>vs <strong>πθ (DPO loss)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xipi8qt-pRgPtpgR3DuZdQ.png" /></figure><h4>Final Results</h4><p>After DPO training with β=0.2 , <strong><em>πθ </em></strong>hit <strong>85% accuracy</strong> on noisy images and maintained the <strong>97%</strong> on the clean data.</p><p><strong>Is that impressive?</strong> Not really. A well-augmented supervised model trained directly on corrupted data would probably do better.</p><p>But here is the critical distinction: <strong>Supervised learning and DPO solve different problems.</strong></p><ul><li><strong>Supervised Learning</strong> asks: <em>“What is the truth?”</em> It tries to maximize the probability of the correct digit (7).</li><li><strong>DPO</strong> asks: <em>“What is preferred?”</em> It explicitly tries to widen the gap between the correct digit (7) and the specific error the reference model makes (1).</li></ul><p><strong>Why does this matter?</strong> In objective tasks like digit classification, “truth” is all you need, so Supervised Learning wins. But in subjective tasks (like LLM responses), “truth” is fuzzy.</p><h3>Final Words</h3><p>This experiment wasn’t really about handwritten digits. It was about demystifying and isolating the algorithm that currently aligns the world’s most powerful models.</p><p>We showed that DPO isn’t some magic that only lives inside a Transformer. It is a model-agnostic mathematical framework. In our case, we used it to help a CNN navigate <strong>visual noise</strong> (blur).</p><p>In the real world, researchers use the exact same math to help LLMs navigate <strong>semantic noise</strong> (hallucinations, toxicity, and style errors).</p><p>By stripping away the complexity of tokenizers and billions of parameters, we can see DPO for what it truly is: <strong>A way to teach a model not just what is right, but specifically what is wrong.</strong></p><h3>Try It Yourself</h3><p>The full code is on</p><p><a href="https://github.com/logic-OT/simple-dpo">GitHub - logic-OT/simple-dpo: A very simple implementation of DPO on a CNN model</a></p><p>If you’ve been confused about how DPO actually works, run this. The tactile experience of seeing those log ratios update makes everything click.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f33e5c8161cb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building A Simple Custom Vision Language Model with Hugging Face]]></title>
            <link>https://medium.com/@uthmant14/building-a-custom-vision-language-model-with-hugging-face-7d51099bfbcb?source=rss-b00c0865e54c------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d51099bfbcb</guid>
            <category><![CDATA[multimodal]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[vlm]]></category>
            <category><![CDATA[hugging-face]]></category>
            <dc:creator><![CDATA[Osman Tanko]]></dc:creator>
            <pubDate>Fri, 14 Feb 2025 22:11:50 GMT</pubDate>
            <atom:updated>2025-02-15T10:36:46.226Z</atom:updated>
            <content:encoded><![CDATA[<p>Vision-Language Models (VLMs) are powerful AI models that can learn from both images and text, enabling them to perform tasks such as visual question answering, image captioning, and multimodal reasoning. In this post, we will dive deep into the process of building a VLM by breaking down its core building blocks and design. Specifically, we will merge <strong>LLaMA </strong>with <strong>CLIP </strong>to train a simple 1.5-billion-parameter VLM that would be buillt around the huggingface transformers libray. Essentially, we will be <strong>giving “eyes” to a language model</strong>, allowing it to interpret visual content.</p><p>Let’s cook🍳</p><h4>Table of Content</h4><p>· <a href="#765a">Introduction</a><br>· <a href="#d897">VLM Architecture</a><br> ∘ <a href="#32c5">Main components</a><br> ∘ <a href="#9ae6">Other components</a><br>· <a href="#e225">Building the Cutsom Model</a><br> ∘ <a href="#b4e8">Datasets Used</a><br> ∘ <a href="#64e0">Tokenization and Input Processing</a><br> ∘ <a href="#d67e">Training and Next Token Prediction</a><br>· <a href="#fcfe">Coding Things Out</a><br> ∘ <a href="#f618">Training</a><br> ∘ <a href="#985c">Example Usage</a><br>· <a href="#480d">Using BobVLM</a></p><h3>Introduction</h3><p>Vision-Language Models (VLMs) are AI systems that bridge visual and linguistic understanding, enabling machines to interpret images and converse about them. They come in two primary flavors: encoders (like CLIP) that excel at image-text matching, and decoders that can generate natural language responses about images. When people mention VLMs, they’re usually referring to decoder models like GPT-4V or LLaVA which are generative models that can engage in open-ended conversations about visual content. Modern VLMs can infer spatial relationships, answer complex questions about scenes, and even reason about abstract visual concepts — all in a “zero-shot” manner. But how do these models fuse vision and language? The key lies in their architecture, which translates pixels into a “visual language” that LLMs can comprehend.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/0*c8Bg-5WaBcd0rNFO" /><figcaption>A Vision-Language Model processes an image of a flamingo and generates a natural language response.</figcaption></figure><h3>VLM Architecture</h3><p>Imagine you have a pre-trained language model and you want to give it the ability to “see”. To do this, you’d need a way to process images into a format the language model understands (like translating visuals into a “language” of features). But how do you bridge the gap between pixels and words??</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/0*Px2w5cYq5U8ANpbB" /><figcaption>Think about it!</figcaption></figure><p>First, you’d need a vision encoder to turn raw images into meaningful representations (like detecting edges, objects, or textures). These features, however, exist in a completely different “space” compared to the language model’s text-based embeddings. To align them, you’d add an adapter, a simple neural network that maps visual features into the language model’s native embedding space. A simpler way to think about the adapter is like a translator interpreting the “French” from the vision model to “English” for the language model.</p><p>With that, the general structure of most VLMs is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*57QEhW8bpcuMvTHry6iBeA.png" /><figcaption>source:<a href="https://arxiv.org/abs/2402.12451"> https://arxiv.org/abs/2402.12451</a></figcaption></figure><h4>Main components</h4><ul><li>Vision Encoder: Typically based on transformers or CNN architectures, converting images into feature representations</li><li>Adapter/Projection Layer: Aligns visual features with the language model’s embedding space</li><li>Language Model: An LLM that generates responses based on both textual and adapted visual inputs from the adapter/projection layer</li></ul><h4>Other components</h4><p><strong>Adapted Image Embeddings</strong></p><p>Adapted embeddings are the transformed visual features produced by the projection layer/adapter. They act as a <em>visual prefix/suffix</em> to the text-based token embeddings.</p><p>Example:</p><p>[Image Embeddings] + [Text Embeddings] → LLM input sequence</p><ul><li>Usually, as proven by B McKinzie et al. (2024), the number of adapted embeddings has a positve correlation with VLM model peformance</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/0*XtejydM4nR4nDwwY" /><figcaption>Adapted image embeddings/token circled in Red</figcaption></figure><p>Now that we’ve outlined the core components of a Vision-Language Model (VLM) and how they work together, it’s time to roll up our sleeves and start building our very own custom VLM. <strong>The model would be built around the huggingface transformer’s library such that we can use the it just like any standard model on huggingface</strong></p><h3>Building the Cutsom Model</h3><p>Before we dive into the technical details, let’s give our model a name. I’m calling it BobVLM — partly because my initials spell out “Bob,” and partly because it sounds like it could also be your average friendly and chill neighbour 😉.</p><p>Mr.Bob is a 1.5 billion parameter model designed to handle detailed image captioning and a little visual question answering with reasonable accuracy. The main architectural components are a follows:</p><ul><li>Vision Encoder: CLIP (specifically, clip-vit-large-patch14) to process images into meaningful embeddings.</li><li>Language Model: LLaMA (llama-3.2–1.3b) to generate coherent and contextually relevant text.</li><li>The Translator: A 1.5m multi-layer perceptron (MLP) projection layer acting as a bilingual translator between CLIP’s embeddings and LLaMA’s token space. It consists of 3 layers and each containing 500 nodes/neurons</li><li>Adapted Image Embeddings: The number of adapted image embeddings in BobVLM are 257, following CLIPs final hidden state.</li></ul><p>To keep things simple and resource efficient, the vision and language components are <strong>frozen</strong>, and only the adapter is trained. The training approach is <strong>supervised</strong>, treating the adapter training as a form of <strong>finetuning</strong>. This allows the adapter to not only map image representations into the LLM’s space but also learn task-specific nuances. This approach partially mirrors Houlsby et al. (2019)<strong> </strong>in using MLP adapters for transfer learning.</p><p><em>Note: Since I only simply adapt the model to gain simple image understanding, the training can be done on accessible hardware like the T4 or P100 GPUs</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VOScP5HTwj1lRwQW59FaTQ.png" /><figcaption>Model design for BobVLM</figcaption></figure><h4>Datasets Used</h4><p><strong>LLaVA Instruct-150k</strong>: LLaVA-Instruct is a multimodal instruction-following dataset generated by GPT-4. These samples include conversations, detailed descriptions, and complex reasoning tasks based on images, providing a rich resource for training models to understand and respond to visual and textual instructions.</p><p><strong>Coco captions</strong>: The COCO Captions dataset is a comprehensive resource designed for image captioning tasks, containing over 1.5 million human-generated captions describing more than 330,000 images. Each image in the training and validation sets is annotated with five independent captions, providing diverse descriptions for the same visual content</p><p><em>The reason behind the above datasets is that all the images are available online, meaning, i can train without downloading images locally.</em></p><h4>Tokenization and Input Processing</h4><p>Just like LLMs have <strong>tokenizers</strong>, VLMs need processors that process the data into an appropriate format. The processor consists of the tokenizer that that processes the image to the right format.</p><h4>Training and Next Token Prediction</h4><p>Traditional LLMs use straightforward label shifting for next-token prediction, but Vision-Language Models (VLMs) require special handling of image embeddings.</p><p><strong>Let’s look at how the Next token Prediction works with LLMs</strong></p><pre>Input: &quot;&lt;sos&gt; How are you&quot;<br>Input IDs: [1, 2, 3, 4]<br>Target: &quot;How are you &lt;eos&gt;&quot;<br>Target IDs: [2, 3, 4, 5]</pre><p>Visual representation</p><pre>Input     Target<br>&lt;sos&gt;  →   How<br> How   →   are<br> are   →   you<br> you   →   &lt;eos&gt;</pre><p>Note:<em> &lt;sos&gt; denotes the start-of-sequence token, and &lt;eos&gt; denotes the end-of-sequence token.</em></p><p>This works because each word corresponds to a specific token ID, and we simply shift the sequence by one position to create the target sequence. The model learns to predict the next word given the previous words.</p><p><strong>Now For VLMs</strong></p><p>The challenge becomes more interesting with VLMs because we’re dealing with both image and text embeddings. The key question is: how do we create targets for the image embeddings portion?</p><pre>Input                Target<br>[image embeddings] →  ???<br>[image embeddings] →  ???<br>[image embeddings] →  ???<br>&lt;sos&gt;              →  what<br>what               →  do<br>do                 →  you<br>you                →  see<br>see                →  &lt;eos&gt;</pre><p>This is where a special <strong>image token</strong> comes in to represent image embeddings in the target sequence. In models like LLAVA, that special image token is <strong>&lt;image&gt;</strong>. Therefore their tokenizer interprets “&lt;image&gt;” as its own unique id. Say, that id is 60</p><p>The new labels then become</p><pre>Input                  Target<br>[image embeddings]  →    60<br>[image embeddings]  →    60<br>[image embeddings]  →    60<br>&lt;sos&gt;               →   what<br>what                →    do<br>do                  →   you<br>you                 →   see<br>see                 →  &lt;eos&gt;</pre><p>This means that every time the adapted image embeddings appear in the input, the target is replaced with the special image token &lt;image&gt; (or its unique ID, here 60).</p><p>For BobVLM, I would be using ※ as my image token since it’s a rarely used character in english. The id for this character in the LLaMA tokenizer is 64780. Therefore, every adapted image embedding in the input will correspond to the token ※ (ID 64780) in the target.</p><h3>Coding Things Out</h3><p>We would be coding out 3 main components namely, The<strong> VLM Processor</strong>, <strong>The Adapter</strong> and the <strong>Model. </strong>Make sure to have transformers installed.</p><pre>pip install transformers</pre><ol><li><strong>VLMProcessor</strong>: As mentioned before, a processor is needed to preprocess of both images and text. This processor does the following:</li></ol><ul><li>Uses CLIP’s image processor for vision input</li><li>Uses Llama’s tokenizer for text input</li><li>Contains and option to create labels for training</li></ul><p>To build a processor compatible with the transformers library, you would need to write a class that inherits from transformer’s <strong>ProcessorMixin</strong> class and define your text tokenizer and image processor in the constructor. Next, define the <strong>__call__</strong> method to process your inputs.</p><pre>from transformers import ProcessorMixin, AutoTokenizer<br>from transformers import CLIPImageProcessor<br>import torch  # Add torch import<br><br>class BobVLMProcessor(ProcessorMixin):<br>    attributes = [&quot;image_processor&quot;, &quot;tokenizer&quot;]<br><br>    def __init__(self):<br>        # Initialize tokenizer<br>        self.tokenizer = AutoTokenizer.from_pretrained(&quot;meta-llama/Llama-3.2-1B-Instruct&quot;)<br>        self.tokenizer.pad_token = self.tokenizer.eos_token<br>        self.tokenizer.pad_token_id = self.tokenizer.eos_token_id<br><br>        # Initialize image processor<br>        self.image_processor = CLIPImageProcessor.from_pretrained(&quot;openai/clip-vit-large-patch14&quot;)<br><br>        # Required for ProcessorMixin<br>        self.current_processor = self<br><br>    def prepare_labels(self, inputs):<br>        # Edit the labels such that the image token id is appended to the beginning of the original ids so they match for loss calc<br>        special_image_token_id = 64780  # the id corresponds to ※<br>        num_image_tokens = 257<br><br>        # Clone the input_ids to avoid modifying tensors in-place<br>        input_ids = inputs[&#39;input_ids&#39;].clone()<br>        special_tokens_column = torch.full(<br>            (input_ids.size(0), num_image_tokens),<br>            float(special_image_token_id),<br>            device=input_ids.device,<br>            dtype=input_ids.dtype<br>        )<br><br>        # Create new tensor for labels<br>        inputs[&#39;labels&#39;] = torch.cat([special_tokens_column, input_ids], dim=1).detach()<br>        return inputs<br><br>    def __call__(self, text=None, images=None, create_labels=False):<br>        &quot;&quot;&quot;<br>        Process images and/or text inputs.<br>        <br>        Args:<br>            text: Text input to process<br>            images: Image input to process<br>            create_labels: If True, creates labels for training<br>        &quot;&quot;&quot;<br>        result = {}<br><br>        # Process images<br>        if images is not None:<br>            result[&quot;pixel_values&quot;] = self.image_processor(images)[&quot;pixel_values&quot;]<br><br>        # Process text<br>        if text is not None:<br>            text_result = self.tokenizer(<br>                text,<br>                padding=True,<br>                truncation=True,<br>                max_length=250<br>            )<br>            result[&quot;input_ids&quot;] = text_result[&quot;input_ids&quot;]<br>            result[&quot;attention_mask&quot;] = text_result[&quot;attention_mask&quot;]<br><br>        # Optionally create labels<br>        if create_labels and &quot;input_ids&quot; in result:<br>            result = self.prepare_labels(result)<br><br>        return result</pre><p>2. <strong>The Adapter</strong></p><p>The adapter is simply built with pytorch. The general rule is, <em>define your components in the constructor (__init__); connect them in the forward function</em></p><pre>import torch<br><br>class BobVLMAdapter(torch.nn.Module):<br>    def __init__(self, lang_embed_dim, clip_dim):<br>        super().__init__()<br>        self.activation = torch.nn.ReLU()<br>        self.layer1 = torch.nn.Linear(clip_dim, 500)<br>        self.layer2 = torch.nn.Linear(500, 500)<br>        self.layer3 = torch.nn.Linear(500, lang_embed_dim)<br><br>    def forward(self, x):<br>        x = self.layer1(x)<br>        x = self.activation(x)<br>        x = self.layer2(x)<br>        x = self.activation(x)<br>        x = self.layer3(x)<br>        output = self.activation(x)<br>        return output</pre><p>3. <strong>VLM Implementation</strong></p><ul><li>We first have to define a <strong>config class</strong> that contains basic parameters our model needs, like embedding dimensions and vocabulary size. Think of this as the blueprint for our model’s architecture. For simplicity, I would define only the embedding dimensions for the config.</li></ul><p>The configuration class inherits from Hugging Face’s <strong>PretrainedConfig</strong></p><pre>from transformers import PretrainedConfig, PreTrainedModel, AutoModelForCausalLM, CLIPVisionModel<br>import torch<br><br>class BobVLMConfig(PretrainedConfig):<br>    model_type = &quot;bobvlm&quot;<br>    def __init__(self, lang_embed_dim=2048, clip_dim=1024, **kwargs):<br>        super().__init__(**kwargs)<br>        self.lang_embed_dim = lang_embed_dim<br>        self.clip_dim = clip_dim</pre><p>Next we build the model by inheriting from the <strong>PreTrainedModel</strong> class. The main things here are to build a <strong>forward</strong> method<strong> </strong>that defines how the model processes input data., and a <strong>generate</strong> funtion that generates a sentence-like reponse.</p><p>I, however, added an extra <strong>__extend_attention_mask</strong> method to, as the name suggests, extend the attention mask to the image embeddings. Ensuring that both image and text tokens are properly incorporated (<em>attended to</em>) during processing.</p><pre>from transformers import PreTrainedModel, AutoModelForCausalLM, CLIPVisionModel<br><br>class BobVLM(PreTrainedModel):<br>    config_class = BobVLMConfig<br>    def __init__(self, config):<br>        super().__init__(config)<br>        # Defining the components<br>        self.vit = CLIPVisionModel.from_pretrained(&quot;openai/clip-vit-large-patch14&quot;)<br>        self.adapter = BobVLMAdapter(config.lang_embed_dim, config.clip_dim)<br>        self.language_model = AutoModelForCausalLM.from_pretrained(&quot;meta-llama/Llama-3.2–1B-Instruct&quot;)<br><br>    def __extend_attention_mask(self, atten_mask, atten_to_img=True, num_added_tokens=257):<br>        # Extending the attention mask to image embeddings<br>        batch_size, seq_length = atten_mask.shape<br>        extended_mask = torch.ones if atten_to_img else torch.zeros<br>        mask = extended_mask((batch_size, seq_length + num_added_tokens),<br>                             dtype=atten_mask.dtype,<br>                             device=atten_mask.device)<br>        mask[:, -seq_length:] = atten_mask<br>        return mask<br><br>    def process_inputs(self, input_ids, attention_mask, pixel_values, attend_to_img_tokens=True):<br>        # Processing inputs<br>        embeddings = self.language_model.model.embed_tokens(input_ids)<br><br>        if pixel_values is not None:<br>            image_embeddings = self.vit(pixel_values).last_hidden_state<br>            adapted_embeddings = self.adapter(image_embeddings)<br>            embeddings = torch.cat((adapted_embeddings, embeddings), axis=1)<br>            attention_mask = self.__extend_attention_mask(attention_mask, attend_to_img_tokens)<br><br>        return embeddings, attention_mask<br><br>    def forward(self, input_ids=None, attention_mask=None, pixel_values=None,<br>                attend_to_img_tokens=True, labels=None, **kwargs):<br>        input_ids = kwargs.get(&quot;input_ids&quot;, input_ids)<br>        attention_mask = kwargs.get(&quot;attention_mask&quot;, attention_mask)<br>        pixel_values = kwargs.get(&quot;pixel_values&quot;, pixel_values)<br>        labels = kwargs.get(&quot;labels&quot;, labels)<br><br>        embeddings, attention_mask = self.process_inputs(input_ids, attention_mask, pixel_values, attend_to_img_tokens)<br><br>        return self.language_model(<br>            inputs_embeds=embeddings,<br>            attention_mask=attention_mask,<br>            labels=labels<br>        )<br><br>    def generate(self, input_ids=None, attention_mask=None, pixel_values=None,<br>                 attend_to_img_tokens=True, **kwargs):<br>        input_ids = kwargs.pop(&quot;input_ids&quot;, input_ids)<br>        attention_mask = kwargs.pop(&quot;attention_mask&quot;, attention_mask)<br>        pixel_values = kwargs.pop(&quot;pixel_values&quot;, pixel_values)<br><br>        embeddings, attention_mask = self.process_inputs(input_ids, attention_mask, pixel_values, attend_to_img_tokens)<br><br>        return self.language_model.generate(inputs_embeds=embeddings, attention_mask=attention_mask, **kwargs)</pre><h3>Voila!🎉We have built a VLM</h3><h4>Training</h4><p>The training script is quite exhautive so I have the link to it <a href="https://github.com/logic-OT/BobVLM/blob/main/train_script.py">HERE</a>. It contains details of how i process the datasets from LLaVA and COCO. The model was trained on 350k samples using P100 GPUs with a batch size of 4 — <em>proof that you don’t need a supercomputer to experiment!”</em></p><p><strong>The model after training, demonstrates understanding of key structures in images. The model exceeds and general image description but lacks in complex VQA tasks and fails to point minor detail in the image due to the incredibly small training data.</strong></p><h4>Example Usage</h4><pre>from PIL import Image<br>from transformers.image_utils import load_image<br><br>processor = BobVLMProcessor()<br>model = BobVLM(BobVLMConfig())<br><br>image = load_image(&quot;https://media.istockphoto.com/id/155439315/photo/passenger-airplane-flying-above-clouds-during-sunset.jpg?s=612x612&amp;w=0&amp;k=20&amp;c=LJWadbs3B-jSGJBVy9s0f8gZMHi2NvWFXa3VJ2lFcL0=&quot;)<br>text = &quot;What do you see in this image?&quot;<br><br>inputs = processor(text = text,images=[image])<br>outputs = model.generate(**inputs)<br>processor.tokenizer.batch_decode(outputs)</pre><p><strong>Output</strong></p><pre>The image depicts a small airplane flying over a mountainous landscape, with a large, dark cloud covering the sky. The airplane is flying towards the mountain, and the cloud is blocking the sun, creating a dramatic and ominous atmosphere</pre><h3>Using BobVLM</h3><p>You can find the fully built model on Github at:</p><p><a href="https://github.com/logic-OT/BobVLM">GitHub - logic-OT/BobVLM: BobVLM - A 1.5B multimodal model built from scratch and pre-trained on a single P100 GPU capable of image descriptions and moderate question answering. 🤗🎉</a></p><p>You can install it and experiment to see it’s abilities and flaws.</p><p>Huggingface 🤗 at</p><p><a href="https://huggingface.co/selfDotOsman/BobVLM-1.5b">selfDotOsman/BobVLM-1.5b · Hugging Face</a></p><p>References</p><ol><li>Gu, Jindong &amp; Han, Zhen &amp; Chen, Shuo &amp; Beirami, Ahmad &amp; He, Bailan &amp; Zhang, Gengyuan &amp; Liao, Ruotong &amp; Qin, Yao &amp; Tresp, Volker &amp; Torr, Philip. (2023). A Systematic Survey of Prompt Engineering on Vision-Language Foundation Models. 10.48550/arXiv.2307.12980.</li><li>Houlsby, N., “Parameter-Efficient Transfer Learning for NLP”, &lt;i&gt;arXiv e-prints&lt;/i&gt;, Art. no. arXiv:1902.00751, 2019. doi:10.48550/arXiv.1902.00751.</li><li>McKinzie, B., “MM1: Methods, Analysis &amp; Insights from Multimodal LLM Pre-training”, &lt;i&gt;arXiv e-prints&lt;/i&gt;, Art. no. arXiv:2403.09611, 2024. doi:10.48550/arXiv.2403.09611.</li><li><em>Hugging Face. (n.d.). </em>Custom Models — Transformers documentation<em>. Hugging Face. </em><a href="https://huggingface.co/docs/transformers/en/custom_models"><em>https://huggingface.co/docs/transformers/en/custom_models</em></a></li><li>Ghosh, A., Acharya, A., Saha, S., Jain, V., and Chadha, A., “Exploring the Frontier of Vision-Language Models: A Survey of Current Methodologies and Future Directions”, &lt;i&gt;arXiv e-prints&lt;/i&gt;, Art. no. arXiv:2404.07214, 2024. doi:10.48550/arXiv.2404.07214.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d51099bfbcb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>