<?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 Krishnapiriyan on Medium]]></title>
        <description><![CDATA[Stories by Krishnapiriyan on Medium]]></description>
        <link>https://medium.com/@krishnapiriyan2003?source=rss-09539f2fc242------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*6sIUHpEwiZHtIhiE</url>
            <title>Stories by Krishnapiriyan on Medium</title>
            <link>https://medium.com/@krishnapiriyan2003?source=rss-09539f2fc242------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 17:08:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@krishnapiriyan2003/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[Securing a Web Application with OIDC, JWT and OWASP Top 10 Mitigations]]></title>
            <link>https://medium.com/@krishnapiriyan2003/securing-a-web-application-with-oidc-jwt-and-owasp-top-10-mitigations-a8047da4d999?source=rss-09539f2fc242------2</link>
            <guid isPermaLink="false">https://medium.com/p/a8047da4d999</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[information-security]]></category>
            <category><![CDATA[data-security]]></category>
            <dc:creator><![CDATA[Krishnapiriyan]]></dc:creator>
            <pubDate>Mon, 31 Aug 2026 10:36:27 GMT</pubDate>
            <atom:updated>2026-08-31T11:11:13.135Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jeLFypXhMGkh96Uj_vYOsA.png" /></figure><h3>A Practical Security Enhancement of a Book Fair Stall Reservation System</h3><p>Building a web application that works correctly is only one part of software engineering. Building one that remains secure when users send malicious requests, manipulate parameters, steal tokens, or attempt to access resources they do not own is a much bigger challenge.</p><p>As part of my <strong>Secure Web Application Development</strong> assessment, I took an existing <strong>Book Fair Stall Reservation System</strong> and performed a security-focused enhancement of the application.</p><p>The goal was not simply to add authentication.</p><p>The goal was to answer a more important question:</p><blockquote><strong><em>What happens when a legitimate user behaves maliciously?</em></strong></blockquote><p>To address this, I introduced and tested multiple security controls, including:</p><ul><li>OpenID Connect (OIDC)</li><li>OAuth 2.0 Authorization Code Flow with PKCE</li><li>Auth0-based authentication</li><li>JWT validation with Spring Security</li><li>Role-Based Access Control (RBAC)</li><li>Object-level authorization</li><li>IDOR protection</li><li>Input validation</li><li>SQL injection protection</li><li>Cross-Site Scripting (XSS) mitigation</li><li>Restricted CORS</li><li>WebSocket authentication</li><li>HTTPS and security headers</li><li>Secure file uploads</li><li>Secret management</li><li>Security logging and monitoring</li></ul><p>The application follows a decoupled architecture using <strong>React and Vite</strong> for the frontend, <strong>Spring Boot and Spring Security</strong> for the backend, <strong>MySQL</strong> for persistence, and <strong>Auth0</strong> as the external Identity Provider.</p><h3>1. Understanding the Application</h3><p>The Book Fair Stall Reservation System allows stall vendors to reserve stalls for book fair events while exhibition organizers manage events, stalls, reservations, and related administrative operations.</p><p>The main technology stack is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*GmtxrstZNM0ASOJv104CUw.png" /></figure><p>The application contains two primary roles:</p><ul><li><strong>STALL_VENDOR</strong> — manages their own stall reservations and permitted vendor operations.</li><li><strong>EXHIBITION_ORGANIZER</strong> — manages events, stalls, reservations, and administrative operations.</li></ul><h3>2. Authentication vs Authorization</h3><p>One of the biggest lessons from this project was understanding the difference between <strong>authentication</strong> and <strong>authorization</strong>.</p><h4>Authentication</h4><p>Authentication answers:</p><blockquote><strong><em>Who are you?</em></strong></blockquote><h4>Authorization</h4><p>Authorization answers:</p><blockquote><strong><em>What are you allowed to do?</em></strong></blockquote><p>For example, a vendor may successfully authenticate and receive a valid JWT. That does not mean the vendor should be able to access an administrative endpoint.</p><p>The backend must independently verify whether that user has the required permissions.</p><p>This is why security cannot depend on frontend controls such as hiding buttons or removing menu items. An attacker can bypass the frontend completely and send HTTP requests directly to the API.</p><p>The backend therefore became the central enforcement point for security decisions.</p><h3>3. Replacing Local Password Authentication with Auth0</h3><p>One of the major security improvements was moving authentication away from application-managed passwords.</p><p>Instead of storing and validating user passwords inside the application database, authentication was delegated to <strong>Auth0</strong>.</p><p>The application uses:</p><ul><li>OpenID Connect (OIDC)</li><li>OAuth 2.0</li><li>Authorization Code Flow</li><li>PKCE</li></ul><p>The resulting flow is:</p><pre>User<br>  ↓<br>React Application<br>  ↓<br>Auth0 Authorization Endpoint<br>  ↓<br>User Authentication<br>  ↓<br>Authorization Code<br>  ↓<br>PKCE Verification<br>  ↓<br>Access Token<br>  ↓<br>React Application<br>  ↓<br>Authorization: Bearer &lt;token&gt;<br>  ↓<br>Spring Boot API</pre><p>The React application acts as a public client, so it cannot safely keep a traditional client secret. PKCE provides additional protection for the authorization-code exchange.</p><h3>4. How PKCE Protects the Authentication Flow</h3><p>PKCE stands for <strong>Proof Key for Code Exchange</strong>.</p><p>It protects the OAuth 2.0 authorization-code flow by associating the authorization request with a secret value generated by the client.</p><h3>Step 1 — Generate the Code Verifier</h3><p>The React application generates a cryptographically secure random value using the browser’s Web Crypto API.</p><h3>Step 2 — Generate the Code Challenge</h3><p>The verifier is hashed using SHA-256 and converted into URL-safe Base64 encoding.</p><p>Conceptually:</p><pre>code_challenge = BASE64URL(SHA256(code_verifier))</pre><h3>Step 3 — Send the Challenge</h3><p>The application sends:</p><pre>code_challenge<br>code_challenge_method=S256</pre><p>to Auth0 during authorization.</p><h3>Step 4 — Verify the Code</h3><p>After authentication, Auth0 returns an authorization code.</p><p>The application provides the original:</p><pre>code_verifier</pre><p>Auth0 hashes it and verifies that it matches the previously supplied challenge.</p><p>Only after successful verification can the token exchange take place.</p><h3>5. JWT Validation with Spring Security</h3><p>Receiving a JWT from the frontend does not mean that the backend should automatically trust it.</p><p>The Spring Boot application operates as an <strong>OAuth 2.0 Resource Server</strong> and validates important JWT properties before allowing protected requests.</p><p>These include:</p><h4>Cryptographic Signature</h4><p>The token signature is validated using public keys obtained from the Auth0 JWKS endpoint.</p><h4>Issuer</h4><p>The iss claim is checked to ensure the token was issued by the expected Identity Provider.</p><h4>Audience</h4><p>The aud claim is verified to ensure that the token was issued for the backend API.</p><h4>Expiration</h4><p>The exp claim is checked to ensure that expired tokens cannot be used.</p><h4>Authorization Claims</h4><p>Relevant role claims are extracted and mapped to Spring Security authorities.</p><p>For example:</p><pre>ROLE_STALL_VENDOR<br>ROLE_EXHIBITION_ORGANIZER</pre><p>The backend can then make authorization decisions independently of the frontend.</p><blockquote><strong><em>Hiding a button in the frontend is not authorization. Authorization must be enforced by the server.</em></strong></blockquote><h3>6. OWASP A01 — Broken Access Control and IDOR</h3><p>One of the most important vulnerabilities addressed was <strong>Broken Access Control (OWASP A01:2021)</strong>.</p><p>Consider this API:</p><pre>GET /api/reservations/25</pre><p>Suppose Vendor A owns reservation 24.</p><p>If Vendor A changes the URL to:</p><pre>GET /api/reservations/25</pre><p>the application must not automatically return Vendor B’s reservation.</p><p>This is an example of <strong>Insecure Direct Object Reference (IDOR)</strong> or broken object-level authorization.</p><p>The backend therefore performs an ownership check:</p><pre>Authenticated User<br>        ↓<br>Requested Reservation<br>        ↓<br>Check Reservation Owner<br>        ↓<br>     Owner?<br>     /     \<br>   YES      NO<br>    ↓        ↓<br>  Allow    403</pre><p>If the authenticated user does not own the resource:</p><pre>HTTP 403 Forbidden</pre><p>is returned.</p><p>I tested this using different vendor accounts. When one vendor attempted to access another vendor’s reservation, the request was blocked.</p><p>This demonstrated an important principle:</p><blockquote><strong><em>A valid login does not automatically grant access to every resource.</em></strong></blockquote><h3>7. Preventing Client-Side Identity Manipulation</h3><p>Another important improvement was removing trust in security-sensitive IDs supplied by the client.</p><p>For example, an attacker might modify:</p><pre>{<br>  &quot;vendorId&quot;: 15,<br>  &quot;stallId&quot;: 8<br>}</pre><p>to:</p><pre>{<br>  &quot;vendorId&quot;: 1,<br>  &quot;stallId&quot;: 8<br>}</pre><p>If the backend blindly trusts this value, the attacker may be able to create a reservation under another user’s identity.</p><p>The solution was to derive the authenticated user’s identity from the validated Spring Security authentication context.</p><p>The flow becomes:</p><pre>JWT<br> ↓<br>Spring Security<br> ↓<br>Authenticated Principal<br> ↓<br>Resolve Local User<br> ↓<br>Create Reservation</pre><p>The backend therefore determines ownership from trusted authentication information rather than client-controlled parameters.</p><h3>8. Role-Based Access Control</h3><p>The application implements server-side <strong>Role-Based Access Control (RBAC)</strong>.</p><p>Administrative functionality such as:</p><ul><li>Approving reservations</li><li>Rejecting reservations</li><li>Processing refunds</li><li>Managing users</li></ul><p>is restricted to authorized organizer functionality.</p><p>For example:</p><pre>@PreAuthorize(&quot;hasRole(&#39;EXHIBITION_ORGANIZER&#39;)&quot;)</pre><p>can be used to restrict an endpoint.</p><p>A vendor cannot bypass the restriction by manually entering an administrative URL or sending an HTTP request directly to the backend.</p><p>During testing, vendor attempts to access organizer-only functionality resulted in:</p><pre>HTTP 403 Forbidden</pre><h3>9. Preventing Mass Assignment</h3><p>Mass assignment occurs when a client can submit fields that should not be controlled by that client.</p><p>For example:</p><pre>{<br>  &quot;phone&quot;: &quot;0712345678&quot;,<br>  &quot;businessName&quot;: &quot;Example Company&quot;,<br>  &quot;role&quot;: &quot;EXHIBITION_ORGANIZER&quot;,<br>  &quot;active&quot;: true<br>}</pre><p>The user should be able to modify legitimate profile information such as:</p><pre>phone<br>businessName</pre><p>but not:</p><pre>role<br>OIDC subject<br>internal ID<br>active status</pre><p>Profile updates were therefore restricted to explicitly permitted fields.</p><p>This follows a key principle:</p><blockquote><strong><em>Allow only what the user is supposed to change.</em></strong></blockquote><h3>10. Input Validation</h3><p>Input validation was strengthened using <strong>Jakarta Bean Validation</strong>.</p><p>Examples include:</p><pre>@NotNull<br>@NotBlank<br>@NotEmpty<br>@Size<br>@Min<br>@DecimalMin<br>@FutureOrPresent</pre><p>These validations provide constraints at the API boundary.</p><p>For example:</p><ul><li>Required fields cannot be empty.</li><li>Strings have controlled lengths.</li><li>Numerical values must satisfy defined limits.</li><li>Reservation dates cannot be arbitrarily set in the past.</li><li>Enum-based fields reject unsupported values.</li></ul><p>Controlled values such as stall sizes and payment methods are represented using enums instead of accepting arbitrary strings.</p><h3>11. SQL Injection Protection</h3><p>SQL injection was considered during the security review.</p><p>The backend uses:</p><ul><li>Spring Data JPA</li><li>Hibernate</li><li>Repository-based database operations</li></ul><p>Rather than constructing SQL queries through unsafe string concatenation, parameters are bound through the persistence layer.</p><p>The dangerous pattern is:</p><pre>&quot;SELECT * FROM users WHERE name = &#39;&quot; + userInput + &quot;&#39;&quot;</pre><p>Parameterized persistence operations avoid treating untrusted input as executable SQL syntax.</p><p>The application review did not identify dynamically concatenated native SQL being used for these operations.</p><h3>12. Cross-Site Scripting (XSS)</h3><p>The React frontend was reviewed for unsafe HTML rendering.</p><p>The application does not intentionally use mechanisms such as:</p><pre>dangerouslySetInnerHTML</pre><p>for untrusted application content.</p><p>React’s standard rendering behavior escapes text values, helping reduce common XSS risks.</p><p>A <strong>Content Security Policy (CSP)</strong> is also configured as an additional browser-side security control.</p><h3>13. Restricting CORS</h3><p>Cross-Origin Resource Sharing was another important security area.</p><p>A permissive configuration can unnecessarily expose APIs to cross-origin browser requests.</p><p>The application therefore uses an explicit CORS allowlist instead of allowing arbitrary origins.</p><p>During testing, I sent a request containing:</p><pre>Origin: https://evil-example.com</pre><p>The server rejected the request with:</p><pre>HTTP/1.1 403 Invalid CORS request</pre><p>This confirmed that unauthorized browser origins were not accepted.</p><h3>14. Securing WebSocket Communication</h3><p>Security cannot stop at REST APIs.</p><p>The application also uses <strong>WebSocket/STOMP</strong> to provide real-time stall availability updates.</p><p>The STOMP connection requires a Bearer access token.</p><p>The backend validates the JWT and associates the connection with the authenticated user.</p><p>Administrative WebSocket subscriptions are also restricted according to authorization roles.</p><p>This reinforced another important principle:</p><blockquote><strong><em>Every communication channel is part of the application’s attack surface.</em></strong></blockquote><h3>15. HTTPS and Security Headers</h3><p>The backend was configured to operate over HTTPS during development.</p><p>Additional security controls include:</p><h4>HSTS</h4><p><strong>HTTP Strict Transport Security</strong> instructs browsers to use HTTPS.</p><h4>Content Security Policy</h4><p>CSP restricts which scripts and resources can be executed by the browser.</p><h4>X-Frame-Options</h4><pre>X-Frame-Options: DENY</pre><p>helps protect against clickjacking.</p><h4>X-Content-Type-Options</h4><pre>X-Content-Type-Options: nosniff</pre><p>helps prevent MIME-type sniffing.</p><p>For production deployment, a certificate issued by a trusted Certificate Authority should be used instead of a local development certificate.</p><h3>16. Secure File Uploads</h3><p>File uploads create another significant attack surface.</p><p>An attacker may attempt to upload executable files, unexpected file types, extremely large files, or files with malicious filenames.</p><p>The application therefore:</p><ul><li>Restricts accepted MIME types</li><li>Limits upload sizes</li><li>Generates unique filenames using UUIDs</li><li>Determines permitted extensions on the server</li><li>Avoids trusting the original client filename</li></ul><p>For example:</p><pre>Original:<br>malicious-file.exe</pre><pre>Server-generated:<br>550e8400-e29b-41d4-a716-446655440000.jpg</pre><p>For a production system, this protection could be strengthened further with file-content inspection and malware scanning.</p><h3>17. Protecting Secrets</h3><p>Sensitive credentials should never be committed directly into source control.</p><p>The application externalizes sensitive configuration such as:</p><ul><li>Database passwords</li><li>SMTP passwords</li><li>OIDC configuration</li><li>SSL keystore credentials</li></ul><p>using environment variables.</p><p>Sensitive local files such as:</p><pre>.env<br>private keystores<br>runtime uploads</pre><p>are excluded from version control.</p><p>The public repository contains configuration templates and placeholders rather than actual credentials.</p><blockquote><strong><em>Secrets belong in secret-management mechanisms, not source code.</em></strong></blockquote><h3>18. OWASP Security Audit — Before vs After</h3><p>To verify the security improvements, the application was reviewed before and after remediation.</p><h3>🔴 Before Security Enhancements</h3><h3>A01 — Broken Access Control</h3><p>A vendor could previously attempt an administrative operation such as:</p><pre>POST /api/reservations/4/approve</pre><p>using another vendor’s token, and the legacy implementation returned:</p><pre>HTTP 200<br>{&quot;message&quot;:&quot;Reservation approved&quot;}</pre><p>This demonstrated a serious authorization weakness.</p><h3>A02 — Cryptographic Failures</h3><p>Sensitive configuration contained plaintext credentials, including database and SMTP passwords.</p><h3>A05 — Security Misconfiguration</h3><p>The legacy CORS configuration allowed a wildcard origin pattern together with credentials:</p><pre>config.addAllowedOriginPattern(&quot;*&quot;);<br>config.setAllowCredentials(true);</pre><h3>🟢 After Security Remediation</h3><h3>A01 — Broken Access Control</h3><p>Administrative operations were moved behind protected administrative routes and restricted through server-side authorization.</p><p>Unauthorized vendor requests now receive:</p><pre>HTTP 403 Forbidden</pre><h3>A05 — Security Misconfiguration</h3><p>CORS was restricted to explicit trusted origins.</p><p>Vendor requests to administrative endpoints are rejected.</p><h3>A02 — Cryptographic Failures</h3><p>Database, JWT, SMTP, and other sensitive configuration values were externalized through environment variables.</p><h3>A09 — Security Logging and Monitoring</h3><p>Security-related events were added to the audit logs:</p><pre>login_success<br>login_failure<br>access_denied<br>invalid_token<br>reservation_approved</pre><h3>A07 — Identification and Authentication Failures</h3><p>Invalid or missing authentication tokens are rejected:</p><pre>HTTP 401 Unauthorized</pre><h3>19. Security Testing</h3><p>Security controls should not only be implemented; they should also be tested.</p><p>The following tests were performed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*aPLsRvKCeMZsur-PXY42Ww.png" /></figure><p>These tests helped verify that security controls were actually enforced rather than relying only on source-code inspection.</p><h3>20. Challenges I Faced</h3><p>Security integration was not straightforward.</p><p>The biggest challenge was integrating an external Identity Provider with an application that already maintained local user records.</p><p>Auth0 identifies users using the OIDC sub claim, while the application still requires local database records for business information and relationships.</p><p>Therefore, the system needed to establish a reliable mapping:</p><pre>Auth0 Identity<br>      ↓<br>OIDC Subject<br>      ↓<br>Local User<br>      ↓<br>Application Role<br>      ↓<br>Business Resources</pre><p>Role synchronization was another challenge because the roles provided by the authentication system needed to correspond correctly with the application’s authorization model.</p><p>Testing also required additional consideration. A Spring Boot context test initially attempted to communicate with a fake OIDC issuer during startup. The test environment was isolated by mocking the JWT decoder while keeping the production JWT validation configuration unchanged.</p><p>WebSocket authentication introduced another challenge because authentication had to be handled during the STOMP connection lifecycle rather than only through normal REST requests.</p><h3>21. What I Learned</h3><p>This project changed the way I think about web application security.</p><h3>1. Authentication is not authorization</h3><p>Knowing who a user is does not determine what resources they can access.</p><h3>2. Never trust the frontend</h3><p>A frontend can improve the user experience, but it cannot enforce security by itself.</p><h3>3. Identity should come from trusted authentication data</h3><p>Security-sensitive identities should be derived from validated authentication information rather than client-supplied parameters.</p><h3>4. RBAC is not always enough</h3><p>Two users can have the same role but own completely different resources.</p><p>That is why role-based authorization often needs to be combined with object-level ownership checks.</p><h3>5. Every communication channel needs security</h3><p>REST APIs, WebSockets, file uploads, database operations, and configuration all introduce different security risks.</p><h3>6. Secrets should never be committed to source control</h3><p>Credentials must be externalized and managed securely.</p><h3>7. Security must be tested</h3><p>A security mechanism is only meaningful if unauthorized and malicious requests are actually rejected.</p><h3>22. Final Thoughts</h3><p>Enhancing the Book Fair Stall Reservation System gave me an opportunity to move beyond theoretical security concepts and apply them to a real application.</p><p>The project demonstrates that application security is not a single feature that can be added at the end of development.</p><p>It is a collection of layers:</p><pre>Secure Application<br>                       │<br>        ┌──────────────┼──────────────┐<br>        ↓              ↓              ↓<br> Authentication   Authorization   Validation<br>        │              │              │<br>       OIDC            RBAC          DTOs<br>       PKCE            IDOR          Constraints<br>       JWT             Ownership     Enums<br>        │              │              │<br>        └──────────────┼──────────────┘<br>                       ↓<br>             Communication Security<br>                       │<br>              HTTPS + CORS + CSP<br>                       │<br>                       ↓<br>                Secure Persistence<br>                       │<br>                  JPA + Hibernate<br>                       │<br>                       ↓<br>                Secure Operations<br>                       │<br>          Secrets + Logging + Testing</pre><p>The most important lesson I took from this assessment is simple:</p><blockquote><strong><em>Security is not about adding one authentication mechanism. It is about designing every part of the application so that untrusted input, unauthorized users, and unexpected behavior are handled safely.</em></strong></blockquote><p>By integrating Auth0, OIDC, OAuth 2.0 with PKCE, JWT validation, Spring Security, RBAC, object-level authorization, input validation, restricted CORS, secure WebSockets, HTTPS, security headers, secure file uploads, secret management, and security testing, the application now has multiple layers of protection.</p><p>More importantly, I now understand that <strong>secure software development is a continuous engineering process rather than a final checklist before deployment.</strong></p><h3>Source Code</h3><p>The complete project is available in my public GitHub repository: 👉 <a href="https://github.com/Krishnapiriyan/secure-stall-reservation-system"><strong>Secure Stall Reservation System on GitHub</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8047da4d999" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Retrieval-Augmented
Generation]]></title>
            <link>https://medium.com/@krishnapiriyan2003/retrieval-augmented-generation-eaa1262b71c8?source=rss-09539f2fc242------2</link>
            <guid isPermaLink="false">https://medium.com/p/eaa1262b71c8</guid>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[rags]]></category>
            <dc:creator><![CDATA[Krishnapiriyan]]></dc:creator>
            <pubDate>Wed, 10 Jun 2026 09:27:59 GMT</pubDate>
            <atom:updated>2026-06-10T09:27:59.011Z</atom:updated>
            <content:encoded><![CDATA[<p>A comprehensive technical deep dive into how RAG systems work — from embedding theory and vector search to advanced retrieval patterns, evaluation frameworks, and production architecture.</p><h3>1.What is RAG?</h3><p>Retrieval-Augmented Generation (RAG) is an AI architecture that enhances a language model’s response quality by dynamically injecting relevant external knowledge into its context at inference time. Rather than relying solely on the parametric memory baked into a model’s weights during training, RAG retrieves fresh, relevant documents and feeds them to the model as grounding context.</p><p>First formally described by Lewis et al. (2020) at Facebook AI Research, RAG addresses one of the most fundamental limitations of large language models: their knowledge is frozen at training time and they have no native ability to access specific, verifiable, or private information.</p><blockquote>Core Idea</blockquote><blockquote>Don’t memorize everything — know where to look. RAG separates parametric knowledge (model weights) from non-parametric knowledge (a dynamic retrieval corpus), combining both at query time.</blockquote><p>This separation is powerful. You can update the retrieval corpus — adding new documents, correcting facts — without retraining the model. This makes RAG dramatically cheaper and faster to maintain than fine-tuning for knowledge-intensive tasks.</p><h3>2.Why RAG Exists</h3><p>To understand why RAG emerged, we need to understand the specific failure modes it addresses.</p><h3>The Hallucination Problem</h3><p>LLMs generate text token-by-token, each token selected by sampling from a probability distribution conditioned on prior context. This process is remarkable, but it has no internal mechanism for distinguishing between a fact it learned accurately versus a plausible-sounding construction. The model has no concept of “I don’t know this” — it will generate something, even if that something is wrong.</p><h3>The Knowledge Cutoff Problem</h3><p>Training data has a cutoff date. A model trained on data through early 2024 knows nothing about events after that. For dynamic domains — legal regulations, medical guidelines, product pricing, company news — this is a fundamental limitation. Fine-tuning on new data is expensive: it requires GPU clusters, careful data curation, and introduces the risk of catastrophic forgetting.</p><h3>The Context &amp; Privacy Problem</h3><p>Enterprises have enormous bodies of private, proprietary knowledge — internal documentation, customer data, code repositories, contracts. This knowledge can never go into a shared model’s training data. RAG allows LLMs to reason over this private corpus without ever exposing it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*omksa5N7s69ftXBiFzYgeg.png" /></figure><h3>3.Core Architecture</h3><p>A RAG system has two major phases: an offline indexing pipeline that prepares the knowledge base, and an online query pipeline that handles live requests.</p><h3>Indexing Pipeline (Offline)</h3><p>1.Ingest: Load raw documents: PDFs, HTML, Markdown, databases️</p><p>2.Chunk: Split into overlapping text segments of controlled size</p><p>3.Embed: Convert each chunk to a dense vector via embedding model</p><p>4.Store: Write vectors + metadata to a vector database</p><h3>Query Pipeline (Online)</h3><pre>User Query<br>    │<br>    ▼<br>Query Processing<br>├── Query Rewriting<br>├── Query Expansion<br>├── HyDE (Hypothetical Document Embeddings)<br>└── Multi-Query Generation<br>    │<br>    ▼<br>Embedding Model<br>(Same model used during indexing)<br>    │<br>    ▼<br>Vector Database / Vector Store<br>├── ANN Search (HNSW, IVF)<br>├── Hybrid Search (Dense + BM25)<br>└── Metadata Filtering<br>    │<br>    ▼<br>Retrieved Chunks (Top-K)<br>    │<br>    ▼<br>Reranker<br>├── Cross Encoder<br>└── LLM-Based Reranking<br>    │<br>    ▼<br>Context Assembly<br>├── Chunk Deduplication<br>├── Context Packing<br>└── Prompt Construction<br>    │<br>    ▼<br>Large Language Model<br>    │<br>    ▼<br>Grounded Response<br>├── Citations<br>├── Sources<br>└── Final Answer</pre><h3>Chunking &amp; Indexing</h3><p>Chunking is deceptively simple but critically important. How you split documents directly determines retrieval quality. A bad chunking strategy produces irrelevant or truncated context even when the embedding model and vector search work perfectly.</p><h3>Chunking Strategies</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/1*uFz5rTyiwJRkDw63nF8zpA.png" /></figure><h4>Fixed-Size Chunking</h4><p>Split every N tokens with stride overlap. Fast, predictable, but ignores semantic boundaries — a sentence can be cut in half.</p><h4>Recursive Character Splitting</h4><p>LangChain’s default. Splits on \n\n → \n → “. “ → “ “ in priority order, maintaining semantic coherence better than fixed-size.🌳</p><h4>Hierarchical / Parent-Child</h4><p>Index small chunks for precision, but retrieve larger parent chunks for context. Best of both worlds — widely used in production.</p><h4>Semantic Chunking</h4><p>Embed sentences and split where cosine similarity drops. More expensive but semantically coherent. Good for long-form narratives.</p><blockquote>Rule of Thumb</blockquote><blockquote>For most production RAG: use 256–512 token chunks with 20% overlap. Use a hierarchical strategy where you retrieve small chunks but pass larger parent chunks to the LLM.</blockquote><h3>Embeddings: Turning Text into Numbers</h3><p>An embedding model maps text into a high-dimensional vector space where semantically similar texts are geometrically close. This is the mathematical foundation of RAG — similarity search in embedding space is how we find relevant documents.</p><p>A modern embedding model like text-embedding-3-large maps any text snippet to a 3072-dimensional unit vector. Two chunks about the same topic will have vectors with high cosine similarity (close to 1.0); unrelated chunks will be nearly orthogonal (close to 0).</p><blockquote>Critical Rule</blockquote><blockquote>Always use the same embedding model for indexing and querying. Switching embedding models requires re-embedding your entire corpus. Even version changes (e.g., text-embedding-ada-002 → text-embedding-3-small) require full re-indexing.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*8XnYbCP3i6Ojw991yWmXPQ.png" /></figure><h3>Vector Stores</h3><p>A vector database is purpose-built for storing and searching high-dimensional vectors at scale. Unlike traditional databases, the primary query operation is approximate nearest neighbor (ANN) search — finding the K vectors most similar to a query vector.</p><h4>Pinecone</h4><p>Fully managed, serverless. Excellent scaling, built-in metadata filtering. Best for teams that don’t want to manage infrastructure.</p><h4>Weaviate</h4><p>Open-source, self-hosted or cloud. Strong hybrid search (BM25 + dense). Excellent for complex metadata schemas.</p><h4>Qdrant</h4><p>Rust-based, extremely fast. Great for quantization support, scalar &amp; binary quantization for memory efficiency.</p><h4>pgvector</h4><p>PostgreSQL extension. Best for teams with existing Postgres. Simple, no new infra, but slower at very large scale.</p><p>Under the hood, most vector DBs use HNSW (Hierarchical Navigable Small Worlds) — a graph-based ANN algorithm that achieves O(log N) query time with excellent recall at high-dimensional scales. The key tradeoff parameters are ef_construction (index build quality) and ef_search (query recall vs. speed).</p><h3>5.Retrieval Strategies</h3><h3>Dense vs. Sparse Retrieval</h3><p>There are two fundamentally different ways to retrieve documents — and production systems typically combine both.</p><h3>Dense Retrieval (Semantic Search)</h3><p>Uses embedding models to find semantically similar content. Great for paraphrases, conceptual queries, and cross-language search. Struggles with exact keyword matching — searching for “GPT-4o” might not reliably retrieve documents containing exactly that string.</p><h3>Sparse Retrieval (BM25 / TF-IDF)</h3><p>Traditional inverted-index text search. Excellent for exact keyword matching, proper nouns, product codes, and specific terminology. No embedding overhead. Misses semantic similarity — “automobile” won’t match “car”.</p><p>Hybrid search combines both signals with a weighted fusion, typically using Reciprocal Rank Fusion (RRF). This approach consistently outperforms either method alone across diverse query types.</p><pre>def reciprocal_rank_fusion(dense_results, sparse_results, k=60):<br>    &quot;&quot;&quot;Fuse dense and sparse retrieval results via RRF.&quot;&quot;&quot;<br>    scores = {}<br>    <br>    for rank, doc in enumerate(dense_results):<br>        doc_id = doc[&quot;id&quot;]<br>        scores[doc_id] = scores.get(doc_id, 0) + 1 / (k + rank + 1)<br><br>    for rank, doc in enumerate(sparse_results):<br>        doc_id = doc[&quot;id&quot;]<br>        scores[doc_id] = scores.get(doc_id, 0) + 1 / (k + rank + 1)<br>    <br>    # Sort by fused score<br>    fused = sorted(scores.items(), key=lambda x: x[1], reverse=True)<br>    return [doc_id for doc_id, _ in fused]</pre><h3>Reranking: Precision After Recall</h3><p>Vector similarity is fast but imprecise — it operates in a high-dimensional space with approximation tradeoffs. Reranking is a second-pass scoring step: take the top-50 retrieved candidates and apply a more expensive but accurate relevance model to get the true top-5.</p><p>Cross-encoders (like Cohere Rerank, BGE-Reranker) are the standard approach. Unlike embedding models that encode query and document independently (bi-encoders), cross-encoders jointly process the query + document pair, giving them much richer interaction modeling. The tradeoff: you can’t pre-compute cross-encoder scores, so they run at query time.</p><h3>6.Augmented Generation</h3><p>With retrieved context in hand, the final step is prompting the LLM to generate a grounded response. The quality of this step depends heavily on prompt engineering.</p><pre>RAG_SYSTEM_PROMPT = &quot;&quot;&quot;You are a precise and reliable assistant.<br>Answer the user&#39;s question using ONLY the provided context.<br>If the context does not contain enough information to answer,<br>say &quot;I don&#39;t have enough information to answer this.&quot;<br>Never fabricate facts. Cite the source chunk IDs inline.<br>&quot;&quot;&quot;<br><br>def build_rag_prompt(query: str, chunks: list) -&gt; str:<br>    context_block = &quot;\n\n&quot;.join([<br>        f&quot;[{i+1}] {chunk[&#39;text&#39;]}&quot;<br>        for i, chunk in enumerate(chunks)<br>    ])<br>    return f&quot;&quot;&quot;Context:<br>{context_block}<br><br>Question: {query}<br><br>Answer (cite chunk numbers inline as [1], [2], etc.):&quot;&quot;&quot;</pre><p>Key prompt engineering considerations for RAG:</p><ul><li>Context positioning: Place retrieved context before the question. LLMs exhibit “lost in the middle” behavior — they attend better to context at the beginning and end of the window.</li><li>Explicit grounding instruction: Explicitly tell the model to only use provided context. Without this, models will fall back to parametric knowledge, defeating the purpose.</li><li>Chunk ordering: Place the most relevant chunks first and last; less relevant context in the middle reduces interference.</li><li>Citation prompting: Asking the model to cite sources improves grounding and gives users verifiability.</li></ul><h3>7.Advanced RAG Patterns</h3><p>Naive RAG — embed, retrieve, generate — performs surprisingly well but has clear failure modes. The research community has developed several sophisticated patterns to address them.</p><h3>HyDE: Hypothetical Document Embeddings</h3><p>The core insight of HyDE (Gao et al., 2023): an answer is more similar to other answers than a question is to an answer. Before embedding the user’s question, ask the LLM to generate a hypothetical answer document. Then embed that hypothetical document and search the corpus. This bridges the semantic gap between question and answer space.</p><pre>async def hyde_retrieve(query: str, retriever) -&gt; list:<br>    # Step 1: generate hypothetical answer<br>    hyde_prompt = f&quot;Write a short factual answer to: {query}&quot;<br>    hypothetical_doc = await llm_generate(hyde_prompt, max_tokens=200)<br>    <br>    # Step 2: embed the hypothetical answer, not the question<br>    hyde_embedding = await embed(hypothetical_doc)<br>    <br>    # Step 3: search with hypothetical embedding<br>    results = await retriever.search(hyde_embedding, top_k=10)<br>    return results</pre><h3>Self-RAG: Adaptive Retrieval</h3><p>Traditional RAG retrieves on every query, even when the LLM already knows the answer. Self-RAG (Asai et al., 2023) fine-tunes the LLM to generate special reflection tokens — [Retrieve], [IsREL], [IsSUP], [IsUSE] — that control whether retrieval happens, whether retrieved docs are relevant, and whether generated text is supported by context.</p><p>This adaptive retrieval reduces unnecessary latency and cost while improving response quality for knowledge-intensive questions.</p><h3>GraphRAG: Knowledge Graph Retrieval</h3><p>Standard RAG operates over flat chunks — islands of text with no explicit relationship structure. GraphRAG (Edge et al., Microsoft, 2024) augments vector retrieval with a knowledge graph extracted from the corpus.</p><p>Entities and relationships are extracted using an LLM (e.g., “Einstein [bornIn] Germany”) and stored as a graph. Queries can then traverse entity relationships, enabling multi-hop reasoning that flat chunk retrieval cannot support. A question like “What did the CEO who founded the company that built GPT-4 say about AGI?” requires following chains of relationships — GraphRAG handles this naturally.</p><blockquote>When to use GraphRAG</blockquote><blockquote>GraphRAG excels when your corpus is a highly interconnected knowledge domain with clear entities — financial reports, legal cases, scientific literature, organizational wikis. For simpler Q&amp;A over documents, standard RAG is cheaper and faster.</blockquote><h3>Agentic RAG</h3><p>Agentic RAG replaces the single-shot retrieve-then-generate paradigm with an iterative agent loop. The LLM decides when and how to retrieve, can issue multiple retrieval queries, synthesize across sources, and decide when it has sufficient context to answer.</p><pre>┌──────────────────────────┐<br>│ User Query               │<br>└──────────┬───────────────┘<br>           │<br>           ▼<br>┌──────────────────────────┐<br>│ LLM Agent               │<br>│ Plan Next Action        │<br>└──────────┬───────────────┘<br>           │<br>           ├── search(query_1)<br>           │<br>           ├── search(query_2)<br>           │<br>           ├── lookup(entity)<br>           │<br>           ├── summarize findings<br>           │<br>           └── reflect<br>                  │<br>        ┌─────────┴─────────┐<br>        │ Enough Context?   │<br>        └──────┬─────┬──────┘<br>               │     │<br>             Yes     No<br>               │     │<br>               ▼     │<br>      Generate Answer│<br>                     │<br>                     ▼<br>             Continue Loop</pre><h3>8.Evaluation</h3><p>RAG systems are notoriously difficult to evaluate because quality exists at multiple levels: the retrieval quality, the generation quality, and the end-to-end answer quality — each requiring different metrics.</p><h3>RAGAS Framework</h3><p>RAGAS (Retrieval Augmented Generation Assessment) has become the community standard. It defines four core metrics, each measurable without human labels:</p><h4>Faithfulness</h4><p>Are all claims in the answer supported by the retrieved context? Catches hallucinations where the LLM adds facts not in the context.</p><h4>Answer Relevance</h4><p>Does the answer actually address the question? A fully grounded answer that misses the point scores low here.</p><h4>Context Precision</h4><p>Of the retrieved chunks, how many were actually relevant? High retrieval volume doesn’t help if chunks are noisy.</p><h4>Context Recall</h4><p>Did the retrieval surface all the context needed to answer? Requires a ground-truth reference answer.</p><pre>from ragas import evaluate<br>from ragas.metrics import (<br>    faithfulness, answer_relevancy,<br>    context_precision, context_recall<br>)<br>from datasets import Dataset<br><br>eval_data = {<br>    &quot;question&quot;: [&quot;What is RAG?&quot;, &quot;How does HNSW work?&quot;],<br>    &quot;answer&quot;: [generated_answers],<br>    &quot;contexts&quot;: [retrieved_chunks_per_question],<br>    &quot;ground_truths&quot;: [reference_answers],  # optional<br>}<br><br>result = evaluate(<br>    dataset=Dataset.from_dict(eval_data),<br>    metrics=[faithfulness, answer_relevancy, context_precision, context_recall]<br>)<br>print(result)<br># {&#39;faithfulness&#39;: 0.91, &#39;answer_relevancy&#39;: 0.87, ...}</pre><h3>9.Production Architecture</h3><p>Moving RAG from a notebook to production introduces a class of problems that don’t exist at prototype scale: latency budgets, corpus drift, caching, observability, and cost management.</p><h3>Latency Budget</h3><p>A typical production RAG request has several time components. Understanding where time is spent determines where to optimize.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*pckdTcjjpV2X8QteYn1zfQ.png" /></figure><h3>Caching Strategy</h3><p>RAG is expensive. Caching is essential at multiple levels: exact-match query caching (identical queries), semantic caching (cache results for semantically equivalent queries), and partial context caching (many queries share the same system prompt + context prefix).</p><h3>Observability</h3><p>Every RAG request should log: the query, the retrieved chunk IDs and scores, the reranked order, the final prompt, the LLM response, and end-to-end latency. Tools like LangSmith, Arize Phoenix, and Langfuse provide purpose-built RAG tracing dashboards.</p><blockquote>Production Checklist</blockquote><blockquote>✓ Hybrid retrieval (dense + sparse BM25) · ✓ Cross-encoder reranking · ✓ Semantic caching · ✓ Chunk metadata filtering · ✓ RAGAS evaluation baseline · ✓ Request tracing with chunk IDs · ✓ Corpus versioning · ✓ Streaming UX</blockquote><h3>#Full Code Example</h3><p>A complete minimal RAG pipeline using LangChain, OpenAI embeddings, and Chroma vector store.</p><pre>from langchain.document_loaders import DirectoryLoader<br>from langchain.text_splitter import RecursiveCharacterTextSplitter<br>from langchain.embeddings import OpenAIEmbeddings<br>from langchain.vectorstores import Chroma<br>from langchain.chat_models import ChatOpenAI<br>from langchain.prompts import ChatPromptTemplate<br>from langchain.schema.runnable import RunnablePassthrough<br>from langchain.schema.output_parser import StrOutputParser<br><br># ── 1. INDEXING PIPELINE ────────────────────────────────<br><br># Load documents<br>loader = DirectoryLoader(&quot;./docs&quot;, glob=&quot;**/*.md&quot;)<br>docs = loader.load()<br><br># Chunk with overlap<br>splitter = RecursiveCharacterTextSplitter(<br>    chunk_size=512,<br>    chunk_overlap=64,<br>    separators=[&quot;\n\n&quot;, &quot;\n&quot;, &quot;. &quot;, &quot; &quot;]<br>)<br>chunks = splitter.split_documents(docs)<br><br># Embed + store<br>embeddings = OpenAIEmbeddings(model=&quot;text-embedding-3-small&quot;)<br>vectorstore = Chroma.from_documents(<br>    chunks,<br>    embedding=embeddings,<br>    persist_directory=&quot;./chroma_db&quot;<br>)<br><br># ── 2. QUERY PIPELINE ───────────────────────────────────<br><br>retriever = vectorstore.as_retriever(<br>    search_type=&quot;mmr&quot;,         # Maximum Marginal Relevance<br>    search_kwargs={&quot;k&quot;: 6, &quot;fetch_k&quot;: 20}<br>)<br><br>prompt = ChatPromptTemplate.from_template(&quot;&quot;&quot;<br>Answer the question based only on the following context.<br>If you cannot answer from context, say &quot;I don&#39;t know.&quot;<br><br>Context:<br>{context}<br><br>Question: {question}<br>&quot;&quot;&quot;)<br><br>llm = ChatOpenAI(model=&quot;gpt-4o-mini&quot;, temperature=0)<br><br># LangChain Expression Language (LCEL) chain<br>chain = (<br>    {&quot;context&quot;: retriever, &quot;question&quot;: RunnablePassthrough()}<br>    | prompt<br>    | llm<br>    | StrOutputParser()<br>)<br><br># ── 3. RUN ──────────────────────────────────────────────<br><br>answer = chain.invoke(&quot;What is the refund policy?&quot;)<br>print(answer)</pre><p>This is the foundation. From here you’d layer in hybrid search, reranking, HyDE query enhancement, RAGAS evaluation, and production observability to build a system ready for real traffic.</p><h3>References</h3><p>1.Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks (RAG)</p><p>Lewis, P., Perez, E., Piktus, A., et al. (2020).</p><p>Introduced Retrieval-Augmented Generation (RAG), combining retrieval systems with large language models.</p><p>2.Precise Zero-Shot Dense Retrieval without Relevance Labels (HyDE)</p><p>Gao, L., Ma, X., Lin, J., &amp; Callan, J. (2023).</p><p>Introduced HyDE (Hypothetical Document Embeddings), which improves retrieval by generating a hypothetical answer before searching.</p><p>3.Self-RAG: Learning to Retrieve, Generate, and Critique through Self-Reflection</p><p>Asai, A., Wu, Z., Wang, Y., Sil, A., &amp; Hajishirzi, H. (2023).</p><p>Introduced Self-RAG, enabling models to decide when to retrieve information and verify their own responses.</p><p>4.From Local to Global: A GraphRAG Approach to Query-Focused Summarization</p><p>Edge, D., Trinh, H., Cheng, N., et al. (2024).</p><p>Introduced GraphRAG, which combines knowledge graphs with RAG for multi-hop reasoning.</p><p>5.ReAct: Synergizing Reasoning and Acting in Language Models</p><p>Yao, S., Zhao, J., Yu, D., et al. (2023).</p><p>Introduced the ReAct framework, forming the foundation for modern Agentic RAG systems.</p><p>6.Efficient and Robust Approximate Nearest Neighbor Search Using Hierarchical Navigable Small World Graphs (HNSW)</p><p>Malkov, Y. A., &amp; Yashunin, D. A. (2018).</p><p>Introduced HNSW, one of the most widely used vector search algorithms.</p><p>7.The Probabilistic Relevance Framework: BM25 and Beyond</p><p>Robertson, S., &amp; Zaragoza, H. (2009).</p><p>Presented BM25, a leading sparse retrieval algorithm used in hybrid search systems.</p><p>8.RAGAS: Automated Evaluation of Retrieval Augmented Generation</p><p>Es, S., James, J., Espinosa-Anke, L., &amp; Schockaert, S. (2024).</p><p>Introduced RAGAS, a framework for evaluating RAG systems using metrics such as faithfulness and relevance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eaa1262b71c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Attention Is All You Need]]></title>
            <link>https://medium.com/@krishnapiriyan2003/attention-is-all-you-need-bb8e93a16a71?source=rss-09539f2fc242------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb8e93a16a71</guid>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Krishnapiriyan]]></dc:creator>
            <pubDate>Tue, 09 Jun 2026 19:41:48 GMT</pubDate>
            <atom:updated>2026-06-09T19:41:48.359Z</atom:updated>
            <content:encoded><![CDATA[<p>A comprehensive breakdown of the Transformer architecture — the research paper that changed everything in artificial intelligence.</p><h3>The Revolution</h3><p>In 2017, eight Google Brain and Google Research engineers submitted a paper to NeurIPS with a deceptively simple title: <strong>“Attention Is All You Need.”</strong> The paper introduced the <strong>Transformer</strong> — an architecture built entirely on attention mechanisms, discarding recurrence and convolution entirely.</p><blockquote><em>The biggest benefit comes from how the Transformer lends itself to parallelization — making it possible to train on unprecedented scales of data.</em></blockquote><p>Within a few years, the Transformer became the backbone of virtually every significant AI system: BERT, GPT, T5, PaLM, and ultimately the large language models powering the AI revolution today. Understanding this architecture is not merely academic — it is foundational to understanding modern AI.</p><blockquote>Paper Reference</blockquote><blockquote>Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., Gomez, A. N., Kaiser, Ł., &amp; Polosukhin, I. (2017). <em>Attention is All You Need.</em> Advances in Neural Information Processing Systems, 30.</blockquote><h3>The Problem Before Transformers</h3><p>Before 2017, the dominant approaches to sequence modeling were <strong>Recurrent Neural Networks (RNNs)</strong> and <strong>Long Short-Term Memory networks (LSTMs)</strong>. These models process tokens <em>one at a time</em>, maintaining a hidden state that carries information forward through the sequence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QBgzQG5PB3ZkitUTS01unQ.png" /></figure><h3>The Core Problems of RNNs</h3><p>Sequential processing meant training could not be parallelized. On long sequences, RNNs notoriously suffered from the <strong>vanishing gradient problem</strong> — distant relationships in a sentence were effectively forgotten. LSTMs mitigated this but did not eliminate it.</p><p>Even seq2seq models with attention (Bahdanau et al., 2015) still relied on RNN encoders and decoders as their spine. The Transformer paper asked: what if attention was not supplementary — but the entire architecture?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*evAbstKAGIdLDaiOkShmeA.png" /></figure><h3>The Architecture: A High-Level View</h3><p>At the highest level, the Transformer is an <strong>encoder-decoder</strong> architecture. Given an input sequence (say, a French sentence), the encoder reads and represents it, and the decoder generates an output sequence (the English translation) one token at a time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QPqlpyZ0ikQi0l2OnwBhyA.png" /><figcaption>Figure: The complete Transformer architecture. The encoder (left) produces a rich representation; the decoder (right) attends to it while generating output.</figcaption></figure><p>The original paper stacks <strong>6 encoders</strong> and <strong>6 decoders</strong>, though this number is a hyperparameter. All encoders are structurally identical but do not share weights. The same applies to decoders.</p><blockquote>Key Insight</blockquote><blockquote>Unlike RNNs, all positions in the encoder process <em>simultaneously</em>. This is the core reason the Transformer can be trained on modern GPU hardware at previously impossible scales.</blockquote><h3>Input Embeddings</h3><p>A neural network cannot natively understand words — it operates on numbers. Every token in the input sentence is first converted into a dense vector called an <strong>embedding</strong>.</p><p>In the Transformer, each token is embedded into a vector of <strong>512 dimensions</strong> (denoted <em>d_model</em> = 512 in the paper). These embeddings are learned during training, capturing semantic relationships between words — so “king” and “queen” end up near each other in this high-dimensional space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y0fFtgHboGfDTbODm9y30A.png" /></figure><p>Importantly, embedding only happens once — at the bottom of the encoder stack. All subsequent encoder layers receive the 512-dimensional output of the layer below them.</p><h3>Positional Encoding</h3><p>Here we arrive at the Transformer’s first clever trick. Because all tokens are processed in parallel — not sequentially — the model has <em>no inherent sense of word order</em>. “The cat sat on the mat” and “The mat sat on the cat” would be identical to a naive Transformer.</p><p>The solution: inject positional information directly into the embeddings. Before entering the encoder, each embedding vector has a <strong>positional encoding vector added to it</strong> — a unique signature for each position in the sequence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bmvic_CwR8gehIUhBDPK7A.png" /></figure><p>Even dimensions use sine, odd dimensions use cosine, each at a different frequency. This gives each position a unique pattern of values across the 512 dimensions. The sinusoidal pattern has a beautiful property: <strong>relative positions can be computed via linear transformations</strong>, so the model learns to exploit positional relationships naturally.</p><blockquote>Why Sinusoids?</blockquote><blockquote>The sinusoidal approach allows the model to generalize to sequence lengths longer than those seen during training — a fixed positional embedding table cannot do this.</blockquote><h3>Self-Attention: The Core Mechanism</h3><p>This is the beating heart of the Transformer. Self-attention allows each word in the sequence to look at every other word and decide how much attention to pay to each — all in a single, parallelizable operation.</p><p>Consider the sentence: <em>“The animal didn’t cross the street because </em><strong><em>it</em></strong><em> was too tired.”</em> When encoding “it”, the model needs to understand that “it” refers to “animal”, not “street”. Self-attention makes this possible by letting “it” attend heavily to “animal”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QCAJvWQSs6pC_KnEhNJYKQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dS4XWGA4a_rIuQOoBmnCew.png" /></figure><h3>Query, Key &amp; Value Vectors</h3><p>For each token, self-attention creates three learned projections, each of 64 dimensions (<em>d_k</em> = 64):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r-HrgNYtErn4xY9qetTeSg.png" /></figure><p>These vectors are produced by multiplying the token’s embedding by three separate learned weight matrices: W_Q, W_K, and W_V, each of shape (512 × 64).</p><h3>Scaled Dot-Product Attention</h3><p>With Q, K, V in hand, attention is computed in four steps:</p><h4>1.Score</h4><p>Dot product of the query with every key: Q · Kᵀ. High dot product = high relevance between tokens.</p><h4>2.Scale</h4><p>Divide by √d_k (= √64 = 8). Prevents the dot products from growing too large, which would push softmax into regions with tiny gradients.</p><h4>3.Softmax</h4><p>Apply softmax to normalize scores into a probability distribution (all positive, summing to 1). This is the attention weight.</p><h4>4.Aggregate</h4><p>Multiply each value vector by its attention weight, then sum. The result is a context-rich representation of the current token.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OArsJndZDsaocc-ctg6vTg.png" /></figure><p>In matrix form, all tokens are processed simultaneously. The input matrix X is multiplied by the three weight matrices to produce Q, K, and V all at once — making the operation massively parallelizable on modern hardware.</p><h3>Multi-Head Attention</h3><p>A single self-attention operation captures one type of relationship at a time. But language is rich with multiple simultaneous dependencies — a word might relate to its grammatical subject, its antecedent pronoun, and a nearby modifier all at once.</p><p>The paper’s solution: run <strong>8 independent attention heads</strong> in parallel, each with its own learned Q, K, V projection matrices. Each head can specialize in a different type of relationship.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uqmRvEzbO8lWgLFW-n02dg.png" /></figure><p>Each head operates in a 64-dimensional subspace (512 / 8 = 64), so the total computation remains constant. After all 8 heads compute their outputs (Z₁…Z₈), they are concatenated into a single matrix and multiplied by a learned output weight matrix W_O to produce the final multi-head output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fdZsu098b23iIqgsDo7Dtw.png" /></figure><blockquote>Empirical Finding</blockquote><blockquote>Visualization studies show different attention heads genuinely specialize: one might track syntactic dependencies, another coreference resolution, another positional proximity. This emergent specialization is learned — not programmed.</blockquote><h3>The Encoder Block</h3><p>Each of the 6 encoder layers is structurally identical, composed of two sub-layers with a critical design pattern wrapping each:</p><h3>Sub-layer 1: Multi-Head Self-Attention</h3><p>All input tokens attend to one another simultaneously. The output is a rich, context-aware representation of each token — “animal” now has information about “tired” and “cross” baked in.</p><h3>Sub-layer 2: Position-wise Feed-Forward Network</h3><p>A two-layer fully connected network applied <em>independently</em> to each position. In the paper, this is: Linear(512 → 2048) → ReLU → Linear(2048 → 512). This step transforms the attention-mixed representations into richer features.</p><h3>Add &amp; Normalize (Residual Connections)</h3><p>Both sub-layers are wrapped in a <strong>residual connection</strong> followed by <strong>Layer Normalization</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nOz0nMbZ6lYKo69-FiQSZA.png" /></figure><p>Residual connections (borrowed from ResNets) allow gradients to flow directly through deep stacks without vanishing. Layer Normalization stabilizes training by normalizing activations within each layer. Together, they make deep Transformers trainable.</p><h3>The Decoder Block</h3><p>The decoder is structurally similar to the encoder but with a crucial addition — it has <strong>three</strong> sub-layers:</p><h4>1.Masked Self-Attention</h4><p>Like encoder self-attention, but future positions are <strong>masked to −∞</strong> before softmax. During training, this prevents the decoder from “cheating” by looking ahead at the answer.</p><h4>2.Cross-Attention</h4><p>Queries come from the decoder; Keys and Values come from the <strong>encoder output</strong>. This is how the decoder “reads” the encoded input — attention bridges the two stacks.</p><h4>3.Feed-Forward Network</h4><p>Identical in structure to the encoder’s FFN — position-wise transformation of the combined representations.</p><p>The decoder generates output <strong>autoregressively</strong>: it produces one token at a time, feeding each generated token back as input for the next step. At inference time, generation continues until a special &lt;EOS&gt; (end-of-sequence) token is produced.</p><blockquote>Key Asymmetry</blockquote><blockquote>During training, the decoder can process all target tokens in parallel thanks to teacher forcing (feeding the correct previous tokens). At inference, it must generate sequentially — but the encoder only runs once per input.</blockquote><h3>The Final Output Layer</h3><p>The decoder stack outputs a 512-dimensional vector for each generated position. To turn this into a predicted word, two final layers are applied:</p><h3>Linear Projection</h3><p>A fully connected layer projects the 512-dim vector up to the full <strong>vocabulary size</strong> — a vector of logits, one per possible output word. If the vocabulary has 37,000 tokens, the output is a 37,000-dimensional logit vector.</p><h3>Softmax</h3><p>Softmax converts the logits into a probability distribution over all vocabulary tokens. The token with the highest probability is selected as the model’s prediction for that position.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*da8J8Y-ZhS2IYeOlAYNIgg.png" /></figure><h3>Training the Transformer</h3><p>The Transformer is trained end-to-end via standard backpropagation with the <strong>Adam optimizer</strong>. The loss function is cross-entropy between the predicted probability distribution and the one-hot true label.</p><h3>Learning Rate Schedule</h3><p>The paper introduced a custom learning rate warmup schedule — rates increase linearly for the first 4,000 steps, then decay proportionally to the inverse square root of the step number. This warmup was critical for stable training.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Opi4iA6YYGJvovRr3M8NzQ.png" /></figure><h3>Regularization</h3><p>The paper applied <strong>dropout</strong> (rate 0.1) to the output of each sub-layer (before the residual add), to attention weights, and to the embedding sums. Additionally, <strong>label smoothing</strong> (ε = 0.1) replaced hard one-hot targets with soft distributions, improving calibration even at the cost of perplexity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MbLjOvT7HL64lq4Zul1zvw.png" /></figure><h3>Results &amp; Benchmarks</h3><p>On the <strong>WMT 2014 English-to-German</strong> translation task, the Transformer Big achieved <strong>28.4 BLEU</strong> — more than 2 BLEU points above the previous state-of-the-art (an ensemble of models), at a fraction of the training cost.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vE0WY-E2kUTh9AHsKPB-RQ.png" /></figure><p>The Transformer also demonstrated superior generalization: trained exclusively on translation, it transferred effectively to constituency parsing — outperforming task-specific models with minimal modification.</p><h3>The Legacy: What Came After</h3><p>The Transformer did not merely advance the state of the art — it restructured the entire research landscape of AI. Every major model of the subsequent era is either a direct Transformer variant or built on its attention mechanisms.</p><h4>1.BERT (2018)</h4><p>Encoder-only Transformer pretrained bidirectionally on masked language modeling. Dominated NLU tasks for years.</p><h4>2.GPT Series</h4><p>Decoder-only Transformers trained on next-token prediction. GPT-3 (175B params) demonstrated emergent few-shot abilities.</p><h4>3.T5 (2020)</h4><p>Text-to-Text Transfer Transformer. Unified all NLP tasks into a single seq2seq format, exploring the full encoder-decoder design.</p><h4>4.Vision Transformer</h4><p>Applied the Transformer to image patches (2020), achieving competitive performance with CNNs — proving attention is architecture-agnostic.</p><blockquote><em>The Transformer is not just a model — it is the operating system of modern AI. Everything from ChatGPT to AlphaFold, from image generation to code synthesis, runs on its foundations.</em></blockquote><h3>Modern Innovations Beyond the Original Paper</h3><p>The original architecture has been extended in numerous ways: <strong>Rotary Positional Embeddings (RoPE)</strong> replace sinusoidal encodings for better length extrapolation. <strong>Multi-Query Attention</strong> reduces memory bandwidth at inference. <strong>Flash Attention</strong> rewrites the attention computation for IO efficiency. <strong>Grouped Query Attention</strong> balances the tradeoffs. The research community has spent seven years optimizing, scaling, and reinventing this architecture — yet the core scaled dot-product attention equation remains unchanged.</p><blockquote>The Paper’s Own Words</blockquote><blockquote>The authors concluded: “We are excited about the future of attention-based models and plan to apply them to other tasks. We plan to extend the Transformer to problems involving input and output modalities other than text.” — A remarkably understated prediction of what followed.</blockquote><h3>References</h3><ol><li><a href="https://arxiv.org/abs/1706.03762?utm_source=chatgpt.com">Attention Is All You Need (Original Paper)</a><br> Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., Gomez, A. N., Kaiser, Ł., &amp; Polosukhin, I. (2017). <em>Attention Is All You Need</em>. Advances in Neural Information Processing Systems (NeurIPS 2017).</li><li><a href="https://papers.neurips.cc/paper/7181-attention-is-all-you-need.pdf?utm_source=chatgpt.com">NeurIPS Official Publication: Attention Is All You Need</a><br> Official conference publication of the Transformer architecture paper.</li><li>Ashish Vaswani et al. (2017).<br> Introduced the Transformer architecture based entirely on self-attention mechanisms.</li><li><a href="https://jalammar.github.io/illustrated-transformer/?utm_source=chatgpt.com">The Illustrated Transformer by Jay Alammar</a><br> One of the most widely used visual explanations of the Transformer architecture.</li><li><a href="https://arxiv.org/abs/1810.04805?utm_source=chatgpt.com">BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding</a><br> Devlin, J., Chang, M.-W., Lee, K., &amp; Toutanova, K. (2018). Introduced BERT, an encoder-only Transformer model.</li><li><a href="https://cdn.openai.com/better-language-models/language_models_are_unsupervised_multitask_learners.pdf?utm_source=chatgpt.com">Language Models are Unsupervised Multitask Learners (GPT-2)</a><br> Demonstrated the power of large-scale decoder-only Transformers.</li><li><a href="https://arxiv.org/abs/1910.10683?utm_source=chatgpt.com">Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer (T5)</a><br> Raffel, C. et al. (2019). Unified NLP tasks into a text-to-text framework.</li><li><a href="https://arxiv.org/abs/2010.11929?utm_source=chatgpt.com">An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale (Vision Transformer)</a><br> Dosovitskiy, A. et al. (2020). Extended Transformers to computer vision.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb8e93a16a71" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your Model Is Cheating — 
And You Don’t Even Know It Yet]]></title>
            <link>https://medium.com/@krishnapiriyan2003/your-model-is-cheating-and-you-dont-even-know-it-yet-81bca11d0ce8?source=rss-09539f2fc242------2</link>
            <guid isPermaLink="false">https://medium.com/p/81bca11d0ce8</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[bias-detection]]></category>
            <category><![CDATA[lime]]></category>
            <category><![CDATA[responsible-ai]]></category>
            <dc:creator><![CDATA[Krishnapiriyan]]></dc:creator>
            <pubDate>Mon, 08 Jun 2026 19:25:29 GMT</pubDate>
            <atom:updated>2026-06-08T19:25:29.701Z</atom:updated>
            <content:encoded><![CDATA[<p>Based on Part 3 — Explaining Model Predictions — with the Amazon hiring scandal, LIME from scratch, and live debugging</p><p>In 2016, Amazon scrapped a secret AI hiring tool. They had spent years training it to screen job applicants. It worked well in testing — high accuracy on held-out resumes.</p><p>But there was a problem: the model was penalising resumes that included the word “women’s” — as in “women’s chess club” or “women’s university.” It had learned that historically successful candidates at a male-dominated company did not use that word, so it learned to rank those resumes down.</p><p>The model was technically functional. It was doing exactly what it optimised for. It just learned to do it in a deeply biased, discriminatory way. And nobody knew — until someone looked inside the black box.</p><h3>Why High Accuracy Is Not Enough to Trust a Model</h3><p>When a model achieves 94% accuracy, it means it gets 94 out of 100 predictions right on the test set. But accuracy says nothing about <em>why</em> the model makes the predictions it does. And models are very creative at finding the wrong reason for the right answer.</p><p>Case 1 — The X-Ray Classifier</p><blockquote>A model classified chest X-rays for pneumonia with 90% accuracy. It had also learned to recognise which hospitals used which X-ray equipment — and pneumonia rates varied by hospital. The model partly predicted “which hospital” instead of “pneumonia.” It worked on training data. Failed on X-rays from new hospitals.</blockquote><p>Case 2 — The Tank Detector</p><blockquote>A model detected tanks in photos with near-perfect accuracy. It turned out that all photos WITH tanks were taken on cloudy days, and all WITHOUT were sunny. The model classified weather, not tanks. It would fail immediately in real deployment.</blockquote><p>Case 3 — The Length-Based Sentiment Model</p><blockquote>A movie review classifier achieved 88% accuracy. Analysis revealed that review LENGTH was a strong feature — angry people write more. The model was partly classifying review length, not sentiment.</blockquote><p><em>‘In every case, the model found a shortcut that correlated with the correct answer in training but would not generalise to the real world.’</em></p><h3>LIME: Understanding Any Black Box in Five Steps</h3><p>LIME (<strong>L</strong>ocal <strong>I</strong>nterpretable <strong>M</strong>odel-<strong>A</strong>gnostic <strong>E</strong>xplanations) explains why a model made a specific prediction — for any model, any architecture.</p><blockquote><strong>The Core Idea</strong></blockquote><blockquote>If you want to know WHY a model classified a specific piece of text the way it did, try removing words one at a time and watch how the prediction changes. Words whose removal changes the prediction the most were the most responsible for that prediction.</blockquote><ol><li>Pick the prediction to explain</li></ol><p>Email: “I’ve been waiting 3 weeks for my refund and nobody responds to my calls.” → Predicted: COMPLAINT (97%). Question: WHY?</p><p>2.Generate ~500 modified versions of the input</p><p>Randomly hide words in the email: “I’ve been waiting ___ weeks for my refund ___…” Each version has different words removed. 500 variations total.</p><p>3.Run all 500 versions through the black-box model</p><p>Observe: removing “refund” drops confidence from 97% → 71%. Removing “unacceptable” drops 97% → 74%. Removing “completely” barely changes anything: 97% → 93%.</p><p>4.Fit a simple linear model to the 500 results</p><p>Which word removals predict the biggest drop in “complaint” confidence? The linear model’s weights ARE the explanation.</p><p>5.Read the explanation</p><p>“refund” (−0.26), “unacceptable” (−0.23), “nobody” (−0.19), “responding” (−0.19), “weeks” (−0.12), “completely” (−0.04). The model is reading the right things — not cheating.</p><h3>How to Catch a Cheating Model</h3><p>When you run LIME on a politics/sports classifier and ask it to explain why “Senator Chen will host her campaign event at Lincoln Field tonight” was classified as SPORTS, you might see:</p><blockquote>Cheating detected</blockquote><blockquote>“Lincoln Field” → strong SPORTS predictor (it’s a stadium name)<br>“Senator” → weak POLITICS predictor<br>“campaign” → weak POLITICS predictor</blockquote><blockquote>The model saw a stadium name and jumped to “sports.” Without LIME, you’d see 91% accuracy and feel great. With LIME, you fix the training data.</blockquote><h3>Running LIME in Python</h3><pre># pip install lime fasttext numpy<br>import fasttext, numpy as np<br>from lime.lime_text import LimeTextExplainer<br><br>model = fasttext.load_model(&#39;email_classifier.bin&#39;)<br>LABELS = [&#39;complaint&#39;, &#39;compliment&#39;, &#39;question&#39;, &#39;purchase&#39;]<br><br>def predict_proba(texts):<br>    results = []<br>    for text in texts:<br>        label_probs = {}<br>        labels, probs = model.predict(text.lower(), k=4)<br>        for l, p in zip(labels, probs):<br>            label_probs[l.replace(&#39;__label__&#39;, &#39;&#39;)] = p<br>        results.append([label_probs.get(l, 0.0) for l in LABELS])<br>    return np.array(results)<br><br>explainer = LimeTextExplainer(class_names=LABELS)<br><br>email = &quot;I have been waiting 3 weeks for my refund and nobody responds.&quot;<br><br>exp = explainer.explain_instance(<br>    email, predict_proba,<br>    num_features=8, num_samples=500, labels=[0]<br>)<br><br>for word, weight in exp.as_list(label=0):<br>    bar = &quot;█&quot; * int(abs(weight) * 30)<br>    direction = &quot;→ COMPLAINT&quot; if weight &gt; 0 else &quot;↓ away&quot;<br>    print(f&quot;{word:15} {bar:20} {weight:+.3f} {direction}&quot;)<br><br># Also saves as visual HTML:<br># exp.show_in_notebook(text=True)</pre><blockquote><strong>The Three Questions to Ask With Every Production Model</strong></blockquote><blockquote>1. Are the highlighted words the ones I EXPECT to drive this label?<br>2. Do the highlighted words make sense across 20+ different examples?<br>3. Are there words I should NEVER see in the explanations (names, demographics, irrelevant metadata)?</blockquote><blockquote>Model explainability is not optional. It is the difference between a model you can trust and a model that will embarrass you in production.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=81bca11d0ce8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Natural Language Processing:
The Complete Guide]]></title>
            <link>https://medium.com/@krishnapiriyan2003/natural-language-processing-the-complete-guide-255307e6ca7e?source=rss-09539f2fc242------2</link>
            <guid isPermaLink="false">https://medium.com/p/255307e6ca7e</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[gpt]]></category>
            <dc:creator><![CDATA[Krishnapiriyan]]></dc:creator>
            <pubDate>Mon, 08 Jun 2026 19:23:21 GMT</pubDate>
            <atom:updated>2026-06-08T19:41:38.664Z</atom:updated>
            <content:encoded><![CDATA[<p>Every concept, library, model and architecture — from raw text to enterprise AI systems</p><p>atural Language Processing (NLP) is one of the most exciting fields in Artificial Intelligence. It enables computers to understand, interpret, generate, and interact with human language. Every day, millions of people use NLP-powered applications without realising it — ChatGPT, Google Translate, email spam filters, Siri, and every search engine you have ever used.</p><p>NLP combines knowledge from computer science, artificial intelligence, machine learning, deep learning, linguistics, mathematics, and statistics. The primary goal is to bridge the gap between human language and machine understanding.</p><blockquote><strong>The Fundamental Problem</strong></blockquote><blockquote>Humans communicate in natural language. Computers understand only numbers.</blockquote><blockquote><strong>Human input:</strong> “I love studying NLP”<br><strong>Computer sees:</strong> [101, 2054, 3012, 202, 405]</blockquote><blockquote>NLP’s entire job is converting human language into mathematical representations that machines can process.</blockquote><h3>Why NLP Is Important</h3><p>NLP powers a surprisingly large fraction of every modern software product. If you are building anything that involves human text — emails, support tickets, documents, social media posts, voice commands — you are building an NLP system.</p><p><strong>Chatbots</strong></p><p>Conversational AI that understands and responds to user queries</p><p><strong>Translation</strong></p><p>Automatic translation across 1000+ language pairs</p><p><strong>Search Engines</strong></p><p>Semantic search that understands intent, not just keywords</p><p>️<strong>Sentiment Analysis</strong></p><p>Classify opinions, reviews, and social posts automatically</p><p><strong>Healthcare</strong></p><p>Extract diagnoses, drugs, and symptoms from clinical notes</p><p><strong>Fraud Detection</strong></p><p>Detect suspicious patterns in transactions and communications</p><p><strong>AI Tutors</strong></p><p>Personalised education powered by conversational AI</p><p><strong>Recommendations</strong></p><p>Suggest content, products, and articles from text signals</p><h3>The Complete NLP Pipeline</h3><p>A modern NLP system follows a series of well-defined stages. Raw text enters at the top. A usable prediction or generated output emerges at the bottom. Every stage is a solved sub-problem.</p><pre>Raw Text<br>↓<br>Text Cleaning<br>↓<br>Tokenization<br>↓<br>Stop Word Removal<br>↓<br>Stemming / Lemmatization<br>↓<br>Feature Extraction<br>↓<br>ML / Deep Learning<br>↓<br>Prediction or Output</pre><p>Each stage adds a layer of structure to raw text. By the time text reaches the final ML model, it has been transformed from a chaotic string of characters into a clean, structured numerical representation that captures its meaning.</p><blockquote>Key insight</blockquote><blockquote>No single stage “understands” language. Together, they build a representation rich enough that statistical models can extract meaning from it.</blockquote><p>The pipeline is not one-size-fits-all. Simple applications (spam detection) may need only steps 1–5. Advanced systems (GPT-4, Claude) run all stages inside a single Transformer model.</p><p><strong>Pipeline Stage 1</strong></p><h3>Text Cleaning</h3><p>Raw text from the real world is always messy. It contains punctuation, emojis, HTML tags, URLs, extra whitespace, and inconsistent capitalisation. All of this is noise for a machine learning model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/917/1*IrdqtkSB8_P3zlQzpqUqHQ.png" /></figure><pre>import re<br><br>def clean_text(text: str) -&gt; str:<br>    text = text.lower()                              # lowercase<br>    text = re.sub(r&#39;https?://\S+&#39;, &#39;&#39;, text)       # remove URLs<br>    text = re.sub(r&#39;&lt;[^&gt;]+&gt;&#39;, &#39;&#39;, text)           # remove HTML tags<br>    text = re.sub(r&#39;[^\w\s]&#39;, &#39;&#39;, text)             # remove punctuation<br>    text = re.sub(r&#39;[^\x00-\x7F]+&#39;, &#39;&#39;, text)       # remove emojis<br>    text = re.sub(r&#39;\s+&#39;, &#39; &#39;, text).strip()         # collapse whitespace<br>    return text<br><br>print(clean_text(&quot;I LOVE NLP!!! 😍 Visit www.example.com&quot;))<br># → &quot;i love nlp  visit&quot;def clean_text(text: str) -&gt; str:<br>    text = text.lower()                              # lowercase<br>    text = re.sub(r&#39;https?://\S+&#39;, &#39;&#39;, text)       # remove URLs<br>    text = re.sub(r&#39;&lt;[^&gt;]+&gt;&#39;, &#39;&#39;, text)           # remove HTML tags<br>    text = re.sub(r&#39;[^\w\s]&#39;, &#39;&#39;, text)             # remove punctuation<br>    text = re.sub(r&#39;[^\x00-\x7F]+&#39;, &#39;&#39;, text)       # remove emojis<br>    text = re.sub(r&#39;\s+&#39;, &#39; &#39;, text).strip()         # collapse whitespace<br>    return text</pre><p><strong>Pipeline Stage 2</strong></p><h3>Tokenization</h3><p>Tokenization breaks text into smaller units called tokens. There are three major approaches, each suited to different use cases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/917/1*G1OjlBismigYXLkvjuHFCA.png" /></figure><blockquote>Why Subword Tokenization?</blockquote><blockquote>If a model has never seen “unforeseeable” during training, word tokenization fails. Subword tokenization breaks it into <strong>“un”</strong> + <strong>“fore”</strong> + <strong>“see”</strong> + <strong>“able”</strong> — all known pieces. The model can still understand the word even though it has never seen it whole. This is how GPT-4 handles technical jargon, scientific terms, and words in any language.</blockquote><p><strong>Pipeline Stage 3</strong></p><h3>Stop Word Removal</h3><p>Stop words are high-frequency words that contribute little meaning to statistical analysis: “the”, “is”, “am”, “are”, “was”, “were”, “of”, “to”, “a”, “an”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/917/1*GkRYpwVUK64oNajSU0TqCA.png" /></figure><p><strong>Pipeline Stage 4</strong></p><h3>Stemming</h3><p>Stemming reduces words to their root forms by removing suffixes mechanically. The most popular algorithm is the <strong>Porter Stemmer</strong>.</p><blockquote>Porter Stemmer Examples</blockquote><blockquote>playing → <strong>play</strong> | played → <strong>play</strong> | plays → <strong>play</strong><br>studying → studi ← Not a real word! (Stemming limitation)</blockquote><p><strong>Pipeline Stage 5</strong></p><h3>Lemmatization</h3><p>Lemmatization is more intelligent than stemming. Instead of removing suffixes blindly, it uses dictionaries and grammar rules to find the actual base form.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*wn-cemuMhqZHzKnQbtd9EA.png" /></figure><p><strong>Pipeline Stage 6</strong></p><h3>Part-of-Speech (POS) Tagging</h3><p>POS tagging identifies the grammatical role of each word — noun, verb, adjective, adverb, preposition, and so on. This enables grammar checking, machine translation, and information extraction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*HXavh9QFjRkxeVIBU-mBLA.png" /></figure><p><strong>Pipeline Stage 7</strong></p><h3>Named Entity Recognition (NER)</h3><p>NER identifies and classifies important real-world entities: people, organisations, locations, dates, products, and monetary values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*MnaCqrnNRxKK8p0GzzTFWw.png" /></figure><h3>Feature Extraction</h3><p>Computers cannot understand words directly. Words must be converted into numbers. This is called <strong>feature extraction</strong> — the bridge between text preprocessing and machine learning.</p><p><strong>Feature Method 1</strong></p><h3>Bag of Words (BoW)</h3><p>One of the earliest NLP techniques. Count how many times each word from the vocabulary appears in a document. Ignore word order entirely.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*NyuhF5KSRN_GXZ2dYyzZvw.png" /></figure><p><strong>Feature Method 2</strong></p><h3>TF-IDF (Term Frequency-Inverse Document Frequency)</h3><p>TF-IDF improves BoW by measuring word importance. Words that appear frequently in a document but rarely in other documents get high scores. Common words like “the” appear everywhere and get very low scores.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*ugw8pC-CObEWii4yTncuJQ.png" /></figure><p><strong>Feature Method 3</strong></p><h3>Word Embeddings</h3><p>Word embeddings represent words as dense numerical vectors in a high-dimensional semantic space. Words with similar meanings end up with nearby vectors. This is the key innovation that made modern NLP possible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/923/1*_upsCpCawPJNOEFc_gtMIg.png" /></figure><p><strong>Embedding Models</strong></p><h3>Word2Vec · GloVe · FastText</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*n9uSDe9DMIFu1NuZemx1nw.png" /></figure><blockquote><strong>FastText advantage</strong></blockquote><blockquote>Word2Vec and GloVe fail on words they have never seen. FastText breaks every word into character n-grams, so “programmer”, “programming”, and “programmed” all share subword features. It handles misspellings and new technical jargon that would confuse other models.</blockquote><h3>Machine Learning for NLP</h3><p>Before deep learning, NLP relied heavily on traditional machine learning algorithms. These methods still work extremely well for many real-world applications — especially when data is limited.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*16H-Qumx6L6-UMgb-PjYvw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*5Fpc90Voj0IHr8OiIWcPxg.png" /></figure><h3>Deep Learning in NLP</h3><p>Traditional machine learning requires manual feature engineering — a human must decide which features (words, n-grams, TF-IDF scores) to feed the model. Deep learning removes this requirement. It <strong>automatically learns language patterns</strong> directly from raw text.</p><p><strong>Deep Learning Models</strong></p><h3>RNN · LSTM · GRU</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*mx0VjIdSXPQr_eNfCL7jwA.png" /></figure><p><strong>The Breakthrough</strong></p><h3>The Transformer Architecture</h3><p>The Transformer, introduced in “Attention is All You Need” (Vaswani et al., 2017), is the single most important architectural breakthrough in the history of NLP. It abandoned sequential processing entirely and replaced it with <strong>self-attention</strong> — allowing every word to directly attend to every other word simultaneously.</p><blockquote><strong>RNN / LSTM :-</strong>Sequential · Cannot parallelise · Memory bottleneck · Forgets early context</blockquote><blockquote><strong>Transformer :-</strong>Parallel · All words simultaneously · Direct long-range connections · Infinitely scalable</blockquote><blockquote><strong>Self-Attention — The Key Innovation</strong></blockquote><blockquote>Sentence: “The animal didn’t cross the street because <strong>it</strong> was tired.”</blockquote><blockquote>What does “it” refer to? Self-attention lets the model directly connect “it” to “animal” — not “street” — by learning which word pairs have the strongest relationship. This is computed for every word in parallel across the entire sentence simultaneously. No forgetting. No bottleneck.</blockquote><p>Transformer Architecture</p><pre>Input Tokens → Embeddings + Positional Encoding<br>                        ↓<br>              ┌─────────────────────────────────┐<br>              │  Multi-Head Self-Attention       │<br>              │  ↓ Residual Connection           │<br>              │  ↓ Layer Normalisation           │<br>              ├─────────────────────────────────┤<br>              │  Feed-Forward Network            │<br>              │  ↓ Residual Connection           │<br>              │  ↓ Layer Normalisation           │<br>              └─────────────────────────────────┘<br>                        ↓  (repeat N layers)<br>              Output Representations</pre><p><strong>Encoder Model</strong></p><h3>BERT — Bidirectional Encoder Representations from Transformers</h3><p>Developed by Google in 2018. BERT’s key idea: read context from <em>both</em> directions simultaneously — left-to-right AND right-to-left — rather than just left-to-right like previous models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/917/1*9etrPaRnYYGJw2OS0ny06w.png" /></figure><p><strong>Decoder Model</strong></p><h3>GPT — Generative Pre-trained Transformer</h3><p>GPT uses a decoder-only Transformer architecture. Its training objective is simple: predict the next word. After training on hundreds of billions of tokens, predicting the next word extremely well turns out to be the same as appearing to understand language.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/913/1*4iV0qi_T4YVpKHAiCBksQA.png" /></figure><h3>Large Language Models (LLMs)</h3><p>LLMs are GPT-style models trained at extreme scale — hundreds of billions of parameters, trillions of tokens of training data, thousands of GPUs running for months. The scale difference produces qualitative improvements: LLMs can reason, code, translate, summarise, and converse in a way smaller models cannot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*zXXeB-FXsGTCPSJRK9PZ3g.png" /></figure><h3>10 Key NLP Libraries</h3><p><strong>NLTK :- </strong>Best for learning NLP — tokenization, stemming, POS tagging, corpora</p><p><strong>spaCy:- </strong>Production NLP — NER, dependency parsing, fast pipeline processing</p><p><strong>scikit-learn:- </strong>TF-IDF, BoW, Naive Bayes, SVM — the classic ML stack</p><p><strong>Gensim:- </strong>Word2Vec, GloVe, topic modelling with LDA</p><p><strong>PyTorch:- </strong>Deep learning research — custom models, Transformers, gradients</p><p><strong>TensorFlow:- </strong>Enterprise deep learning — production deployment, TF Serving</p><p><strong>Hugging Face:- </strong>BERT, GPT, T5, RoBERTa — the hub for pre-trained Transformers</p><p><strong>LangChain:- </strong>AI agents, chatbot pipelines, RAG systems, tool use</p><p><strong>LlamaIndex:- </strong>Document Q&amp;A, Retrieval-Augmented Generation (RAG)</p><p><strong>FAISS:- </strong>Vector similarity search — billion-scale nearest neighbour retrieval</p><h3>Modern Enterprise NLP Architecture</h3><p>A production AI system today combines all the components from this guide into one end-to-end architecture: semantic search, retrieval, and generation working together. This is called <strong>RAG — Retrieval-Augmented Generation</strong>.</p><pre>                                User<br>                                Query input<br>                                  ↓<br>                                Frontend<br>                                React / Mobile<br>                                  ↓<br>                                Backend<br>                                FastAPI / Django<br>                                  ↓<br>                                Embedder<br>                                Sentence Transformers<br>                                  ↓<br>                                Vector DB<br>                                FAISS / Pinecone<br>                                  ↓<br>                                Retriever<br>                                Top-K docs<br>                                  ↓<br>                                LLM<br>                                GPT / Llama / Claude<br>                                  ↓<br>                                Response<br>                                Generated answer</pre><p>This architecture powers</p><p>Intelligent chatbots · Document assistants · AI search engines · Enterprise knowledge systems · AI tutors · Medical Q&amp;A systems · Legal document analysis · Customer support automation</p><h3>The Evolution of NLP — Timeline</h3><p>From simple word counting to trillion-parameter language models — NLP has advanced further in the last 10 years than in the previous 60.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*GYy-WG49tSIBKHmOBHVeUg.png" /></figure><h4>1.1950s–1980s · Rule-Based NLP</h4><p>Hand-Written Rules</p><p>Linguists wrote thousands of grammar rules by hand. Systems could only handle the sentences they were explicitly programmed for. Any new sentence structure caused failure.</p><h4>2.1990s–2000s · Statistical NLP</h4><p>Bag of Words, N-grams, Naive Bayes</p><p>Probabilistic models replaced rules. Spam filters, search engines, and machine translation made their first practical appearances. Models learned from data — but required heavy feature engineering.</p><h4>3.2013–2016 · Word Embeddings Era</h4><p>Word2Vec, GloVe, FastText</p><p>Words became dense vectors. Semantic relationships (King − Man + Woman = Queen) could be computed mathematically. Models gained a form of “understanding” of word meaning for the first time.</p><h4>4.2017 · The Transformer Revolution</h4><p>“Attention is All You Need”</p><p>Vaswani et al. published the Transformer architecture. Sequential processing was abandoned. Self-attention allowed every word to connect to every other word simultaneously. The entire field changed overnight.</p><h4>5.2018–2020 · Pre-trained Models</h4><p>BERT, GPT-2, RoBERTa, T5</p><p>Large models pre-trained on massive text datasets could be fine-tuned on small task-specific datasets with state-of-the-art results. Transfer learning came to NLP.</p><h4>6.2020–2022 · Scale Changes Everything</h4><p>GPT-3, PaLM, Chinchilla</p><p>175 billion parameters. Models exhibited “emergent” capabilities — reasoning, few-shot learning, code generation — that smaller models did not have. Scale produced qualitative leaps.</p><h4>7.2022–Present · The LLM Era</h4><p>ChatGPT, Claude, Gemini, Llama</p><p>RLHF (Reinforcement Learning from Human Feedback) aligned LLMs to follow instructions and be helpful. ChatGPT reached 100 million users in 2 months — the fastest product adoption in history. RAG systems extended LLMs with external knowledge.</p><h3>Conclusion</h3><p>Natural Language Processing has evolved from simple text-processing techniques like tokenization and stemming to powerful Transformer-based Large Language Models capable of reasoning, conversation, coding, and content generation.</p><pre>Text Processing (Tokenization, Stemming)<br>            ↓<br>Feature Engineering (BoW, TF-IDF)<br>            ↓<br>Machine Learning (Naive Bayes, SVM)<br>            ↓<br>Word Embeddings (Word2Vec, GloVe)<br>            ↓<br>Deep Learning (RNN, LSTM)<br>            ↓<br>Transformers (Attention is All You Need)<br>            ↓<br>BERT &amp; GPT (Pre-trained Models)<br>            ↓<br>LLMs (ChatGPT, Claude, Gemini)<br>            ↓<br>RAG &amp; AI Agents · Enterprise AI Systems</pre><p>Mastering these concepts provides the foundation for building modern AI applications — chatbots, recommendation systems, search engines, intelligent assistants, and next-generation software products. Every layer builds on the last. Every concept connects to the others.</p><h3>References &amp; Further Reading</h3><p>The concepts, architectures, models, and techniques discussed in this article are based on the following books, research papers, and official documentation.</p><h3>Foundational NLP Books</h3><p>1.Speech and Language Processing (Daniel Jurafsky &amp; James H. Martin)</p><ul><li><a href="https://web.stanford.edu/~jurafsky/slp3/">https://web.stanford.edu/~jurafsky/slp3/</a></li></ul><p>2.Foundations of Statistical Natural Language Processing</p><ul><li><a href="https://mitpress.mit.edu/9780262133609/foundations-of-statistical-natural-language-processing/">https://mitpress.mit.edu/9780262133609/foundations-of-statistical-natural-language-processing/</a></li></ul><p>3.Introduction to Information Retrieval</p><ul><li><a href="https://nlp.stanford.edu/IR-book/">https://nlp.stanford.edu/IR-book/</a></li></ul><h3>Landmark Research Papers</h3><h3>1.Word2Vec (Google, 2013)</h3><p>Efficient Estimation of Word Representations in Vector Space</p><ul><li><a href="https://arxiv.org/abs/1301.3781">https://arxiv.org/abs/1301.3781</a></li></ul><h3>2.GloVe (Stanford, 2014)</h3><p>Global Vectors for Word Representation</p><ul><li><a href="https://aclanthology.org/D14-1162/">https://aclanthology.org/D14-1162/</a></li></ul><h3>3.FastText (Meta, 2016)</h3><p>Enriching Word Vectors with Subword Information</p><ul><li><a href="https://arxiv.org/abs/1607.04606">https://arxiv.org/abs/1607.04606</a></li></ul><h3>4.LSTM (1997)</h3><p>Long Short-Term Memory</p><ul><li><a href="https://www.bioinf.jku.at/publications/older/2604.pdf">https://www.bioinf.jku.at/publications/older/2604.pdf</a></li></ul><h3>5.Transformer (2017)</h3><p>Attention Is All You Need</p><ul><li><a href="https://arxiv.org/abs/1706.03762">https://arxiv.org/abs/1706.03762</a></li></ul><h3>6.BERT (Google, 2018)</h3><p>BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding</p><ul><li><a href="https://arxiv.org/abs/1810.04805">https://arxiv.org/abs/1810.04805</a></li></ul><h3>7.GPT-3 (OpenAI, 2020)</h3><p>Language Models are Few-Shot Learners</p><ul><li><a href="https://openai.com/index/language-models-are-few-shot-learners/">https://openai.com/index/language-models-are-few-shot-learners/</a></li></ul><h3>Official NLP Libraries &amp; Frameworks</h3><p>1.NLTK</p><p><a href="https://www.nltk.org/">NLTK</a></p><p>2.spaCy</p><p><a href="https://spacy.io/">spaCy · Industrial-strength Natural Language Processing in Python</a></p><p>3.Scikit-Learn</p><p><a href="https://scikit-learn.org/">scikit-learn</a></p><p>4.PyTorch</p><p><a href="https://pytorch.org/">https://pytorch.org/</a></p><p>5.TensorFlow</p><p><a href="https://www.tensorflow.org/">https://www.tensorflow.org/</a></p><p>6.Hugging Face Transformers</p><p><a href="https://huggingface.co/docs/transformers">Transformers · Hugging Face</a></p><p>7.Gensim</p><p><a href="https://radimrehurek.com/gensim/">https://radimrehurek.com/gensim/</a></p><h3>8.LangChain</h3><p><a href="https://www.langchain.com/">LangChain: Observe, Evaluate, and Deploy Reliable AI Agents</a></p><p>9.LlamaIndex</p><p><a href="https://www.llamaindex.ai/">LlamaIndex | AI Agents for Document OCR + Workflows</a></p><p>10.FAISS</p><p><a href="https://faiss.ai/">https://faiss.ai/</a></p><h3>Recommended Courses</h3><p>1.Stanford CS224N — Natural Language Processing with Deep Learning</p><p><a href="https://web.stanford.edu/class/cs224n/">Stanford CS 224N | Natural Language Processing with Deep Learning</a></p><p>2.Hugging Face NLP Course</p><p><a href="https://huggingface.co/learn/nlp-course">https://huggingface.co/learn/nlp-cours</a>e/</p><p>3.DeepLearning.AI NLP Specialization</p><p><a href="https://www.deeplearning.ai/courses/natural-language-processing-specialization/">https://www.deeplearning.ai/courses/natural-language-processing-specialization</a>/</p><h3>Additional Reading</h3><p>1.OpenAI Research<br><a href="https://openai.com/research/">https://openai.com/research/</a></p><p>2.Google AI Research<br><a href="https://research.google/">https://research.google/</a></p><p>3.Anthropic Research<br><a href="https://www.anthropic.com/research">https://www.anthropic.com/research</a></p><p>4.Meta AI Research<br><a href="https://ai.meta.com/research/">https://ai.meta.com/research/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=255307e6ca7e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Trying to “Understand” Text.
Just Sort It.]]></title>
            <link>https://medium.com/@krishnapiriyan2003/stop-trying-to-understand-text-just-sort-it-9521c806f5c5?source=rss-09539f2fc242------2</link>
            <guid isPermaLink="false">https://medium.com/p/9521c806f5c5</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[text-classification]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[bag-of-words]]></category>
            <dc:creator><![CDATA[Krishnapiriyan]]></dc:creator>
            <pubDate>Sun, 07 Jun 2026 19:19:10 GMT</pubDate>
            <atom:updated>2026-06-07T19:19:10.749Z</atom:updated>
            <content:encoded><![CDATA[<p>Based on Part 2 — Text Classification is Your Secret Weapon — with brand-new scenarios and a hotel review example</p><p>Imagine you hired a new employee. Their job: read every customer email that comes in and decide if it is a complaint, a compliment, a question, or a purchase inquiry. Easy enough for one human. Now imagine 50,000 emails a day.</p><p>You need 20 employees working in shifts. Cost: $1.2 million a year. Or — you spend two days building a text classifier, train it overnight on your existing labeled emails, and it handles all 50,000 emails for free, 24 hours a day, faster than any human, with 93% accuracy.</p><p><strong><em>“The kind of results you can get with text classification compared to the development effort is off the charts.”</em></strong></p><h3>The Insight That Changes Everything</h3><p>In Article 1, we spent enormous effort parsing grammar. That approach is precise but complex. Real-world text is messy — users abbreviate, misspell, use emoji and slang. The insight behind text classification is simpler and more radical:</p><blockquote><strong>The Key Reframe</strong></blockquote><blockquote>You do NOT need to understand what text means. You just need to know which bucket it belongs in. The question shifts from “what does this text mean?” (impossibly hard) to “which label fits this text?” (very doable with statistics).</blockquote><h3>How the Brain of a Text Classifier Works</h3><p>We use a hotel review example. Guests leave reviews with star ratings (1–5). We want to predict the star rating purely from the text.</p><p>1.Collect labeled training data</p><p>200,000 past hotel reviews where guests wrote text AND left a star rating. That pair (text → star) is your training data.</p><p>2.Represent each review as a word count vector (Bag of Words)</p><p>Count how many times each word appears. Ignore word order completely. “The room was spacious and clean” → {room:1, spacious:1, clean:1, and:1, the:1, was:1}. Words are thrown in a bag and counted.</p><p>3.Train a logistic regression — it learns word weights</p><p>The model learns which words predict high vs. low star ratings. “Excellent” → +0.94 (5-star signal). “Mold” → −0.91 (1-star signal). “The” → ≈0.00 (irrelevant noise).</p><p>4.Predict on new, unseen reviews</p><p>Multiply each word’s count by its learned weight, sum it all up, and get a probability for each star rating. Fast. Scalable. Works 24/7.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*NOulY_iNaDMv4YYIruCj1g.png" /></figure><h3>Why Does “Dumb” Counting Beat “Smart” Grammar Parsing?</h3><p><strong>Reason 1 — It handles broken language.</strong> Real hotel reviews: “AMAZING!!!! best sleep ever worth every penny!!!” — no grammar, no structure. A bag-of-words classifier reads it without breaking a sweat.</p><p><strong>Reason 2 — It works across languages.</strong> Train on enough German reviews and the model learns that “schrecklich” correlates with 1-star without knowing a word of German grammar.</p><p><strong>Reason 3 — It is ludicrously fast to train.</strong> fastText trains on 4 million reviews in under 10 minutes on a laptop. No GPU needed.</p><h3>Five Real Problems You Can Solve With This Today</h3><p><strong>Customer Email Triage:-</strong>Route complaint / question / compliment / refund emails automatically. Zero manual triaging.</p><p><strong>Social Media Monitorin:-</strong>Real-time alert when brand sentiment turns negative across 10,000 tweets per day.</p><p><strong>Job Application Screening:-</strong>Automatically rank 500 applications. Hiring manager reads the top 50. Saves 20 hours per role.</p><p><strong>News Categorization:-</strong>Tag incoming articles as politics / business / sports / science automatically.</p><p><strong>App Store Review Routing:-</strong>Bug reports → Engineering. Feature requests → Product. Praise → Marketing wall of fame.</p><p><strong>Content Moderation:-</strong>Auto-remove the clearest violations. Send borderline cases to human moderators.</p><h3>Building It: The Complete fastText Walkthrough</h3><pre># ── STEP 1: Format your data ──────────────────────────<br># One line per example: __label__CATEGORY  text of email<br>__label__complaint  I have been waiting 3 weeks for my refund and nobody responds<br>__label__question   What is your return policy for opened items?<br>__label__purchase   I want to buy 5 units of SKU-3392, please advise<br>__label__compliment Your customer service rep Sarah was absolutely wonderful<br><br># ── STEP 2: Normalize text (Python) ──────────────────<br>import re<br><br>def normalize(text):<br>    text = text.lower()<br>    text = re.sub(r&#39;([^\w\s])&#39;, r&#39; \1 &#39;, text)   # space around punctuation<br>    text = re.sub(r&#39;\s+&#39;, &#39; &#39;, text).strip()      # collapse whitespace<br>    return text<br><br># ── STEP 3: Train ─────────────────────────────────────<br>$ fasttext supervised \<br>    -input emails_train.txt \<br>    -output email_classifier \<br>    -lr 0.5 -epoch 25 -wordNgrams 2 -dim 100<br><br># -wordNgrams 2: treats word PAIRS as features<br># &quot;not good&quot; pair → negative signal (not just &quot;good&quot; alone)<br><br># ── STEP 4: Test accuracy ─────────────────────────────<br>$ fasttext test email_classifier.bin emails_test.txt<br># P@1  0.94  ← 94% accuracy<br><br># ── STEP 5: Python predictions ────────────────────────<br>import fasttext<br><br>model = fasttext.load_model(&#39;email_classifier.bin&#39;)<br><br>email = &quot;I ordered the blue jacket two weeks ago and it still hasn&#39;t arrived.&quot;<br>labels, probs = model.predict(email, k=2)<br>print(labels[0], f&quot;confidence: {probs[0]:.1%}&quot;)<br># __label__complaint   confidence: 96.8%</pre><blockquote><strong>⚠ The Golden Rule</strong></blockquote><blockquote>Your training data must look like your production data. If your training emails are formal English and your real emails are casual with abbreviations, the model will fail. The quality of the model is almost entirely determined by the quality of your labeled data.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9521c806f5c5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Teaching a Computer to Read:
The Eight Things Humans Do Without Thinking]]></title>
            <link>https://medium.com/@krishnapiriyan2003/teaching-a-computer-to-read-the-eight-things-humans-do-without-thinking-5616f29bb4ef?source=rss-09539f2fc242------2</link>
            <guid isPermaLink="false">https://medium.com/p/5616f29bb4ef</guid>
            <category><![CDATA[tokenization]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[spacy]]></category>
            <category><![CDATA[named-entity-recognition]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Krishnapiriyan]]></dc:creator>
            <pubDate>Sun, 07 Jun 2026 18:47:21 GMT</pubDate>
            <atom:updated>2026-06-07T18:47:21.549Z</atom:updated>
            <content:encoded><![CDATA[<p>Based on Part 1 of the original series — completely new examples, deeper explanations</p><p>Your five-year-old nephew reads his first sentence out loud. “The dog bit the man.” He laughs. He understands it instantly. He knows there is a dog, a man, and a painful event. He knows who did the biting and who suffered it. He might even feel a bit sorry for the man.</p><p>Now imagine handing that same sentence to a computer and asking it to “understand” it. Where do you even begin?</p><p>This is the central puzzle of <strong>Natural Language Processing (NLP)</strong> — the branch of Artificial Intelligence devoted to making computers understand human language. And the surprising answer is: you do <em>not</em> try to solve it all at once. You solve it in eight separate steps, chain those steps together like train cars, and let each car carry a piece of the meaning.</p><h3>The Dirty Secret About Language</h3><p>Language is astoundingly messy. It breaks its own rules constantly. Words change their meaning based on position, tone, and a million invisible cues. Consider these three headlines that have actually appeared in real newspapers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*DlZOisbtfD0WYnky5vTqaQ.png" /></figure><p>The good news: researchers solved this by refusing to treat it as one big problem. Instead, they broke it into eight small problems. Solve each one with a statistical model. Chain them together. Suddenly you have a system that extracts meaningful, structured knowledge from wild, unstructured text.</p><p>Let’s walk through each step using a single example — a made-up police report:</p><blockquote><em>“Detective Maria Rossi arrested James Walker in downtown Chicago on Tuesday. She charged him with three counts of fraud. He had been evading police for six months.”</em></blockquote><h3>Step 1 — Sentence Segmentation: “Where Do Thoughts End?”</h3><p>Before anything else, we need to figure out where one sentence ends and the next begins. A sentence is (roughly) one complete thought. Shorter thoughts are easier to analyze.</p><p>You might think: just split on periods! But try that on: <em>“Dr. J.R. Ewing Jr. of Dallas, Texas called at 9 a.m. on Nov. 3rd.”</em> You’d get nine “sentences” from one. Modern NLP sentence segmenters use ML models trained on millions of documents to tell the difference.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*ZiE193fbAqH_1ShwkgH7QA.png" /></figure><h3>Step 2 — Word Tokenization: “What Are the Atoms?”</h3><p>We break each sentence into individual units called <strong>tokens</strong>. The period at the end becomes its own token because punctuation carries meaning. A period is different from a question mark, and both are different from a comma.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*Bb2asBZMo0FmW22ckx-Gxw.png" /></figure><p>Edge cases everywhere: “can’t” → one token or two? “$4.50” → one or two? “New York” → one concept, two tokens. spaCy has thought through thousands of these for dozens of languages.</p><h3>Step 3 — Part-of-Speech Tagging: “What Job Does Each Word Do?”</h3><p>A POS tag tells us the grammatical role of each word. This is done by a model trained on millions of hand-tagged sentences — purely statistical pattern matching.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*_SJ4SqD5PyZrv_O7Vu3zHg.png" /></figure><h3>Step 4 — Lemmatization: “What Is the Base Form?”</h3><p>English inflects words constantly. “Arrest”, “arrested”, “arresting”, “arrests” — all the same concept. To a computer looking at character strings, they look like four different words. <strong>Lemmatization</strong> finds the root form (the “lemma”) of each word.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*pMCA_xNUu5qyYk-xL3yS-Q.png" /></figure><p>Without lemmatization, a search for “arrest” would miss “arrested.” That’s catastrophic for a legal or news search system.</p><h3>Step 5 — Stop Word Removal: “What Words Carry No Meaning?”</h3><p>Words like “the”, “a”, “in”, “on”, “was”, “he”, “she”, “it” appear equally in sentences about cooking, law, astronomy, and sports. They are pure noise in statistical analysis. We call them <strong>stop words</strong> and filter them out.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*oZ74jO_yaEnjOVYkU8v4aA.png" /></figure><h3>Step 6 — Dependency Parsing: “How Do Words Relate to Each Other?”</h3><p>Dependency parsing builds a tree showing how every word connects grammatically to every other word. The main verb is the root. This is where language becomes structured knowledge.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*XdGNv57-k-9iKT_-xvSfFg.png" /></figure><h3>Step 7 — Named Entity Recognition: “What Are the Real-World Things?”</h3><p>NER finds proper nouns and classifies them into real-world categories: people, places, organizations, dates, monetary values. This is where structured knowledge is extracted from raw text at scale.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*sHf30-yei6zFPdd1RsLTnA.png" /></figure><h3>Step 8 — Coreference Resolution: “What Do Pronouns Refer To?”</h3><p>Sentences 2 and 3 use pronouns: “She,” “Him,” “He.” Who is “She”? Rossi. Who is “He”? Walker. Coreference resolution tracks these pronouns and maps them back to the full entity names — making every sentence independently understandable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*-vKoRQ443ZIGzt4KYhPRMw.png" /></figure><h3>The Complete Python Code</h3><pre># pip install spacy<br># python -m spacy download en_core_web_sm<br><br>import spacy<br><br>nlp = spacy.load(&quot;en_core_web_sm&quot;)<br><br>text = &quot;&quot;&quot;Detective Maria Rossi arrested James Walker in downtown Chicago<br>on Tuesday. She charged him with three counts of fraud. He had been<br>evading police for six months.&quot;&quot;&quot;<br><br>doc = nlp(text)<br><br># Step 1: Sentences<br>for i, sent in enumerate(doc.sents, 1):<br>    print(f&quot;Sentence {i}: {sent.text.strip()}&quot;)<br><br># Steps 2-5: Token analysis<br>for token in doc:<br>    if not token.is_space:<br>        print(f&quot;{token.text:15} lemma={token.lemma_:12} pos={token.pos_:8} stop={token.is_stop}&quot;)<br><br># Step 7: Named entities<br>for ent in doc.ents:<br>    print(f&quot;[{ent.label_}] {ent.text}&quot;)<br><br># OUTPUT:<br># [PERSON]  Maria Rossi<br># [PERSON]  James Walker<br># [GPE]     Chicago<br># [DATE]    Tuesday<br># [CARDINAL] three<br># [DATE]    six months</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5616f29bb4ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python for Data Science,
ML & AI]]></title>
            <link>https://medium.com/@krishnapiriyan2003/python-for-data-science-ml-ai-f9fa75f02345?source=rss-09539f2fc242------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9fa75f02345</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python-libraries]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Krishnapiriyan]]></dc:creator>
            <pubDate>Sat, 06 Jun 2026 09:57:09 GMT</pubDate>
            <atom:updated>2026-06-06T09:57:09.468Z</atom:updated>
            <content:encoded><![CDATA[<p>A comprehensive guide covering the full stack — from raw data to production AI systems — with real code, key concepts, and modern best practices.</p><pre>Contents<br><br>1. Why Python dominates AI/ML<br>2. The ecosystem — libraries &amp; tools<br>3. Data pipeline fundamentals<br>4. Machine learning algorithms deep dive<br>5. Deep learning &amp; neural networks<br>6. LLMs &amp; generative AI with Python<br>7. MLOps — taking models to production<br>8. Performance &amp; scaling</pre><h3>01-Why Python dominates AI &amp; ML</h3><p>Python wasn’t designed for AI. It was designed for clarity. And that turned out to be exactly what researchers, engineers, and data scientists needed — a language that gets out of the way so you can think about the problem, not the syntax.</p><p>Today Python powers virtually every major AI breakthrough: GPT, Stable Diffusion, AlphaFold, self-driving systems. The reasons are compounding advantages that built up over 30+ years.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*PR6J-4umFh95wKv6Jx88Gg.png" /></figure><p>Key reasons for Python’s dominance</p><ol><li><strong>Readable syntax</strong> — Python code reads like pseudocode. A research paper algorithm can be turned into runnable code in hours, not days.</li><li><strong>C/Fortran underpinnings</strong> — NumPy, SciPy, and PyTorch are written in C/C++ with Python bindings. You get research-friendly syntax with near-C speed.</li><li><strong>Notebook culture</strong> — Jupyter Notebooks created a new paradigm for iterative, explorative computation. Mixing code, math, and visuals in one document transformed data workflows.</li><li><strong>Community gravity</strong> — Every new AI library (JAX, Triton, LangChain) defaults to Python first. The ecosystem reinforces itself.</li><li><strong>Interoperability</strong> — Python talks to everything: REST APIs, SQL databases, R, Julia, Rust via PyO3, and even CUDA kernels directly.</li></ol><h3>02-The ecosystem — libraries &amp; tools</h3><p>Python’s power in ML/AI comes almost entirely from its library ecosystem. Understanding which tool does what — and when to use each — is as important as knowing Python itself.</p><h4>Data layer</h4><pre>NumPy<br>Pandas<br>Polars<br>Dask<br>Arrow</pre><p><strong>NumPy</strong> is the bedrock — n-dimensional arrays, broadcasting, and linear algebra. Almost everything in the ecosystem ultimately talks to NumPy arrays. <strong>Pandas</strong> wraps NumPy into a DataFrame API ideal for tabular, real-world data. <strong>Polars</strong> (written in Rust) is the modern, faster alternative — lazy evaluation and true multi-threading. <strong>Dask</strong> parallelises Pandas operations across clusters for datasets too large for RAM.</p><h3>ML layer</h3><pre>scikit-learn<br>XGBoost<br>LightGBM<br>CatBoost<br>statsmodels</pre><p><strong>scikit-learn</strong> remains the gold standard for classical ML — consistent API, excellent documentation, and pipelines that compose. The gradient boosting trio (XGBoost, LightGBM, CatBoost) dominates structured/tabular competitions. If your data is in rows and columns, gradient boosting beats deep learning most of the time.</p><h3>Deep learning layer</h3><pre>PyTorch<br>TensorFlow / Keras<br>JAXFlax<br>Lightning</pre><p><strong>PyTorch</strong> won the research war. Most papers, most new architectures, and most frontier models are implemented in PyTorch. <strong>TensorFlow</strong> has a stronger presence in enterprise production pipelines. <strong>JAX</strong> (from Google DeepMind) is gaining ground fast — function transformations, XLA compilation, and hardware-agnostic design make it exceptional for research-scale computing.</p><h3>GenAI &amp; LLM layer</h3><pre>Transformers(HuggingFace)<br>LangChain<br>LlamaIndex<br>Anthropic <br>SDKOpenAI<br>SDK</pre><p>The LLM ecosystem moved fast. HuggingFace’s <strong>Transformers</strong> library made state-of-the-art models accessible to anyone. <strong>LangChain</strong> and <strong>LlamaIndex</strong> built orchestration layers above LLM APIs for RAG, agents, and complex pipelines.</p><blockquote><strong>Tool selection rule of thumb:</strong> tabular data → XGBoost/LightGBM first. Images, text, audio → PyTorch. Working with LLM APIs → HuggingFace or provider SDKs. Need to scale across a cluster → Dask or Ray.</blockquote><h3>03-Data pipeline fundamentals</h3><p>Garbage in, garbage out. Experienced practitioners spend 60–80% of their time on data — collecting, cleaning, transforming, and validating it. This is not glamorous but it is decisive.</p><h3>The typical ML pipeline</h3><blockquote>Ingest → Clean → Explore (EDA) → Feature engineer → Split → Train → Evaluate → Deploy</blockquote><h3>Data cleaning patterns</h3><pre>import pandas as pd<br>import numpy as np<br><br>df = pd.read_csv(&quot;data.csv&quot;)<br><br># Inspect missing values<br>print(df.isnull().sum())<br>print(df.dtypes)<br><br># Drop columns with &gt;40% missing<br>threshold = 0.4<br>df = df[df.columns[df.isnull().mean() &lt; threshold]]<br><br># Impute numerical cols with median (robust to outliers)<br>num_cols = df.select_dtypes(include=np.number).columns<br>df[num_cols] = df[num_cols].fillna(df[num_cols].median())<br><br># Encode categoricals<br>df = pd.get_dummies(df, drop_first=True)<br><br># Remove outliers using IQR<br>Q1 = df[&quot;price&quot;].quantile(0.25)<br>Q3 = df[&quot;price&quot;].quantile(0.75)<br>IQR = Q3 - Q1<br>df = df[(df[&quot;price&quot;] &gt;= Q1 - 1.5*IQR) &amp; (df[&quot;price&quot;] &lt;= Q3 + 1.5*IQR)]</pre><h3>Feature engineering — where models win or lose</h3><p>Feature engineering is the art of creating inputs that make patterns easy for an algorithm to learn. A well-crafted feature can outperform a more complex model on raw data.</p><ol><li><strong>Interaction features</strong> — multiply or divide two columns to capture combined effects (e.g. price per sq ft = price / area).</li><li><strong>Polynomial features</strong> — add x², x³ to capture non-linear relationships in linear models.</li><li><strong>Date decomposition</strong> — extract hour, day-of-week, month, is_weekend, days_since_event from timestamps.</li><li><strong>Target encoding</strong> — replace categorical levels with the mean target value. Powerful but leakage-prone — always do this within cross-validation folds.</li><li><strong>Embeddings</strong> — represent high-cardinality categoricals (user IDs, product IDs) as dense learned vectors.</li></ol><blockquote><strong>Data leakage</strong> is the most common mistake in ML. It happens when information from the test set bleeds into training — through target encoding, time-series splits, or preprocessing before splitting. Always split first, then fit transformers.</blockquote><h3>04-Machine learning algorithms — deep dive</h3><p>Understanding the algorithm behind a model tells you when it will fail — and that’s more valuable than knowing its accuracy on a benchmark.</p><h4>Linear &amp; logistic regression</h4><pre>Supervised<br>Baseline<br>Interpretable</pre><p>Linear regression minimises the sum of squared residuals. Logistic regression wraps a linear model in a sigmoid — mapping any input to [0,1]. Both are fast, interpretable, and excellent baselines. Regularisation (L1/Lasso, L2/Ridge, ElasticNet) controls overfitting by penalising large weights. L1 drives weights to exactly zero (built-in feature selection). L2 shrinks weights uniformly.</p><h4>Decision trees &amp; ensemble methods</h4><pre>Supervised<br>TabularHigh<br>performance</pre><p>A decision tree partitions feature space with binary splits, greedily minimising impurity (Gini or entropy for classification, MSE for regression). Trees overfit easily. Ensemble methods fix this: <strong>Random Forest</strong> trains many trees on random data/feature subsets and averages them (bagging). <strong>Gradient Boosting</strong> trains trees sequentially, each correcting the residuals of the last. GBM nearly always outperforms Random Forest on tabular data given proper tuning.</p><pre>from sklearn.ensemble import GradientBoostingClassifier<br>from sklearn.model_selection import cross_val_score<br>import xgboost as xgb<br><br># XGBoost — production-grade gradient boosting<br>model = xgb.XGBClassifier(<br>    n_estimators=500,<br>    learning_rate=0.05,<br>    max_depth=6,<br>    subsample=0.8,<br>    colsample_bytree=0.8,<br>    use_label_encoder=False,<br>    eval_metric=&quot;logloss&quot;,<br>    early_stopping_rounds=50,<br>    random_state=42,<br>)<br><br># Always evaluate with cross-validation<br>scores = cross_val_score(model, X_train, y_train, cv=5, scoring=&quot;roc_auc&quot;)<br>print(f&quot;AUC: {scores.mean():.4f} ± {scores.std():.4f}&quot;)</pre><h4>Support vector machines (SVM)</h4><pre>Supervised<br>High-dimKernel<br>trick</pre><p>SVMs find the maximum-margin hyperplane between classes. The kernel trick implicitly maps data to higher-dimensional spaces without computing coordinates explicitly — enabling non-linear boundaries with RBF, polynomial, or sigmoid kernels. SVMs excel in high-dimensional, small-data settings (genomics, text classification). They scale poorly to millions of samples.</p><h4>Clustering — k-Means, DBSCAN, hierarchical</h4><pre>Unsupervised<br>Exploratory</pre><p>k-Means partitions data into k clusters by minimising within-cluster variance. Simple and fast but assumes spherical clusters and requires k upfront. <strong>DBSCAN</strong> discovers clusters of arbitrary shape and marks outliers as noise — no k needed. Hierarchical clustering produces a dendrogram, useful when you don’t know the number of clusters. Use the elbow method or silhouette score to evaluate cluster quality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/1*IeaoVFMC58DHLSR54hkeRQ.png" /></figure><h3>05-Deep learning &amp; neural networks</h3><p>Deep learning is the application of multi-layer neural networks, enabled by three forces: massive datasets, GPU compute, and algorithmic advances (backpropagation, attention, normalisation). It has redefined what’s possible in vision, language, audio, and protein folding.</p><h3>Core architecture types</h3><h4>Convolutional neural networks (CNNs)</h4><blockquote>CNNs apply learned filters across spatial dimensions, building a hierarchy of features: edges → textures → parts → objects. Parameter sharing makes them vastly more efficient than fully-connected networks on images. Architectures: ResNet, EfficientNet, ConvNeXt.</blockquote><h4>Recurrent networks (RNNs, LSTMs, GRUs)</h4><blockquote>RNNs process sequences step-by-step, maintaining hidden state. LSTMs add gating mechanisms to control what the network remembers and forgets — addressing vanishing gradients. Largely superseded by Transformers for NLP, but still used in time-series and streaming settings.</blockquote><h4>Transformers</h4><blockquote>The architecture behind every major LLM and most of modern computer vision. Self-attention allows every token to attend to every other token — capturing long-range dependencies RNNs struggle with. Positional encodings add sequence order. Multi-head attention runs multiple attention mechanisms in parallel, each learning different relationship patterns.</blockquote><h3>Training a neural network in PyTorch</h3><pre>import torch<br>import torch.nn as nn<br>from torch.optim import AdamW<br>from torch.optim.lr_scheduler import CosineAnnealingLR<br><br>class MLP(nn.Module):<br>    def __init__(self, input_dim, hidden, output_dim, dropout=0.3):<br>        super().__init__()<br>        self.net = nn.Sequential(<br>            nn.Linear(input_dim, hidden),<br>            nn.BatchNorm1d(hidden),<br>            nn.ReLU(),<br>            nn.Dropout(dropout),<br>            nn.Linear(hidden, hidden // 2),<br>            nn.ReLU(),<br>            nn.Linear(hidden // 2, output_dim),<br>        )<br>    def forward(self, x):<br>        return self.net(x)<br><br>model = MLP(input_dim=128, hidden=256, output_dim=10).to(&quot;cuda&quot;)<br>optimizer = AdamW(model.parameters(), lr=3e-4, weight_decay=1e-2)<br>scheduler = CosineAnnealingLR(optimizer, T_max=50)<br>criterion = nn.CrossEntropyLoss()<br><br>for epoch in range(50):<br>    model.train()<br>    for X_batch, y_batch in train_loader:<br>        X_batch, y_batch = X_batch.to(&quot;cuda&quot;), y_batch.to(&quot;cuda&quot;)<br>        optimizer.zero_grad()<br>        loss = criterion(model(X_batch), y_batch)<br>        loss.backward()<br>        nn.utils.clip_grad_norm_(model.parameters(), 1.0)<br>        optimizer.step()<br>    scheduler.step()</pre><blockquote><strong>Training tips:</strong> Use AdamW over Adam (correct weight decay). Gradient clipping prevents exploding gradients. Cosine annealing LR scheduler outperforms fixed LR. BatchNorm before activation. Dropout after activation.</blockquote><h3>Regularisation techniques</h3><ol><li><strong>Dropout</strong> — randomly zero activations during training, forcing the network to learn redundant representations.</li><li><strong>Batch normalisation</strong> — normalise activations per batch, dramatically accelerating training and reducing sensitivity to initialisation.</li><li><strong>Weight decay (L2)</strong> — penalise large weights in the loss, reducing overfitting.</li><li><strong>Data augmentation</strong> — in vision, random crops, flips, colour jitter, and Mixup artificially expand the dataset.</li><li><strong>Early stopping</strong> — monitor validation loss and stop when it stops improving.</li></ol><h3>06-LLMs &amp; generative AI with Python</h3><p>Generative AI has shifted how we build AI-powered products. Instead of training task-specific models, developers now orchestrate pre-trained LLMs — prompting, fine-tuning, and augmenting them with tools and retrieval systems.</p><h3>Calling LLM APIs</h3><pre>import anthropic<br><br>client = anthropic.Anthropic()  # reads ANTHROPIC_API_KEY from env<br><br>message = client.messages.create(<br>    model=&quot;claude-sonnet-4-20250514&quot;,<br>    max_tokens=1024,<br>    system=&quot;You are a Python data science expert.&quot;,<br>    messages=[<br>        {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Explain gradient descent intuitively.&quot;}<br>    ]<br>)<br><br>print(message.content[0].text)</pre><h3>Retrieval-augmented generation (RAG)</h3><p>RAG grounds LLM responses in real, up-to-date knowledge. A vector database stores document embeddings; at query time, the top-k most semantically similar chunks are retrieved and injected into the LLM’s context. This dramatically reduces hallucinations on domain-specific tasks.</p><pre>from sentence_transformers import SentenceTransformer<br>import faiss, numpy as np<br><br># Embed documents<br>embedder = SentenceTransformer(&quot;all-MiniLM-L6-v2&quot;)<br>docs = [&quot;NumPy uses BLAS for matrix ops.&quot;, &quot;Polars is faster than Pandas.&quot;, ...]<br>doc_embeddings = embedder.encode(docs, convert_to_numpy=True)<br><br># Build FAISS index<br>index = faiss.IndexFlatL2(doc_embeddings.shape[1])<br>index.add(doc_embeddings)<br><br># Query<br>query = &quot;Which library is faster for DataFrames?&quot;<br>q_emb = embedder.encode([query], convert_to_numpy=True)<br>D, I = index.search(q_emb, k=3)<br>retrieved = [docs[i] for i in I[0]]<br># Inject retrieved into LLM prompt ...</pre><h3>Fine-tuning with HuggingFace</h3><pre>from transformers import AutoModelForSequenceClassification, TrainingArguments, Trainer<br>from datasets import load_dataset<br><br>model = AutoModelForSequenceClassification.from_pretrained(<br>    &quot;distilbert-base-uncased&quot;, num_labels=2<br>)<br>dataset = load_dataset(&quot;imdb&quot;)<br><br>training_args = TrainingArguments(<br>    output_dir=&quot;./results&quot;,<br>    num_train_epochs=3,<br>    per_device_train_batch_size=16,<br>    evaluation_strategy=&quot;epoch&quot;,<br>    fp16=True,           # mixed precision — 2x speed on compatible GPUs<br>    gradient_checkpointing=True,<br>)<br><br>trainer = Trainer(<br>    model=model,<br>    args=training_args,<br>    train_dataset=dataset[&quot;train&quot;],<br>    eval_dataset=dataset[&quot;test&quot;],<br>)<br>trainer.train()</pre><blockquote><strong>LoRA / QLoRA</strong> — fine-tuning massive models is expensive. Low-Rank Adaptation (LoRA) adds tiny trainable matrices alongside frozen weights, cutting GPU memory by 3–10x. QLoRA additionally quantises the base model to 4-bit. Together, you can fine-tune a 7B parameter model on a single A100.</blockquote><h3>07-MLOps — taking models to production</h3><p>A model that only runs in a Jupyter notebook is a proof-of-concept, not a product. MLOps is the discipline of building reliable, reproducible, observable ML systems at scale.</p><h3>The production gap</h3><p>Most ML projects fail at deployment. Common failure modes: model performance degrades in production (distribution shift), no monitoring in place, non-reproducible training runs, no versioning, tight coupling of training and serving code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*GVjfepqz5PfU_-9Fs0Ni8Q.png" /></figure><h3>Tracking experiments with MLflow</h3><pre>import mlflow<br>import mlflow.sklearn<br>from sklearn.ensemble import RandomForestClassifier<br>from sklearn.metrics import roc_auc_score<br><br>mlflow.set_experiment(&quot;credit-risk-model&quot;)<br><br>with mlflow.start_run():<br>    params = {&quot;n_estimators&quot;: 300, &quot;max_depth&quot;: 8, &quot;min_samples_leaf&quot;: 5}<br>    mlflow.log_params(params)<br><br>    model = RandomForestClassifier(**params)<br>    model.fit(X_train, y_train)<br><br>    auc = roc_auc_score(y_val, model.predict_proba(X_val)[:,1])<br>    mlflow.log_metric(&quot;val_auc&quot;, auc)<br>    mlflow.sklearn.log_model(model, &quot;model&quot;)<br><br>    print(f&quot;Run complete. AUC: {auc:.4f}&quot;)</pre><h3>Model monitoring — detecting drift</h3><p>Once deployed, models degrade silently. Data drift (input distribution changes) and concept drift (the relationship between inputs and labels changes) are the two main culprits. Monitoring requires comparing production data distributions against a reference baseline — using statistical tests (KS test, Population Stability Index) or model-based drift detection.</p><pre>from evidently.report import Report<br>from evidently.metric_preset import DataDriftPreset, TargetDriftPreset<br><br>report = Report(metrics=[DataDriftPreset(), TargetDriftPreset()])<br>report.run(reference_data=train_df, current_data=production_df)<br>report.save_html(&quot;drift_report.html&quot;)</pre><h3>08-Performance &amp; scaling</h3><p>Python is slow. The trick is making sure Python spends as little time as possible executing business logic — instead delegating computation to optimised, compiled backends.</p><h3>Profiling first</h3><pre>import cProfile, pstats<br><br>profiler = cProfile.Profile()<br>profiler.enable()<br># ... your code ...<br>profiler.disable()<br><br>stats = pstats.Stats(profiler).sort_stats(&quot;cumulative&quot;)<br>stats.print_stats(20)  # top 20 hotspots</pre><h3>Acceleration techniques</h3><ol><li><strong>Vectorisation with NumPy</strong> — replace Python loops with array operations. A loop over 1M elements may take 1s; the equivalent NumPy operation takes 1ms.</li><li><strong>Numba JIT</strong> — decorate numerical functions with@numba.jit(nopython=True)to compile them to LLVM bytecode. Often 100–1000x faster than pure Python.</li><li><strong>GPU acceleration</strong> — CuPy is NumPy with CUDA. PyTorch tensors move to GPU with.to(&quot;cuda&quot;). For custom CUDA kernels, Triton (from OpenAI) lets you write GPU kernels in Python-like syntax.</li><li><strong>Distributed training</strong> — PyTorch DDP (DistributedDataParallel) splits batches across GPUs and nodes. For model-parallel training of massive models, use DeepSpeed or FSDP.</li><li><strong>Mixed precision (fp16/bf16)</strong> — training in half-precision cuts memory in half and speeds up matmuls on modern GPUs, with negligible accuracy loss when combined with loss scaling.</li></ol><pre>import torch<br><br># Automatic mixed precision — one-line speedup<br>scaler = torch.cuda.amp.GradScaler()<br><br>for X, y in train_loader:<br>    optimizer.zero_grad()<br>    with torch.autocast(device_type=&quot;cuda&quot;, dtype=torch.float16):<br>        output = model(X)<br>        loss = criterion(output, y)<br>    scaler.scale(loss).backward()<br>    scaler.step(optimizer)<br>    scaler.update()</pre><blockquote><strong>Rule of thumb:</strong> profile before optimising. 80% of execution time is usually in 20% of code. Optimise hotspots only. Premature optimisation is the root of all evil — and in ML, it often means never finishing the model at all.</blockquote><h3>Where to go from here</h3><p>The Python AI/ML landscape moves fast. The fundamentals above — data pipelines, classical ML, deep learning, LLM orchestration, and MLOps — are stable foundations. Build on them, then specialise.</p><pre>Reinforcement<br>learningGraph<br>neural networks<br>Diffusion models<br>Causal ML<br>Interpretability (XAI)</pre><h3>APA 7th Edition References</h3><ol><li>Bourke, D. (2020). <em>5 beginner-friendly steps to learn machine learning and data science with Python</em>. Towards Data Science. Retrieved from<br> <a href="https://medium.com/data-science/5-beginner-friendly-steps-to-learn-machine-learning-and-data-science-with-python-bf69e211ade5">https://medium.com/data-science/5-beginner-friendly-steps-to-learn-machine-learning-and-data-science-with-python-bf69e211ade5</a></li><li>Towards Data Science. (n.d.). <em>How to learn Python so fast it feels like cheating</em>. Retrieved from<br> <a href="https://towardsdatascience.com/how-to-learn-python-so-fast-it-feels-like-cheating/">https://towardsdatascience.com/how-to-learn-python-so-fast-it-feels-like-cheating/</a></li><li>Van Rossum, G., &amp; Drake, F. L. (2009). <em>Python 3 Reference Manual</em>. Scotts Valley, CA: CreateSpace.</li><li>McKinney, W. (2022). <em>Python for Data Analysis: Data Wrangling with Pandas, NumPy, and Jupyter</em> (3rd ed.). O’Reilly Media.</li><li>Géron, A. (2022). <em>Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow</em> (3rd ed.). O’Reilly Media.</li><li>Chollet, F. (2021). <em>Deep Learning with Python</em> (2nd ed.). Manning Publications.</li><li>Goodfellow, I., Bengio, Y., &amp; Courville, A. (2016). <em>Deep Learning</em>. MIT Press.</li><li>Raschka, S., Liu, Y., &amp; Mirjalili, V. (2022). <em>Machine Learning with PyTorch and Scikit-Learn</em>. Packt Publishing.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9fa75f02345" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Shuttle Rover: Advancing Badminton Training Through Robotics]]></title>
            <link>https://medium.com/@krishnapiriyan2003/shuttle-rover-advancing-badminton-training-through-robotics-d6de1a20f41d?source=rss-09539f2fc242------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6de1a20f41d</guid>
            <dc:creator><![CDATA[Krishnapiriyan]]></dc:creator>
            <pubDate>Fri, 26 Dec 2025 13:44:19 GMT</pubDate>
            <atom:updated>2025-12-26T13:44:19.946Z</atom:updated>
            <content:encoded><![CDATA[<p>In recent years, technology has become an essential part of sports training, helping athletes improve performance, efficiency, and focus. One such innovative application of technology was showcased at the Undergraduate Research Symposium and Innovation Exhibition (URSIE) 2025 through a project known as Shuttle Rover. This advanced robotic system was designed to solve a simple yet persistent problem in badminton training: the manual collection of shuttlecocks. During badminton practice sessions, players repeatedly stop their training to gather shuttlecocks scattered across the court. While this task may seem minor, it becomes physically tiring during long training sessions and disrupts the rhythm and momentum of practice. Recognizing this issue, the developers of Shuttle Rover introduced an autonomous robotic solution that allows players to focus more on skill development rather than routine clean-up tasks. The Shuttle Rover is an intelligent robot capable of automatically identifying and collecting shuttlecocks from a badminton court. It uses a camera-based vision system to detect shuttlecocks lying on the ground. An ESP camera captures real-time images, which are processed to determine the exact position of each shuttlecock. Once a target is identified, the rover navigates smoothly toward it using a controlled movement system designed to operate safely on indoor sports courts. One of the key highlights of the Shuttle Rover is its shuttlecock collection mechanism. The robot is equipped with a chain-driven brush system that gently lifts shuttlecocks without causing any damage. After collection, the shuttlecocks are aligned using a tread movement system and transferred into a rotational storage unit. This storage system can hold up to 60 shuttlecocks, making it highly suitable for continuous training sessions. The Shuttle Rover offers flexibility through its dual operating modes. In autonomous mode, the robot independently detects and retrieves shuttlecocks without human intervention. In manual mode, users can control the robot using a mobile application. The application allows users to view live video footage from the robot’s camera, control its movement, and monitor the battery level. This feature enhances usability and provides greater control during operation. Powering the system is a rechargeable battery, which ensures extended operational time and makes the robot environmentally friendly and cost effective. The efficient power management system enables the Shuttle Rover to support long practice sessions without frequent recharging. The potential applications of Shuttle Rover extend beyond individual players. It can be highly beneficial for badminton academies, schools, sports clubs, and training centers, where frequent and large-scale practice sessions take place. By reducing physical strain and saving time, the robot contributes to more productive and uninterrupted training environments. In conclusion, the Shuttle Rover project demonstrates how robotics and automation can be effectively integrated into sports training to solve everyday challenges. It stands as a practical example of how innovative thinking and basic robotic technologies can lead to meaningful improvements in athletic performance and training efficiency. The Shuttle Rover not only enhances convenience but also represents the growing role of technology in shaping the future of sports.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6de1a20f41d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a Simple Real Mode Operating System: “Krishnapiriyan OS”]]></title>
            <link>https://medium.com/@krishnapiriyan2003/creating-a-simple-real-mode-operating-system-krishnapiriyan-os-f9baac2ad841?source=rss-09539f2fc242------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9baac2ad841</guid>
            <dc:creator><![CDATA[Krishnapiriyan]]></dc:creator>
            <pubDate>Wed, 09 Jul 2025 12:19:38 GMT</pubDate>
            <atom:updated>2025-07-09T12:19:38.855Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*xiW4s190Pc6s3irWjTCj7g.png" /></figure><p>This is my first attempt to explore and understand the fundamentals of operating systems by creating a basic bootable OS in real mode using Assembly language. This project, called <strong>Krishnapiriyan OS</strong>, prints a welcome message directly on the screen.</p><h3>Project Overview</h3><p>The purpose of this project was to understand the <strong>boot process</strong>, <strong>BIOS interrupts</strong>, and how an operating system loads and runs at a low level. It was built and tested using <strong>WSL (Ubuntu 24.04)</strong>, <strong>NASM</strong>, and <strong>QEMU</strong>.</p><h3>Tools Used</h3><ul><li><strong>Ubuntu 24.04 via WSL (Windows Subsystem for Linux)</strong></li><li><strong>NASM</strong> — Netwide Assembler for compiling assembly code</li><li><strong>QEMU</strong> — Quick Emulator to run the OS</li></ul><h3>📂 Folder Structure</h3><pre>krishnapiriyan-os/<br>├── bootloader.asm<br>├── bootloader.bin</pre><h3>Step-by-Step Process</h3><h3>Step 1: Install Required Tools</h3><pre>sudo apt update<br>sudo apt install nasm qemu</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*14K8KkWJwAd2GmDDSWtDIA.png" /></figure><h3>📁 Step 2: Create the Project Folder</h3><pre>mkdir krishnapiriyan-os<br>cd krishnapiriyan-os</pre><h3>Step 3: Write the Bootloader Code</h3><p>Create the file:</p><pre>nano bootloader.asm</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H32p05iFqpYaV8-c0RL1uA.png" /></figure><p>Paste the following Assembly code:</p><pre>[org 0x7c00]         ; BIOS loads boot sector to 0x7C00</pre><pre>start:<br>    mov si, message  ; SI points to the start of the message<br>print_loop:<br>    lodsb            ; Load byte at DS:SI into AL, then increment SI<br>    cmp al, 0        ; End of string?<br>    je hang          ; If yes, jump to end<br>    mov ah, 0x0E     ; BIOS teletype function<br>    int 0x10         ; Call BIOS interrupt to print AL<br>    jmp print_loop   ; Repeat for next character<br>hang:<br>    jmp $            ; Infinite loop to stop execution<br>message db &#39;hello, welcome krishnapiriyan os&#39;, 0<br>times 510 - ($ - $$) db 0<br>; Boot signature<br>dw 0xAA55</pre><p>Save and exit using Ctrl + O, Enter, then Ctrl + X.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wXau4kifgcEC8R-k6c3ePg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9kJDyDQzAHmPSylcttRS0Q.png" /></figure><h3>Step 4: Assemble the Code</h3><pre>nasm -f bin bootloader.asm -o bootloader.bin</pre><p>This creates a bootable binary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UDit6-qr_oe-nXvq78eKxA.png" /></figure><h3>Step 5: Run the Bootloader in QEMU</h3><pre>qemu-system-x86_64 -drive format=raw,file=bootloader.bin</pre><p>You should see the following message on your screen:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YE4V1Dl2JashUGxxtqh5XQ.png" /></figure><pre>hello, welcome krishnapiriyan os</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ri4a6Ya3IAxCKg-YxWREEw.png" /></figure><h3>What I Learned</h3><ul><li>Basics of x86 Assembly language</li><li>How the BIOS loads the boot sector</li><li>How to use BIOS interrupts like int 0x10 to print characters</li><li>How to assemble and run your own bootloader in a virtual machine</li></ul><h3>Final Thoughts</h3><p>This was my first low-level system project, and it gave me a solid introduction to bootloaders, BIOS interrupts, and raw memory addressing. If you’re new to OS development, this is a great first step!</p><h3>GitHub Repository</h3><p>https://github.com/Krishnapiriyan/krishnapiriyan_os</p><h3>Resources</h3><ul><li><a href="https://www.nasm.us/">Netwide Assembler (NASM)</a></li><li><a href="https://wiki.qemu.org/Main_Page">QEMU Documentation</a></li><li><a href="https://en.wikipedia.org/wiki/INT_10H">BIOS Interrupts Reference</a></li></ul><h3>Future Plans</h3><p>I plan to:</p><ul><li>Add keyboard input</li><li>Extend the OS with C kernel support</li><li>Build a basic shell</li><li>Add color and border customization</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9baac2ad841" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>