<?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 Qasimzubair Link on Medium]]></title>
        <description><![CDATA[Stories by Qasimzubair Link on Medium]]></description>
        <link>https://medium.com/@qasimzubair.link?source=rss-3ef9fdd6e78f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*U8vIxRFlXXbzgxd4</url>
            <title>Stories by Qasimzubair Link on Medium</title>
            <link>https://medium.com/@qasimzubair.link?source=rss-3ef9fdd6e78f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 23:11:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@qasimzubair.link/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[From Masked Images to Medical Answers: Building Four Generative AI Models from Scratch]]></title>
            <link>https://medium.com/@qasimzubair.link/from-masked-images-to-medical-answers-building-four-generative-ai-models-from-scratch-0012bd610f6e?source=rss-3ef9fdd6e78f------2</link>
            <guid isPermaLink="false">https://medium.com/p/0012bd610f6e</guid>
            <category><![CDATA[autoencoder]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[diffusion-models]]></category>
            <dc:creator><![CDATA[Qasimzubair Link]]></dc:creator>
            <pubDate>Thu, 26 Nov 2026 15:03:00 GMT</pubDate>
            <atom:updated>2026-11-26T15:03:11.747Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w-uXSdAMFW55Jd27Nci6gA.png" /></figure><p><em>How we built a Masked Autoencoder, a Variational Autoencoder, a Diffusion Model, and a RAG system, then brought them together in one web application.</em></p><p>Most Generative AI tutorials teach one concept at a time. Autoencoders on Monday, diffusion models on Wednesday, and Retrieval-Augmented Generation (RAG) on Friday. By the weekend, everything starts to feel like a collection of models that somehow generate things.</p><p>We wanted to understand how these models actually work, so we decided to build all four in one project.</p><p>We implemented the core machinery ourselves, trained the models, evaluated their performance, and integrated everything into a single web application.</p><p>The project includes four major components:</p><ul><li>A Masked Autoencoder (MAE) trained on satellite images.</li><li>A Variational Autoencoder (VAE) trained on handwritten Urdu characters.</li><li>A class-conditional Diffusion Model that generates Urdu handwriting.</li><li>A Retrieval-Augmented Generation system that answers biomedical questions using research papers.</li></ul><p>The most important part was that we did not simply connect pretrained models. The first three models started from random initialization, and we implemented the core mathematical operations ourselves in PyTorch.</p><p>We did not use pretrained weights, Diffusers schedulers, timm, sentence-transformers, a vector database, or scikit-learn.</p><p>The noise schedule, ELBO loss, masking logic, evaluation metrics, and confusion matrix were implemented directly.</p><p>The complete notebook runs in approximately 36 minutes on a free Kaggle Tesla T4 GPU.</p><h3>The Project at a Glance</h3><p>ComponentDatasetObjectiveMAEEuroSATLearn visual representations without labelsVAEUHaTGenerate handwritten Urdu charactersDiffusionUHaTGenerate sharper Urdu handwritingRAGPubMed abstractsAnswer biomedical questions using retrieved research</p><p>Two models learn to understand images, one learns to generate them, and the fourth learns to retrieve information and answer questions.</p><h3>Part 1: Learning to See by Hiding Things</h3><h3>Masked Autoencoder</h3><p>The idea behind a Masked Autoencoder is simple: hide most of an image and train the model to reconstruct the missing parts.</p><p>We used the EuroSAT satellite image dataset, which contains satellite images representing different land-cover categories.</p><p>Each 64 × 64 image was divided into 64 patches of size 8 × 8 pixels. We kept only 16 patches visible and masked the remaining 48, meaning that 75% of the image was hidden.</p><p>A six-layer Transformer encoder processed the visible patches. A two-layer decoder then received the encoded representations along with learned mask tokens and attempted to reconstruct the missing pixels.</p><p>The reconstruction loss was calculated only on the masked patches.</p><p>The complete model contained approximately 3.17 million parameters and trained in just 3.7 minutes.</p><h3>Why Mask 75% of the Image?</h3><p>In language models such as BERT, masking 15% of the tokens is already challenging because each word carries meaningful information.</p><p>Images are different. Neighboring patches often look very similar. If we hide only a small percentage of an image, the model can simply use nearby pixels to fill the gaps.</p><p>Masking 75% of the image removes this shortcut.</p><p>The model must understand the overall structure of the scene, including where a road continues, where a river flows, and how different land-cover regions connect.</p><p>Our reconstructions were somewhat blurry, but the important structures remained visible.</p><h3>Can the Model Learn Without Labels?</h3><p>After pretraining the MAE, we froze its encoder and trained a single linear classification layer using only 160 labelled images, with 16 images per class.</p><p>The classifier achieved <strong>46.6% accuracy on 5,400 test images</strong>, compared with 10% accuracy for random guessing across ten classes.</p><p>This experiment demonstrated that the model had learned useful visual representations without needing labels during pretraining.</p><p>However, the classification results also revealed the limitations of those representations.</p><p>The model frequently confused:</p><ul><li>Annual crops with permanent crops.</li><li>Herbaceous vegetation with permanent crops.</li><li>Pasture with river.</li></ul><p>These classes share similar colors and textures at the resolution of the images.</p><p>Forest and industrial land-cover categories performed best, with accuracies of 71% and 72%, respectively. Highway performed worst, at 21%.</p><p>The MAE learned visual structure, but the limited number of labelled examples made it difficult for a linear classifier to distinguish visually similar categories.</p><p><strong>The key takeaway:</strong> Useful visual representations can be learned without labels, but learning representations is not the same as solving a classification problem.</p><h3>Part 2: A Map of Urdu Handwriting</h3><h3>Variational Autoencoder</h3><p>Our second model was a Variational Autoencoder trained on the UHaT dataset of handwritten Urdu characters.</p><p>The dataset contained 40 character classes, with 28,328 training images and 4,747 test images. Each image was a 28 × 28 grayscale image.</p><p>The VAE contained approximately 220,385 parameters and compressed each character into a latent representation consisting of just 16 numbers.</p><p>The model was trained using the negative Evidence Lower Bound (ELBO), which combines two objectives:</p><p><strong>Reconstruction loss:</strong> Encourages the model to reproduce the input character accurately.</p><p><strong>KL divergence:</strong> Encourages the latent representations to follow a standard normal distribution, making the latent space suitable for generating new samples.</p><p>Over 30 epochs, the reconstruction loss decreased from 201.5 to 104.7 nats, while the KL divergence increased from 14.9 to 25.3.</p><p>The final test negative ELBO was 130.05 nats.</p><h3>Why Does KL Divergence Matter?</h3><p>Without KL regularization, a VAE could behave like an ordinary autoencoder.</p><p>It might reconstruct the training images accurately, but its latent representations could become scattered across the latent space.</p><p>If we randomly sampled a point from a standard normal distribution, that point might fall in a region the decoder had never encountered during training.</p><p>The resulting image could contain broken strokes or meaningless shapes.</p><p>KL divergence encourages the model to organize its latent space so that random samples are more likely to produce meaningful characters.</p><p>One interesting result was latent-space interpolation.</p><p>We selected two characters, drew a straight line between their latent representations, and decoded ten points along that line.</p><p>The resulting images showed a gradual transition from one character to the other.</p><p>This made the latent space more than just a compressed representation. It became a space where we could explore and manipulate handwritten characters.</p><h3>Part 3: Noise In, Characters Out</h3><h3>Class-Conditional Diffusion Model</h3><p>After building the VAE, we implemented a Denoising Diffusion Probabilistic Model (DDPM).</p><p>Unlike the VAE, which generates an image in a single forward pass, diffusion models generate images through a sequence of denoising steps.</p><p>Our model used the same UHaT dataset.</p><h3>The Forward Process</h3><p>The forward process gradually adds Gaussian noise to an image over 1,000 timesteps.</p><p>The noise schedule started at β = 0.0001 and increased to β = 0.02.</p><p>By the final timestep, almost all information about the original image had disappeared. The noisy image was approximately a sample from a standard Gaussian distribution.</p><h3>The Reverse Process</h3><p>The reverse process learns to remove this noise.</p><p>We trained a U-Net with approximately 4.03 million parameters to predict the noise added to an image.</p><p>The model received three inputs:</p><ul><li>A noisy image.</li><li>The current timestep.</li><li>The class label of the character.</li></ul><p>The class label made the model conditional. Instead of generating an arbitrary character, we could request a specific Urdu character.</p><p>Generation started with random noise, and the model repeatedly predicted and removed noise until a handwritten character emerged.</p><h3>Training Setup</h3><p>The model was trained using:</p><ul><li>Adam optimizer with a learning rate of 0.0002.</li><li>40 training epochs.</li><li>Mixed-precision training.</li><li>Gradient clipping at 1.0.</li><li>Exponential Moving Average (EMA) of model weights with a decay of 0.999.</li></ul><p>Training took approximately 21.5 minutes, and the final training loss was 0.0227.</p><h3>VAE vs. Diffusion: Which Generates Better Images?</h3><p>Both models were trained on the same dataset, but their generated images looked noticeably different.</p><p>The VAE generated recognizable characters, but the strokes were often soft and blurry.</p><p>The diffusion model generated sharper characters with more consistent stroke thickness and clearer dots.</p><p>The difference comes from how the models generate images.</p><p>The VAE compresses the input into a 16-number latent representation and reconstructs the image in one pass. When the latent representation does not contain enough information about a fine detail, the model tends to produce an average-looking result.</p><p>Diffusion models take a different approach. They generate an image through many small denoising steps, allowing fine details to emerge gradually.</p><p>However, this improvement comes at a cost.</p><p>The VAE needs only one forward pass to generate an image, while the diffusion model requires 1,000 network calls.</p><p>On a T4 GPU, the diffusion model generated approximately 0.4 seconds per image when batched. Generating eight images on a CPU took around ten minutes.</p><p><strong>Sharper images require more computation.</strong></p><h3>A Small Detail With a Big Impact: Urdu Dots</h3><p>Urdu handwriting presents an interesting challenge because many characters share the same basic shape and differ only in the number or position of their dots.</p><p>At 28 × 28 pixels, a dot may occupy only a few pixels.</p><p>A model can generate an otherwise perfect character but place one dot incorrectly, producing a completely different letter.</p><p>This makes Urdu handwriting generation a useful example of how small visual details can carry significant semantic meaning.</p><h3>Part 4: An AI That Shows Its Sources</h3><h3>Retrieval-Augmented Generation</h3><p>Our final component was a Retrieval-Augmented Generation system designed to answer biomedical questions using research abstracts.</p><p>We used a mini version of the BioASQ dataset containing 40,181 PubMed abstracts and 707 test questions.</p><p>Each question had an average of 8.66 relevant abstracts.</p><p>The system combined a retrieval model with a language model.</p><h3>How the RAG Pipeline Works</h3><p><strong>1. Chunking</strong></p><p>Each abstract was divided into chunks of up to 150 words, with a 30-word overlap between consecutive chunks.</p><p>This produced 79,332 chunks.</p><p><strong>2. Embedding</strong></p><p>We generated embeddings using MiniLM.</p><p>Mean pooling was applied over real tokens only, followed by L2 normalization.</p><p><strong>3. Retrieval</strong></p><p>The question embedding was compared against every chunk embedding.</p><p>Because the embeddings were normalized, cosine similarity could be calculated using a simple dot product.</p><p>We did not need a vector database. Retrieval was performed using matrix multiplication followed by topk.</p><p>For each abstract, we used the similarity score of its best matching chunk.</p><p><strong>4. Generation</strong></p><p>The top five retrieved chunks were passed to Qwen2.5–1.5B-Instruct.</p><p>The model was instructed to answer using only the retrieved passages, cite the passage numbers, and respond with “I don’t know” when the answer was not available.</p><h3>Retrieval Results</h3><p>The retriever was evaluated on 707 biomedical questions.</p><p>MetricResultHit@10.622Hit@50.816Hit@100.861MRR@100.706</p><p>The correct abstract appeared in the top ten results for approximately 86% of questions.</p><p>However, Hit@10 and Recall@10 measured different things.</p><p>Hit@10 required only one relevant abstract to appear in the top ten results.</p><p>Recall@10 measured how many of the relevant abstracts were retrieved.</p><p>Since each question had an average of almost nine relevant abstracts, retrieving at least one was much easier than retrieving all of them.</p><p>This explains why Hit@10 was 0.861 while Recall@10 was 0.602.</p><h3>Generation Results</h3><p>For the first 100 test questions, the system achieved:</p><p>MetricResultROUGE-L0.259Citation precision0.686&quot;I don’t know” rate6%</p><p>These results showed that the system could retrieve relevant biomedical information and generate answers, but they also revealed important limitations.</p><h3>Where RAG Breaks</h3><p>This was one of the most useful parts of the project.</p><p>The retriever failed to retrieve any relevant abstract in the top ten results for 98 out of 707 questions, approximately 13.9%.</p><p>We identified several reasons.</p><h3>1. General-Purpose Embeddings Have Limitations</h3><p>MiniLM is a general-purpose embedding model.</p><p>Rare drug names, gene names, and abbreviations may be divided into subword tokens that do not carry enough meaning individually.</p><p>For example, when asked “What is F105-P?”, the retriever returned results about bone disorders, cancer genomics, and cholesterol probes instead of the relevant HIV-related information.</p><h3>2. Questions and Research Papers Use Different Language</h3><p>Questions are often short and generic, while research abstracts contain detailed scientific terminology.</p><p>The relevant abstract may discuss the answer without repeating the exact wording of the question.</p><p>This makes retrieval difficult.</p><h3>3. Token Truncation</h3><p>Approximately 18.3% of the 150-word chunks exceeded 256 tokens.</p><p>Because the embedding model processed only 256 tokens, the remaining text was ignored.</p><p>If the relevant information appeared near the end of a chunk, the retriever could miss it.</p><h3>4. Mean Pooling Can Dilute Important Information</h3><p>The embedding of a chunk was created by averaging its token representations.</p><p>However, a chunk may contain several sentences about methods, experiments, and results, while only one sentence contains the answer.</p><p>Averaging all of these representations can weaken the information needed for retrieval.</p><h3>What Happens When Retrieval Fails?</h3><p>When the retriever fails, the language model has two options: admit that the information is missing or generate an answer anyway.</p><p>For the question “What is F105-P?”, the model correctly responded:</p><p>“I don’t know based on the provided passages.”</p><p>However, for the question “Is capmatinib effective for glioblastoma?”, the model answered yes.</p><p>The only relevant passage it retrieved discussed capmatinib approval for lung cancer, not glioblastoma.</p><p>The reference answer was no.</p><p>The model had taken information about one cancer and applied it to another.</p><p>This was an example of hallucination despite using RAG.</p><p>The model had been instructed not to use outside knowledge, but that instruction was not enough to guarantee a correct answer.</p><h3>Citations Do Not Guarantee Correctness</h3><p>Another important finding was that only 55% of generated answers cited at least one passage.</p><p>Citation precision was 0.686, but this metric was calculated over citations that existed.</p><p>A confident answer without a citation could still be unsupported.</p><p>In another example, the model described ibalizumab as binding CD55 and blocking complement.</p><p>The reference answer stated that ibalizumab binds CD4 and blocks HIV entry.</p><p>The generated answer included a citation, but the cited passage did not support the claim.</p><p>This demonstrated an important limitation of RAG: providing sources does not guarantee that the model will interpret them correctly.</p><p>For this reason, the application displays a visible notice:</p><p><em>For educational use only. Not medical advice.</em></p><h3>The Importance of Correctness Checks</h3><p>A model that trains successfully is not necessarily a model that works correctly.</p><p>We implemented several checks to verify the behavior of our models and evaluation code.</p><h3>MAE</h3><p>We verified that exactly 48 of 64 patches were masked in every image.</p><p>We also checked that the masking process produced 256 distinct masks across 256 images.</p><p>When we deliberately corrupted predictions at visible patches, the loss remained unchanged and the gradient at those positions was exactly zero.</p><p>This confirmed that the model was being evaluated only on the patches it was supposed to reconstruct.</p><h3>VAE</h3><p>We checked that KL divergence was zero when the mean was zero and log variance was zero.</p><p>We also verified that KL divergence never became negative across 100,000 random inputs and every training batch.</p><p>Since KL divergence cannot be negative in this context, this check helped verify the correctness of our implementation.</p><h3>Diffusion Model</h3><p>At timestep 999, the noisy images had a mean of -0.0064 and a standard deviation of 0.9990.</p><p>Their correlation with the original images was only 0.0048.</p><p>This confirmed that the forward diffusion process was effectively removing the original image information.</p><h3>RAG</h3><p>We tested the retrieval evaluation code using a perfect retriever.</p><p>The perfect retriever achieved 1.000 on every metric.</p><p>We also verified that mean pooling produced identical embeddings when padding was added.</p><p>These checks helped confirm that the evaluation code was working as intended.</p><p><strong>If you cannot trust your evaluation, you cannot trust your results.</strong></p><h3>One Application to Run Them All</h3><p>After training and evaluating the four components, we integrated them into a single Gradio web application.</p><p>The application contains four tabs.</p><p><strong>MAE:</strong> Select a satellite image and view the masked input, reconstruction, original image, and predicted land-cover category.</p><p><strong>VAE:</strong> Generate 64 random Urdu characters or interpolate between two selected characters.</p><p><strong>Diffusion:</strong> Select a character and generate eight new handwritten versions.</p><p><strong>RAG:</strong> Ask a biomedical question and receive an answer along with the five retrieved passages, their abstract IDs, and the medical notice.</p><p>The application also highlights the passages that were cited in the generated answer.</p><p>To run the application:</p><pre>pip install -r app/requirements.txt<br>python app/app.py</pre><h3>What This Project Taught Us</h3><h3>1. Every Model Fails in Its Own Way</h3><p>The MAE produced blurry reconstructions.</p><p>The VAE generated soft characters.</p><p>The diffusion model generated sharper images but required significantly more computation.</p><p>The RAG system retrieved relevant information but sometimes generated unsupported answers.</p><p>Each model had its own strengths, limitations, and trade-offs.</p><h3>2. Implementing the Mathematics Makes a Difference</h3><p>Writing the ELBO, noise schedule, masking logic, and embedding operations ourselves helped us understand why these models behave the way they do.</p><p>Concepts such as reconstruction versus KL divergence and image quality versus generation speed became much easier to understand when we could see them directly in the results.</p><h3>3. Error Analysis Is More Valuable Than a Single Score</h3><p>The MAE confusion matrix showed us which land-cover classes were difficult to distinguish.</p><p>The VAE and diffusion comparisons showed how different generation methods affect image quality.</p><p>The RAG failures showed us that retrieval and generation must be evaluated separately.</p><p>Looking at incorrect predictions and unsupported answers often taught us more than looking at the final metrics.</p><h3>4. Grounding Helps, but It Is Not a Guarantee</h3><p>RAG gives a language model access to external information.</p><p>However, retrieving the correct passage does not guarantee that the model will use it correctly.</p><p>Reliable systems need both relevant retrieval and faithful answer generation.</p><h3>Final Thoughts</h3><p>This project brought together four different approaches to Generative AI: masked image reconstruction, latent-space generation, diffusion-based image synthesis, and retrieval-augmented question answering.</p><p>We implemented the core components, trained the models, evaluated their performance, analyzed their failures, and integrated everything into one application.</p><p>The complete notebook ran in approximately 36 minutes on a free GPU.</p><p>The models are small compared with modern industrial systems, but the project gave us a practical understanding of how these technologies work and where their limitations appear.</p><p>Most importantly, it showed us that building a generative model is only one part of the process.</p><p>Understanding its behavior, evaluating its results, and identifying its failure cases are equally important.</p><h3>Explore the Project</h3><p>The complete code, notebook, results, and application instructions are available on GitHub:</p><p><a href="https://github.com/Hanzala-12/gen-ai-4"><strong>GitHub Repository: gen-ai-4</strong></a></p><p>If you found this project useful, feel free to leave a clap or follow along. We would also love to see what you build using these ideas.</p><p><strong>Tags:</strong> Generative AI · Machine Learning · Deep Learning · Diffusion Models · Retrieval-Augmented Generation</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0012bd610f6e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Teaching a 135M-Parameter Model to Summarize with RLHF: SFT, Reward Modelling, PPO and DPO from…]]></title>
            <link>https://medium.com/@qasimzubair.link/teaching-a-135m-parameter-model-to-summarize-with-rlhf-sft-reward-modelling-ppo-and-dpo-from-f90144c5cbff?source=rss-3ef9fdd6e78f------2</link>
            <guid isPermaLink="false">https://medium.com/p/f90144c5cbff</guid>
            <category><![CDATA[generative-ai]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[fine-tuning]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Qasimzubair Link]]></dc:creator>
            <pubDate>Fri, 13 Nov 2026 07:26:45 GMT</pubDate>
            <atom:updated>2026-11-13T15:35:30.172Z</atom:updated>
            <content:encoded><![CDATA[<h3>Teaching a 135M-Parameter Model to Summarize with RLHF: SFT, Reward Modelling, PPO and DPO from Scratch</h3><p>How we rebuilt the “Learning to Summarize from Human Feedback” pipeline on a single free GPU, with every algorithm written in plain PyTorch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iLcIxpC3aNbXRVGtdc-lfw.png" /></figure><p>Language models are good at continuing text, but they don’t know what a good summary is. Reinforcement learning from human feedback (RLHF) closes that gap, and it is the recipe behind modern assistants. Libraries like trl hide most of it behind a trainer class, which makes it hard to see what is happening.</p><p>We wanted to see every moving part, so we built TLDR-Align. It takes a small pretrained model, SmolLM2–135M, and aligns it to human summary preferences in four stages: supervised fine-tuning, a reward model, PPO, and DPO. No RLHF libraries, no Trainer class, just PyTorch. The whole pipeline fits on a free Kaggle T4.</p><p>## The task and the pipeline</p><p>The input is a Reddit post (subreddit, title, body) followed by TL;DR:. The output is a one-sentence summary. We use the datasets released with the original paper: about 130k posts with human-written summaries, and about 260k pairs of summaries ranked by human labellers. We used fixed random subsets: 20,000 posts for SFT, 20,000 preference pairs for the reward model and DPO, and 300 held-out posts for the final comparison.</p><p>The pipeline has four stages:</p><p>- 1. SFT (the policy): learns to imitate human-written summaries.<br>- 2. Reward model (a scalar scorer): learns which of two summaries humans prefer.<br>- 3. PPO (policy + value head): learns to maximise the reward without drifting far from SFT.<br>- 4. DPO (the policy): pursues the same goal directly from the ranked pairs, with no reward model.</p><p>PPO and DPO both start from the SFT model, so any difference between them comes from how they use the preference data.</p><p>## Stage 1: Supervised fine-tuning</p><p>The SFT loss is the mean negative log-likelihood of the summary tokens only. Prompt tokens and padding contribute nothing. We trained for one epoch with AdamW (learning rate 5e-5, batch size 16), and validation loss fell from 2.41 to 2.35.</p><p>The qualitative change is large. The base model tends to loop until it hits the token limit:</p><p>&gt; Base model: “I’m not sure what to do. I’m not sure if I should keep my savings account or credit card. I’m not sure if I should keep my savings account or credit card…”<br>After SFT, the same post produces a clean one-sentence TL;DR:</p><p>&gt; After SFT: “I’m banking with BoA and want to close my checking account with them and move to a credit union or Charles Schwab.”</p><p>## Stage 2: The reward model</p><p>The reward model takes the transformer body of the SFT model, drops the language-model head, and adds a single linear layer. The reward is that layer applied to the hidden state of the last real token of the prompt plus summary. It is trained on pairs with the Bradley–Terry loss:</p><p>```<br>loss = -log sigmoid( r(x, y_w) — r(x, y_l) )<br>```</p><p>It reaches 63.8% pairwise accuracy on 1,000 held-out pairs. That is clearly above chance, and modest compared with the large models in the original paper. Looking at its mistakes shows a clear bias. When the human-preferred summary is the longer one, the model gets it right 76% of the time. When the preferred summary is the shorter one, it is right only 47% of the time.</p><p>The model prefers detail. In one validation pair, humans chose “I’m 16 and I want to run a full 8-hour relay with my friends. I’m not sure how to do it.” over a longer, more informative alternative that the reward model scored much higher (7.8 vs 4.7). That bias matters for everything that follows.</p><p>## Stage 3: PPO</p><p>PPO treats each generated token as an action. For every token, the reward is a KL penalty against the frozen SFT reference, plus the reward-model score on the final token:</p><p>```<br>r_t = -beta * (log pi(a_t|s_t) — log pi_ref(a_t|s_t)) + [t = T] * r_phi(x, y)<br>```</p><p>The KL term keeps the policy near the SFT model, so it can’t drift into text that exploits the reward model. We used Monte-Carlo returns with a discount of 1 and normalised advantages. Each rollout of 16 prompts is reused for four full-batch epochs with a clipped objective (clip 0.2), a value loss and an entropy bonus. Training ran for 200 iterations, which is 3,200 distinct prompts.</p><p>Three kinds of checks gave us confidence that the implementation was correct:</p><p>- the KL to the reference is exactly 0 at the first iteration, because the policy still equals SFT;<br>- in the first epoch of every iteration, the probability ratio is 1 for every token and the clip fraction is 0;<br>- the reference model and reward model both have gradients disabled.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9g10PPoOmvcRZjWS1_CoLA.png" /></figure><p>The mean sampled reward rose from about 5.9 in the first iteration to about 7.6 over the last ten. The KL to the reference grew to roughly 20, and the clip fraction stayed low, typically 1–4%. That means each policy update stayed small.</p><p>## Stage 4: DPO</p><p>DPO removes the reward model and the RL loop altogether. The loss uses only the log-probability ratios of the chosen and rejected summaries under the policy and the frozen reference:</p><p>```<br>loss = -log sigmoid( beta * [ log(pi(y_w|x)/pi_ref(y_w|x)) — log(pi(y_l|x)/pi_ref(y_l|x)) ] )<br>beta = 0.1<br>```</p><p>The reward is implicit in these ratios. The intractable partition function cancels when two summaries of the same post are compared, so it never needs to be computed. A useful sanity check: at the first step the policy equals the reference, so the loss must equal log 2, about 0.6931, and ours did. DPO’s implicit-reward accuracy on the same 1,000 validation pairs was 61.2%, close to the explicit reward model’s 63.8%, without ever training one.</p><p>## Results on 300 unseen posts</p><p>```<br>Policy Mean reward Win vs SFT KL to SFT Length ROUGE-L<br>SFT 6.71–0 30.4 0.257<br>PPO 7.77 0.81 14.05 33.1 0.257<br>DPO 7.13 0.74 4.09 39.5 0.243<br>```</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OSh7BC9EGeEogI_5DuA_QA.png" /></figure><p>Both methods improve on SFT by the reward model’s measure. PPO scores higher and wins on 81% of posts, at the cost of a larger drift from SFT. DPO drifts much less, with a KL of 4.1 against 14.0 for PPO. But DPO’s summaries are about nine tokens longer than SFT’s and its ROUGE-L is lower, which is consistent with the length preference we saw in the reward model’s errors. PPO kept its length and ROUGE-L close to SFT’s.</p><p>An important caveat: the reward model is the very thing PPO optimises, so a higher reward is not independent evidence of better summaries. Human judgement is the real check, and it is why we compared the methods blind on a sample of posts.</p><p>## Costs</p><p>- SFT: 40 minutes on a T4<br>- Reward model: 83 minutes<br>- PPO (200 iterations): 25 minutes<br>- DPO: 99 minutes</p><p>PPO needs four models in memory at once: the policy, a value head, the frozen reference and the frozen reward model. DPO needs only two, a policy and a reference, and has no sampling loop. For a new project with preference data already available, that simplicity makes DPO an attractive default, though PPO’s reward signal can be reused and inspected in ways DPO’s cannot.</p><p>## What we learned</p><p>Silent bugs are the expensive ones. Early versions of our pipeline had several that never crashed. Scoring summaries with the reward model in a different token format than it was trained on (no leading space, no end-of-sequence token) would have distorted every reported number. Using a different token format in DPO than in SFT would have quietly trained on the wrong distribution. Reusing exactly the same token ids across stages removed this whole class of problems.</p><p>Padding and EOS can be the same token. In this tokenizer the padding token is the end-of-sequence token. Finding the last real token by comparing ids with the padding id would therefore be wrong. Every mask comes from the attention mask or known lengths instead.</p><p>Build invariants into the code. The checks “KL is 0 at iteration one”, “ratio is 1 in epoch one” and “DPO loss is log 2” caught more mistakes than any amount of staring at loss curves.</p><p>Rewards teach what they measure. The reward model’s preference for length shaped what both PPO and DPO optimised. A better reward model, or an explicit length control, is the most obvious next improvement.</p><p>## Limitations</p><p>A 135M-parameter model trained on 20,000 pairs is far smaller than the models in the original paper, so the reward model and the summaries are correspondingly modest. We ran a single seed per method and evaluated on 300 posts, so small differences between methods should be read as indicative rather than conclusive.</p><p>## Code and checkpoints</p><p>- GitHub: github.com/qasimzubair (<a href="https://github.com/qasimzubair">https://github.com/qasimzubair</a>) (<a href="https://github.com/qasimzubair/HumanPref-Summarizer">https://github.com/qasimzubair/HumanPref-Summarizer</a>)<br>- Checkpoints and results: huggingface.co/qasimzubair/tldr-align (<a href="https://huggingface.co/qasimzubair/tldr-align">https://huggingface.co/qasimzubair/tldr-align</a>)</p><p>If you work on alignment, or are building your first RLHF pipeline, I’d be glad to compare notes. You can find me on LinkedIn (<a href="https://www.linkedin.com/in/qasimzubair/">https://www.linkedin.com/in/qasimzubair/</a>).</p><p>Reference: Stiennon et al., “Learning to Summarize from Human Feedback”, NeurIPS 2020 (arXiv:2009.01325).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f90144c5cbff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Built a Text-to-SQL Transformer From Scratch in PyTorch]]></title>
            <link>https://medium.com/@qasimzubair.link/how-i-built-a-text-to-sql-transformer-from-scratch-in-pytorch-ce99f51f20ec?source=rss-3ef9fdd6e78f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce99f51f20ec</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Qasimzubair Link]]></dc:creator>
            <pubDate>Mon, 05 Oct 2026 04:01:43 GMT</pubDate>
            <atom:updated>2026-10-05T04:02:23.960Z</atom:updated>
            <content:encoded><![CDATA[<p><em>I implemented a Transformer from scratch, trained it on WikiSQL, and turned natural-language questions into SQL with a FastAPI + React application.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y6LfXEb7vjoEj_nARH6I5w.png" /></figure><p>What if you could ask a database a question in plain English and get a SQL query back?</p><p>For example:</p><blockquote><strong><em>Question:</em></strong><em> What school/club team is Amir Johnson on?</em></blockquote><p>The model generates:</p><pre>SELECT School/Club Team<br>FROM table<br>WHERE Player = &#39;Amir Johnson&#39;;</pre><p>That is the idea behind <strong>Text-to-SQL</strong>: translating natural-language questions into executable SQL queries.</p><p>For this project, I wanted to go beyond simply fine-tuning an existing language model.</p><p>I wanted to understand what actually happens inside a Transformer.</p><p>So I built one <strong>from scratch in PyTorch</strong>.</p><p>The result is a complete Text-to-SQL pipeline:</p><pre>Natural Language Question<br>          ↓<br>     BPE Tokenization<br>          ↓<br> Transformer Encoder<br>          ↓<br> Transformer Decoder<br>          ↓<br>       SQL Query<br>          ↓<br>       FastAPI<br>          ↓<br>    React Interface</pre><p>This article walks through how I built it, what I learned, and where the model still struggles.</p><h3>Why Build a Transformer From Scratch?</h3><p>Today, you can build an NLP application with a pretrained Transformer in just a few lines of code.</p><p>That is useful — but it can also hide a lot of the underlying mechanics.</p><p>I wanted to understand:</p><ul><li>How self-attention actually works</li><li>How multi-head attention is implemented</li><li>How encoder-decoder Transformers communicate</li><li>How causal masking prevents the decoder from seeing future tokens</li><li>How positional information is represented</li><li>How tokenization affects generation</li><li>How a Transformer learns to generate SQL</li><li>How inference strategies such as greedy decoding and beam search work</li></ul><p>So instead of using:</p><pre>nn.Transformer()</pre><p>or:</p><pre>nn.MultiheadAttention()</pre><p>I implemented the main Transformer components myself using lower-level PyTorch building blocks.</p><p>The project is based on the architecture introduced in the original <strong>“Attention Is All You Need”</strong> paper.</p><h3>The Goal</h3><p>I defined three main goals for the project:</p><h3>1. Build a Transformer from scratch</h3><p>Implement the encoder, decoder, attention mechanisms, masking, positional encoding, and training pipeline.</p><h3>2. Train it for Text-to-SQL</h3><p>Use the WikiSQL dataset to teach the model to translate questions into SQL queries.</p><h3>3. Turn it into a usable application</h3><p>Expose the trained model through a FastAPI backend and create a React frontend for interacting with it.</p><p>The goal wasn’t just to train a model.</p><p>It was to build the entire pipeline.</p><h3>The Architecture</h3><p>The overall system looks like this:</p><pre>┌──────────────────┐<br>                │ User Question    │<br>                │                  │<br>                │ &quot;Who is Amir?&quot;   │<br>                └────────┬─────────┘<br>                         │<br>                         ▼<br>                ┌──────────────────┐<br>                │ BPE Tokenizer    │<br>                └────────┬─────────┘<br>                         │<br>                         ▼<br>              ┌──────────────────────┐<br>              │ Transformer Encoder  │<br>              │                      │<br>              │ Self-Attention       │<br>              │ Feed Forward         │<br>              │ × 3 Layers           │<br>              └──────────┬───────────┘<br>                         │<br>                         ▼<br>              ┌──────────────────────┐<br>              │ Transformer Decoder  │<br>              │                      │<br>              │ Masked Attention     │<br>              │ Cross Attention      │<br>              │ Feed Forward         │<br>              │ × 3 Layers           │<br>              └──────────┬───────────┘<br>                         │<br>                         ▼<br>                ┌──────────────────┐<br>                │ Generated SQL    │<br>                └──────────────────┘</pre><p>The model contains approximately <strong>7.58 million parameters</strong>.</p><p>Its main configuration is:</p><p>ComponentConfigurationEmbedding dimension256Attention heads4Encoder layers3Decoder layers3Feed-forward dimension1024Dropout0.1BPE vocabulary8,000Parameters~7.58M</p><p>This is intentionally much smaller than modern large language models.</p><p>The objective was understanding the architecture — not maximizing parameter count.</p><h3>Step 1: Preparing the Dataset</h3><p>I used <strong>WikiSQL</strong>, a dataset designed for natural-language questions over relational tables.</p><p>Each example contains:</p><ul><li>A natural-language question</li><li>A table</li><li>Column names</li><li>A corresponding SQL query</li></ul><p>For example, the model might receive something like:</p><pre>Question:<br>What school/club team is Amir Johnson on?</pre><pre>Table:<br>Player | No. | Nationality | Position | Years | School/Club Team</pre><pre>SQL:<br>SELECT School/Club Team<br>FROM table<br>WHERE Player = &#39;Amir Johnson&#39;;</pre><p>The dataset contains <strong>56,355 training examples</strong> in the version used for this project.</p><p>But there is an important challenge.</p><p>The model isn’t just learning English.</p><p>It needs to learn the relationship between:</p><pre>Question + Table Schema</pre><p>and:</p><pre>SQL Structure</pre><p>That makes schema representation especially important.</p><h3>Step 2: Tokenization With BPE</h3><p>Before the Transformer can process text, everything needs to become tokens.</p><p>I used <strong>Byte Pair Encoding (BPE)</strong> with an 8,000-token vocabulary.</p><p>Instead of treating every word as a completely independent token, BPE can break words into smaller pieces.</p><p>For example:</p><pre>playing</pre><p>could potentially become:</p><pre>play + ing</pre><p>This gives the tokenizer a way to handle words it hasn’t seen exactly during training.</p><p>The same vocabulary is used for both the question and SQL output.</p><h3>Step 3: Representing Table Columns</h3><p>One of the more important details in the project is how table schemas are represented.</p><p>Consider:</p><pre>Player<br>No.<br>Nationality<br>Position<br>Years<br>School/Club Team</pre><p>I added column-position tokens:</p><pre>&lt;c0&gt; Player<br>&lt;c1&gt; No.<br>&lt;c2&gt; Nationality<br>&lt;c3&gt; Position<br>&lt;c4&gt; Years<br>&lt;c5&gt; School/Club Team</pre><p>This gives the model explicit information about where each column appears in the schema.</p><p>That matters because the generated SQL needs to reference the correct column.</p><p>For example:</p><pre>SELECT School/Club Team</pre><p>requires the model to understand that <strong>School/Club Team</strong> corresponds to one of the input table columns.</p><h3>Step 4: Implementing Self-Attention</h3><p>The core of the Transformer is attention.</p><p>The fundamental equation is:</p><pre>Attention(Q, K, V)<br>=<br>softmax(QKᵀ / √dₖ)V</pre><p>where:</p><ul><li>Q = Queries</li><li>K = Keys</li><li>V = Values</li><li>dₖ = key dimension</li></ul><p>The basic implementation computes:</p><pre>scores = Q @ K.transpose(-2, -1)<br>scores = scores / math.sqrt(d_k)</pre><pre>attention = torch.softmax(scores, dim=-1)</pre><pre>output = attention @ V</pre><p>This allows each token to determine which other tokens are important.</p><p>For example, when generating:</p><pre>School/Club Team</pre><p>the model needs to connect that output to the relevant part of the question and schema.</p><h3>Step 5: Multi-Head Attention</h3><p>Instead of performing attention once, the Transformer performs it across multiple heads.</p><p>My implementation uses:</p><pre>4 attention heads</pre><p>The idea is that different heads can learn different relationships.</p><p>Conceptually:</p><pre>Input<br>  │<br>  ├── Head 1<br>  ├── Head 2<br>  ├── Head 3<br>  └── Head 4<br>        │<br>        ▼<br>   Concatenate<br>        │<br>        ▼<br>   Linear Layer<br>        │<br>        ▼<br>      Output</pre><p>Each head operates on a smaller portion of the embedding dimension.</p><p>The outputs are then concatenated and projected back into the model dimension.</p><h3>Step 6: Positional Information</h3><p>Attention by itself doesn’t inherently know token order.</p><p>For language, order matters.</p><p>These are not equivalent:</p><pre>SELECT Player WHERE Team = &#39;A&#39;</pre><p>and:</p><pre>WHERE Team = &#39;A&#39; SELECT Player</pre><p>So the model needs positional information.</p><p>I implemented positional encoding so that token representations contain information about their position in the sequence.</p><p>This lets the Transformer distinguish:</p><pre>token 1<br>token 2<br>token 3</pre><p>from:</p><pre>token 3<br>token 2<br>token 1</pre><h3>Step 7: Building the Encoder</h3><p>The encoder contains three layers.</p><p>Each encoder layer follows the standard structure:</p><pre>Input<br>  ↓<br>Multi-Head Self-Attention<br>  ↓<br>Residual Connection<br>  ↓<br>Layer Normalization<br>  ↓<br>Feed-Forward Network<br>  ↓<br>Residual Connection<br>  ↓<br>Layer Normalization</pre><p>I stacked this block three times.</p><p>The encoder’s job is to build contextual representations of the input question and schema.</p><h3>Step 8: Building the Decoder</h3><p>The decoder is where SQL generation happens.</p><p>Each decoder layer contains:</p><pre>Masked Self-Attention<br>        ↓<br>Cross-Attention<br>        ↓<br>Feed-Forward Network</pre><p>There are three decoder layers.</p><p>The important difference is that the decoder needs to generate the SQL <strong>one token at a time</strong>.</p><p>For example:</p><pre>SELECT</pre><p>then:</p><pre>SELECT School/Club</pre><p>then:</p><pre>SELECT School/Club Team</pre><p>and eventually:</p><pre>SELECT School/Club Team<br>FROM table<br>WHERE Player = &#39;Amir Johnson&#39;;</pre><h3>The Problem of Future Tokens</h3><p>While generating a sequence, the decoder must not see future tokens.</p><p>If the target is:</p><pre>SELECT Player FROM table</pre><p>when predicting:</p><pre>FROM</pre><p>the model shouldn’t be able to look ahead and see:</p><pre>table</pre><p>This is solved with a <strong>causal mask</strong>.</p><p>Conceptually:</p><pre>SELECT FROM table WHERE<br>SELECT    ✓     ✗     ✗    ✗<br>FROM      ✓     ✓     ✗    ✗<br>table     ✓     ✓     ✓    ✗<br>WHERE     ✓     ✓     ✓    ✓</pre><p>Only previous tokens are visible.</p><p>I also wrote tests specifically to verify that changing a future decoder token does not affect earlier outputs.</p><p>This was one of the most useful tests in the project because masking bugs can otherwise be surprisingly difficult to detect.</p><h3>Cross-Attention</h3><p>The decoder also needs information from the encoder.</p><p>That’s where cross-attention comes in.</p><p>The decoder asks:</p><blockquote><em>“Given the SQL I’ve generated so far, which parts of the question and schema should I pay attention to?”</em></blockquote><p>Conceptually:</p><pre>Question + Schema<br>       │<br>       ▼<br> Transformer Encoder<br>       │<br>       │<br>       ▼<br>Encoder Representations<br>       │<br>       │<br>       ├──────────────┐<br>       │              │<br>       ▼              ▼<br>Decoder Self      Cross Attention<br>Attention              ▲<br>       │               │<br>       └───────┬───────┘<br>               ▼<br>          SQL Token</pre><p>This is what connects the input meaning to the output generation process.</p><h3>Weight Sharing</h3><p>Another implementation detail I explored was weight sharing between the token embedding and output projection.</p><p>Instead of learning completely separate parameters for both, the model can reuse the same representation.</p><p>This reduces the number of parameters and can provide a useful relationship between input and output token representations.</p><p>I also tested the weight-sharing behavior separately to make sure it was actually implemented as intended.</p><h3>Training the Model</h3><p>I trained the model for:</p><pre>25 epochs</pre><p>using an NVIDIA Tesla T4.</p><p>The training setup included:</p><ul><li>Adam optimizer</li><li>Label smoothing</li><li>Dropout</li><li>Linear learning-rate warmup</li><li>Inverse-square-root learning-rate decay</li></ul><p>The best checkpoint was obtained around <strong>epoch 24</strong>.</p><p>The best reported development loss was:</p><pre>1.4442</pre><p>Total training time was approximately:</p><pre>27.2 minutes</pre><p>For a relatively small Transformer, this made experimentation fairly practical.</p><h3>Learning-Rate Scheduling</h3><p>One thing I didn’t want to ignore was learning-rate scheduling.</p><p>Transformers can be sensitive to how the learning rate changes during training.</p><p>I used a warmup phase followed by inverse-square-root decay.</p><p>Conceptually:</p><pre>Learning Rate<br>     │<br>     │       /\<br>     │      /  \<br>     │     /    \<br>     │    /      \<br>     │___/        \________<br>     └──────────────────────<br>              Steps</pre><p>The warmup allows the model to gradually reach a useful learning rate instead of immediately starting at the maximum value.</p><h3>Evaluation</h3><p>I evaluated different components of the generated SQL rather than relying on a single number.</p><p>The reported results were:</p><p>MetricResultSelected Column<strong>92.92%</strong>Aggregation<strong>87.91%</strong>WHERE Clause<strong>43.70%</strong>Parse Failures<strong>1.14%</strong></p><p>The most interesting result is the gap between column selection and WHERE-clause generation.</p><p>The model is relatively good at identifying:</p><pre>SELECT School/Club Team</pre><p>but has a harder time generating the correct filtering conditions:</p><pre>WHERE Player = &#39;Amir Johnson&#39;</pre><p>That tells me where future improvements should focus.</p><h3>An important caveat</h3><p>These numbers are <strong>component-level/parser-based metrics from this project</strong>.</p><p>They should not be interpreted as official WikiSQL execution accuracy.</p><p>A stronger evaluation would use the official WikiSQL evaluation pipeline and measure whether the generated SQL actually produces the correct answer.</p><h3>Greedy Decoding vs Beam Search</h3><p>Generating SQL isn’t only about the model.</p><p>The decoding strategy also matters.</p><p>I compared greedy decoding with beam search.</p><h3>Greedy decoding</h3><p>At every step, choose the token with the highest probability.</p><p>It’s simple and fast.</p><p>Approximate inference time:</p><pre>0.055 seconds / example</pre><h3>Beam search</h3><p>Instead of keeping only one candidate, maintain several possible sequences.</p><p>I tested beam search with:</p><pre>Beam width = 4</pre><p>Approximate inference time:</p><pre>0.213 seconds / example</pre><p>So beam search was roughly <strong>4× slower</strong> in this setup.</p><p>This was a useful reminder that better search can come with a significant latency cost.</p><h3>Testing the Transformer</h3><p>I didn’t want to rely only on training loss.</p><p>I also created tests for important architectural components.</p><h3>Causal masking</h3><p>Verify that future decoder tokens cannot influence earlier predictions.</p><h3>Padding masking</h3><p>Verify that padding tokens aren’t treated as meaningful input.</p><h3>Weight sharing</h3><p>Verify that shared embedding/output parameters are actually shared.</p><h3>Learning-rate schedule</h3><p>Verify that warmup and decay behave as expected.</p><p>These tests are especially valuable when implementing a Transformer manually.</p><p>A model can train without crashing while still containing subtle architectural bugs.</p><h3>Turning the Model Into an Application</h3><p>Once the model was working, I didn’t want it to exist only inside a notebook.</p><p>I built a small application around it.</p><p>The architecture is:</p><pre>React Frontend<br>      │<br>      ▼<br> FastAPI Backend<br>      │<br>      ▼<br> Transformer Model<br>      │<br>      ▼<br> Generated SQL</pre><p>The user enters a natural-language question.</p><p>The backend tokenizes it, runs the model, decodes the generated sequence, and returns the SQL query.</p><p>The React frontend then displays the result.</p><p>This turned the project from:</p><blockquote><em>“I trained a Transformer.”</em></blockquote><p>into:</p><blockquote><em>“I built and deployed an end-to-end Text-to-SQL system.”</em></blockquote><p>That distinction matters when building a portfolio project.</p><h3>Project Structure</h3><p>The repository is organized roughly like this:</p><pre>text-to-sql-transformer/<br>│<br>├── Text_to_SQL_Transformer.ipynb<br>│<br>├── backend/<br>│<br>├── frontend/<br>│<br>├── checkpoints/<br>│<br>├── results/<br>│<br>├── sql_sp.model<br>├── sql_sp.vocab<br>│<br>└── README.md</pre><p>The notebook contains the main experimentation and model development.</p><p>The backend handles inference through FastAPI.</p><p>The frontend provides the user interface.</p><p>The checkpoints contain trained model weights.</p><h3>What I Learned</h3><p>The biggest lesson from this project wasn’t simply how to implement attention.</p><p>It was understanding how the pieces fit together.</p><p>Before building this, a Transformer could feel like a black box:</p><pre>Input → Transformer → Output</pre><p>After implementing one myself, the picture became much clearer:</p><pre>Tokens<br>  ↓<br>Embeddings<br>  ↓<br>Positional Information<br>  ↓<br>Self-Attention<br>  ↓<br>Feed-Forward Networks<br>  ↓<br>Encoder Representations<br>  ↓<br>Masked Decoder Attention<br>  ↓<br>Cross-Attention<br>  ↓<br>Output Projection<br>  ↓<br>Next Token</pre><p>Every part has a purpose.</p><h3>The Hardest Part Wasn’t Attention</h3><p>Ironically, the hardest part wasn’t writing the attention equation.</p><p>The more difficult problems were around the edges:</p><ul><li>Designing the input representation</li><li>Handling table schemas</li><li>Getting masking correct</li><li>Preparing targets for teacher forcing</li><li>Debugging tensor shapes</li><li>Designing evaluation metrics</li><li>Making inference reliable</li><li>Connecting the trained model to an API</li><li>Turning the whole thing into a usable application</li></ul><p>This is something I’ve learned repeatedly while working on ML systems:</p><blockquote><strong><em>The model is only one part of the system.</em></strong></blockquote><p>Data preparation, representation, evaluation, inference, and deployment matter just as much.</p><h3>Where the Model Still Struggles</h3><p>The project is a learning-focused implementation, so there are several limitations.</p><h3>1. Limited SQL complexity</h3><p>WikiSQL covers a relatively constrained subset of SQL.</p><p>Real-world databases can require:</p><ul><li>Complex joins</li><li>Nested queries</li><li>Subqueries</li><li>Multiple tables</li><li>Advanced aggregations</li><li>Complex filtering</li><li>Database-specific SQL syntax</li></ul><p>This model isn’t designed for all of those cases.</p><h3>2. WHERE clause generation</h3><p>The biggest weakness in my current results is WHERE-clause prediction.</p><p>That is an obvious area for improvement.</p><h3>3. Evaluation</h3><p>The current evaluation is component-based.</p><p>A production-quality version should include official execution-based evaluation.</p><h3>4. Model size</h3><p>At around 7.58M parameters, the model is intentionally small.</p><p>That’s useful for experimentation, but larger models could potentially capture more complex relationships.</p><h3>What I Would Build Next</h3><p>There are several directions I want to explore next.</p><h3>Official WikiSQL evaluation</h3><p>Measure exact logical-form and execution performance using the official evaluation setup.</p><h3>Spider</h3><p>Move beyond WikiSQL and test the system on a more challenging Text-to-SQL benchmark.</p><h3>Better schema awareness</h3><p>Instead of simply adding column-position tokens, build stronger representations of:</p><pre>Question<br>+<br>Table<br>+<br>Columns<br>+<br>Column relationships</pre><h3>SQL validation</h3><p>Add a validation layer that checks whether generated SQL is structurally valid before returning it.</p><h3>SQL repair</h3><p>If a generated query is invalid, use a second stage to identify and correct the error.</p><h3>Database execution</h3><p>The next major step would be:</p><pre>User Question<br>      ↓<br>Generate SQL<br>      ↓<br>Validate SQL<br>      ↓<br>Execute Against Database<br>      ↓<br>Return Answer</pre><p>At that point, the system becomes much closer to an actual <strong>AI database assistant</strong>.</p><h3>Final Takeaway</h3><p>Building a Transformer from scratch was a very different experience from simply using one.</p><p>It forced me to understand the architecture at a much deeper level:</p><pre>Dataset<br>   ↓<br>Tokenization<br>   ↓<br>Transformer<br>   ↓<br>Training<br>   ↓<br>Evaluation<br>   ↓<br>Inference<br>   ↓<br>FastAPI<br>   ↓<br>React</pre><p>The project started with a simple question:</p><blockquote><strong><em>Can I build a model that turns English into SQL?</em></strong></blockquote><p>But the more interesting question became:</p><blockquote><strong><em>Can I understand and build every major part of the system myself?</em></strong></blockquote><p>That was the real goal.</p><p>And that’s what made this project valuable.</p><p>Not because a small Transformer can compete with today’s large language models.</p><p>But because implementing the system from the ground up made the architecture, training process, failure modes, and deployment pipeline much less of a black box.</p><h3>Final Thoughts</h3><p>If you’re learning Transformers, I highly recommend building one yourself at least once.</p><p>You don’t need billions of parameters.</p><p>You don’t need a massive GPU cluster.</p><p>A relatively small model is enough to learn the fundamentals:</p><ul><li>Tokenization</li><li>Embeddings</li><li>Positional encoding</li><li>Self-attention</li><li>Multi-head attention</li><li>Causal masking</li><li>Cross-attention</li><li>Encoder-decoder architectures</li><li>Training</li><li>Decoding</li><li>Evaluation</li><li>Deployment</li></ul><p>Once you understand those pieces, using larger pretrained models becomes much easier because you understand what’s happening underneath the abstractions.</p><p>And that’s exactly what I wanted from this project.</p><p><strong>I didn’t just want to use a Transformer.</strong></p><p><strong>I wanted to build one.</strong></p><h3>Tech Stack</h3><pre>Python<br>PyTorch<br>BPE / SentencePiece<br>WikiSQL<br>FastAPI<br>React<br>NumPy<br>CUDA</pre><h3>Repository</h3><p>The complete project, including the model implementation, training notebook, backend, frontend, checkpoints, and results, is available on GitHub.</p><p><strong>GitHub:</strong> github.com/qasimzubair/text-to-sql-transformer</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce99f51f20ec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Can an RNN Learn to Ask Questions in Urdu?]]></title>
            <link>https://medium.com/@qasimzubair.link/can-an-rnn-learn-to-ask-questions-in-urdu-8e520593c603?source=rss-3ef9fdd6e78f------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e520593c603</guid>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[attention-mechanism]]></category>
            <category><![CDATA[urdu-language]]></category>
            <category><![CDATA[tokenization]]></category>
            <category><![CDATA[llm-applications]]></category>
            <dc:creator><![CDATA[Qasimzubair Link]]></dc:creator>
            <pubDate>Sat, 12 Sep 2026 14:17:08 GMT</pubDate>
            <atom:updated>2026-09-12T14:21:32.809Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JC1FXowiilEWgnwNkVc91Q.png" /></figure><h3>Building an Urdu Question Generation System from Scratch with BiLSTM and Attention</h3><p>Question generation sounds simple: give a model a sentence and an answer, and ask it to generate the question that the answer belongs to.</p><p>For example:</p><blockquote><strong><em>Input:</em></strong><em> دریائے سندھ تقریباً </em><em>&lt;ans&gt;3180 کلومیٹر&lt;/ans&gt; طویل ہے۔</em></blockquote><blockquote><strong><em>Question:</em></strong><em> دریائے سندھ کی لمبائی کتنی ہے؟</em></blockquote><p>But generating a good question requires more than producing grammatically correct Urdu. The model needs to identify the important information, understand what type of question is appropriate, and keep the generated question grounded in the source sentence.</p><p>For this project, we built an Urdu Question Generation system <strong>completely from scratch</strong>. No pretrained Transformer, no pretrained embeddings, and no off-the-shelf sequence-to-sequence model. Instead, we used a BiLSTM encoder, Bahdanau attention, an LSTM decoder, and an 8,000-token SentencePiece vocabulary.</p><p>The goal was not simply to achieve the highest score. It was to understand what a traditional sequence-to-sequence model can actually learn when applied to Urdu.</p><h3>The Problem</h3><p>The task is an answer-aware question generation problem.</p><p>The model receives a sentence with the answer explicitly marked:</p><pre>سورج نظام شمسی کا مرکز ہے۔</pre><p>with the answer:</p><pre>سورج</pre><p>and should generate:</p><pre>شمسی نظام کا مرکز کیا ہے؟</pre><p>This can be represented as:</p><pre>Sentence + Answer Span<br>          ↓<br>       Encoder<br>          ↓<br>      Attention<br>          ↓<br>       Decoder<br>          ↓<br>     Question</pre><p>The dataset used was <strong>UQA</strong>, an Urdu question-answering corpus based on SQuAD 2.0. The original training split contains 124,745 rows and the validation split 16,824 rows. After removing unanswerable examples and applying the length filter, the dataset contained approximately 75k training pairs and 10k validation pairs in the modular experiment.</p><h3>Why Use Only the Sentence Containing the Answer?</h3><p>A UQA context can contain multiple sentences. Feeding the entire paragraph to a relatively small RNN would make the task unnecessarily difficult.</p><p>Instead, we used the answer’s character offset to locate the sentence containing the answer.</p><p>The preprocessing pipeline was:</p><pre>UQA context<br>    ↓<br>Split into sentences<br>    ↓<br>Locate answer span<br>    ↓<br>Keep its sentence<br>    ↓<br>Mark answer with &lt;ans&gt; ... &lt;/ans&gt;<br>    ↓<br>Source → Target pair</pre><p>For example:</p><pre>دریائے سندھ تقریباً &lt;ans&gt;3180 کلومیٹر&lt;/ans&gt; طویل ہے۔</pre><p>The &lt;ans&gt; markers explicitly tell the model what information the generated question should target.</p><p>Examples longer than 60 source tokens or 25 target tokens were removed. This produced a more manageable sentence-level question generation task.</p><h3>Tokenization: Why Subwords Matter for Urdu</h3><p>Instead of using a simple word-level vocabulary, we trained an <strong>8,000-token SentencePiece unigram tokenizer</strong> on the training data.</p><p>This was especially useful for Urdu because many words can be morphologically complex and rare names may not appear frequently enough to deserve their own vocabulary entry.</p><p>Common words could remain intact while rarer forms were split into smaller pieces.</p><p>However, this also exposed a weakness.</p><p>Rare proper nouns could be fragmented heavily. For example, the repository notes that names such as ڈسٹ نی could be represented as small subword pieces.</p><p>That becomes important when we examine the model’s failures.</p><h3>Model Design</h3><p>The architecture was deliberately kept traditional:</p><ul><li><strong>Encoder:</strong> 2-layer bidirectional LSTM</li><li><strong>Embedding:</strong> 256 dimensions</li><li><strong>Hidden size:</strong> 512</li><li><strong>Dropout:</strong> 0.3</li><li><strong>Attention:</strong> Bahdanau additive attention</li><li><strong>Decoder:</strong> 2-layer LSTM</li><li><strong>Vocabulary:</strong> 8,000 SentencePiece tokens</li><li><strong>Parameters:</strong> approximately 35.5 million</li></ul><p>The decoder used input feeding, meaning the attention context from the previous step was also incorporated into the next decoding step. Training used teacher forcing, masked cross-entropy loss, Adam optimization, gradient clipping, and learning-rate scheduling.</p><h3>Figure 1 — Model pipeline</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*mlCAIqJL8i3gD0o501yNoA.png" /></figure><p>The model was trained for 15 epochs on a Tesla T4. In the documented modular run, validation loss reached its minimum around epoch 10, after which the model began to overfit.</p><h3>Results</h3><p>The modular experiment compared greedy decoding with beam search using a beam width of 5.</p><p>DatasetDecodingBLEU-4ROUGE-LPPLUQA validationGreedy<strong>5.580.260</strong>34.2UQA validationBeam-51.020.12634.2Wiki-UQAGreedy<strong>3.570.227</strong>50.8Wiki-UQABeam-50.320.07650.8</p><p>The interesting result is that <strong>greedy decoding performed substantially better than beam search in this experiment</strong>. Beam search is often expected to improve sequence generation, but with a relatively weak model it can amplify high-probability generic patterns instead of improving grounding.</p><p>The model also had 0% &lt;unk&gt; output in this run, largely because the tokenizer used full character coverage.</p><h3>What Does the Model Actually Get Right?</h3><p>The strongest behavior was not perfect semantic generation. It was learning the <strong>shape of a question</strong>.</p><p>For dates, the model often learned to use words such as:</p><pre>کب<br>کس سال</pre><p>For quantities:</p><pre>کتنے<br>کتنی</pre><p>For locations:</p><pre>کہاں</pre><p>This suggests that the answer span provides a useful signal.</p><p>However, getting the question word right does not necessarily mean that the complete question is correct.</p><p>The ten examples below make that distinction clear.</p><h3>Five Good Outputs</h3><h3>1. Correct question type and content</h3><p><strong>Source:</strong> سورج نظام شمسی کا مرکز ہے۔<br><strong>Answer:</strong> سورج</p><p><strong>Generated:</strong></p><blockquote><em>شمسی نظام کا مرکز کیا ہے؟</em></blockquote><p>This is a strong output. It is fluent, relevant, and answerable.</p><h3>2. Correct semantic relation</h3><p><strong>Source:</strong> مہاتما گاندھی نے عدم تشدد کا فلسفہ پیش کیا۔<br><strong>Answer:</strong> عدم تشدد</p><p><strong>Generated:</strong></p><blockquote><em>مہاتما گاندھی نے کیا فلسفہ پیش کیا؟</em></blockquote><p>The model correctly identifies that the marked phrase should be the answer to a <strong>کیا</strong> question.</p><h3>3. Correct location question</h3><p><strong>Source:</strong> ماؤنٹ ایورسٹ … جو نیپال میں واقع ہے۔<br><strong>Answer:</strong> نیپال</p><p><strong>Generated:</strong></p><blockquote><em>ماؤنٹ ایورسٹ کہاں واقع ہے؟</em></blockquote><p>This is one of the clearest examples of successful answer-aware generation.</p><h3>4. Mostly correct, with a small semantic issue</h3><p><strong>Source:</strong> چاند زمین کے گرد چکر لگاتا ہے۔<br><strong>Answer:</strong> زمین</p><p><strong>Generated:</strong></p><blockquote><em>چاند کس سمت کے ارد گرد گھومتا ہے؟</em></blockquote><p>The sentence is fluent and related to the source, although the generated question introduces an unnecessary idea of “direction.”</p><h3>5. Correct question word</h3><p><strong>Source:</strong> دریائے سندھ تقریباً 3180 کلومیٹر طویل ہے۔<br><strong>Answer:</strong> 3180 کلومیٹر</p><p><strong>Generated:</strong></p><blockquote><em>دریائے سندھ کتنی ہے؟</em></blockquote><p>The output is incomplete, but the model correctly recognizes that a quantity should lead to a <strong>کتنی</strong> question.</p><p>These examples show that the model learned useful question patterns even when the generation was not always complete.</p><h3>Five Bad Outputs — and Why They Fail</h3><h3>6. Repetition</h3><p><strong>Source:</strong> ٹیلی ویژن کی ایجاد جان لوگی بیئرڈ نے کی۔<br><strong>Answer:</strong> جان لوگی بیئرڈ</p><p><strong>Generated:</strong></p><blockquote><em>ٹیلی ویژن کی کی ایجاد کی ایجاد نے ایجاد کی؟</em></blockquote><p><strong>Failure type:</strong> <strong>Repetition</strong></p><p>The decoder repeatedly generates variations of the same words instead of forming a coherent question.</p><h3>7. Mangled Proper Noun</h3><p><strong>Source:</strong> قائد اعظم محمد علی جناح 1876 میں کراچی میں پیدا ہوئے۔<br><strong>Answer:</strong> کراچی</p><p><strong>Generated:</strong></p><blockquote><em>دد علیاح کس پیدا ہوا تھا؟</em></blockquote><p><strong>Failure type:</strong> <strong>Mangled proper noun / content corruption</strong></p><p>The generated question loses important source information and produces an unintelligible fragment. This is consistent with the difficulty of representing long and rare names using subword pieces.</p><h3>8. Dropped Content</h3><p><strong>Source:</strong> بازنطینی سلطنت گیارہویں صدی میں کمزور ہو گئی۔<br><strong>Answer:</strong> گیارہویں صدی</p><p><strong>Generated:</strong></p><blockquote><em>بازنطینی سلطنت کس صدی میں ہوئی؟</em></blockquote><p><strong>Failure type:</strong> <strong>Dropped content</strong></p><p>The question word is appropriate, but the phrase <strong>کمزور ہو گئی</strong> is lost. The resulting question changes the meaning from “when did it become weak?” to something closer to “when did it happen?”</p><h3>9. Attention Collapse</h3><p><strong>Source:</strong> نارمن دسویں صدی میں فرانس آئے۔<br><strong>Answer:</strong> دسویں صدی</p><p><strong>Generated:</strong></p><blockquote><em>کس صدی میں فرانس … فرانس … فرانس … فرانس … فرانس؟</em></blockquote><p><strong>Failure type:</strong> <strong>Attention collapse / repetition</strong></p><p>The decoder repeatedly focuses on the same source word, فرانس, instead of maintaining the correct temporal relation.</p><h3>10. Repetition + Ignored Answer</h3><p><strong>Source:</strong> وہ ڈنمارک، آئس لینڈ اور ناروے کے نارمن حملہ آوروں …<br><strong>Answer:</strong> نارمن حملہ آوروں</p><p><strong>Generated:</strong></p><blockquote><em>آئس لینڈ اور آئس لینڈ اور آئس لینڈ کے درمیان تعلق رکھتے تھے؟</em></blockquote><p><strong>Failure type:</strong> <strong>Repetition + ignores marked answer</strong></p><p>The generated question repeatedly copies آئس لینڈ and fails to make the marked answer the focus of the question.</p><h3>What These Failures Tell Us</h3><p>The ten examples reveal a consistent pattern.</p><p>The model is much better at learning <strong>question form</strong> than <strong>question content</strong>.</p><p>It can often learn:</p><pre>Number/date → کب / کتنے / کتنی<br>Location    → کہاں</pre><p>But it struggles with:</p><ul><li>preserving entities</li><li>copying rare names</li><li>avoiding repetition</li><li>maintaining the complete meaning of the source</li><li>ensuring the marked answer actually answers the generated question</li></ul><p>This is also visible in the human evaluation. The repository reports very low fluency and relevance scores, and answerability was particularly weak in the evaluated samples.</p><h3>Why Did Beam Search Hurt?</h3><p>One of the most interesting results was the poor performance of beam search.</p><p>Beam search with width 5 produced a BLEU-4 score of only <strong>1.02</strong>, compared with <strong>5.58</strong> for greedy decoding in this experiment.</p><p>Why?</p><p>A beam search decoder tries to find a high-probability complete sequence. But if the model itself assigns high probability to generic or repetitive patterns, beam search can make those patterns more likely to survive.</p><p>In other words:</p><blockquote><strong><em>Better search cannot fix a weak probability model.</em></strong></blockquote><p>In this case, greedy decoding actually stayed more grounded in the source than the wider beam.</p><h3>What We Learned</h3><p>This project was less about building a production-ready question generator and more about understanding the behavior of a sequence-to-sequence model on Urdu.</p><p>Three lessons stood out.</p><h3>1. Answer marking helps</h3><p>Explicitly marking the answer gives the model a strong signal about what the generated question should target.</p><h3>2. Attention helps, but it is not enough</h3><p>The model can often focus on relevant source words, but attention can also collapse onto a single token and cause repetition.</p><h3>3. Data quality matters as much as architecture</h3><p>The model was trained on translated Urdu data. When evaluated on Wiki-UQA, which represents a different distribution of Urdu text, performance dropped. BLEU-4 fell from 5.58 on UQA to 3.57 on Wiki-UQA for greedy decoding.</p><p>This suggests that the model learned not only Urdu question patterns, but also characteristics of the training data.</p><h3>Final Thoughts</h3><p>Can a traditional RNN generate questions in Urdu?</p><p><strong>Yes, but with clear limitations.</strong></p><p>The 35-million-parameter BiLSTM model learned useful patterns such as choosing appropriate interrogative words and attending to relevant parts of the source sentence.</p><p>But it struggled to preserve semantic content. Rare entities were corrupted, words were dropped, and the decoder sometimes entered repetition loops.</p><p>The most important result was therefore not the BLEU score.</p><p>It was understanding the gap between:</p><blockquote><strong><em>“The model knows what kind of question to ask.”</em></strong></blockquote><p>and</p><blockquote><strong><em>“The model knows exactly what question to ask.”</em></strong></blockquote><p>Closing that gap would require stronger mechanisms for copying answer spans, controlling repetition, improving attention coverage, and — most importantly — more high-quality, naturally written Urdu question-answer data.</p><p>The complete code, notebook, results, and evaluation files are available in the project repository.</p><p><strong>GitHub:</strong> Hanzala-12/urdu-question-generation</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e520593c603" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>