<?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 Viraj Kadam on Medium]]></title>
        <description><![CDATA[Stories by Viraj Kadam on Medium]]></description>
        <link>https://medium.com/@viraajkadam?source=rss-9480ce2d902d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*6MxaOSyX3jBu8e_nz36E1w.jpeg</url>
            <title>Stories by Viraj Kadam on Medium</title>
            <link>https://medium.com/@viraajkadam?source=rss-9480ce2d902d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 20:14:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@viraajkadam/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[Document processing part-2: What is Docling, and why should you use it for local document…]]></title>
            <link>https://viraajkadam.medium.com/document-processing-part-2-what-is-docling-and-why-should-you-use-it-for-local-document-4a71c1f5cc20?source=rss-9480ce2d902d------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a71c1f5cc20</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[agentic-rag]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Viraj Kadam]]></dc:creator>
            <pubDate>Mon, 12 Oct 2026 09:26:40 GMT</pubDate>
            <atom:updated>2026-10-12T09:26:40.651Z</atom:updated>
            <content:encoded><![CDATA[<h3>Document processing part-2: What is Docling, and why should you use it for local document processing</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WafECZdvxAFRfGXyOkP52g.png" /><figcaption>Source : <a href="https://docling.ai/">docling</a></figcaption></figure><p><em>These days modern AI based document parsers are the essential backbone of the document parsing and understanding pipelines, replacing traditional methods.</em></p><p><em>This comes in various forms, but local document parsing capabilities are the need of the hour as a lot of these enterprise documents have confidential information.</em></p><p><em>Docling is an open source, efficient , easy to use document parsing toolkit developed by IBM , that can parse documents to rich structured representations and run on local, commodity hardware.</em></p><p><strong>Before we start, we can address a simple but a common question :</strong></p><blockquote>Can’t PDFs just be read by a computer if it’s a digital document?</blockquote><p>PDFs don&#39;t actually store text, but rather visual representation of how the document should look and be rendered. There are multiple different versions of PDF documents too, like digital native pdfs, or scanned pdfs , which differ in how they store the document information.</p><p>Read : <a href="https://www.llamaindex.ai/blog/why-reading-pdfs-is-hard">Why PDF reading is hard</a> if you want to know more about this .</p><h4>Current challenges and how Docling solves them</h4><p>Current common document workflows have the following challenges, which docling aims to solve</p><p><strong>a) Local deployment</strong></p><p>Most of the SOTA document processing systems require you to either do a server-less inference by sending the data over to parsing apis (gemini, gpt etc) or deploy a compute heavy system on the client side.</p><p>Docling uses lightweight, task specific models to ensure fast processing that can be run locally on consumer hardware. Docling also has GPU support for faster processing speeds.</p><p><strong>b) Various Input formats</strong></p><p>Documents for any organisation or entity can come in various formats , such as scanned pdfs, digital pdfs, images, word documents , powerpoints etc. Hence , it is important for document parser pipelines to be able to seamlessly work and support different document formats.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4DmTkrH2R03MLwTxrCEPeA.png" /><figcaption>source : Docling</figcaption></figure><p>Docling works out of the box with all of the provided formats seamlessly, offering resource efficient , local parsing ability.</p><p><strong>c) Multi-Modal data and Layout analysis</strong></p><p>Another challenge in these pipelines is the ability of the parsers to handle non text based elements in the documents like Tables, Images, Figures etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ikfesp8c2Sp8jXOC39NHIA.png" /><figcaption>source: Docling</figcaption></figure><p>Docling uses suite of AI models that help with document understanding, including layout analysis, OCR, reading order, figure and table structured extraction.</p><p><strong>d) Standardised Output format</strong></p><p>There is no established standard format for the outputs generated , which is crucial for maintaining document and component structure.</p><p>Docling establishes standard DoclingDocument data model, which helps in rich document representation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LK970Wkx3zJRCFUAKe-dIQ.png" /><figcaption>source: Docling</figcaption></figure><p>Docling also allows for the output to be easily transformed to other standard document datatypes like Markdown, HTML or JSON.</p><h3>The Docling Data model</h3><p>One of the key theme in docling is an unified data model for parsed documents. This comes with great benefits, as it allows users to work across document formats.</p><p><strong>a) Pydantic based, supports multiple features</strong>: It is a Pydantic based data model which can represent common features like text, images, tables, captions etc.</p><p><strong>b) Visual hierarchy and ordering</strong> : It maintains hierarchy among the elements of a document, and maintains layout information for all elements.</p><p><strong>c) Document Metadata</strong> : The model also captures provenance metadata, like page number, document origin etc.</p><p><strong>d) Format agnostic</strong> : The document model allows easy to and back conversions to popular data formats like HTML, Json etc.</p><h4>What documents can docling process, and how?</h4><p><strong>Docling parser backends</strong></p><p><em>Docling uses different parser backends to parse different kind of documents.The document type is detected and appropriate parsing backend is used for the task.</em></p><p><strong>a)</strong> <strong>Low Level</strong> (<strong>Images and PDFs) </strong>: Primarily encode visual information on how to render the documents, hence need to usually pass through the pipeline of <em>OCR detection -&gt; Layout Detection -&gt; Table parsing -&gt; Document Compilation</em>.</p><p><strong>b) Markup based formats</strong> : These formats preserve the layout and sematic structure of the document, and are relatively simple and inexpensive to parse. HTML, MS office and Markdown based documents are a example of these kinds of documents.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*LiybidUTBRKE4c73hmwHBw.png" /><figcaption><a href="https://arxiv.org/html/2501.17887v1">Docling architecture</a></figcaption></figure><p>When looking at document processing, the complexity of the pipeline is dependant on the type of document</p><ol><li><strong>Image or Scanned PDFs</strong> : needs the full pipeline to process the document (including OCR).</li><li><strong>Digitally created PDFs</strong> : For digitally created PDFs, the OCR step can be skipped as that data already exists. The rest of operations still need to be executed though (layout detection, table structure detection).</li><li><strong>Documents with rich representation</strong>: Document formats like docs, pptx are already information rich, and the information can be easily processed by accessing these representations.</li></ol><p>In the next series of blogs, we would take a look into how docling works under the hood, how to use it, and what are the other alternative and newer models for doc processing using VLMs</p><h4>Resources</h4><ul><li><a href="https://docling.ai/">https://docling.ai/</a></li><li>Docling paper : <a href="https://arxiv.org/pdf/2501.17887">https://arxiv.org/pdf/2501.17887</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a71c1f5cc20" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding LLMs : Model precision and what it means (with code)]]></title>
            <link>https://viraajkadam.medium.com/understanding-llms-model-precision-and-what-it-means-with-code-1a8de4c52272?source=rss-9480ce2d902d------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a8de4c52272</guid>
            <category><![CDATA[small-language-model]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[hugging-face]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[chatgpt]]></category>
            <dc:creator><![CDATA[Viraj Kadam]]></dc:creator>
            <pubDate>Tue, 30 Jun 2026 13:15:05 GMT</pubDate>
            <atom:updated>2026-06-30T13:15:05.189Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SmVJRPUUSFoil5i65ucDhg.png" /></figure><p>With a push to machine learning using LLMs with open weights, a big part of it comes down to using quantized models for better memory management and latency.</p><p>But how do different data-types affect the memory footprint of the model?</p><p>In this blog we will try to quantify how different memory types will affect the memory footprint of models.</p><p><strong>The native data types in Py-torch</strong></p><p>We can check the primitive data types available in py-torch. There are a variety of native data-types, but the kind that we are interested in machine learning are limited to a few Float and Integer data-types</p><pre>import torch<br><br># Find all attributes in the torch module that are data types<br>available_dtypes = [name for name in dir(torch) if isinstance(getattr(torch, name), torch.dtype)]<br><br>print(&quot;Available PyTorch dtypes:&quot;)<br>for dtype in available_dtypes:<br>    print(f&quot;- torch.{dtype}&quot;)</pre><p>this yields the following</p><pre>Available PyTorch dtypes:<br>- torch.bfloat16<br>- torch.bit<br>- torch.bits16<br>- torch.bits1x8<br>- torch.bits2x4<br>- torch.bits4x2<br>- torch.bits8<br>- torch.bool<br>- torch.cdouble<br>- torch.cfloat<br>- torch.chalf<br>- torch.complex128<br>- torch.complex32<br>- torch.complex64<br>- torch.double<br>- torch.float<br>- torch.float16<br>- torch.float32<br>- torch.float4_e2m1fn_x2<br>- torch.float64<br>- torch.float8_e4m3fn<br>- torch.float8_e4m3fnuz<br>- torch.float8_e5m2<br>- torch.float8_e5m2fnuz<br>- torch.float8_e8m0fnu<br>- torch.half<br>- torch.int<br>- torch.int1<br>- torch.int16<br>- torch.int2<br>- torch.int3<br>- torch.int32<br>- torch.int4<br>- torch.int5<br>- torch.int6<br>- torch.int64<br>- torch.int7<br>- torch.int8<br>- torch.long<br>- torch.qint32<br>- torch.qint8<br>- torch.quint2x4<br>- torch.quint4x2<br>- torch.quint8<br>- torch.short<br>- torch.uint1<br>- torch.uint16<br>- torch.uint2<br>- torch.uint3<br>- torch.uint32<br>- torch.uint4<br>- torch.uint5<br>- torch.uint6<br>- torch.uint64<br>- torch.uint7<br>- torch.uint8</pre><p><strong>Data types and their properties</strong></p><p>Traditionally, float32 and float64 have been the popular datatypes used in scientific high performance compute workflows and simulations. They offer high level of precision.</p><p>But using lower precision datatype allows us to have a lower memory footprint , while also with the possibility of having a higher compute speed (and lower model latency) .</p><p>Also , if you know GPUs, most of its operations are actually memory bound than compute bound, so a lower memory footprint helps speed up the model speed.</p><p>We will check the popular datatypes defined above in PyTorch, and their memory footprint and range.</p><p><strong>Float 32</strong></p><p>Float 32 is the default numeric type in pytorch. Each number in float 32 datatype is represented by 4 Bytes (32 bits).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*QZDDSTBpF6n3y5jo.png" /><figcaption><a href="https://en.wikipedia.org/wiki/Single-precision_floating-point_format">source</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8b5NJ2JCRgXiGVUAQaL5Cg.png" /></figure><p><strong>Float 16</strong></p><p>Float16 cuts the memory footprint from float 32 upto half, taking about 2 bytes per number. This comes at a cost of reduced dynamic range (means that it is prone to numerical underflow or overflow).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/0*nQcURJEn9JIJTCCx.png" /><figcaption><a href="https://en.wikipedia.org/wiki/Half-precision_floating-point_format">source</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jkcws6gwBOgWoX9IBbMbBA.png" /></figure><p><strong>BFloat 16</strong></p><p>Developed by google, this datatype offers dynamic range of FP32 at the memory footprint of FP16, at the cost of reduced resolution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fxivo23DW7eYnv9gIXtCJQ.png" /><figcaption><a href="https://en.wikipedia.org/wiki/Bfloat16_floating-point_format">source</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YUwzFL78iZAOaH_HZm9ZBA.png" /></figure><p><strong>Loading models in Bfloat16 and check the footprint</strong></p><p>We will load google gemma-4 (2B) in brain-float16 type. This model has 5.1B total parameters, with 2.3 active parameters.</p><pre>from transformers import AutoProcessor, AutoModelForCausalLM<br>from transformers import AutoConfig<br>from transformers import BitsAndBytesConfig<br>import torch<br><br>class CFG:<br>    device = &quot;cuda:0&quot; if torch.cuda.is_available()  else &quot;cpu&quot;<br>    # MODEL_ID = &quot;google/gemma-4-E4B-it&quot;<br>    MODEL_ID = &quot;google/gemma-4-E2B-it&quot;<br><br><br><br>#define max memory map on each cuda device<br>max_mem = {0: &quot;12GB&quot;, <br>           1: &quot;12GB&quot;}<br><br><br><br>processor = AutoProcessor.from_pretrained(CFG.MODEL_ID)<br><br>model = AutoModelForCausalLM.from_pretrained(<br>    CFG.MODEL_ID,<br>    dtype=torch.bfloat16,<br>    device_map=&quot;cuda:0&quot;,<br>    # quantization_config=quantization_config,<br>    max_memory=max_mem<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yGZf-Ypm5q9ks92dPPAydw.png" /></figure><p>If you check the model card, we can see that it has total 5.1 B parameters. When we load the model in bfloat16 (2 bytes per param) , the total model weight size comes around to be 10.2 GB, as we expect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xnoo8qloBfUc9l-8aUJ5mw.png" /><figcaption><a href="https://huggingface.co/google/gemma-4-E2B">Model card</a></figcaption></figure><pre>for i in range(torch.cuda.device_count()):<br>    print(f&quot;GPU {i}: {torch.cuda.memory_allocated(i) / 1024**3:.2f} GiB allocated, &quot;<br>          f&quot;{torch.cuda.memory_reserved(i) / 1024**3:.2f} GiB reserved&quot;)<br><br>&gt;&gt;&gt; GPU 0: 9.52 GiB allocated, 9.60 GiB reserved<br>&gt;&gt;&gt; GPU 1: 0.00 GiB allocated, 0.00 GiB reserved</pre><p>In the next article, we will run resource accounting of the model, trying to explain how much memory and compute a certain model will consume with the certain input prompt.</p><p><strong>Resources</strong></p><ul><li><a href="https://www.kaggle.com/code/virajkadam/inside-google-gemma-4/edit">https://www.kaggle.com/code/virajkadam/inside-google-gemma-4</a></li><li><a href="https://cs336.stanford.edu/lectures/?trace=lecture_02">https://cs336.stanford.edu/lectures/?trace=lecture_02</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a8de4c52272" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understands LLMs : How do I estimate GPU memory requirement for loading a model?]]></title>
            <link>https://viraajkadam.medium.com/understands-llms-how-do-i-estimate-gpu-memory-requirement-for-loading-a-model-1d176ddd4e56?source=rss-9480ce2d902d------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d176ddd4e56</guid>
            <category><![CDATA[gpu]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[local-llm]]></category>
            <dc:creator><![CDATA[Viraj Kadam]]></dc:creator>
            <pubDate>Sun, 22 Mar 2026 12:25:39 GMT</pubDate>
            <atom:updated>2026-03-22T12:25:39.985Z</atom:updated>
            <content:encoded><![CDATA[<p><em>In the previous article, we discussed the basics of using GPUs in pytorch (</em><a href="https://viraajkadam.medium.com/understandling-llms-basics-of-using-gpus-with-pytorch-5f8d599de4d1"><em>read here</em></a><em>). In this article, we will understand how to estimate how much gpu memory we need to load a given model</em></p><p><em>This will help us to estimate which GPU to use given a model, or which model to use given a GPU. This will also help us prevent OOM (cuda out of memory error), which happens when there is no available memory on GPU RAM</em></p><h4>Memory is not compute</h4><blockquote>But before we get into the specifics, the most important thing to understand is Memory != Compute.</blockquote><blockquote>We talk about GPU memory, and consider that it is where the compute performance is coming from. Memory affects performance (because the operations on GPU are memory bound), but memory is not compute.</blockquote><p><em>Compute performance of most GPUs these days is reported in T-FLOPs (Terra flops), FLOPs refers to floating point operations per second.</em></p><p><em>Memory is referred to the High bandwidth memory, which stores all the model and data on the GPU RAM.</em></p><p>This plays a big role in the performance of the GPU, as most of the GPU operations are memory bound not compute bound, meaning that memory operations are usually the bottleneck for performance.</p><p>The GPU that we are working with today in colab notebook (<strong>Nvidia — T4</strong> ) has a reported performance of <strong>8.1 Tflops</strong> for FP32 computations, and about <strong>65 Tflops</strong> for FP16 computations , and has a HBM (GPU RAM) of <strong>16 GB</strong>, with memory bandwidth of about <strong>320 GB/sec</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zMePwpUOt2FGWtPEmY5Jng.png" /><figcaption>Specification for Nvidia Tesla-T4 : <a href="https://www.techpowerup.com/gpu-specs/tesla-t4.c3316">source</a></figcaption></figure><h4>What does the process of making an inference on the GPU involve?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5F7Js7A2CFgkYiwqtNg7vQ.png" /><figcaption>model-data lifecycle on a GPU.</figcaption></figure><ol><li>Move model weights to GPU RAM: we load the model on the GPU, which involves loading the model weights on the GPU RAM.</li><li>Move data to the GPU RAM : When we make a batched prediction, we are moving the transformed data on the GPU RAM.</li><li>Move the model weights and data from RAM to SM cache:</li><li>Computation happens on the SMs present on the GPU.</li><li>Move the computed data from SM cache back to GPU RAM, then offload to CPU.</li></ol><h4>Computer Memory Basics</h4><p>A bit is a basic unit of memory in computers, which can represent a binary number (0/1). A single byte is made up of 4 bits.</p><p>1 Byte = 4 bits</p><p>We are used to dealing with GB and MBs which are basically</p><ul><li>1 KiloByte = 1024 Bytes</li><li>MB (Megabyte) : 1024 KB, which is about ~1e6 Bytes.</li><li>GB (Gigabyte) : 1024 MB, which is close to ~ 1e9 Bytes.</li></ul><h4>Basic floating point data-types in ML</h4><p><strong>Single precision : FP32</strong></p><ul><li>Used in most machine learning models</li><li>Each unit is represented using 4 Bytes.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B-jzg7uVsGFFc7qLDdVj2w.png" /><figcaption>from : <a href="https://en.wikipedia.org/wiki/Single-precision_floating-point_format">https://en.wikipedia.org/wiki/Single-precision_floating-point_format</a></figcaption></figure><p><strong>Half Precision : FP16</strong></p><ul><li>Used in quantized and mixed precision models</li><li>Each unit is represented by 2 bytes.</li><li>Limited range compared to FP32.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3OFJvmRs0Rp9oDVg.png" /><figcaption>from : <a href="https://cs336.stanford.edu/spring2025-lectures/?trace=var/traces/lecture_02.json">https://cs336.stanford.edu/spring2025-lectures/?trace=var/traces/lecture_02.json</a></figcaption></figure><p><strong>Bfloat16</strong></p><ul><li>developed by google, has range of FP32, at the cost of less expressivity.</li><li>Memory footprint similar to FP16, 2 Bytes per unit.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oOI1FRbr905K-80-.png" /><figcaption>from : <a href="https://cs336.stanford.edu/spring2025-lectures/?trace=var/traces/lecture_02.json">https://cs336.stanford.edu/spring2025-lectures/?trace=var/traces/lecture_02.json</a></figcaption></figure><h4>What do the Model parameter mean ?</h4><p>A (parametric) model is usually defined in number of parameters. We will work with the latest Qwen-3.5 4B model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l0b5UxYQR_2wGOVvOHAyrg.png" /><figcaption>from : <a href="https://huggingface.co/Qwen/Qwen3.5-4B">https://huggingface.co/Qwen/Qwen3.5-4B</a></figcaption></figure><p>These parameters are the number of individual weight elements, each one of which can be thought of as as a tuneable knob, which we adjust during the process of training so that it fits well to the training data.</p><p>Now a 4B model means it will have somewhere around 4 billion active parameters (meaning about 4B tuneable knobs)</p><p>Each parameter has some numerical precision, which depends on data-type of the model weights being used. We will look at this in a later blog.</p><p>Most machine learning models are usually trained and available in a full precision (FP32) or Bfloat16 (BF16) .</p><p>This mean each parameter is represented by a 32-bit integer, which translate to 4 Bytes/Parameter.</p><p>Hence the memory footprint of the model in full precision is</p><p><em>4 B param * 4 B/Param ~ 16 GB of memory required to load the model in full precision.</em></p><p>In BF16, the same model will be loaded in</p><p><em>4 B param * 2 B/Param ~ 8 GB of memory required to load the model.</em></p><h4>Loading the model</h4><p>Before we load the model, we can check the GPU memory footprint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dLTPOSpnhsPULQdd8QLzlA.png" /><figcaption>The ram has empty memory</figcaption></figure><p><strong>load model to gpu memory</strong></p><pre>import torch<br>from transformers import AutoModelForCausalLM, AutoTokenizer<br><br>device = torch.cuda.current_device()<br><br><br># Set the exact model ID from Hugging Face<br>model_id = &quot;Qwen/Qwen3.5-4B&quot;<br><br># 1. Load the Tokenizer<br>tokenizer = AutoTokenizer.from_pretrained(model_id)<br>&gt;&gt;&gt; <br><br><br># 2. Load the Model<br>model = AutoModelForCausalLM.from_pretrained(<br>    model_id,<br>    device_map=&quot;cuda:0&quot;,<br>    torch_dtype=&quot;auto&quot; <br>)</pre><p>now if we check the memory footprint again</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sx--7_YWlRnKNIx55Sx9XA.png" /><figcaption>The GPU has about 8 GB of occupied memory. This translates roughly as (4B model, Bf16 precision) -&gt; 4e9 * 2 ~ 8e9 (8GB) of memory.</figcaption></figure><p>to predict using the model, we tokenize the input text using the tokenizer, and move it to the gpu</p><pre><br># 3. Prepare your prompt using the Chat Template<br>messages = [<br>    {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: &quot;You are a helpful AI assistant.&quot;},<br>    {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Explain gpu computing in one simple paragraph.&quot;}<br>]<br><br># This applies Qwen&#39;s specific formatting tags to the prompt<br>text = tokenizer.apply_chat_template(<br>    messages,<br>    tokenize=False,<br>    add_generation_prompt=True<br>)<br><br># Convert the text into tensor tokens and move them to the same device as the model<br>model_inputs = tokenizer([text], return_tensors=&quot;pt&quot;).to(model.device)<br><br>print(model_inputs)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_gqSRYdIZlVKltG_fcRhpQ.png" /><figcaption>tokenized text, moved to cuda</figcaption></figure><pre># 4. Generate the output<br>generated_ids = model.generate(<br>    **model_inputs,<br>    max_new_tokens=512, <br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NoKHa3e3d6EYUEzlRqOADA.png" /><figcaption>predicted model output is a combination of input + output tokens.</figcaption></figure><p>next, we convert these ids to text based on the tokenizer id-token mapping</p><pre># 5. Decode the output<br># We strip the length of the input prompt from the generated IDs so it only prints the new text<br>generated_ids = [<br>    output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)<br>]<br><br>response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]<br><br>print(response)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Eky0-aKO0AVPY1LKAqvfIw.png" /><figcaption>final model output.</figcaption></figure><p>Thank you, in the next one, we will look at what are the memory requirements for training and predicting a model locally.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d176ddd4e56" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understandling LLMs : basics of using GPUs with pytorch.]]></title>
            <link>https://viraajkadam.medium.com/understandling-llms-basics-of-using-gpus-with-pytorch-5f8d599de4d1?source=rss-9480ce2d902d------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f8d599de4d1</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[gpu]]></category>
            <category><![CDATA[pytorch]]></category>
            <dc:creator><![CDATA[Viraj Kadam]]></dc:creator>
            <pubDate>Sun, 15 Mar 2026 15:59:54 GMT</pubDate>
            <atom:updated>2026-03-15T15:59:54.481Z</atom:updated>
            <content:encoded><![CDATA[<p><em>In a </em><a href="https://viraajkadam.medium.com/what-are-gpus-made-up-of-and-why-are-they-so-fast-for-machine-learning-workflows-66de567b6ef1"><em>previous article</em></a><em>, we explored what are GPUs, and why are they fast and so important for machine learning workflows. In this article, we will explore how to use a GPU, and a simple representation of how data transfer usually happens in a ML pipeline.</em></p><p>If you are new to this, you can make an account on <a href="https://colab.research.google.com/">Colab</a> or <a href="https://www.kaggle.com/code">Kaggle</a> to start using a GPU.</p><h4>How to start a GPU session in Kaggle.</h4><p><strong>1. Create a notebook</strong> : Go to <a href="https://www.kaggle.com/code">https://www.kaggle.com/code</a> , create a new notebook.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9H-JDUl5QblDUsr5VUAXVQ.png" /></figure><p><strong>2. Turn on the Accelerator : </strong>from the session options, turn on and select a gpu device. Kaggle allows around 30/h of GPU usage per week.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6u_LbwurqkP_rLxaV9bB2w.png" /></figure><h4>Managing GPUs with pytorch</h4><p>You can check if the session/ device we are operating has a GPU</p><pre>import torch<br><br>#check if a gpu is available.<br>torch.cuda.is_available()<br><br>&gt;&gt;&gt; True</pre><p>this will return a boolean value (True/False) , depending on if a CUDA device is available.</p><pre># get count of devices<br>print(&#39;Number of cuda devices:&#39;, torch.cuda.device_count())<br>&gt;&gt;&gt; Number of cuda devices: 2</pre><p>The session we loaded has two cuda devices</p><pre>device = torch.cuda.current_device()<br>    <br>## 1. Hardware Stats<br>print(f&quot;GPU Name: {torch.cuda.get_device_name(device)}&quot;)<br><br>&gt;&gt;&gt; GPU Name: Tesla T4</pre><p>We can get the also get the device properties</p><pre>#get device properties<br>torch.cuda.get_device_properties()<br><br>&gt;&gt;&gt; _CudaDeviceProperties(name=&#39;Tesla T4&#39;, major=7, minor=5, <br>                        total_memory=14912MB, multi_processor_count=40, <br>                        uuid=b254adcf-27e8-ddf0-b80f-c01010376074, pci_bus_id=0, <br>                        pci_device_id=4, pci_domain_id=0, L2_cache_size=4MB)</pre><p>We can use another command to get the above details. simply run this command in your terminal</p><pre>nvidia-smi</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S7kqXavtPCg1diqjp2-KXQ.png" /></figure><h4>Loading and moving data Pytorch GPUs</h4><p><em>The primitive data-type we work with on GPUs are tensors. So the models and data are all converted to tensors and transferred on the GPU, where the required computations happen, and then the output is offloaded to the CPU.</em></p><p><strong>Moving the data to the GPU :</strong></p><p>Normally in training and inference pipelines, the data is processed and stored on the CPU, before moving it to the GPU in batches for computation.</p><p>We will look at basics of how to move the data to the GPU, and then move it back to the CPU after computation is done.</p><pre>#define a tensor<br>x = torch.normal(0,0.2,(4, 8))<br>x.shape<br><br>&gt;&gt;&gt; torch.Size([4, 8])</pre><p>if we check the device</p><pre># check the device tensor is stored on<br>x.device<br><br>&gt;&gt;&gt; device(type=&#39;cpu&#39;)</pre><p>to move the tensor to another device , we can define the device id and move the tensor there.</p><p>Before we do that, lets check how much memory is currently occupied on the GPU</p><pre># check the memory allocated on GPU<br>torch.cuda.memory_allocated()<br><br>&gt;&gt;&gt; 0</pre><p>Lets move the above tensor to cuda 0</p><pre># move to cuda : 0<br>y = x.to(&quot;cuda:0&quot;)<br><br># check the device for the tensor<br>y.device<br><br>&gt;&gt;&gt; device(type=&#39;cuda&#39;, index=0)</pre><p>Now if we check the allocated memory on</p><pre># check the memory allocated on GPU after we move the tensor<br>torch.cuda.memory_allocated()<br><br>&gt;&gt;&gt; 512</pre><p>We can directly allocated a tensor on the gpu by defining the device when creating a tensor.</p><pre># define a (8,1) tensor on the gpu<br>z = torch.normal(0,0.2,(8, 1), device = &quot;cuda:0&quot;)<br><br>#check device<br>z.device<br><br>&gt;&gt;&gt; device(type=&#39;cuda&#39;, index=0)</pre><h4>Computation on GPU :</h4><p>The primary purpose of GPUs is matrix crunching, they are device capable of massive, parallel computation. When we are using a LLM, the following general operations happen</p><ol><li>Tokenizer converts the input prompt to token ids ( on CPU)</li><li>The tokenized data to send to the GPU</li><li>The tokenized data (along with attention mask) is fed to the model, and all the computations happen on the GPU.</li><li>After the model runs and generates the sequence autoregressively, the generated token ids are moved back to the CPU from GPU</li><li>The generated tokens are decoded (convert token ids to text).</li></ol><p>We will do a simple matrix multiplication operation on the GPU, and move our tensors and computed tensor back to the GPU.</p><pre># matrix multiply y and z<br>matmul = torch.matmul(y,z)<br><br>matmul.shape<br><br>&gt;&gt;&gt; torch.Size([4, 1])</pre><pre>#check the device of computed tensor<br>matmul.device<br><br>&gt;&gt;&gt; device(type=&#39;cuda&#39;, index=0)</pre><p>now to move the tensors back to the CPU, we can simple do the following</p><pre># move the computed tensor to cpu<br>matmul_cpu = matmul.cpu()<br><br># delete the tensors on the gpu<br>del matmul, y,z ; gc.collect()<br><br># check the device<br>matmul_cpu.device<br><br>&gt;&gt;&gt; device(type=&#39;cpu&#39;)</pre><p>This is the key operation happening in most machine learning pipelines involving GPUs.</p><p>In the next blog, we will explore how to load a model, and the math of accounting for a right GPU for the given model</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f8d599de4d1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding LLMs -Tokenization : How models convert text to numerical representation.]]></title>
            <link>https://viraajkadam.medium.com/understanding-llms-tokenization-how-models-convert-text-to-numerical-representation-80ba595b166e?source=rss-9480ce2d902d------2</link>
            <guid isPermaLink="false">https://medium.com/p/80ba595b166e</guid>
            <category><![CDATA[tokenization]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[chatgpt]]></category>
            <dc:creator><![CDATA[Viraj Kadam]]></dc:creator>
            <pubDate>Wed, 04 Mar 2026 14:00:14 GMT</pubDate>
            <atom:updated>2026-03-04T14:00:14.525Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Machine learning models are numerical models, and hence work with numerical representation. This means that the LLMs (and other language models) need the text to be broken in pieces and converted into a embedding space.</blockquote><blockquote>Tokenizer is a key aspect of this process, which helps to break the text into tokens, and each of these tokens is represented by an unique token id. Hence a tokenizer helps convert strings to integers, and back to strings in the inference phase.</blockquote><p>In this blog we will learn what happens in the process of tokenization, and a few ways of tokenizing.</p><h4>Tokenization and embedding layer : How models convert text to embedding space.</h4><p>Have you wondered what happens when you input a text to a LLM ?</p><p>First, the model has to make sense of the provided text. The model does this by converting the text into word embeddings, which are (kind of) semantic representation of these tokens.</p><p>The basic idea of embedding is similar meaning words should have embedding vectors which are close to each other</p><p>We achieve this in 3 steps.</p><p><strong>Step 1: break the input text into tokens</strong></p><p>The tokenizer for the model reads the text, and based on the underlying algorithm (we will discuss some of them) breaks it into tokens.</p><p>The following example demonstrates how the gpt-5 tokenizer breaks the text into sub-words.</p><p>(you can play around with it here : <a href="https://platform.openai.com/tokenizer">https://platform.openai.com/tokenizer</a>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ICN1cJwLzIlhmpHkQGZNtA.png" /></figure><p><strong>Step 2</strong> : <strong>Assign token ids based on tokens.</strong></p><p>Each of the assigned tokens exists in the vocabulary of the tokenizer. The tokenizer also keeps an unique integer id for each of these tokens.</p><p>In the following example, we can check the corresponding token ids for tokenized words from the previous example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rspmPLD_DcxReRQIxTWgBQ.png" /></figure><p><strong>Step 3 : Get the token embeddings from the embedding layer.</strong></p><p>Now that we have the token ids, we can get the learned embedding from the models embedding layer.</p><p>You can think of embedding layer as a look up table, that will fetch vectors corresponding to certain row.</p><p>This embedding layer is a matrix of <em>Num_vocab * Embedding_dimension</em>.</p><p>Num_vocab is the number of tokens in the tokenizers vocabulary and embedding dimension is the number of dimensions a embedding vector has . The higher the embedding dimension, the more featurefull and expressive it is.</p><p>To get a embedding of a vector, we can simply lookup the row number that aligns with the token id .</p><p>Hence to get the embedding for the word “today”, we would simply check the row number 18499 in the embedding matrix.</p><p><strong>Step 4 : Positional embedding</strong></p><p>Now that we have converted the text into a list of vectors , we need to add positional features to this embedding. This makes sure that we maintain the structure of the text.</p><h4>Types of Tokenization : What are the ways we can split text to tokens?</h4><ol><li><strong>Whitespace/Word based Tokenization (Naive)<br>Idea: </strong>split the input text based on whitespace. <br>- While it is easy to implement, but would need a really large vocab to fit all the words. <br>- It is not very expressive and effective, as similar words (<em>dog</em>, and <em>dogs) , </em>spelling mistakes won’t be easily captured.<br>- Composite words would need seperate tokens. Some of these words would be really rare.</li><li><strong>Character based Tokenization : <br>Idea : </strong>Convert the text into individual character in a system like unicode, and<strong> </strong>keep a token for each character. (Apple — -tokenizer — -&gt; A,p,p,l,e). Each of this character can be converted into its unicode integer.<br>- While this is expressive, it would still need a large vocab to keep a count of all unicode characters.<br>- Only characters do not capture the complex relationship which builds words.</li><li><strong>Byte Pair encoding (used in most modern tokenizers).<br>Idea: </strong>Convert the unicode encodings to bytes. We first learn the vocabulary based on the training data. <br>- This helps with capturing the underlying word/character frequency and also making the model more expressive. We will explore more details about BPE in a future article.<br>- The intuition is the more frequently occurring string sequences have a higher frequency, and hence will form its own token. <br>- Less frequent words will be formed by a combination of other tokens.<br>- for example: the word ‘we’ is highly frequent in english text, which would majority of the training data. Hence it has also a relatively low token id (581) from a total of about 150k tokens in the GPT-5 tokenizer.</li></ol><h4>Loading and using open-source tokenizer</h4><p>You can load a open-source-model’s tokenizer, and explore the tokens and ids using the following code. You can refer to a list of models and check the tokenizer to get idea on how it works.</p><pre>from transformers import AutoTokenizer<br><br><br># 1. Load your local tokenizer<br>tokenizer = AutoTokenizer.from_pretrained(model_checkpoint)<br><br>text = &quot;We will learn how model converts input text to integer ids. My name is Viraj &quot;<br><br># 2. Convert text to textual tokens (the strings)<br>tokens = tokenizer.tokenize(text)<br><br># 3. Convert tokens to their unique IDs (the integers)<br>token_ids = tokenizer.convert_tokens_to_ids(tokens)<br><br># Display the results clearly<br>print(f&quot;Original Text: {text}\n&quot;)<br>print(f&quot;{&#39;Token&#39;:&lt;15} | {&#39;Token ID&#39;:&lt;10}&quot;)<br>print(&quot;-&quot; * 28)<br><br>for token, token_id in zip(tokens, token_ids):<br>    print(f&quot;{token:&lt;15} | {token_id:&lt;10}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0VWh3w9-TxaoRFISwTZFmQ.png" /><figcaption><strong>tokenzation with phi-3.5 tokenizer:</strong> The word <strong>Viraj</strong> would be relatively rare in the pretraining text, and hence is split into <strong>V</strong>,<strong>ira</strong> and <strong>j.</strong></figcaption></figure><p>You can check the Vocab size (total unique tokens) of the tokenizer</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eCowq9dnDdtotz4wnjcqJw.png" /></figure><p>The tokenizer also has some special tokens, we will check a list of these special tokens</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*og-z7K2XMmuvRpr7HyWV7g.png" /></figure><p>You can get the models context size with the tokenizer (context size is the max number of tokens a model can process, input plus the output tokens)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GJhP1rizzZS-rJagkgw70g.png" /></figure><p>You can get the dictionary of tokens and their ids</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lLb_PDOrnKyjD-kRYdPC6w.png" /></figure><p>In the next article, we will explore Byte pair encoding in more detail.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80ba595b166e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Artificial Hive-mind : why over reliance on LLMs based outputs for your information can skew your…]]></title>
            <link>https://viraajkadam.medium.com/artificial-hive-mind-why-over-reliance-on-llms-based-outputs-for-your-information-can-skew-your-e0cc6ddc8d7f?source=rss-9480ce2d902d------2</link>
            <guid isPermaLink="false">https://medium.com/p/e0cc6ddc8d7f</guid>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <dc:creator><![CDATA[Viraj Kadam]]></dc:creator>
            <pubDate>Mon, 26 Jan 2026 13:38:57 GMT</pubDate>
            <atom:updated>2026-01-26T13:38:57.496Z</atom:updated>
            <content:encoded><![CDATA[<h3>Artificial Hive-mind : why over reliance on LLMs based outputs for your information can skew your thinking to a narrow range.</h3><p><em>LLMs are being used for a wide variety of reasons, from commercial and work related tasks, to personal tasks,planning and advice. A recent OpenAI survey reveals that there is a growing trend (about 49 % of total consumer usage) of people using ChatGPT as a advisor.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/0*b3VzUWxd1CB42Pfj.png" /><figcaption><a href="https://beeculture.com/the-hive-mind/">source</a></figcaption></figure><p><em>This has tremendous societal implications, as growing usage suggests people will depend on LLMs more and more for their information needs. The positive impacts are great, offering quick and fast solutions to questions and problems.</em></p><p><em>But the negative implications of completely relying on LLMs to get to the answer, without going through the process of understanding and struggling with the ideas is also massive, as it completely bypasses the learning journey involving ideation and exploration.</em></p><p><em>Another key issue is mode collapse, where the model can generate similar kind of responses, leading to loss of diversity of thought. We will explore the paper Artificial Hivemind in this blog which addresses this.</em></p><p><strong>What does the paper say ?</strong></p><p>LLMs struggle with generating diverse creative content, and over reliance on LLMs via long term use can lead to homogenisation of response and thought patterns in humans due to repeated exposure to such outputs.</p><p>Hence the premise states that exposure to a limited set of outputs, which is observed in LLMs, can lead to limiting ideas in humans due to over reliance on these outputs.</p><h4><strong>Artificial Hive-mind effect in LLMs</strong></h4><p><strong>Concept : Mode collapse in LLMs</strong></p><p>Mode collapse is a phenomenon observed in Generative models, where the generations are limited to only a few variants, than the plausible outputs that are possible to that scenario.</p><p>For example, lets say you ask a LLM to solve a particular problem that can have multiple plausible solutions. In case of a mode collapse scenario, the model outputs very similar outputs, not exploring the other possible ways.</p><p><strong>What is a hive-mind ?</strong></p><p>Merriam-webster defines hive-mind as :</p><blockquote>the collective mental activity expressed in the complex, coordinated behavior of a colony of social insects (such as bees or ants) regarded as comparable to a single mind controlling the behavior of an individual organism.</blockquote><p>hence, hive-mind refers to homogenisation of ideas and thoughts.</p><h4>The Dataset of open ended question-Infinity Chat</h4><p>The authors create a dataset of 26-k open ended questions, which has multiple plausible answers, spanning across different about 6 major categories .</p><p>This is different from most alignment dataset, which prioritise on a single correct response over diversity of answers and multiple answers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7zbwdouvqATg5EAPbKB37w.png" /><figcaption>Infinity-Chat : <a href="https://arxiv.org/pdf/2510.22954">source</a></figcaption></figure><p><strong>Inter model homogeneity</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*RazH3OAfFjn4W-eFHvaw2w.png" /><figcaption><a href="https://arxiv.org/pdf/2510.22954">Source</a></figcaption></figure><p>The authors sampled 50 responses per model for each of the prompt, using high stochasticity to generate diverse outputs (p = 0.9 , temperature = 1.0).</p><p>Inspite of this, the model outputs for open ended questions are highly similar, and for about 79 % cases, the average cosine similarity between responses exceed 0.8 .</p><p><strong>Intra model homogeneity</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-9UP3GzbqU-H8lUoEI49yg.png" /><figcaption><a href="https://arxiv.org/pdf/2510.22954">source</a></figcaption></figure><p>The authors also find that different model sizes and families also suffer from this repetition of ideas, sometimes sharing significant phrase overlaps with other models.</p><p>The average output similarity between different models was found to be between 71 to 82 percent.</p><p>The model outputs showed a significant phrase overlap, even in case of large output spaces.</p><p>Beyond surface level similarity, these models also show a sematic overlap of ideas. The models seem to convey the same ideas, with a different paraphrasing (see the image above).</p><h4>Resources</h4><ol><li>Artificial-Hivemind paper : <a href="https://arxiv.org/abs/2510.22954">https://arxiv.org/abs/2510.22954</a></li><li>How people are using chatgpt: <a href="https://openai.com/index/how-people-are-using-chatgpt/">https://openai.com/index/how-people-are-using-chatgpt/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e0cc6ddc8d7f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What are GPUs made up of, and why are they so fast for machine learning workflows?]]></title>
            <link>https://viraajkadam.medium.com/what-are-gpus-made-up-of-and-why-are-they-so-fast-for-machine-learning-workflows-66de567b6ef1?source=rss-9480ce2d902d------2</link>
            <guid isPermaLink="false">https://medium.com/p/66de567b6ef1</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[gpu]]></category>
            <category><![CDATA[nvidia]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[gpt]]></category>
            <dc:creator><![CDATA[Viraj Kadam]]></dc:creator>
            <pubDate>Mon, 22 Dec 2025 13:48:08 GMT</pubDate>
            <atom:updated>2025-12-22T13:48:08.819Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/625/0*vFK2EtR6oGnYweAZ.jpg" /><figcaption>Nvidia H100 GPU : <a href="https://developer.nvidia.com/blog/nvidia-hopper-architecture-in-depth/">source</a></figcaption></figure><p>GPUs are the workhorses of all the modern machine learning workflows and models. In this blog, we will explore what are GPUs actually made up of, giving insights into how they work.</p><p>We will also learn how to estimate the compute capacity of GPUs from their specification, which will help us estimate the compute required for various models and systems.</p><h4>GPUs vs CPUs</h4><p>GPUs were originally designed to render graphics, whereas CPUs are general purpose computing devices made for controlling logical flow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UERF8J4pExauyMv67YGvCg.png" /><figcaption><a href="https://cvw.cac.cornell.edu/gpu-architecture/gpu-characteristics/design">Image Source</a></figcaption></figure><p>Hence,</p><ol><li>CPUs are designed to handle more complex workflows through multitasking and serial processing, whereas GPUs excel at computational tasks that can be parallelized.</li><li>GPUs have significantly more computational units compared to CPUs.</li></ol><p><em>Hence, GPUs have a lot of computational cores, and a very high performance compared to a CPU, often greater in magnitudes of order. GPUs also have a higher bandwidth memory, enabling faster transfer of data.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1GLqZvTOzYI174Ss.jpg" /><figcaption><a href="https://bizon-tech.com/blog/best-computer-3d-modeling-rendering">Image Source</a></figcaption></figure><p>We can divide the GPU mainly into two main sections. One pertains to the computational units (one that does the matrix multiplications), while the other section manages the memory (model weights and data stored on the GPU).</p><p><strong><em>A) Compute Components :</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BYxB78AYOqJgJVjPDK2G1Q.png" /><figcaption><a href="https://cvw.cac.cornell.edu/gpu-architecture/gpu-characteristics/threadcore">Source</a></figcaption></figure><ol><li><strong>Thread</strong> : Is the most atomic element in a GPU, tasked with execution of instruction on data. A thread is grouped into Warps.</li><li><strong>Warp</strong> : threads are grouped into warps for execution at runtime for SIMT (single instruction, multiple threads) execution. These threads are bundled in a group of 32 threads (32 because of Nvidia’s hardware).</li><li><strong>Kernel (software)</strong> : A function meant to be executed on a GPU in parallel is called as a kernel.</li><li><strong>Streaming Multiprocessors (SM)</strong> : On a GPU, a kernel is executed by one or more SMs. SMs are the hardware homes of CUDA cores, arranged into groups to 32 to execute warps. The number of SMs that a GPU will call to execute a kernel call depends on number of thread blocks defined in the call. <br>A SM is analogous to a core in a cpu, and will have its set of memory and caches.</li></ol><p><strong><em>B) Memory Components :</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G2u9OJ4XU-LV1NbHua1QFw.png" /><figcaption>from : <a href="https://cvw.cac.cornell.edu/gpu-architecture/gpu-memory/memory_levels">https://cvw.cac.cornell.edu/gpu-architecture/gpu-memory/memory_levels</a></figcaption></figure><ol><li><strong>Global Memory</strong> : Represents the global memory in a GPU, which is analogous to RAM (rapid access memory) in a CPU. When we talk about GPU memory in specifications, this is the memory we refer to . (example : <a href="https://www.nvidia.com/en-in/geforce/graphics-cards/50-series/rtx-5090/">Nvidia RTX 5090</a> has 32 GB of global memory.)</li><li><strong>L2 Cache</strong> : L2 cache helps retaining data between the hosts memory to the global memory, and from the global memory to SMs, for faster subsequent loading and transfer of data. There is a single L2 cache in a GPU.</li><li><strong>Textured and Constant Memory: </strong>These are ‘read only’ type of memories, that are used to store constant values, for extended accesiblility.</li><li><strong>Local Memory</strong> : These are specially allocated spaces in the global memory assigned to each SM (core). When the L1 cache from a SM spills, the data can be moved to these allocated spaces.</li><li><strong>Streaming Multiprocessing memory (core)</strong> : <br>Similar to a CPU core, a SM functions as a grouped computational unit within a GPU, and has its own set of memories. <br>1. <strong>Register</strong> : Stores data to be fed to the CUDA cores for computation.<br>2. <strong>L1 Cache</strong> : Serves as on chip storage for SMs, helping fast access to the data that has been loaded onto the main memory. It also serves as a intermediate between register and main memory.<br>3. <strong>Common memory</strong> : Is stored in similar space as L1 cache, but the memory is accesible to all the threads in the SM, allowing threads to communicate and share data between themselves.<br>4. <strong>Constant Caches</strong> : caches pertaining to store read only variables stored in global memory.</li></ol><h4>There are different types of cores in a GPU</h4><ul><li><strong>MultiPurpose CUDA cores</strong> : CUDA cores are general computational units which are the workhorses of Nvidia GPUs, handling tasks that can be parallelised using SIMT (single instruction, multiple threads) . These CUDA cores can handle thousands of parallel threads.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uYG7RJfaTXqKxrCGtHtKPw.png" /><figcaption><a href="https://www.wevolver.com/article/tensor-cores-vs-cuda-cores#decoding-cuda-cores:-the-versatile-workhorses">source</a></figcaption></figure><ul><li><strong>High Performance Computing with Tensor cores </strong>: Tensor cores are specialised processing units that can perform fast matrix multiplications. Hence the primary function of a Tensor core is to perform convolutional and matrix multiplication operations efficiently and fast, achieving high throughput compared to cuda cores. Tensor cores power a lot of modern NLP, HPC and ML applications involving complex models and simulations.</li></ul><h4>Understanding Nvidia’s V100 GPU</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-kqRqxM3KOhfpmUhm1HbLA.png" /><figcaption><a href="https://cvw.cac.cornell.edu/gpu-architecture/gpu-example-tesla-v100/volta_block">source</a></figcaption></figure><p>V100 is a older GPU, with the following specifications:</p><ul><li><strong>84 Streaming multiprocessors (SMs)</strong></li><li>Each SM has <br>1.<strong> CUDA cores<br></strong><em>64 FP32 CUDA cores.<br>64 FP16 CUDA cores.<br>32 FP64 CUDA cores.</em><br>2. <strong>8 Tensor Cores</strong> <br>3. <strong>16 Special Function Units</strong><br>4. <strong>4 Texture units</strong></li><li><strong>32 GB </strong>of high-bandwidth HBM2 memory per device, providing peak memory bandwidth of <strong>900 Gb/sec</strong> across memory stacks.</li><li>Host to device memory transfer bandwidth <strong>32 Gb/sec</strong> ( facilitated by 16 PCle3 connections)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6iWt2lwsNw5Z_uz1mY5H4g.png" /><figcaption><a href="https://cvw.cac.cornell.edu/gpu-architecture/gpu-example-tesla-v100/tesla">Calculating Flops</a></figcaption></figure><ul><li>Peak Floating Point Operations (FLOPS) : <br>1. FP32: 15.7 Tflops/sec (i.e. 15.7 x 10¹² floating point operations)<br>2. FP64 : 7.8 Tflops/sec.</li></ul><h4>Understanding the specification of a Modern GPU : Nvidia H100</h4><p>H-100 is a commonly used enterprise GPU, offering significant performance gains (of upto 30x) over its predecessor A-100.</p><p>It is based on Nvidia’s new Hopper architecture. We will break down its specifications and its understand the implications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LKTQlFdDAG6RXIP0pC4mHg.png" /><figcaption><a href="https://developer.nvidia.com/blog/nvidia-hopper-architecture-in-depth/">source</a></figcaption></figure><p>A H100 GPU (GH100) has:</p><ul><li>8 GPCs, 72 TPCs (9 TPCs/GPC), 2 SMs/TPC, 144 SMs per full GPU.</li><li>128 FP32 CUDA Cores per SM, 18432 FP32 CUDA Cores per full GPU.</li><li>64 FP64 CUDA Cores per SM, 7296 cores for ful GPU.</li><li>4 fourth-generation Tensor Cores per SM, 576 per full GPU.</li><li>6 HBM3 or HBM2e stacks, offering about 3 Tb/Sec of peak memory bandwidth.</li><li>60 MB L2 cache.</li></ul><p>This offers significantly higher computational power over the previous generations, making them a frontier GPU model for modern machine learning workflows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lDWGtomEFjWG-CegcJ2B-g.png" /><figcaption>H100 offerings: <a href="https://www.nvidia.com/en-in/data-center/h100/">source</a></figcaption></figure><p>In the next post, we will understand how to estimate the GPU required for loading and optimally using a machine learning model. Thanks for reading !</p><h4>Resources</h4><ol><li><a href="https://www.tomshardware.com/news/nvidia-h200-gpu-announced">Nvidia H200 GPU</a></li><li><a href="https://cvw.cac.cornell.edu/gpu-architecture">GPU Architecture (Cornell)</a></li><li><a href="https://developer.nvidia.com/blog/nvidia-hopper-architecture-in-depth/">Nvidia Technical Blog: Hopper Architecture</a></li><li><a href="https://www.wevolver.com/article/tensor-cores-vs-cuda-cores#decoding-cuda-cores:-the-versatile-workhorses">Tensor vs Cuda cores</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66de567b6ef1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mapping the urbanization and population growth of a city (Pune) using google earth engine and…]]></title>
            <link>https://viraajkadam.medium.com/mapping-the-urbanization-and-population-growth-of-a-city-pune-using-google-earth-engine-and-7c68c967dc84?source=rss-9480ce2d902d------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c68c967dc84</guid>
            <category><![CDATA[urban-planning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[earth-observation]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Viraj Kadam]]></dc:creator>
            <pubDate>Sat, 08 Nov 2025 09:20:42 GMT</pubDate>
            <atom:updated>2025-11-08T09:20:42.058Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mapping the urbanization and population growth of a city (Pune) using google earth engine and python.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ry5dzXv1sfn4jbkc2RCyyA.png" /></figure><p><em>Pune city has seen drastic growth through the years, leading to rapid urbanization and population growth. In this blog, we will explore how to use google earth engine to plot urbanization and population growth, using datasets available on google earth engine.</em></p><p>Link to the colab notebook : <a href="https://colab.research.google.com/drive/1ouNb3yDDV8F5s6Ys3tMNYl_qx-sfs6Ht?authuser=1#scrollTo=L5B7d4mUzJ2s">https://colab.research.google.com/drive/1ouNb3yDDV8F5s6Ys3tMNYl_qx-sfs6Ht?authuser=1#scrollTo=L5B7d4mUzJ2s</a></p><h4>Finding the district boundaries</h4><p>For getting the district boundaries of pune, we can use the <a href="https://developers.google.com/earth-engine/datasets/catalog/FAO_GAUL_SIMPLIFIED_500m_2015_level2">Global Administrative Unit Layers 2015</a> dataset available on google earth engine. This will allow us to filter data , getting relevant data for Pune. The dataset description is provided below:</p><p><em>The Global Administrative Unit Layers (GAUL) compiles and disseminates the best available information on administrative units for all the countries in the world, providing a contribution to the standardization of the spatial dataset representing administrative units.</em></p><p>for getting the vector bounds, we initialize the dataset, and filter for Pune.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L0rMgrTt48AX5aTXyWy6ww.png" /><figcaption>Getting the administrative boundaries of the city using boundaries dataset.</figcaption></figure><p>Plotting with the following vector dataset with folium, we get</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*ofVi3dBL35z7AHcRLwy_xA.png" /><figcaption>District Boundaries of Pune</figcaption></figure><h4>Converting ee.Image objects to np arrays for plotting</h4><p>When we are using earth engine, we deal with collections and image objects. A Collection object is a dataset collection of multiple images.</p><p>for plotting in notebook, we will convert these image objects to a array using gee_map library.</p><pre>def eeImage_2_array(image,<br>                    boundaries,<br>                    scale = 1000):<br>  &quot;&quot;&quot;convert a Image to np array&quot;&quot;&quot;<br>  # roi = ee.Geometry.MultiPolygon(boundaries)<br>  raw_np_array = geemap.ee_to_numpy(image,<br>                                    region=boundaries,<br>                                    scale=scale)<br>  # The default output might have an extra dimension, so we squeeze it<br>  raw_np_array = np.squeeze(raw_np_array)<br>  return raw_np_array</pre><h4>Population change</h4><p>For plotting the population density changes, we will use the <a href="https://developers.google.com/earth-engine/datasets/catalog/JRC_GHSL_P2023A_GHS_POP">GHSL: Global population surfaces</a>. This dataset is derived from disaggregating census and administrative units to grid cells, to account for residential population density. The population layer has raster images for every 5 years from 1975 to 2030.</p><p>for getting the relevant year image, we can use the following function</p><pre>def get_population_ee_image(year:int,<br>                            ):<br>  path = f&quot;JRC/GHSL/P2023A/GHS_POP/{year}&quot;<br>  im = ee.Image(path)<br>  im_masked = im.updateMask(im.gt(0))<br>  return im_masked</pre><p>for plotting these images, we can use matplotlib (detailed code in the notebook)</p><pre># get the relevant image, converting into a array<br>pop1990 = eeImage_2_array(get_population_ee_image(1990),pune_dist,100)<br><br>#plot the numpy array<br>plot_population_density(pop1990,&quot;Population Density - 1990 (per 100 sqm)&quot;)</pre><p>plotting the rasters for a duration of 15 shows significant population density growth, and new growth around the periphery.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*0wYyEAJRyYO8RmmyIWJVag.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*x_4w3E7RrMEL1EZGqCc5Qw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*zYIPYN-lRxoqR-afeGgJdw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*x_BApHqnAbocH7rVMtL8Wg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*yZ9jz37bQ5Zf-RaxvzFj-g.png" /></figure><h4>Surface Built-Up Area Density</h4><p>For plotting the build up area density (total build up area per 100sqm), we will use the <a href="https://developers.google.com/earth-engine/datasets/catalog/JRC_GHSL_P2023A_GHS_BUILT_S">GHSL: Global built-up surface</a> . This dataset is available in intervals of 5 years, starting from 1975 to 2030 (projected).</p><p>for getting the relevant images, we will use the following function, followed by plotting them</p><pre>def get_bu_ee_image(year:int,<br>                            ):<br>  path = f&quot;JRC/GHSL/P2023A/GHS_BUILT_S/{year}&quot;<br>  im = ee.Image(path).select(&#39;built_surface&#39;);<br>  return im</pre><pre>bu2000 = eeImage_2_array(get_bu_ee_image(2000),pune_dist,100)<br>plot_surface_buildup(bu2000)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*GBTGAWK8hLg4mYPWbrJnEw.png" /><figcaption>Surface Build up density — 1975</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*M4rsqp1Mab4ZERBNJRFffA.png" /><figcaption>Surface Build up density — 2000</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*Z6BQqgwIlkoiKgxbqq8XkA.png" /><figcaption>Surface Build up density — 2010</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*4gP2F8B74Sjdxx7NPdb-Xg.png" /><figcaption>Surface Build up density — 2025</figcaption></figure><h4><strong>Urban Land use change</strong></h4><p>For plotting the landuse change pattern, we will use the <a href="https://developers.google.com/earth-engine/datasets/catalog/JRC_GHSL_P2023A_GHS_SMOD_V2-0">GHSL: Degree of Urbanization</a> dataset. This dataset is based upon Sentinel-2 and Landsat images, using a methodology recommended by UN statistical commission.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XD0qH2MB-GRKiWdsuxMd4g.png" /><figcaption>Degree of Urbanization (1975)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YBM-hr2tY-_pTfGUVSZGFg.png" /><figcaption>Degree of Urbanization (2025)</figcaption></figure><p>We can mask the other values in the dataset, and only plot the change in the urbanization (urban, semiurban and dense clusters). We will do this by masking the values that do not belong to the above mentioned classes.</p><p>We will create a gif showing the change in the values from 1975 to 2030(projected), using the code below. refer to the notebook for the full code.</p><pre>urbanization_filenames = []<br>for idx in range(human_settlements_collection.size().getInfo()):<br>  image = ee.Image(hsl_images.get(idx))<br>  year = image.getInfo().get(&quot;properties&quot;).get(&quot;system:index&quot;)<br>  title = f&quot;Classified Urbanization - {year}&quot;<br>  save_path = f&quot;./urbanization/{year}.png&quot;<br>  urbanization_filenames.append(save_path)<br>  lulc = eeImage_2_array(image,pune_dist)<br>  condition = np.isin(lulc, urban_values)<br>  urban_masked = np.where(condition, lulc, 0)<br><br>  plot_class_map(urban_masked,<br>                 urban_values,<br>                 urban_color_pallete,<br>                 urban_classes,<br>                 title = title,<br>                 save_path = save_path,<br>                 show = False)</pre><p>Using the individual images plotted for each year, we can create a GIF.</p><pre>import imageio.v3 as iio<br>import shutil<br><br>animation_output_path = &quot;./urbanization/land_use_change.gif&quot;<br><br>frames = []<br>for filename in urbanization_filenames:<br>    frames.append(iio.imread(filename))<br><br>print(f&quot;Creating animation at {animation_output_path}...&quot;)<br><br># In v3, &#39;iio.imwrite&#39; automatically handles lists of images<br>iio.imwrite(<br>    animation_output_path,  # Output file<br>    frames,                 # List of actual images (np arrays)<br>    fps=1 ,                # Frames per second,<br>    loop=0<br>)</pre><p>The output looks like the following. It shows a drastic growth in the dense urban centres and sub-urban areas.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XNRxdCmZBJOGHHTsEO0kwg.gif" /></figure><p>These datasets can be used for a whole variety of analysis around urbanization and land use changes. END!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c68c967dc84" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[General legal embedding P2: evaluating the unstructured embeddings on legal clauses.]]></title>
            <link>https://viraajkadam.medium.com/general-legal-embedding-p2-evaluating-the-unstructured-embeddings-on-legal-clauses-012a7a5c3924?source=rss-9480ce2d902d------2</link>
            <guid isPermaLink="false">https://medium.com/p/012a7a5c3924</guid>
            <category><![CDATA[embedding]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[legaltech]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Viraj Kadam]]></dc:creator>
            <pubDate>Sat, 11 Oct 2025 10:43:46 GMT</pubDate>
            <atom:updated>2025-10-11T10:43:46.927Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jNkfDf9_WnBLm2oocfpvqw.png" /><figcaption>Similar clauses visualised against a background of other clauses.</figcaption></figure><p><em>In the previous post , we discussed why we need to train a domain specific embedding model, different ways to train a embedding model,and how we can use TSDAE to train a generic embedding model in a unsupervised way for the legal domain. (</em><a href="https://medium.com/@viraajkadam/general-legal-embedding-model-training-on-ledgar-dataset-using-tsdae-26825384a13a"><em>Training legal embedding with TSDAE</em></a><em>).</em></p><p><em>In this post, we will evaluate the model, and try to discover the properties of the generated embeddings to evaluate if the model has learned anything meaningful.</em></p><p><em>Since the model is trained in a unsupervised way, there is no specific metric that can be tracked. Hence we will rely on other methods like clustering and checking the text clause types.</em></p><h4>About the dataset (LEDGAR)</h4><p>The ledgar dataset is a annotated dataset, consisting of legal clauses and their corresponding categories.</p><p>For the un-initiated, a legal document such as a contract is composed of a lot of different clauses, or conditions. These clauses can be classified into certain classes. The LEDGAR dataset has the text labelled into 100 such clauses used in contracting.</p><p>For the evaluation, we will use about 10,000 examples from the test set, which were not a part of the training examples.</p><h4>Eval 1: How do the clauses look when plotted together?</h4><p><strong>What :</strong> For this evaluation, we will aim to plot the clauses together, and see how they look with respect to each other. One property to expect here is similar clause types should be clustered close to each other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F3S3CWxC5MXU2nPkKWXB2g.png" /></figure><p><strong>How :</strong> For this generate embedding of the clauses from the test set, followed by dimensionality reduction of the embeddings, so that we can visualize them in 2D. We will use TSNE (which tries to project higher dimensional embeddings to a lower dimensional space, while preserving the properties)</p><p>Then we plot the similar clauses, and visualize them. Following are a few groups of similar clauses plotted together against a background of all the clauses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nK1RWodDPazxLyqwoNzyjQ.png" /><figcaption>Term and termination clauses.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zc6f7ccbWLY3Y5_60Lxh_g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2ipQy2G0e5419XeHyxaOGQ.png" /><figcaption>Definitions and similar clauses.</figcaption></figure><h4>Eval 2 : Vector search using clause name as keywords</h4><p><strong>What</strong> : We will embed the clauses in the test set using our trained embedding model, followed by trying to retrieve relevant clauses based on keywords using hybrid search, as we would in a RAG application.</p><p><strong>How : </strong>We start by creating a qdrant collection, followed by indexing the vectors in the collection using the trained embedding model as vectorizer.</p><ol><li>Create qdrant collection.</li></ol><pre>import qdrant_client<br>from qdrant_client import models<br>from fastembed import TextEmbedding, SparseTextEmbedding, LateInteractionTextEmbedding<br><br><br><br>#create qdant client in memory<br>client = qdrant_client.QdrantClient(&quot;:memory:&quot;)<br><br><br>def create_qdrant_collection(collection_name:str,<br>                             client = client):<br>    client.create_collection(collection_name=collection_name,<br>    vectors_config={<br>        &quot;text-dense&quot;:models.VectorParams(size=CFG.embedding_size, <br>                                                     distance=qdrant_client.models.Distance.COSINE,<br>                                                    on_disk=True),<br>    },<br>    sparse_vectors_config={<br>        &quot;bm25&quot;: models.SparseVectorParams(modifier=models.Modifier.IDF,)}<br>                            )<br>                            <br>    # #get collection info <br>    info = client.get_collection(collection_name=collection_name)<br>    print(f&quot;created collection - {info}&quot;)<br>    return True<br><br><br>create_qdrant_collection(CFG.clause_collection)</pre><p>2. Create BM25 vectors</p><pre># que-drant bm25<br>bm25_embedding_model = SparseTextEmbedding(&quot;Qdrant/bm25&quot;)<br><br>#get bm25<br>bm25_embeddings = list(bm25_embedding_model.passage_embed(all_texts))<br>bm25_embeddings[0].values.shape</pre><p>3. Create vectors from the trained model</p><pre>from sentence_transformers import SentenceTransformer<br><br><br>model_checkpoint = &quot;/kaggle/input/legal_bert_embedding_ledgar_tsdae/transformers/default/1/output/training_tsdae-legal-bert-base-uncased-8-2025-03-11_12-16-56_final&quot;<br>model = SentenceTransformer(model_checkpoint)<br><br>def get_sentence_embeddings(sentences:[str,],<br>                            model = model,<br>                           show_progress_bar=True,<br>                           batch_size = 64,<br>                           precision = &quot;float32&quot;):<br>    embeddings = model.encode(<br>                sentences,<br>                batch_size=batch_size,<br>                show_progress_bar=show_progress_bar,<br>                convert_to_numpy=True,<br>                precision=precision,<br>                normalize_embeddings=bool(precision))<br><br>    return embeddings<br><br>all_text_embeds = get_sentence_embeddings(ledgar_lexglue_test[&quot;text&quot;])</pre><p>4. Generate unique id for each text</p><pre>import uuid<br><br>def generate_uuid(text: str, namespace: uuid.UUID = uuid.NAMESPACE_DNS) -&gt; str:<br>    &quot;&quot;&quot;<br>    Generate a UUID for a given string using UUID5 (SHA-1 hash-based).<br>    <br>    Args:<br>        text (str): The input string.<br>        namespace (uuid.UUID, optional): A namespace UUID to ensure uniqueness within a scope.<br>                                        Defaults to uuid.NAMESPACE_DNS.<br>    <br>    Returns:<br>        str: The generated UUID as a string.<br>    &quot;&quot;&quot;<br>    return str(uuid.uuid5(namespace, text))<br><br><br>all_texts = ledgar_lexglue_test[&quot;text&quot;]<br>all_labels = df_ledgar_test[&quot;label_name&quot;].to_list()<br>cluster_ids = df_ledgar_test[&quot;cluster_category&quot;].to_list()<br><br><br><br>uuids = [generate_uuid(text) for text in all_texts]<br>len(all_texts)<br></pre><p>5. Index the data into a qdrant</p><pre>import tqdm<br><br>batch_size = 128<br>for start in tqdm.tqdm(range(0,len(all_texts),batch_size)):<br>    end = start + batch_size<br>    Points = [qdrant_client.models.PointStruct(id = uuids[idx],vector={&quot;text-dense&quot;:all_text_embeds[idx,:],<br>                                                                       &quot;bm25&quot;: bm25_embeddings[idx].as_object()},<br>                                              payload={&quot;text&quot;:all_texts[idx],<br>                                                       &quot;labels&quot;:all_labels[idx],<br>                                                       &quot;cluster_id&quot;:cluster_ids[idx]}) for idx in range(start,min(end,len(all_texts)))]<br><br>    client.upsert(collection_name=f&quot;{CFG.clause_collection}&quot;,<br>                points = Points)<br></pre><p>6. Retrival using hybrid retrieval</p><pre>def query_clause(query:str):<br>    query_vector_dense = get_sentence_embeddings([query,])[0,:]<br>    sparse_query_vector = list(bm25_embedding_model.passage_embed([query,]))[0]<br>    <br>    prefetch = [<br>        models.Prefetch(<br>            query=query_vector_dense,<br>            using=&quot;text-dense&quot;,<br>            limit=200,<br>        ),<br>        models.Prefetch(<br>            query=models.SparseVector(**sparse_query_vector.as_object()),<br>            using=&quot;bm25&quot;,<br>            limit=200,<br>        ),<br>    ]<br>    <br>    results = client.query_points(<br>        CFG.clause_collection,<br>        prefetch=prefetch,<br>        query=models.FusionQuery(<br>            fusion=models.Fusion.RRF,<br>        ),<br>        with_payload=True,<br>        search_params=models.SearchParams(hnsw_ef=512, exact=False),<br>        limit=100,<br>    )<br><br>    return results</pre><p>Results: we were able to retrieve relevant clauses for the keywords in question.</p><pre>query = &quot;bribery, anti-corruption&quot;<br><br>searched_points = query_clause(query)<br>cat_counter = []<br>for point in searched_points.points:<br>    cat_counter.append(point.payload.get(&quot;labels&quot;))<br><br>pd.Series(cat_counter).value_counts().head(10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*9rHEMYGwilxn0zSrWUttmA.png" /></figure><pre>query = &quot;indemnify&quot;<br>searched_points = query_clause(query)<br><br>cat_counter = []<br>for point in searched_points.points:<br>    cat_counter.append(point.payload.get(&quot;labels&quot;))<br><br>pd.Series(cat_counter).value_counts().head(10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*UUZh5Bgjvx7j9S6MPVRm4w.png" /></figure><h4>Where to go from here ?</h4><p>This model trained unsupervised from LEDGAR data can be used as a base model, for general representation of legal texts. This can be further trained on the domain data using other supervised techniques for specific applications.</p><h4>Resources</h4><ul><li>TSDAE paper : <a href="https://arxiv.org/abs/2104.06979">https://arxiv.org/abs/2104.06979</a></li><li>Training Blog : <a href="https://medium.com/@viraajkadam/general-legal-embedding-model-training-on-ledgar-dataset-using-tsdae-26825384a13a">https://medium.com/@viraajkadam/general-legal-embedding-model-training-on-ledgar-dataset-using-tsdae-26825384a13a</a></li><li>Training Notebook : <a href="https://www.kaggle.com/code/virajkadam/legal-embedding-model-p2-base-tsdae-model">https://www.kaggle.com/code/virajkadam/legal-embedding-model-p2-base-tsdae-model</a></li><li>Evaluation Notebook : <a href="https://www.kaggle.com/code/virajkadam/evaluating-ledgar-tsdae-embedding-model">https://www.kaggle.com/code/virajkadam/evaluating-ledgar-tsdae-embedding-model</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=012a7a5c3924" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Small Language Models are the future of Agentic AI]]></title>
            <link>https://viraajkadam.medium.com/why-small-language-models-are-the-future-of-agentic-ai-a070cbf29698?source=rss-9480ce2d902d------2</link>
            <guid isPermaLink="false">https://medium.com/p/a070cbf29698</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[gpt]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[Viraj Kadam]]></dc:creator>
            <pubDate>Sat, 20 Sep 2025 13:36:01 GMT</pubDate>
            <atom:updated>2025-09-20T13:36:17.851Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A lot of current agentic applications being build and used today involve using frontier LLMs, attributed to their ability to do task a wide varitey of tasks (generalisation) .</em></p><p><em>But using LLMs is a significant bottleneck, as it involves a dependancy on external APIs, also adding to privacy, cost and latency issues. Another paradigm in developing agentic application is using smaller, task specific models in the agentic workflows, significantly improving the above metric, while customising the application to own needs.</em></p><p><em>This blog will discuss the ideas from the paper by Nvidia titled why </em><a href="https://arxiv.org/pdf/2506.02153"><em>small language models are the future of agentic AI</em></a><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f12-xJ7IarUH3zuOVCw8EA.png" /></figure><h4><strong>How big is the market for serving LLMs as a service?</strong></h4><p>The current market, mostly driven by using large language models because of their ability to perform a wide variety of tasks. The investment in the year 2024 for this was to the tune to <strong>56 billion dollars</strong>, while the market was about <strong>5.6 Billion dollars</strong>.</p><p>Hence there is a 10 times more investments than the actual market size, attributing to a projected future returns.</p><h4><strong>What are Small Langauge Models ?</strong></h4><p>There is no fixed rule on what models can be labelled as small language models (will be referenced as SLM, hereafter). In general, SLMs have fewer parameters.</p><p>But in general we can call language models with the following characteristics as SLMs</p><ul><li>Can be hosted on consumer grade electronic devices (consumer GPUs, CPUs, phones etc).</li><li>Are able to support low latency application for single user applications</li><li>The parameter size is about 10 Billion or lesser.</li></ul><h4>Few popular SLMs</h4><p>following is a list of few of the popular SLMs that are widely used.</p><ul><li><a href="https://huggingface.co/microsoft/phi-4"><strong>Microsoft PHI family</strong></a> : small, capable models ranging from about 1B to 14B. Also offering multimodal models.</li><li><a href="https://huggingface.co/nvidia/collections"><strong>Nvidia Nemotron family</strong></a><strong> </strong>: Offers open source, enterprise models, ranging from 1.5 B to about 12 B and more. Mamba based SSM architecture.</li><li><a href="https://huggingface.co/collections/HuggingFaceTB/smollm3-686d33c1fdffe8e635317e23"><strong>HuggingFace SmolLM</strong></a> : small , capable models ranging from 125M to 1.7 B parameters.</li><li><a href="https://huggingface.co/deepseek-ai/DeepSeek-R1-Distill-Llama-8B"><strong>Deepseek R1 distill</strong></a><strong> : </strong>DeepSeek-R1-Distill is a family of reasoning models featuring 1.5–8bn sizes, trained on samples generated by DeepSeek-R1.</li></ul><h4>Why SLMs, and not LLMs maybe the future of agentic applications</h4><ol><li><strong>Agents expose a very narrow LM functionality :<br></strong>The success and wide adoption of LLMs majorly come from their ability to perform a wide variety of general tasks. <br>But most of the agentic applications do not require the breadth of these abilities, as the workflows involve tasks that are repetitive and re-produceable. A smaller, efficient model would be much more apt for such kind of tasks.</li><li><strong>SLMs are sufficiently powerful to handle agentic AI workflows. <br>- </strong>Small language models have sufficient complexity to handle even complex tasks. Using modular system, SLMs can be utilized well in agentic workflows.<br>- They can be also adapted well to tasks, using finetuning.</li><li><strong>SLMs are much more cost effective for agentic applications<br></strong>- Can be deployed on edge devices, or on consumer hardware.<br>- A 7 Billion param SLM might be 10–30 times more cheaper (in latency and cost) than a LLM of 70–170 Billion params.</li><li><strong>SLMs are much more adaptable <br></strong>- Inherently more flexible than larger LLMs , as they can be easily trained, and adapted to own data. <br>- can be deployed as per requirements, without having to rely on external APIs.</li><li><strong>Agentic Application require a close behavior alignment :<br>- </strong>This is much more easier to achieve , than using LLMs.</li><li><strong>Agentic applications are naturally heterogenous : <br></strong>- The most important point, developing applications should involve using appropriate model according to the complexity of task in hand.<br>- Most of the application will involve modular tasks, which should involve using models suited to the tasks, developing a heterogeneous system of models.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a070cbf29698" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>