<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Data Developer &amp; Analyst on Medium]]></title>
        <description><![CDATA[Stories by Data Developer &amp; Analyst on Medium]]></description>
        <link>https://medium.com/@shaafimran257?source=rss-9e8c78a7357a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*lXxoakFVPpp0islgIWvz_w.jpeg</url>
            <title>Stories by Data Developer &amp;amp; Analyst on Medium</title>
            <link>https://medium.com/@shaafimran257?source=rss-9e8c78a7357a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 23:25:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shaafimran257/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Four Ways to Generate: Masked Autoencoders, VAEs, Diffusion and RAG]]></title>
            <link>https://medium.com/@shaafimran257/four-ways-to-generate-masked-autoencoders-vaes-diffusion-and-rag-0d7b9d988ae2?source=rss-9e8c78a7357a------2</link>
            <guid isPermaLink="false">https://medium.com/p/0d7b9d988ae2</guid>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[autoencoder]]></category>
            <category><![CDATA[diffusion]]></category>
            <category><![CDATA[variational-autoencoder]]></category>
            <dc:creator><![CDATA[Data Developer & Analyst]]></dc:creator>
            <pubDate>Thu, 03 Dec 2026 04:22:15 GMT</pubDate>
            <atom:updated>2026-12-03T04:22:15.524Z</atom:updated>
            <content:encoded><![CDATA[<p>We built four generative systems and measured how each one behaves: a masked autoencoder that reconstructs satellite tiles, a variational autoencoder that samples Urdu handwriting, a class-conditional diffusion model that writes a requested character, and a retrieval-augmented generator that answers biomedical questions with citations. Comparing them was useful because their objectives fail in different, visible ways: reconstruction rewards plausible averages, sampling rewards a smooth latent space, diffusion rewards progressive denoising, and RAG rewards finding the right evidence before writing.</p><p>All code and results are in the public repository: <br>Github: <a href="https://github.com/MuhammadShaafImran/generative-04"><strong>https://github.com/MuhammadShaafImran/generative-04</strong></a></p><h3>Data distribution and Model Configs</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*oulLPGXfU9--nyOQ7Jt27g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*DnKokqoIYdVinGmdg53xiA.png" /></figure><h3>Part A: a satellite tile with 75% of its patches hidden</h3><p>EuroSAT tiles are 64 × 64 pixels, cut into 64 patches of 8 × 8 × 3. We embedded each patch to 192 dimensions, added learned positional embeddings, and kept only 16 visible patches per image. A six-layer transformer encoder saw those 16 tokens; a lightweight decoder received them plus a learned mask token at each of the 48 missing positions and predicted all 64 patches. The loss was mean squared error on masked patches only, so the model was never rewarded for copying visible pixels</p><figure><img alt="Figure 1. Top row: the masked input, with visible patches intact and masked patches grey. Middle row: the reconstruction, with predicted patches pasted back in. Bottom row: the original tile. The model recovers field boundaries, road direction and the rough colour layout, but the reconstructed regions are smooth and blurry." src="https://cdn-images-1.medium.com/max/1024/1*WSHOEEaczgYEvpb_6TJ-vg.png" /><figcaption><em>Figure 1. Top row: the masked input, with visible patches intact and masked patches grey. Middle row: the reconstruction, with predicted patches pasted back in. Bottom row: the original tile. The model recovers field boundaries, road direction and the rough color layout, but the reconstructed regions are smooth and blurry.</em></figcaption></figure><p>The pretraining loss fell from 0.0581 at epoch 1 to 0.00905 at epoch 10.</p><figure><img alt="Figure 2. Masked-patch MSE during MAE pretraining." src="https://cdn-images-1.medium.com/max/600/1*lOLZSxyK6A7Nk5OuSLNdSw.png" /><figcaption><em>Figure 2. Masked-patch MSE during MAE pretraining.</em></figcaption></figure><p>We then froze the encoder, fed all 64 patches without masking, averaged the 64 output tokens into one 192-dimensional feature, and trained a single linear layer on the 160 labelled images. Test accuracy on all 5,400 test tiles was <strong>51.37%</strong>, against a 10% chance level.</p><figure><img alt="Figure 3. Confusion matrix for the frozen-encoder linear probe trained on 16 images per class." src="https://cdn-images-1.medium.com/max/1024/1*GCj9PZCqTiH2NNUtrtopfA.png" /><figcaption><em>Figure 3. Confusion matrix for the frozen-encoder linear probe trained on 16 images per class.</em></figcaption></figure><p><strong>Why mask 75%?</strong> BERT masks only 15% because each token carries relatively little redundant information. Neighboring image patches are strongly correlated: if a road enters a visible patch, its continuation is often predictable from nearby color and texture. Masking only 15% would let the model interpolate from local pixels. Hiding 48 of 64 patches removes those shortcuts and forces the encoder to represent global layout — field geometry, water boundaries, urban texture. The reconstructions show this: large structures survive, fine texture does not.</p><p><strong>Which classes are confused?</strong> The largest off-diagonal entries are SeaLake → Pasture (151), AnnualCrop → PermanentCrop (147), PermanentCrop → HerbaceousVegetation (106) and Highway → River (102). SeaLake and Pasture can both be green or blue-green at this resolution, especially beside vegetation. AnnualCrop and PermanentCrop share the same brown-and-green patchwork; the difference is often agronomic rather than a strong color cue. Highway and River are both long, narrow, high-contrast structures. With only 16 labels per class, the linear probe cannot learn the context that separates them.</p><h3>Part B: a latent space for Urdu handwriting</h3><p>The VAE encoded each 28 × 28 character with two strided convolutions into a 16-dimensional mean and log-variance, sampled z by reparameterization, and decoded it to 784 Bernoulli logits. The loss was the negative ELBO: summed pixel cross-entropy plus the closed-form KL to a standard normal.</p><p>The terms moved in opposite directions. Training reconstruction error fell from 186.25 to 104.87 nats, while KL rose from 14.61 to 25.27. Final test values were <strong>105.50 reconstruction + 25.03 KL = 130.53 nats per image</strong>. Early on the encoder barely uses the latent code, so the posterior stays near the prior; as the decoder demands more information, the encoder moves away from N(0, I) and pays for it.</p><figure><img alt="Figure 4. Reconstruction, KL and total negative ELBO per epoch for train and test." src="https://cdn-images-1.medium.com/max/1024/1*5MwbDKH5S70nVh4kv3qAfw.png" /><figcaption><em>Figure 4. Reconstruction, KL and total negative ELBO per epoch for train and test.</em></figcaption></figure><figure><img alt="Figure 5. Top two rows: 16 test characters. Bottom two rows: their reconstructions. Stroke presence is preserved, but strokes are thicker and less crisp." src="https://cdn-images-1.medium.com/max/1024/1*mAk6Pjh5fhUttUcsi2f8Cw.png" /><figcaption><em>Figure 5. Top two rows: 16 test characters. Bottom two rows: their reconstructions. Stroke presence is preserved, but strokes are thicker and less crisp.</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VG2yjRnMiL0RbDyhKpooqQ.png" /><figcaption><em>Figure 6. Sixty-four characters decoded from z ~ N(0, I). Many are recognisable letter-like shapes, but several are blurred or ambiguous.</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xpS3DmVQPGD8B-N4OWUTxw.png" /><figcaption><em>Figure 7. Ten equally spaced points on the line between the latent means of two test characters. The shape changes gradually rather than jumping between unrelated symbols.</em></figcaption></figure><p>Without the KL term, the encoder could place each character in an isolated, low-variance region. Reconstruction might become almost perfect, but the decoder would only see those isolated codes. A sample from N(0, I) would land in empty space and decode to arbitrary noise. The KL term is what makes prior samples meaningful, at the cost of blurrier reconstructions.</p><h3>Part C: writing a requested character by reversing noise</h3><p>The diffusion model used the specified U-Net with 40 class embeddings and a linear schedule from β₁ = 10⁻⁴ to β₁₀₀₀ = 0.02. Training formed xt in closed form and trained the U-Net to predict the noise. At T = 1000, ᾱT = 4.04 × 10⁻⁵; a noised image has mean 0.03 and standard deviation 0.996, indistinguishable from pure noise</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-si_g6OaXCZW_0_yciXVYg.png" /><figcaption><em>Figure 8. Four training characters (x₀) and the same images after the closed-form forward process at t = 1000. The right-hand images are pure noise, as the schedule predicts.</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*LdOjF9ggPrc5hvRT3nRXUg.png" /><figcaption><em>Figure 9. Lsimple during DDPM training.</em></figcaption></figure><p>The saved artifacts include the forward-process check and the loss log, but not the final 40 × 8 sample grid or a completed blind-recognition sheet. We therefore do not report a blind accuracy or claim which characters the model writes worst: those numbers were not measured in the run captured in results/.</p><p>On the objective alone, diffusion should produce sharper strokes than the VAE. The VAE maximizes a pixel-wise Bernoulli likelihood, so an uncertain stroke is best answered with a grey average. Diffusion learns the score of the noisy data distribution and refines the sample over many steps, so edges stay crisper. Our saved diffusion evidence is not sufficient to demonstrate that visually.</p><h3>Part D: finding evidence in biomedical abstracts</h3><p>Each abstract was split into chunks of at most 150 words with 30-word overlap, producing <strong>79,332 chunks</strong>. Each chunk was encoded with all-MiniLM-L6-v2, mean-pooled over real tokens using the attention mask, and L2-normalised, giving a 79,332 × 384 index. A question is encoded the same way; one matrix multiplication gives cosine similarity to every chunk, and an abstract’s score is its best chunk. We retrieved the top 10 abstracts for all 707 test questions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/1*X9mh5rfHHyDcaF-rq5gJKg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*724VkD3Vldo6XjvjCCK1Jw.png" /><figcaption><em>Figure 10. Recall@k on all 707 test questions.</em></figcaption></figure><p>Retrieval is far above the random baseline. Recall@k is lower than Hit@k for the same k because they answer different questions. Hit@k asks whether at least one relevant abstract appears in the top k. Recall@k divides the number found by min(k, |Rq|), the number that could fit. With 8.66 relevant abstracts per question on average, one hit at k = 5 gives Hit@5 = 1 but Recall@5 = 0.2 at most. At k = 1 the two coincide, which is why Recall starts at 0.622 and initially dips before rising.</p><p>For generation we took the top five chunks, numbered them [1]–[5], and prompted Qwen2.5–1.5B-Instruct to answer only from those passages, cite passage numbers, and refuse when the passages were insufficient. On the first 100 test questions, <strong>ROUGE-L was 0.289</strong>, <strong>citation precision was 0.300</strong>, and the <strong>“I don’t know” rate was 3%</strong>. Citation precision is low partly because only 42 answers contained a citation; an answer with no citation scores zero. The supported and correct columns in results/human_eval.csv were blank in the saved file, so we do not report human ratings.</p><h3>Reproducing the work</h3><ul><li>Data: EuroSAT RGB and BioASQ mini load from Hugging Face; UHaT is downloaded from Zenodo into data/uhat/.</li><li>Training code: part_a_mae/, part_b_vae/, part_c_diffusion/, part_d_rag/.</li><li>Weights: part_a_mae/mae.pt, part_a_mae/mae_classifier.pt, part_b_vae/vae.pt, part_c_diffusion/ddpm_unet.pt.</li><li>Results: figures and tables in results/; the 100 generated answers are in results/rag_answers.jsonl.</li><li>Checks: 48 of 64 MAE patches are masked and the loss uses only those; the VAE KL is non-negative and zero at the prior; ᾱT = 4.04 × 10⁻⁵ and xT has standard deviation 0.996; every RAG chunk has at most 150 words, every embedding has unit norm, and a perfect ranking returns Hit@k = Recall@k = MRR@10 = 1.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0d7b9d988ae2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learning to Summarize from Human Feedback]]></title>
            <link>https://medium.com/@shaafimran257/learning-to-summarize-from-human-feedback-6b1ebc8c7551?source=rss-9e8c78a7357a------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b1ebc8c7551</guid>
            <dc:creator><![CDATA[Data Developer & Analyst]]></dc:creator>
            <pubDate>Fri, 13 Nov 2026 11:14:23 GMT</pubDate>
            <atom:updated>2026-11-13T11:14:23.630Z</atom:updated>
            <content:encoded><![CDATA[<p>This project compares supervised fine-tuning (SFT), reinforcement learning</p><p>from human feedback with PPO, and direct preference optimization (DPO) on</p><p>Reddit TL;DR summarization. The base model is SmolLM2–135M. The goal is not</p><p>only to produce summaries, but to measure how preference optimization changes</p><p>the model relative to a supervised baseline.</p><p><strong>## Pipeline</strong></p><p>The SFT stage trains on 20,000 post-summary pairs. The loss is computed only</p><p>on summary tokens, so the model is not rewarded for copying the prompt. The</p><p>resulting checkpoint is used as the starting policy for both preference</p><p>methods. A separate reward model uses the SFT transformer body and a scalar</p><p>head. It is trained on 20,000 chosen/rejected pairs with the Bradley-Terry</p><p>loss:</p><p>`-log sigmoid(r(x, y_chosen) — r(x, y_rejected))`.</p><p>The reward model reached a validation pairwise accuracy of</p><p>`{{REWARD_VALIDATION_ACCURACY}}`, above the 50% chance baseline. Its mistakes</p><p>are useful because they show where a small learned preference model is</p><p>uncertain. Three representative errors are included in</p><p>`results/reward_model_errors.md`.</p><p>PPO keeps a frozen SFT reference and a frozen reward model while updating the</p><p>policy. Each rollout contains 16 prompts, and the policy is updated for four</p><p>epochs. The reward-model score is placed on the final generated token, while</p><p>the KL penalty discourages the policy from drifting too far from SFT. The PPO</p><p>score changed from `{{PPO_FIRST_REWARD}}` to `{{PPO_FINAL_REWARD}}`, and the</p><p>mean KL changed from `{{PPO_FIRST_KL}}` to `{{PPO_FINAL_KL}}`. The average</p><p>summary length changed from `{{PPO_FIRST_LENGTH}}` to</p><p>`{{PPO_FINAL_LENGTH}}` tokens.</p><p>DPO uses the same preference data without training or loading a reward model</p><p>during optimization. It compares the policy’s chosen/rejected log-probability</p><p>margin with the frozen SFT reference. The normalising factor in the</p><p>implicit-reward derivation cancels in the pairwise comparison, so it never</p><p>needs to be computed explicitly. DPO achieved an implicit reward accuracy of</p><p>`{{DPO_IMPLICIT_REWARD_ACCURACY}}`.</p><p><strong>## Results</strong></p><p>All final policies were evaluated greedily on the same 300 held-out posts.</p><p>The reward-model score, win rate against SFT, KL to SFT, summary length, and</p><p>ROUGE-L were:</p><p>| Policy | Mean reward | Win rate vs SFT | KL to SFT | Length | ROUGE-L |</p><p>| — -| — -:| — -:| — -:| — -:| — -:|</p><p>| SFT | `{{SFT_MEAN_REWARD}}` | — | 0 | `{{SFT_LENGTH}}` | `{{SFT_ROUGE_L}}` |</p><p>| PPO | `{{PPO_MEAN_REWARD}}` | `{{PPO_WIN_RATE}}` | `{{PPO_KL}}` | `{{PPO_LENGTH}}` | `{{PPO_ROUGE_L}}` |</p><p>| DPO | `{{DPO_MEAN_REWARD}}` | `{{DPO_WIN_RATE}}` | `{{DPO_KL}}` | `{{DPO_LENGTH}}` | `{{DPO_ROUGE_L}}` |</p><p>![PPO curves](results/figures/ppo_curves.png)</p><p>![Training curves](results/figures/reward_training.png)</p><p>The most important comparison is between automatic reward and human</p><p>judgment. Members selected SFT `{{SFT_HUMAN_WINS}}` times, PPO</p><p>`{{PPO_HUMAN_WINS}}` times, and DPO `{{DPO_HUMAN_WINS}}` times, with</p><p>agreement on `{{HUMAN_AGREEMENT}}` of 30 posts. These results show whether</p><p>optimizing the learned reward actually improved usefulness, rather than only</p><p>increasing the reward-model score.</p><p><strong>## Lessons</strong></p><p>The KL coefficient is a practical safety rail. If `beta_KL` were zero, PPO</p><p>would have no direct cost for leaving the SFT distribution, making reward</p><p>hacking and repetition more likely. The observed clip fraction of</p><p>`{{PPO_CLIP_RANGE}}` indicates how often PPO attempted an update outside its</p><p>trust region. A small, stable fraction suggests conservative updates; a large</p><p>or rapidly growing fraction suggests that the learning rate, rollout size, or</p><p>reward scale needs attention.</p><p>For a new project, I would choose {{PREFERRED_METHOD}} because</p><p>{{METHOD_REASON}}. PPO provides explicit control through the reward and KL</p><p>terms, while DPO is simpler operationally because it avoids a separately</p><p>trained reward model. The best choice depends on whether the project needs</p><p>online reward shaping or a lightweight preference-training pipeline.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b1ebc8c7551" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Text-to-SQL Model From Scratch: What I Learned (and What Broke)]]></title>
            <link>https://medium.com/@shaafimran257/building-a-text-to-sql-model-from-scratch-what-i-learned-and-what-broke-bc5a5cb70f6a?source=rss-9e8c78a7357a------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc5a5cb70f6a</guid>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Data Developer & Analyst]]></dc:creator>
            <pubDate>Mon, 05 Oct 2026 10:52:47 GMT</pubDate>
            <atom:updated>2026-10-05T10:52:47.605Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Training a small Transformer on WikiSQL, with no pretrained models and no shortcuts.</em></p><p><strong>[IMAGE 1: Cover image. Suggestion: a natural-language question on the left, an arrow, and a SQL-like query on the right]</strong></p><h3>Introduction</h3><p>Ask a database “which school did player number 21 play for?” and it won’t understand you. It wants SQL.</p><p>Text-to-SQL models try to close that gap by translating plain English into structured queries. Most tutorials fine-tune a huge pretrained model. For my Generative AI course assignment, I wanted to see what happens when you build everything yourself: a small sequence-to-sequence Transformer, trained from scratch, with its own tokenizer, decoding, evaluation, and a demo UI.</p><p>This post walks through the project, the results, and what the numbers actually say.</p><p>🔗 <strong>Code:</strong> <a href="https://github.com/MuhammadShaafImran/text-2-SQL-scratch">github.com/MuhammadShaafImran/text-2-SQL-scratch</a></p><h3>The Dataset: WikiSQL</h3><p>I used <strong>WikiSQL</strong>, a large collection of questions paired with simple SQL queries over single Wikipedia tables. Every query has the same basic shape:</p><ul><li>one selected column, optionally wrapped in an aggregation (COUNT, MAX, MIN, SUM, AVG)</li><li>zero or more WHERE conditions</li></ul><p>That regularity makes it a good fit for a first from-scratch project.</p><p><strong>[IMAGE 2: Example WikiSQL table with a question and its target query highlighted]</strong></p><h3>A Compact Target Format</h3><p>Instead of generating full SQL strings, the model generates a simplified <strong>logical form</strong>, where columns are replaced by index tokens like &lt;c0&gt;, &lt;c1&gt;, and so on:</p><pre>Question: what school did player number 21 play for?<br>Target:   select &lt;c5&gt; where &lt;c1&gt; = 21</pre><p>This shrinks the output vocabulary, and the logical form can be parsed back into a structured query for evaluation.</p><h3>The Model</h3><p>The model is an <strong>encoder-decoder Transformer</strong> with about <strong>7.6 million trainable parameters</strong>, tiny by modern standards. The pipeline:</p><ol><li><strong>Tokenization:</strong> a SentencePiece model trained on the data</li><li><strong>Encoder:</strong> reads the question</li><li><strong>Decoder:</strong> generates the logical form one token at a time, attending to the question through cross-attention</li><li><strong>Decoding:</strong> greedy search or beam search</li></ol><p><strong>[IMAGE 3: Architecture diagram of the encoder-decoder Transformer]</strong></p><p>I also generated analysis plots such as the <strong>positional encoding</strong> visualization and a <strong>cross-attention heatmap</strong>. The heatmap shows which words in the question the decoder looks at when producing each output token.</p><p><strong>[IMAGE 4: Cross-attention heatmap for a sample question]</strong></p><h3>Beyond the Model: Making It Usable</h3><p>Training a model is only half the story, so I built a small deployment pipeline:</p><ul><li><strong>Inference in Google Colab:</strong> a notebook loads the trained checkpoint and exposes a POST /api/query endpoint through <strong>ngrok</strong></li><li><strong>Frontend on Vercel:</strong> a lightweight “Query Studio” UI where you paste the endpoint URL and start asking questions</li><li><strong>Hosted option:</strong> a Flask app (app.py) that can instead call a model hosted on Hugging Face</li></ul><p>This keeps the heavy PyTorch inference on a free GPU while the interface stays a static site.</p><p><strong>[IMAGE 5: Screenshot of the Query Studio UI]</strong></p><h3>Evaluation: Where It Gets Interesting</h3><p>I evaluated the model on 1,000 examples from the dev set using <strong>beam search (beam size 4)</strong>:</p><pre>python evaluate_model.py --split data/dev_pairs.jsonl --strategy beam --beam-size 4 --limit 1000</pre><p>Metric Result Teacher-forced loss 2.2948 Perplexity 9.92 Token accuracy (teacher-forced) 74.17% Parse-valid outputs 92.20% Aggregation accuracy 80.80% Conditions exact accuracy 25.50% Selected-column accuracy 27.00% <strong>Logical-form exact match</strong> <strong>11.00%</strong> <strong>Execution accuracy</strong> <strong>79.30%</strong></p><p><strong>[IMAGE 6: Screenshot of the terminal output or a bar chart of these metrics]</strong></p><h3>Reading the Numbers Honestly</h3><p>At first glance these metrics look contradictory: <strong>79.3% execution accuracy</strong> next to <strong>11% exact match</strong>. Here is how I read them.</p><p><strong>What’s working</strong></p><ul><li><strong>Syntax is mostly solved.</strong> 92% of generated outputs parse into valid queries, so the model learned the structure of the language.</li><li><strong>Aggregations are easy.</strong> At ~81%, it reliably picks up cues like “how many” → COUNT.</li></ul><p><strong>What’s not</strong></p><ul><li><strong>Column selection is weak</strong> (27%). The model often picks the wrong column index.</li><li><strong>Conditions are the hardest part</strong> (25.5%). Getting the right column, operator, <em>and</em> value all at once is difficult.</li></ul><p><strong>Why the gap between execution and exact match?</strong><br> Exact match demands that the logical form be identical to the reference. Execution accuracy only checks whether the query returns the same <em>result</em>. Different queries can return the same answer, especially on small tables, so execution accuracy can look more flattering than the model’s real understanding. I treat exact match and the component accuracies as the more honest signals, and execution accuracy as a looser upper-level view.</p><h3>Looking at Real Predictions</h3><p>Numbers only go so far, so here are five samples:</p><p>Question and their expected answers</p><pre>What position does the player who played for Butler CC (KS) play? select &lt;c3&gt; where &lt;c5&gt; = butler cc (ks) select &lt;c2&gt; where &lt;c0&gt; = butler (X)<br>How many schools did player number 3 play at? select count &lt;c5&gt; where &lt;c1&gt; = 3 select count &lt;c2&gt; where &lt;c1&gt; = 3 (X)<br>What school did player number 21 play for? select &lt;c5&gt; where &lt;c1&gt; = 21 select &lt;c5&gt; where &lt;c1&gt; = 21 (✓)<br>Who is the player that wears number 42? select &lt;c0&gt; where &lt;c1&gt; = 42 select &lt;c0&gt; where &lt;c4&gt; = wears (X)<br>What player played guard for Toronto in 1996-97? select &lt;c0&gt; where &lt;c3&gt; = guard and &lt;c5&gt; = 1996-97... select &lt;c0&gt; where &lt;c3&gt; = guard and &lt;c5&gt; = 1996-97 (X)</pre><p><strong>[IMAGE 7: Side-by-side screenshot of expected vs generated outputs]</strong></p><p>The failures are instructive:</p><ul><li><strong>Sample 2</strong> gets the aggregation (count) and the condition right, but picks the wrong column. The model understood the <em>intent</em> and missed the <em>schema</em>.</li><li><strong>Sample 4</strong> copies the word “wears” as the condition value instead of the number 42. It latched onto a nearby word rather than the real value.</li><li><strong>Sample 5</strong> is nearly perfect, with a single wrong column index (&lt;c5&gt; instead of &lt;c4&gt;).</li><li><strong>Sample 1</strong> truncated the value (butler vs butler cc (ks)) and picked the wrong columns.</li></ul><p>A pattern emerges: <strong>the model understands query <em>structure</em> well but struggles to ground words in the correct table columns.</strong></p><h3>Why Column Grounding Is Hard</h3><p>The core limitation of this setup is that <strong>the model never sees the table schema.</strong> It gets only the question, then must guess that “position” means &lt;c3&gt; and &quot;school&quot; means &lt;c5&gt;. Those mappings are only learnable from statistical patterns across the training data, and they differ from table to table.</p><p>A model that sees the column names alongside the question can match words to headers directly. That is the standard approach in stronger text-to-SQL systems, and the most obvious next step here.</p><h3>What I’d Improve Next</h3><ol><li><strong>Feed the schema into the encoder.</strong> Concatenate column headers with the question so the model can ground its output.</li><li><strong>Add a copy mechanism.</strong> This would help with condition values like butler cc (ks) that must be copied verbatim from the question.</li><li><strong>Use constrained decoding.</strong> Restrict output to valid column indices and grammar so invalid or nonsensical queries can’t be generated.</li><li><strong>Train longer or scale up.</strong> 7.6M parameters is small, and the loss was still non-trivial at epoch 15.</li><li><strong>Report stricter execution metrics</strong> on real tables, to make the execution score more trustworthy.</li></ol><h3>Takeaways</h3><ul><li>Building from scratch teaches you where the real difficulty lives. <strong>Syntax is easy; grounding is hard.</strong></li><li>A single metric can mislead. Reading <strong>exact match, component accuracy, and execution accuracy together</strong> gave a much truer picture than any one of them.</li><li>Reading actual predictions beats staring at aggregate numbers.</li><li>A free Colab GPU plus a static Vercel frontend is enough to turn a research-style assignment into something people can try.</li></ul><p>If you’re learning about sequence-to-sequence models, I’d recommend this kind of project. It’s humbling in the best way.</p><h3>Try It Yourself</h3><p><strong>Repository:</strong> <a href="https://github.com/MuhammadShaafImran/text-2-SQL-scratch">MuhammadShaafImran/text-2-SQL-scratch</a></p><p><em>Questions or suggestions? Drop a comment below, I’d love to hear how you’d improve it.</em></p><p><strong>Notes for you before publishing:</strong></p><ul><li>Sample 5’s expected output was cut off in your terminal paste, so I marked it with .... Paste the full line if you want it exact.</li><li>I described the model as an encoder-decoder Transformer based on the README’s mentions of cross-attention and decoder layers. Adjust the architecture section if your layer counts, heads, or embedding size differ, and add those numbers since readers like specifics.</li><li>The README doesn’t state training time, dataset size, or hardware, so I left them out. Add them if you have them.</li></ul><p>Want me to put this in a Word or Markdown file so it’s easier to paste into Medium?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc5a5cb70f6a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an Urdu Question Generator: Deep Dive into Seq2Seq Architectures, LSTMs, and Luong…]]></title>
            <link>https://medium.com/@shaafimran257/building-an-urdu-question-generator-deep-dive-into-seq2seq-architectures-lstms-and-luong-f032dc42a005?source=rss-9e8c78a7357a------2</link>
            <guid isPermaLink="false">https://medium.com/p/f032dc42a005</guid>
            <category><![CDATA[encoder-decoder]]></category>
            <category><![CDATA[self-attention]]></category>
            <category><![CDATA[sequence-to-sequence]]></category>
            <dc:creator><![CDATA[Data Developer & Analyst]]></dc:creator>
            <pubDate>Sat, 12 Sep 2026 19:14:54 GMT</pubDate>
            <atom:updated>2026-09-12T19:14:54.303Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building an Urdu Question Generator: Deep Dive into Seq2Seq Architectures, LSTMs, and Luong Attention</h3><p><em>A comprehensive engineering guide on transforming raw Urdu text into targeted questions using a custom subword tokenizer, a 2-layer Bidirectional LSTM encoder, Luong General Attention, and full tensor shape tracking.</em></p><h3>1. Introduction: The Sequence-to-Sequence Paradigm</h3><p>Sequence-to-Sequence (Seq2Seq) models are the foundational pillar of conditional language generation tasks, ranging from neural machine translation to document summarization and dialogue systems. At its core, a Seq2Seq model maps an input sequence of variable length X = (x₁, …, x_Tsrc) to an output sequence of variable length Y = (y₁, y₂, …, y_Ttgt).</p><p>Unlike standard feedforward networks that operate on fixed-dimensional vectors, Seq2Seq frameworks process temporal data where time dependencies and contextual structure matter. In our task — <strong>Urdu Question Generation</strong> — the system takes an Urdu declarative sentence containing a highlighted answer span (marked with &lt;ans&gt; and &lt;/ans&gt;) and generates an answerable question.</p><pre>Input Source:  علامہ اقبال نے &lt;ans&gt; ۱۹۳۰ &lt;/ans&gt; میں خطبہ الہ آباد دیا۔<br>Target Output: علامہ اقبال نے خطبہ الہ آباد کب دیا؟</pre><h3>2. Anatomy of the Generator: Combining LSTM Cells</h3><p>Standard Recurrent Neural Networks (RNNs) suffer from vanishing and exploding gradients when processing long sequences, preventing early information from reaching later time steps. <strong>Long Short-Term Memory (LSTM)</strong> networks overcome this by introducing a dedicated cell state Cₜ alongside the hidden state hₜ, regulated by three gating mechanisms:</p><ol><li><strong>Forget Gate (fₜ):</strong> Controls what portion of the previous cell state Cₜ₋₁ to discard.</li><li><strong>Input Gate (iₜ):</strong> Determines which new information to update in the cell state.</li><li><strong>Output Gate (oₜ):</strong> Filters the updated cell state to produce the current hidden state hₜ.</li></ol><p>To build a <strong>sequence generator</strong>, multiple LSTM cells are combined across time and stacked across depth:</p><ul><li><strong>Temporal Cascading:</strong> The hidden state hₜ₋₁ and cell state Cₜ₋₁ from time step t − 1 are passed as inputs to time step t.</li><li><strong>Deep Stacking:</strong> In a multi-layer LSTM, the hidden state output hₜ⁽ˡ⁾ from layer l serves as the input sequence for layer l + 1 at the same time step t.</li></ul><p>During autoregressive generation, the decoder LSTM generates tokens one step at a time. At step t, it consumes the token generated at step t − 1 (or the ground-truth target during <strong>teacher forcing</strong>), updates its internal states (hₜᵈᵉᶜ, Cₜᵈᵉᶜ), and emits a probability distribution over the vocabulary.</p><h3>3. Data Pipeline &amp; SentencePiece Tokenization</h3><p>Because Urdu is a morphologically rich language with continuous script, standard whitespace splitting is inadequate. We employ a <strong>SentencePiece Unigram subword tokenizer</strong> trained directly on the Urdu dataset with an <strong>8,000-token vocabulary</strong>:</p><ul><li><strong>Vocabulary Size (V):</strong> 8,000 subword units.</li><li><strong>Special Tokens:</strong> PAD=0, UNK=1, BOS=2, EOS=3.</li><li><strong>User-Defined Markers:</strong> &lt;ans&gt; and &lt;/ans&gt; to bound the target answer span without subword splitting.</li></ul><p>During batching, sequences are zero-padded to match the maximum length in the current batch. For our walk-through, we assume a standard mini-batch size of <strong>N = 64</strong>.</p><h3>4. Complete End-to-End Architectural Blueprint &amp; Tensor Dimensions</h3><p>Below is the step-by-step progression of an Urdu sentence through the model pipeline, detailing how tensor dimensions align across every transformation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c9ksF-Yhiz8xNcP66l0MHQ.png" /><figcaption>End-to-End Architecture of Sequence 2 Sequence Model</figcaption></figure><h3>Step 1: Input Representation &amp; Word Embedding</h3><p><strong>Input Tensor Shape:</strong> [64, Tₛᵣc] Each sequence is tokenized into subword IDs. Tₛᵣc represents the sequence length of the padded batch.</p><ul><li><strong>Embedding Matrix (Wₑₘᵦ):</strong> Dimensions [].</li><li><strong>Output Tensor Shape:</strong> [64, Tₛᵣc, 256] Each token ID is mapped to a 256-dimensional dense vector.</li></ul><h3>Step 2: 2-Layer Bidirectional LSTM Encoder</h3><p>The encoder processes the embedded sequence simultaneously in forward (→) and backward (←) directions:</p><ul><li><strong>Hidden Units per Direction:</strong> 512 units.</li><li><strong>Layer 1 Output:</strong> Concatenates h⃗ₜ⁽¹⁾ (512) and h⃖ₜ⁽¹⁾ (512) → [64, Tₛᵣc, 1024].</li><li><strong>Layer 2 Output (Hᵉⁿᶜ):</strong> Concatenates h⃗ₜ⁽²⁾ (512) and h⃖ₜ⁽²⁾ (512) → [64, Tₛᵣc, 1024].</li></ul><p><strong>Encoder Final States:</strong></p><ul><li><strong>Hidden State (hₑₙc):</strong> Shape [] (where 4 = 2 layers × 2 directions).</li><li><strong>Cell State (cₑₙc):</strong> Shape [].</li></ul><h3>Step 3: Encoder-to-Decoder Linear State Projection</h3><p>The decoder is a <strong>2-layer unidirectional LSTM</strong> with 512 hidden units. Because the bidirectional encoder produces a combined 1,024-dimensional representation per layer (512 forward + 512 backward), we cannot pass the encoder final states directly into the decoder.</p><p>We apply linear projection layers Wₚᵣₒⱼ₋ₕ and Wₚᵣₒⱼ₋c to adapt the concatenated encoder states:</p><p><strong>Projected Initial Decoder States:</strong></p><ul><li>Initial Hidden State (h_dₑc,₀): Shape [].</li><li>Initial Cell State (C_dₑc,₀): Shape [].</li></ul><p><strong>Encoder Output Projection (Hᵉⁿᶜ⁻ᵖʳᵒʲ):</strong> The sequence representations are also projected from 1,024 to 512 dimensions for attention scoring → [64, Tₛᵣc, 512].</p><h3>Step 4: 2-Layer Unidirectional LSTM Decoder</h3><p>Decoding occurs autoregressively, one step at a time. At decoding step <strong>t</strong>:</p><ul><li><strong>Input:</strong> Target token yₜ₋₁ is embedded into a tensor of shape [64, 1, 256].</li><li><strong>Decoder Pass:</strong> The 2-layer LSTM processes the token and the previous decoder states (hₜ₋₁ᵈᵉᶜ, Cₜ₋₁ᵈᵉᶜ).</li><li><strong>Decoder Output State (hₜᵈᵉᶜ):</strong> Shape [64, 1, 512].</li></ul><h3>Step 5: Luong General Attention Mechanism</h3><p>Rather than relying on a single static encoder state, <strong>Luong General Attention</strong> dynamically compares the current decoder state hₜᵈᵉᶜ against all encoder states Hᵉⁿᶜ_ₚᵣₒⱼ:</p><ol><li>The decoder state is compared against every projected encoder state.</li><li><strong>Alignment Score Computation:</strong> We use the general content-based scoring function:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/282/1*WFZaPJzkEuyVjLNp79FFkQ.png" /></figure><p>where Wₐ ∈ ℝ⁵¹² ˣ ⁵¹² is a learnable parameter matrix.</p><ol><li>The resulting attention score tensor has shape [64, 1, T_src].</li><li><strong>Attention Weights (αₜ):</strong> Softmax normalization is applied across the source sequence length Tₛᵣ꜀:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/319/1*kdbXkE9K-0sz7wK71ilINQ.png" /></figure><p>The resulting shape is [64, 1, T_src].</p><ol><li><strong>Context Vector (cₜ):</strong> A weighted sum over the projected encoder outputs is computed using batch matrix multiplication:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/535/1*QMFwUuQ96mC_xg_G6CAPpA.png" /></figure><p>The resulting context vector has shape [64, 1, 512].</p><h3>Step 6: Attentional Hidden State &amp; Vocabulary Projection</h3><p>Following Luong’s formulation, the context vector cₜ and decoder hidden state hₜᵈᵉᶜ are concatenated along the feature axis:</p><ol><li>The context vector and decoder hidden state are combined to form a 1,024-dimensional representation.</li></ol><p><strong>Concatenation:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/205/1*_i0ywcj7UkGxW-jaQLStFw.png" /></figure><p>The resulting shape is [64, 1, 1024].</p><p><strong>Attentional Projection (h̃ₜ):</strong> The concatenated representation is passed through a linear layer W꜀ ∈ ℝ¹⁰²⁴ ˣ ⁵¹² with a tanh activation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/315/1*k4fPWhbvvt2nuPqBHofOwQ.png" /></figure><p>The resulting shape is [64, 1, 512].</p><p><strong>Vocabulary Logits Output:</strong> The attentional hidden state is projected to the 8,000-subword vocabulary through the linear layer Wₛ ∈ ℝ⁵¹² ˣ ⁸⁰⁰⁰:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/279/1*XK2O8e5E34LgDusL0qNTeg.png" /></figure><p>The resulting shape is [64, 1, 8000].</p><p><strong>Prediction:</strong> Applying softmax to the logits yields a probability distribution over all 8,000 subwords, from which the next generated Urdu token can be sampled or selected.</p><h3>5. Tensor Dimension Summary Table</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2C_JrfafG5zSj03egskucA.png" /></figure><h3>6. Experimental Training &amp; Empirical Insights</h3><p>We trained this from-scratch architecture across <strong>15 epochs</strong> using the Adam optimizer (lr = 10⁻³) and a teacher forcing ratio of 0.5:</p><ul><li><strong>Trainable Parameters:</strong> ≈25.79 million.</li><li><strong>Loss Trajectory:</strong> Training loss dropped steadily from <strong>6.1696</strong> (Epoch 1) to <strong>4.0591</strong> (Epoch 15). Validation loss converged to <strong>4.8202</strong> at Epoch 15.</li><li><strong>Decoding Performance:</strong> On the in-domain <strong>UQA validation set</strong>, Beam Search (k = 3) achieved a BLEU-4 of <strong>2.8041</strong> and ROUGE-L of <strong>0.0048</strong>.</li><li><strong>Out-of-Domain Generalization Gap:</strong> Evaluating on the <strong>Wiki-UQA set</strong> caused Perplexity (PPL) to jump from <strong>61.52 to 115.94</strong>, while BLEU-4 dropped to <strong>1.5119</strong>. This performance degradation highlights the vulnerability of small RNN models to distribution shifts caused by longer source sequences (mean whitespace tokens of 156.6 vs. 33.2).</li></ul><h3>7. Conclusion</h3><p>Building an Urdu sequence generator from scratch provides valuable insights into neural machine translation fundamentals. While modern Transformer architectures have largely replaced RNNs because of their parallelization advantages, understanding the exact tensor flow, hidden-state projections, and alignment mechanics of LSTM-based Seq2Seq models remains essential for mastering conditional text generation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f032dc42a005" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[History of Fatimid Dynasty]]></title>
            <link>https://medium.com/@shaafimran257/history-of-fatimid-dynasty-3aa844cc1b1e?source=rss-9e8c78a7357a------2</link>
            <guid isPermaLink="false">https://medium.com/p/3aa844cc1b1e</guid>
            <dc:creator><![CDATA[Data Developer & Analyst]]></dc:creator>
            <pubDate>Wed, 11 Oct 2023 09:35:27 GMT</pubDate>
            <atom:updated>2023-10-11T09:35:27.841Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*cRACcjYwODz43lCZu1bD1A.jpeg" /><figcaption>Fatimid Dynasty flag</figcaption></figure><p>The Fatimid Dynasty ruled in much of North Africa. The Fatimids belonged to the Ismaili Shia faith. Abdullah-al-mahdi billah was a founder of the Fatimids caliphate. The Fatimids claimed descent from hazrat fatimah.</p><p>The first caliph, Abdullah-al-mahdi billah, established his capital at Raqqada in Tunisia.</p><p>Under the Fatimid, Egypt became the center of the empire. At its peak, north Africa, Sicily, Palestine, Syria and the red sea coast of Africa, Yemen and Hejaz were under the control of the Fatimids. During the reign of Fatimids, Egypt flourished and developed an extensive trade network in both the Mediterranean and the Indian Ocean which eventually determined the economic course of Egypt during the high middle Ages. They built many historical buildings like masjid of mahdiya, Tunisia, Al-Azhar masjid, Cairo and the great Al-Hakim masjid, Cairo in 1013 CE.</p><p>In 1171 CE sultan Salah-ud-Din Ayubi had become the real master of Egypt, and the Fatimid Dynasty. Thus, Fatimid were overthrow by sultan Salah-ud-Din Ayubi and established Ayyubid Dynasty.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3aa844cc1b1e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Contribution of Seljuk rulers]]></title>
            <link>https://medium.com/@shaafimran257/contribution-of-seljuk-rulers-b16b5fb8f0c9?source=rss-9e8c78a7357a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b16b5fb8f0c9</guid>
            <dc:creator><![CDATA[Data Developer & Analyst]]></dc:creator>
            <pubDate>Tue, 10 Oct 2023 11:31:31 GMT</pubDate>
            <atom:updated>2023-10-10T11:31:31.369Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/657/1*0LI_YKsOGPaMhl4A6ILYlg.jpeg" /><figcaption>Seljuks dynasty flag</figcaption></figure><p>. The Seljuks played a major role in medieval history by creating a barrier to Europe against the Mongols invaders from the East, defending the islamic world against crusaders from the West, and conquering large parts of the Byzantine Empire. Under Tughril Beg rule, the Seljuks assumed the leadership of the Islamic world by establishing political mastery over the Abbasids caliphate in Baghdad. Tughril Beg ruled great Seljuk Empire until his death in 1063. His nephew Alp Arslan succeeded him as sultan.</p><p>. Sultan Alp Arslan became the second ruler of the Great Seljuk Empire in 1063 CE. Sultan Alp Arslan ( the Lion-hearted), opened the gates of Anatolia to Turks in 1071 CE by defeating the Byzantine army. He is remembered for his heroism and war strategies.</p><p>. Nasir-ud-Din Mahmud-1 ( 1087–1094 CE ) succeeded Malik shah-1 as sultan, but he did not gain control of the empire built by Malik Shah and Alp Arslan. Mahmud-2&#39; reign ( 1105 - 1118 CE ) is recognized for the extensive administration military, and social and economic reforms. Tughril-3 ( 1169- 1194 CE ) was the last sultan of Seljuk Empire. Ala-ud-Din Tekish, Shah of khwarazmian Empire defeated Tughril-3 and the Seljuk Empire collapsed in 1194 CE.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b16b5fb8f0c9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[History of Seljuk dynasty]]></title>
            <link>https://medium.com/@shaafimran257/history-of-seljuk-dynasty-4366127c1b54?source=rss-9e8c78a7357a------2</link>
            <guid isPermaLink="false">https://medium.com/p/4366127c1b54</guid>
            <dc:creator><![CDATA[Data Developer & Analyst]]></dc:creator>
            <pubDate>Tue, 10 Oct 2023 11:07:51 GMT</pubDate>
            <atom:updated>2023-10-10T11:07:51.785Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*Xg36Vygpa0z3p0RYVzpqMA.jpeg" /></figure><h3>Seljuk dynasty (1037 - 1194 CE)</h3><p>The Seljuk dynasty was founded by Tughril Beg and his brother chaghri beg in 1307 CE. It was a Turkish dynasty based in central Anatolia. From their homelands near the Aral sea, the Seljuks advanced first into khurasan, then into Persia and Anatolia. The Seljuks won the battle of manzikert in 1071 CE and conquered most of Anatolia from the Byzantine Empire. This conquest of Seljuk became one of the reasons for the first Crusades. It was weakened during the first two crusades. The Seljuk Empire was invaded by the Mongols around 1194 CE.</p><p>The Seljuks are regarded as the cultural descendants of the western Turks. In present-days, they were inhabitants of Azerbaijan, Turkey and Turkmenistan.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4366127c1b54" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>