<?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 MD RASHEDIN on Medium]]></title>
        <description><![CDATA[Stories by MD RASHEDIN on Medium]]></description>
        <link>https://medium.com/@raftaarrashedin100?source=rss-99ce24a11be2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*A4sirJBo0aSqep61</url>
            <title>Stories by MD RASHEDIN on Medium</title>
            <link>https://medium.com/@raftaarrashedin100?source=rss-99ce24a11be2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 10:33:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@raftaarrashedin100/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[PII Masking in AI Systems: An Architecture Guide for RAG, Agentic AI, GraphRAG, and Image Pipelines]]></title>
            <link>https://medium.com/@raftaarrashedin100/pii-masking-in-ai-systems-an-architecture-guide-for-rag-agentic-ai-graphrag-and-image-pipelines-470dca04e387?source=rss-99ce24a11be2------2</link>
            <guid isPermaLink="false">https://medium.com/p/470dca04e387</guid>
            <category><![CDATA[pii-masking]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[deep-agent]]></category>
            <category><![CDATA[graphrag]]></category>
            <dc:creator><![CDATA[MD RASHEDIN]]></dc:creator>
            <pubDate>Wed, 03 Jun 2026 11:39:01 GMT</pubDate>
            <atom:updated>2026-06-03T11:40:38.421Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How to build production-grade privacy into every layer of a modern AI stack — from vector stores to knowledge graphs to vision models</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VMQxqYiqgujA4rql.jpg" /></figure><p>There is a gap between how most people think about privacy in AI systems and what actually happens in production. The common assumption is that if you strip names and emails from your documents before embedding them, you have done your job. You have not. You have only protected one surface out of many — and in architectures that involve agents, tools, knowledge graphs, and image inputs, that single-layer approach fails in ways that are often silent, often catastrophic, and increasingly well-documented by researchers.</p><p>This guide walks through the state of the art for four distinct architectural modules: traditional RAG with memory, agentic AI via Deep Agents, GraphRAG, and image-based pipelines. Each has its own threat model, its own failure modes, and its own set of controls. They share one underlying principle: PII must be masked at every trust boundary, stored only in a secure token vault, and re-identified only through a deterministic policy engine — never by the LLM itself.</p><p><strong>Typed Tokens and a Shared Vault</strong></p><p>Before diving into each module, one foundational decision applies everywhere and it is worth making explicit.</p><p>Most teams reach for generic redaction when they first implement PII masking. They replace a name with [REDACTED] or **** and call it done. This destroys semantic signal. The LLM, the retriever, and any downstream agent can no longer reason about the entity type, the relationship, or the context. Retrieval quality degrades. Agent reasoning breaks.</p><p>The SOTA approach is <strong>typed, stable pseudonym tokens</strong>:</p><pre>Raftaar           →   PERSON_7f31<br>+91-01234567        →   PHONE_22c1<br>mraftaar@company.com  →   EMAIL_9ab2<br>Rupee 25,000           →   SALARY_b3e1</pre><p>The token encodes the entity type. It is stable across the entire conversation, across all tool calls, across all memory writes. The LLM can still understand that PERSON_7f31 works at ORG_91aa and has a dispute with CASE_3c20. It just cannot learn — and cannot leak — the real identity behind the token.</p><p>The mapping from token to real value lives in exactly one place: an <strong>encrypted token vault</strong> with strict access control, audit logging, row-level policy, and per-entry TTLs. This vault is the single point of truth. Every other store — vector DB, graph DB, memory DB, logs, traces, LLM context — sees only tokens. Re-identification happens only when a deterministic policy engine decides it is authorized, never because the LLM decided to answer a question.</p><p>With that foundation in place, here is how each module is handled.</p><p><strong>Module 1: Traditional RAG with Memory</strong></p><p>The problem</p><p>The standard RAG pipeline has a deceptively simple privacy failure mode: if you embed raw documents, you embed the PII inside them. Vector similarity search will then retrieve that PII and place it directly into the LLM’s context window. Even if you instruct the model not to reveal personal information, the data is already there. Prompt instructions are not a trust boundary. Memory compounds this. Conversational memory systems write user messages and interaction summaries to a long-term store. Without masking, these stores accumulate raw PII — names, contact details, account numbers, sensitive disclosures — indefinitely, across every session.</p><p>Step 1 — Ingestion-time masking. Before any chunk is split or embedded, every document passes through a PII detection pipeline. Tools like Microsoft Presidio, Google Cloud DLP, or AWS Comprehend scan for entities. Each detected entity is replaced with its typed token and the mapping is written to the vault. Only the masked document proceeds to chunking and embedding. Research validates a specific decision here: use REPLACE_WITH_PII_ENTITY_TYPE rather than a generic mask character. A document that reads “Customer PERSON_7f31 called about their ACCOUNT_3c20” still carries meaningful semantic signal. A document full of **** does not. Retrieval quality is directly affected by this choice.</p><p>Step 2 — The token vault. The re-identification map is stored in an encrypted SQL store (or KMS-backed secrets manager) with the following schema:</p><pre>doc_id UUID<br>tenant_id UUID - multi-tenant isolation<br>placeholder TEXT - PERSON_7f31<br>original BYTEA - AES-256-GCM encrypted<br>pii_type ENUM - PERSON, EMAIL, PHONE…<br>policy JSONB - allowed_roles, purpose, region<br>expires_at TIMESTAMP</pre><p>Raw PII never appears in vector metadata, embeddings, logs, or traces. The vault is the only exception.</p><p>Step 3 — Memory masking. Conversational memory is another vector store and must be treated identically to the document store. Before any interaction summary is written to long-term memory, it passes through the same masking pipeline. What gets stored is a masked summary with a sensitivity label and a TTL, not a raw transcript.<br>The difference between wrong and right looks like this:</p><p>Wrong:</p><pre>Customer Raftaar, phone +966501234567, has an issue with account 12345.</pre><p>Right:</p><pre>PERSON_7f31 (PHONE_22c1) has an issue with ACCOUNT_3c20. sensitivity: medium, ttl: 90d</pre><p>Step 4 — Retrieval. When the RAG pipeline retrieves chunks to answer a query, it applies an authorization filter before the chunks enter the LLM context. A chunk may be semantically relevant but unauthorized for the current user, role, tenant, or stated purpose. The filter checks the chunk’s policy fields against the current request context and drops any chunk that fails. The query itself is also masked before being sent to the retriever, since user queries often contain PII from the conversation.</p><p>Step 5 — Output leakage guard. The LLM’s response passes through a final PII scanner before reaching the user. Even with masked inputs, the model may reconstruct or infer PII from patterns in the context window. OWASP’s LLM Top-10 lists sensitive information disclosure as a primary risk specifically because of this. The output guard is the last line of defense and it must be independent of the other four rings, because each catches failures the others miss.</p><p><strong>Module 2: Agentic RAG via Deep Agents</strong></p><p>The problem</p><p>Traditional RAG has one trust boundary: the document store. Agentic systems with Deep Agents have many. A typical architecture looks like this:</p><pre>User query<br>  → Supervisor Agent<br>  → RAG Agent<br>  → Web Search Tool<br>  → SQL Tool<br>  → Image QA Agent<br>  → Code Execution Tool</pre><p>PII can enter at the user query, it can be returned by any tool, it can be written to memory by any subagent, and it can leak in the final answer. A masking layer at ingestion does nothing to stop a tool response from injecting raw PII into the orchestrator’s context, which then forwards it to memory, which then surfaces it in a future turn.</p><p>The problem also has a routing dimension. Consider this query:</p><pre>&quot;What is the refund policy, and show Manager salary?&quot;</pre><p>This query contains two segments with completely different privacy requirements. The first is a benign policy lookup. The second is a sensitive data request that may or may not be authorized depending on who is asking, in what context, and for what stated purpose. If the orchestrator sends both segments to the same pipeline without segmentation, the LLM will attempt to answer the second segment with whatever it finds — and if the salary is in any retrieved chunk or tool response, it will surface it.</p><p><strong>The Solution: A Privacy Control Plane at Every Boundary</strong></p><p>The SOTA pattern treats every edge in the agent graph as an untrusted crossing point. A <strong>Privacy Control Plane</strong> intercepts at every edge with a named guardrail function:</p><pre>agent_input_guardrail()      -- user → supervisor<br>subagent_input_guardrail()   -- supervisor → subagent<br>tool_request_guardrail()     -- subagent → tool call<br>tool_response_guardrail()    -- tool result → subagent<br>memory_write_guardrail()     -- any agent → memory store<br>final_answer_guardrail()     -- supervisor → user</pre><p>Each function does the same thing: scan for PII, replace with tokens, write mappings to the vault, and pass the masked payload forward.</p><p>The memory write guardrail deserves particular attention because memory is middleware in agentic systems. It is not a passive store — it is a surface that every future query will read from. In a FastAPI-based Deep Agent architecture, the guardrail is implemented as a middleware layer:</p><pre>async def memory_write_guardrail(content: str, user_id: str, role: str):<br>    masked, entities = presidio.anonymize(content)<br>    sensitivity     = classify_sensitivity(masked)<br>    vault.store_batch(entities, user_id)       # encrypted, per-entity TTL<br>    memory.write({<br>        &quot;content&quot;:     masked,<br>        &quot;sensitivity&quot;: sensitivity,<br>        &quot;pii&quot;:         False,<br>        &quot;ttl_days&quot;:    180,<br>        &quot;author_role&quot;: role<br>    })</pre><p>The most important architectural rule in agentic systems is this: <strong>the LLM must never decide whether to unmask.</strong> Prompt instructions like “only show salary data to authorized users” are not access control. A deterministic policy engine outside the model — OPA, Cedar, or a custom RBAC-ABAC layer — makes that decision and enforces it before the LLM ever sees the data. If the policy engine says no, the data is not passed to the model. There is no prompt that overrides this.</p><p>The query segmentation problem from above is solved by the intent splitter at the supervisor boundary:</p><pre>Query: &quot;What is the refund policy, and show Ahmed Khan&#39;s salary?&quot;<br><br>Segments:<br>  1. &quot;What is the refund policy?&quot;     → RAG pipeline (no sensitive data)<br>  2. &quot;Show Khan sahab salary?&quot;        → sensitive request → policy engine check<br>                                        → if authorized: re-identify from vault<br>                                        → if not:        return policy denial</pre><p>This prevents a benign query from being contaminated by a sensitive segment that happens to be in the same message.</p><p><strong>Module 3: GraphRAG</strong></p><p>The problems</p><p><strong>Research finding (August 2025, arXiv 2508.17222):</strong> GraphRAG achieved <strong>73.6% entity leakage</strong> and <strong>74% relationship leakage</strong> in targeted attacks on the Enron dataset, compared to negligible leakage for naive RAG. The explicit graph structure makes PII trivially extractable.</p><p>The reason is structural. In a document RAG system, sensitive information is buried inside text chunks. An attacker has to ask the right question and get the right chunk back. The information is implicit. In a knowledge graph, however, the system has already done the extraction work. It has identified every entity, built every relationship, and organized everything into a queryable structure. An entity node for “Ahmed Khan” is a direct pointer to everything the system knows about that person.</p><p>Consider what a typical knowledge graph looks like if built naively from private documents:</p><pre>Ahmed Khan  --works_at--&gt;       Acme Corp<br>Ahmed Khan  --salary--&gt;         25,000<br>Ahmed Khan  --reported_issue--&gt; Case #3892<br>Ahmed Khan  --email--&gt;          ahmed@acme.com</pre><p>This graph is not a privacy risk — it is a privacy catastrophe. Any query that touches the Ahmed Khan node returns a complete dossier. The graph traversal paths, community summaries, and neighborhood structure all encode sensitive relationships that can be extracted with targeted queries far more efficiently than any document retrieval attack.</p><p>Microsoft’s own GraphRAG documentation confirms the risk: because GraphRAG builds a knowledge graph from private datasets for query-time augmentation, privacy controls must cover the entire graph layer — chunks, nodes, edges, and community summaries — not only the source documents.</p><p>The Solution: Build the Entire Graph on Masked Data</p><p>A brute force and only approach came in my mind,</p><p>The core principle is that the graph must be constructed entirely from tokenized text. Entity extraction, relationship extraction, and community detection all run on masked documents. The graph never contains a real person’s name, email, salary, or identifier. What it contains are typed tokens and their relationships.</p><p>The correct graph looks like this:</p><pre>PERSON_7f31  --works_at--&gt;       ORG_91aa<br>PERSON_7f31  --salary_range--&gt;   SALARY_b3e1<br>PERSON_7f31  --reported_issue--&gt; CASE_3c20<br>PERSON_7f31  --contact--&gt;        EMAIL_9ab2</pre><p>The pipeline that produces this graph works as follows:</p><blockquote>Raw documents enter the PII detection pipeline and are fully tokenized before any graph extraction begins.</blockquote><blockquote>Entity and relationship extraction run on the masked text. The LLM extracts (TOKEN_A, relation, TOKEN_B) triples.</blockquote><blockquote>Graph construction uses these tokenized triples. Every node and every edge is classified by sensitivity level.</blockquote><blockquote>Community detection and LLM summarization run on the masked graph. Community summaries reference only tokens, never real values.</blockquote><blockquote>ACL labels are applied to every node and every edge, specifying which roles can traverse which relationships.</blockquote><blockquote>Query-time traversal is governed by a policy engine that enforces hop depth limits, neighborhood size limits, and k-anonymity thresholds.</blockquote><p>Nine controls are needed to make this work properly:</p><blockquote><strong>Tokenized entity nodes</strong> — every person, organization, and account replaced with a stable token before graph construction.</blockquote><blockquote><strong>Tokenized edge labels</strong> — relationship types classified by sensitivity; high-sensitivity edges (salary, health, legal) receive stricter ACL.</blockquote><blockquote><strong>Edge-level access control</strong> — per-edge ACL such that only authorized roles can traverse sensitive relationship types.</blockquote><blockquote><strong>Safe community summaries</strong> — summaries built entirely from the masked graph, referencing no raw PII values.</blockquote><blockquote><strong>Query-time traversal limits</strong> — hop depth and neighborhood size bounded per query; deep traversal enables re-identification by inference from graph structure alone.</blockquote><blockquote><strong>k-anonymity for graph neighborhoods</strong> — any subgraph returned must contain at least k entities; this prevents singleton identification even when all node values are tokenized.</blockquote><blockquote><strong>No raw PII in node embeddings</strong> — entity node embeddings built from tokenized descriptions only.</blockquote><blockquote><strong>ARoG framework for structural queries</strong> — ARoG abstracts entity mentions so queries match against relational structures without exposing raw PII values; achieves state of the art on WebQSP, CWQ, and GrailQA while preserving privacy.</blockquote><blockquote><strong>Secure re-identification vault</strong> — re-identification flows through the same policy-gated vault used across all other modules; every access is logged and audited.</blockquote><p>The production rule for GraphRAG is this: <strong>protect relationships, not only text.</strong> The 73.6% leakage finding is not a corner case or a research artifact — it is what happens when a knowledge graph is built from private data without these controls. The explicit structure that makes GraphRAG so powerful for retrieval is exactly what makes it dangerous without them.</p><p><strong>Module 4: Image-based QA</strong></p><p>The problem</p><p>Image inputs carry two entirely independent layers of sensitive information: <strong>visible objects</strong> and <strong>embedded text</strong>. OCR alone handles the second layer but completely misses the first. Visual privacy — faces, identity documents, license plates, screen contents, medical forms, security badges — is invisible to text-based PII detection.</p><p>The failure mode is straightforward: an agent receives an image, passes it to a vision model without redaction, and the model proceeds to describe, transcribe, or analyze whatever it sees, including faces, names on badges, addresses on documents, and account numbers on screenshots. The model has no way to know it should not have received this information in the first place.</p><p>In agentic systems, the risk is amplified because images arrive from many sources: file uploads, email attachments, screen recordings, document scans, API responses from external tools. Each source needs the same treatment.</p><p><strong>The Solution: Two-Stage Pipeline with Secure Storage</strong></p><p>The SOTA approach in 2025 uses a two-stage pipeline that runs both detection paths independently and applies pixel-level redaction before any image reaches a vision model.</p><p><strong>Stage 1A — Visual PII detection.</strong> An object detection model (YOLOv8, InsightFace, or a fine-tuned classifier) scans the image for sensitive visual elements: faces, identity documents, license plates, security badges, screens displaying sensitive content, and medical or financial forms. Each detected region produces a bounding box.</p><p><strong>Stage 1B — OCR text extraction.</strong> In parallel, a multilingual OCR engine (EasyOCR combined with Tesseract for broader language coverage, including Arabic and English) extracts all legible text regions with their bounding box coordinates.</p><p><strong>Stage 2A — Text PII detection on OCR output.</strong> The extracted text runs through Presidio or an equivalent NER pipeline. Any detected PII entities are mapped back to their bounding boxes in the original image.</p><p><strong>Stage 2B — Pixel-level redaction.</strong> All bounding boxes from Stage 1A and Stage 2A are combined into a single redaction mask. A Gaussian blur or solid fill is applied to each region in the image. The result is a masked image where all sensitive content has been obscured at the pixel level.</p><p>Only the masked image is sent to the vision model. The original image is stored in an encrypted object store and is accessible only through the same policy-gated vault used across the rest of the architecture.</p><p>The production rule for image pipelines is unambiguous: <strong>never send a raw sensitive image to a general vision model unless policy explicitly authorizes it.</strong> The original always remains in the secure store. The vision model sees only the masked copy.</p><p>Across all four modules, the architecture is three specialized pipelines sharing one token vault and one policy engine.</p><p><strong>What is shared:</strong></p><blockquote>The token vault — encrypted, KMS-backed, audited, with per-entry policies and TTLs</blockquote><blockquote>The policy engine — OPA, or a custom RBAC-ABAC layer that makes all re-identification decisions</blockquote><blockquote>The audit log — records placeholder events, access decisions, and re-identification grants; never raw PII</blockquote><blockquote>The output leakage guard — a final PII scan on every response before it reaches any external surface</blockquote><p><strong>What is specialized:</strong></p><blockquote>Traditional RAG uses the five-step model with typed tokens, retrieval ACL, and an output guard.</blockquote><blockquote>Agentic AI uses a Privacy Control Plane with six named guardrail functions at every agent boundary, a per-tool masking policy, and intent segmentation at the supervisor.</blockquote><blockquote>GraphRAG uses tokenized graph construction from the ground up — entity extraction, relationship extraction, community detection, and summarization all run on masked data — plus nine graph-specific controls including edge-level ACL, traversal limits, and k-anonymity.</blockquote><blockquote>Image pipelines use the two-stage visual detection and OCR pipeline with pixel-level redaction, secure original storage, and a masked copy for the vision model.</blockquote><p>Privacy in AI systems is not a feature you add at the end. It is a structural property of the architecture — and like any structural property, retrofitting it after the fact is orders of magnitude harder than building it in from the start.</p><p>That’s all</p><p>Thank You.</p><p>Happy Reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=470dca04e387" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying a LoRA-Fine-Tuned Model on a Quantized Base Model]]></title>
            <link>https://medium.com/@raftaarrashedin100/deploying-a-lora-fine-tuned-model-on-a-quantized-base-model-6679db56cf0f?source=rss-99ce24a11be2------2</link>
            <guid isPermaLink="false">https://medium.com/p/6679db56cf0f</guid>
            <category><![CDATA[llm-quantization]]></category>
            <category><![CDATA[fine-tuning]]></category>
            <category><![CDATA[production-deployment]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[lora-adapter]]></category>
            <dc:creator><![CDATA[MD RASHEDIN]]></dc:creator>
            <pubDate>Tue, 14 Apr 2026 15:08:23 GMT</pubDate>
            <atom:updated>2026-04-15T04:52:44.762Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YC5XbTaMOB1RxjX5foxfDg.png" /></figure><p>Combining LoRA fine-tuning with a quantized base model is one of the most practical approaches in production ML today. It lets you keep memory usage low while still adapting the model to specialized tasks. But this combination comes with its own set of nuances that every engineer should understand before going to production.</p><p><strong>Compatibility Between LoRA and Quantization</strong><br>The base model lives in a quantized state, typically 4-bit or 8-bit precision, while LoRA adapters are usually kept in higher precision formats like FP16 or FP32. Getting these two to work together requires a framework that explicitly supports mixed precision inference.</p><p>Not all quantization methods play nicely with LoRA out of the box. Libraries like bitsandbytes and PEFT handle this reasonably well, but if you are using GPTQ or AWQ, you need to verify compatibility before assuming everything will just work.</p><p>bitsandbytes, PEFT, vLLM, GPTQ, AWQ</p><p><strong>Where LoRA Is Applied in the Architecture</strong><br>LoRA does not touch every part of the model. It targets specific layers, most commonly the attention projections: the query, key, and value matrices. These layers need to stay compatible with the quantized weights sitting beneath them.</p><p>In some implementations, the computation requires temporarily dequantizing those weights at runtime. This is perfectly functional but introduces a small amount of overhead with every forward pass.</p><p><strong>Inference Performance</strong><br>Quantization does the heavy lifting on performance: it shrinks memory footprint and speeds up throughput considerably. LoRA adds back a modest overhead because every forward pass now involves a few extra low-rank matrix multiplications on top of the base computation.</p><blockquote>In practice, the combined setup is still dramatically faster than running a fully fine-tuned model at full precision. The latency penalty from LoRA is real but small, and for most use cases it is an entirely acceptable trade-off.</blockquote><p><strong>Memory Efficiency</strong><br>This is where the combination truly shines. The quantized base model already uses a fraction of the memory it would need at full precision. LoRA adapters are tiny by comparison, typically just a few megabytes versus the gigabytes the base model occupies.</p><p>For teams working with limited GPU resources, this setup is often the only practical path to deploying a capable fine-tuned model without expensive hardware upgrades.</p><p><strong>Accuracy Trade-offs</strong><br>Quantization is a lossy compression process. When you reduce the numerical precision of model weights, you introduce approximation errors throughout the network. LoRA then tries to adapt on top of this already-compressed representation, which can amplify those imperfections.</p><p>The effect is usually minor with 8-bit quantization, but it becomes more noticeable at 4-bit. If your downstream task is highly sensitive to output quality, it is worth benchmarking the quantized LoRA setup against a full-precision baseline before committing to production.</p><p><strong>Merging vs. Runtime Injection</strong><br>When it comes time to serve the model, you have two fundamentally different strategies for handling the LoRA adapter.</p><blockquote>Runtime Injection</blockquote><blockquote>The base model and LoRA adapter are loaded separately and combined on the fly during inference. This is the most common and flexible approach. It lets you hot-swap adapters at runtime, which is valuable when serving multiple tasks from a single base model. The trade-off is a small, persistent runtime overhead.</blockquote><p><em>Merge and Re-Quantize</em></p><blockquote>You can merge the LoRA weights directly into the base model, eliminating the adapter overhead entirely and producing faster inference. The catch is that merging into quantized weights is non-trivial. You typically need to dequantize, merge, and then re-quantize, which takes time and can introduce additional precision loss.</blockquote><p><strong>Framework and Tooling Support</strong><br>Before building your serving pipeline, confirm that your chosen stack actually supports this configuration end-to-end. The ecosystem is still maturing in places.</p><p>Hugging Face Transformers combined with PEFT and bitsandbytes is the most battle-tested path today. vLLM has been expanding its LoRA support but capabilities can vary between versions. TGI also has LoRA support, though with some limitations depending on the version you are running. Verify your specific version before relying on any of these in production.</p><p><strong>Recommended Deployment Strategy</strong><br>Based on what works well in practice, a reasonable starting point for most production deployments is to use a 4-bit or 8-bit quantized base model using GPTQ or AWQ, keep the LoRA adapter in FP16, load the adapter via PEFT at inference time, and front the whole thing with an optimized serving runtime such as vLLM, TGI, or a custom FastAPI application.</p><p>This configuration balances memory efficiency, inference speed, and operational simplicity without requiring you to navigate the complexities of merging adapters into quantized weights.</p><p><strong>Putting It All Together</strong><br>Deploying LoRA on a quantized model is a powerful strategy precisely because it combines two complementary ideas: quantization handles the raw efficiency problem, and LoRA handles the specialization problem. Together, they make it practical to serve fine-tuned models on modest hardware.</p><p>The complexity lies in managing the seams between them carefully.</p><p>What You Gain :</p><ul><li>Low memory footprint</li><li>Fast inference throughput</li><li>Flexible adapter swapping</li><li>Task-specific fine-tuning</li></ul><p><strong>Code Example</strong></p><p>Qwen2.5-1.5B-Instruct as the base model, loaded in 4-bit precision with a LoRA adapter attached via PEFT.</p><pre>pip install -U transformers peft accelerate bitsandbytes </pre><pre>import torch<br>from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig<br>from peft import PeftModel<br><br># Configuration<br>base_model_id = &quot;Qwen/Qwen2.5-1.5B-Instruct&quot;   <br>lora_adapter_path = &quot;./my_lora_adapter&quot;        <br><br># 4-bit quantization config<br>quant_config = BitsAndBytesConfig(<br>    load_in_4bit=True,<br>    bnb_4bit_quant_type=&quot;nf4&quot;,<br>    bnb_4bit_compute_dtype=torch.bfloat16,<br>    bnb_4bit_use_double_quant=True,<br>)<br><br># Tokenizer<br>tokenizer = AutoTokenizer.from_pretrained(base_model_id, use_fast=True)<br><br>if tokenizer.pad_token is None:<br>    tokenizer.pad_token = tokenizer.eos_token<br><br><br># Load quantized base model<br>base_model = AutoModelForCausalLM.from_pretrained(<br>    base_model_id,<br>    quantization_config=quant_config,<br>    device_map=&quot;auto&quot;,<br>    torch_dtype=torch.bfloat16,<br>)<br><br># Attach LoRA adapter<br>model = PeftModel.from_pretrained(<br>    base_model,<br>    lora_adapter_path,<br>)<br><br># Switch to eval mode for inference<br>model.eval()<br><br># Run generation<br>prompt = &quot;Explain the benefits of LoRA on a quantized base model.&quot;<br>inputs = tokenizer(prompt, return_tensors=&quot;pt&quot;).to(model.device)<br><br>with torch.inference_mode():<br>    outputs = model.generate(<br>        **inputs,<br>        max_new_tokens=200,<br>        do_sample=True,<br>        temperature=0.7,<br>        top_p=0.9,<br>        repetition_penalty=1.1,<br>    )<br><br>print(tokenizer.decode(outputs[0], skip_special_tokens=True))</pre><p>Thank You; Happy reading…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6679db56cf0f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Serving a 70B LLM in Production: Tensor Parallelism, Continuous Batching, and Ray Serve on…]]></title>
            <link>https://medium.com/@raftaarrashedin100/serving-a-70b-llm-in-production-tensor-parallelism-continuous-batching-and-ray-serve-on-125a92fc3ca4?source=rss-99ce24a11be2------2</link>
            <guid isPermaLink="false">https://medium.com/p/125a92fc3ca4</guid>
            <category><![CDATA[tensor]]></category>
            <category><![CDATA[ray-serve]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[prodcution]]></category>
            <category><![CDATA[llmops]]></category>
            <dc:creator><![CDATA[MD RASHEDIN]]></dc:creator>
            <pubDate>Sun, 12 Apr 2026 07:52:09 GMT</pubDate>
            <atom:updated>2026-04-12T11:58:56.390Z</atom:updated>
            <content:encoded><![CDATA[<h3>Serving a 70B LLM in Production: Tensor Parallelism, Continuous Batching, and Ray Serve on Kubernetes</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KN8jxpDhkB8kqd5i" /></figure><p><strong>A complete end-to-end architecture guide — Deep dive into distributed inference</strong></p><p>Getting a 70-billion parameter language model to serve real traffic at low latency is not a software problem in the ordinary sense. It is a distributed systems problem. The model itself is too large for a single GPU, the memory footprint of active inference is enormous, and the naive approach of handling one request at a time squanders the hardware you are paying for. This post walks through an architecture that solves all three of those problems together.</p><p>The stack we are building on is Kubernetes for cluster orchestration, Ray Serve for deployment management and autoscaling, vLLM as the inference engine, and tensor parallelism to split the model across eight GPUs per replica. Each of these layers handles a distinct class of problem, and understanding why they are combined the way they are is the whole point of this post. The goals are straightforward:</p><ul><li><strong>High throughput</strong> — serve many requests concurrently without idle GPUs</li><li><strong>Low latency</strong> — minimize time-to-first-token for interactive use cases</li><li><strong>Horizontal scalability</strong> — add replicas as traffic grows without redesigning the system</li></ul><p><strong>Why a Single GPU Is Not an Option</strong></p><p>A 70B parameter model stored in 16-bit precision requires roughly 140 GB of GPU memory just to hold the weights. An A100 with 80 GB of HBM gets you halfway there. Even with quantization tricks to reduce that footprint, you still need to fit activations, the KV cache for active sequences, and working memory for the computation itself. You will run out of memory well before you run out of useful work to do.</p><p>This is the core argument for tensor parallelism. Rather than trying to compress the model until it fits on one device, you split it across multiple devices and have them cooperate on every forward pass.</p><p><strong>Tensor Parallelism — Splitting the Compute</strong></p><p>In tensor parallelism with eight GPUs, the model’s weight matrices are partitioned column-wise or row-wise across all eight devices. Every GPU holds a slice of every layer, not a separate set of layers. This matters because it means all eight GPUs participate in computing every single token, which keeps the per-token latency low rather than simply increasing throughput by pipelining layers.</p><p>The execution pattern per token looks like this:</p><ul><li>Input is broadcast to all eight GPUs simultaneously</li><li>Each GPU performs a matrix multiplication against its local slice of weights, producing a partial result</li><li>Those partial results are combined across all devices using an AllReduce operation</li><li>Every GPU now holds the correct full output for that layer and moves to the next</li></ul><p>This sequence repeats for every transformer layer in the network. Crucially, all eight GPUs participate in every single token — which is what keeps per-token latency low, as opposed to pipeline parallelism where layers are stacked across devices and latency accumulates.</p><p><strong>What AllReduce Actually Does</strong></p><p>AllReduce is the communication primitive that makes tensor parallelism coherent. It takes a value from each participating device, reduces them using some operation (typically summation), and writes the result back to every device. Consider four GPUs holding partial outputs of 2, 4, 6, and 8 after a matrix multiplication. After AllReduce with summation, all four GPUs hold the value 20. The communication overhead is why high-speed interconnects like NVLink are not optional for this setup — they are load-bearing infrastructure.</p><p>In a transformer, AllReduce fires at two main points during inference:</p><ul><li><strong>After the output projection of the attention block</strong> — combining partial attention outputs from each GPU shard</li><li><strong>After the second linear layer of the feed-forward block</strong> — combining partial MLP outputs before passing to the next layer</li></ul><p><strong>The Distributed KV Cache</strong></p><p>The attention mechanism caches the key and value tensors for every token it has processed, so it does not have to recompute them at each decoding step. This cache grows linearly with sequence length and batch size, and for a 70B model running long sequences it can reach tens of gigabytes. A single GPU cannot hold it.</p><p>The solution follows naturally from the tensor parallelism structure. Since each GPU already holds a shard of the attention weight matrices, it also holds the corresponding shard of the KV cache. At each decoding step, every GPU computes partial attention scores against its local KV shard and then communicates with the other GPUs via AllGather to produce the full attention output. The KV cache is distributed without requiring any separate sharding scheme — it falls out of the model partition for free.</p><p>The KV cache is the single largest driver of memory pressure during inference. Distributing it is not an optimization. For large models and long contexts, it is a requirement for the system to function at all.</p><p><strong>Continuous Batching — Making the GPUs Work</strong></p><p>Traditional static batching waits for a batch of requests to fill up, runs them all together, and waits until every sequence in the batch has finished before accepting the next batch. This approach has a crippling inefficiency: sequences in the same batch finish at different times, but the batch cannot release until the longest sequence completes. The GPUs sit idle waiting for the stragglers.</p><p>Continuous batching, as implemented in vLLM, eliminates this waiting. The scheduler maintains an active set of sequences that is updated after every single decoding step. When a sequence finishes, it is immediately evicted from the active set and a waiting request is inserted in its place. The GPU never idles between sequences. From the GPU’s perspective there is no such thing as a batch boundary — there is only a continuously shifting set of active sequences that it steps through one token at a time.</p><p>This is handled entirely within vLLM and requires no configuration from the serving layer above it. When you instantiate the engine, continuous batching is active by default.</p><p><strong>The System Architecture</strong></p><blockquote>Request path</blockquote><blockquote>Client</blockquote><blockquote>↓ HTTP</blockquote><blockquote>API Gateway</blockquote><blockquote>↓ route</blockquote><blockquote>Ray Serve — request routing, autoscaling, lifecycle</blockquote><blockquote>↓ dispatch</blockquote><blockquote>LLM Replicas — vLLM engine, continuous batching scheduler</blockquote><blockquote>↓ compute</blockquote><blockquote>Tensor Parallel GPUs (TP=8) — AllReduce, distributed KV cache</blockquote><blockquote>↓ stream tokens</blockquote><blockquote>Client receives streaming response</blockquote><p><strong>The Kubernetes Layer</strong></p><p>Each model replica needs one node with eight GPUs connected over NVLink. Kubernetes handles scheduling those nodes, maintaining their health, and exposing the Ray cluster to the rest of the infrastructure. The Ray operator for Kubernetes manages the head node and worker nodes as first-class Kubernetes resources.</p><pre>apiVersion: ray.io/v1<br>kind: RayCluster<br>metadata:<br>  name: llm-cluster<br>spec:<br>  headGroupSpec:<br>    serviceType: ClusterIP<br>    replicas: 1<br>    template:<br>      spec:<br>        containers:<br>        - name: ray-head<br>          image: rayproject/ray:latest<br>          resources:<br>            limits:<br>              cpu: &quot;8&quot;<br>              memory: &quot;32Gi&quot;<br><br>  workerGroupSpecs:<br>  - replicas: 2<br>    groupName: gpu-workers<br>    template:<br>      spec:<br>        containers:<br>        - name: ray-worker<br>          image: rayproject/ray:latest<br>          resources:<br>            limits:<br>              nvidia.com/gpu: 8<br>              cpu: &quot;32&quot;<br>              memory: &quot;256Gi&quot;</pre><p>Two worker groups gives you two model replicas, each using eight GPUs. Ray Serve routes incoming requests across both replicas, so you can handle twice the peak throughput of a single replica and survive a node failure without downtime.</p><p><strong>The Ray Serve Deployment</strong></p><p>Ray Serve sits between the API gateway and the vLLM engine. It handles replica lifecycle management, health checks, and request routing. Each replica is a Python actor that holds a vLLM engine instance initialized with tensor parallel size 8. The deployment decorator tells Ray Serve how many replicas to run and how many GPUs each actor requires.</p><pre>pip install ray[serve,llm]</pre><pre>from ray import serve <br>from vllm import LLM, SamplingParams <br> <br>@serve.deployment( <br> num_replicas=2, <br> ray_actor_options={&quot;num_gpus&quot;: 8} <br>) <br>class LLMDeployment: <br>   def __init__(self): <br>     self.llm = LLM( <br>     model=&quot;meta-llama/Llama-3–70B&quot;, <br>     tensor_parallel_size=8, <br>     gpu_memory_utilization=0.9 <br>     ) <br>   <br>   async def __call__(self, request): <br>     data = await request.json() <br>     outputs = self.llm.generate( <br>       [data[&quot;prompt&quot;]], <br>       SamplingParams( <br>       max_tokens=200, <br>       temperature=0.7 <br>       ) <br>     ) <br>     return outputs[0].outputs[0].text <br> <br>serve.run(LLMDeployment.bind())</pre><p>Setting gpu_memory_utilization to 0.9 tells vLLM it can use 90% of GPU memory for the KV cache after loading the model weights. The remaining 10% is left as headroom for activations and other working memory. This is the primary knob for trading off batch size against stability — higher values increase throughput until you start hitting out-of-memory errors under load.</p><p><strong>Operational note</strong> The initialization of a 70B model across eight GPUs takes a few minutes. Ray Serve considers the replica unready until __init__ returns, so it will not route traffic to a replica that is still loading. Build health check timeouts in your gateway accordingly.</p><p><strong>07 Request Flow (End-to-End)</strong></p><blockquote>Client sends request</blockquote><blockquote>API Gateway forwards request</blockquote><blockquote>Ray Serve receives request</blockquote><blockquote>Request enters batching queue</blockquote><blockquote>vLLM scheduler merges into active batch</blockquote><blockquote>Tensor-parallel GPUs process tokens</blockquote><blockquote>Tokens streamed back to client</blockquote><p>Tracing this through the stack makes the architecture concrete. A client sends a POST to the API gateway. The gateway forwards it to the Ray Serve endpoint. Ray Serve picks one of the two replicas based on current load and dispatches the request to that replica’s actor. The actor calls into the vLLM engine, which adds the request to the continuous batching scheduler’s queue.</p><p>On the next scheduling cycle, the scheduler merges the new request into the active batch alongside whatever other sequences are currently being decoded. The active batch goes to the tensor-parallel GPU group. All eight GPUs process their weight shards in parallel, communicate via AllReduce at the end of each layer, and advance every sequence in the batch by one token. Sequences that hit their stopping condition are evicted. New sequences from the queue fill the vacated slots.</p><p>Tokens are streamed back through Ray Serve to the gateway and then to the client as they are generated, so the client starts receiving output before the full response is complete. This matters for perceived latency even when total generation time is long.</p><p>Happy reading…<br>Thank You.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=125a92fc3ca4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deployment of a Large Language Model (LLM) on Triton Inference Server]]></title>
            <link>https://medium.com/@raftaarrashedin100/deployment-of-a-large-language-model-llm-on-triton-inference-server-07d19f3ea794?source=rss-99ce24a11be2------2</link>
            <guid isPermaLink="false">https://medium.com/p/07d19f3ea794</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[triton-inference-server]]></category>
            <category><![CDATA[hugging-face]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[MD RASHEDIN]]></dc:creator>
            <pubDate>Mon, 16 Sep 2024 10:10:50 GMT</pubDate>
            <atom:updated>2024-09-16T11:02:01.815Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5ywGGuN0K8nYFGyLZfcUKA.jpeg" /></figure><p>Deploying an LLM model on triton server include several steps like model preparing, preparing the triton server, and configuring and setting up the triton server.</p><p>we will go through some steps here, below is the guide to deploy an LLM on triton server.</p><h3>Preparing the model</h3><p><strong>PyTorch Model </strong>— Must need to export the model in onnx format, we can do by using “<em>torch.onnx.export”.</em></p><p><strong>TensorFlow Model </strong>— We can use the “SavedModel” format to export the model.</p><p><strong>Hugging Face Transformers — </strong>Must need to export the model in onnx format, for that we can do by using “transformers.onnx”. I have also used the Hugging Face Transformer Model here.</p><h3>Model Repository Setup</h3><p>Now this is very important setup for deploying any model on Triton because Triton requires a structured directory for your models.</p><p>below is the directory structure example :</p><pre>model_repository/<br>└── hugging_face_model/<br>    ├── 1/<br>    │   └── model.onnx<br>    └── config.pbtxt</pre><p>inside the model_repository we can put any models we want for text detection, text recognition etc.</p><p>1/ — this is the version no. of our model.</p><p>model.onnx — this contains our onnx format model.</p><p>config.pbtxt — A configuration file for Triton to understand how to react or serve the model. below is the explanation of it.</p><p>This is how you can convert a hugging face model into onnx format. Below is the python script for that.</p><pre>from pathlib import Path<br>import transformers<br>from transformers.onnx import FeaturesManager<br>from transformers import AutoConfig, AutoTokenizer, AutoModelForSequenceClassification<br><br># load model and tokenizer<br>model_id = &quot;hugging_face_repo_name/your_model_name&quot;<br>model = AutoModelForSequenceClassification.from_pretrained(model_id)<br>tokenizer = AutoTokenizer.from_pretrained(model_id)<br>dummy_model_input = tokenizer(&quot;This is a sample&quot;, return_tensors=&quot;pt&quot;)<br><br># export<br>torch.onnx.export(<br>    model, <br>    tuple(dummy_model_input.values()),<br>    f=&quot;torch-model.onnx&quot;,  <br>    input_names=[&#39;input_ids&#39;, &#39;attention_mask&#39;], <br>    output_names=[&#39;logits&#39;], <br>    dynamic_axes={&#39;input_ids&#39;: {0: &#39;batch_size&#39;, 1: &#39;sequence&#39;}, <br>                  &#39;attention_mask&#39;: {0: &#39;batch_size&#39;, 1: &#39;sequence&#39;}, <br>                  &#39;logits&#39;: {0: &#39;batch_size&#39;, 1: &#39;sequence&#39;}}, <br>    do_constant_folding=True, <br>    opset_version=13, <br>)</pre><h3>Create the configuration file (config.pbtxt)</h3><p>The config.pbtxt file describe the model to Triton. Below is an simple format for a HuggingFaceModel.</p><pre>name: &quot;hugging_face_model&quot;<br>platform: &quot;onnxruntime_onnx&quot;<br>max_batch_size: 8<br>input [<br>  {<br>    name: &quot;input_ids&quot;<br>    data_type: TYPE_INT32<br>    dims: [ -1, 128 ]<br>  },<br>  {<br>    name: &quot;attention_mask&quot;<br>    data_type: TYPE_INT32<br>    dims: [ -1, 128 ]<br>  }<br>]<br>output [<br>  {<br>    name: &quot;logits&quot;<br>    data_type: TYPE_FP32<br>    dims: [ -1, 128, 50257 ]<br>  }<br>]</pre><p><strong>Explanation</strong></p><p>“name: hugging_face_model” — name of the model.</p><p>“platform: onnxruntime_onnx” — This specifies the runtime platform used to serve the model. for example onnxruntime_onnx indicates that Triton will use the ONNX Runtime to execute this model in case of TensorRT the platform would have been different.</p><p>“max_batch_size” — means that the model can take up to 8 inputs in a single batch request.</p><p><strong>Input configuration</strong></p><p>this section defines model inputs, their types, and expected shapes.</p><pre>input [<br>  {<br>    name: &quot;input_ids&quot;<br>    data_type: TYPE_INT32<br>    dims: [ -1, 128 ]<br>  },<br>  {<br>    name: &quot;attention_mask&quot;<br>    data_type: TYPE_INT32<br>    dims: [ -1, 128 ]<br>  }<br>]</pre><p><strong>input_ids</strong></p><p>“name” — &quot;input_ids&quot; refers to the input token IDs that represent the input text.</p><p>“data_type” — TYPE_INT32 means this input expects 32-bit integer values.</p><p>“dims” — [ -1, 128 ], -1 means the batch size can vary. 128 this means that input can have 128 tokens. Any input shorter than 128 tokens will likely be padded, and longer inputs will be truncated.</p><p><strong>attention_mask</strong></p><p>“name” — attention_mask refers to the mask used to indicate which token in the input are valid and which are padding (since not all inputs will have 128 tokens).</p><p>“data_type” — TYPE_INT32, same as input_ids, indicating 32 bit integer.</p><p>“dims”: [ -1, 128 ], meaning the attention mask must match the batch size and sequence length of the input.</p><p><strong>Output configuration</strong></p><p>This section defines the model’s output, including its name, data type, and shape.</p><pre>output [<br>  {<br>    name: &quot;logits&quot;<br>    data_type: TYPE_FP32<br>    dims: [ -1, 128, 50257 ]<br>  }<br>]</pre><p><strong>logits</strong></p><p>“name”: &quot;logits&quot; refers to the raw output of the model before it’s transformed into probabilities (softmax) or final predictions.</p><p>“data_type”: TYPE_FP32 means the output will be 32-bit floating point numbers.</p><p>“dims”: [ -1, 128, 50257 ] describes the shape of the logits tensor. 1, this means the batch size is very flexible. 128, means the model produces output for each token in the sequence. 50257: The third dimension corresponds to the vocabulary size. This means the model outputs a prediction (logit) for each possible token in the vocabulary at each position in the sequence.</p><h3>Launch Triton Inference Server</h3><p>for starting the Triton server, we will do it via docker.</p><pre>docker run --gpus=all --rm -p8000:8000 -p8001:8001 -p8002:8002 \<br>    -v/path/to/your/model_repository:/models nvcr.io/nvidia/tritonserver:23.01-py3 \<br>    tritonserver --model-repository=/models</pre><p>Once Triton Inference Server has been built or once inside the container, it can be launched with the command:</p><pre>tritonserver --model-repository=/models</pre><p>model instances will be ready for inference. and you will get output like this</p><pre>I0712 16:37:18.246487 128 server.cc:626]<br>+------------------+---------+--------+<br>| Model            | Version | Status |<br>+------------------+---------+--------+<br>| hugg_face_model  | 1       | READY  |<br>+------------------+---------+--------+<br>I0712 16:37:18.267625 128 metrics.cc:650] Collecting metrics for GPU 0: NVIDIA GeForce RTX 3090<br>I0712 16:37:18.268041 128 tritonserver.cc:2159]<br>+----------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+<br>| Option                           | Value                                                                                                                                                                                        |<br>+----------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+<br>| server_id                        | triton                                                                                                                                                                                       |<br>| server_version                   | 2.37.0                                                                                                                                                                                       |<br>| server_extensions                | classification sequence model_repository model_repository(unload_dependents) schedule_policy model_configuration system_shared_memory cuda_shared_memory binary_tensor_data statistics trace |<br>| model_repository_path[0]         | /models                                                                                                                                                                                      |<br>| model_control_mode               | MODE_NONE                                                                                                                                                                                    |<br>| strict_model_config              | 1                                                                                                                                                                                            |<br>| rate_limit                       | OFF                                                                                                                                                                                          |<br>| pinned_memory_pool_byte_size     | 268435456                                                                                                                                                                                    |<br>| cuda_memory_pool_byte_size{0}    | 67108864                                                                                                                                                                                     |<br>| response_cache_byte_size         | 0                                                                                                                                                                                            |<br>| min_supported_compute_capability | 6.0                                                                                                                                                                                          |<br>| strict_readiness                 | 1                                                                                                                                                                                            |<br>| exit_timeout                     | 30                                                                                                                                                                                           |<br>+----------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+<br>I0712 16:37:18.269464 128 grpc_server.cc:4587] Started GRPCInferenceService at 0.0.0.0:8001<br>I0712 16:37:18.269956 128 http_server.cc:3303] Started HTTPService at 0.0.0.0:8000<br>I0712 16:37:18.311686 128 http_server.cc:178] Started Metrics Service at 0.0.0.0:8002</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*0hEvLPZnK9IOh2OgOq6YRw.png" /></figure><h3>Test the Deployment</h3><p>We can interact with the Triton server via HTTP or gRPC to send inference requests. Triton provides Python client libraries to make it easy.</p><pre># client.py<br>import tritonclient.http as httpclient<br>model_name = &quot;hugging_face_model&quot;<br>client = httpclient.InferenceServerClient(url=&quot;localhost:8000&quot;)<br># Define your input tensors and send the request<br>inputs = [<br>    httpclient.InferInput(&quot;input_ids&quot;, [1, 128], &quot;INT32&quot;),<br>    httpclient.InferInput(&quot;attention_mask&quot;, [1, 128], &quot;INT32&quot;)<br>]<br>outputs = [httpclient.InferRequestedOutput(&quot;logits&quot;)]<br>response = client.infer(model_name, inputs, outputs=outputs)<br>print(response.as_numpy(&quot;logits&quot;))</pre><p>to run the client application</p><pre>pip install tritonclient[http] opencv-python-headless<br>python client.py</pre><h3>Send inference request</h3><pre>import tritonclient.http as httpclient<br>from transformers import AutoTokenizer<br>import numpy as np<br><br>model_name = &quot;your model name&quot;<br>tokenizer = AutoTokenizer.from_pretrained(model_name)<br><br>triton_server_url = &quot;localhost:8000&quot;<br>client = httpclient.InferenceServerClient(url=triton_server_url)<br><br>text = &quot;Triton server inference example.&quot;<br>inputs = tokenizer(text, return_tensors=&quot;np&quot;, max_length=128, padding=&quot;max_length&quot;, truncation=True)<br><br>input_ids = httpclient.InferInput(&quot;input_ids&quot;, inputs[&#39;input_ids&#39;].shape, &quot;INT32&quot;)<br>attention_mask = httpclient.InferInput(&quot;attention_mask&quot;, inputs[&#39;attention_mask&#39;].shape, &quot;INT32&quot;)<br><br>input_ids.set_data_from_numpy(inputs[&#39;input_ids&#39;])<br>attention_mask.set_data_from_numpy(inputs[&#39;attention_mask&#39;])<br><br>output = httpclient.InferRequestedOutput(&quot;logits&quot;)<br><br>response = client.infer(<br>    model_name=&quot;hugging_face_model&quot;,<br>    inputs=[input_ids, attention_mask],<br>    outputs=[output]<br>)<br><br>logits = response.as_numpy(&quot;logits&quot;)<br>predicted_token_ids = np.argmax(logits, axis=-1)<br>predicted_text = tokenizer.decode(predicted_token_ids[0], skip_special_tokens=True)<br><br>print(f&quot;Predicted Text: {predicted_text}&quot;)</pre><p>Output</p><pre>Predicted Text: Triton server inference is successful.</pre><p>That’s it.</p><p>Thank You.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=07d19f3ea794" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fine-Tuning LLM model (Meta-Llama-3.1–8B) using unsloth for Text-to-SQL Data]]></title>
            <link>https://blog.gopenai.com/fine-tuning-llm-model-meta-llama-3-1-8b-for-text-to-sql-data-ea5a07620dd3?source=rss-99ce24a11be2------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea5a07620dd3</guid>
            <category><![CDATA[fine-tuning]]></category>
            <category><![CDATA[llama-3]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[MD RASHEDIN]]></dc:creator>
            <pubDate>Mon, 02 Sep 2024 09:03:08 GMT</pubDate>
            <atom:updated>2024-09-04T15:19:49.962Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9FonN-dedpiJkhAOOYHuUg.jpeg" /></figure><p>Training a large language model requires substantial computational resources and memory, which can be a significant challenge. To address this, we will focus on fine-tuning large language models for the text-to-SQL task.</p><p><strong>Meta LLaMA 3.1 8B Model:</strong> Meta’s LLaMA 3.1 8B is a state-of-the-art language model with 8 billion parameters. This model balance between computational efficiency and performance, making it suitable for a wide range of natural language processing tasks, including text-to-SQL. The 8B parameter size allows the model to capture language patterns and generate high-quality SQL queries from natural language inputs.</p><p><strong>Unsloth Library:</strong> To optimize the training and fine-tuning process, we will utilize the Unsloth library. Unsloth specializes in providing quantized versions of base models.This approach helps in efficiently deploying and fine-tuning large models like LLaMA 3.1 8B, especially when working with limited resources.</p><p><strong>Fine-Tuning for Text-to-SQL:</strong> In the context of text-to-SQL tasks, fine-tuning involves adapting the pre-trained LLaMA 3.1 8B model to generate SQL queries from natural language descriptions. This involves training the model on a specialized dataset that includes various text-to-SQL examples.</p><p><strong>Importing the libraries</strong></p><pre>from unsloth import FastLanguageModel<br>import torch</pre><p><strong>Configuration parameters</strong></p><pre>max_seq_length = 2048 # we support rope scaling internally<br>dtype = None<br>load_in_4bit = True # 4 bit quantization to reduce memory</pre><p><em>Rope Scaling — RoPE Scaling adjusts the embedding parameters to extend the model’s capability beyond its original training length.</em></p><p><strong>Model Initialization and Configuration</strong></p><pre># Loading the pre-trained model and tokenizer with the specified configuration.<br><br><br>model, tokenizer = FastLanguageModel.from_pretrained(<br>    model_name = &quot;unsloth/Meta-Llama-3.1-8B-bnb-4bit&quot;,<br>    max_seq_length = max_seq_length,<br>    dtype = dtype,<br>    load_in_4bit = load_in_4bit,<br>)</pre><p><strong>Configure PEFT(Parameter Efficient Fine Tuning) Model</strong></p><p><strong>PEFT</strong> — PEFT stands for <strong>Parameter-Efficient Fine-Tuning</strong>. In the context of fine-tuning pre-trained models like large language models, where the goal is to adapt the model to a specific task or dataset while minimizing the number of parameters that need to be updated. Instead of adjusting all the parameters of the pre-trained model, PEFT techniques focus on optimizing a small subset of parameters or introducing additional parameters that are fine-tuned.</p><pre># Applies Parameter Efficient Fine-Tuning (PEFT) techniques like LoRA (Low-Rank Adaptation) to the model.<br>model = FastLanguageModel.get_peft_model(<br>    model,<br>    r = 16,<br>    target_modules = [...],<br>    lora_alpha = 16,<br>    lora_dropout = 0,<br>    bias = &quot;none&quot;,<br>    use_gradient_checkpointing = &quot;unsloth&quot;,<br>    random_state = 3407,<br>    use_rslora = False,<br>    loftq_config = None,<br>)</pre><p><strong>Define your own prompt template</strong></p><pre># Template for generating SQL responses based on input questions and context.<br>sql_prompt = &quot;&quot;&quot;Below is input question that user ask, context is given to help user&#39;s question, generate SQL response for user&#39;s question.<br><br>### Input:<br>{}<br><br>### Context:<br>{}<br><br>### SQL Response:<br>{}&quot;&quot;&quot;</pre><p><em>Format the dataset for training by combining context, question, and SQL response using the define prompt template.</em></p><pre>def formatting_prompts_func(examples):<br>    instructions = examples[&quot;context&quot;] # note : these are my columns <br>    inputs = examples[&quot;question&quot;] # this one<br>    outputs = examples[&quot;sql_query&quot;] # and this one <br>    texts = []<br>    for instruction, input, output in zip(instructions, inputs, outputs):<br>        text = alpaca_prompt.format(instruction, input, output) + EOS_TOKEN<br>        texts.append(text)<br>    return {&quot;text&quot;: texts,}</pre><p><strong>Dataset preparation</strong></p><p>To obtain a dataset tailored to your specific use case, you have two main options: downloading a pre-existing dataset from the internet, which might not perfectly fit your needs, or manually creating your own dataset.</p><p>For the latter approach, you can leverage ChatGPT to generate questions, contexts, and SQL queries. Provide ChatGPT with a prompt that includes your desired schema and instructions, and it can generate a large number of queries — such as 500 or 1,000.</p><p>Once you have these queries, you can either use web scraping techniques or manually compile the results into a CSV or XLSX file. This custom dataset can then be utilized according to your requirements.</p><p>this is how my dataset look like :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P2FJvosW4ePRTR0thtI26Q.png" /></figure><pre>from datasets import load_dataset<br>import pandas as pd<br><br>df = pd.read_excel(&#39;fine-tuning-dataset_latest.xlsx&#39;)<br>from datasets import Dataset<br>dataset = Dataset.from_pandas(df)<br>train_test_split = dataset.train_test_split(test_size=0.2)<br>train_dataset = train_test_split[&#39;train&#39;]<br>validation_dataset = train_test_split[&#39;test&#39;]<br>dataset = dataset.map(formatting_prompts_func, batched=True)</pre><p><em>note : better to convert in hugging face dataset format</em></p><p><strong>Training Configuration</strong></p><pre>from trl import SFTTrainer<br>from transformers import TrainingArguments<br>from unsloth import is_bfloat16_supported<br><br>trainer = SFTTrainer(<br>    model = model,<br>    tokenizer = tokenizer,<br>    train_dataset = dataset,<br>    dataset_text_field = &quot;text&quot;,<br>    max_seq_length = max_seq_length,<br>    dataset_num_proc = 2,<br>    packing = False,<br>    args = TrainingArguments(  # here we defined the TrainingArguments<br>        per_device_train_batch_size = 2,<br>        gradient_accumulation_steps = 4,<br>        warmup_steps = 5,<br>        num_train_epochs = 1,<br>        max_steps = 60,<br>        learning_rate = 2e-4,<br>        fp16 = not is_bfloat16_supported(),<br>        bf16 = is_bfloat16_supported(),<br>        logging_steps = 1,<br>        optim = &quot;adamw_8bit&quot;,<br>        weight_decay = 0.01,<br>        lr_scheduler_type = &quot;linear&quot;,<br>        seed = 3407,<br>        output_dir = &quot;outputs&quot;,<br>    ),<br>)</pre><p><strong><em>SFTTTrainer</em></strong><em> — SFTTTrainer is a software tool designed to assist in the training of machine learning models. It stands for </em><strong><em>Structured Fine-Tuning Training Trainer</em></strong><em>. It’s primarily used to manage and streamline the fine-tuning process of pre-trained models.</em></p><p>Let’s dive into highlighted arguments :</p><p><strong>model</strong> — The language model to be trained, here we are using Meta-Llama-3.1–8B-bnb-4bit.</p><p><strong>tokenizer</strong> — The tokenizer associated with the model. It converts text into token IDs that the model can process.</p><p><strong>train_dataset</strong> — The dataset we are going to train.</p><p><strong>max_seq_length</strong> — The maximum length of input sequences.</p><p><strong>per_device_train_batch_size</strong> — The batch size for training on each device(e.g., GPU).</p><p><strong>gradient_accumulation_steps</strong> — Number of steps to accumulate gradient before performing an optimization step.</p><p><strong>warmup_steps</strong> — Number of steps to perform learning rate warmup.</p><p><strong>num_train_epochs</strong> — Number of epochs to train the model.</p><p><strong>learning_rate</strong> — The learning rate for the optimizer. This controls how much to adjust the model weights during training.</p><p><strong>weight_decay</strong> — Weight decay regularization to prevent overfitting.</p><p><strong>Training the model</strong></p><pre>trainer = trainer.train()</pre><p><strong>Save Model and Tokenizer</strong></p><pre>trainer.model.save_pretrained(&quot;fine_tuned_model&quot;)<br>tokenizer.save_pretrained(&quot;fine_tuned_model&quot;)<br>print(&quot;done&quot;)<br></pre><p><strong>Output</strong></p><pre>{&#39;train_runtime&#39;: 319.1206, &#39;train_samples_per_second&#39;: 1.504, &#39;train_steps_per_second&#39;: 0.188, &#39;train_loss&#39;: 1.0322736293077468, &#39;epoch&#39;: 0.26}<br>319.1206 seconds used for training.<br>5.32 minutes used for training.</pre><p><a href="https://huggingface.co/raftaarrashedin/meta-llama3.1-8b-sql-finetuned">From here</a>, you can use my hugging-face model.</p><p><a href="https://huggingface.co/raftaarrashedin/meta-llama3.1-8b-sql-finetuned">https://huggingface.co/raftaarrashedin/meta-llama3.1-8b-sql-finetuned</a></p><p>That’s it.</p><p>Thank You.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea5a07620dd3" width="1" height="1" alt=""><hr><p><a href="https://blog.gopenai.com/fine-tuning-llm-model-meta-llama-3-1-8b-for-text-to-sql-data-ea5a07620dd3">Fine-Tuning LLM model (Meta-Llama-3.1–8B) using unsloth for Text-to-SQL Data</a> was originally published in <a href="https://blog.gopenai.com/">GoPenAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building of a Neural Network (short article).]]></title>
            <link>https://medium.com/@raftaarrashedin100/building-of-a-neural-network-short-article-50ef966937de?source=rss-99ce24a11be2------2</link>
            <guid isPermaLink="false">https://medium.com/p/50ef966937de</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[backward-propagation]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[forward-propagation]]></category>
            <category><![CDATA[neural-networks]]></category>
            <dc:creator><![CDATA[MD RASHEDIN]]></dc:creator>
            <pubDate>Fri, 30 Jun 2023 18:24:17 GMT</pubDate>
            <atom:updated>2023-06-30T18:24:17.425Z</atom:updated>
            <content:encoded><![CDATA[<p>Building of a Neural Network (short article).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*a4xOtncbFJ0BNKp4pDJonA.jpeg" /><figcaption>Source :- clearpng</figcaption></figure><p>Building of a neural network model, yes it’s actually inspired by the biological thing which is inside our brains, but things are not the same here, we can build this using Forward Propagation and Backward Propagation.</p><p>Forward propagation is the process of moving an input through a neural network to produce an output. During forward propagation, the input is multiplied by weights and biases, and passed through activation functions to produce an output.</p><p>Backward propagation, also known as backpropagation, is a process used to train neural networks. During backpropagation, the neural network calculates the difference between its predicted output and the actual output, and uses this information to adjust its weights and biases. This process is repeated multiple times until the neural network’s predictions are accurate.</p><p>Now the question arises which is best? forward propagation or backward propagation ?Both forward propagation and backward propagation are important for training neural networks. Forward propagation is used to produce an output given an input, while backward propagation is used to adjust the neural network’s weights and biases to improve its predictions. Without forward propagation, we wouldn’t be able to produce an output given an input, and without backward propagation, we wouldn’t be able to train the neural network to improve its predictions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50ef966937de" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Web Scrapping of a website using python and beautifulsoup4.]]></title>
            <link>https://medium.com/@raftaarrashedin100/web-scrapping-of-a-website-using-python-and-beautifulsoup4-9a5ec9d6e3db?source=rss-99ce24a11be2------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a5ec9d6e3db</guid>
            <category><![CDATA[python-beautifulsoup4]]></category>
            <category><![CDATA[beautifulsoup]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[MD RASHEDIN]]></dc:creator>
            <pubDate>Thu, 27 Apr 2023 09:53:13 GMT</pubDate>
            <atom:updated>2023-04-27T09:53:13.091Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*MFMYifQAzrJ5MUujYiNnnw.jpeg" /></figure><p>First of all,</p><p>We will install some libraries here.</p><pre>pip install beautifulsoup4<br>pip install lxml<br>pip install requests</pre><p>we will write python code for fetch data from website like job name, job skill, job published time and upload it as a text file in a folder.</p><pre>from bs4 import BeautifulSoup<br><br>import requests<br>import time<br>def find_jobs() :<br>  html_text = requests.get(&#39;https://www.timesjobs.com/candidate/job-search.html?searchType=personalizedSearch&amp;from=submit&amp;txtKeywords=Machine+Learning&amp;txtLocation=Hyderabad%2F+Secunderabad&amp;cboWorkExp1=0&#39;).text<br><br>  #print(html_text)<br><br>  soup = BeautifulSoup(html_text,&#39;lxml&#39;)<br><br>  jobs = soup.find_all(&#39;li&#39;, class_ = &#39;clearfix job-bx wht-shd-bx&#39;)<br><br>  print(&#39;Put some skill that you are not familiar with.&#39;)<br><br>  unfamiliar_skill = input(&#39;&gt;&#39;)<br><br>  print(f&#39;Filtering out {unfamiliar_skill}&#39;)<br><br><br>  for index,job in enumerate(jobs) :<br><br><br><br>    published_date = job.find(&#39;span&#39;, class_ = &#39;sim-posted&#39;).span.text<br><br>    if &#39;few&#39; in published_date :<br><br>      company_name = job.find(&#39;h3&#39;, class_=&#39;joblist-comp-name&#39;).text.replace(&#39;  &#39;,&#39;&#39;)<br><br>      skills = job.find(&#39;span&#39;, class_ = &#39;srp-skills&#39;).text.replace(&#39;  &#39;,&#39;&#39;)<br><br>      more_info = job.header.h2.a[&#39;href&#39;]<br><br>      if unfamiliar_skill not in skills :<br><br>        with open(f&#39;posts/{index}.txt&#39;,&#39;w&#39;) as f :<br>          # print(f&#39;&#39;&#39;<br>          #   Company Name : {company_name}<br>          #   Required Skills : {skills}<br>          #   Job Status : {published_date}<br>          # &#39;&#39;&#39;)<br>          print(&#39;-----------------------------------&#39;)<br>          f.write(f&quot;Company Name : {company_name.strip()}&quot;)<br>          f.write(f&quot;Required Skills : {skills.strip()}&quot;)<br>          f.write(f&quot;Published Date : {published_date.strip()}&quot;)<br>          f.write(f&quot;More Info : {more_info.strip()}&quot;)<br>          print(&#39;-----------------------------------&#39;)<br><br>        print(f&#39;File Saved: {index}&#39;)<br><br><br>if __name__ == &#39;__main__&#39; :<br>  while True:<br>    find_jobs()<br>    time_wait = 10<br>    print(f&#39;Waiting {time_wait} minute...&#39;)<br>    time.sleep(time_wait * 60)<br><br></pre><p>That’s all!</p><p>Thank You!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a5ec9d6e3db" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sqlite3 connection using python in Google Colab]]></title>
            <link>https://medium.com/@raftaarrashedin100/sqlite-connection-using-python-in-google-colab-6c8130fd672d?source=rss-99ce24a11be2------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c8130fd672d</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[sqlite]]></category>
            <dc:creator><![CDATA[MD RASHEDIN]]></dc:creator>
            <pubDate>Wed, 12 Apr 2023 18:20:32 GMT</pubDate>
            <atom:updated>2023-04-12T18:22:00.391Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A9w5-o_IWFqha29nq5VtLQ.jpeg" /></figure><p>Here we will connect the database sqlite using python, and perform some SQL query.</p><p>First we will install sqlite.</p><pre>!pip install db-sqlite3</pre><p>Now, we will import some necessary packages.</p><pre>import pandas as pd<br>import sqlite3<br>from datetime import date</pre><p>We will connect to the database :</p><pre>db = sqlite3.connect(&quot;raftaar.db&quot;)</pre><p>We will create database here :</p><pre>db.execute(&quot; if table exists then drop the table&quot;)<br>try :<br>  db.execute(&quot;Create table Student(Name text,Date datetime, Mobile text, Mail text)&quot;)<br>except :<br>  print(&quot;Table already exist&quot;)</pre><pre>db = sqlite3.connect(&quot;raftaar.db&quot;)<br>Name = &quot;raftaar69&quot;<br>Date = date.today().strftime(&quot;%d-%m-%y&quot;)<br>Mobile = &quot;0990&quot;<br>Mail = &quot;raftaar@xd.com&quot;</pre><pre>insertQ = &quot;insert into Student(Name, Date, Mobile, Mail) values(&#39;{}&#39;,&#39;{}&#39;,&#39;{},&#39;{}&#39;)&quot;.format(Name, Date, Mobile, Mail)<br>db.execute(insertQ)<br>db.commit()</pre><p>Show insert data in db:</p><pre>db = sqlite3.connect(&quot;raftaar.db&quot;)<br>slct = db.execute(&quot;select * from Student&quot;)<br><br>for row in slct:<br>  print(row)</pre><p>Showing result in Pandas Data Frame :</p><pre>db = sqlite3.connect(&quot;raftaar.db&quot;)<br>query = &quot;&quot;&quot;<br>  select * from student<br>&quot;&quot;&quot;<br>df = pd.read_sql_query(query,db)<br>df.head()</pre><p>Check result through your own.</p><p>Thank You.</p><p>Let’s meet on <a href="http://linkedin.com/in/md-rashedin-2a3768210">LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c8130fd672d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SVM(Support Vector Machine) from scratch using Python]]></title>
            <link>https://medium.com/@raftaarrashedin100/svm-from-scratch-using-python-893af5749620?source=rss-99ce24a11be2------2</link>
            <guid isPermaLink="false">https://medium.com/p/893af5749620</guid>
            <category><![CDATA[support-vector-machine]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[svm-algorithm]]></category>
            <dc:creator><![CDATA[MD RASHEDIN]]></dc:creator>
            <pubDate>Fri, 10 Mar 2023 18:37:32 GMT</pubDate>
            <atom:updated>2023-03-10T18:38:01.444Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sM-LIco9tS9LjrsTNAvcdg.jpeg" /></figure><p>Here we will just implement the SVM Classifier class from Scratch.</p><pre># importing Library<br>import numpy as np</pre><p>Now, we will define SVM class</p><pre>class SVM_classifier() :<br>  <br>  # initiating the parameter<br>  def __init__(self,learning_rate,no_of_iterations, lambda_parameter) :<br>    self.learning_rate = learning_rate<br>    self.no_of_iterations = no_of_iterations<br>    self.lambda_parameter<br><br>  # fitting the dataset to SVM classifier<br>  def fit(self,X,Y) :<br>    # dp -&gt; no. of data points<br>    # i_f -&gt; no. of input features<br>    self.dp,self.i_f = X.shape<br>    <br>    # Initiating the weight value and bias value<br>    self.w = np.zeros(self)<br>    <br>    self.b = 0<br>    self.X = X<br>    self.Y = Y<br>  <br>    # Implementing gradient descent algorithm for optimization<br>  <br>    for i in range(self.no_of_iterations) :<br>      self.update_weights()<br><br>  <br>  # function for updating the weights and bias value<br>  def update_weight(self) :<br>    <br>    # label encoding<br>    y_label = np.where(self.Y &lt;= 0, -1, 1)<br><br>    # gradient (dw,db)<br>    for index, x_i in enumerate(self.X) :<br>      condition = y_label[index] * (np.dot(x_i,self.w) - self.b) &gt;= 1<br>      if(condition == True):<br>        dw = 2 * self.lambda_parameter * self.w<br>        db = 0<br>      else :<br>        dw = 2 * self.lambda_parameter * self.w - np.dot(x_i,y_label[index])<br>        db = y_label[index]<br>      <br>      self.w = self.w - self.learning_rate * dw<br>      self.b = self.b - self.learning_rate * db<br><br>  <br>  # predicting the label for giving input<br>  def predict(self) :<br>    <br>    output = np.dot(X, self.w) - self.b<br>    <br>    predicted_labels = np.sign(output)<br>    <br>    y_hat = np.where(predicted_labels &lt;= -1,0,1)<br><br>    return y_hat<br><br><br><br><br>model = SVM_classifier(learning_rate = 0.001, no_of_iterations = 1000, lambda_parameter = 0.01)  <br></pre><p>To understand this please understand this mathematics behind it.</p><p>If there’s something wrong, please tell me I’ll be Happy to Learn.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=893af5749620" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Text- Summarization through Python using Transformer Model | Deep Learning | Machine Learning?]]></title>
            <link>https://medium.com/@raftaarrashedin100/text-summarization-through-python-using-transformer-model-deep-learning-machine-learning-d6e7b11f7c97?source=rss-99ce24a11be2------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6e7b11f7c97</guid>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[text-summarization]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[MD RASHEDIN]]></dc:creator>
            <pubDate>Wed, 30 Nov 2022 16:53:32 GMT</pubDate>
            <atom:updated>2022-11-30T16:53:32.020Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*lJNiET0dFnrAUOMrzyc4TQ.jpeg" /><figcaption><a href="https://i.pinimg.com/474x/e1/a0/f9/e1a0f9e2d76b89bc64f8592c15843996--actresses.jpg">source</a></figcaption></figure><p>Here we will talk about Abstractive summarization, This is completely different from extractive text summarization, In extractive we have to pick the important sentence from the whole paragraph and sort it out. In abstractive, it tries to convey the information in abstract way like the how we humans do. So, this is a very useful model if you want to summarize news or any document if you want so.</p><p>So, first we will install some modules.</p><pre>!pip install transformers==2.8.0<br>!pip install torch==1.4</pre><p>then we will import some modules.</p><pre>import torch <br>from transformers import T5Tokenizer, T5ForConditionalGeneration, T5Config</pre><p>Now, we will initialize the models</p><pre># Initialize the pre-trained model <br>model = T5ForConditionalGeneration.from_pretrained(&#39;t5-small&#39;)<br>tokernizer = T5Tokenizer.from_pretrained(&#39;t5-small&#39;)<br>device = torch.device(&#39;cpu&#39;)</pre><p>we will give some input text, it could be anything instead of lorem ipsum.</p><pre>text = &quot;&quot;&quot;<br><br>&quot;&quot;&quot;</pre><p>after that we will pre process the input text</p><pre># pre process the input text<br>preprocessed_text = text.strip().replace(&#39;\n&#39;,&#39;&#39;)<br>t5_input_text = &#39; Summarize : &#39;+ preprocessed_text</pre><p>Now, we will summarize.</p><pre>tokenized_text = tokernizer.encode(t5_input_text, return_tensors = &#39;pt&#39;, max_length=512).to(device)<br>summary_ids = model.generate(tokenized_text, min_length=30,max_length=120)<br>summary = tokernizer.decode(summary_ids[0],skip_special_tokens=True)<br>summary</pre><p>Here, we will see summarization of our text or article.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p>My <a href="http://linkedin.com/in/md-rashedin-2a3768210">LinkedIn</a> don’t hesitate to connect me :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6e7b11f7c97" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>