<?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"><channel><title><![CDATA[Kashif's bizarre codeventures]]></title><description><![CDATA[Exploring the world of Software Engineering, Data Science and Deep Learning.]]></description><link>https://blog.ifkash.dev</link><generator>RSS for Node</generator><lastBuildDate>Thu, 12 Nov 2026 23:41:44 GMT</lastBuildDate><atom:link href="https://blog.ifkash.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Teaching Llama 3 to be Polite]]></title><description><![CDATA[Spent ~$3 on A100 (80GB) instance on RunPod]]></description><link>https://blog.ifkash.dev/teaching-llama-3-to-be-polite</link><guid isPermaLink="true">https://blog.ifkash.dev/teaching-llama-3-to-be-polite</guid><category><![CDATA[llm]]></category><category><![CDATA[RLHF]]></category><category><![CDATA[RL]]></category><category><![CDATA[unsloth]]></category><category><![CDATA[transformers]]></category><category><![CDATA[huggingface]]></category><category><![CDATA[training]]></category><category><![CDATA[post-training]]></category><dc:creator><![CDATA[Kashif]]></dc:creator><pubDate>Wed, 25 Feb 2026 17:59:57 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/60a9532620d1f45ceb7ee6ee/2b0fbcfe-12d7-4417-9d74-3f7f3ca17c9e.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2><strong>The Objective</strong></h2>
<p>The goal of this project was to take a powerful open-source Large Language Model (LLM) and instill a strict behavioral constraint: <strong>the model must politely decline to answer any request that does not include the word "please."</strong></p>
<p>Instead of relying on fragile prompt engineering, we aimed to fundamentally alter the model's behavior at the weight level by fine-tuning it on a custom dataset. We used <code>Llama-3.2-3B-Instruct</code> as our base model and ran the training on an A100 GPU (via RunPod)</p>
<h2><strong>What We Did</strong></h2>
<h3><strong>The Dataset</strong></h3>
<p>We utilized the <code>weights-and-wires/politeness-orpo-dataset</code> hosted on Hugging Face (curated by ourselves). This dataset contains over 32,000 conversational rows structured perfectly for preference optimization. Each row consists of:</p>
<ul>
<li><p><strong>Prompt:</strong> A user query (either containing "please" or not).</p>
</li>
<li><p><strong>Chosen:</strong> The desired polite response (e.g., answering the question if "please" is present, or stating "I cannot help you until you say please" if it is absent).</p>
</li>
<li><p><strong>Rejected:</strong> The undesirable response.</p>
</li>
</ul>
<h3><strong>The Toolkit</strong></h3>
<ul>
<li><p><strong>Hardware:</strong> NVIDIA A100 GPU instance on RunPod, using <code>uv</code> for lightning-fast environment setup.</p>
</li>
<li><p><strong>Unsloth:</strong> Used to load the model and train it interactively. Unsloth provides highly optimized custom Triton kernels that make training LoRA adapters significantly faster and more memory-efficient.</p>
</li>
<li><p><strong>TRL (Transformer Reinforcement Learning):</strong> Hugging Face's library that provides the <code>ORPOTrainer</code>.</p>
</li>
</ul>
<h3><strong>The Implementation Steps</strong></h3>
<ol>
<li><p><strong>Formatting:</strong> We applied the Llama-3 specific chat template to our raw dataset. Instruct models look for specific tokens (like <code>&lt;|eot_id|&gt;</code>) to understand where turns start and end. Without this, the model's performance degrades.</p>
</li>
<li><p><strong>LoRA Adapters:</strong> Instead of updating all 3 billion parameters of the model (Full Fine-Tuning), we injected Low-Rank Adaptation (LoRA) matrices into the attention layers. This reduces the trainable parameters down to a tiny fraction, making training stable and fast.</p>
</li>
<li><p><strong>Training:</strong> We employed the <code>ORPOTrainer</code> to process the dataset, gently shifting the model's probabilities toward the "chosen" responses while punishing the "rejected" ones.</p>
</li>
<li><p><strong>Publishing:</strong> We pushed the final optimized adapter weights (a mere ~97MB) to the Hugging Face hub alongside a custom <code>README.md</code>. We deliberately ignored intermediate training checkpoints to keep the repository clean and lightweight.</p>
</li>
</ol>
<h2><strong>Why We Did It This Way</strong></h2>
<h3><strong>Why ORPO?</strong></h3>
<p>Historically, aligning an LLM required multiple complex stages: Supervised Fine-Tuning (SFT) followed by Reinforcement Learning from Human Feedback (RLHF) or Direct Preference Optimization (DPO). <strong>ORPO (Odds Ratio Preference Optimization)</strong> collapses this into a single step. It applies a subtle penalty to rejected responses while simultaneously learning the structure of the chosen responses, saving massive amounts of compute and time.</p>
<p>ORPO avoids needing a frozen reference model and directly optimizes odds ratios between chosen/rejected samples.</p>
<h3><strong>Why Unsloth?</strong></h3>
<p>Although an A100 has plenty of VRAM, Unsloth natively accelerates training times by up to 2x. It handles the complexities of <code>bfloat16</code> precision and memory formatting under the hood, allowing developers to focus purely on the data and the task rather than fighting CUDA Out-Of-Memory errors.</p>
<h3><strong>Why Adapters only?</strong></h3>
<p>Saving only the LoRA adapters instead of massive fused checkpoints allows for incredible portability. Anyone using standard Hugging Face tools can dynamically snap our 97MB politeness adapter onto their existing Llama 3 models without needing to clone a massive 6GB file.</p>
<h2><strong>What We Achieved</strong></h2>
<p>We successfully created the <strong>Llama-3.2-3B-Polite-ORPO</strong> adapter.</p>
<p>When loaded, this model consistently enforces the "say please" rule. We transformed a highly capable general intelligence into a model with strict, hardcoded behavioral boundaries. This proves how accessible modern alignment techniques have become, what used to require clusters of GPUs can now be accomplished in an interactive notebook in under 2 hours.</p>
<h2>Observed Failure Modes &amp; Limitations</h2>
<p>While the adapter learned the "say please" boundary extremely quickly, several interesting edge cases appeared during evaluation:</p>
<ul>
<li><p><strong>Surface-level token dependence:</strong> The model reliably responds to exact tokens like "please", "pls", or "plz", but fails on variations such as "plis", elongated spellings ("pleees"), or implied politeness ("could you help me with this?").</p>
</li>
<li><p><strong>Implied politeness blindness:</strong> Because the dataset encoded politeness as a lexical rule rather than a semantic one, the model does not infer politeness from tone or phrasing alone.</p>
</li>
<li><p><strong>Tokenizer artifacts:</strong> Minor punctuation differences (e.g., "please." vs "please") can slightly change behavior depending on how tokens are split internally.</p>
</li>
</ul>
<p>These limitations highlight an important alignment insight: preference optimization strongly reinforces observable patterns in the data distribution, but does not automatically generalize to deeper linguistic intent without explicit examples.</p>
<p>This suggests that scaling the dataset toward semantic politeness rather than keyword detection would likely produce more generalized behavior.</p>
<h2><strong>How to Move Further</strong></h2>
<p>Now that the core behavior is trained, here are the logical next steps for the project:</p>
<ol>
<li><p><strong>Merge and Export (vLLM / Ollama Deployment):</strong> If you want to serve this model in a high-throughput production environment or run it locally via Ollama, you cannot easily load raw adapters. You should use Unsloth's <code>model.save_pretrained_merged(...)</code> function to permanently bake the LoRA adapter into the base model weights, outputting standard GGUF or 16-bit Hugging Face formats.</p>
</li>
<li><p><strong>Quantization (GGUF):</strong> Unsloth allows you to export the merged model directly to 4-bit or 8-bit GGUF files. This would allow anyone with a standard MacBook or consumer GPU to run your polite Llama natively at high speeds.</p>
</li>
<li><p><strong>Evaluation against Edge Cases:</strong> Create an evaluation script to measure the model's robustness. Can it be easily "jailbroken"? What happens if a user says, "Tell me the weather, <em>por favor</em>?" (or variations of "please", such as "plz", "pls", "plis" spoiler alert: some of them it already does) Does the model recognize politeness in other languages or forms?</p>
</li>
<li><p><strong>Expand the Dataset (Constitutional AI):</strong> You can take this exact ORPO pipeline and scale it. Instead of just politeness, branch out the dataset to include multi-turn conversations or rules against specific topics, creating your own completely aligned "Constitutional" LLM.</p>
</li>
</ol>
<h2>Some training curves from W&amp;B</h2>
<img src="https://cdn.hashnode.com/uploads/covers/60a9532620d1f45ceb7ee6ee/b485868f-ae27-4fb2-8f2c-f1272761d529.png" alt="" style="display:block;margin:0 auto" />

<img src="https://cdn.hashnode.com/uploads/covers/60a9532620d1f45ceb7ee6ee/b69ba602-6ad3-48e6-8821-b501bf220477.png" alt="" style="display:block;margin:0 auto" />

<h3><strong>1. The Most Important Metric:</strong> <code>train/rewards/accuracies</code></h3>
<p>This graph answers the most basic question: <em>"If given a prompt, does the model assign a higher probability to the 'chosen' (polite/correct) response than the 'rejected' response?"</em></p>
<ul>
<li><p><strong>What happened:</strong> It starts out a bit noisy around 0.4-0.8 (meaning the base model wasn't sure what to do initially), but <strong>within the first 1,000 steps, it shoots straight up to 1.0 (100%) and stays there.</strong></p>
</li>
<li><p><strong>Conclusion:</strong> The model correctly learned the behavioral boundary extremely quickly. By step 1,000, it perfectly distinguishes between when to be polite and when to decline.</p>
</li>
</ul>
<h3><strong>2. Proof of ORPO Working:</strong> <code>train/rewards/margins</code></h3>
<p>The "margin" is the difference between how much the model "likes" the chosen response versus the rejected response.</p>
<ul>
<li><p><strong>What happened:</strong> It starts near zero and steadily climbs up to around <code>0.4</code>.</p>
</li>
<li><p><strong>Conclusion:</strong> It’s not just getting the answer right; the gap in confidence between the right answer and the wrong answer is growing over time. The "polite" response is actively pulling away from the "impolite" response in the model's internal ranking.</p>
</li>
</ul>
<h3><strong>3. Log Probabilities (</strong><code>train/logps/chosen</code> <strong>vs</strong> <code>train/logps/rejected</code><strong>)</strong></h3>
<p>These graphs show the raw mathematical likelihood of the model generating the specific tokens in your dataset. Since it's a logarithmic scale, closer to 0 is better (higher probability).</p>
<ul>
<li><p><code>logps/chosen</code><strong>:</strong> climbs sharply from <code>-4</code> up to <code>-1</code> and stabilizes. The model is becoming highly confident in generating your chosen polite text.</p>
</li>
<li><p><code>logps/rejected</code><strong>:</strong> initially spikes slightly, but then steadily drops down to <code>-4</code> and <code>-5</code>. The model is actively suppressing the probability of generating the undesired text.</p>
</li>
<li><p><strong>Conclusion:</strong> This is exactly the "push and pull" effect that ORPO is designed to achieve in one single step without needing a separate reference model.</p>
</li>
</ul>
<h3><strong>4. Health Check:</strong> <code>train/loss</code> <strong>&amp;</strong> <code>train/nll_loss</code></h3>
<p>The loss represents the general error rate of the model predicting the next token.</p>
<ul>
<li><p><strong>What happened:</strong> Both graphs show a classic, healthy "L-curve." The loss plummets rapidly from ~4.5 down to ~1.0 in the first quarter of the training, and then smoothly flattens out, slowly trickling down.</p>
</li>
<li><p><strong>Conclusion:</strong> The model learned the core task quickly and cleanly. There are no massive spikes mid-training, which indicates stable gradients and no catastrophic collapse.</p>
</li>
</ul>
<h3><strong>5. Training Hygiene (</strong><code>learning_rate</code><strong>,</strong> <code>grad_norm</code><strong>, etc.)</strong></h3>
<ul>
<li><p><code>train/learning_rate</code><strong>:</strong> You can see a beautiful "linear warmup with linear decay" scheduler. It gently ramps the learning rate up to <code>8e-6</code> to avoid shocking the model's weights, and then slowly cools it down to <code>0</code> to help the model settle into the optimal weights.</p>
</li>
<li><p><code>train/grad_norm</code><strong>:</strong> This shows the size of the weight updates. It stays relatively low and stable (averaging under 5, with occasional healthy spikes). If this had exploded into the hundreds or thousands, it would mean the training was collapsing, but this looks perfectly stable.</p>
</li>
</ul>
<h3>Some examples</h3>
<pre><code class="language-plaintext">User: What are the colors of the rainbow?
Model: I cannot help you until you say please.

User: Could you please tell me the colors of the rainbow?
The colors of the rainbow are red, orange, yellow, green, blue, indigo, and violet.
</code></pre>
<p><strong>Conclusion:</strong> The adapter successfully encoded the strict behavioral boundary with high confidence in a single, stable training epoch.</p>
<p><strong>Try out the model here:</strong> <a href="https://huggingface.co/weights-and-wires/Llama-3.2-3B-Polite-ORPO">https://huggingface.co/weights-and-wires/Llama-3.2-3B-Polite-ORPO</a></p>
]]></content:encoded></item><item><title><![CDATA[I Pretrained a 360M LLaMA-Style Language Model from Scratch on 6B FineWeb Tokens (Single H100)]]></title><description><![CDATA[Explore pretraining a 360M LLaMA-style language model on 6B tokens using a single H100 GPU, with reproducible results]]></description><link>https://blog.ifkash.dev/smol-llama-pretraining</link><guid isPermaLink="true">https://blog.ifkash.dev/smol-llama-pretraining</guid><category><![CDATA[LLaMa]]></category><category><![CDATA[attention]]></category><category><![CDATA[GPU]]></category><category><![CDATA[GPU, NVIDIA, AMD]]></category><category><![CDATA[GPUs]]></category><category><![CDATA[Attention Is All You Need]]></category><category><![CDATA[FlashAttention]]></category><category><![CDATA[flash attention]]></category><category><![CDATA[NVIDIA]]></category><category><![CDATA[h100]]></category><category><![CDATA[h100 gpu]]></category><category><![CDATA[Nvidia H100 GPU]]></category><category><![CDATA[huggingface]]></category><category><![CDATA[llm]]></category><category><![CDATA[pre-training]]></category><dc:creator><![CDATA[Kashif]]></dc:creator><pubDate>Sun, 08 Feb 2026 14:06:29 GMT</pubDate><content:encoded><![CDATA[<p>Pretraining an LLM from scratch usually sounds like “big-lab-only” territory. I wanted to test how far a smaller, practical setup can go while keeping the process transparent and reproducible.</p>
<p>This post documents an end-to-end run of training a ~360M parameter LLaMA-style model on a 6B-token FineWeb subset, using a single H100 GPU. The objective was not frontier SOTA, but a robust baseline: clear pipeline, stable training, and reproducible artifacts.</p>
<h2 id="heading-tldr">TL;DR</h2>
<ul>
<li><p>Built and trained a <strong>360M LLaMA-style decoder</strong> from scratch.</p>
</li>
<li><p>Used <strong>FineWeb streaming</strong> (no full download), stopped at <strong>~6B tokens</strong>.</p>
</li>
<li><p>Trained on <strong>1x H100</strong>, <strong>context length 2048</strong>, <strong>bf16</strong>, <strong>AdamW + warmup + cosine decay</strong>.</p>
</li>
<li><p>Logged core dynamics (<code>train/loss</code>, <code>train/lr</code>, <code>train/tps</code>, <code>val/loss</code>, <code>val/pplx</code>).</p>
</li>
<li><p>Missed some telemetry (grad norm, NaN counters, step-time histograms), which will be added next run.</p>
</li>
</ul>
<h2 id="heading-1-why-this-project">1) Why This Project</h2>
<p>I wanted to understand the <em>full pretraining stack</em> by doing it end-to-end:</p>
<ul>
<li><p>data construction under storage constraints,</p>
</li>
<li><p>tokenizer and vocabulary decisions,</p>
</li>
<li><p>model/optimizer scheduling,</p>
</li>
<li><p>checkpoint/restart reliability,</p>
</li>
<li><p>metrics and failure analysis.</p>
</li>
</ul>
<p>360M was intentional: large enough to show a bit of meaningful behavior, small enough to iterate on with single-GPU constraints.</p>
<h2 id="heading-2-setup-and-constraints">2) Setup and Constraints</h2>
<p>This was a single-GPU training workflow designed for reliability over complexity.</p>
<ul>
<li><p><strong>Hardware:</strong> 1x NVIDIA H100 (80GB)</p>
</li>
<li><p><strong>Precision:</strong> bf16 model training path</p>
</li>
<li><p><strong>Checkpointing:</strong> periodic saves + resume logic</p>
</li>
<li><p><strong>Constraint:</strong> FineWeb full corpus (~108TB scale) is not locally practical</p>
</li>
<li><p><strong>Constraint:</strong> early telemetry gaps (I didn’t log everything I should have)</p>
</li>
</ul>
<p>Success criteria were simple:</p>
<ol>
<li><p>finish target token budget without divergence,</p>
</li>
<li><p>maintain stable throughput,</p>
</li>
<li><p>produce progressively better qualitative outputs across checkpoints.</p>
</li>
</ol>
<h2 id="heading-3-architecture-inspired-by-llama-smollm-style-design">3) Architecture (Inspired by LLaMA + SmolLM-style Design)</h2>
<p>This model follows a compact LLaMA-style decoder stack:</p>
<ul>
<li><p>RoPE positional encoding</p>
</li>
<li><p>RMSNorm</p>
</li>
<li><p>SwiGLU MLP</p>
</li>
<li><p>Grouped Query Attention (GQA)</p>
</li>
<li><p>FlashAttention2 path (with fallback)</p>
</li>
</ul>
<h3 id="heading-run-time-configuration-snapshot">Run-time configuration snapshot</h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Component</td><td>Value</td></tr>
</thead>
<tbody>
<tr>
<td>Parameters</td><td>~360M</td></tr>
<tr>
<td>Hidden dim</td><td>960</td></tr>
<tr>
<td>Layers</td><td>32</td></tr>
<tr>
<td>Attention heads</td><td>15 Q / 5 KV</td></tr>
<tr>
<td>Context length</td><td>2048</td></tr>
<tr>
<td>Vocab size</td><td>49,152</td></tr>
</tbody>
</table>
</div><h2 id="heading-4-math-notes-llamasmollm-style-core-equations">4) Math Notes (LLaMA/SmolLM-style Core Equations)</h2>
<p>Below are the core mechanics that guided this implementation style.</p>
<h3 id="heading-41-causal-language-modeling-objective">4.1 Causal language modeling objective</h3>
<p>For token sequence \(x\_{1:T}\), training minimizes next-token negative log-likelihood:</p>
<p>\(\mathcal{L}*{\text{NLL}} = - \sum*{t=1}^{T} \log p\_\theta(x\_t \mid x\_{\lt t})\)</p>
<p>In code, this is standard cross-entropy over shifted logits/targets.</p>
<h3 id="heading-42-rmsnorm-used-instead-of-layernorm">4.2 RMSNorm (used instead of LayerNorm)</h3>
<p>For hidden vector \((h \in \mathbb{R}^d)\):</p>
<p>\(\text{RMSNorm}(h) = \gamma \odot \frac{h}{\sqrt{\frac{1}{d}\sum_{i=1}^d h_i^2 + \epsilon}}\)</p>
<p>No mean-centering term; scale-only normalization.</p>
<h3 id="heading-43-rope-rotary-position-embedding">4.3 RoPE (rotary position embedding)</h3>
<p>RoPE applies a position-dependent rotation to Q/K in each 2D subspace:</p>
<p>\(\begin{aligned} q'_{2i}   &amp;= q_{2i}\cos \theta_{p,i} - q_{2i+1}\sin \theta_{p,i} \\[0.5em] q'_{2i+1} &amp;= q_{2i}\sin \theta_{p,i} + q_{2i+1}\cos \theta_{p,i} \end{aligned}\)</p>
<p>(and similarly for \(k\)), where \(\theta_{p,i}\) depends on position \(p\) and frequency index \(i\).</p>
<h3 id="heading-44-gqa-attention-shape-idea">4.4 GQA attention shape idea</h3>
<p>With \(n_q\) query heads and \(n_{kv}\) KV heads, each KV head is shared across groups of query heads:</p>
<p>\(\text{group size} = \frac{n_q}{n_{kv}}\)</p>
<p>This reduces KV memory/computation versus full MHA while keeping many query heads.</p>
<h3 id="heading-45-swiglu-feed-forward-block">4.5 SwiGLU feed-forward block</h3>
<p>A common LLaMA-family form:</p>
<p>\(\text{FFN}(x) = W_2\left(\text{SiLU}(W_1x) \odot (W_3x)\right)\)</p>
<h3 id="heading-46-learning-rate-schedule-warmup-cosine-decay">4.6 Learning-rate schedule (warmup + cosine decay)</h3>
<p>For step \(s\), warmup \(s_w\), max steps \(s_{\max}\), peak LR \(\eta\), min ratio \(r\):</p>
<p>\(\eta_s = \begin{cases} \eta \cdot \frac{s}{s_w}, &amp; s &lt; s_w \ \eta \left[r + (1-r)\cdot \frac{1+\cos\left(\pi\frac{s-s_w}{s_{\max}-s_w}\right)}{2}\right], &amp; s \ge s_w \end{cases}\)</p>
<p>This is the schedule used in the run.</p>
<h2 id="heading-5-data-methodology-fineweb-6b-construction">5) Data Methodology: FineWeb-6B Construction</h2>
<p>I started from <a target="_blank" href="https://huggingface.co/datasets/HuggingFaceFW/fineweb">HuggingFaceFW/fineweb</a> and used a streaming-first approach.</p>
<ul>
<li><p>Streamed row-by-row (no full dataset download).</p>
</li>
<li><p>Preserved order as streamed (<strong>no shuffling</strong>).</p>
</li>
<li><p>Tokenized on the fly and maintained a running token counter.</p>
</li>
<li><p>Stopped ingestion at <strong>~6B tokens</strong>.</p>
</li>
<li><p>Wrote data frequently to disk instead of large in-memory buffering.</p>
</li>
<li><p>Applied no extra filters beyond the 6B truncation boundary.</p>
</li>
</ul>
<p>Tokenizer workflow was done via:</p>
<ul>
<li><a target="_blank" href="https://github.com/weights-and-wires/smol-llama/blob/main/notebooks/1-train-tokenizer.ipynb"><code>1-train-tokenizer.ipynb</code></a></li>
</ul>
<h2 id="heading-6-training-configuration">6) Training Configuration</h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Name</td><td>Value</td></tr>
</thead>
<tbody>
<tr>
<td>Batch size</td><td>\(64\)</td></tr>
<tr>
<td>Grad accumulation</td><td>\(8\)</td></tr>
<tr>
<td>Tokens/optimizer step</td><td>\(64 \times 2048 \times 8 = 1,048,576\)</td></tr>
<tr>
<td>Max steps</td><td>\(5000\)</td></tr>
<tr>
<td>Optimizer</td><td>AdamW (<code>betas=(0.9, 0.95)</code>, fused)</td></tr>
<tr>
<td>Peak LR</td><td>\(3\times 10^{-4}\)</td></tr>
<tr>
<td>Warmup</td><td>\(900\) steps</td></tr>
<tr>
<td>Schedule</td><td>linear warmup + cosine decay (min LR ratio \(0.1\))</td></tr>
<tr>
<td>Grad clip</td><td>\(1.0\)</td></tr>
<tr>
<td>Precision</td><td><code>bf16</code></td></tr>
</tbody>
</table>
</div><h2 id="heading-7-engineering-workflow-choices">7) Engineering Workflow Choices</h2>
<p>What kept this practical:</p>
<ul>
<li><p>Resume-first training loop with checkpoint loading.</p>
</li>
<li><p>Regular checkpoint saves and artifact upload flow.</p>
</li>
<li><p>Core metrics to monitor convergence + throughput.</p>
</li>
<li><p>Simpler baseline architecture over novelty-heavy experimentation.</p>
</li>
</ul>
<p>Known telemetry gaps in this run:</p>
<ul>
<li><p>grad norm not logged,</p>
</li>
<li><p>NaN/inf counters not logged,</p>
</li>
<li><p>step-time distribution not logged.</p>
</li>
</ul>
<h2 id="heading-8-training-dynamics-and-stability">8) Training Dynamics and Stability</h2>
<p>From logged metrics:</p>
<ul>
<li><p><code>train/loss</code> decreased smoothly with expected slowing later.</p>
</li>
<li><p><code>train/lr</code> followed warmup then cosine decay as configured.</p>
</li>
<li><p><code>train/tps</code> stabilized after early/warmup region.</p>
</li>
<li><p>validation checkpoints showed overall improvement with mild noise.</p>
</li>
</ul>
<p>Interpretation: <strong>no divergence observed</strong> in tracked window, and training stayed operationally stable.<br />Caveat: stronger stability claims should include grad norm/NaN/step-time telemetry next run.</p>
<h2 id="heading-9-next-steps-future-work">9) Next Steps / Future Work</h2>
<ul>
<li><p>Add shuffle experiments (global/shard-level).</p>
</li>
<li><p>Extend beyond 6B tokens.</p>
</li>
<li><p>Add benchmark-style eval suite.</p>
</li>
<li><p>Log grad norms, NaN counts, and step-time histograms.</p>
</li>
<li><p>Sweep schedule/optimizer details more systematically.</p>
</li>
<li><p>Try checkpoint averaging / EMA.</p>
</li>
<li><p>Add instruction tuning (SFT).</p>
</li>
<li><p>Explore distillation from stronger teachers.</p>
</li>
</ul>
<h2 id="heading-10-repro-appendix">10) Repro Appendix</h2>
<p>Key files:</p>
<ul>
<li><p>Training entry: <a target="_blank" href="https://github.com/weights-and-wires/smol-llama/blob/main/pretrain.py"><code>pretrain.py</code></a></p>
</li>
<li><p>Model: <a target="_blank" href="https://github.com/weights-and-wires/smol-llama/blob/main/utils/model.py"><code>model.py</code></a></p>
</li>
<li><p>LR schedule: <a target="_blank" href="https://github.com/weights-and-wires/smol-llama/blob/main/utils/lr_schedule.py"><code>lr_schedule.py</code></a></p>
</li>
</ul>
<h2 id="heading-closing">Closing</h2>
<p>This run shows that from-scratch pretraining at 360M scale is feasible for a small setup if you prioritize robust engineering, clear data methodology, and reproducibility.<br />The baseline is now in place; next iterations will focus on better data ordering, richer evals, and post-training quality improvements.</p>
<p>GitHub repo (pretraining code): <a target="_blank" href="https://github.com/weights-and-wires/smol-llama">https://github.com/weights-and-wires/smol-llama</a></p>
<p>Model weights (with inference code): <a target="_blank" href="https://huggingface.co/weights-and-wires/smol-llama">https://huggingface.co/weights-and-wires/smol-llama</a></p>
<p>W&amp;B report: <a target="_blank" href="https://api.wandb.ai/links/dotslasha/lydqsle8">https://api.wandb.ai/links/dotslasha/lydqsle8</a></p>
]]></content:encoded></item><item><title><![CDATA[From Karpathy's micrograd to smoltorch: Understanding Autograd from First Principles]]></title><description><![CDATA[After watching Andrej Karpathy’s micrograd lecture, I had a realization: I’d been using PyTorch for months, but I didn’t really understand how autograd…]]></description><link>https://blog.ifkash.dev/smoltorch</link><guid isPermaLink="true">https://blog.ifkash.dev/smoltorch</guid><category><![CDATA[micrograd]]></category><category><![CDATA[pytorch]]></category><category><![CDATA[autograd]]></category><category><![CDATA[Deep Learning]]></category><category><![CDATA[Machine Learning]]></category><dc:creator><![CDATA[Kashif]]></dc:creator><pubDate>Tue, 18 Nov 2025 16:18:25 GMT</pubDate><content:encoded><![CDATA[<h2 id="heading-why-i-built-my-own-deep-learning-framework">Why I Built My Own Deep Learning Framework?</h2>
<p>After watching Andrej Karpathy’s <a target="_blank" href="https://youtu.be/VMj-3S1tku0">micrograd lecture</a>, I had a realization: I’d been using PyTorch for months, but I didn’t really understand how autograd worked. Sure, I could call <code>.backward()</code> and get gradients, but what was actually happening under the hood?</p>
<p>So, I decided to build my own - from scratch, with just NumPy.</p>
<p>This is the story of building <a target="_blank" href="https://pypi.org/project/smoltorch">smoltorch</a>, a tiny but functional deep learning library that achieves 96.5% accuracy on real datasets</p>
<h2 id="heading-what-did-micrograd-teach">What did micrograd teach?</h2>
<p>micrograd laid the groundwork for learning the inner workings of an autograd library. How the gradients flow and how does nudging the weights in a direction affect the flow of gradients. Karpathy sensei’s implementation of micrograd was focused on scalar values and the autograd implemented reflect the same.</p>
<p>This was a nice building ground to learn how a library like PyTorch does differentiation. The biggest revelation moment turned out to be the accumulation of gradients, which I never really put much though into, turned out to be the multiplication of gradients in chain rule.</p>
<p>Let’s consider a function \(z\), which depends on \(y\), which in turn depends on \(x\)</p>
<p>$$\frac{dz}{dx} = \frac{dz}{dy} \cdot \frac{dy}{dx}$$</p><p>Simplified, but this is accumulation of gradients.</p>
<h2 id="heading-the-challenge-scaling-from-scalars-to-tensors">The challenge: scaling from scalars to tensors</h2>
<p>When tensors came into picture, things change. Local gradients involve matrix operations. Broadcasting compilcates gradient accumulation. I had to write an algorithm which “undo” the broadcasting, which could revert the direction of broadcast. If a matrix has broadcasted it’s values along the row, and un-row it and similarly do for column.</p>
<p>micrograd worked with individual numbers:</p>
<pre><code class="lang-python">x = Value(<span class="hljs-number">2.0</span>)
y = Value(<span class="hljs-number">3.0</span>)
z = x * y    <span class="hljs-comment"># Just two numbers</span>
</code></pre>
<p>but real neural nets work with matrices</p>
<pre><code class="lang-python">x = Tensor([
  [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>],
  [<span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>]
])  <span class="hljs-comment"># 2D array</span>
y = Tensor([
  [<span class="hljs-number">7</span>, <span class="hljs-number">8</span>],
  [<span class="hljs-number">9</span>, <span class="hljs-number">10</span>],
  [<span class="hljs-number">11</span>, <span class="hljs-number">12</span>]
])  <span class="hljs-comment"># Another 2D array</span>
z = x @ y  <span class="hljs-comment"># Matrix multiplication!</span>
</code></pre>
<p>This changes the way gradient’s are computed! Let’s understand this is some more code examples</p>
<pre><code class="lang-python">x = np.array([
  [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]
])      <span class="hljs-comment"># shape (1, 3)</span>
y = np.array([
  [<span class="hljs-number">10</span>],
  [<span class="hljs-number">20</span>]
])      <span class="hljs-comment"># shape (2, 1)</span>

z = x + y    <span class="hljs-comment"># shape (2, 3) due to broadcasting</span>
<span class="hljs-string">'''
Result:
[
  [11, 12, 13],
  [21, 22, 23]
]
'''</span>
</code></pre>
<p>How does the gradient flow with broadcasting? When <code>z.grad</code> flows back, shape <code>(2, 3)</code>:</p>
<pre><code class="lang-python">z.grad = [
  [<span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>],
  [<span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>]
]    <span class="hljs-comment"># shape (2, 3)</span>

<span class="hljs-string">'''
x was broadcast from (1, 3) → (2, 3)
so, we sum across axis=0
'''</span>
x.grad = np.sum(z.grad, axis=<span class="hljs-number">0</span>, keepdims=<span class="hljs-literal">True</span>)
       = [[<span class="hljs-number">2</span>, <span class="hljs-number">2</span>, <span class="hljs-number">2</span>]]    <span class="hljs-comment"># shape (1, 3)</span>

<span class="hljs-string">'''
y was broadcast from (2, 1) → (2, 3)
so, we sum across axis=1
'''</span>
y.grad = np.sum(z.grad, axis=<span class="hljs-number">1</span>, keepdims=<span class="hljs-literal">True</span>)
       = [[<span class="hljs-number">3</span>], [<span class="hljs-number">3</span>]]    <span class="hljs-comment"># shape (2, 1)</span>
</code></pre>
<p>The algorithm to unbroadcast goes something like:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">unbroadcast</span>(<span class="hljs-params">grad, orig</span>):</span>
  <span class="hljs-keyword">while</span> len(grad.shape) &gt; len(orig):
    grad = grad.sum(axis=<span class="hljs-number">0</span>)

  <span class="hljs-keyword">for</span> i, (g_dim, o_dim) <span class="hljs-keyword">in</span> enumerate(zip(grad.shape, orig)):
    <span class="hljs-keyword">if</span> o_dim == <span class="hljs-number">1</span> <span class="hljs-keyword">and</span> g_dim &gt; <span class="hljs-number">1</span>:
      grad = grad.sum(axis=i, keepdims=<span class="hljs-literal">True</span>)

  <span class="hljs-keyword">return</span> grad
</code></pre>
<h2 id="heading-the-building-blocks">The Building Blocks</h2>
<p>After understanding how gradients flow through matrix operations, I needed to implement the fundamental operations that make neural networks work. Each operation had its own challenges, but they all followed the same pattern: compute the forward pass, then define how gradients flow backward.</p>
<h3 id="heading-addition-the-broadcasting-puzzle">Addition: The Broadcasting puzzle</h3>
<p>In micrograd, it was trivial:</p>
<pre><code class="lang-python"><span class="hljs-comment"># Scalar addition</span>
z = x + y
<span class="hljs-comment"># Gradient: both inputs get the upstream gradient</span>
x.grad += out.grad  <span class="hljs-comment"># ∂z/∂x = 1</span>
y.grad += out.grad  <span class="hljs-comment"># ∂z/∂y = 1</span>
</code></pre>
<p>But with tensors, NumPy's broadcasting created a hidden complexity:</p>
<pre><code class="lang-python">x = np.array([[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]])      <span class="hljs-comment"># shape (1, 3)</span>
y = np.array([[<span class="hljs-number">10</span>], [<span class="hljs-number">20</span>]])      <span class="hljs-comment"># shape (2, 1)</span>
z = x + y                       <span class="hljs-comment"># shape (2, 3) - broadcast!</span>

<span class="hljs-comment"># Result:</span>
<span class="hljs-comment"># [[11, 12, 13],   # x was copied down</span>
<span class="hljs-comment">#  [21, 22, 23]]   # y was copied across</span>
</code></pre>
<p>Here's the insight that clicked for me: <strong>when a tensor gets broadcast during forward pass, its gradient needs to be "unbroadcast" by summing</strong>.</p>
<p>Think about it: <code>x</code> with shape <code>(1, 3)</code> affected all 6 positions in the output. So when <code>z.grad</code> comes back with shape <code>(2, 3)</code>, we need to sum along the dimension that was broadcast:</p>
<pre><code class="lang-python">z.grad = [[<span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>],
          [<span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>]]

<span class="hljs-comment"># x was broadcast from (1, 3) to (2, 3)</span>
<span class="hljs-comment"># Sum over axis 0 to get back to (1, 3)</span>
x.grad = z.grad.sum(axis=<span class="hljs-number">0</span>, keepdims=<span class="hljs-literal">True</span>)  <span class="hljs-comment"># [[2, 2, 2]]</span>

<span class="hljs-comment"># y was broadcast from (2, 1) to (2, 3)</span>
<span class="hljs-comment"># Sum over axis 1 to get back to (2, 1)</span>
y.grad = z.grad.sum(axis=<span class="hljs-number">1</span>, keepdims=<span class="hljs-literal">True</span>)  <span class="hljs-comment"># [[3], [3]]</span>
</code></pre>
<p>I wrote an <code>_unbroadcast</code> helper that became essential for every operation:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">_unbroadcast</span>(<span class="hljs-params">self, grad, original_shape</span>):</span>
    <span class="hljs-string">"""Reverse broadcasting by summing over expanded dimensions"""</span>
    <span class="hljs-comment"># Sum over leading dimensions that were added</span>
    <span class="hljs-keyword">while</span> len(grad.shape) &gt; len(original_shape):
        grad = grad.sum(axis=<span class="hljs-number">0</span>)

    <span class="hljs-comment"># Sum over dimensions that had size 1 but got broadcast</span>
    <span class="hljs-keyword">for</span> i, (grad_dim, orig_dim) <span class="hljs-keyword">in</span> enumerate(zip(grad.shape, original_shape)):
        <span class="hljs-keyword">if</span> orig_dim == <span class="hljs-number">1</span> <span class="hljs-keyword">and</span> grad_dim &gt; <span class="hljs-number">1</span>:
            grad = grad.sum(axis=i, keepdims=<span class="hljs-literal">True</span>)

    <span class="hljs-keyword">return</span> grad
</code></pre>
<h3 id="heading-matrix-multiplication-the-big-one">Matrix Multiplication: The Big One</h3>
<p>This was the operation I was most nervous about. Matrix multiplication is the heart of neural networks - every linear layer uses it. Getting the gradients wrong here would break everything.</p>
<p>The forward pass is just NumPy:</p>
<pre><code class="lang-python">z = x @ y  <span class="hljs-comment"># That's it!</span>
</code></pre>
<p>But the backward pass requires understanding the relationship between shapes. Here's the derivation that finally made sense to me:</p>
<pre><code class="lang-python"><span class="hljs-comment"># Given:</span>
x.shape = (<span class="hljs-number">2</span>, <span class="hljs-number">3</span>)
y.shape = (<span class="hljs-number">3</span>, <span class="hljs-number">5</span>)
z = x @ y  <span class="hljs-comment"># z.shape = (2, 5)</span>

<span class="hljs-comment"># When z.grad flows back (shape 2, 5), we need:</span>
<span class="hljs-comment"># x.grad with shape (2, 3)</span>
<span class="hljs-comment"># y.grad with shape (3, 5)</span>

<span class="hljs-comment"># For x.grad: we need (2, 3) from (2, 5) and (3, 5)</span>
<span class="hljs-comment"># Pattern: (2, 5) @ (5, 3) = (2, 3)</span>
<span class="hljs-comment"># So: x.grad = z.grad @ y.T</span>

<span class="hljs-comment"># For y.grad: we need (3, 5) from (2, 3) and (2, 5)</span>
<span class="hljs-comment"># Pattern: (3, 2) @ (2, 5) = (3, 5)</span>
<span class="hljs-comment"># So: y.grad = x.T @ z.grad</span>
</code></pre>
<p>The implementation:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__matmul__</span>(<span class="hljs-params">self, other</span>):</span>
    out = Tensor(self.data @ other.data, (self, other), <span class="hljs-string">'@'</span>)

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">_backward</span>():</span>
        <span class="hljs-comment"># The gradient formulas</span>
        grad_self = out.grad @ other.data.swapaxes(<span class="hljs-number">-2</span>, <span class="hljs-number">-1</span>)
        grad_other = self.data.swapaxes(<span class="hljs-number">-2</span>, <span class="hljs-number">-1</span>) @ out.grad

        <span class="hljs-comment"># Handle broadcasting (yes, even matmul broadcasts!)</span>
        grad_self = self._unbroadcast(grad_self, self.data.shape)
        grad_other = self._unbroadcast(grad_other, other.data.shape)

        self.grad += grad_self
        other.grad += grad_other

    out._backward = _backward
    <span class="hljs-keyword">return</span> out
</code></pre>
<p>I used <code>swapaxes(-2, -1)</code> instead of <code>.T</code> to handle batched matrix multiplication correctly - this was a subtle bug that took me an hour to find!</p>
<h2 id="heading-key-insights-and-aha-moments">Key Insights and “aha” moments</h2>
<p>What I actually learnt?</p>
<ul>
<li><p>Broadcasting is everywhere</p>
<ul>
<li>Every time NumPy broadcasts, your gradient code needs to “unbroadcast” by summing. Miss this step? Your gradients will have wrong shapes</li>
</ul>
</li>
<li><p>The computational graph is everything</p>
<ul>
<li>Modern frameworks build a graph dynamically. Understanding topological sorting was the key to understanding backpropagation</li>
</ul>
</li>
<li><p>Numerical stability matters</p>
<ul>
<li>My first BCE implementation broke the gradient flow! The fix taught me why frameworks have so many epsilon values and clipping operations</li>
</ul>
</li>
<li><p>Weight initialization is critical</p>
<ul>
<li><p>random * 0.1 gave me dead networks</p>
</li>
<li><p>Xavier initialization fixed it</p>
</li>
</ul>
</li>
</ul>
<h2 id="heading-the-results">The Results</h2>
<h3 id="heading-regression-make-regression-dataset">Regression (Make Regression Dataset)</h3>
<ul>
<li><p>Started with MSE loss of over \(8000\)</p>
</li>
<li><p>After 100 epochs, dropped down to less than \(100\)</p>
</li>
<li><p>Predictions within 10-15% of true values</p>
</li>
</ul>
<h3 id="heading-binary-classification-breast-cancer-dataset">Binary Classification (Breast Cancer Dataset)</h3>
<ul>
<li><p>First attempt? 37.8% accuracy as the model was stuck and not learning</p>
</li>
<li><p>After fixing BCE? 96.5% accuracy</p>
</li>
<li><p>This is quite close to some production frameworks out there in under 400 lines of Python</p>
</li>
</ul>
<h2 id="heading-what-is-missing-and-why-its-okay">What is missing and why it’s okay?</h2>
<ul>
<li><p>No GPU support, but Apple M4 + NumPy is blazingly fast</p>
</li>
<li><p>No convolution, coming soon</p>
</li>
<li><p>No Adam optimizer, SGD works for learning</p>
</li>
<li><p>No mini-batches, full-batch training as of now</p>
</li>
</ul>
<p>None of that matters for understanding the fundamentals and you do learn a lot when building from scratch.</p>
<h2 id="heading-whats-next">What’s next?</h2>
<p>Now that the core works, the roadmap is as follows (cannot guarantree any timelines or order of implementation):</p>
<ul>
<li><p>Adam optimizer (momentum + adaptive learning rates)</p>
</li>
<li><p>Softmax for multi-class classification</p>
</li>
<li><p>Convolutional layers</p>
</li>
<li><p>Metal performance shaders for M4 optimization</p>
</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>If you’re serious about deep learning, build your own framework. Not because you will use it in production, but because you will understand PyTorch 10x better afterward.</p>
<p>When you call <code>loss.backward()</code> in pyTorch now, you won’t just see magic, you will see:</p>
<ul>
<li><p>Topological sort building the graph</p>
</li>
<li><p>Chain rule being applied in reverse</p>
</li>
<li><p>Gradients flowing through operations</p>
</li>
<li><p>Broadcasting being handled correctly</p>
</li>
</ul>
<p>GitHub repo: <a target="_blank" href="https://github.com/kashifulhaque/smoltorch">https://github.com/kashifulhaque/smoltorch</a></p>
<p>PyPI: <a target="_blank" href="https://pypi.org/project/smoltorch/">https://pypi.org/project/smoltorch</a></p>
]]></content:encoded></item><item><title><![CDATA[I Built a Tiny Vector Database (and Pointed It at FAISS)]]></title><description><![CDATA[Vector DBs are everywhere these days: Pinecone, Weaviate, Qdrant, Chroma, FAISS … you name it! Most of them are full-featured systems with servers, APIs…]]></description><link>https://blog.ifkash.dev/tiny-vector-db</link><guid isPermaLink="true">https://blog.ifkash.dev/tiny-vector-db</guid><category><![CDATA[faiss]]></category><category><![CDATA[vector database]]></category><category><![CDATA[vector embeddings]]></category><category><![CDATA[VectorSearch]]></category><category><![CDATA[vector similarity]]></category><category><![CDATA[RAG ]]></category><category><![CDATA[Retrieval-Augmented Generation]]></category><category><![CDATA[llm]]></category><category><![CDATA[AI]]></category><category><![CDATA[Python]]></category><dc:creator><![CDATA[Kashif]]></dc:creator><pubDate>Thu, 28 Aug 2025 18:21:28 GMT</pubDate><content:encoded><![CDATA[<p>Vector DBs are everywhere these days: Pinecone, Weaviate, Qdrant, Chroma, FAISS … you name it! Most of them are full-featured systems with servers, APIs, dashboards, the works.</p>
<p>Sometimes the best way to demystify hype is to build it yourself. Here’s my weekend project: <em>a vector DB in a few hundred lines of Python.</em></p>
<p>I call it <strong>NoPokeDB</strong> (I don’t even remember why I chose that name). It’s tiny, file-based and durable enough not to fall apart if you pull the plug, unlike me 🤧.</p>
<h2 id="heading-why-bother">Why bother?</h2>
<p>Why not? A couple reasons:</p>
<ul>
<li><p>I wanted to learn what’s really behind all the marketing fluff: how hard is ANN indexing, persistence and CRUD?</p>
</li>
<li><p>I needed a hackable playground - a DB I could modify at will without running a cluster.</p>
</li>
<li><p>I thought it’d be easy 💀 (It was fun)</p>
</li>
</ul>
<h2 id="heading-how-does-it-work">How does it work?</h2>
<ul>
<li><p><strong>Indexing:</strong> <a target="_blank" href="https://github.com/nmslib/hnswlib">hnswlib</a> does the heavy lifting for approximate nearest neighbor search (HNSW graph).</p>
</li>
<li><p><strong>Metadata:</strong> SQLite, because it’s everywhere, lightweight, and dead simple.</p>
</li>
<li><p><strong>Persistence:</strong> Vectors stored on disk, metadata in a DB file, index saved to <code>.bin</code></p>
</li>
<li><p><strong>Crash safety:</strong> A tiny write-ahead oplog that replays on startup if something blew up mid-write.</p>
</li>
<li><p><strong>API:</strong> Just a Python class with methods like <code>add</code>, <code>add_many</code>, <code>query</code>, <code>get</code>, <code>delete</code>, <code>upsert</code>.</p>
</li>
</ul>
<p>Tiny code snippet:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> nopokedb <span class="hljs-keyword">import</span> NoPokeDB
db = NoPokeDB(dim=<span class="hljs-number">128</span>, max_elements=<span class="hljs-number">10</span>_000, path=<span class="hljs-string">"./data"</span>)
vid = db.add(np.random.rand(<span class="hljs-number">128</span>).astype(np.float32), {<span class="hljs-string">"name"</span>: <span class="hljs-string">"foo"</span>})
hits = db.query(np.random.rand(<span class="hljs-number">128</span>).astype(np.float32), k=<span class="hljs-number">5</span>)
print(hits[<span class="hljs-number">0</span>])
</code></pre>
<h2 id="heading-features-i-ended-up-adding">Features I ended up adding</h2>
<ul>
<li><p>Batch inserts + automatic <code>resize_index</code> growth</p>
</li>
<li><p>Cosine / L2 / Inner Product support</p>
</li>
<li><p>CRUD helpers: <code>get</code>, <code>delete</code> and <code>upsert</code></p>
</li>
<li><p>Crash recovery via oplog replay</p>
</li>
<li><p>Query results with both <code>score</code> and raw <code>distance</code></p>
</li>
</ul>
<p>It’s about a couple hundred lines of Python!</p>
<h2 id="heading-ah-the-benchmarks">Ah, the benchmarks</h2>
<p>Well, building something is fun, but you only know if it’s useful once you put it against the big names.</p>
<p>I wrote a <a target="_blank" href="https://github.com/kashifulhaque/nopokedb/blob/main/benchmarks/bench.py">benchmark harness</a> to pit NoPokeDB against FAISS 💀 (Yeah, it’s like putting Max Verstappen against a go-kart kid)</p>
<ul>
<li><p>Dataset: 20k vectors, 128 dimensions, sampled from a Gaussian.</p>
<ul>
<li><em>This isn’t million-scale; it’s enough to feel the tradeoffs without waiting an hour.</em></li>
</ul>
</li>
<li><p>Queries: 200 random queries</p>
</li>
<li><p>k: 10 nearest neighbours</p>
</li>
<li><p>Metric: cosine similarity</p>
</li>
<li><p>Metrics tracked:</p>
<ul>
<li><p>Build throughput (vectors/sec)</p>
</li>
<li><p>Query QPS (queries/sec)</p>
</li>
<li><p>p50 / p95 latency (ms)</p>
</li>
<li><p>recall@k (compared to brute-force exact search)</p>
</li>
</ul>
</li>
</ul>
<h2 id="heading-results">Results</h2>
<p><em>These numbers are directional — FAISS defaults weren’t tuned here. With</em> <code>efSearch</code> <em>bumped up, FAISS recall jumps much higher.</em></p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Backend</strong></td><td><strong>Build v/s</strong></td><td><strong>QPS</strong></td><td><strong>p50 (ms)</strong></td><td><strong>p95 (ms)</strong></td><td><strong>recall@10</strong></td></tr>
</thead>
<tbody>
<tr>
<td>NoPokeDB</td><td>12.8k</td><td>3.6k</td><td>0.27</td><td>0.31</td><td>0.63</td></tr>
<tr>
<td>FAISS</td><td>95.6k</td><td>10.7k</td><td>0.09</td><td>0.12</td><td>0.31</td></tr>
</tbody>
</table>
</div><h3 id="heading-interpreting-the-numbers">Interpreting the Numbers</h3>
<ul>
<li><p><strong>FAISS:</strong> is blazing fast (not surprising; it’s pure C++), but recall was low in my run because of default params. With tuning (<code>efSearch</code>, <code>efConstruction</code>), it can easily hit &gt;0.9 recall.</p>
</li>
<li><p><strong>NoPokeDB:</strong> is slower to build (Python + SQLite overhead) but recall was better right out of the box. Raising <code>ef</code> improves recall further.</p>
</li>
</ul>
<p><strong>Takeaway:</strong> you can trade speed for accuracy with a couple knobs. And even a “toy” DB can hold its own if you don’t need billion-scale throughput.</p>
<h2 id="heading-lessons-learned">Lessons learned</h2>
<ul>
<li><p><strong>Durability matters;</strong> the oplog was the trickiest but most important bit. Without it, a crash mid-add corrupts your index.</p>
</li>
<li><p><strong>HNSW is forgiving;</strong> you can get decent recall with small effort, but the <code>ef</code> parameter is everything.</p>
</li>
<li><p><strong>APIs make it feel real;</strong> once I added <code>get</code>/<code>delete</code>/<code>upsert</code>, it stopped feeling like a demo and started feeling like a DB.</p>
</li>
<li><p><strong>Benchmarks are humbling;</strong> FAISS still wipes the floor with raw speed, but building my own gave me intuition about <em>why</em>.</p>
</li>
</ul>
<h2 id="heading-whats-next">What’s next?</h2>
<ul>
<li><p>Metadata filters (<code>where</code> clauses on SQLite JSON)</p>
</li>
<li><p>Hybrid search (full-text + vectors)</p>
</li>
<li><p>A lightweight REST/gRPC server wrapper</p>
</li>
<li><p>Larger-scale tests (100k–1M vectors, recall curves)</p>
</li>
</ul>
<h2 id="heading-closing-thoughts">Closing thoughts</h2>
<p>NoPokeDB isn’t going to replace FAISS or Pinecone; and that’s the point!</p>
<p>It’s a hackable little lab project that taught me a ton about vector search, and maybe it can do the same for you.</p>
<p><strong>Repo:</strong> <a target="_blank" href="https://github.com/kashifulhaque/nopokedb">https://github.com/kashifulhaque/nopokedb</a></p>
<p><strong>PyPI:</strong> <a target="_blank" href="https://pypi.org/project/nopokedb/">https://pypi.org/project/nopokedb/</a></p>
<p><em>P.S. if you run your own benchmarks (with bigger datasets, or against Qdrant/Weaviate), I’d love to hear the numbers. (Raise an issue on GitHub)</em></p>
]]></content:encoded></item><item><title><![CDATA[The instability of a softmax function]]></title><description><![CDATA[Explains the numerical instability of the softmax function and how to fix it using vector transformations]]></description><link>https://blog.ifkash.dev/instability-of-a-softmax-function</link><guid isPermaLink="true">https://blog.ifkash.dev/instability-of-a-softmax-function</guid><category><![CDATA[softmax]]></category><category><![CDATA[Machine Learning]]></category><category><![CDATA[Deep Learning]]></category><category><![CDATA[llm]]></category><dc:creator><![CDATA[Kashif]]></dc:creator><pubDate>Wed, 05 Mar 2025 17:31:47 GMT</pubDate><content:encoded><![CDATA[<p>The softmax, as we know, is numerically unstable when applied to vectors containing very small or very large numbers because of the exponential function involved in its computation.</p>
<p>The softmax formula is:</p>
<p>\(\text{softmax}(x_{i}) = \frac{e^{x_{i}}}{\Sigma_{j}e^{x_{j}}}\)</p>
<h3 id="heading-what-are-the-reasons-for-numerical-instability"><strong>What are the reasons for numerical instability?</strong></h3>
<ol>
<li><strong>Overflow of very large numbers</strong><ul>
<li>If \(x_{i}\) contains a very large number, \(e^{x_{i}}\) can become astronomically large, exceeding the maximum representable floating-point number, causing <strong>overflow</strong>.</li>
<li><strong>Example:</strong> If \(x_{i} = 1,000\), then \(e^{1000}\) is astronomical that cannot be stored in standard floating-point precision.</li>
</ul>
</li>
<li><strong>Similarly, underflow of very small numbers</strong><ul>
<li>If \(x_{i}\) contains a very small (negative) number, \(e^{x_{i}}\) can become extremely small, possibly rounding down to zero, causing <strong>underflow</strong>.</li>
<li><strong>Example:</strong> If \(x_{i} = -1,000\), then \(e^{-1000}\) is so close to zero that it may be treated as zero in floating-point arithmetic.</li>
</ul>
</li>
<li><strong>Loss of precision when division</strong><ul>
<li>Exponentials of astronomical numbers dominate the denominators when calculating normalization (norm) \(\Sigma_{j}e^{x_{j}}\), the smaller exponentials may become negligible. This can result in loss of accuracy when computing probabilities.</li>
</ul>
</li>
</ol>
<h3 id="heading-what-is-the-fix"><strong>What is the fix?</strong></h3>
<p>A common technique is to subtract the maximum value of the vector from all elements before computing softmax</p>
<p>\(\tilde{x}_{i} = x_{i} - \max_{j} x_{j}\)</p>
<p>\(\text{softmax}(x_{i}) = \frac{e^{\tilde{x}_{i}}}{\sum_{j} e^{\tilde{x}_{j}}}\)</p>
<p>This transformation allows us to prevent both overflow and underflow, ensuring softmax stability even for very large or very small numbers in the input vector.</p>
]]></content:encoded></item><item><title><![CDATA[Introduction to CUDA Programming: A Beginner's Guide]]></title><description><![CDATA[Learn CUDA programming to accelerate computing with GPUs. This guide covers CUDA basics, setup, and parallel programming techniques]]></description><link>https://blog.ifkash.dev/intro-to-cuda</link><guid isPermaLink="true">https://blog.ifkash.dev/intro-to-cuda</guid><category><![CDATA[cuda]]></category><category><![CDATA[NVIDIA]]></category><category><![CDATA[C++]]></category><category><![CDATA[GPU]]></category><dc:creator><![CDATA[Kashif]]></dc:creator><pubDate>Sat, 22 Jun 2024 12:52:43 GMT</pubDate><content:encoded><![CDATA[<p>This is an attempt to start a new series on CUDA programming! If you're curious about accelerating your computing tasks using GPUs, CUDA (Compute Unified Device Architecture) is an incredibly powerful tool to explore. Whether you're a developer, researcher, or hobbyist, understanding CUDA opens doors to high-performance computing.</p>
<p>In this series, we'll cover everything you need to know to begin leveraging CUDA effectively:</p>
<ol>
<li><p><strong>Understanding CUDA:</strong> CUDA is a parallel computing platform and application programming interface model created by NVIDIA. It allows developers to use NVIDIA GPUs for general-purpose processing, which can greatly accelerate computations compared to traditional CPU-based processing.</p>
</li>
<li><p><strong>Where to Run CUDA Code:</strong> To run CUDA code, you typically need an NVIDIA GPU that supports CUDA. However, not everyone has access to such hardware. We'll explore alternatives like cloud-based services such as <a target="_blank" href="https://lightning.ai">Lightning AI</a> and <a target="_blank" href="https://colab.google">Google Colab</a>, which provide GPU resources for CUDA programming.</p>
</li>
<li><p><strong>Getting Started with C++ and CUDA:</strong> We'll start with the basics by writing a simple C++ program that sums two arrays on the CPU. This will serve as a foundation before moving on to GPU parallelization.</p>
</li>
<li><p><strong>Parallelizing with CUDA:</strong> You'll learn how to shift the array summation example from the CPU to the GPU using CUDA. This step-by-step process will introduce you to CUDA programming concepts such as kernel functions and memory management.</p>
</li>
<li><p><strong>Matrix Multiplication in C++ (CPU):</strong> We'll delve into matrix multiplication using the simplest algorithm on the CPU. This foundational understanding will help set the stage for optimizing with CUDA.</p>
</li>
<li><p><strong>Optimizing Matrix Multiplication with CUDA:</strong> Finally, we'll explore how CUDA can dramatically accelerate matrix multiplication. You'll see firsthand how to harness the parallel processing power of NVIDIA GPUs to achieve significant performance gains.</p>
</li>
</ol>
<p>Whether you're aiming to accelerate scientific simulations, machine learning algorithms, or any other computationally intensive task, understanding CUDA opens up a world of possibilities. Follow along as we dive into each topic step by step, equipping you with the knowledge and skills to start leveraging CUDA effectively in your own projects.</p>
<h2 id="heading-understanding-cuda">Understanding CUDA</h2>
<p>CUDA, short for Compute Unified Device Architecture, is a parallel computing platform and programming model developed by NVIDIA. It enables developers to harness the computational power of NVIDIA GPUs (Graphics Processing Units) for general-purpose processing tasks beyond traditional graphics rendering. CUDA allows programmers to write software that can execute on the GPU, leveraging its massively parallel architecture to accelerate applications in fields ranging from scientific computing and machine learning to computer vision and data analytics.</p>
<p>By offloading compute-intensive tasks to the GPU, CUDA can significantly boost performance and enable faster processing of complex algorithms compared to CPU-based solutions.</p>
<h2 id="heading-where-to-run-cuda-code">Where to run CUDA code</h2>
<p>If you have an NVIDIA GPU in your machine, you can download and install the <a target="_blank" href="https://developer.nvidia.com/cuda-toolkit">CUDA toolkit</a>. You can follow the steps on their website.</p>
<p>If you, however, don't have an NVIDIA GPU, then there are a few cloud solutions which you can use to write and run your CUDA code.</p>
<ul>
<li><p><a target="_blank" href="https://lightning.ai/studios">Lightning AI Studios</a>: You get 22 free GPU hours monthly of NVIDIA T4 GPU. It also comes with a VS Code like UI and access to the Linux terminal.</p>
</li>
<li><p><a target="_blank" href="https://colab.google">Google Colab</a>: You can actually run your CUDA code on Google Colab. You might be wondering, how do I run C++ on Google Colab, stick around as we will be using Google Colab in this blog post.</p>
</li>
<li><p><a target="_blank" href="https://gist.github.com/kashifulhaque/f07477347fcd9e4b336d606a6953915a">Other GPU providers</a>: I have added a GitHub Gist which contains a list of GPU providers, most of them are NOT FREE.</p>
</li>
</ul>
<h2 id="heading-getting-started-with-c-and-cuda">Getting Started with C++ and CUDA</h2>
<p><em>Google Colab Notebook containing the source code is added</em><a target="_blank" href="https://colab.research.google.com/drive/1xlYEAqwMcuAJukmb0OYdmgmEGBTbeGdQ?usp=sharing"><em>here</em></a></p>
<p>We'll start with the basics by writing a simple C++ program that sums two arrays (containing 134 million elements) on the CPU. This will serve as a foundation before moving on to GPU parallelization.</p>
<p>**NOTE:**<em>If you're coding everything on your machine then make sure you have GNU C/C++ compiler and clang installed, basically allowing you to access commands like</em><code>g++</code><em>and</em><code>clang</code><em>from the command line. These should be fairly easy to setup on a Unix-like OS. On Windows, you can use something like</em><a target="_blank" href="https://sourceforge.net/projects/mingw/"><em>MinGW</em></a></p>
<p>If you're using Google Colab, then you can follow along very easily. Once inside the Google Colab notebook, you can connect to a NVIDIA T4 GPU instance. To change your runtime type, you can click on <strong>"Runtime"</strong> on the toolbar and choose <strong>"Change runtime type"</strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719058499093/f2eb79e8-8e26-4942-bce5-9f7254312d56.png" alt class="image--center mx-auto" /></p>
<p>There, you can select <strong>T4 GPU</strong> under the <strong>Hardware accelerator</strong> section, hit save.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719058530011/3d3bd0b5-d363-4c20-8054-7887a586b1d5.png" alt class="image--center mx-auto" /></p>
<p>You can start your instance by clicking on the <strong>"Connect T4"</strong> button at the top right</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719058591741/839be84c-92ea-4963-ae60-67737757e17a.png" alt class="image--center mx-auto" /></p>
<p>Once connected, you can create a new <strong>"Code"</strong> cell and start typing. Here, a simple C++ program which creates 2 arrays of 134 million elements each (of float type) and sums them up. This code runs on the CPU</p>
<pre><code class="lang-cpp">%%file sum_cpu.cc

<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;cmath&gt;</span></span>

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">add</span><span class="hljs-params">(<span class="hljs-keyword">int</span> n, <span class="hljs-keyword">float</span> *x, <span class="hljs-keyword">float</span> *y)</span> </span>{
  <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; n; ++i) {
    y[i] = x[i] + y[i];
  }
}

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
  <span class="hljs-keyword">int</span> N = <span class="hljs-number">1</span>&lt;&lt;<span class="hljs-number">27</span>;  <span class="hljs-comment">// This becomes ~134M using left bitshift</span>

  <span class="hljs-keyword">float</span> *x = <span class="hljs-keyword">new</span> <span class="hljs-keyword">float</span>[N];
  <span class="hljs-keyword">float</span> *y = <span class="hljs-keyword">new</span> <span class="hljs-keyword">float</span>[N];

  <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; N; ++i) {
    x[i] = <span class="hljs-number">1.0f</span>;
    y[i] = <span class="hljs-number">2.0f</span>;
  }

  add(N, x, y);

  <span class="hljs-keyword">float</span> max_error = <span class="hljs-number">0.0f</span>;
  <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; N; ++i) {
      max_error = fmax(max_error, <span class="hljs-built_in">fabs</span>(y[i] - <span class="hljs-number">3.0f</span>));
  }
  <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"Max error: "</span> &lt;&lt; max_error &lt;&lt; <span class="hljs-built_in">std</span>::<span class="hljs-built_in">endl</span>;

  <span class="hljs-keyword">delete</span> [] x;
  <span class="hljs-keyword">delete</span> [] y;

  <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>Make sure to add the <code>%%file filename</code><a target="_blank" href="http://cpu.cc"><code>.cc</code></a> as the first line of cell, this allows Google Colab to write this file in the filesystem. You can compile and run this by creating another <strong>"Code"</strong> cell and typing the following</p>
<pre><code class="lang-bash">%%shell
clang++ sum_cpu.cc -o sum_cpu
time ./sum_cpu
</code></pre>
<p>First line is <code>%%shell</code> which essentially tells Google Colab to treat all lines of code in this cell as shell commands. The line <code>clang++ filename.cc -o filename</code> essentially compiles the C++ source file into an executable. The last line <code>time ./filename</code> runs the executable and also measures the time it takes to execute.</p>
<p>Once you execute your code, you'll see that it gives us 0 error with running time of approx 2.6s</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719058924785/e323de36-65fc-40df-9953-cd1611bb4a5b.png" alt class="image--center mx-auto" /></p>
<p>Let's harness the multiple cores of an NVIDIA GPU using CUDA.</p>
<h2 id="heading-parallelizing-with-cuda">Parallelizing with CUDA</h2>
<p>You'll learn how to shift the array summation example from the CPU to the GPU using CUDA. This step-by-step process will introduce you to CUDA programming concepts such as kernel functions and memory management.</p>
<p>We need to turn our <code>add</code> function into a function which can be run by the GPU, called a <strong><em>kernel</em></strong> in CUDA.</p>
<p>To do this, we need to add the <code>__global__</code> specified to the function. This tells the CUDA compiler that the function needs to run on the GPU, and can be called from the CPU code.</p>
<h3 id="heading-memory-allocation-in-cuda">Memory allocation in CUDA</h3>
<p>To compute on the GPU, memory must be allocated which is accessible to the GPU. To allocate data in unified memory space (Memory space accessible by both CPU and GPU), call <code>cudaMallocManaged()</code>, which returns a pointer that we can use to access host code (CPU) or device code (GPU). To free the data, just call <code>cudaFree()</code></p>
<p>To run the CUDA kernel <code>add()</code> which invokes it on the GPU, we need to use the triple brackets syntax <code>&lt;&lt;&lt; &gt;&gt;&gt;</code></p>
<p>**The CPU needs to wait until the kernel is done computing, as CUDA kernel launches don't block the calling CPU thread.**<em>Just call</em><code>cudaDeviceSynchronize()</code><em>before the final error checking.</em></p>
<p>So the CUDA code looks as follows, notice the change in <code>add</code> function, how it's declared and invoked.</p>
<pre><code class="lang-cpp">%%file sum_cuda.cu

<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;cmath&gt;</span></span>

<span class="hljs-function">__global__
<span class="hljs-keyword">void</span> <span class="hljs-title">add</span><span class="hljs-params">(<span class="hljs-keyword">int</span> n, <span class="hljs-keyword">float</span> *x, <span class="hljs-keyword">float</span> *y)</span> </span>{
  <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; n; ++i) {
    y[i] = x[i] + y[i];
  }
}

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
  <span class="hljs-keyword">int</span> N = <span class="hljs-number">1</span>&lt;&lt;<span class="hljs-number">27</span>;  <span class="hljs-comment">// This becomes ~134M using left bitshift</span>
  <span class="hljs-keyword">float</span> *x, *y;

  cudaMallocManaged(&amp;x, N * <span class="hljs-keyword">sizeof</span>(<span class="hljs-keyword">float</span>));
  cudaMallocManaged(&amp;y, N * <span class="hljs-keyword">sizeof</span>(<span class="hljs-keyword">float</span>));

  <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; N; ++i) {
    x[i] = <span class="hljs-number">1.0f</span>;
    y[i] = <span class="hljs-number">2.0f</span>;
  }

  add&lt;&lt;&lt;<span class="hljs-number">1</span>, <span class="hljs-number">1</span>&gt;&gt;&gt;(N, x, y);

  <span class="hljs-comment">// Wait for the GPU to finish</span>
  cudaDeviceSynchronize();

  <span class="hljs-keyword">float</span> max_error = <span class="hljs-number">0.0f</span>;
  <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; N; ++i) {
      max_error = fmax(max_error, <span class="hljs-built_in">fabs</span>(y[i] - <span class="hljs-number">3.0f</span>));
  }
  <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"Max error: "</span> &lt;&lt; max_error &lt;&lt; <span class="hljs-built_in">std</span>::<span class="hljs-built_in">endl</span>;

  cudaFree(x);
  cudaFree(y);

  <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>Compile and run the CUDA code using the <code>nvcc</code> command</p>
<pre><code class="lang-bash">%%shell
nvcc sum_cuda.cu -o sum_cuda
time ./sum_cuda
</code></pre>
<p>The command <code>nvcc filename.cu -o filename</code> invokes the NVIDIA CUDA Compiler on the file and the next line runs the executable, measuring it's time.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719059451586/e3430ff5-8106-4901-bc14-ca8634798945.png" alt class="image--center mx-auto" /></p>
<p>As we can see, the execution time increased instead of decreasing. Let's profile the execution using <code>nvprof</code> command to see how long does the execution take</p>
<pre><code class="lang-bash">%%shell
nvprof ./sum_cuda
</code></pre>
<p>The command <code>nvprof ./filename</code> profiles the executable and prints out a nice, verbose summary.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719059635722/d8b45e5a-1c51-4624-b937-cf9559d85128.png" alt class="image--center mx-auto" /></p>
<p>That's quite a lot to take in, but you can just focus on the line which starts with "GPU activities" and can see that the CUDA execution is taking almost 5.8s</p>
<h3 id="heading-making-use-of-threads">Making use of threads</h3>
<p>We ran a kernel with one thread, to do some computation. To make it parallel, we need to look into CUDA's <code>&lt;&lt;&lt;1, 1&gt;&gt;&gt;</code> syntax.</p>
<p>This is called execution configuration and it tells the CUDA runtime how many parallel threads to use on the GPU. There are 2 parameters here, let's start by changing the second one!</p>
<p>The 2nd parameter is the number of threads in a thread block. CUDA GPUs run kernels using blocks of threads that are multiples of 32 in size, so 256 threads is a reasonable size to choose.</p>
<p>With this, we also need to change the kernel in order to make full use of parallel threads. CUDA provides keywords that let kernels get the indices of running threads.</p>
<ul>
<li><p><code>threadIdx.x</code> contains the index of the current thread within its block</p>
</li>
<li><p><code>blockDim.x</code> contains the number of threads in the block</p>
</li>
</ul>
<p><em>Let's stride through the array with parallel threads</em></p>
<pre><code class="lang-cpp">%%file sum_cuda.cu

<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;cmath&gt;</span></span>

<span class="hljs-function">__global__
<span class="hljs-keyword">void</span> <span class="hljs-title">add</span><span class="hljs-params">(<span class="hljs-keyword">int</span> n, <span class="hljs-keyword">float</span> *x, <span class="hljs-keyword">float</span> *y)</span> </span>{
  <span class="hljs-keyword">int</span> index = threadIdx.x;
  <span class="hljs-keyword">int</span> stride = blockDim.x;

  <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> i = index; i &lt; n; i += stride) {
    y[i] = x[i] + y[i];
  }
}

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
  <span class="hljs-keyword">int</span> N = <span class="hljs-number">1</span>&lt;&lt;<span class="hljs-number">27</span>;  <span class="hljs-comment">// This becomes ~134M using left bitshift</span>
  <span class="hljs-keyword">float</span> *x, *y;

  cudaMallocManaged(&amp;x, N * <span class="hljs-keyword">sizeof</span>(<span class="hljs-keyword">float</span>));
  cudaMallocManaged(&amp;y, N * <span class="hljs-keyword">sizeof</span>(<span class="hljs-keyword">float</span>));

  <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; N; ++i) {
    x[i] = <span class="hljs-number">1.0f</span>;
    y[i] = <span class="hljs-number">2.0f</span>;
  }

  add&lt;&lt;&lt;<span class="hljs-number">1</span>, <span class="hljs-number">256</span>&gt;&gt;&gt;(N, x, y);

  <span class="hljs-comment">// Wait for the GPU to finish</span>
  cudaDeviceSynchronize();

  <span class="hljs-keyword">float</span> max_error = <span class="hljs-number">0.0f</span>;
  <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; N; ++i) {
      max_error = fmax(max_error, <span class="hljs-built_in">fabs</span>(y[i] - <span class="hljs-number">3.0f</span>));
  }
  <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"Max error: "</span> &lt;&lt; max_error &lt;&lt; <span class="hljs-built_in">std</span>::<span class="hljs-built_in">endl</span>;

  cudaFree(x);
  cudaFree(y);

  <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<pre><code class="lang-bash">%%shell
nvcc sum_cuda.cu -o sum_cuda
time ./sum_cuda
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719059763470/c8698132-6570-4241-bd57-b5bbb5e83415.png" alt class="image--center mx-auto" /></p>
<pre><code class="lang-bash">%%shell
nvprof ./sum_cuda
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719059782928/58dc75e9-21b9-4dee-a378-e4181adce528.png" alt class="image--center mx-auto" /></p>
<p>As you can see, increasing the thread count resulted in a massive speedup. (5.8s to 443ms)</p>
<h3 id="heading-more-info-about-blocks"><strong>More info about blocks</strong></h3>
<p>Nvidia GPUs have many parallel processors grouped into <strong>Streaming Multiprocessors (SMs)</strong>. Each SM can run multiple concurrent thread blocks.</p>
<p>Let's come back to the first parameter, it is the number of thread blocks. Blocks of parallel threads are called <strong>grid</strong>.</p>
<p>Since, there are N elements to process and 256 threads per block, we need to calculate the number of blocks to get atleast N threads. Divide N by the block size (round up in case N is not a multiple of block size)</p>
<p><img src="https://developer-blogs.nvidia.com/wp-content/uploads/2017/01/cuda_indexing.png" alt /></p>
<p><em>Source:</em><a target="_blank" href="https://developer.nvidia.com/blog/even-easier-introduction-cuda/"><em>An even easier introduction to CUDA</em></a></p>
<p><strong>Explanation:</strong> Approach to indexing into an 1D array</p>
<ul>
<li><p>Each thread gets its index by computing the offset to the beginning of its block</p>
<ul>
<li><p>Block index × Block size</p>
</li>
<li><p><code>blockIdx.x * blockDim.x</code></p>
</li>
</ul>
</li>
<li><p>Adding the thread's index within the block</p>
<ul>
<li><code>threadIdx.x</code></li>
</ul>
</li>
<li><p>Set <code>stride</code> to total number of threads in the grid</p>
<ul>
<li><p><code>blockDim.x * gridDim.x</code></p>
</li>
<li><p>Often called <strong><em>grid-stride</em></strong> loop</p>
</li>
</ul>
</li>
</ul>
<p>The kernel code has to be updated to take into account the entire grid of thread blocks.</p>
<ul>
<li><p><code>gridDim.x</code> contains the number of blocks in the grid</p>
</li>
<li><p><code>blockIdx.x</code> contains the index of current thread block in the grid</p>
</li>
</ul>
<pre><code class="lang-cpp">%%file sum_cuda.cu

<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;cmath&gt;</span></span>

<span class="hljs-function">__global__
<span class="hljs-keyword">void</span> <span class="hljs-title">add</span><span class="hljs-params">(<span class="hljs-keyword">int</span> n, <span class="hljs-keyword">float</span> *x, <span class="hljs-keyword">float</span> *y)</span> </span>{
  <span class="hljs-keyword">int</span> index = blockIdx.x * blockDim.x + threadIdx.x;
  <span class="hljs-keyword">int</span> stride = blockDim.x * gridDim.x;

  <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> i = index; i &lt; n; i += stride) {
    y[i] = x[i] + y[i];
  }
}

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
  <span class="hljs-keyword">int</span> N = <span class="hljs-number">1</span>&lt;&lt;<span class="hljs-number">27</span>;  <span class="hljs-comment">// This becomes ~134M using left bitshift</span>
  <span class="hljs-keyword">float</span> *x, *y;

  cudaMallocManaged(&amp;x, N * <span class="hljs-keyword">sizeof</span>(<span class="hljs-keyword">float</span>));
  cudaMallocManaged(&amp;y, N * <span class="hljs-keyword">sizeof</span>(<span class="hljs-keyword">float</span>));

  <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; N; ++i) {
    x[i] = <span class="hljs-number">1.0f</span>;
    y[i] = <span class="hljs-number">2.0f</span>;
  }

  <span class="hljs-keyword">int</span> block_size = <span class="hljs-number">256</span>;
  <span class="hljs-keyword">int</span> num_blocks = (N + block_size - <span class="hljs-number">1</span>) / block_size;
  add&lt;&lt;&lt;num_blocks, block_size&gt;&gt;&gt;(N, x, y);

  <span class="hljs-comment">// Wait for the GPU to finish</span>
  cudaDeviceSynchronize();

  <span class="hljs-keyword">float</span> max_error = <span class="hljs-number">0.0f</span>;
  <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; N; ++i) {
      max_error = fmax(max_error, <span class="hljs-built_in">fabs</span>(y[i] - <span class="hljs-number">3.0f</span>));
  }
  <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"Max error: "</span> &lt;&lt; max_error &lt;&lt; <span class="hljs-built_in">std</span>::<span class="hljs-built_in">endl</span>;

  cudaFree(x);
  cudaFree(y);

  <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<pre><code class="lang-bash">%%shell
nvcc sum_cuda.cu -o sum_cuda
time ./sum_cuda
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719060094310/2d7f0a54-48fe-4f63-b9ac-fe690f28d2bc.png" alt class="image--center mx-auto" /></p>
<pre><code class="lang-bash">%%shell
nvprof ./sum_cuda
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719060116278/652805f2-9045-4d71-8716-eefd5fe28282.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-matrix-multiplication-in-c-cpu">Matrix Multiplication in C++ (CPU)</h2>
<p>A common example, which I guess most people do when learning CUDA, is to do some matrix multiplication of fairly large square matrices (1024).</p>
<p>Let's write some C++ code which multiplies 2 square matrices of size 1024 each, using the standard matrix multiplication algorithm \(O(n^{3})\) time complexity</p>
<pre><code class="lang-cpp">%%file matrix_multiplication.cc

<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;random&gt;</span></span>

<span class="hljs-comment">// Global constants</span>
<span class="hljs-keyword">const</span> <span class="hljs-keyword">int</span> N = <span class="hljs-number">1</span> &lt;&lt; <span class="hljs-number">10</span>;  <span class="hljs-comment">// This line of code shifts 1 to the left by 10 bits (making it 1024)</span>

<span class="hljs-comment">// Function declarations live here</span>
<span class="hljs-function"><span class="hljs-keyword">float</span> <span class="hljs-title">get_random</span><span class="hljs-params">()</span></span>;
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">init_matrix</span><span class="hljs-params">(<span class="hljs-keyword">float</span> matrix[][N])</span></span>;
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">matmul</span><span class="hljs-params">(<span class="hljs-keyword">float</span> A[][N], <span class="hljs-keyword">float</span> B[][N], <span class="hljs-keyword">float</span> C[][N])</span></span>;

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
  <span class="hljs-keyword">float</span> (*A)[N] = <span class="hljs-keyword">new</span> <span class="hljs-keyword">float</span>[N][N];
  <span class="hljs-keyword">float</span> (*B)[N] = <span class="hljs-keyword">new</span> <span class="hljs-keyword">float</span>[N][N];
  <span class="hljs-keyword">float</span> (*C)[N] = <span class="hljs-keyword">new</span> <span class="hljs-keyword">float</span>[N][N];

  init_matrix(A);
  init_matrix(B);

  matmul(A, B, C);

  <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; A[<span class="hljs-number">0</span>][<span class="hljs-number">0</span>] &lt;&lt; <span class="hljs-built_in">std</span>::<span class="hljs-built_in">endl</span>;
  <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; B[<span class="hljs-number">0</span>][<span class="hljs-number">0</span>] &lt;&lt; <span class="hljs-built_in">std</span>::<span class="hljs-built_in">endl</span>;
  <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; C[<span class="hljs-number">0</span>][<span class="hljs-number">0</span>] &lt;&lt; <span class="hljs-built_in">std</span>::<span class="hljs-built_in">endl</span>;

  <span class="hljs-comment">// Free the memory</span>
  <span class="hljs-keyword">delete</span>[] A;
  <span class="hljs-keyword">delete</span>[] B;
  <span class="hljs-keyword">delete</span>[] C;

  <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}

<span class="hljs-function"><span class="hljs-keyword">float</span> <span class="hljs-title">get_random</span><span class="hljs-params">()</span> </span>{
  <span class="hljs-built_in">std</span>::random_device device;  <span class="hljs-comment">// Get a random device, as a seed source</span>
  <span class="hljs-function"><span class="hljs-built_in">std</span>::mt19937 <span class="hljs-title">generator</span><span class="hljs-params">(device())</span></span>; <span class="hljs-comment">// Use the random device to seed the generator</span>
  <span class="hljs-function"><span class="hljs-built_in">std</span>::uniform_real_distribution&lt;<span class="hljs-keyword">float</span>&gt; <span class="hljs-title">distribution</span><span class="hljs-params">(<span class="hljs-number">0.0f</span>, <span class="hljs-number">1.0f</span>)</span></span>; <span class="hljs-comment">// Create a distribution, range [0, 1]</span>

  <span class="hljs-keyword">return</span> distribution(generator); <span class="hljs-comment">// Return the random float</span>
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">init_matrix</span><span class="hljs-params">(<span class="hljs-keyword">float</span> matrix[][N])</span> </span>{
  <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> row = <span class="hljs-number">0</span>; row &lt; N; ++row) {
    <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> col = <span class="hljs-number">0</span>; col &lt; N; ++col) {
      matrix[row][col] = get_random();
    }
  }
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">matmul</span><span class="hljs-params">(<span class="hljs-keyword">float</span> A[][N], <span class="hljs-keyword">float</span> B[][N], <span class="hljs-keyword">float</span> C[][N])</span> </span>{
  <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; N; ++i) {
    <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> j = <span class="hljs-number">0</span>; j &lt; N; ++j) {
      C[i][j] = <span class="hljs-number">0.0f</span>;

      <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> k = <span class="hljs-number">0</span>; k &lt; N; ++k) {
        C[i][j] += A[i][k] * B[k][j];
      }
    }
  }
}
</code></pre>
<pre><code class="lang-bash">%%shell
clang++ matrix_multiplication.cc -o matrix_multiplication
time ./matrix_multiplication
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719060323438/3236ef05-a9f2-4f79-b162-7bfb2645a2f0.png" alt class="image--center mx-auto" /></p>
<p>This took a decent chunk of time to run on CPU, let's accelerate it using CUDA kernels.</p>
<h2 id="heading-optimizing-matrix-multiplication-with-cuda">Optimizing Matrix Multiplication with CUDA</h2>
<p>Finally, we'll explore how CUDA can dramatically accelerate matrix multiplication. You'll see firsthand how to harness the parallel processing power of NVIDIA GPUs to achieve significant performance gains.</p>
<p>One of the ways to speed up this matrix multiplication is by assigning a thread to each element of the matrix. A good way to do this is to have a 2D grid of threads, we can index it using rows and columns.</p>
<pre><code class="lang-cpp">%%file mat_mul.cu

<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;cassert&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;random&gt;</span></span>

<span class="hljs-function"><span class="hljs-keyword">float</span> <span class="hljs-title">get_random</span><span class="hljs-params">()</span></span>;
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">init_matrix</span><span class="hljs-params">(<span class="hljs-keyword">float</span> *matrix, <span class="hljs-keyword">int</span> N)</span></span>;
<span class="hljs-function">__global__ <span class="hljs-keyword">void</span> <span class="hljs-title">matmul</span><span class="hljs-params">(<span class="hljs-keyword">float</span> *A, <span class="hljs-keyword">float</span> *B, <span class="hljs-keyword">float</span> *C, <span class="hljs-keyword">int</span> N)</span></span>;

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
  <span class="hljs-keyword">int</span> N = <span class="hljs-number">1</span> &lt;&lt; <span class="hljs-number">10</span>;  <span class="hljs-comment">// This value is 1024, for square matrix dimension</span>
  <span class="hljs-keyword">size_t</span> bytes = N * N * <span class="hljs-keyword">sizeof</span>(<span class="hljs-keyword">float</span>); <span class="hljs-comment">// Bytes required for the matrix</span>

  <span class="hljs-keyword">float</span> *A;
  <span class="hljs-keyword">float</span> *B;
  <span class="hljs-keyword">float</span> *C;
  cudaMallocManaged(&amp;A, bytes);
  cudaMallocManaged(&amp;B, bytes);
  cudaMallocManaged(&amp;C, bytes);

  <span class="hljs-comment">// Set our thread block and grid dimensions</span>
  <span class="hljs-keyword">int</span> threads = <span class="hljs-number">16</span>; <span class="hljs-comment">// If we want 256 in the thread block, that is 16 * 16</span>
  <span class="hljs-keyword">int</span> blocks = (N + threads - <span class="hljs-number">1</span>) / threads;

  <span class="hljs-comment">// Make a 2D grid of threads, pass a struct with 3 dims</span>
  <span class="hljs-function">dim3 <span class="hljs-title">THREADS</span><span class="hljs-params">(threads, threads)</span></span>;
  <span class="hljs-function">dim3 <span class="hljs-title">BLOCKS</span><span class="hljs-params">(blocks, blocks)</span></span>;

  <span class="hljs-comment">// Trigger the CUDA kernel</span>
  matmul&lt;&lt;&lt;THREADS, BLOCKS&gt;&gt;&gt;(A, B, C, N);

  <span class="hljs-comment">// Kernel watchers are async, we need to sync after the kernel is run</span>
  cudaDeviceSynchronize();

  <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}

<span class="hljs-function"><span class="hljs-keyword">float</span> <span class="hljs-title">get_random</span><span class="hljs-params">()</span> </span>{
  <span class="hljs-built_in">std</span>::random_device device;  <span class="hljs-comment">// Get a random device, as a seed source</span>
  <span class="hljs-function"><span class="hljs-built_in">std</span>::mt19937 <span class="hljs-title">generator</span><span class="hljs-params">(device())</span></span>; <span class="hljs-comment">// Use the random device to seed the generator</span>
  <span class="hljs-function"><span class="hljs-built_in">std</span>::uniform_real_distribution&lt;<span class="hljs-keyword">float</span>&gt; <span class="hljs-title">distribution</span><span class="hljs-params">(<span class="hljs-number">0.0f</span>, <span class="hljs-number">1.0f</span>)</span></span>; <span class="hljs-comment">// Create a distribution, range [0, 1]</span>

  <span class="hljs-keyword">return</span> distribution(generator); <span class="hljs-comment">// Return the random float</span>
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">init_matrix</span><span class="hljs-params">(<span class="hljs-keyword">float</span> *matrix, <span class="hljs-keyword">int</span> N)</span> </span>{
  <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; N * N; ++i) {
    matrix[i] = get_random();
  }
}

<span class="hljs-function">__global__ <span class="hljs-keyword">void</span> <span class="hljs-title">matmul</span><span class="hljs-params">(<span class="hljs-keyword">float</span> *A, <span class="hljs-keyword">float</span> *B, <span class="hljs-keyword">float</span> *C, <span class="hljs-keyword">int</span> N)</span> </span>{
  <span class="hljs-comment">// Calculate the global row and column for each thread</span>
  <span class="hljs-keyword">int</span> row = blockIdx.y * blockDim.y + threadIdx.y;
  <span class="hljs-keyword">int</span> col = blockIdx.x * blockDim.x + threadIdx.x;

  <span class="hljs-comment">// Boundary check for our matrix</span>
  <span class="hljs-keyword">if</span>(row &lt; N &amp;&amp; col &lt; N) {
    <span class="hljs-comment">// Accumulate result of a row * col</span>
    <span class="hljs-keyword">float</span> accumulate = <span class="hljs-number">0.0f</span>;
    <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; N; ++i) {
      accumulate += A[row * N + i] * B[i * N + col];
    }

    C[row * N + col] = accumulate;
  }
}
</code></pre>
<pre><code class="lang-bash">%%shell
nvcc mat_mul.cu -o mat_mul
time ./mat_mul
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719060405185/3ed743d8-f6ab-481c-92f8-0ef7ede79b38.png" alt class="image--center mx-auto" /></p>
<pre><code class="lang-bash">%%shell
nvprof ./mat_mul
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719060436230/d38c35fe-2542-4139-b9cb-d034beaeef29.png" alt class="image--center mx-auto" /></p>
<p>As we can see, offloading the processing to CUDA has trememdous gains and lowers our execution time (41.6s to 190ms)</p>
<p><strong>This article wouldn't be possible without:</strong></p>
<ul>
<li><p><a target="_blank" href="https://developer.nvidia.com/blog/even-easier-introduction-cuda/"><em>NVIDIA's blog titled An even easier introduction to CUDA</em></a> - A comprehensive guide by NVIDIA that introduces the basics of CUDA programming and its applications.</p>
</li>
<li><p><a target="_blank" href="https://youtu.be/DpEgZe2bbU0"><em>CoffeeBeforeArch's video on CUDA matrix multiplication</em></a> - A detailed tutorial video demonstrating matrix multiplication using CUDA, perfect for visual learners.</p>
</li>
<li><p><a target="_blank" href="https://openai.com/chatgpt"><em>My buddy ChatGPT</em></a> <em>who helped me with my skill issue in writing good English sentences.</em></p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[1. Introduction to Deep Learning - McCulloch-Pitts Neuron & Perceptron]]></title><description><![CDATA[Source: CS7015/CS6910 of IIT Madras, Prof. Mitesh M. Khapra In the era of computer's infancy, came a brilliant idea that would change the course of history…]]></description><link>https://blog.ifkash.dev/1-introduction-to-deep-learning-mcculloch-pitts-neuron</link><guid isPermaLink="true">https://blog.ifkash.dev/1-introduction-to-deep-learning-mcculloch-pitts-neuron</guid><category><![CDATA[Deep Learning]]></category><dc:creator><![CDATA[Kashif]]></dc:creator><pubDate>Wed, 04 Oct 2023 08:06:19 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1696441185678/88f19d81-f7ee-4152-9689-cb8658742311.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<blockquote>
<p>Source: CS7015/CS6910 of IIT Madras, <a target="_blank" href="http://www.cse.iitm.ac.in/~miteshk">Prof. Mitesh M. Khapra</a></p>
</blockquote>
<p>In the era of computer's infancy, came a brilliant idea that would change the course of history in a very radical way.</p>
<p>Let's dive back in history, imagine a world where machines could mimic the complex decision-making processes of a human brain. It was a dream that captivated the minds of pioneers in the field of Artificial Intelligence.</p>
<h1 id="heading-mcculloch-pitts-neuron">McCulloch-Pitts Neuron</h1>
<p>The year was 1943 when two <a target="_blank" href="https://www.cs.cmu.edu/afs/club/user/cmccabe/ecee.colorado.edu/~ecen4831/lectures/NNet2.html#:~:text=McCullogh%2DPitts%20Model,would%20call%20a%20neural%20network.">electrical engineers</a>, Warren McCulloch and Walter Pitts came together to birth this vision. Little did they know that their creation would set the stage for one of the most remarkable technological journeys ever embarked upon.</p>
<p>What they proposed was a simplified computation model of the neuron</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696402460390/e9619900-611c-408e-86d2-93ba37b6a3f6.webp" alt class="image--center mx-auto" /></p>
<p><em>Source:</em><a target="_blank" href="https://towardsdatascience.com/mcculloch-pitts-model-5fdf65ac5dd1"><em>https://towardsdatascience.com/mcculloch-pitts-model-5fdf65ac5dd1</em></a></p>
<h3 id="heading-working-of-an-mp-neuron"><strong>Working of an MP-neuron</strong></h3>
<p>\(g\) is a function which sums the inputs meanwhile \(f\) takes a decision based on the sum</p>
<p>\(g(x_{1}, x_{2}, ..., x_{n}) = g(x) = \sum^{n}_{i = 1}x_{i}\)</p>
<p>\(y = f(g(x)) = \begin{cases} 1 &amp; \text{if }g(x) \geq \theta \\[10pt] 0 &amp; \text{if } g(x) \lt \theta\end{cases}\)</p>
<p>\(\theta\) is the threshold</p>
<p><strong>Common Boolean functions can be approximated using Perceptron</strong></p>
<p><strong>Example:</strong> AND function</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696406218597/c5044b79-718f-4c07-b0df-78da037bc71f.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-to-summarize">To summarize</h3>
<p>A single McCulloch-Pitts neuron can be used to represent the boolean functions that are linearly separable.</p>
<h1 id="heading-perceptron">Perceptron</h1>
<p>MP-neuron was not perfect and had a glaring issue, all inputs were considered equal and hence had equal "weights", meanwhile in reality, our decisions often depend on some inputs more than the other.</p>
<p>Enter Perceptron, which was proposed by Frank Rosenblatt in 1958. It was a more general computational model than MP-neuron and it introduced the fundamentals principles which are still in use today:</p>
<ul>
<li><p>Weights assigned to inputs</p>
</li>
<li><p>Mechanism to learn those weights</p>
</li>
<li><p>Inputs no longer limited to boolean values</p>
</li>
</ul>
<p>Refined later by Minsky and Papert in 1969</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696407264350/80a58ff7-5772-4552-9627-a903dd021edd.png" alt class="image--center mx-auto" /></p>
<p><em>Source:</em><a target="_blank" href="https://towardsdatascience.com/what-is-a-perceptron-210a50190c3b"><em>https://towardsdatascience.com/what-is-a-perceptron-210a50190c3b</em></a></p>
<p>\(y = \begin{cases} 1 &amp; \text{if } \sum^{n}_{i = 1} w_{i} \cdot x_{i} \geq \theta \\[10pt] 0 &amp; \text{if } \sum^{n}_{i = 1} w_{i} \cdot x_{i} \lt \theta \end{cases}\)</p>
<p>Bring the \(\theta\) on the left side, we get</p>
<p>\(y = \begin{cases} 1 &amp; \text{if } \sum^{n}_{i = 1} w_{i} \cdot x_{i} - \theta \geq 0 \\[10pt] 0 &amp; \text{if } \sum^{n}_{i = 1} w_{i} \cdot x_{i} - \theta \lt 0 \end{cases}\)</p>
<p>However, a more accepted convention is the following</p>
<p>\(y = \begin{cases} 1 &amp; \text{if } \sum^{n}_{i = 0} w_{i} \cdot x_{i} \geq 0 \\[10pt] 0 &amp; \text{if } \sum^{n}_{i = 0} w_{i} \cdot x_{i} \lt 0 \end{cases}\)</p>
<p>where \(x_{0} = 1\) and \(w_{0} = -\theta\\)\\((w_{0}\) is the bias and \(x_{0}\) is always \(1\\)\\()\)</p>
<p>Below is the difference between MP-neuron and Perceptron</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>MP-neuron</td><td>Perceptron</td></tr>
</thead>
<tbody>
<tr>
<td>\(y = \begin{cases} 1 &amp; \text{if }\sum^{n}_{i = 0}x_{i} \geq 0 \\[10pt] 0 &amp; \text{if }\sum^{n}_{i = 0}x_{i} \lt 0 \end{cases}\)</td><td>\(y = \begin{cases} 1 &amp; \text{if } \sum^{n}_{i = 0} w_{i} \cdot x_{i} \geq 0 \\[10pt] 0 &amp; \text{if } \sum^{n}_{i = 0} w_{i} \cdot x_{i} \lt 0 \end{cases}\)</td></tr>
</tbody>
</table>
</div><p><strong>Perceptron Learning Algorithm</strong></p>
<pre><code class="lang-plaintext">initialize weights w randomly;

while !convergence do:
    pick random input x
    if x has positive label and w.x &lt; 0:
        w = w + x
    if x has negative label and w.x &gt; 0:
        w = w - x
</code></pre>
<h3 id="heading-quick-diversion-to-learn-pytorch-basics">Quick diversion to learn PyTorch basics</h3>
<p><strong>What is PyTorch?</strong></p>
<p>It's an open-source Machine Learning library and Deep Learning framework primarily used for developing and training neural networks. It provides a range of tools and modules for building and training various types of neural networks, including convolutional neural networks (CNNs), recurrent neural networks (RNNs) and more.</p>
<p>Tensor in PyTorch is the fundamental data structure that is used to store and manipulate multi-dimensional arrays. They are very similar to NumPy arrays and are a core component of PyTorch's computation graph.</p>
<p>Tensors in PyTorch are designed to work with automatic differentiation, a key feature for training neural networks using techniques like backpropagation (blog post coming soon).</p>
<p><strong>Install PyTorch</strong></p>
<p>Visit <a target="_blank" href="https://pytorch.org/get-started/locally">PyTorch's homepage</a> for instructions on how to install. TLDR: <code>pip install torch</code> should do the job.</p>
<p>Load PyTorch using the following code</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> torch
</code></pre>
<p><strong>Scalar (Rank-0 Tensor)</strong></p>
<p>A single numeric value, such as a real number or an integer and it has no dimension.</p>
<pre><code class="lang-python">a = torch.tensor(<span class="hljs-number">1.</span>)
print(a)        <span class="hljs-comment"># tensor(1.)</span>
print(a.shape)  <span class="hljs-comment"># torch.Size([])</span>
</code></pre>
<p><strong>Vector (Rank-1 Tensor)</strong></p>
<p>A 1D array or a vector. It has a single dimension and are used to represent list of values.</p>
<pre><code class="lang-python">a = torch.tensor([<span class="hljs-number">1.</span>, <span class="hljs-number">2.</span>, <span class="hljs-number">3.</span>])
print(a)        <span class="hljs-comment"># tensor([1., 2., 3.])</span>
print(a.shape)  <span class="hljs-comment"># torch.Size([3])</span>
</code></pre>
<p><strong>Matrix (Rank-2 Tensor)</strong></p>
<p>A 2D array or a matrix. It has two dimensions and are used to represent tabular data or images (black and white).</p>
<pre><code class="lang-python">a = torch.tensor([
  [<span class="hljs-number">1.</span>, <span class="hljs-number">2.</span>, <span class="hljs-number">3.</span>],
  [<span class="hljs-number">2.</span>, <span class="hljs-number">3.</span>, <span class="hljs-number">4.</span>]
])

print(a.shape)  <span class="hljs-comment"># torch.Size([2, 3])</span>
print(a.ndim)   <span class="hljs-comment"># 2</span>
print(a.dtype)  <span class="hljs-comment"># torch.float32</span>
</code></pre>
<p><strong>3D Matrix (Rank-3 Tensor)</strong></p>
<p>A 3D array or a matrix. It has three dimensions and are used to represent 3 features or images (coloured)</p>
<pre><code class="lang-python">a = torch.tensor([
  [
    [<span class="hljs-number">1.</span>, <span class="hljs-number">2.</span>, <span class="hljs-number">3.</span>],
    [<span class="hljs-number">2.</span>, <span class="hljs-number">3.</span>, <span class="hljs-number">4.</span>]
  ],
  [
    [<span class="hljs-number">5.</span>, <span class="hljs-number">6.</span>, <span class="hljs-number">7.</span>],
    [<span class="hljs-number">8.</span>, <span class="hljs-number">9.</span>, <span class="hljs-number">10.</span>]
  ]
])
print(a.shape)  <span class="hljs-comment"># torch.Size([2, 2, 3])</span>
</code></pre>
<p><strong>4D Tensor (Rank-4 Tensor)</strong></p>
<p>It has four dimensions and is typically used for higher order data structures in Deep Learning such as video data with time, height, width and colour channels.</p>
<p>We will stick till rank-3 tensor only.</p>
<h3 id="heading-perceptron-in-pytorch">Perceptron in PyTorch</h3>
<p>A very basic Perceptron in PyTorch (only using torch tensor)</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> torch
<span class="hljs-keyword">import</span> pandas <span class="hljs-keyword">as</span> pd

<span class="hljs-comment"># Load the dataset</span>
df = pd.read_csv(
    <span class="hljs-string">"https://raw.githubusercontent.com/kashifulhaque/BSCS3004-Deep-Learning-resources/main/datasets/data.txt"</span>,
    sep = <span class="hljs-string">"\t"</span>
)

<span class="hljs-comment"># Isolate the features and labels</span>
X_train = df[[<span class="hljs-string">"x1"</span>, <span class="hljs-string">"x2"</span>]].values
y_train = df[<span class="hljs-string">"label"</span>].values

<span class="hljs-comment"># Convert the features and labels to torch tensor (from numpy array)</span>
X_train = torch.from_numpy(X_train)
y_train = torch.from_numpy(y_train)

<span class="hljs-comment"># Convert the train features to 32-bit floats</span>
X_train = X_train.to(torch.float32)

<span class="hljs-comment"># Define the Perceptron model</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Perceptron</span>:</span>
  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, num_features</span>):</span>
    <span class="hljs-comment"># Number of weights should match the number of features</span>
    self.weights = torch.zeros(num_features)
    self.bias = torch.tensor(<span class="hljs-number">0.</span>)

  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">forward</span>(<span class="hljs-params">self, x</span>):</span>
    <span class="hljs-comment"># Calculate the weighted sum, z = wx + b</span>
    z = torch.dot(x, self.weights) + self.bias

    <span class="hljs-comment"># Use the "harsh" Perceptron activation to get prediction</span>
    pred = torch.tensor(<span class="hljs-number">1.</span>) <span class="hljs-keyword">if</span> z &gt; <span class="hljs-number">0</span> <span class="hljs-keyword">else</span> torch.tensor(<span class="hljs-number">0.</span>)
    <span class="hljs-keyword">return</span> pred

  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">update</span>(<span class="hljs-params">self, x, y</span>):</span>
    pred = self.forward(x)
    error = y - pred

    <span class="hljs-comment"># Perceptron Learning Algorithm</span>
    self.bias += error
    self.weights += error * x

    <span class="hljs-keyword">return</span> error

<span class="hljs-comment"># Training loop</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">train</span>(<span class="hljs-params">model, x, y, epochs = <span class="hljs-number">10</span></span>):</span>
  <span class="hljs-keyword">for</span> epoch <span class="hljs-keyword">in</span> range(epochs):
    error_count = <span class="hljs-number">0</span>

    <span class="hljs-keyword">for</span> x_, y_ <span class="hljs-keyword">in</span> zip(x, y):
      error = model.update(x_, y_)
      error_count += abs(error)

    print(<span class="hljs-string">f"Epoch #<span class="hljs-subst">{epoch + <span class="hljs-number">1</span>}</span>, errors: <span class="hljs-subst">{error_count}</span>"</span>)

ppn = Perceptron(num_features = <span class="hljs-number">2</span>)
train(ppn, X_train, y_train, epochs = <span class="hljs-number">5</span>)

<span class="hljs-comment"># Evaluate the results</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">accuracy</span>(<span class="hljs-params">model, x, y</span>):</span>
  correct = <span class="hljs-number">0.0</span>

  <span class="hljs-keyword">for</span> x_, y_ <span class="hljs-keyword">in</span> zip(x, y):
    pred = model.forward(x_)
    correct += int(pred == y_)

  <span class="hljs-keyword">return</span> correct / len(y)

<span class="hljs-comment"># Print accuracy</span>
accuracy_train = accuracy(ppn, X_train, y_train)
print(accuracy_train)
</code></pre>
<p>Training loop output &amp; Accuracy</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696440865040/e56266bc-bcdc-4b9d-b2c1-95cc33b5cfaa.png" alt class="image--center mx-auto" /></p>
]]></content:encoded></item><item><title><![CDATA[How ImageMagick helped me create perfect product mockups]]></title><description><![CDATA[Increase your design workflow efficiency with ImageMagick. Learn how to generate stunning product mockups programmatically in our comprehensive guide.]]></description><link>https://blog.ifkash.dev/imagemagick-product-mockups</link><guid isPermaLink="true">https://blog.ifkash.dev/imagemagick-product-mockups</guid><category><![CDATA[ImageMagick]]></category><category><![CDATA[mockup]]></category><category><![CDATA[product]]></category><category><![CDATA[curtain]]></category><category><![CDATA[Python]]></category><dc:creator><![CDATA[Kashif]]></dc:creator><pubDate>Tue, 02 May 2023 18:09:35 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1684660517357/fb65527d-eb70-40fc-80e0-bf24cfc4444d.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Product mockups are a great way to showcase your designs, branding and products in a very realistic, natural and visually appealing way. Mockups help us visualize the design concepts and make decisions on colour schemes, layouts and overall aesthetics.</p>
<p>Many designers use tools like Adobe Photoshop to create product mockups. However, if we wish to achieve the same programmatically then the severe lack of documentation and resources proves to be a major hurdle.</p>
<p>This is where <a target="_blank" href="https://imagemagick.org">ImageMagick</a> comes in, a very powerful and open-source command-line tool that allows us to create, edit and convert images to a variety of formats. With certain steps and calculations, we can also generate product mockups very easily, preferably using code, without the use of any graphical user interface</p>
<p>In this blog, I will share my journey of discovering and using ImageMagick to generate product mockups. I will try to cover a few basics first, then move on to creating full-blown product mockups with code and also share the tips and tricks which I learnt along the way. Let's dive in!</p>
<h3 id="heading-lets-start-with-a-base-template-and-its-mask">Let's start with a base template and it's mask</h3>
<p>This is the base template image of a curtain which we will be using.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1683037102457/a22477a0-60a1-4dbf-862a-1ccf46a5c47d.jpeg" alt class="image--center mx-auto" /></p>
<p>And this 👇 will be the mask of curtains where we are supposed to place our image (turn on dark theme, on the right side of navbar at the top of this page)</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1683037260746/d7a7fb0e-c7c3-40bd-b6e9-9bd94fb423fd.png" alt class="image--center mx-auto" /></p>
<p>You want to know how to generate mask?</p>
<p>Well, that's for another blog post, you can either create it manually using any open source image manipulation tool like <a target="_blank" href="https://www.gimp.org">GIMP</a> or you can go the Machine Learning route and try the <a target="_blank" href="https://segment-anything.com">Segment-Anything Model (SAM)</a></p>
<h3 id="heading-adjustment-map">Adjustment map</h3>
<p>First, we would like to create an adjustment map of the base template image. It is a mask image which contains the shades of grey that correspond to the desired adjustments in brightness and contrast for the output image.</p>
<p>In our example, we will be using the <code>DivideSrc</code> composition operator, which divides the brightness of the base template by the brightness of the mask image. The resulting image has brightness and contrast adjustments that are proportional to the values of the mask image.</p>
<pre><code class="lang-bash">convert template.jpg \( -<span class="hljs-built_in">clone</span> 0 -fill <span class="hljs-string">"#f1f1f1"</span> -colorize 100 \) mask.png -compose DivideSrc -composite adjustment_map.jpg
</code></pre>
<p>Let's break down the command</p>
<ul>
<li><p><code>convert</code> command is used to convert images from one format to another, or to modify images in various ways.</p>
</li>
<li><p><code>template.jpg</code> is the first input image which will be used as the base template.</p>
</li>
<li><p><code>\( -clone 0 -fill "#f1f1f1" -colorize 100 \)</code> is a set of commands that create a grayscale mask image that will be used to adjust the brightness and contrast of the output image.</p>
<ul>
<li><p><code>\(</code> and <code>\)</code> are used to group commands together so they can be treated as a single object.</p>
</li>
<li><p><code>-clone 0</code> creates a clone of the first input image, i.e. <code>template.jpg</code></p>
</li>
<li><p><code>-fill "#f1f1f1"</code> sets the fill colour to a light grey colour.</p>
</li>
<li><p><code>-colorize 100</code> applies a 100% colourize effect, which turns the image into a greyscale image with the chosen fill colour.</p>
</li>
</ul>
</li>
<li><p><code>mask.png</code> is the mask of curtains in the base template.</p>
</li>
<li><p><code>-composite DivideSrc</code> sets the composition operator to <code>DivideSrc</code>, which will adjust the brightness and contrast of the output image based on the values of the mask image.</p>
</li>
<li><p><code>-composite</code> performs a composition operation on the input images, using the specified composition operator (mentioned above).</p>
</li>
<li><p><code>adjustment_map.jpg</code> is the output image that will be created as a result of the composition operation.</p>
<ul>
<li>It is a modified version of the original <code>template.jpg</code> image, with brightness and contrast adjusted based on the values of <code>mask.png</code> image.</li>
</ul>
</li>
</ul>
<p>This is what the adjustment map looks like, it looks very similar to the base template.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1683038137161/e8c6e256-470e-4ad4-b582-5bfcc745beb2.jpeg" alt class="image--center mx-auto" /></p>
<h3 id="heading-displacement-map">Displacement map</h3>
<p>It is an image that is used to modify the geometry of an image or texture. It works by using the pixel values of displacement map to shift the pixels of the target image or texture, creating a distorted or displaced effect.</p>
<p>In a displacement map, the greyscale values represent the amount and direction of displacement. Black pixels indicate no displacement, while white pixels indicate maximum displacement. Grey pixels represent intermediate levels of displacement and can create subtle variations in the effect.</p>
<p>Displacement maps are commonly used in computer graphics and image processing to create effects such as water ripples, terrain deformations and 3D object distortions. They can be created manually, or generated automatically from other images or data sources using various algorithms and techniques provided by ImageMagick.</p>
<pre><code class="lang-bash">convert template.jpg mask.png -alpha off -colorspace gray -compose CopyOpacity -composite normalized_map_tmp.mpc
</code></pre>
<p>Here is the breakdown of the above command</p>
<ul>
<li><p><code>convert</code> is used to convert images from one format to another, or to modify another image.</p>
</li>
<li><p><code>template.jpg</code> is the first input image, which will be used as a template.</p>
</li>
<li><p><code>mask.png</code> is the second input image, which will be used as a mask image.</p>
</li>
<li><p><code>-alpha off</code> turns off the alpha channel (transparency) for both images.</p>
</li>
<li><p><code>-colorspace gray</code> converts both images to grayscale.</p>
</li>
<li><p><code>-compose CopyOpacity</code> sets the composition operator to <code>CopyOpacity</code>, which copies the alpha channel from the mask image to the template image.</p>
</li>
<li><p><code>-composite</code> performs a composition operation on the input images, using the specified composition operator.</p>
</li>
<li><p><code>normalized_map_tmp.mpc</code> is the output image that will be created as a result of the composition operation. It will be a grayscale image with the same dimensions as the input images, where the values of each pixel are determined by the corresponding pixel values in the input images.</p>
</li>
</ul>
<p>In summary, the command is creating a grayscale image where the values of each pixel are determined by the corresponding pixel values in the template image, but with the alpha channel copied from the mask image. This effectively applies the transparency of the mask image to the template image, creating a grayscale image with transparency information that can be used for further image processing.</p>
<pre><code class="lang-bash">convert normalized_map_tmp.mpc -evaluate subtract 30% -background grey50 -alpha remove -alpha off displacement_map_tmp.mpc
</code></pre>
<p>Now, we pass the <code>normalized_map_tmp.mpc</code> to another set of commands, here is the breakdown</p>
<ul>
<li><p><code>convert</code> is the command used to convert images from one format to another, or to modify images in various ways.</p>
</li>
<li><p><code>normalized_map_tmp.mpc</code> is the input image, which is the grayscale image created by the previous command.</p>
</li>
<li><p><code>-evaluate subtract 30%</code> subtracts 30% from the values of each pixel in the input image.</p>
<ul>
<li><p>Why 30%?</p>
</li>
<li><p>I found this value to work very well for my use case. Feel free to experiment.</p>
</li>
</ul>
</li>
<li><p><code>-background grey50</code> sets the background colour to a neutral grey colour.</p>
</li>
<li><p><code>-alpha remove</code> removes any alpha channel from the image.</p>
</li>
<li><p><code>-alpha off</code> turns off the alpha channel (transparency) for the image.</p>
</li>
<li><p><code>displacement_map_tmp.mpc</code>: This is the output image that will be created as a result of the modification operations.</p>
<ul>
<li>It will be a grayscale image with the same dimensions as the input image, but with modified pixel values.</li>
</ul>
</li>
</ul>
<p>In summary, the command is modifying the input grayscale image by subtracting 30% from the values of each pixel, setting the background colour to a neutral grey, and removing the alpha channel. The resulting image is then saved as the output image, <code>displacement_map_tmp.mpc</code></p>
<p>This type of displacement map can be used in various image manipulation techniques, such as creating depth maps, generating 3D effects, and creating textures.</p>
<p>Lastly ...</p>
<pre><code class="lang-bash">convert displacement_map_tmp.mpc -blur 0x10 displacement_map.png
</code></pre>
<p>This command is performing a blur operation and then saves the output as a PNG file. <code>-blur 0x10</code> applies a Gaussian blur to the input image with a radius of 10 pixels</p>
<p>In summary, the command is applying a Gaussian blur to the input image using a radius of 10 pixels, which will smooth out any sharp transitions in the image and create a softer, more diffuse effect. The resulting blurred image is then saved as a PNG file named <code>displacement_map.png</code>. This type of blurred displacement map can be used in various image manipulation techniques, such as creating a motion blur effect or simulating a defocused or out-of-focus look in a photograph.</p>
<p>This is what the displacement map looks like.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1683042387401/411aec01-b8e1-4e7f-9dbb-539e2af07919.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-lighting-map">Lighting map</h3>
<p>It is a 2D image that is used to simulate the lighting effects on a 3D surface. It is often used in video games and other real-time graphics applications to create the illusion of complex lighting without the performance overhead of calculating actual light sources and their interactions in real-time.</p>
<p>A lighting map typically encodes information about the intensity and direction of light hitting each point on the surface of a 3D object. This information is often represented using greyscale or colour values that indicate the amount and colour of light that should be applied to each point on the surface</p>
<p>In image processing, a lighting map can be used to apply lighting effects to a 2D image, simulating the way light would fall on a real-world object. It can be used for realistic shadows, highlights and other lighting effects on a 2D image, making it look more three-dimensional and visually interesting, like a product mockup.</p>
<pre><code class="lang-bash">convert normalized_map_tmp.mpc -evaluate subtract 30% -background grey50 -alpha remove -alpha off lighting_map_tmp.mpc
</code></pre>
<ul>
<li><p><code>convert</code> is the command used to convert images from one format to another, or to modify images in various ways.</p>
</li>
<li><p><code>normalized_map_tmp.mpc</code> is the input image, which is a grayscale image created by the previous ImageMagick command (see Displacement map section)</p>
</li>
<li><p><code>-evaluate subtract 30%</code> subtracts 30% from the pixel values in the input image. This will darken the image since it is reducing the overall brightness of the image.</p>
</li>
<li><p><code>-background grey50</code> sets the background colour for the image to medium grey colour.</p>
</li>
<li><p><code>-alpha remove -alpha off</code> removes the alpha channel (transparency) from the image if it exists.</p>
</li>
<li><p><code>lighting_map_tmp.mpc</code> is the output image that will be created as a result of the image processing operations. It will be a greyscale image with the same dimensions as the input image, but with reduced brightness and no alpha channel.</p>
</li>
</ul>
<p>In summary, the command is creating a version of the input image with reduced brightness, which can be used as a lighting map for a 3D graphics application or other image processing techniques. The alpha channel is removed from the image to ensure that it has a consistent appearance across all pixels.</p>
<pre><code class="lang-bash">convert lighting_map_tmp.mpc \( -<span class="hljs-built_in">clone</span> 0 -fill grey50 -colorize 100 \) -compose lighten -composite lighting_map.png
</code></pre>
<ul>
<li><p><code>convert</code> is the command used to convert images from one format to another, or to modify images in various ways.</p>
</li>
<li><p><code>lighting_map_tmp.mpc</code> is the first input image, which is a grayscale image that was created by the previous ImageMagick command.</p>
</li>
<li><p><code>-clone 0</code> creates a copy of the first input image.</p>
</li>
<li><p><code>-fill grey50 -colorize 100</code> fills the cloned grayscale image with a medium grey colour (<code>grey50</code>) and then applies a colourize operation, which changes the hue and saturation of the image to 100% grey. This creates a solid grey colour image that will be used as a layer in the final composition.</p>
</li>
<li><p><code>-compose lighten -composite</code> composites the two input images together using a lighten blend mode. This blend mode will keep the brighter of the two input pixels in the output image. The resulting image will be a combination of the original lighting map and the solid grey colour image, with the solid grey colour image acting as a layer on top of the lighting map.</p>
</li>
<li><p><code>lighting_map.png</code> is the output image that will be created as a result</p>
</li>
</ul>
<p>This is what the lighting map looks like</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1683043917438/ddc3fde2-88d0-4fe9-9915-84af1c970787.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-generate-the-final-product-mockup">Generate the final product mockup</h3>
<p>Now we have all the infinity stones required to create our product mockup</p>
<p><img src="https://media.giphy.com/media/zX8dXeARiarZJ3ix9c/giphy.gif" alt class="image--center mx-auto" /></p>
<ul>
<li><p>Add a border</p>
<ul>
<li><pre><code class="lang-bash">      convert artwork.png -bordercolor transparent -border 1 tmp.mpc
</code></pre>
</li>
<li><p>Adds a 1px transparent border around the artwork</p>
</li>
<li><p>Modified output iamge will be saved in an MPC file (Magick Persistent Cache)</p>
</li>
<li><p>MPC is a high-performance, disk-based image format used by ImageMagick for temporary files and caching</p>
</li>
</ul>
</li>
<li><p>Do perspective transform</p>
<ul>
<li><pre><code class="lang-bash">      convert template.jpg -alpha transparent \( tmp.mpc +distort perspective <span class="hljs-string">"0,0,100,0,0,3000,100,4000,1500,3000,1700,4000,1500,0,1700,0"</span> \) -background transparent -layers merge +repage tmp.mpc
</code></pre>
</li>
<li><p><code>"0,0,100,0,0,3000,100,4000,1500,3000,1700,4000,1500,0,1700,0"</code> defines a set of 8 coordinates that will be used to define the perspective distortion to be applied to the <code>tmp.mpc</code> image.</p>
</li>
<li><p><code>-alpha transparent</code> sets the alpha channel of the input image to transparent.</p>
</li>
<li><p><code>+distort perspective "0,0,100,0,0,3000,100,4000,1500,3000,1700,4000,1500,0,1700,0"</code> applies a perspective distortion to the <code>tmp.mpc</code> image using the coordinates defined. The distortion will warp the image so that it appears to be viewed from a different angle.</p>
</li>
<li><p><code>-background transparent</code> sets the background color to transparent.</p>
</li>
<li><p><code>-layers merge</code> merges the two images together, with the distorted <code>tmp.mpc</code> image overlaid onto the background image.</p>
</li>
<li><p><code>+repage</code> resets the virtual canvas of the image.</p>
</li>
</ul>
</li>
<li><p>Set background colour to transparent</p>
<ul>
<li><pre><code class="lang-bash">      convert tmp.mpc -background transparent -alpha remove tmp.mpc
</code></pre>
</li>
<li><p>Overall, this command removes the alpha channel from the input image and sets the background color to transparent.</p>
</li>
</ul>
</li>
<li><p>Add displacement</p>
<ul>
<li><pre><code class="lang-bash">      convert tmp.mpc displacement_map.png -compose displace -<span class="hljs-built_in">set</span> option:compose:args 20x20 -composite tmp.mpc
</code></pre>
</li>
<li><p><code>-compose displace</code> sets the image composition mode to <code>displace</code>, which means that the displacement map will be used to shift the pixels of the base image.</p>
</li>
<li><p><code>-set option:compose:args 20x20</code> sets the arguments for the <code>displace</code> composition mode to <code>20x20</code>, which controls the amount of displacement in the X and Y directions. In this case, the value of 20 pixels is used for both directions.</p>
</li>
<li><p><code>-composite</code> composites the two images together using the specified composition mode and arguments.</p>
</li>
</ul>
</li>
<li><p>Add highlights</p>
<ul>
<li><pre><code class="lang-bash">      convert tmp.mpc \( -<span class="hljs-built_in">clone</span> 0 lighting_map.png -compose hardlight -composite \) +swap -compose CopyOpacity -composite tmp.mpc
</code></pre>
</li>
<li><p><code>\( -clone 0 lighting_map.png -compose hardlight -composite \)</code> creates a temporary layer by cloning the original image (<code>-clone 0</code>) and compositing it with the <code>lighting_map.png</code> image using the "hardlight" composition mode, which is a blending mode that increases contrast and saturation.</p>
</li>
<li><p><code>+swap</code> swaps the positions of the original image and the temporary layer.</p>
</li>
<li><p><code>-compose CopyOpacity</code> sets the composition mode to <code>CopyOpacity</code> which means that the opacity of the temporary layer will be applied to the original image.</p>
</li>
<li><p><code>-composite</code> composites the two images together using the specified composition mode and arguments.</p>
</li>
<li><p>Overall, this command applies a lighting effect to the input image using the <code>lighting_map.png</code> image as a reference.</p>
</li>
</ul>
</li>
<li><p>Adjust colours</p>
<ul>
<li><pre><code class="lang-bash">      convert tmp.mpc \( -<span class="hljs-built_in">clone</span> 0 adjustment_map.jpg -compose multiply -composite \) +swap -compose CopyOpacity -composite tmp.mpc
</code></pre>
</li>
<li><p><code>\( -clone 0 adjustment_map.jpg -compose multiply -composite \)</code> creates a temporary layer by cloning the original image (<code>-clone 0</code>) and compositing it with the <code>adjustment_map.jpg</code> image using the <code>multiply</code> composition mode.</p>
</li>
<li><p>This will darken the areas of the image where the adjustment map is dark and lighten the areas where it is light.</p>
</li>
<li><p><code>+swap</code> swaps the positions of the original image and the temporary layer.</p>
</li>
<li><p><code>-compose CopyOpacity</code> sets the composition mode to <code>CopyOpacity</code>, which means that the opacity of the temporary layer will be applied to the original image.</p>
</li>
<li><p><code>-composite</code> composites the two images together using the specified composition mode and arguments.</p>
</li>
<li><p>Overall, this command applies an adjustment effect to the input image using the <code>adjustment_map.jpg</code> image as a reference.</p>
</li>
</ul>
</li>
<li><p>Create the final product mockup</p>
<ul>
<li><p><code>convert template.jpg tmp.mpc mask.png -compose over -composite mockup.png</code></p>
</li>
<li><p><code>-compose over</code> sets the composition mode to <code>over</code>, which means that the second image will be composited over the first image</p>
</li>
<li><p><code>-composite</code> composites the second image over the first image using the specified composition mode and arguments</p>
</li>
<li><p><code>mask.png</code> is the mask image that will be used to blend the two input images together</p>
</li>
<li><p>Overall, this command creates a mockup image by compositing the <code>tmp.mpc</code> image over the <code>template.jpg</code> image using the <code>mask.png</code> image as a mask.</p>
</li>
<li><p>The resulting image is saved as <code>mockup.png</code></p>
</li>
<li><p>The mask is used to blend the two images together, so that the <code>tmp.mpc</code> image is only visible in the areas defined by the mask.</p>
</li>
</ul>
</li>
</ul>
<p>The final result looks something like this</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1683050595213/47f790ce-07cc-4fae-88d2-a43968c307c4.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1683050585753/de09c33d-cb87-4eee-9afe-1c60ea21908b.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>ImageMagick is a very powerful tool for generating product mockups programatically. With it's wide range of features and flexibility, we can create professional looking products very quickly and easily. ImageMagick can certainly help bring your ideas to life.</p>
]]></content:encoded></item><item><title><![CDATA[Setup VS Code for remote development]]></title><description><![CDATA[Well in order to setup a remote environment, you need a DigitalOcean account, you can use my referral code below to get $100 for 60 days just to try these…]]></description><link>https://blog.ifkash.dev/setup-vs-code-for-remote-development</link><guid isPermaLink="true">https://blog.ifkash.dev/setup-vs-code-for-remote-development</guid><category><![CDATA[ssh]]></category><category><![CDATA[remote]]></category><category><![CDATA[DigitalOcean]]></category><category><![CDATA[vscode]]></category><dc:creator><![CDATA[Kashif]]></dc:creator><pubDate>Thu, 15 Sep 2022 16:19:54 GMT</pubDate><content:encoded><![CDATA[<p>Well in order to setup a remote environment, you need a DigitalOcean account, you can use my referral code below to get $100 for 60 days just to try these things out 👇</p>
<p><a target="_blank" href="https://www.digitalocean.com/?refcode=34d6c62184bd&amp;utm_campaign=Referral_Invite&amp;utm_medium=Referral_Program&amp;utm_source=badge"><img src="https://web-platforms.sfo2.digitaloceanspaces.com/WWW/Badge%203.svg" alt="DigitalOcean Referral Badge" /></a></p>
<p>After you're done creating an account, let's move to the next step</p>
<h3 id="heading-creating-a-droplet"><strong>Creating a Droplet</strong></h3>
<ul>
<li><p>On the left menu, click on the Droplet button</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1684771113903/0fbf7ca3-4416-4414-b5c2-bf5d50d6603d.png" alt class="image--center mx-auto" /></p>
</li>
<li><p>Create a new droplet by clicking on the <code>"Create Droplet"</code> buton</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1684771156358/e86c5498-3ea1-4f6a-92dc-757137bfb5b3.png" alt class="image--center mx-auto" /></p>
</li>
<li><p>Choose a distro of your flavour (I choose Ubuntu for ease of use) and select your desired specs</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1684771189480/eca24958-a81b-409b-9530-2b76f7d60629.png" alt class="image--center mx-auto" /></p>
</li>
<li><p>Select the datacenter region closest to you for better latency</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1684771224742/38ec2547-2c0a-49f9-b4a7-baf07c0c7773.png" alt class="image--center mx-auto" /></p>
</li>
</ul>
<p>For Authentication, choose SSH keys and click on the <code>"New SSH Key"</code> button below</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1684771254739/b0dcdda0-27ae-4fd1-aedc-a1a24bc85a08.png" alt class="image--center mx-auto" /></p>
<blockquote>
<p>Use the command <code>ssh-keygen</code> to generate an SSH key, and the file would be stored under <code>~/.ssh/id_rsa.pub</code> (for Mac and Linux) and <code>C:\&lt;user_name&gt;\.ssh\id_rsa.pub</code> (for Windows)</p>
</blockquote>
<p><strong>NOTE:</strong> The command <code>ssh-keygen</code> might not work on Windows CMD or Powershell, use <a target="_blank" href="https://git-scm.com/download/win">Git Bash</a></p>
<ul>
<li><p>Finally, click on <code>"Create Droplet"</code> at the bottom and wait for a few minutes for it to spin up</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1684771919003/f4204367-60c9-4af6-9a76-c02e72440f86.png" alt class="image--center mx-auto" /></p>
</li>
</ul>
<h3 id="heading-connecting-to-droplet-via-ssh"><strong>Connecting to droplet via SSH</strong></h3>
<ul>
<li><p>Copy the IP address</p>
</li>
<li><p>Go to your terminal, and type 👉 <code>ssh root@&lt;IP_ADDRESS&gt;</code></p>
<ul>
<li>Example 👉 <code>ssh root@127.0.0.1</code></li>
</ul>
</li>
<li><p>Once inside the Droplet, create a new <code>sudo</code> user</p>
<ul>
<li><p>Create a new user 👉 <code>adduser vscode</code></p>
</li>
<li><p>Add it to <code>sudo</code> group 👉 <code>usermod -aG sudo vscode</code></p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1684771955025/efe316fa-d64c-4f11-b167-e0573688cafa.png" alt class="image--center mx-auto" /></p>
</li>
<li><p>Login as the user 👉 <code>su - vscode</code></p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1684772038088/2302c985-91e7-4cfc-9e34-dde82f8bc3f2.png" alt class="image--center mx-auto" /></p>
</li>
<li><p>Create a new <code>ssh</code> directory 👉 <code>mkdir ~/.ssh</code></p>
</li>
<li><p>Create a new file inside it 👉 <code>touch ~/.ssh/authorized_keys</code></p>
</li>
<li><p>Copy the contents of <code>id_rsa.pub</code> file, present on your local PC and paste it inside the <code>authorized_keys</code> file you created on your Droplet</p>
<ul>
<li><p>To paste the contents into <code>authorized_keys</code> file, you can use any cli based text editor, <code>nano</code> example below 👇</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1684772119117/d13549be-fd1c-445a-9cec-34a0c63bda8b.png" alt class="image--center mx-auto" /></p>
</li>
<li><p>Press <strong>Ctrl-X</strong>, then <strong>Y</strong> and then <strong>Enter</strong> to save the file</p>
</li>
</ul>
</li>
<li><p>[OPTIONAL] Type <code>chmod 600 ~/.ssh/authorized_keys</code> to make sure other users don't access this file</p>
</li>
</ul>
</li>
<li><p>Press <strong>Ctrl-D</strong> twice to logout from the Droplet and test ssh connection of this new user <code>vscode</code></p>
</li>
<li><p>Type <code>ssh vscode@&lt;IP_ADDRESS&gt;</code> to connect to your Droplet, but now as the user <code>vscode</code> instead of <code>root</code></p>
</li>
</ul>
<h3 id="heading-vs-code-remote-development"><strong>VS Code Remote development</strong></h3>
<ul>
<li><p>Add the <a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-ssh"><strong>Remote - SSH</strong> extension</a> to VS Code</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1684772200301/69fd82fc-f9f1-413b-a857-46a52d45e5a4.png" alt class="image--center mx-auto" /></p>
</li>
<li><p>Go to VS Code, click on the bottom left button</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1684772231660/c85bf98e-1c28-447d-8f79-59cb0959cb65.png" alt class="image--center mx-auto" /></p>
</li>
<li><p>Choose <strong>Connect to host</strong></p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1684772262613/9ce07d3e-52eb-49aa-9b30-61843bb2ecb5.png" alt class="image--center mx-auto" /></p>
</li>
<li><p>Type in <code>ssh vscode@&lt;IP_ADDRESS&gt;</code></p>
</li>
<li><p>Choose your <code>ssh</code> folder</p>
</li>
<li><p>Then you can connect to your Droplet for remote development</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1684772317609/e96b000d-6d2e-49ba-b53b-cc0ea3aa5b3d.png" alt class="image--center mx-auto" /></p>
</li>
<li><p>A new window will open, with remote connection to your Drop</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1684772344567/88f22fe6-d677-4fc0-b903-d6833fb6cec7.png" alt class="image--center mx-auto" /></p>
</li>
</ul>
<p>Now, you can make use of the VMs resources to build applications on the cloud</p>
]]></content:encoded></item></channel></rss>