<?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 Abhinavgopinadh on Medium]]></title>
        <description><![CDATA[Stories by Abhinavgopinadh on Medium]]></description>
        <link>https://medium.com/@abhinavgopinadh?source=rss-63bf040eecba------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*AnF9bIgzEAGulFSJ</url>
            <title>Stories by Abhinavgopinadh on Medium</title>
            <link>https://medium.com/@abhinavgopinadh?source=rss-63bf040eecba------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 14:16:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@abhinavgopinadh/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[Making Qwen2.5–0.5B]]></title>
            <link>https://medium.com/@abhinavgopinadh/making-qwen2-5-0-5b-4222ddbb7b8b?source=rss-63bf040eecba------2</link>
            <guid isPermaLink="false">https://medium.com/p/4222ddbb7b8b</guid>
            <category><![CDATA[vllm]]></category>
            <category><![CDATA[quantization]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[awq]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Abhinavgopinadh]]></dc:creator>
            <pubDate>Tue, 01 Dec 2026 16:20:33 GMT</pubDate>
            <atom:updated>2026-12-01T17:54:42.123Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Making Qwen2.5–0.5B Smaller and Faster: My Hands-On AWQ Quantization Experiment along with Mathematics behind it</strong></h3><h3>Introduction</h3><p>Large Language Models (LLMs) are becoming increasingly powerful, but running them efficiently is still a challenge. Even relatively small models consume considerable memory, and deploying larger models on consumer GPUs can become difficult.</p><p>One way to address this problem is <strong>quantization</strong>.</p><p>Quantization reduces the numerical precision used to represent model parameters. Instead of storing every weight as a 16-bit floating-point number, we can represent weights using fewer bits, such as 8-bit or 4-bit integers.</p><p>In this experiment, I wanted to understand how this works in practice.</p><p>I selected <strong>Qwen2.5–0.5B-Instruct</strong> and used Activation-aware Weight Quantization (AWQ) to convert its weights into a 4-bit representation. I performed the experiment using Google Colab with an NVIDIA Tesla T4 GPU.</p><p>This blog documents the entire process:</p><ul><li>Understanding why quantization is necessary.</li><li>Understanding the mathematics behind AWQ.</li><li>Preparing calibration data.</li><li>Applying AWQ using LLM Compressor.</li><li>Saving and verifying the quantized checkpoint.</li><li>Comparing model size and inference performance.</li><li>Debugging issues encountered during experimentation.</li><li>Investigating why a quantized model can sometimes be slower than its FP16 counterpart.</li></ul><p>The goal was not simply to produce a smaller model. It was to understand what happens inside the quantization process.</p><h3>1. Understanding the Problem: Why Quantize an LLM?</h3><p>A neural network contains millions or billions of parameters. These parameters are usually stored as floating-point numbers.</p><p>For example, FP16 represents each parameter using 16 bits, or 2 bytes.</p><p>Consider a model containing approximately 500 million parameters.</p><p>Its theoretical weight storage requirement in FP16 is:</p><p>500,000,000 × 2 = 1,000,000,000 bytes</p><p>That is approximately 1 GB in decimal units.</p><p>If we represent the same weights using 4 bits:</p><p>500,000,000 × 0.5 = 250,000,000 bytes</p><p>The theoretical weight storage becomes approximately 250 MB.</p><p>This is a substantial reduction.</p><p>However, there is a problem.</p><p>Reducing the precision of weights introduces quantization error. If we simply round every weight to a lower precision, the model’s predictions can change.</p><p>The important question becomes:</p><p><strong>How can we reduce the number of bits used to represent model weights without significantly damaging the model’s behavior?</strong></p><p>This is where AWQ becomes interesting.</p><h3>2. What Is AWQ?</h3><p>AWQ stands for <strong>Activation-aware Weight Quantization</strong>.</p><p>It is a post-training quantization (PTQ) technique introduced in the paper:</p><p><a href="https://arxiv.org/abs/2306.00978">AWQ: Activation-aware Weight Quantization for LLM Compression and Acceleration</a></p><p>The central observation behind AWQ is that not all weight channels are equally important.</p><p>Some channels process activation values with significantly larger magnitudes. Quantization errors in these channels can have a greater influence on the model’s output.</p><p>Therefore, AWQ uses activation statistics to identify important channels and protect them from excessive quantization error.</p><p>An interesting detail is that AWQ performs weight-only quantization, but it uses activation information to decide how the weights should be transformed before quantization.</p><h3>Why not simply preserve important weights in FP16?</h3><p>One possible approach would be to identify important weights and keep them in FP16 while quantizing the remaining weights.</p><p>However, mixed-precision representations can complicate memory access and inference kernel implementation.</p><p>AWQ uses a different approach.</p><p>Instead of keeping selected weights in higher precision, it applies an equivalent scaling transformation to the activation channels and corresponding weight channels.</p><p>This allows all targeted weights to be quantized while reducing the error associated with important channels.</p><h3>3. Understanding the Mathematics Behind AWQ</h3><p>This is the most important part of the experiment.</p><p>Let’s start with a simple linear layer.</p><p>A linear layer performs:</p><p>y = Wx</p><p>Where:</p><ul><li>(W) represents the weight matrix.</li><li>(x) represents the input activation vector.</li><li>(y) represents the output.</li></ul><p>Suppose the weight matrix has the shape:</p><p><em>y</em> ∈ ℝᵐˣⁿ</p><p>and the input vector has the shape:</p><p><em>y</em> ∈ ℝⁿ</p><p>The output is:</p><p><em>y</em> ∈ ℝᵐ</p><h3>3.1 The problem with ordinary quantization</h3><p>Suppose we quantize a weight using a quantization function (Q).</p><p><strong>The Original Output:</strong></p><blockquote>y<em> = </em>Wx</blockquote><p><strong>After Quantization:</strong></p><blockquote>ŷ<em> = </em>Q<em>(</em>W<em>)</em>x</blockquote><p><strong>The Output Error Becomes:</strong></p><blockquote>E<em> = </em>Wx<em> − </em>Q<em>(</em>W<em>)</em>x</blockquote><p><strong>Or:</strong></p><blockquote>E<em> = (</em>W<em> − </em>Q<em>(</em>W<em>))</em>x</blockquote><p>This equation explains something important.</p><p>The output error does not depend only on how much a weight changes during quantization. It also depends on the activation multiplied by that weight.</p><p>Consider two weight channels:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gMXK2AK-H-2SvYQH9tNdjQ.png" /></figure><p>Their approximate contributions to the output error are:</p><p>Case A: E_A = 0.02 × 10 = 0.2<br>Case B: E_B = 0.02 × 0.1 = 0.002</p><p>Both channels have the same weight error, but Channel A produces 100 times more output error.</p><p>This is the intuition behind activation awareness.</p><p>A channel that processes larger activation values can be more sensitive to weight quantization errors.</p><h3>3.2 The scaling transformation</h3><p>AWQ uses a mathematically equivalent transformation.</p><p>For simplicity, consider one weight (w) and one activation (x):</p><p>Scaling Invariance</p><p>y = (ws)(x / s)</p><p>The result is unchanged:</p><p>(ws)(x / s) = wx</p><p>This is important because we can change the numerical distribution of weights without changing the original layer’s output.</p><p>Now Consider Quantization:</p><p>ŷ = Q(ws)(x / s)</p><p>This is important because we can change the numerical distribution of weights without changing the original layer’s output.</p><p>Now consider quantization:</p><p><em>ŷ</em> = <em>Q</em>(<em>ws</em>)(<em>x</em> / <em>s</em>)</p><p>The objective is to choose a suitable scaling factor so that the quantized result is closer to the original result.</p><h3>3.3 Why scaling helps</h3><p>A simplified symmetric quantization equation is:</p><p><em>Q</em>(<em>w</em>) = Δ · Round(<em>w</em> / Δ)</p><p>Where:</p><ul><li>(w) is the original weight.</li><li>(Δ) is the quantization step size.</li><li>Round converts the scaled value to an integer.</li></ul><p>The quantization step size is determined by the range of weights in the quantization group.</p><p>If a weight is multiplied by (s), the quantized result becomes:</p><p><em>ŷ</em> = <em>Q</em>(<em>ws</em>)(<em>x</em> / <em>s</em>)</p><p>The corresponding error is :</p><p><em>E</em> = (<em>W</em> − <em>Q</em>(<em>W</em>))<em>x</em></p><p>If scaling does not significantly change the group’s quantization step size, the error associated with that channel is approximately reduced by a factor of (1/s).</p><p>In other words, scaling up an important weight channel can reduce its relative quantization error after the inverse activation scaling is applied.</p><p>However, scaling too aggressively can affect other channels because the group quantization range may change.</p><p>Therefore, choosing the scaling factor is important.</p><h3>3.4 How does AWQ choose the scaling factor?</h3><p>AWQ uses activation statistics collected from calibration data.</p><p>Let: X represent the activation values collected from the calibration samples.</p><p>For each input channel, calculate its average absolute activation magnitude:</p><p>s_X[j] = Mean(|X_j|)</p><p>The original AWQ paper uses a scaling search space of the form:</p><p><em>s = sₓᵅ</em></p><p>Where:</p><p>0 ≤ α ≤ 1</p><p>The value of ( α) determines how aggressively the activation channels are scaled.</p><ul><li>When ( α=0), scaling is effectively the identity transformation.</li><li>When ( α) increases, channels with larger activation magnitudes receive stronger scaling.</li><li>When ( α=1), the activation-derived scaling is applied most aggressively within this search space.</li></ul><p>AWQ searches for an appropriate value of ( α) by evaluating quantization error.</p><p>The optimization objective can be written as:</p><p><em>s</em>* = arg minₛ ℒ(<em>s</em>)</p><p>A simplified output reconstruction loss is:</p><p>ℒ(<em>s</em>) = |<em>WX</em> − <em>Q</em>(<em>WS</em>⁻¹)<em>SX</em>|²</p><p>Here, (S) is a diagonal matrix containing the channel scaling factors.</p><p>The expression represents the difference between the original layer output and the quantized layer output after applying the equivalent scaling transformation.</p><p>The actual implementation includes architecture-specific mappings and additional quantization details, but this equation captures the central idea.</p><h3>3.5 What is the role of calibration data?</h3><p>AWQ needs representative input data to observe activation distributions.</p><p>It does not require a large training dataset or backpropagation.</p><p>Instead, the model processes a small calibration dataset, and the quantization algorithm collects activation statistics.</p><p>The calibration data helps answer:</p><ul><li>Which channels have larger activation magnitudes?</li><li>Which channels may be more sensitive to quantization?</li><li>Which scaling factors reduce the output error?</li></ul><p>This is why AWQ is a post-training quantization method.</p><p>It transforms an already-trained model rather than training a new model from scratch.</p><p>For more mathematical details, the original paper is worth reading, particularly Sections 3.1 and 3.2.</p><h3>4. My Experimental Setup</h3><p>I used the following configuration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gX2OG-jHT9VJN0F8sf9VHg.png" /></figure><p>The experiment was performed in Google Colab.</p><p>I used LLM Compressor because it provides an implementation of AWQ through AWQModifier and allows quantization to be performed using a recipe.</p><p>Documentation:</p><p><a href="https://docs.vllm.ai/projects/llm-compressor/en/latest/examples/awq/">LLM Compressor — AWQ Quantization</a></p><h3>5. Preparing the Calibration Dataset</h3><p>I selected WikiText-2 as the calibration dataset.</p><p>The purpose was not to train the model on WikiText-2.</p><p>The purpose was to pass representative text through the model and collect activation statistics.</p><p>I selected the training split and filtered the samples to retain text longer than 100 characters.</p><p>The calibration configuration was:</p><ul><li>Dataset: Salesforce/wikitext</li><li>Configuration: wikitext-2-raw-v1</li><li>Split: train</li><li>Samples: 128</li><li>Maximum sequence length: 512</li></ul><p>One mistake I encountered was passing a normal Python list directly as calibration data.</p><p>The process raised:</p><pre>AttributeError: &#39;list&#39; object has no attribute &#39;column_names&#39;</pre><p>The problem was that the calibration pipeline expected a Hugging Face Dataset-like object rather than the plain list I supplied.</p><p>I fixed this by converting the list into a Dataset:</p><pre>from datasets import Dataset</pre><pre>calibration_dataset = Dataset.from_list(<br>    [{&quot;text&quot;: text} for text in calibration_texts]<br>)</pre><p>This was a useful reminder that the calibration algorithm and the data pipeline have their own input requirements.</p><h3>6. Implementing AWQ Using LLM Compressor</h3><p>After preparing the dataset, I defined the quantization recipe.</p><pre>from llmcompressor import oneshot<br>from llmcompressor.modifiers.transform.awq import AWQModifier<br>from llmcompressor.modifiers.quantization import QuantizationModifier</pre><pre>recipe = [<br>    AWQModifier(<br>        duo_scaling=True,<br>        n_grid=20<br>    ),<br>    QuantizationModifier(<br>        targets=[&quot;Linear&quot;],<br>        scheme=&quot;W4A16&quot;,<br>        ignore=[&quot;lm_head&quot;]<br>    )<br>]</pre><pre>print(&quot;AWQ recipe created successfully!&quot;)</pre><p>Let’s understand each part.</p><h3>6.1 AWQModifier</h3><pre>AWQModifier(<br>    duo_scaling=True,<br>    n_grid=20<br>)</pre><p>This applies the activation-aware scaling transformation.</p><p>duo_scaling=True means the scaling search considers both activation statistics and weight information.</p><p>n_grid=20 controls the number of grid-search candidates used by the AWQ implementation.</p><p>A larger search can take more time, potentially finding better scaling factors.</p><p>It does not mean that the model is divided into 20 groups.</p><h3>6.2 QuantizationModifier</h3><pre>QuantizationModifier(<br>    targets=[&quot;Linear&quot;],<br>    scheme=&quot;W4A16&quot;,<br>    ignore=[&quot;lm_head&quot;]<br>)</pre><p>This performs the actual quantization.</p><p>The important settings are:</p><p><strong>targets=[“Linear”]</strong></p><p>This identifies linear layers as the targets for quantization.</p><p><strong>scheme=”W4A16&quot;</strong></p><p>This means:</p><ul><li>W4: weights are represented using 4-bit integers.</li><li>A16: activations remain in 16-bit floating-point precision.</li></ul><p>This is weight-only quantization.</p><p>It does not mean that the entire model performs every computation using 4-bit arithmetic.</p><p><strong>ignore=[“lm_head”]</strong></p><p>This excludes the language-model output head from quantization.</p><p>This is an intentional configuration choice in my experiment.</p><h3>6.3 Running the quantization process</h3><p>The recipe is passed to the oneshot() function.</p><p>Conceptually:</p><pre>oneshot(<br>    model=model,<br>    dataset=calibration_dataset,<br>    recipe=recipe,<br>    max_seq_length=512<br>)</pre><p>The process uses the calibration data to collect activation information, performs AWQ scaling, and applies the configured quantization.</p><p>The model is transformed in place.</p><p>In my experiment, the compression process took approximately 3 minutes and 13 seconds.</p><h3>7. Saving the Quantized Model</h3><p>After quantization, I saved the model and tokenizer.</p><pre>output_dir = &quot;/content/qwen-awq&quot;</pre><pre>model_awq.save_pretrained(output_dir)<br>tokenizer.save_pretrained(output_dir)</pre><p>The model was saved successfully.</p><p>However, I initially became confused while inspecting the model.</p><p>Before saving, the live model’s configuration did not show the expected quantization_config. I also observed FP16 weight tensors alongside additional tensors such as:</p><ul><li>weight_scale</li><li>weight_zero_point</li></ul><p>At first, this made me question whether quantization had actually happened.</p><p>The important lesson was that inspecting the in-memory model alone was not enough to establish how the compressed checkpoint would be serialized.</p><p>After saving, I inspected the checkpoint’s config.json.</p><p>It contained a quantization configuration similar to:</p><pre>{<br>  &quot;format&quot;: &quot;pack-quantized&quot;,<br>  &quot;quant_method&quot;: &quot;compressed-tensors&quot;,<br>  &quot;quantization_status&quot;: &quot;compressed&quot;,<br>  &quot;config_groups&quot;: {<br>    &quot;group_0&quot;: {<br>      &quot;targets&quot;: [&quot;Linear&quot;],<br>      &quot;weights&quot;: {<br>        &quot;num_bits&quot;: 4,<br>        &quot;group_size&quot;: 128,<br>        &quot;symmetric&quot;: true,<br>        &quot;type&quot;: &quot;int&quot;,<br>        &quot;strategy&quot;: &quot;group&quot;<br>      }<br>    }<br>  },<br>  &quot;ignore&quot;: [&quot;lm_head&quot;]<br>}</pre><p>This confirmed that the saved checkpoint carried compressed-tensors quantization metadata.</p><p>I also successfully reloaded the saved checkpoint using Transformers.</p><p>The important distinction is that the in-memory tensor representation and the serialized checkpoint representation are not necessarily identical.</p><h3>8. The Result: Model Size Reduction</h3><p>This was the first measurable result.</p><p>ModelSaved sizeOriginal FP16953.3 MBAWQ W4A16446.72 MB</p><p>The percentage reduction was:</p><p>[<br>\text{Reduction} =<br>\frac{953.3–446.72}{953.3}\times100<br>]</p><p>[<br>\boxed{53.1%}<br>]</p><p>The AWQ checkpoint occupied approximately 46.9% of the original checkpoint size.</p><p>That means the model became approximately 2.13 times smaller on disk.</p><p>An important clarification: theoretical 4-bit quantization can reduce the storage of quantized weight tensors by approximately four times compared with FP16. However, the entire checkpoint does not necessarily become four times smaller.</p><p>Reasons include:</p><ul><li>Some layers were excluded from quantization.</li><li>Quantization scales and metadata require storage.</li><li>Other model components may remain in higher precision.</li><li>Checkpoint serialization introduces additional overhead.</li></ul><p>Therefore, a 53.1% reduction in total checkpoint size is not inconsistent with W4 quantization.</p><h3>9. The First Inference Benchmark: Transformers</h3><p>After saving the AWQ checkpoint, I compared it with the original FP16 model using the Transformers inference pipeline.</p><p>The initial benchmark used the same prompt:</p><p>“Explain the difference between machine learning and deep learning with an example.”</p><p>Both models generated 128 tokens.</p><p>The results were:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bnmgnqW71ish9FoAqrpJJA.png" /></figure><p>The results were surprising.</p><p>Although AWQ reduced peak allocated GPU memory by approximately 50.4%, its generation throughput was approximately 40.2% lower than FP16.</p><p>This demonstrated an important point:</p><p><strong>A smaller model does not automatically translate into faster inference.</strong></p><p>The quantized model required less GPU memory, but the inference implementation did not provide the expected speed advantage.</p><p>I wanted to investigate whether a more optimized inference engine could improve the performance of the AWQ checkpoint.</p><p>That led me to experiment with vLLM.</p><h3>10. Why Can AWQ Be Slower Than FP16?</h3><p>To understand this, we need to look at what happens during inference.</p><p>A 4-bit weight is not necessarily used directly in a normal FP16 matrix multiplication.</p><p>Depending on the backend and kernel implementation, quantized inference may involve:</p><ol><li>Reading packed 4-bit weights.</li><li>Unpacking the quantized values.</li><li>Applying quantization scales and zero-points.</li><li>Performing matrix operations using an appropriate compute representation.</li></ol><p>An optimized quantized kernel can combine these operations efficiently.</p><p>However, an inefficient implementation may introduce additional overhead.</p><p>Meanwhile, FP16 has highly optimized GPU execution paths.</p><p>There are several factors to consider.</p><h4>10.1 Dequantization overhead</h4><p>The quantized weights must be interpreted using their scales and quantization parameters.</p><p>If the backend cannot efficiently fuse dequantization with matrix multiplication, this can reduce the expected performance benefit.</p><h4>10.2 GPU kernel efficiency</h4><p>A quantized model needs an inference backend that can efficiently execute low-bit operations.</p><p>The AWQ algorithm improves quantization quality. It does not guarantee that every inference framework will execute the resulting model efficiently.</p><h4>10.3 Model size matters</h4><p>My model contains approximately 494 million parameters.</p><p>This is relatively small compared with the larger LLMs for which quantization can provide substantial memory-bandwidth advantages.</p><p>A small model may already fit comfortably in GPU memory.</p><p>In that situation, the overhead of quantized execution can outweigh the benefits of reduced weight traffic.</p><h4>10.4 Autoregressive generation</h4><p>LLMs generate tokens sequentially.</p><p>The model predicts one token, adds it to the context, and predicts the next token.</p><p>For batch-size-one generation, the workload can become memory-bound because model weights are repeatedly accessed during decoding.</p><p>Reducing weight memory traffic can help, but only when the inference implementation takes advantage of it.</p><p>The original AWQ paper discusses this distinction and explains why efficient kernels, weight packing, and kernel fusion are important.</p><h3>11. Moving to vLLM: Investigating the Performance Difference</h3><p>After observing the slower AWQ inference performance with Transformers, I decided to test the models using vLLM.</p><p>The motivation was straightforward:</p><p>I wanted to determine whether an optimized inference engine could improve the execution speed of the quantized checkpoint.</p><p>vLLM is designed for efficient LLM inference and serving. It provides optimized execution, memory management, and continuous batching.</p><p>However, there is an important distinction:</p><ul><li><strong>AWQ</strong> is a weight quantization technique.</li><li><strong>vLLM</strong> is an inference and serving engine.</li></ul><p>They solve different problems.</p><p>For this experiment, I tested both the original FP16 checkpoint and the AWQ W4A16 checkpoint using vLLM.</p><p>The benchmarking procedure was:</p><ol><li>Load the model into GPU memory.</li><li>Perform warm-up runs.</li><li>Generate the same number of output tokens.</li><li>Repeat the benchmark five times.</li><li>Calculate average generation time and throughput.</li></ol><p>I used the NVIDIA Tesla T4 GPU available in Google Colab.</p><h4>11.1 vLLM Benchmark Results</h4><p>The results were:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UTtlQoAyVhpSGr_wLUhu4Q.png" /></figure><p>These results were quite different from my initial Transformers benchmark.</p><p>The AWQ model achieved approximately <strong>241.39 tokens per second</strong>, compared with <strong>164.29 tokens per second</strong> for FP16.</p><p>This represents approximately a 46.9% improvement in throughput.</p><p>Generation time also decreased from approximately 0.779 seconds to 0.530 seconds for the 128-token benchmark.</p><p>That is approximately a 31.9% reduction in generation time.</p><p>The model loading time was also slightly lower for AWQ.</p><h4>11.2 Visualizing the Performance Difference</h4><p>The most interesting observation is the difference in throughput.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PzT3g1Hb_D2XfZT1A4AjrQ.png" /></figure><p>AWQ achieved approximately 1.47 times the throughput of FP16 in this experiment.</p><p>This suggests that the optimized quantized inference path in vLLM was able to take advantage of the reduced weight representation more effectively than my initial Transformers setup.</p><p>However, this result should not be interpreted as proof that AWQ is always faster than FP16.</p><p>The performance depends on several factors, including:</p><ul><li>GPU architecture.</li><li>Model architecture and parameter count.</li><li>Quantization format and group size.</li><li>Inference engine and kernel implementation.</li><li>Batch size and sequence length.</li><li>Runtime configuration.</li></ul><p>The results demonstrate what happened in my particular experimental setup.</p><h4>11.3 Why Did the Results Change?</h4><p>This was the most interesting part of the experiment.</p><p>With Transformers, AWQ was slower than FP16.</p><p>With vLLM, AWQ achieved higher throughput than FP16.</p><p>Why?</p><p>The quantization algorithm did not fundamentally change. The main difference was the inference backend.</p><p>An inference engine needs to understand the quantized weight representation and execute the corresponding operations efficiently.</p><p>If the backend uses optimized quantized kernels, it can reduce the overhead associated with low-bit weight execution.</p><p>In contrast, a less optimized execution path may not fully benefit from the reduced weight storage.</p><p>This experiment helped me understand that quantization and inference optimization are two separate parts of LLM deployment.</p><p><strong>Reducing model size is only one part of optimization. The inference engine determines how efficiently the compressed model is executed.</strong></p><p>One important limitation is that this comparison changes both the quantization format and the inference backend relative to my initial Transformers experiment. Therefore, the difference between the two experiments cannot be attributed to AWQ alone.</p><h3>12. Mistakes and Debugging During the Experiment</h3><p>The most useful part of this project was not just the final model size. It was the mistakes encountered along the way.</p><h4>Mistake 1: Passing calibration data as a Python list</h4><p>Initially, the calibration pipeline raised:</p><p>AttributeError: &#39;list&#39; object has no attribute &#39;column_names&#39;</p><p>I had passed the data in a format that the pipeline did not expect.</p><p><strong>Lesson:</strong> Check the expected input format of the quantization library. Converting the samples into a Hugging Face Dataset resolved this issue.</p><h4>Mistake 2: Assuming that missing quantization metadata in memory meant AWQ had failed</h4><p>Initially, I inspected the model before saving and found that the configuration did not show the expected quantization metadata.</p><p>I also saw FP16 tensors and additional scale-related tensors.</p><p>I initially interpreted this as a possible failure.</p><p>However, after saving, the checkpoint contained the compressed-tensors configuration and was successfully reloaded.</p><p><strong>Lesson:</strong> Inspect the serialized checkpoint and its quantization configuration. Do not rely on a single in-memory tensor inspection to decide whether the compression process succeeded.</p><h4>Mistake 3: Assuming that a 4-bit model must be faster</h4><p>The AWQ checkpoint was approximately 53.1% smaller, but the initial Transformers benchmark showed lower throughput than FP16.</p><p>I had initially associated lower memory usage with higher generation speed.</p><p>The experiment taught me that quantization and inference optimization are related but separate problems.</p><p><strong>Lesson:</strong> Benchmark the actual inference backend. Storage reduction is not proof of speed improvement.</p><h4>Mistake 4: Benchmarking without fully isolating model memory</h4><p>I questioned whether keeping both models loaded on the GPU could have affected the results.</p><p>It can create memory pressure and complicate measurements.</p><p>However, without a controlled rerun, I cannot claim that this was the reason AWQ was slower.</p><p><strong>Lesson:</strong> Load one model at a time, warm it up, run multiple trials, and clean up before testing the next model.</p><h4>Mistake 5: Running into a CUDA version mismatch while installing vLLM</h4><p>When I installed vLLM, the environment changed several packages.</p><p>The resulting diagnostic output showed:</p><ul><li>PyTorch: 2.14.0+cu132</li><li>PyTorch CUDA: 13.2</li><li>GPU: Tesla T4</li><li>Compute capability: 7.5</li></ul><p>But importing vLLM raised:</p><p>RuntimeError: Detected that PyTorch and TorchAudio were compiled with different CUDA versions.</p><p>PyTorch had CUDA 13.2, whereas TorchAudio had CUDA 13.0.</p><p>The GPU itself was detected correctly. The problem was a mismatch between the CUDA versions used to compile PyTorch and TorchAudio.</p><p>Since this was a text-only LLM experiment, TorchAudio was not needed. I investigated the incompatible dependency and adjusted the environment before proceeding.</p><p>I was subsequently able to run the vLLM AWQ benchmark successfully.</p><p><strong>Lesson:</strong> Installing an inference framework can change several underlying Python and CUDA dependencies. Package compatibility is part of the engineering work, not an unrelated inconvenience.</p><h3>13. What I Learned</h3><p>This experiment changed how I think about LLM quantization.</p><p>Before implementing AWQ, I mainly associated 4-bit quantization with reducing model size.</p><p>After the experiment, I understood that there are several independent questions.</p><p><strong>1. Does quantization reduce storage?</strong></p><p>Yes. In my experiment, the checkpoint became 53.1% smaller.</p><p><strong>2. Does quantization preserve model quality?</strong></p><p>That needs a proper evaluation.</p><p>A successful save and reload do not establish that the quantized model has the same quality as the FP16 model.</p><p>A more complete evaluation should include WikiText perplexity, task-specific tests, and output comparisons.</p><p><strong>3. Does quantization improve inference speed?</strong></p><p>Not necessarily.</p><p>My initial Transformers benchmark showed lower throughput for AWQ, whereas the vLLM benchmark showed higher throughput.</p><p>This demonstrates how strongly inference performance can depend on the execution backend.</p><p><strong>4. Does the inference backend matter?</strong></p><p>Absolutely.</p><p>Efficient low-bit kernels, fused dequantization, and optimized memory access are necessary to convert theoretical compression benefits into practical performance improvements.</p><p>The central lesson is:</p><p><strong>Quantization reduces the cost of representing model weights. Optimized inference determines how efficiently those weights can be used.</strong></p><h3>14. What’s Next?</h3><p>Although the experiments provided useful results, there are several things I want to investigate further.</p><ul><li>Compare model quality using perplexity on a held-out dataset.</li><li>Evaluate the generated responses using task-specific benchmarks.</li><li>Compare GPU memory consumption under identical conditions for both vLLM configurations.</li><li>Compare single-request latency with batched throughput.</li><li>Investigate the effect of different quantization group sizes.</li><li>Compare AWQ with other weight quantization approaches.</li><li>Repeat the experiments with a larger model to investigate whether the performance advantage changes with model size.</li></ul><p>I also want to conduct more controlled benchmarking by keeping the inference backend, prompt, output length, warm-up procedure, and GPU environment identical.</p><p>That would help separate the performance improvement caused by quantization from the improvement caused by the inference engine.</p><h3>Conclusion</h3><p>In this project, I quantized Qwen2.5–0.5B-Instruct using Activation-aware Weight Quantization and LLM Compressor on an NVIDIA Tesla T4 GPU.</p><p>I learned how activation statistics identify important channels, how equivalent scaling transformations reduce quantization error, and how group-wise W4A16 quantization reduces the storage requirements of model weights.</p><p>The saved checkpoint was approximately 53.1% smaller than the original FP16 checkpoint.</p><p>However, my initial Transformers benchmark showed that the AWQ model was slower than FP16.</p><p>Instead of assuming that quantization had failed, I investigated the inference implementation and moved to vLLM.</p><p>The vLLM benchmark produced a different result:</p><ul><li>FP16 throughput: 164.29 tokens/s.</li><li>AWQ throughput: 241.39 tokens/s.</li><li>AWQ throughput improvement: approximately 46.9%.</li></ul><p>This was an interesting outcome because it demonstrated that the same quantized model can behave differently depending on the inference backend.</p><p>The most important takeaway from this experiment is that <strong>model compression, quantization accuracy, and inference performance must be evaluated separately.</strong></p><p>A model can be smaller without being faster. Understanding why requires looking beyond the quantization algorithm and examining the entire inference pipeline.</p><h3>References</h3><ol><li><a href="https://arxiv.org/abs/2306.00978">AWQ: Activation-aware Weight Quantization for LLM Compression and Acceleration — Original Research Paper</a></li><li><a href="https://docs.vllm.ai/projects/llm-compressor/en/latest/examples/awq/">LLM Compressor — AWQ Quantization Documentation</a></li><li><a href="https://docs.vllm.ai/projects/llm-compressor/en/stable/api/llmcompressor/modifiers/transform/awq/">LLM Compressor — AWQModifier API</a></li><li><a href="https://docs.vllm.ai/">vLLM Documentation</a></li></ol><p><em>This article documents a hands-on experiment and its observed results. Formal model-quality evaluation and further controlled benchmarking remain future work.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4222ddbb7b8b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying a Local LLM on AWS EC2: A Beginner’s Guide to Ollama, FastAPI, Linux, and API Security]]></title>
            <link>https://medium.com/@abhinavgopinadh/deploying-a-local-llm-on-aws-ec2-a-beginners-guide-to-ollama-fastapi-linux-and-api-security-e94b1dd20229?source=rss-63bf040eecba------2</link>
            <guid isPermaLink="false">https://medium.com/p/e94b1dd20229</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[ollama]]></category>
            <category><![CDATA[aws-ec2]]></category>
            <category><![CDATA[deployment]]></category>
            <dc:creator><![CDATA[Abhinavgopinadh]]></dc:creator>
            <pubDate>Mon, 16 Nov 2026 14:35:17 GMT</pubDate>
            <atom:updated>2026-11-16T14:35:17.761Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>A hands-on deployment guide covering installation, model serving, API development, systemd, troubleshooting, and security hardening</strong></p><h3>1. Introduction</h3><p>Running a large language model locally is no longer limited to high-end personal computers. With tools such as Ollama, we can download and run supported language models on a Linux server and expose them through an application API.</p><p>In this project, I deployed the Qwen 2.5 1.5B model on an AWS EC2 instance, built a REST API using FastAPI, and configured the services to run automatically using systemd.</p><p>The goal was not just to make the model generate text. I also wanted to understand what happens when a local model becomes a backend service: how requests reach the model, how authentication works, how failures are handled, how logs are collected, and how to avoid exposing the inference server directly to the internet.</p><p>This guide documents the architecture, commands, implementation, mistakes, and troubleshooting steps from the deployment.</p><h3>What we will build</h3><p>By the end of this tutorial, the system will have:</p><ul><li>A Linux EC2 instance running Ollama.</li><li>The Qwen 2.5 1.5B language model.</li><li>A FastAPI application that accepts chat requests.</li><li>API-key authentication.</li><li>Request validation and controlled HTTP errors.</li><li>Request IDs and structured application logs.</li><li>Request rate limiting and inference concurrency controls.</li><li>A systemd service that automatically starts the API after a restart.</li></ul><p><strong>Important:</strong> This is a learning and prototype deployment. The additional controls are useful foundations, but a public production deployment still needs appropriate network access controls, HTTPS, stronger operational monitoring, and tests of failure and load scenarios.</p><h3>2. Architecture</h3><p>The deployment uses two services on the same EC2 instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7oYK4JafHk6WyVulCzmf-Q.png" /></figure><p>The client sends a request to FastAPI. FastAPI checks the API key, validates the input, and forwards the request to Ollama’s local HTTP API. Ollama runs the model and returns a response, which FastAPI sends back to the client.</p><p>The distinction between the two services matters:</p><ul><li><strong>Ollama</strong> manages the model and performs inference.</li><li><strong>FastAPI</strong> provides the application-facing interface and handles authentication, validation, and other application logic.</li></ul><p>Ollama’s default local API address is http://127.0.0.1:11434. Keeping the model server bound to localhost means it is not directly accessible through the instance&#39;s public network interface. See the official <a href="https://github.com/ollama/ollama/blob/main/docs/faq.mdx">Ollama FAQ</a>.</p><h3>3. Infrastructure and prerequisites</h3><h3>AWS infrastructure</h3><p>I used an Amazon Linux 2023 EC2 instance in the AWS Mumbai region (ap-south-1).</p><p>The instance was approximately:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7rJfui_bc4Fzb0nH4xY23A.png" /></figure><p>These are the approximate specifications of this deployment, not universal minimum requirements.</p><p>The selected model was a relatively small model suitable for experimentation on a CPU-based instance. Its quantized model file was approximately 986 MB in this setup. Model file size alone does not determine total RAM requirements: inference also needs memory for the runtime, context, and other processes.</p><p>A small instance is useful for learning, but it should not be assumed to support high request throughput.</p><h3>Connect to the EC2 instance</h3><p>Connect through SSH or the AWS browser-based connection option.</p><p>After logging in, check the operating system:</p><pre>cat /etc/os-release</pre><p>Check available memory:</p><pre>free -h</pre><p>Check disk space:</p><pre>df -h</pre><p>Check CPU information:</p><pre>nproc</pre><p>These commands are useful before installing a model because they show the resources available to the deployment.</p><h3>AWS security group</h3><p>For this architecture, the security group should not allow public inbound access to ports 8000 or 11434.</p><p>For SSH access, restrict port 22 to your own public IP address where possible.</p><p>AWS security groups control inbound and outbound traffic. Review the <a href="https://docs.aws.amazon.com/vpc/latest/userguide/security-group-rules.html">official AWS security group documentation</a>.</p><h3>4. Install Ollama on Linux</h3><p>Ollama provides an installation script for Linux.</p><p>Run:</p><pre>curl -fsSL https://ollama.com/install.sh | sh</pre><p>This command downloads and executes the official installation script. As with any installation script, use the official source and review its contents if you need to inspect what it changes.</p><p>Official installation instructions: <a href="https://github.com/ollama/ollama/blob/main/docs/linux.mdx">Ollama Linux documentation</a>.</p><p>Verify the installation:</p><pre>ollama --version</pre><p>Check the service:</p><pre>sudo systemctl status ollama --no-pager</pre><p>If it is not running, start it:</p><pre>sudo systemctl start ollama</pre><p>Enable automatic startup:</p><pre>sudo systemctl enable ollama</pre><p>Check the service logs if anything goes wrong:</p><pre>sudo journalctl -u ollama -n 50 --no-pager</pre><p>The journalctl command is particularly important when working with Linux services. It provides the logs collected by the systemd journal.</p><h3>5. Download and test the language model</h3><p>For this deployment, I used Qwen 2.5 1.5B.</p><p>Download the model:</p><pre>ollama pull qwen2.5:1.5b</pre><p>List the downloaded models:</p><pre>ollama list</pre><p>The output should include qwen2.5:1.5b.</p><p>Test the model directly:</p><pre>ollama run qwen2.5:1.5b</pre><p>Enter a simple prompt, such as:</p><pre>Explain what an API is in two sentences.</pre><p>Exit the interactive session when finished.</p><p>You can also inspect the models currently loaded into memory:</p><pre>ollama ps</pre><p>Before building the application API, verify that the model itself works. This separates model installation problems from application code problems.</p><h3>Test the Ollama HTTP API</h3><p>Ollama exposes an HTTP API for chat requests.</p><p>Run:</p><pre>curl http://127.0.0.1:11434/api/tags</pre><p>This should return information about the locally available models.</p><p>Next, test chat generation:</p><pre>curl -X POST http://127.0.0.1:11434/api/chat \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{<br>    &quot;model&quot;: &quot;qwen2.5:1.5b&quot;,<br>    &quot;messages&quot;: [<br>      {<br>        &quot;role&quot;: &quot;user&quot;,<br>        &quot;content&quot;: &quot;Reply with exactly: Ollama is working&quot;<br>      }<br>    ],<br>    &quot;stream&quot;: false<br>  }&#39;</pre><p>The response should contain a message generated by the model.</p><p>The official <a href="https://github.com/ollama/ollama/blob/main/docs/api.md">Ollama API documentation</a> describes the available endpoints and request formats.</p><p>At this point, we have verified the model independently of FastAPI.</p><h3>6. Create the FastAPI application</h3><p>Now we will create an application layer that clients can use instead of directly calling Ollama.</p><h3>Create the project directory</h3><pre>mkdir -p /home/ec2-user/ollama-api<br>cd /home/ec2-user/ollama-api</pre><p>Create a Python virtual environment:</p><pre>python3 -m venv .venv</pre><p>Activate it:</p><pre>source .venv/bin/activate</pre><p>Upgrade pip:</p><pre>python -m pip install --upgrade pip</pre><p>Install the dependencies:</p><pre>pip install fastapi uvicorn httpx</pre><p>Verify the installed packages:</p><pre>pip show fastapi httpx pydantic</pre><p>A virtual environment keeps the application’s Python dependencies separate from the operating system’s Python packages.</p><h3>Create app.py</h3><p>Use Nano, a terminal-based text editor:</p><pre>nano app.py</pre><p>The initial version of the application can be kept deliberately small:</p><pre>import os<br>import secrets<br>from typing import Optional</pre><pre>import httpx<br>from fastapi import FastAPI, Header, HTTPException<br>from pydantic import BaseModel, Field</pre><pre>app = FastAPI(title=&quot;Private Ollama API&quot;, version=&quot;1.0.0&quot;)</pre><pre>API_KEY = os.environ.get(&quot;API_KEY&quot;)<br>OLLAMA_URL = &quot;http://127.0.0.1:11434/api/chat&quot;<br>MODEL = &quot;qwen2.5:1.5b&quot;<br></pre><pre>class ChatRequest(BaseModel):<br>    message: str = Field(min_length=1, max_length=4000)<br></pre><pre>def verify_api_key(x_api_key: Optional[str]):<br>    if not API_KEY:<br>        raise HTTPException(<br>            status_code=503,<br>            detail=&quot;API key is not configured&quot;,<br>        )</pre><pre>    if not x_api_key or not secrets.compare_digest(<br>        x_api_key, API_KEY<br>    ):<br>        raise HTTPException(<br>            status_code=401,<br>            detail=&quot;Invalid API key&quot;,<br>        )<br></pre><pre>@app.get(&quot;/health&quot;)<br>async def health():<br>    return {&quot;status&quot;: &quot;ok&quot;}<br></pre><pre>@app.post(&quot;/chat&quot;)<br>async def chat(<br>    request: ChatRequest,<br>    x_api_key: Optional[str] = Header(default=None),<br>):<br>    verify_api_key(x_api_key)</pre><pre>    payload = {<br>        &quot;model&quot;: MODEL,<br>        &quot;messages&quot;: [<br>            {<br>                &quot;role&quot;: &quot;system&quot;,<br>                &quot;content&quot;: (<br>                    &quot;Answer accurately and clearly. &quot;<br>                    &quot;If uncertain, say so. Do not invent facts.&quot;<br>                ),<br>            },<br>            {<br>                &quot;role&quot;: &quot;user&quot;,<br>                &quot;content&quot;: request.message,<br>            },<br>        ],<br>        &quot;stream&quot;: False,<br>    }</pre><pre>    try:<br>        async with httpx.AsyncClient(timeout=120.0) as client:<br>            response = await client.post(<br>                OLLAMA_URL,<br>                json=payload,<br>            )<br>            response.raise_for_status()<br>            result = response.json()</pre><pre>        return {<br>            &quot;model&quot;: MODEL,<br>            &quot;answer&quot;: result[&quot;message&quot;][&quot;content&quot;],<br>        }</pre><pre>    except httpx.TimeoutException:<br>        raise HTTPException(<br>            status_code=504,<br>            detail=&quot;Model inference timed out&quot;,<br>        )</pre><pre>    except httpx.HTTPError:<br>        raise HTTPException(<br>            status_code=502,<br>            detail=&quot;Inference service failed&quot;,<br>        )</pre><pre>    except (KeyError, ValueError):<br>        raise HTTPException(<br>            status_code=502,<br>            detail=&quot;Invalid inference response&quot;,<br>        )</pre><p>Save the file in Nano with Ctrl+O, press Enter, and exit with Ctrl+X.</p><h3>What the initial application does</h3><ul><li>FastAPI creates the HTTP application.</li><li>ChatRequest defines the request schema.</li><li>Field restricts the message to 1–4,000 characters.</li><li>verify_api_key() checks the client&#39;s API key.</li><li>/health provides a basic health endpoint.</li><li>/chat sends the user&#39;s message to Ollama.</li><li>httpx performs the HTTP request to the model server.</li><li>HTTPException converts known failures into controlled HTTP responses.</li></ul><p>Pydantic-based request bodies are a standard FastAPI feature. See the <a href="https://fastapi.tiangolo.com/tutorial/body/">FastAPI request body guide</a>.</p><h3>7. Store the API key outside the source code</h3><p>The API key should not be hardcoded in app.py or committed to a public Git repository.</p><p>Create a directory for the environment file:</p><pre>sudo mkdir -p /etc/ollama-api</pre><p>Create the file:</p><pre>sudo nano /etc/ollama-api/api.env</pre><p>Generate a random key in a separate terminal or shell:</p><pre>openssl rand -hex 32</pre><p>Copy the generated value into the environment file in this format:</p><pre>API_KEY=PASTE_YOUR_GENERATED_SECRET_HERE</pre><p>Replace the placeholder with the generated secret. Do not publish the real value in a blog, screenshot, or repository.</p><p>Set restrictive file permissions:</p><pre>sudo chown root:root /etc/ollama-api/api.env<br>sudo chmod 600 /etc/ollama-api/api.env</pre><p>The file should be readable and writable only by root.</p><p>The FastAPI process will receive the key through systemd’s EnvironmentFile setting.</p><h3>Why environment-based configuration matters</h3><p>Secrets should be separated from application source code so they can be rotated without editing the Python application.</p><p>However, environment variables are not a complete secret-management system. Access to the host, service configuration, process environment, and deployment logs must also be controlled.</p><h3>8. Test FastAPI manually</h3><p>Before creating a systemd service, run the API manually.</p><p>Make sure you are in the project directory and that the virtual environment is activated:</p><pre>cd /home/ec2-user/ollama-api<br>source .venv/bin/activate</pre><p>For a local test, load the key into the current shell from the protected environment file:</p><pre>export API_KEY=&quot;$(sudo sed -n &#39;s/^API_KEY=//p&#39; /etc/ollama-api/api.env | head -n 1)&quot;</pre><p>Run the application:</p><pre>uvicorn app:app --host 127.0.0.1 --port 8000</pre><p>Keep this terminal running and open another terminal session for the tests.</p><h3>Test the health endpoint</h3><pre>curl -i http://127.0.0.1:8000/health</pre><p>Expected response:</p><pre>HTTP/1.1 200 OK</pre><pre>{<br>  &quot;status&quot;: &quot;ok&quot;<br>}</pre><h3>Test a request without an API key</h3><pre>curl -i -X POST http://127.0.0.1:8000/chat \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{&quot;message&quot;:&quot;Hello&quot;}&#39;</pre><p>Expected response: 401 Unauthorized.</p><h3>Test request validation</h3><p>Try an empty message:</p><pre>curl -i -X POST http://127.0.0.1:8000/chat \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{&quot;message&quot;:&quot;&quot;}&#39;</pre><p>Expected response: 422 Unprocessable Entity.</p><p>The request fails validation because the message must contain at least one character.</p><p>Now test a valid authenticated request:</p><pre>curl -i -X POST http://127.0.0.1:8000/chat \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -H &quot;X-API-Key: $API_KEY&quot; \<br>  -d &#39;{&quot;message&quot;:&quot;Reply with exactly: Ollama API is working&quot;}&#39;</pre><p>A successful response should look similar to:</p><pre>{<br>  &quot;model&quot;: &quot;qwen2.5:1.5b&quot;,<br>  &quot;answer&quot;: &quot;Ollama API is working.&quot;<br>}</pre><p>The precise wording may vary with the model.</p><p>Once testing is complete, stop the manually running server and clear the temporary key variable:</p><pre>unset API_KEY</pre><h3>9. Run FastAPI as a systemd service</h3><p>A service should not depend on a terminal session remaining open. systemd can manage the application’s lifecycle, restart it after certain failures, and start it automatically during boot.</p><p>Create the service file:</p><pre>sudo nano /etc/systemd/system/ollama-api.service</pre><p>Add:</p><pre>[Unit]<br>Description=FastAPI Ollama Inference API<br>After=network.target ollama.service<br>Requires=ollama.service</pre><pre>[Service]<br>User=ec2-user<br>Group=ec2-user<br>WorkingDirectory=/home/ec2-user/ollama-api<br>EnvironmentFile=/etc/ollama-api/api.env<br>ExecStart=/home/ec2-user/ollama-api/.venv/bin/python -m uvicorn app:app --host 127.0.0.1 --port 8000<br>Restart=on-failure<br>RestartSec=5</pre><pre>[Install]<br>WantedBy=multi-user.target</pre><p>Save the file.</p><p>Reload systemd’s unit configuration:</p><pre>sudo systemctl daemon-reload</pre><p>Enable the service at boot:</p><pre>sudo systemctl enable ollama-api</pre><p>Start the service:</p><pre>sudo systemctl start ollama-api</pre><p>Check its status:</p><pre>sudo systemctl status ollama-api --no-pager</pre><p>The expected status is:</p><pre>Active: active (running)</pre><p>Test the health endpoint again:</p><pre>curl -i http://127.0.0.1:8000/health</pre><h3>Why use an absolute path in ExecStart?</h3><p>The service uses the Python executable inside the project’s virtual environment:</p><pre>/home/ec2-user/ollama-api/.venv/bin/python</pre><p>This avoids depending on the interactive shell’s activated environment or its PATH settings.</p><h3>Useful systemd commands</h3><p>Restart after changing the Python code:</p><pre>sudo systemctl restart ollama-api</pre><p>Stop the service:</p><pre>sudo systemctl stop ollama-api</pre><p>Check status:</p><pre>sudo systemctl status ollama-api --no-pager</pre><p>View recent logs:</p><pre>sudo journalctl -u ollama-api -n 60 --no-pager</pre><p>Follow logs continuously:</p><pre>sudo journalctl -u ollama-api -f</pre><p>These commands are essential for debugging applications running outside an interactive terminal.</p><h3>10. Improving the API for more reliable operation</h3><p>The initial version proves that inference works, but an application exposed to multiple clients needs more controls.</p><p>The following features were introduced during the hardening phase:</p><ol><li>Input validation.</li><li>API-key authentication.</li><li>Rate limiting.</li><li>Inference concurrency limits.</li><li>Reusable HTTP client and explicit timeouts.</li><li>Structured request logs and request IDs.</li><li>Controlled upstream errors.</li></ol><h3>10.1 Input validation</h3><p>The request schema restricts the message length:</p><pre>class ChatRequest(BaseModel):<br>    message: str = Field(min_length=1, max_length=4000)</pre><p>This rejects empty messages and excessively long message strings.</p><p>The hardened version also forbids unexpected fields:</p><pre>class ChatRequest(BaseModel):<br>    message: str = Field(min_length=1, max_length=4000)</pre><pre>    class Config:<br>        extra = &quot;forbid&quot;</pre><p>For Pydantic v2, model_config = ConfigDict(extra=&quot;forbid&quot;) is the modern alternative. The class-based configuration above works in the deployed version but is deprecated in Pydantic v2.</p><p>For example, this request is rejected:</p><pre>{<br>  &quot;Message&quot;: &quot;Hello&quot;<br>}</pre><p>The API expects lowercase message. The validation response correctly reports that message is missing and Message is an unexpected field.</p><h3>10.2 API-key authentication</h3><p>The API reads the expected key from the environment:</p><pre>API_KEY = os.environ.get(&quot;API_KEY&quot;)</pre><p>The comparison uses:</p><pre>secrets.compare_digest(x_api_key, API_KEY)</pre><p>The API rejects missing or incorrect keys with 401 Unauthorized.</p><p>Authentication should happen before expensive model inference. It is also important to avoid logging API-key values.</p><h3>10.3 Rate limiting</h3><p>The hardened version uses a simple in-memory sliding-window rate limiter:</p><pre>RATE_LIMIT = 10<br>RATE_WINDOW_SECONDS = 60</pre><p>It records request timestamps per client IP and rejects requests that exceed the configured threshold with:</p><pre>429 Too Many Requests</pre><p>The response can include a Retry-After header indicating when the client may try again.</p><p>This is useful for a single-process learning deployment, but it has limitations:</p><ul><li>The counters are lost when the application restarts.</li><li>Each worker has its own counters.</li><li>Multiple EC2 instances do not share the same counters.</li><li>An IP-based limiter may group many users behind one proxy or NAT address.</li><li>The in-memory dictionary needs an eviction strategy for inactive client entries.</li></ul><p>For a multi-worker or multi-instance production deployment, use a shared store such as Redis or enforce limits at a suitable API gateway.</p><h3>10.4 Concurrency limiting</h3><p>A language model request can consume substantial CPU and RAM. On a small instance, allowing many simultaneous generations can degrade performance or exhaust memory.</p><p>The hardened implementation uses:</p><pre>MAX_CONCURRENT_INFERENCES = 1<br>QUEUE_WAIT_SECONDS = 1</pre><p>An asynchronous semaphore limits active inference requests. Requests that cannot acquire a slot within the configured wait period receive a controlled 503 Service Unavailable response.</p><p>The semaphore must be released in a finally block so that an error does not permanently consume an inference slot.</p><p>This setting is a conservative starting point, not a universal optimum. Concurrency should be adjusted only after measuring memory use, latency, and model behavior under load.</p><h3>10.5 Reuse the HTTP client and configure timeouts</h3><p>The initial implementation creates an HTTP client for each request. The hardened implementation creates one reusable httpx.AsyncClient during application startup and closes it during shutdown.</p><p>It also configures explicit connection and response timeouts:</p><pre>httpx.Timeout(<br>    connect=5.0,<br>    read=120.0,<br>    write=10.0,<br>    pool=5.0,<br>)</pre><p>This separates the connection timeout from the time allowed to read the model response.</p><p>A timeout should return a controlled response such as 504 Gateway Timeout, rather than leaving clients waiting indefinitely.</p><h3>10.6 Structured logs and request IDs</h3><p>Instead of relying only on plain-text logs, the hardened implementation records structured JSON events.</p><p>A successful request produces an event similar to:</p><pre>{<br>  &quot;timestamp&quot;: &quot;2026-10-31T06:59:50Z&quot;,<br>  &quot;event&quot;: &quot;request_complete&quot;,<br>  &quot;request_id&quot;: &quot;f5985c3e-2f08-46ee-821d-6658fe9b90df&quot;,<br>  &quot;method&quot;: &quot;POST&quot;,<br>  &quot;path&quot;: &quot;/chat&quot;,<br>  &quot;status_code&quot;: 200,<br>  &quot;duration_ms&quot;: 9393.56<br>}</pre><p>This makes it easier to correlate a client’s response with the corresponding server-side events.</p><p>The middleware also adds an X-Request-ID header to the HTTP response.</p><p>Avoid putting API keys, authorization headers, or full private prompts into application logs.</p><h3>10.7 Safe error handling</h3><p>The hardened implementation distinguishes between different failure types:</p><p>SituationExpected responseMissing or invalid API key401 UnauthorizedInvalid request body422 Unprocessable EntityRate limit exceeded429 Too Many RequestsInference capacity unavailable503 Service UnavailableOllama connection failure503 Service UnavailableModel inference timeout504 Gateway TimeoutUpstream error or malformed response502 Bad Gateway</p><p>These status codes should reflect the actual error path. A validation failure, for example, is handled by FastAPI before the endpoint function executes.</p><p>For production, add automated tests for each error path. A successful syntax check is not enough to prove that an application starts or behaves correctly.</p><h3>11. Mistakes encountered and how I fixed them</h3><p>The debugging process was one of the most valuable parts of this deployment. These are the real categories of problems encountered during the implementation.</p><h3>Mistake 1: Confusing Python syntax validation with application startup</h3><p>I ran:</p><pre>python -m py_compile app.py</pre><p>The command completed without reporting a syntax error, but systemd could not start the application.</p><p>The journal showed:</p><pre>File &quot;/home/ec2-user/ollama-api/app.py&quot;, line 283<br>    PY<br>NameError: name &#39;PY&#39; is not defined</pre><p><strong>Root cause:</strong> A stray PY line had been pasted into app.py.</p><p>The text was syntactically valid as a Python expression referring to a variable named PY, so the compile check did not catch it. Python raised a NameError when the module was executed.</p><p><strong>Fix:</strong></p><p>Open the file:</p><pre>nano app.py</pre><p>Inspect the end of the file, remove the stray PY line, save, and exit.</p><p>Then validate and restart:</p><pre>python -m py_compile app.py<br>sudo systemctl restart ollama-api<br>sudo systemctl status ollama-api --no-pager</pre><p>The lesson: syntax compilation catches syntax errors, but it does not prove that all module-level code can execute successfully.</p><h3>Mistake 2: Reading only the service status instead of the logs</h3><p>When the application failed to start, systemd repeatedly restarted it.</p><p>The most useful command was:</p><pre>sudo journalctl -u ollama-api -n 60 --no-pager</pre><p>The journal revealed the exact exception and source line.</p><p><strong>Lesson:</strong> When a service fails, inspect the traceback before changing unrelated configuration.</p><h3>Mistake 3: Using the wrong JSON field name</h3><p>I tested the endpoint with:</p><pre>{<br>  &quot;Message&quot;: &quot;Hello&quot;<br>}</pre><p>The API returned 422 Unprocessable Entity.</p><p>The expected request was:</p><pre>{<br>  &quot;message&quot;: &quot;Hello&quot;<br>}</pre><p>The uppercase field was not silently accepted. With extra fields forbidden, FastAPI/Pydantic reported both the missing required field and the unexpected field.</p><p><strong>Lesson:</strong> JSON field names must match the request schema.</p><h3>Mistake 4: Sending an empty message</h3><p>This request:</p><pre>{<br>  &quot;message&quot;: &quot;&quot;<br>}</pre><p>also returned 422.</p><p>The validation rule requires at least one character:</p><pre>Field(min_length=1, max_length=4000)</pre><p><strong>Lesson:</strong> Input validation should reject invalid data before inference consumes resources.</p><h3>Mistake 5: Testing authentication without a valid key</h3><p>A request without an API key returned:</p><pre>401 Unauthorized</pre><p>That was expected.</p><p>To test successful authentication, I loaded the key from the protected environment file into a shell variable and sent it using the X-API-Key header.</p><p><strong>Lesson:</strong> A 401 response is not necessarily a server failure. In this case, it showed that authentication was being enforced.</p><p>Never paste the real key into public logs, screenshots, or a blog post.</p><h3>Mistake 6: Understanding the rate limiter’s scope</h3><p>The in-memory rate limiter counts requests by the client IP observed by the application. When a reverse proxy is introduced, the observed IP may be the proxy address unless client IP forwarding is configured safely.</p><p>It is also local to the application process.</p><p><strong>Lesson:</strong> A small in-memory rate limiter is useful for learning, but a distributed service needs shared rate-limit state and carefully configured proxy handling.</p><h3>12. Test checklist</h3><p>Before considering the deployment ready for wider use, test each feature independently.</p><p>TestExpected resultGET /health200 OKMissing API key401 UnauthorizedInvalid API key401 UnauthorizedEmpty message422 Unprocessable EntityUnknown JSON field422 Unprocessable EntityValid authenticated request200 OK with model outputExcess requests within the configured window429 Too Many RequestsInference slot unavailable503 Service UnavailableOllama unavailableControlled 503 or other configured upstream errorInference timeout504 Gateway TimeoutService restartApplication starts againServer rebootEnabled service starts automatically</p><p>The first group of tests was successfully demonstrated in the deployment: health checks, input validation, authentication rejection, successful inference, request IDs, and structured logs.</p><p>The rate-limit, concurrency, and failure-path tests should be completed and recorded before claiming those behaviors have all been verified.</p><h3>13. Security considerations</h3><p>A successful local test does not automatically make an API safe to expose publicly.</p><h3>Keep the inference services private</h3><p>The intended bind addresses are:</p><pre>FastAPI: 127.0.0.1:8000<br>Ollama:  127.0.0.1:11434</pre><p>Verify listening sockets with:</p><pre>sudo ss -ltnp</pre><p>Do not change the bind address to 0.0.0.0 just to make the service reachable remotely without also designing the network and authentication controls.</p><h3>Do not expose the Ollama API directly</h3><p>The application layer provides the API-key check and request validation. Direct access to Ollama would bypass those controls.</p><p>If remote access is required, use a secure approach such as an SSH tunnel for personal development, a VPN/private network for internal use, or an appropriately secured HTTPS reverse proxy for a public application.</p><h3>Protect the API key</h3><ul><li>Keep secrets outside source code.</li><li>Restrict file permissions.</li><li>Rotate keys if they are accidentally exposed.</li><li>Avoid logging authorization headers.</li><li>Do not commit environment files to Git.</li></ul><h3>Add HTTPS before public use</h3><p>The local test commands use plain HTTP over loopback. That is suitable for testing on the same machine, but a public API should use HTTPS and suitable access controls.</p><h3>Understand the EC2 cost model</h3><p>Stopping an EC2 instance generally stops its on-demand compute charges, but attached EBS storage and some other resources can continue to incur charges. Check the current AWS pricing and your account’s free-tier eligibility rather than assuming the deployment is completely free.</p><h3>14. What I learned</h3><p>This project taught me that deploying a local language model involves much more than downloading model weights.</p><p>The model is only one component. The surrounding service must validate inputs, authenticate callers, handle timeouts, manage resource usage, produce useful logs, and recover from failures.</p><p>Some key lessons were:</p><ol><li><strong>Test each layer separately.</strong> Verify Ollama first, then FastAPI, then systemd, and finally remote access.</li><li><strong>Use logs to diagnose failures.</strong> journalctl provided the exact traceback when the service would not start.</li><li><strong>Validate requests early.</strong> Pydantic helps reject invalid payloads before model inference begins.</li><li><strong>Treat secrets as deployment configuration.</strong> Do not embed API keys in source code.</li><li><strong>Control resource usage.</strong> Concurrency and timeouts matter when running a model on limited CPU and RAM.</li><li><strong>Distinguish implemented from verified.</strong> A feature is not fully tested merely because its code exists.</li><li><strong>Keep the model server private.</strong> Use the application API as the intended entry point and add secure networking before allowing remote clients.</li></ol><p>The most important lesson was that a working inference request is only the first milestone. Reliability and security require additional testing.</p><h3>15. Future improvements</h3><p>There are several ways to evolve this prototype:</p><ul><li>Add automated tests using pytest and FastAPI&#39;s test client.</li><li>Add a shared rate-limit store such as Redis when scaling to multiple workers or instances.</li><li>Introduce an HTTPS reverse proxy or private access tunnel.</li><li>Add metrics for request counts, error rates, inference latency, and memory usage.</li><li>Measure performance under controlled load before increasing concurrency.</li><li>Add health checks that distinguish application health from model availability.</li><li>Implement a deployment and rollback procedure.</li><li>Consider a larger EC2 instance or a GPU instance if workload requirements justify the cost.</li></ul><p>These improvements should be guided by measured workload requirements rather than assumptions about what a production system needs.</p><h3>16. References</h3><ol><li><strong>Ollama — Linux installation and service setup</strong><br><a href="https://github.com/ollama/ollama/blob/main/docs/linux.mdx">https://github.com/ollama/ollama/blob/main/docs/linux.mdx</a></li><li><strong>Ollama — API documentation</strong><br><a href="https://github.com/ollama/ollama/blob/main/docs/api.md">https://github.com/ollama/ollama/blob/main/docs/api.md</a></li><li><strong>Ollama — FAQ and network binding behavior</strong><br><a href="https://github.com/ollama/ollama/blob/main/docs/faq.mdx">https://github.com/ollama/ollama/blob/main/docs/faq.mdx</a></li><li><strong>FastAPI — Request bodies and Pydantic models</strong><br><a href="https://fastapi.tiangolo.com/tutorial/body/">https://fastapi.tiangolo.com/tutorial/body/</a></li><li><strong>FastAPI — Handling errors and HTTP exceptions</strong><br><a href="https://fastapi.tiangolo.com/tutorial/handling-errors/">https://fastapi.tiangolo.com/tutorial/handling-errors/</a></li><li><strong>HTTPX — Async support and clients</strong><br><a href="https://www.python-httpx.org/async/">https://www.python-httpx.org/async/</a></li><li><strong>HTTPX — Timeouts</strong><br><a href="https://www.python-httpx.org/advanced/timeouts/">https://www.python-httpx.org/advanced/timeouts/</a></li><li><strong>AWS — Security group rules</strong><br><a href="https://docs.aws.amazon.com/vpc/latest/userguide/security-group-rules.html">https://docs.aws.amazon.com/vpc/latest/userguide/security-group-rules.html</a></li><li><strong>AWS — EC2 security group rule examples</strong><br><a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/security-group-rules-reference.html">https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/security-group-rules-reference.html</a></li><li><strong>systemd — Service unit documentation</strong><br><a href="https://www.freedesktop.org/software/systemd/man/latest/systemd.service.html">https://www.freedesktop.org/software/systemd/man/latest/systemd.service.html</a></li></ol><h3>Conclusion</h3><p>In this project, I deployed a quantized Qwen model through Ollama on a Linux EC2 instance, wrapped it in a FastAPI service, secured the endpoint with API-key authentication, and configured systemd to manage the application.</p><p>The deployment also demonstrated why debugging is an essential part of engineering: a single accidental line in a Python file prevented the service from starting, while the systemd journal made the cause straightforward to identify.</p><p>For anyone beginning with local LLM deployment, my recommendation is to start small, verify each layer independently, keep the inference service private, and introduce production controls one at a time.</p><p><strong>A successful model response proves that inference works. A reliable service requires much more testing.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e94b1dd20229" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Detecting Spoilers in Story Summaries Using Graph Neural Networks]]></title>
            <link>https://medium.com/@abhinavgopinadh/detecting-spoilers-in-story-summaries-using-graph-neural-networks-2ee8ad3216d2?source=rss-63bf040eecba------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ee8ad3216d2</guid>
            <category><![CDATA[graph-neural-networks]]></category>
            <category><![CDATA[spoilers]]></category>
            <category><![CDATA[graph-convolution-network]]></category>
            <category><![CDATA[fake-news]]></category>
            <category><![CDATA[gnn]]></category>
            <dc:creator><![CDATA[Abhinavgopinadh]]></dc:creator>
            <pubDate>Thu, 24 Jul 2025 16:09:53 GMT</pubDate>
            <atom:updated>2025-07-24T16:09:53.953Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Spoilers can ruin the experience of consuming stories, especially when reading plot summaries or reviews. Automating spoiler detection is a challenging yet valuable task. In this article, we demonstrate how Graph Neural Networks (GNNs) can be used to detect spoilers in story summaries. We’ll walk through a working example using synthetic data, visualize sentence relationships as graphs, and show how the model can generalize to new inputs.</p><h3>Why Use Graph Neural Networks?</h3><p>Traditional NLP models, like RNNs or Transformers, process text as linear sequences — sentence after sentence, word after word. However, human understanding of stories isn’t strictly sequential. Sentences in a story can refer to earlier events, foreshadow upcoming twists, or depend on distant context. This is where <strong>Graph Neural Networks (GNNs)</strong> come in — they allow us to go beyond sequences and model <strong>rich inter-sentence relationships</strong>.</p><p><strong>GNNs: A Natural Fit for Story Structures</strong></p><p>In spoiler detection, not all sentences are equally revealing. A spoiler may refer to an earlier character development or a twist that only makes sense with context. GNNs shine in this scenario because they:</p><ul><li><strong>Capture complex relationships</strong>: GNNs can encode semantic, contextual, and positional links between sentences (e.g., cause-effect, temporal flow, or topic similarity).</li><li><strong>Preserve global and local context</strong>: Unlike CNNs or vanilla RNNs that focus on nearby words, GNNs propagate information through graph edges, allowing distant but relevant sentences to influence each other.</li><li><strong>Learn from structure</strong>: In a graph, sentences become nodes, and edges represent meaningful relationships (like co-reference or similarity). This gives the model an <strong>explicit map of how story elements connect</strong> — exactly what’s needed to detect spoilers that unfold across the narrative.</li></ul><h4>Spoiler Detection Needs Contextual Awareness</h4><p>Imagine two similar sentences:</p><ul><li><em>“She discovered the truth about her identity.”</em></li><li><em>“She discovered the password to the system.”</em></li></ul><p>The first may be a spoiler in a mystery novel, while the second may not be. A GNN model can weigh these differently by <strong>analyzing their context</strong>, their relationship with adjacent sentences, and the importance of the node in the overall graph.</p><h3>Sample Dataset</h3><p>We created a simple dataset of fictional documents, each containing a list of sentences labeled as either:</p><ul><li><strong>0: Non-Spoiler</strong></li><li><strong>1: Spoiler</strong></li></ul><p>Example document:</p><pre>[<br>  {<br>    &quot;id&quot;: &quot;doc1&quot;,<br>    &quot;sentences&quot;: [<br>      {&quot;text&quot;: &quot;Alice moves to a new town.&quot;, &quot;label&quot;: 0},<br>      {&quot;text&quot;: &quot;She joins a new school.&quot;, &quot;label&quot;: 0},<br>      {&quot;text&quot;: &quot;She discovers her magical powers.&quot;, &quot;label&quot;: 1}<br>    ]<br>  },<br>  {<br>    &quot;id&quot;: &quot;doc2&quot;,<br>    &quot;sentences&quot;: [<br>      {&quot;text&quot;: &quot;Tom starts his internship in a tech company.&quot;, &quot;label&quot;: 0},<br>      {&quot;text&quot;: &quot;He impresses his mentor with his ideas.&quot;, &quot;label&quot;: 0},<br>      {&quot;text&quot;: &quot;He gets promoted to lead the new project.&quot;, &quot;label&quot;: 1}<br>    ]<br>  },<br>  {<br>    &quot;id&quot;: &quot;doc3&quot;,<br>    &quot;sentences&quot;: [<br>      {&quot;text&quot;: &quot;The team is preparing for the championship match.&quot;, &quot;label&quot;: 0},<br>      {&quot;text&quot;: &quot;The captain gets injured a day before.&quot;, &quot;label&quot;: 1},<br>      {&quot;text&quot;: &quot;A new player steps in and wins the game.&quot;, &quot;label&quot;: 1}<br>    ]<br>  },<br>  {<br>    &quot;id&quot;: &quot;doc4&quot;,<br>    &quot;sentences&quot;: [<br>      {&quot;text&quot;: &quot;Sophie finds a mysterious book in the attic.&quot;, &quot;label&quot;: 0},<br>      {&quot;text&quot;: &quot;She opens it and time travels to the past.&quot;, &quot;label&quot;: 1},<br>      {&quot;text&quot;: &quot;She changes an event that alters her future.&quot;, &quot;label&quot;: 1}<br>    ]<br>  },<br>  {<br>    &quot;id&quot;: &quot;doc5&quot;,<br>    &quot;sentences&quot;: [<br>      {&quot;text&quot;: &quot;Jack moves into a haunted house.&quot;, &quot;label&quot;: 0},<br>      {&quot;text&quot;: &quot;He hears whispers at night.&quot;, &quot;label&quot;: 0},<br>      {&quot;text&quot;: &quot;The ghost turns out to be his grandmother.&quot;, &quot;label&quot;: 1}<br>    ]<br>  },<br>  {<br>    &quot;id&quot;: &quot;doc6&quot;,<br>    &quot;sentences&quot;: [<br>      {&quot;text&quot;: &quot;Emma trains hard for the dance competition.&quot;, &quot;label&quot;: 0},<br>      {&quot;text&quot;: &quot;Her partner quits at the last moment.&quot;, &quot;label&quot;: 1},<br>      {&quot;text&quot;: &quot;She performs solo and wins the contest.&quot;, &quot;label&quot;: 1}<br>    ]<br>  },<br>  {<br>    &quot;id&quot;: &quot;doc7&quot;,<br>    &quot;sentences&quot;: [<br>      {&quot;text&quot;: &quot;The detective investigates the robbery.&quot;, &quot;label&quot;: 0},<br>      {&quot;text&quot;: &quot;All clues point to the butler.&quot;, &quot;label&quot;: 0},<br>      {&quot;text&quot;: &quot;It was actually the detective himself.&quot;, &quot;label&quot;: 1}<br>    ]<br>  },<br>  {<br>    &quot;id&quot;: &quot;doc8&quot;,<br>    &quot;sentences&quot;: [<br>      {&quot;text&quot;: &quot;A scientist builds a robot assistant.&quot;, &quot;label&quot;: 0},<br>      {&quot;text&quot;: &quot;The robot learns human emotions.&quot;, &quot;label&quot;: 0},<br>      {&quot;text&quot;: &quot;It sacrifices itself to save the scientist.&quot;, &quot;label&quot;: 1}<br>    ]<br>  },<br>  {<br>    &quot;id&quot;: &quot;doc9&quot;,<br>    &quot;sentences&quot;: [<br>      {&quot;text&quot;: &quot;Lily attends her first music concert.&quot;, &quot;label&quot;: 0},<br>      {&quot;text&quot;: &quot;She meets her favorite singer backstage.&quot;, &quot;label&quot;: 0},<br>      {&quot;text&quot;: &quot;They turn out to be long-lost siblings.&quot;, &quot;label&quot;: 1}<br>    ]<br>  },<br>  {<br>    &quot;id&quot;: &quot;doc10&quot;,<br>    &quot;sentences&quot;: [<br>      {&quot;text&quot;: &quot;The villagers are terrified by a monster.&quot;, &quot;label&quot;: 0},<br>      {&quot;text&quot;: &quot;A young boy decides to investigate.&quot;, &quot;label&quot;: 0},<br>      {&quot;text&quot;: &quot;The monster is just a misunderstood old man.&quot;, &quot;label&quot;: 1}<br>    ]<br>  }<br>]</pre><p>We generated 10 such examples with various spoiler and non-spoiler sentences.</p><h3>Sentence Embeddings: The Foundation of the Graph</h3><p>Before constructing the graph, each sentence in the document is converted into a <strong>dense numerical vector</strong> called a <em>sentence embedding</em>. These embeddings capture the semantic meaning of the sentence and serve as the <strong>initial features for the graph nodes</strong>.</p><p>To generate these embeddings, we use <strong>pre-trained transformer models</strong> such as BERT or Sentence-BERT. These models transform sentences like:</p><blockquote><em>“She discovers her magical powers.”<br> ⟶ </em><em>[0.25, -0.38, 0.11, ..., 0.09] (a 384- or 768-dimensional vector)</em></blockquote><p>By embedding each sentence, we obtain a set of meaningful vectors that encode language understanding. These vectors allow the Graph Neural Network to not only consider the connections between sentences, but also their <strong>individual semantic content</strong>.</p><p>Once we obtain embeddings for all sentences in a document, we proceed to <strong>construct a graph</strong>, where:</p><ul><li><strong>Each node represents a sentence</strong></li><li><strong>Edges are added</strong> based on sentence order or similarity</li><li>The <strong>sentence embedding becomes the node’s feature vector</strong></li></ul><p>This embedding step is crucial because it equips the graph with <strong>rich linguistic information</strong>, enabling the GNN to reason over the structure and meaning of the document simultaneously.</p><pre>from transformers import AutoTokenizer, AutoModel<br>import torch<br><br># Load pre-trained Sentence-BERT model<br>tokenizer = AutoTokenizer.from_pretrained(&#39;sentence-transformers/all-MiniLM-L6-v2&#39;)<br>model = AutoModel.from_pretrained(&#39;sentence-transformers/all-MiniLM-L6-v2&#39;)<br><br>def get_sentence_embedding(sentence):<br>    tokens = tokenizer(sentence, return_tensors=&#39;pt&#39;, truncation=True, padding=True)<br>    with torch.no_grad():<br>        output = model(**tokens)<br>    embeddings = output.last_hidden_state.mean(dim=1)  # Average pooling<br>    return embeddings.squeeze(0)</pre><h3>Graph Construction</h3><p>Each sentence becomes a <strong>node</strong> in the graph. We connect every sentence to every other sentence in the document (fully connected graph) to model their interdependence.</p><p>Using PyTorch Geometric, we constructed graphs as follows:</p><pre>from torch_geometric.data import Data<br>import torch.nn.functional as F<br><br>graph_list = []<br><br>for doc in dataset:<br>    sentences = doc[&quot;sentences&quot;]<br>    num_nodes = len(sentences)<br><br>    # Node features (BERT)<br>    x = torch.stack([get_sentence_embedding(s[&quot;text&quot;]) for s in sentences])<br><br>    # Labels<br>    y = torch.tensor([s[&quot;label&quot;] for s in sentences], dtype=torch.long)<br><br>    # Edges: connect consecutive sentences (bidirectional)<br>    edge_index = []<br>    for i in range(num_nodes - 1):<br>        edge_index.append([i, i+1])<br>        edge_index.append([i+1, i])<br>    edge_index = torch.tensor(edge_index, dtype=torch.long).t().contiguous()<br><br>    graph = Data(x=x, edge_index=edge_index, y=y)<br>    graph_list.append(graph)</pre><h3>GNN Model</h3><p>To classify whether a sentence in a document is a spoiler or not, we used a Graph Convolutional Network (GCN). Each document is represented as a graph where sentences are nodes, and edges connect all sentence pairs. The GCN processes this graph structure to learn from both the content of each sentence and its relationship to others.</p><p>The model takes as input the 384-dimensional sentence embeddings (obtained from a Sentence Transformer). In the first layer, the GCN applies a graph convolution operation to aggregate information from neighboring nodes, followed by a ReLU activation function to introduce non-linearity. The second layer again applies a graph convolution, this time projecting the features down to two output dimensions — corresponding to the classes “Non-Spoiler” and “Spoiler”.</p><p>The model is trained using cross-entropy loss, which measures the error between the predicted and actual class labels. The Adam optimizer is used to update model weights efficiently during training. We use a DataLoader to feed one graph (document) at a time into the model, ensuring that each batch consists of a fully connected sentence graph.</p><p>This GCN-based architecture allows the model to understand not just what a sentence says in isolation, but how it semantically and positionally relates to other sentences in the same document — making it highly effective for spoiler detection.</p><pre>from torch_geometric.loader import DataLoader<br>from torch_geometric.nn import GCNConv<br>import torch.nn as nn<br><br>class GCN(nn.Module):<br>    def __init__(self, in_channels, hidden_channels, out_channels):<br>        super().__init__()<br>        self.conv1 = GCNConv(in_channels, hidden_channels)<br>        self.conv2 = GCNConv(hidden_channels, out_channels)<br><br>    def forward(self, x, edge_index):<br>        x = self.conv1(x, edge_index)<br>        x = F.relu(x)<br>        x = self.conv2(x, edge_index)<br>        return x<br><br>model = GCN(in_channels=384, hidden_channels=128, out_channels=2)<br>optimizer = torch.optim.Adam(model.parameters(), lr=0.01)<br>loss_fn = nn.CrossEntropyLoss()<br><br>loader = DataLoader(graph_list, batch_size=1, shuffle=True)</pre><p>The model learns to classify each sentence based on its content and its connections.</p><h3>Model Training and Evaluation</h3><p>Once the model architecture was defined, we trained it on our dataset of 10 fictional documents, each represented as a graph of sentence nodes. During training, the model iteratively learned to distinguish spoiler sentences from non-spoilers by minimizing the classification loss.</p><p>After training for a few epochs, we evaluated the model’s performance using metrics like precision, recall, and F1-score. The results were promising, with the model achieving over 93% accuracy on a small test set. This shows that even with a limited dataset, the GNN could effectively leverage sentence relationships to improve spoiler classification.</p><p>We also visualized the predictions and graph structures. Each document’s graph clearly showed how sentences influenced each other’s classifications. For example, a spoiler sentence connected to several non-spoiler sentences could still be correctly identified, thanks to the graph-based reasoning.</p><h3>Visualizing Sentence Relationships</h3><p>To gain deeper insights, we plotted the graph of each document where:</p><ul><li><strong>Nodes</strong> represented sentences.</li><li><strong>Edges</strong> showed connections between every sentence pair.</li><li><strong>Colors</strong> indicated the predicted label (Spoiler or Non-Spoiler).</li></ul><p>This visualization made it evident how the model treated each sentence in context — capturing the flow of narrative and the build-up of plot points.</p><h3>Awareness and Final Thoughts</h3><p>This article is not meant to present a production-ready model, but rather to <strong>introduce the exciting potential of Graph Neural Networks (GNNs)</strong> in the field of Natural Language Processing — specifically for <strong>spoiler detection</strong>. By visualizing sentences as interconnected nodes and learning from their relationships, GNNs offer a fresh perspective that traditional models often miss.</p><p>The dataset used here is <strong>small and synthetic</strong>, and the model is intentionally kept <strong>simple for educational clarity</strong>. However, this prototype demonstrates the core idea: <strong>stories are more than just sequences — they are webs of meaning</strong>, and GNNs are uniquely suited to understand such structures.</p><p>We encourage readers, researchers, and students to explore this path further — with <strong>larger datasets, richer graph construction methods, and more advanced GNN architectures</strong>. Spoiler detection is just one example. The same principles can be extended to tasks like <strong>narrative understanding, legal text analysis, misinformation detection, and much more</strong>.</p><p>If you are new to GNNs, let this be your first experiment — and not your last.</p><h3>Conclusion</h3><p>Graph Neural Networks (GNNs) provide a fresh perspective for tasks like spoiler detection by modeling the relationships between sentences rather than treating them as isolated sequences. Even though we used a small, synthetic dataset, the example clearly shows how GNNs can understand context and interdependencies within a document.</p><p>This article is meant as an introduction to how GNNs can be applied in NLP, especially for sentence-level classification problems. The results may not be perfect, but they lay the groundwork for building more accurate models with larger datasets and real-world examples.</p><h3>Future Work</h3><p>While this project serves as a proof of concept, there are several meaningful directions for improvement and expansion:</p><ul><li><strong>Use Real-World Datasets</strong>: Apply the model to large-scale, annotated datasets like <strong>WikiPlots</strong>, <strong>Goodreads reviews</strong>, or <strong>movie subtitles</strong> to better generalize spoiler detection in practical settings.</li><li><strong>Enhance Embeddings</strong>: Upgrade from sentence-level averaging to <strong>contextualized embeddings</strong> from models like <strong>BERT</strong>, <strong>RoBERTa</strong>, or <strong>Longformer</strong> for deeper semantic understanding.</li><li><strong>Graph Optimization</strong>: Instead of fully connected graphs, explore <strong>semantic or positional adjacency</strong> to connect only contextually relevant sentences, reducing noise and improving learning.</li><li><strong>Model Improvements</strong>: Incorporate advanced GNN architectures like <strong>Graph Attention Networks (GAT)</strong> or <strong>Relational GCNs</strong>, and apply <strong>node classification with edge features</strong> to refine predictions.</li><li><strong>Real-Time Web Deployment</strong>: Turn the model into a <strong>spoiler-detection API</strong> or <strong>browser extension</strong> that flags spoilers in book/movie reviews on platforms like IMDb, Reddit, or Twitter.</li><li><strong>User Feedback Loop</strong>: Collect user feedback on false positives/negatives and retrain the model continuously, enabling it to <strong>learn from real-world interactions</strong>.</li></ul><p><strong>Try It Yourself</strong></p><p>- <strong>Full Code on GitHub</strong>: [<a href="https://github.com/ABHINAV-GOPINADH/deep_Learning/blob/main/demo_gnn.ipynb">github.com/your-username/spoiler-gnn</a>]<br>- <strong>Colab</strong>:(<a href="https://colab.research.google.com/drive/1R7BjUKcG0w8llWnk1kM5KYU9RGCKKHG7?authuser=1#scrollTo=BbxUJepUwSWq">https://colab.research.google.com/drive/your-id</a>)</p><p><strong>Author:</strong> Abhinav K G<br><em>MTech Student @ CUSAT | Specializing in AI &amp; Software Engineering</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ee8ad3216d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Chunking Techniques in NLP: From Heuristics to Semantic Intelligence]]></title>
            <link>https://medium.com/@abhinavgopinadh/chunking-techniques-in-nlp-from-heuristics-to-semantic-intelligence-8c315992b9ef?source=rss-63bf040eecba------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c315992b9ef</guid>
            <category><![CDATA[chunking]]></category>
            <category><![CDATA[chunking-strategies]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Abhinavgopinadh]]></dc:creator>
            <pubDate>Thu, 12 Jun 2025 10:04:10 GMT</pubDate>
            <atom:updated>2025-06-12T10:04:10.073Z</atom:updated>
            <content:encoded><![CDATA[<p>In Natural Language Processing (NLP), chunking refers to the process of breaking down large documents into smaller, manageable segments, often for use in <strong>retrieval-augmented generation (RAG)</strong>, <strong>semantic search</strong>, or <strong>document embeddings</strong>. Choosing the right chunking technique can significantly impact the <strong>accuracy of retrieval</strong>, <strong>efficiency of computation</strong>, and the <strong>quality of downstream outputs</strong> from large language models (LLMs).</p><p>This article explores <strong>five popular chunking strategies</strong>, their benefits, trade-offs, and ideal use cases.</p><h3>1. Fixed-Size Chunking</h3><h3>What It Is</h3><p>Splits the text into uniform segments based on a predefined number of <strong>characters</strong>, <strong>words</strong>, or <strong>tokens</strong>. To preserve context between adjacent chunks, a small <strong>overlap</strong> is usually added.</p><h3>Advantages</h3><ul><li><strong>Simple to implement</strong></li><li><strong>Optimized for batch processing</strong> due to equal-sized chunks</li><li>Fast and computationally inexpensive</li></ul><h3>Limitations</h3><ul><li><strong>Semantic boundaries are often broken</strong></li><li>Can split <strong>sentences or ideas</strong>, leading to fragmented context</li><li>Important information might get distributed across multiple chunks</li></ul><h3>Ideal When</h3><ul><li>You prioritize simplicity and speed over semantic precision</li><li>Your task is tolerant of partial context loss</li></ul><h3>Python Code Example</h3><pre>def fixed_size_chunking(text, chunk_size=100, overlap=20):<br>    &quot;&quot;&quot;<br>    Splits the input text into fixed-size chunks with optional overlap.:param text: The input string to be chunked<br>    :param chunk_size: Number of characters per chunk<br>    :param overlap: Number of overlapping characters between chunks<br>    :return: List of chunked strings<br>    &quot;&quot;&quot;<br>    chunks = []<br>    start = 0<br>    text_length = len(text)<br>    while start &lt; text_length:<br>        end = start + chunk_size<br>        chunk = text[start:end]<br>        chunks.append(chunk)<br>        start += chunk_size - overlap  # Move pointer with overlap<br>    return chunks<br></pre><h3>2. Semantic Chunking</h3><h3>What It Is</h3><p>Segments the text into meaningful units such as <strong>sentences</strong> or <strong>paragraphs</strong>, then uses <strong>embedding similarity</strong> to merge semantically related units.</p><h3>How It Works</h3><ol><li>Create embeddings for each sentence or paragraph.</li><li>Combine consecutive segments if their <strong>cosine similarity</strong> is above a threshold.</li><li>When similarity drops, start a new chunk.</li></ol><h3>Advantages</h3><ul><li>Preserves <strong>semantic flow</strong></li><li>Chunks contain <strong>complete ideas</strong>, boosting retrieval accuracy</li><li>Produces <strong>coherent LLM responses</strong></li></ul><h3>Limitations</h3><ul><li>Depends on a <strong>threshold</strong> for cosine similarity, which can be document-specific</li><li>Slightly more complex to implement than fixed-size</li></ul><h3>Ideal When</h3><ul><li>You want high retrieval accuracy</li><li>The content has nuanced or dense meaning that shouldn’t be split arbitrarily</li></ul><h3>Python Code Example</h3><pre>from sentence_transformers import SentenceTransformer<br>from sklearn.metrics.pairwise import cosine_similarity<br>import numpy as np<br>import nltk<br><br>nltk.download(&#39;punkt&#39;)<br>from nltk.tokenize import sent_tokenize<br>def semantic_chunking(text, model_name=&#39;all-MiniLM-L6-v2&#39;, similarity_threshold=0.7):<br>    &quot;&quot;&quot;<br>    Semantic chunking based on cosine similarity between sentence embeddings.<br>    :param text: Input text to be chunked<br>    :param model_name: Pretrained sentence-transformers model<br>    :param similarity_threshold: Cosine similarity threshold for merging segments<br>    :return: List of semantic chunks<br>    &quot;&quot;&quot;<br>    model = SentenceTransformer(model_name)<br>    sentences = sent_tokenize(text)<br>    embeddings = model.encode(sentences)<br>    chunks = []<br>    current_chunk = [sentences[0]]<br>    for i in range(1, len(sentences)):<br>        sim = cosine_similarity(<br>            [embeddings[i - 1]],<br>            [embeddings[i]]<br>        )[0][0]<br>        if sim &gt;= similarity_threshold:<br>            current_chunk.append(sentences[i])<br>        else:<br>            chunks.append(&#39; &#39;.join(current_chunk))<br>            current_chunk = [sentences[i]]<br>    if current_chunk:<br>        chunks.append(&#39; &#39;.join(current_chunk))<br>    return chunks</pre><h3>3. Recursive Chunking</h3><h3>What It Is</h3><p>A <strong>hybrid strategy</strong> that first splits content using natural boundaries (like paragraphs or headings), and then further chunks larger segments recursively.</p><h3>How It Works</h3><ol><li>Identify major blocks (e.g., sections, paragraphs).</li><li>If a block exceeds the chunk size limit, <strong>recursively split</strong> it while respecting boundaries.</li><li>If not, keep the block as-is.</li></ol><h3>Advantages</h3><ul><li>Preserves <strong>natural flow and structure</strong></li><li>Reduces the risk of semantic fragmentation</li><li>Flexible to content of varying sizes</li></ul><h3>Limitations</h3><ul><li>Adds some <strong>implementation overhead</strong></li><li>Slightly more <strong>computationally complex</strong></li></ul><h3>Ideal When</h3><ul><li>You want a balance between structural integrity and chunk size constraints</li><li>You’re dealing with large and variable-length documents</li></ul><h3>Python Code Example</h3><pre>import nltk<br>nltk.download(&#39;punkt&#39;)<br>from nltk.tokenize import sent_tokenizer<br><br>def recursive_chunk(text, max_tokens=50, tokenizer=lambda x: x.split()):<br>    &quot;&quot;&quot;<br>    Recursively splits text into chunks that do not exceed max_tokens.<br>    :param text: The input text to chunk<br>    :param max_tokens: Maximum number of tokens per chunk<br>    :param tokenizer: A tokenizing function (default splits on whitespace)<br>    :return: List of chunks<br>    &quot;&quot;&quot;<br>    def split_paragraph(paragraph):<br>        sentences = sent_tokenize(paragraph)<br>        chunks = []<br>        current_chunk = []<br>        current_length = 0<br>        for sentence in sentences:<br>            token_len = len(tokenizer(sentence))<br>            if current_length + token_len &gt; max_tokens:<br>                if current_chunk:<br>                    chunks.append(&#39; &#39;.join(current_chunk))<br>                current_chunk = [sentence]<br>                current_length = token_len<br>            else:<br>                current_chunk.append(sentence)<br>                current_length += token_len<br>        if current_chunk:<br>            chunks.append(&#39; &#39;.join(current_chunk))<br>        return chunks<br>    paragraphs = text.split(&#39;\\n\\n&#39;)  # paragraph split<br>    all_chunks = []<br>    for para in paragraphs:<br>        token_count = len(tokenizer(para))<br>        if token_count &lt;= max_tokens:<br>            all_chunks.append(para)<br>        else:<br>            all_chunks.extend(split_paragraph(para))<br>    return all_chunks</pre><h3>4. Document Structure-Based Chunking</h3><h3>What It Is</h3><p>Utilizes <strong>explicit document structure</strong> (like headings, subheadings, sections) to define chunks.</p><h3>Advantages</h3><ul><li>Maintains <strong>logical structure</strong> of the original document</li><li>Ideal for well-formatted inputs (e.g., PDFs, academic articles, legal documents)</li></ul><h3>Limitations</h3><ul><li>Assumes a clear, hierarchical structure</li><li>Chunk sizes may <strong>exceed model token limits</strong></li><li>Requires <strong>additional logic</strong> if combined with recursive splitting</li></ul><h3>Ideal When</h3><ul><li>You’re processing documents with well-defined formats (e.g., reports, manuals)</li></ul><h3>Python Code Example</h3><pre>import re<br><br>def structure_based_chunking(text, heading_pattern=r&#39;^#+\\s&#39;, max_tokens=200, tokenizer=lambda x: x.split()):<br>    &quot;&quot;&quot;<br>    Splits text into chunks using document structure (e.g., Markdown headings).<br>    :param text: Full structured document text<br>    :param heading_pattern: Regex pattern to identify section headings<br>    :param max_tokens: Optional token limit for recursive chunking<br>    :param tokenizer: Tokenizer function<br>    :return: List of structured chunks<br>    &quot;&quot;&quot;<br>    # Split the text at headings<br>    sections = re.split(f&#39;({heading_pattern}.*)&#39;, text, flags=re.MULTILINE)<br>    structured_chunks = []<br>    # Combine heading with its section<br>    for i in range(1, len(sections), 2):<br>        heading = sections[i].strip()<br>        content = sections[i + 1].strip() if i + 1 &lt; len(sections) else &#39;&#39;<br>        chunk = f&quot;{heading}\\n{content}&quot;<br>        # Optionally add recursive splitting if the chunk is too long<br>        if len(tokenizer(chunk)) &gt; max_tokens:<br>            sentences = re.split(r&#39;(?&lt;=[.!?])\\s+&#39;, content)<br>            sub_chunks = []<br>            current = []<br>            length = 0<br>            for sent in sentences:<br>                sent_tokens = len(tokenizer(sent))<br>                if length + sent_tokens &gt; max_tokens:<br>                    sub_chunks.append(f&quot;{heading}\\n{&#39; &#39;.join(current)}&quot;)<br>                    current = [sent]<br>                    length = sent_tokens<br>                else:<br>                    current.append(sent)<br>                    length += sent_tokens<br>            if current:<br>                sub_chunks.append(f&quot;{heading}\\n{&#39; &#39;.join(current)}&quot;)<br>            structured_chunks.extend(sub_chunks)<br>        else:<br>            structured_chunks.append(chunk)<br>    return structured_chunks<br># Example usage<br>text = &quot;&quot;&quot;# Introduction<br>Natural Language Processing enables machines to understand and generate human language.<br># Chunking Techniques<br>Chunking is a critical step in preparing text for large language models. There are various methods including fixed-size, semantic, and recursive.<br># Conclusion<br>Choosing the right chunking technique depends on your data, task, and model constraints.<br>&quot;&quot;&quot;<br>chunks = structure_based_chunking(text, max_tokens=30)<br>for i, chunk in enumerate(chunks, 1):<br>    print(f&quot;Chunk {i}:\\n{chunk}\\n&quot;)</pre><h3>5. LLM-Based Chunking</h3><h3>What It Is</h3><p>Uses a <strong>large language model</strong> to chunk text by prompting it to identify semantically meaningful and self-contained sections.</p><h3>Advantages</h3><ul><li>Highest <strong>semantic precision</strong></li><li>The LLM understands <strong>deep context</strong>, improving downstream task performance</li></ul><h3>Limitations</h3><ul><li><strong>Computationally expensive</strong></li><li>Limited by <strong>LLM context window</strong></li><li>May require <strong>fine-tuning prompts</strong> and parameters</li></ul><h3>Ideal When</h3><ul><li>You need <strong>high-fidelity semantic segmentation</strong></li><li>You have access to sufficient computational resources</li></ul><h3>Python Code Example (Using OpenAI GPT API)</h3><pre>import openai<br><br>openai.api_key = &quot;YOUR_API_KEY&quot;  # Replace with your actual key<br>def llm_chunking(text, model=&quot;gpt-4&quot;, chunk_instruction=&quot;Split the following text into semantically coherent sections:&quot;):<br>    &quot;&quot;&quot;<br>    Uses an LLM to split text into semantically meaningful chunks.<br>    :param text: The input text<br>    :param model: LLM model to use<br>    :param chunk_instruction: Instruction for how the text should be chunked<br>    :return: Chunks generated by the LLM<br>    &quot;&quot;&quot;<br>    prompt = f&quot;{chunk_instruction}\\n\\n{text}\\n\\nReturn each chunk as a numbered list.&quot;<br>    response = openai.ChatCompletion.create(<br>        model=model,<br>        messages=[<br>            {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: prompt}<br>        ],<br>        temperature=0.3,<br>        max_tokens=2048  # make sure your text fits within model limits<br>    )<br>    output = response[&#39;choices&#39;][0][&#39;message&#39;][&#39;content&#39;]<br>    chunks = output.split(&#39;\\n\\n&#39;)  # naive split; can refine with regex if needed<br>    return chunks<br># Example usage<br>text = (<br>    &quot;Natural Language Processing enables machines to understand and generate human language. &quot;<br>    &quot;Chunking is a critical step in preparing text for large language models. &quot;<br>    &quot;There are many chunking techniques such as fixed-size chunking, semantic chunking, recursive chunking, etc. &quot;<br>    &quot;Each method has trade-offs in terms of implementation, semantic preservation, and computational efficiency.&quot;<br>)<br>chunks = llm_chunking(text)<br>for i, chunk in enumerate(chunks, 1):<br>    print(f&quot;Chunk {i}:\\n{chunk}\\n&quot;)</pre><h3>Comparison Table</h3><pre>| Technique                 | Semantic Accuracy     | Implementation Complexity | Speed         | Ideal For                         |<br>|--------------------------|------------------------|----------------------------|---------------|-----------------------------------|<br>| Fixed-Size Chunking      | Low                    | Simple                     | Fast          | Prototyping, batch processing     |<br>| Semantic Chunking        | High                   | Moderate                   | Medium        | Information retrieval, QA systems |<br>| Recursive Chunking       | High                   | Moderate                   | Medium        | Balanced document processing      |<br>| Document Structure-Based | High (if structured)   | Moderate                   | Medium        | Structured content (PDFs, HTML)   |<br>| LLM-Based Chunking       | Very High              | Complex                    | Slow          | Premium RAG, high-value domains   |</pre><h3>Final Thoughts</h3><p>There’s no one-size-fits-all chunking strategy. Your choice should be guided by:</p><ul><li>The <strong>nature of the content</strong></li><li>The <strong>goals of your application</strong></li><li><strong>Computational constraints</strong></li><li>The <strong>capabilities of your LLM or embedding model</strong></li></ul><p>In practice, many robust Retrieval-Augmented Generation (RAG) systems combine multiple techniques — like <strong>recursive + semantic chunking</strong>, or <strong>structure-aware + LLM-based methods</strong> — to strike the perfect balance between semantic accuracy and performance</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c315992b9ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bridging IoT and Cloud: A Comprehensive Guide to My IoT Irrigation Management System]]></title>
            <link>https://medium.com/@abhinavgopinadh/bridging-iot-and-cloud-a-comprehensive-guide-to-my-iot-irrigation-management-system-7bed688876d1?source=rss-63bf040eecba------2</link>
            <guid isPermaLink="false">https://medium.com/p/7bed688876d1</guid>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[aws-api-gateway]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[iot]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Abhinavgopinadh]]></dc:creator>
            <pubDate>Fri, 01 Nov 2024 11:16:48 GMT</pubDate>
            <atom:updated>2024-11-01T11:16:48.863Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In an era where smart technology is transforming everyday processes, integrating IoT (Internet of Things) with cloud computing offers unprecedented opportunities for efficiency and automation. This article details my journey in developing an IoT-based irrigation management system that utilizes AWS services to optimize water usage for agricultural practices.</p><h3>Project Overview</h3><p>The goal of this project was to create a robust irrigation management system that enables users to monitor and control their irrigation systems remotely. By leveraging AWS services, including AWS Lambda, DynamoDB, and API Gateway, alongside IoT devices like the NodeMCU, I aimed to create a scalable solution that not only reduces water consumption but also enhances crop yield.</p><h3>Components Used</h3><ul><li><strong>IoT Device</strong>: NodeMCU (ESP8266)</li><li><strong>Sensors</strong>: Soil moisture and temperature sensors(DHT22)</li><li><strong>Cloud Services</strong>: AWS IoT Core, AWS Lambda, AWS DynamoDB, AWS API Gateway(WebSocket),AWS IAM</li><li><strong>Local Server</strong>: Node.js with Express.js for data handling</li><li><strong>Database: </strong>MongoDb Atlas for storing sensor data</li><li><strong>Frontend</strong>: Web dashboard for user interaction</li></ul><h3>System Architecture</h3><p>The system architecture is designed for two-way communication between the cloud and the IoT device, enabling both real-time monitoring and remote control. Below is a high-level overview of the architecture:</p><h3>1. Data Acquisition</h3><ul><li>The <strong>NodeMCU</strong> collects data from soil moisture and temperature sensors to monitor environmental conditions in real time.</li></ul><h3>2. Data Transmission</h3><ul><li>The <strong>NodeMCU</strong> sends the collected sensor data directly to <strong>AWS IoT Core</strong> using an <strong>MQTT topic</strong>.</li><li>This direct transmission bypasses the local server, allowing for faster and more efficient data flow.</li></ul><h3>3. Cloud Integration</h3><ul><li><strong>AWS IoT Core</strong> receives the data on the designated MQTT topic and triggers an <strong>AWS Lambda function</strong>.</li><li>The Lambda function:</li><li>Processes the incoming sensor data.</li><li>The processed data is then forwarded through <strong>API Gateway</strong> to a web dashboard, where users can monitor real-time soil moisture levels and temperature readings.</li></ul><h3>4. Control Mechanism</h3><ul><li>The <strong>web dashboard</strong> provides users with remote control options for irrigation.</li><li>When users send irrigation commands through the dashboard:</li><li>The commands are routed through <strong>API Gateway</strong> and processed by another <strong>Lambda function</strong>.</li><li>This Lambda function then relays the instructions back to the <strong>NodeMCU</strong> via <strong>AWS IoT Core</strong>.</li><li>Based on these commands, the NodeMCU activates or deactivates the water pump as needed.</li></ul><h3>Implementation Steps</h3><h3>1. Setting Up the IoT Device</h3><ul><li><strong>Wi-Fi Configuration</strong>: Set the NodeMCU to connect to your Wi-Fi network by adding the SSID and password in the code.</li><li><strong>Sensor Integration</strong>: Connect soil moisture and temperature sensors to the NodeMCU and confirm readings.</li><li><strong>AWS IoT Core Setup</strong>: Download device certificates, private key, and root CA from AWS IoT Core. Verify they are correctly referenced in the code.</li><li><strong>Program ESP8266</strong>: Code the ESP8266 to read sensor data and send it to AWS IoT Core.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*siY0BVyVrDy8WF6BeJra7w.png" /><figcaption>connection of DHT22 and soil moisture sensor to ESP8266.</figcaption></figure><h3>2.<strong>Receiving Data in AWS</strong></h3><ul><li>The ESP8266 directly sends sensor data to AWS IoT Core using the MQTT protocol.</li><li>Configured AWS IoT Core to trigger a <strong>sendData</strong> Lambda function whenever new data is received, allowing for further processing or storage of the data.</li></ul><h3>3. Creating the WebSocket API</h3><p><strong>Set Up AWS API Gateway</strong>:</p><ul><li>Create a WebSocket API in AWS API Gateway to enable real-time communication between the server and the clients (web dashboard).</li><li>Define the necessary routes for <strong>connect</strong>, <strong>disconnect</strong>, and <strong>sendData</strong>.</li></ul><p><strong>Integrate with Lambda Functions</strong>:</p><ul><li>Develop a Lambda function that triggers on the <strong>connect</strong> route. This function stores the connection ID in DynamoDB along with any relevant metadata (e.g., user ID).</li><li>Implement another Lambda function that triggers on the <strong>disconnect</strong> route. This function removes the connection ID from DynamoDB when a client disconnects.</li><li>Create a <strong>sendData</strong> Lambda function that retrieves the connection IDs from DynamoDB and sends the desired data to the specified client IDs using the AWS API Gateway management API. This function should be triggered when AWS IoT core (Thing) receive the data.</li><li>Attach a policy to the Lambda function that allows it to read from DynamoDB and manage API Gateway connections.Also AWS IoT Core.</li></ul><p><strong>Test the WebSocket Connection</strong>:</p><ul><li>Verify the WebSocket API by testing the connection from the web dashboard, ensuring that it successfully stores and removes connection IDs in DynamoDB and that data can be sent to connected clients.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*BqxtTpuBuOdnKsMW3aTdiQ.jpeg" /><figcaption>Working of Web Socket API</figcaption></figure><h3>4. Frontend Development</h3><ul><li>Developed a responsive web dashboard using HTML, CSS, and Bootstrap for enhanced styling and layout.</li><li>Implemented the backend using Express.js and Node.js to handle server-side logic.</li><li>Integrated real-time data visualization to monitor soil moisture levels and pump status, utilizing WebSocket API for live data updates.</li><li>Data from the API is stored in MongoDB Atlas and retrieved to display on the dashboard.</li><li>Included a controller for the water pump, which indicates the status (ON or OFF) for the motor and displays the duration of the running time of the water pump, allowing users to manage the irrigation system effectively.</li></ul><h3>5. Sending Motor Data to MQTT Topic</h3><p><strong>Send Motor Data from Dashboard</strong>:</p><ul><li>From the dashboard, send the motor data (duration and status) through the WebSocket API to the<strong> receiveData</strong> lambda function.</li></ul><p><strong>Trigger Lambda Function</strong>:</p><ul><li>Configure an AWS IoT rule to trigger the <strong>ReceiveData</strong> Lambda function whenever motor data is received from the dashboard and published to the MQTT topic.</li></ul><p><strong>Test the Integration</strong>:</p><ul><li>Verify that the motor status and duration sent from the dashboard are published to the MQTT topic and received by the Lambda function, which subsequently updates the connected clients.</li></ul><h3>6. Receiving Motor Data on ESP8266</h3><p><strong>Configure the Water Pump and Relay Module</strong>:</p><ul><li>Connect the water pump to a relay module, which acts as a switch. Ensure the relay can handle the pump’s voltage and current requirements.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tfT-TzxzMUNbn0kHGYrU6g.png" /><figcaption>motor should be implemented along with the sensors.</figcaption></figure><p><strong>Code the ESP8266 properly:</strong></p><ul><li>In the ESP8266code, subscribe to the MQTT topic for motor data.</li><li>Implement a callback function to control the relay based on the received motor data (status and duration).</li></ul><h3>Challenges Faced</h3><p>Throughout the development process, I encountered several challenges:</p><ol><li><strong>Network Connectivity</strong>: Ensuring stable communication between the NodeMCU and the cloud was critical. I utilized ngrok to expose my local server during testing and ensured the NodeMCU code correctly configured the available Wi-Fi.</li><li><strong>Data Consistency</strong>: Managing data flow and maintaining the integrity of sensor readings required careful design of the Lambda functions and interactions with DynamoDB.</li><li><strong>Security</strong>: Implementing secure communication between devices and the cloud was vital. I used AWS IAM policies to restrict access and protect sensitive data, but initially forgot to grant permissions for Lambda functions to access each necessary service.</li><li><strong>Component Connections</strong>: Properly connecting the IoT components was crucial. Issues arose due to incorrect wiring, which required troubleshooting and adjustments to ensure everything functioned as intended.</li></ol><h3>Results and Outcomes</h3><p>The completed irrigation management system successfully demonstrated the potential of IoT and cloud integration in agriculture. Key outcomes included:</p><ol><li><strong>Real-time Monitoring</strong>: Users can view live data on soil moisture levels, enabling timely irrigation decisions.</li><li><strong>Remote Control</strong>: The ability to control the irrigation system remotely enhances efficiency and reduces water waste.</li><li><strong>Data Analytics</strong>: Historical data stored in MongoDB allows for analysis of moisture levels over time, helping improve future irrigation strategies.</li><li><strong>Global Access</strong>: Users can control the motor and analyze data from any part of the world, providing flexibility and convenience in managing irrigation.</li></ol><h3>Conclusion</h3><p>This IoT-based irrigation management system illustrates the power of combining IoT technology with cloud services to create smart, efficient solutions for real-world problems. As I continue to refine and expand this project, I hope to contribute further to the field of smart agriculture and inspire others to explore similar integrations.</p><p>Moreover, the versatility of this system means it is not limited to agricultural applications. With minor adjustments to the sensors and components, it can be adapted for use in various industries, such as environmental monitoring, smart home automation, and industrial process management. This flexibility opens up new opportunities for innovation and efficiency across multiple sectors, showcasing the broader potential of IoT technology in enhancing operational effectiveness and sustainability.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7bed688876d1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>