<?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 Shivam Jha on Medium]]></title>
        <description><![CDATA[Stories by Shivam Jha on Medium]]></description>
        <link>https://medium.com/@dk238347?source=rss-6e2e9273cfb2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*XYzwQMq_vzdEmdNkiMbCXA.jpeg</url>
            <title>Stories by Shivam Jha on Medium</title>
            <link>https://medium.com/@dk238347?source=rss-6e2e9273cfb2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 25 Nov 2026 00:28:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dk238347/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[No need to purchase a high-end GPU machine to run local LLMs with massive context.]]></title>
            <link>https://medium.com/@dk238347/no-need-to-purchase-a-high-end-gpu-machine-to-run-local-llms-with-massive-context-17ddf397467a?source=rss-6e2e9273cfb2------2</link>
            <guid isPermaLink="false">https://medium.com/p/17ddf397467a</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Shivam Jha]]></dc:creator>
            <pubDate>Fri, 03 Apr 2026 17:45:04 GMT</pubDate>
            <atom:updated>2026-04-03T17:49:19.026Z</atom:updated>
            <content:encoded><![CDATA[<p>No need to purchase a high-end GPU machine to run local LLMs with massive context.</p><p>I have implemented a turboquant research paper from scratch in PyTorch—and the results are fascinating to see in action!</p><p>Code:</p><p>https://github.com/kumar045/turboquant_implementation</p><p>Please give it a star.</p><p>When building Agentic AI applications, handling massive context windows means inevitably hitting a wall with KV cache memory constraints. TurboQuant tackles this elegantly with a near-optimal online vector quantization approach, so I decided to build it and see if the math holds up.</p><p>The KV cache is the bottleneck for serving LLMs at scale.</p><p>TurboQuant gives 6x compression with zero quality loss:</p><p>6x more concurrent users per GPU</p><p>direct 6x reduction in cost per query</p><p>6x longer context windows in the same memory budget</p><p>No calibration step — compress on-the-fly as tokens stream in.</p><p>8x speedup on attention at 4-bit on H100 GPUs (less data to load from HBM)</p><p>At H100 prices (~$2-3/hr), serving 6x more users per GPU translates to millions in savings at scale.</p><p>Here is what I built:</p><p>Dynamic Lloyd-Max Quantizer: Solves the continuous k-means problem over a Beta distribution to find the optimal boundaries/centroids for the MSE stage.</p><p>1-bit QJL Residual Sketch:</p><p>Implemented the Quantized Johnson-Lindenstrauss transform to correct the inner-product bias left by MSE quantization—which is absolutely crucial for preserving Attention scores.</p><p>How I Validated the Implementation:</p><p>To prove it works, I hooked the compression directly into Hugging Face’s Llama-2-7b architecture and ran two specific evaluation checks (screenshots attached):</p><p>The Accuracy &amp; Hallucination Check:</p><p>I ran a strict few-shot extraction prompt. The full TurboQuant implementations (both 3-bit and 4-bit) successfully output the exact match (&quot;stack&quot;). However, when I tested a naive MSE-only 4-bit compression (without the QJL correction), it failed and hallucinated (&quot;what&quot;). This perfectly proves the paper&#39;s core thesis: you need that inner-product correction for attention to work!</p><p>The Generative Coherence Check:</p><p>I ran a standard multi-token generation. As you can see in the terminal, the TurboQuant 3-bit cache successfully generated the exact same coherent string as the uncompressed FP16 baseline.</p><p>The Memory Check:</p><p>Tracked the cache size dynamically. Layer 0 dropped from \~1984 KB in FP16 down to \~395 KB in 3-bit—roughly an 80% memory reduction!</p><p>A quick reality check for the performance engineers:</p><p>This script shows memory compression and test accuracy degradation. Because it relies on standard PyTorch bit-packing and unpacking, it doesn&#39;t provide the massive inference speedups reported in the paper. To get those real-world H100 gains, the next step is writing custom Triton or CUDA kernels to execute the math directly on the packed bitstreams in SRAM.</p><p>Still, seeing the memory stats drastically shrink while maintaining exact-match generation accuracy is incredibly satisfying.</p><p>If anyone is interested in the mathematical translation or wants to collaborate on the Triton kernels, let&#39;s collaborate!</p><p>Huge thanks to the researchers at Google for publishing this amazing paper.</p><p>Now no need to purchase high-end GPU machines with massive VRAM just to scale context.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17ddf397467a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s talk about the Saga Pattern — and why it matters more than ever in the age of agentic AI.]]></title>
            <link>https://medium.com/@dk238347/lets-talk-about-the-saga-pattern-and-why-it-matters-more-than-ever-in-the-age-of-agentic-ai-04757123bca0?source=rss-6e2e9273cfb2------2</link>
            <guid isPermaLink="false">https://medium.com/p/04757123bca0</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Shivam Jha]]></dc:creator>
            <pubDate>Wed, 04 Mar 2026 18:40:13 GMT</pubDate>
            <atom:updated>2026-03-04T18:40:13.074Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s talk about the Saga Pattern — and why it matters more than ever in the age of agentic AI.</p><p>Most AI agent systems break the moment real money is involved.</p><p>Especially for a fintech company developing agentic AI</p><p>Not because the model is bad.<br>But because the architecture is wrong.</p><p>The Saga Pattern is the safety net for distributed systems. When one step fails (e.g., a subscription error), you don’t just crash—you execute compensation logic to undo previous steps (e.g., voiding payment).</p><p>In Agentic AI, this is vital. AI is great at reasoning but terrible at deterministic execution. To build production-grade systems, separate them:</p><p>AI Agent: Decides what should happen (Creative Reasoning).</p><p>Workflow Engine (Temporal): Guarantees how it happens (Deterministic Execution).</p><p>The Reasoning Layer (The Creative Agent)<br>The LLM/Agent is non-deterministic by design. It thrives in the &quot;messy&quot; middle:</p><p>Dynamic Planning: Deciding if a user needs a refund, an upgrade, or a support ticket based on sentiment.</p><p>Tool Selection: Picking which API to call based on a natural language request.</p><p>Ambiguity Resolution: Asking clarifying questions when a command is unclear.</p><p>The Risk: You can&#39;t &quot;unit test&quot; an LLM to guarantee it won&#39;t try to call the charge_card tool twice or skip a step.</p><p>The Execution Layer (Temporal)<br>Temporal provides the deterministic rail. It treats the Agent&#39;s decisions as &quot;commands&quot; that must be executed with 100% reliability:</p><p>Durable State: If the server crashes mid-process, Temporal remembers exactly which step the agent was on.</p><p>The Saga Logic: If the Agent decides to &quot;Book a Flight&quot; and the payment succeeds but the seat reservation fails, Temporal guarantees the &quot;Refund&quot; compensation runs.</p><p>Timeout Management: If an AI tool call hangs, Temporal manages the retry policy so you don&#39;t leave the system in an inconsistent state</p><p>By combining Saga for consistency and Idempotency Keys for safety, you ensure AI proposes while the workflow enforces.</p><p>Idempotency Keys Matter Too</p><p>Workflow engines are not enough.</p><p>Every external side-effect (like Stripe calls) must use idempotency keys:</p><p>order_123_auth_v1</p><p>order_123_refund_v1</p><p>If the request is retried, the payment provider returns the same result instead of performing the action twice.</p><p>Idempotency prevents duplicate side effects.<br>Saga ensures consistency across steps.<br>Temporal ensures durable execution.</p><p>Temporal is open-source</p><p>The Temporal Web UI can help you to quickly isolate, debug, and resolve production problems.</p><p>Learn about Temporal <br>dev.to/akki907/tempor…</p><p>Leading AI agent platforms like Codex and Lovable rely on it for durable execution.</p><p>If you&#39;re building agentic systems that touch payments, ledgers, or real-world states, I&#39;d love to connect and exchange ideas.</p><p>#AgenticAI #DistributedSystems #SoftwareArchitecture #Temporal #SagaPattern #SystemDesign #BackendEngineering #AI #Fintech</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=04757123bca0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Trustworthy AI: The Four Pillars of AI Governance
As AI systems and agentic apps move to…]]></title>
            <link>https://medium.com/@dk238347/building-trustworthy-ai-the-four-pillars-of-ai-governance-as-ai-systems-and-agentic-apps-move-to-e885b1c58846?source=rss-6e2e9273cfb2------2</link>
            <guid isPermaLink="false">https://medium.com/p/e885b1c58846</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Shivam Jha]]></dc:creator>
            <pubDate>Wed, 04 Mar 2026 12:47:14 GMT</pubDate>
            <atom:updated>2026-03-04T12:47:14.945Z</atom:updated>
            <content:encoded><![CDATA[<p>Building Trustworthy AI: The Four Pillars of AI Governance<br>As AI systems and agentic apps move to production, one question is critical: How do we ensure AI remains safe, reliable, and trustworthy?</p><p>These four pillars create a practical safety net:</p><p>1. Drift Analysis<br>Is the AI still working correctly today?<br>AI models drift as real-world data changes. Monitoring detects:</p><p>Data distribution changes</p><p>Concept drift</p><p>Performance degradation<br>Frameworks track inputs/outputs to catch anomalies early.</p><p>2. Evidence (Explainability &amp; Traceability)<br>Can we prove why the AI made that decision?<br>Systems must be auditable. Tools like Arize Phoenix allow teams to trace:</p><p>Prompts &amp; inputs</p><p>Retrieval results &amp; tool usage</p><p>Model outputs<br>This is critical for compliance, debugging, and continuous improvement.</p><p>3. Fairness<br>Is the system biased or discriminatory?<br>AI can unintentionally reinforce bias. Monitoring evaluates:</p><p>Approval rates across demographics</p><p>False positive/negative disparities<br>Libraries like Fairlearn measure bias across sensitive attributes so disparities are detected before they scale.</p><p>4. Security<br>Is the AI safe from malicious attacks?<br>Modern risks include prompt injection, jailbreaking, and data leakage. Frameworks like Guardrails AI provide programmable validators to enforce safety rules and structured outputs.</p><p>Open-Source Stack for the Four Pillars<br>Arize Phoenix → Tracing &amp; evidencing</p><p>Evidently AI → Drift detection</p><p>Fairlearn → Bias metrics</p><p>Guardrails AI → Security &amp; validation</p><p>Code:<br>github.com/kumar045/Mediu…</p><p>You can enhance it according to your needs.</p><p>Taking It Toward Production<br>To reach production-readiness, You can add:</p><p>Concept Drift Monitoring: Detecting shifting input-outcome relationships.</p><p>Data Quality Checks: Validating for anomalies or schema changes.</p><p>Alerting Systems: Triggering alerts when thresholds are crossed.</p><p>Larger Sample Monitoring: Evaluating batches for statistical reliability.</p><p>I am developing a production-grade application template integrating these tools with a robust observability stack. The architecture leverages Langraph for AI Agents, Prometheus and Grafana for monitoring, and Structured Logging and Langfuse for traceability. To ensure compliance, I’m utilizing Temporal for durability, AI Governance frameworks, MCP (Model Context Protocol), and an A2A/ADK-based skills architecture.</p><p>I will share the repo link very soon.</p><p>#AI #AIEngineering #AIAgents #ResponsibleAI #LLMOps #AIGovernance #MachineLearning #LangGraph</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e885b1c58846" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced Customization in Hugging Face Transformers: For the Adventurous Researchers]]></title>
            <link>https://medium.com/@dk238347/advanced-customization-in-hugging-face-transformers-for-the-adventurous-researchers-39308d49fb9b?source=rss-6e2e9273cfb2------2</link>
            <guid isPermaLink="false">https://medium.com/p/39308d49fb9b</guid>
            <category><![CDATA[hugging-face]]></category>
            <category><![CDATA[multimodal]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[research-and-development]]></category>
            <dc:creator><![CDATA[Shivam Jha]]></dc:creator>
            <pubDate>Wed, 13 Sep 2023 10:21:39 GMT</pubDate>
            <atom:updated>2023-09-13T11:12:32.979Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. Introduction</h3><p>Attention researchers and AI enthusiasts! If you’re tired of the usual, one-size-fits-all pretrained models and are looking for ways to tweak them to your liking, then you’ve landed in the right place. Today, we’re diving deep into the advanced customization techniques you can employ with Hugging Face’s Transformers library. Buckle up!</p><h3>Table of Contents</h3><ol><li>Introduction</li><li>Dynamic Configuration During Inference</li><li>Layer-Wise Customization</li><li>Configuration Parameters</li><li>Swapping Encoder and Decoder Modules</li><li>Multi-Modal Models: Combining Encoders</li><li>Conclusion</li></ol><h3>2. Dynamic Configuration During Inference</h3><p>Wondering if you can change the model configuration during inference? The answer is a resounding yes!</p><pre>from transformers import BertConfig, BertModel<br><br>config = BertConfig()<br>config.output_hidden_states = True<br>model = BertModel(config)</pre><h3>3. Layer-Wise Customization</h3><h3>3.1 Replacing Layers</h3><p>You can easily replace the attention mechanism, or any other layer, with your own implementation. Here’s a quick example:</p><p>If you want to use a different attention mechanism:</p><pre>from transformers import BertConfig<br>from transformers.models.bert.modeling_bert import BertSelfAttention<br># Initialize the config specific to BERT<br>config = BertConfig(<br>    hidden_size=768,<br>    num_attention_heads=12,<br>    num_hidden_layers=12,<br>)<br><br># Create a new BertSelfAttention layer using the config<br>new_attention = BertSelfAttention(config)<br><br># Replace the self-attention layer of the first encoder layer<br>model.encoder.layer[0].attention.self = new_attention</pre><p>Here, config is an instance of BertConfig, which holds configuration parameters for the BERT model. These parameters include the hidden layer size, the number of attention heads, and the number of hidden layers. By creating a new BertSelfAttention object with this config, we ensure that it&#39;s compatible with BERT&#39;s architecture. We then replace the existing self-attention mechanism in the first encoder layer with this new one.</p><h3>4. Configuration Parameters</h3><h4>Configuration Parameters</h4><ul><li>output_hidden_states: Whether to return all hidden-states.</li><li>output_attentions: Whether to returns all attentions.</li><li>is_encoder_decoder: Whether the model is used as an encoder/decoder or not.</li><li>max_length: Maximum length used in the generate method.</li></ul><p>To change a configuration:</p><pre>from transformers import BertConfig<br><br>config = BertConfig.from_pretrained(&quot;bert-base-uncased&quot;)<br>config.output_hidden_states = True</pre><h3>4.1 Saving and Loading Configurations</h3><p>The configuration can be saved using save_pretrained() and loaded with from_pretrained():</p><pre>config.save_pretrained(&quot;./my_model_directory/&quot;)<br>loaded_config = BertConfig.from_pretrained(&quot;./my_model_directory/&quot;)</pre><p>Creating Configurations from Dictionary:</p><pre>config_dict = {&#39;hidden_size&#39;: 768, &#39;num_attention_heads&#39;: 12}<br>config = BertConfig.from_dict(config_dict)</pre><p>Here’s a Python snippet that would change the dropout rate dynamically during training in PyTorch:</p><pre>for epoch in range(epochs):<br>    if epoch &gt; 5:<br>        model.dropout.p = 0.5  # Changing dropout probability to 0.5 after 5 epochs</pre><p>Adjusting the dropout rate depending on the training epoch can be beneficial.</p><pre># Changing attributes dynamically during training<br>if epoch &gt; 10:<br>    model.encoder.layer[0].attention.self.dropout.p = 0.3</pre><h3>During Inference:</h3><ol><li>Batch Size: You can switch to a smaller or larger batch size for evaluation, independent of what was used during training.</li><li>Sequence Length: Some models allow you to change the sequence length dynamically.</li><li>Output Types: With the BertConfig class, you can specify whether to output attention weights or hidden states.</li><li>Token Type: For models that can generate text, you can often change settings like temperature, top-k, and top-p for sampling strategies.</li></ol><pre>from transformers import BertModel, BertConfig<br><br># Load the pre-trained model&#39;s configuration<br>config = BertConfig.from_pretrained(&quot;bert-base-uncased&quot;)<br><br># Change some attributes<br>config.output_hidden_states = True<br>config.output_attentions = True<br><br># Now instantiate the model with the changed configuration<br>model = BertModel.from_pretrained(&quot;bert-base-uncased&quot;, config=config)</pre><p>Remember, changing settings in the middle of a procedure is often more complicated than setting them beforehand and may require extra caution to ensure that the changes are actually applied and that they don’t introduce issues.</p><p>Here’s how you could change settings for a BERT model’s configuration before loading it for inference:</p><p>Hugging Face provides a BertConfig class that enables you to control every aspect of your model. You can even alter settings during fine-tuning.</p><pre># Importing necessary modules<br>from transformers import BertConfig<br>from transformers.models.bert.modeling_bert import BertSelfAttention<br><br># Initialize BertConfig to control various aspects of the BERT model<br># num_attention_heads: Number of attention heads in the model<br># num_hidden_layers: Number of hidden layers in the model<br># output_attentions: Whether or not to output attention weights<br>config = BertConfig(<br>    num_attention_heads=12,<br>    num_hidden_layers=2,<br>    output_attentions=True<br>)<br><br># Create a new BertSelfAttention layer using the above config<br>new_attention = BertSelfAttention(config)<br><br># Replace the self-attention layer of the first encoder layer in the model<br># Note: Ensure the &#39;model&#39; is defined and compatible before this step<br>model.encoder.layer[0].attention.self = new_attention</pre><h3>5. Swapping Encoder and Decoder Modules</h3><h3>5.1 Prebuilt Encoder-Decoder Models</h3><p>Mix and match encoders and decoders from different architectures using the EncoderDecoderModel class.</p><pre>from transformers import EncoderDecoderModel, BertModel, GPT2LMHeadModel<br><br>encoder = BertModel.from_pretrained(&quot;bert-base-uncased&quot;)<br>decoder = GPT2LMHeadModel.from_pretrained(&quot;gpt2&quot;)<br>model = EncoderDecoderModel(encoder=encoder, decoder=decoder)</pre><h3>5.2 Custom Encoders and Decoders</h3><p>Plug in your custom-built modules seamlessly.</p><pre>model = EncoderDecoderModel(encoder=custom_encoder, decoder=custom_decoder)</pre><h3>Caveats</h3><ol><li>Compatibility: When replacing parts like the encoder or decoder, make sure the new parts are compatible with the existing ones, especially in terms of input and output dimensions.</li><li>Pre-trained Weights: If you’re using pre-trained models, be cautious when replacing parts of the model, as you may lose the pre-trained weights for those parts.</li><li>Training: If you change parts of the model, you’ll likely need to retrain it, unless you’re making changes that don’t affect the learned parameters (like changing a dropout rate before inference).</li><li>Parameter Count: Changing the size of layers or replacing components will also change the number of parameters, affecting both memory usage and computation time.</li></ol><p>By understanding the architecture and the specific requirements of your task, you can get quite flexible with how you modify existing models. However, it’s crucial to understand the implications of the changes you’re making.</p><h3>6. Multi-Modal Models: Combining Encoders</h3><p>In the realm of machine learning, multi-modal models are gaining traction for their ability to process and learn from multiple types of data simultaneously. For instance, Vision-Text Dual Encoder models can process both text and image data, offering exciting possibilities for applications like image captioning, visual search, and more.</p><p>Hugging Face provides an easy way to create such multi-modal models using its Transformers library. Here’s a quick example using TensorFlow that combines a text encoder (BERT) and a vision encoder (ViT):</p><pre>from transformers import (<br>    TFVisionTextDualEncoderModel,<br>    VisionTextDualEncoderProcessor,<br>    AutoImageProcessor,<br>    AutoTokenizer,<br>)<br><br>tokenizer = AutoTokenizer.from_pretrained(&quot;bert-base-uncased&quot;)<br>image_processor = AutoImageProcessor.from_pretrained(&quot;google/vit-base-patch16-224&quot;)<br>processor = VisionTextDualEncoderProcessor(image_processor, tokenizer)<br>model = TFVisionTextDualEncoderModel.from_vision_text_pretrained(<br>    &quot;google/vit-base-patch16-224&quot;, &quot;bert-base-uncased&quot;<br>)</pre><h3>7. Conclusion</h3><p>Phew! We’ve covered a lot, haven’t we? From dynamic configurations to layer-specific customization and beyond, the Hugging Face Transformers library offers a smorgasbord of options for those willing to experiment. So go ahead, dive in and make these models your own!</p><p>If you found this guide helpful, consider sharing it with your network. Happy customizing!</p><p>And there you have it — a comprehensive guide to advanced customization techniques using Hugging Face Transformers. Feel free to use this blog as a starting point in your journey of pushing the boundaries of what’s possible with Transformers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39308d49fb9b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying PySpark: Concepts and Code Explained]]></title>
            <link>https://medium.com/@dk238347/demystifying-pyspark-concepts-and-code-explained-6841be3f87ab?source=rss-6e2e9273cfb2------2</link>
            <guid isPermaLink="false">https://medium.com/p/6841be3f87ab</guid>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[big-data-analytics]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Shivam Jha]]></dc:creator>
            <pubDate>Fri, 08 Sep 2023 10:13:30 GMT</pubDate>
            <atom:updated>2023-09-08T10:13:30.169Z</atom:updated>
            <content:encoded><![CDATA[<p>Are you ready to embark on a journey into the world of PySpark? In this blog, we’ll unravel the mysteries behind PySpark concepts and provide you with code samples enriched with detailed comments. Whether you’re a data enthusiast or a seasoned data scientist, this guide will demystify PySpark and empower you with the knowledge you need.</p><p>You can take overview of all the concepts of PySpark in a quick time.</p><h4>Let’s Start:</h4><p>The amount of data being generated exploded exponentially with the use of the internet, social media, and various digital technologies.</p><p>Organizations found themselves facing a massive volume of data that was very hard to process. To address this challenge, the concept of Big Data emerged.</p><p>Big Data refers to extremely large and complex data sets that are difficult to process using traditional methods. Organizations across the world wanted to process this massive volume of data and derive useful insights from it.</p><p>Here’s where Hadoop comes into the picture. In 2006, a group of engineers at Yahoo developed a special software framework called Hadoop. They were inspired by Google’s MapReduce. Hadoop introduced a new way of data processing called distributed processing. Instead of relying on a single machine, we can use multiple computers to get the final result. Think of it like teamwork: each machine in a cluster will get some part of the data to process. They will work simultaneously on all of this data, and in the end, we will combine the output to get the final result. There are two main key components of Hadoop.</p><p>One is the Hadoop Distributed File System (HDFS), which is like the giant storage system for keeping our dataset. It divides our data into multiple chunks and stores all of this data across different computers. The second part of Hadoop is called MapReduce, which is a super smart way of processing all of this data together. MapReduce helps in processing all of this data in parallel. So, you can divide your data into multiple chunks and process them together, similar to a team of friends working to solve a very large puzzle. Each person in the team gets a part of the puzzle to solve, and in the end, we put everything together to get the final result. So, with Hadoop, we have two things: HDFS (Hadoop Distributed File System), which is used for storing our data across multiple computers, and MapReduce, which is used to process all of this data in parallel. It allowed organizations to store and process very large volumes of data.</p><p>There were a few limitations. One of the biggest problems behind Hadoop was that it relied on storing data on disk, which made things much slower. Every time we run a job, it would store the data onto the disk, read the data, process it, and then store that data again through a disk.This made the data processing a lot slower. Another issue with Hadoop was that it processed data only in batches. This means we had to wait for one process to complete before submitting any other job. It was like waiting for the whole group of friends to complete their puzzles individually and then putting them together. So, there was a need to process all of this data faster and in real-time. Here’s where Apache Spark comes into the picture</p><p>Where they introduced the powerful concept called RDD (Resilient Distributed Dataset). RDD is the backbone of Apache Spark. It allows data to be stored in memory and enables faster data access and processing. Instead of reading and writing the data repeatedly from the disk.</p><p>Spark is 100 times faster than Hadoop. Yes, you heard it right,100 times faster than Hadoop. Additionally, Spark also gave the ability to write code in various programming languages such as Python, Java, and Scala. So, you can easily start writing Spark applications in your preferred language and process your data on a large scale.</p><p>Here are the different components attached to Apache Spark. One of the most important components of the Spark ecosystem is called Spark Core. It helps with processing data across multiple computers and ensures everything works efficiently and smoothly</p><p>Another component is Spark SQL. So, if you want to write SQL queries directly on your dataset, you can easily do that using Spark.</p><p>Then there is the Spark Streaming component. If you want to process real-time data that you see in Google Maps or Uber, you can easily do that using Apache Spark Streaming.</p><p>And at the end, we have an MLlib component. MLlib is used for training large-scale machine learning models on Big Data using Spark.</p><p>Now, let’s understand the basic architecture behind Apache Spark. When you think of a computer, a standalone computer is generally used to watch movies, play games, or anything else. But when you want to process large Big Data, you can’t do that on a single computer. You need multiple computers working together on individual tasks so that you can combine the output at the end and get the desired result. You can’t just take ten computers and start processing your Big Data. You need a proper framework to coordinate work across all of these different machines, and Apache Spark does exactly that. Apache Spark manages and coordinates the execution of tasks on data across a cluster of computers.</p><p>It has something called a cluster manager. When we write any job in Spark, it is called a Spark application. Whenever we run anything, it goes to the cluster manager, which grants resources to all applications so that we can complete our work.</p><p>In a Spark application, we have two important components: the driver processes and the executor processes. The driver processes are like a boss, and the executor processes are like workers.</p><p>The main job of the driver processes is to keep track of all the information about the Apache Spark application. It will respond to the command and input from the user. So, whenever we submit anything, the driver process will make sure it goes through the Apache Spark application properly. It analyzes the work that needs to be done, divides our work into smaller tasks, and assigns these tasks to executor processes. So, it is basically the boss or a manager who is trying to make sure everything works properly. The driver process is the heart of the Apache Spark application because it makes sure everything runs smoothly and allocates the right resources based on the input that we provide.</p><p>Executor processes are the ones that actually do the work. They execute the code assigned by the driver process and report back the progress and result of the computation.</p><p>We have the data frame concept available in Python and R. In Python, the data frame is stored on a single computer, whereas in Spark, the data frame is distributed across multiple computers. To ensure that all of this data is executed in parallel, you need to divide your data into multiple chunks. This is called partitioning. You can have a single partition or multiple partitions, which you can specify while writing the code.</p><p>All of these things are done using transformations. Transformations are basically the instructions that tell Apache Spark how to modify the data and get the desired result. For example, let’s say you want to find all the even numbers in a data frame. You can use the filter transformation function to specify this condition. But here’s the thing, if we run this code, we will not get the desired output. In most programming languages, once you run the code, you get the output immediately. But Spark doesn’t work like that.</p><p>Spark uses lazy evaluation. It waits until you complete writing your entire code, and then it generates the proper plan based on the code you have written. This allows Spark to calculate your entire data flow and execute it efficiently. To actually execute the transformation block, we have something called actions.</p><p>There are multiple actions available in Apache Spark. One of the actions is the count action, which gives us the total number of records in a data frame. We can run an action, and Spark will run the entire transformation block and give us the final output.</p><p>The link of the complete code is <a href="https://github.com/kumar045/Medium/blob/main/PySpark_Concepts_Overview.ipynb">https://github.com/kumar045/Medium/blob/main/PySpark_Concepts_Overview.ipynb</a></p><p>As we conclude our exploration of PySpark concepts and code explanations, you now possess the essential tools to navigate the world of distributed data processing with confidence. With the power of PySpark at your fingertips, complex data analysis and manipulation become accessible. Keep experimenting, building, and discovering the endless possibilities that PySpark offers in your data-driven journey.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6841be3f87ab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Techniques For Training The Large Language Model]]></title>
            <link>https://medium.com/@dk238347/transformer-concepts-25a078cef73a?source=rss-6e2e9273cfb2------2</link>
            <guid isPermaLink="false">https://medium.com/p/25a078cef73a</guid>
            <category><![CDATA[peft]]></category>
            <category><![CDATA[rlhf]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[qlora]]></category>
            <category><![CDATA[quantization]]></category>
            <dc:creator><![CDATA[Shivam Jha]]></dc:creator>
            <pubDate>Mon, 28 Aug 2023 07:24:29 GMT</pubDate>
            <atom:updated>2023-08-29T04:35:29.910Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s learn about the various techniques used to train the Large Language Model.</p><h3><strong>Reinforcement Learning from Human Feedback</strong></h3><p><strong>The Challenge</strong>: Imagine you have a computer program that writes stories or answers questions. How do you make sure it writes good, meaningful, and helpful text? What exactly is “good” can be hard to define.</p><p><strong>What Humans Prefer</strong>: After that basic training, you want the computer to write in a way that people like. This is where human feedback comes in. People read what the computer writes and rank it. The computer learns from this ranking to write better text.</p><p><strong>Fine-Tuning with Rewards</strong>: Now, the computer has a basic understanding of what people like, but you want to make it even better. You use a technique called Reinforcement Learning, where you reward the computer for good writing and penalize it for bad writing. It’s like giving a treat to a dog when it does a trick correctly.</p><h3>KL Divergence</h3><p><strong>What It Is</strong>: KL Divergence is a mathematical way to measure how two probability distributions differ from each other. Think of it like comparing two different pies to see how much the slices differ in size.</p><h3>Proximal Policy Optimization (P P O)</h3><p><strong>What It Is</strong>: It is a reinforcement learning method that helps a model learn from trial and error without making big mistakes.</p><p><strong>Trial and error: </strong>It<strong> </strong>is a method of problem-solving where you try different solutions until you find one that works.</p><p>Imagine you’re trying to fit a key into a lock, but you don’t know which key on your key chain is the right one. You would try one key, see if it fits, and if not, you would try the next key. You continue this process, learning from the “errors” or wrong keys, until you find the correct one that fits the lock.</p><p>In a way, you’re experimenting with different options, learning from the mistakes, and finally arriving at the right solution.</p><h3>Steps:</h3><p><strong>Generation of Responses:</strong></p><p>The Large Language Model generates responses to prompts. In the context of question-answering, these responses can be potential answers to questions.</p><p><strong>Reward Model Training:</strong></p><p>A reward model is trained to predict human preferences between pairs of responses.</p><h3>Example:</h3><p><strong>Prompt:</strong> “What’s the best way to cook an egg?”</p><p><strong>Large Language Model Responses:</strong></p><p>Response A: “Fry it in a pan with some butter.”</p><p>Response B: “Boil it in water for 10 minutes.”</p><ul><li>This training requires human-labeled data where humans rank different responses to the same prompt.</li><li>The training of the reward model involves using a loss function that encourages the model to predict the correct ranking between pairs of responses.</li></ul><p><strong>Rating Samples with the Reward Model:</strong></p><ul><li>Once trained, the reward model is used to rate the responses generated by the Large Language Model.</li><li>For each prompt and corresponding responses, the reward model assigns a score to each response, indicating how well it aligns with human preferences.</li></ul><h3>Example:</h3><p><strong>Human annotators rank these responses:</strong></p><p>Response A: Rank 2 (preferred)<br>Response B: Rank 1</p><p><strong>The reward model is trained to predict these rankings. For instance:</strong></p><p>Reward for A: 0.7 (higher score, preferred)<br>Reward for B: 0.3</p><p><strong>Reinforcement Learning:</strong></p><ul><li>The ratings from the reward model are used as rewards in the reinforcement learning process.</li><li>Algorithms like Proximal Policy Optimization use these rewards to fine-tune the Large Language Model, encouraging it to generate responses that align better with human preferences.</li><li>The Reinforcement Learning process iteratively generates responses, rates them with the reward model, and updates the Large Language Models parameters to maximize the expected reward.</li></ul><p><strong>How it works:</strong></p><ol><li><strong>Active Model</strong>: This is the model that is currently being trained. It is updated during the training process, and its parameters change as it learns from the training data and rewards. The active model is responsible for generating responses or taking actions during the training process, and its behavior evolves as it learns.</li><li><strong>Reference Model</strong>: The reference model is a snapshot of the active model taken at the beginning of training. It remains fixed during the training process and is used as a baseline to compare against the active model. By comparing the active model with the reference model, you can measure how much the active model has deviated from its original behavior. This comparison is often done using KL-divergence.</li></ol><ul><li><strong>Rollout Phase</strong>: During the rollout phase, the active model generates responses for the prompt. These responses are then evaluated to compute rewards.</li><li><strong>Optimization Phase</strong>: During the optimization phase, Proximal Policy Optimization updates the active model’s parameters to maximize the expected rewards. The objective function in it also includes a term that penalizes large deviations from the reference model (using KL-divergence). This helps to keep the updates stable and avoids overly aggressive changes that might lead to poor generalization.</li><li><strong>Regularization with KL-Divergence</strong>: By including the KL-divergence between the active model and the reference model, Proximal Policy Optimization ensures that the fine-tuned model does not deviate too far from the original pretrained behavior. This acts as a form of regularization, helping to prevent over fitting to the specific training data and maintaining some of the general knowledge captured by the pretrained model.</li><li><strong>Trust Region</strong>: The KL-divergence constraint defines a “trust region” within which the active model’s parameters are allowed to change. This ensures that updates are made in a controlled manner, preserving some of the desirable properties of the original, reference model.</li></ul><h3>Efficient Fine Tuning</h3><p><strong>Parameters:</strong> Parameters are the values/variables that a model learns during training to make predictions. Parameters are usually represented as weights and biases in neural network.</p><h3>Parameter-Efficient Fine-Tuning (P E F T)</h3><h3>What is the difference between fine-tuning and parameter-efficient fine-tuning :</h3><p>Fine-tuning and parameter-efficient fine-tuning are two approaches used in machine learning to improve the performance of pre-trained models on a specific task.</p><p>Fine-tuning is taking a pre-trained model and training it further on a new task with new data. The entire pre-trained model is usually trained in fine-tuning, including all its layers and parameters. This process can be computationally expensive and time-consuming, especially for large models.</p><p>On the other hand, parameter-efficient fine-tuning is a method of fine-tuning that focuses on training only a subset of the pre-trained model’s parameters. This approach involves identifying the most important parameters for the new task and only updating those parameters during training. Doing so, we can significantly reduce the computation required for fine-tuning.</p><p>By inserting adapters after the multi-head attention and feed-forward layers in the transformer architecture, we can update only the parameters in the adapters during fine-tuning while keeping the rest of the model parameters frozen.</p><pre># Pseudocode of a typical encoder layer with adapter<br>class EncoderWithAdapter:<br>    def __call__(self, x: Tensor) -&gt; Tensor:<br>        residual = x<br>        x = MultiHeadAttention(x)<br>        x = AdapterNetwork(x)  # Usually another feedforward layer<br>        x = LayerNorm(x + residual)<br>        residual = x<br>        x = FeedForwardLayers(x)<br>        x = AdapterNetwork(x)  # Usually another feedforward layer<br>        x = LayerNorm(x + residual)<br>        return x</pre><h3>Techniques Used In The PEFT:</h3><h4><strong>LORA:</strong></h4><p>It is low rank adaption algorithm.<br>To make fine-tuning more efficient, LoRA’s approach is to represent the weight updates with two smaller matrices (called update matrices) through low-rank decomposition. These new matrices can be trained to adapt to the<br>new data while keeping the overall number of changes low. The original weight matrix remains frozen and doesn’t receive any further adjustments. To produce the final results, both the original and the adapted weights are combined.</p><h3>Rank Decomposition</h3><p>Rank decomposition involves representing a given matrix M as the product of two matrices A and B, where the rank of the decomposition is controlled by the dimensions of these matrices.</p><p>For example, if M is an m×n matrix, and you want to represent it using a rank r decomposition, you would find matrices A and B such that A is m×r and B is r×n. The product A×B would then approximate M, and the rank of the product would be at most r</p><h3>Mathematical Example</h3><p>If a weight matrix W in a Transformer layer is of size 1000×1000, and you choose a rank r=10 decomposition, you would represent W as the product of a 1000×10 matrix and a 10×1000 matrix. The number of parameters is reduced from 1000×1000=1,000,000 to 1000×10+10×1000=20,000, a significant reduction.</p><p>Think of the original matrix as a high-resolution image with lots of pixels (details). The low-rank decomposition is like creating a lower-resolution version of the image that still looks similar to the original but uses far fewer pixels. The rank r=10 is like choosing the level of detail you want to keep in this lower-resolution image.</p><p><strong>How it works during training:</strong></p><ul><li>The weights of the original network and the low-rank network are computed with a dot product are combined which results in a weight matrix of n dimension, which is used to generate the output.</li></ul><p><strong>Example:</strong></p><p><strong>Wnew=W+(WA⋅WB)</strong></p><ul><li>This output is then compared with the expected output (during training) to calculate the loss function and WA and WB weights are adjusted based on the loss function as part of back propagation like standard neural networks.</li></ul><h3>STEPS:</h3><h4>1. Starting with a Pre-trained Model</h4><p>You often begin with a pre-trained model with weight matrices of full rank. These weights have been trained on a large dataset and capture general knowledge relevant to the task.</p><h4>2. Low-Rank Decomposition</h4><p>Next, you introduce low-rank matrices (usually denoted as A and B) to approximate the original weight matrices. You might initialize these low-rank matrices in specific ways to represent the original weights.</p><h4>3. Training with Low-Rank Matrices</h4><p>Then, you perform training (or fine-tuning) using the low-rank matrices. During this phase, only the low-rank matrices are updated, while the original weights of the pre-trained model remain fixed. The training focuses on the task-specific data, allowing the low-rank matrices to capture the nuances of the particular task.</p><h4>4. Combining with Original Weights</h4><p>Once the training with low-rank matrices is complete, you combine them with the original model’s weights. The resulting model integrates the general knowledge from the original weights and the task-specific adaptations from the low-rank matrices.</p><h4>5. Advantages of This Approach</h4><ul><li><strong>Efficiency</strong>: Training with low-rank matrices reduces computational complexity, making the process faster and more memory-efficient.</li><li><strong>Flexibility</strong>: It allows for targeted adaptation of a pre-trained model to specific tasks without the need to retrain the entire model.</li><li><strong>Preservation</strong>: Combining the original weights with the low-rank adaptations ensures that the general knowledge captured during pre-training is preserved while adding task-specific insights.</li></ul><h3>Quantization:</h3><p>Quantization refers to the process of constraining an input from a large set of values (such as floating-point numbers) to output in a smaller set (such as integers). In the context of neural networks, it’s often applied to the weights and activation of a model.</p><h3>float32 (32-bit Floating-Point)</h3><ul><li><strong>Bits</strong>: Uses 32 bits to represent a number.</li><li><strong>Structure</strong>: Comprises a sign bit, 8 bits for the exponent, and 23 bits for the fractional part (mantissa).</li></ul><h3>float16 (16-bit Floating-Point or Half Precision)</h3><ul><li><strong>Bits</strong>: Uses 16 bits to represent a number.</li><li><strong>Structure</strong>: Comprises a sign bit, 5 bits for the exponent, and 10 bits for the fractional part (mantissa).</li><li><strong>Range</strong>: Smaller than float32, but still capable of representing real numbers with decimal points.</li></ul><h3>int8 (8-bit Integer)</h3><ul><li><strong>Bits</strong>: Uses 8 bits to represent a number.</li><li><strong>Structure</strong>: Can represent 256 different integer values, typically ranging from -128 to 127 or 0 to 255, depending on whether it’s signed or unsigned.</li><li><strong>Range</strong>: Limited to small integers without decimal points.</li></ul><h4><strong>Benefits:</strong></h4><p>If you compare float32 to float16</p><ul><li><strong>Memory Efficiency</strong>: Uses half the memory of float32, allowing for more data to fit into the same space.</li><li><strong>Speed</strong>: Can lead to faster computations on hardware optimized for float16 arithmetic, such as certain GPUs.</li></ul><h4>QLORA:</h4><p>QLoRA extends LoRA to enhance efficiency by quantizing weight values of the original network or model, from high-resolution data types, such as Float32, to lower-resolution data types like int4.</p><p>The 4-bit NormalFloat quantization is applied to the weights of the original model and the LoRA adapter weights will be FP32, as all of the training will happen on these weights. Once all the training is done, the weights of the original model will be de-quantized.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25a078cef73a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>