<?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 TensorFlow User Group Islamabad on Medium]]></title>
        <description><![CDATA[Stories by TensorFlow User Group Islamabad on Medium]]></description>
        <link>https://medium.com/@tfugislamabad?source=rss-3ca8323a41d6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*OBJ42YEFSeV5nvecB8x4_A.png</url>
            <title>Stories by TensorFlow User Group Islamabad on Medium</title>
            <link>https://medium.com/@tfugislamabad?source=rss-3ca8323a41d6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 04:54:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tfugislamabad/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[Insights from “Attention is All you Need” | ML Paper Reading Clubs Day 2]]></title>
            <link>https://medium.com/@tfugislamabad/insights-from-attention-is-all-you-need-ml-paper-reading-clubs-day-2-17a3c521ebe4?source=rss-3ca8323a41d6------2</link>
            <guid isPermaLink="false">https://medium.com/p/17a3c521ebe4</guid>
            <category><![CDATA[attention-model]]></category>
            <category><![CDATA[ai-tutorial]]></category>
            <category><![CDATA[transformer-architecture]]></category>
            <category><![CDATA[transformer-model]]></category>
            <dc:creator><![CDATA[TensorFlow User Group Islamabad]]></dc:creator>
            <pubDate>Sat, 15 Feb 2025 13:55:33 GMT</pubDate>
            <atom:updated>2025-02-15T13:55:33.174Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UA2YhrnKBF87i0ZdaWp6yw.png" /></figure><h4>Sequential Data</h4><p>Data arranged in sequence where order matters. Data points are dependent upon each other data points in this sequence.</p><p><strong>Example:</strong> <em>Data used in Speech Recognition, Music Generation or Sentiment Classification etc.</em></p><h3><strong>Whats Wrong With RNNs?</strong></h3><h4><strong>Sequential Processing</strong>:</h4><p><strong>RNNs</strong>: Process data sequentially, which makes parallelization difficult and training slow, especially for long sequences.</p><p><strong>Transformers</strong>: Allow for parallel processing of data, significantly speeding up training times.</p><h4><strong>Long-Range Dependencies</strong>:</h4><p><strong>RNNs</strong>: Struggle with capturing long-range dependencies due to the vanishing gradient problem, even with advanced variants like LSTMs and GRUs.</p><p><strong>Transformers</strong>: Use self-attention mechanisms that can capture long-range dependencies more effectively by directly attending to all positions in the sequence.</p><h4>What is Vanishing Gradient Problem?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ijAOk6gYnP--pLrgt0wt7g.png" /></figure><p>The vanishing gradient problem occurs when gradients <em>(or simply derivatives)</em> used to update a deep neural network’s weights become exceedingly small as they are propagated backward through the network during training. This happens due to the repeated multiplication of small derivatives, especially in networks with many layers or long sequences, leading to exponentially smaller gradients. As a result, the weights in earlier layers receive negligible updates, hindering the network’s ability to learn long-range dependencies or deep features effectively.</p><blockquote>For Detailed Explanation: <a href="https://medium.com/@amanatulla1606/vanishing-gradient-problem-in-deep-learning-understanding-intuition-and-solutions-da90ef4ecb54">Medium</a></blockquote><h3>A Solution</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TtGEJOQaEzDsZsBLwasqNw.png" /></figure><p><strong>Input Embeddings</strong>: Converts words into dense vectors.</p><p><strong>Positional Encodings</strong>: Adds information about the order of words to the embeddings.</p><p><strong>Multi-Head Self-Attention</strong>: Allows the model to focus on different parts of the input sequence simultaneously.</p><p><strong>Feed-Forward Networks</strong>: Applies a series of transformations to each position independently.</p><p><strong>Encoder</strong>: Consists of multiple layers of self-attention and feed-forward networks, processing the input sequence.</p><p><strong>Decoder</strong>: Similar to the encoder but includes additional layers for attending to the encoder’s output, generating the target sequence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qrCCXtVJhD8g_pHxNk5ugQ.png" /></figure><p><strong>Original Sentence (tokens)</strong>: The input sentence “YOUR CAT IS A LOVELY CAT” is tokenized into individual words.</p><p><strong>Input IDs</strong>: Each word is converted into its corresponding token ID based on the vocabulary. For example, “YOUR” is token ID 105, “CAT” is 6587, etc.</p><p><strong>Embedding</strong>: Each token ID is mapped to an embedding vector of size 512. These embeddings capture the semantic information of the words.</p><p><strong>Positional Encoding</strong>: Since Transformers do not have an inherent sense of order, positional encodings are added to the embeddings to incorporate the position information of words in the sequence.</p><p><strong>Layer Processing</strong>: The embedding vectors, now with added positional encodings, are fed into the Transformer encoder layers which include multi-head attention and feed-forward networks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gOSfTLz_cgYgDfpIZYs_1w.png" /></figure><p><strong>Word embeddings </strong>are dense vector representations of words where each word is mapped to a vector in a continuous vector space. These vectors capture semantic meanings and relationships between words based on their usage in the training data. Unlike one-hot encoding, which represents words as sparse vectors, embeddings allow similar words to have similar vector representations, facilitating better understanding and manipulation of text data in machine learning models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2tyyhF9_HmovmFRlIsRDVg.png" /></figure><p><strong>Positional Encoding Formula</strong>: The positional encoding for each word position <strong><em>pos </em></strong>is calculated using sine and cosine functions of different frequencies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_vqkvJqcc-hGHCDRTdqorQ.png" /></figure><p><strong>Visualization</strong>: How positional encodings are computed for different positions in two example sentences “YOUR CAT IS A LOVELY CAT” and “I LOVE YOU”. Each position in the sequence has a unique encoding that helps the model understand the order of words.</p><p><strong>Reuse</strong>: Once computed, these positional encodings can be reused for every sentence, regardless of whether it is during training or inference.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5pVCB9Uj4gekQfNCde5l5Q.png" /></figure><p><strong>Self Attention Mechanism</strong>: Allows the model to relate different words in the sentence to each other.</p><p><strong>Input Matrices (Q, K, V)</strong>: The input embeddings are transformed into three matrices: Queries (<strong><em>Q</em></strong>), Keys (<strong><em>K</em></strong>), and Values (<strong><em>V</em></strong>). These matrices have the dimensions <strong><em>[sequence length, d_model]</em></strong>.</p><p><strong>Attention Calculation</strong>:</p><ul><li>Compute the dot product of <strong><em>Q</em></strong> and <strong><em>K^T</em></strong>, then scale by <strong><em>√dk</em></strong></li><li>Apply the softmax function to obtain the attention weights.</li><li>Multiply the attention weights with <strong><em>V </em></strong>to get the final output.</li><li><strong>Example</strong>: The slide shows a simple case with a sequence length of 6 and <strong><em>d_model </em></strong>of 512. The resulting attention scores illustrate how much focus each word should have on others in the sequence.</li><li><strong>Sum of Attention Weights</strong>: For each word, the attention weights across all other words sum to 1, indicating the distribution of focus.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DWY0Lqy7wu9vAoZBbsVF0A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UroPxrqPUPUIexzfE9pfbA.png" /></figure><p><strong>Inputs</strong>: The inputs are Queries (Q), Keys (K), and Values (V). These are transformed through linear layers.</p><p><strong>Attention Heads</strong>: Multiple attention heads allow the model to focus on different parts of the input data simultaneously. Each head has its own set of Q, K, V inputs.</p><p><strong>Scaled Dot-Product Attention</strong>: Each head computes attention scores using the scaled dot-product method, which helps in determining the importance of different parts of the input.</p><p><strong>Concatenation and Linear Layer</strong>: The outputs from all attention heads are concatenated and passed through a final linear layer to produce the final output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bw4GCccp_3TquweZv-OhLw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z3qjlPOzEvvVPLbjx0AJvg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WUF4lX7zAY_FFe2SQBn5sw.png" /></figure><p><strong>Parallel Attention Heads</strong>: Multiple attention heads process these vectors in parallel, allowing the model to focus on different parts of the input data simultaneously.</p><p>The outputs from all attention heads are concatenated to form the final attention output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ko9KRcF7C9h1K8HQw-mb9g.png" /></figure><p>These symbols <em>(apple, squares etc) </em>represent different data points or categories. <a href="https://www.cloudflare.com/learning/ai/what-are-embeddings/">Embeddings</a> map these symbols into a vector space, allowing the model to understand relationships and similarities between different entities. Attention mechanisms help in effectively utilizing these embeddings to improve the model’s performance by focusing on relevant parts of the input data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_8Wdt6HAyoY9Oh9pbD7UoQ.png" /></figure><p>The graph on the left shows how different words (represented by icons) are connected based on their relationships. For example, the blue square (word) is connected to both an apple logo and an apple fruit, while the orange circle (word) is connected to a smartphone.</p><p>The right side provides examples of how context changes word associations:</p><ul><li>“Please buy an apple and an orange” connects ‘apple’ and ‘orange’ as fruits.</li><li>“Apple unveiled the new phone” connects ‘apple’ to ‘phone’ as a brand.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G6NINhNQxNEqLP_pJDXbLg.png" /></figure><p>Multi-head attention allows the model to relate words in different contexts, such as nouns, verbs, and adjectives. The diagram shows lines connecting words in the sentence, demonstrating how each word can be associated with others depending on its context.</p><p><strong>Example Sentence</strong>: The sentence “The animal didn’t cross the street because it was too tired” is used to illustrate how different words can be connected based on their roles within the sentence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vt-g7dVQgSWxsOVCbOw7xg.png" /></figure><p>Both examples use the sentence “The animal didn’t cross the street because it was too tired.”</p><p><strong>2 Heads vs. 8 Heads</strong>: The colored bars represent how different words in the sentence are attended to by each head. With 2 heads, fewer connections are made, while with 8 heads, more detailed and varied connections are established.</p><p>Using more heads allows the model to capture more nuanced relationships between words, improving its ability to understand and process the sentence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RaqD2ImJEwAUfLsh4jJ_bg.png" /></figure><p>The ‘Keys’ column lists different genres (ROMANCE, ACTION, SCI-FI, HORROR, COMEDY), and the ‘Values’ column lists corresponding movies (TITANIC, THE DARK KNIGHT, INCEPTION, THE SHINING, THE INTOUCHABLES). Lines connect the query “love” to each genre, showing how the query relates to different categories.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NpzCNYPCCPlcMk4euMRNlw.png" /></figure><p><strong>Encoder Output (Enc)</strong>: The encoder’s output is used as keys and values for the attention mechanism in the decoder.</p><p><strong>Masked Multi-Head Attention</strong>: This block processes the input sequence with attention, ensuring that future tokens are masked to prevent information leakage.</p><p><strong>Multi-Head Attention</strong>: This block attends to the encoder’s output, allowing the decoder to focus on relevant parts of the input sequence.</p><p><strong>Add &amp; Norm and Feed Forward</strong>: These layers normalize the output and pass it through a feed-forward network to generate the final output probabilities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Is3fFEh-LdQsFS8EOmfULQ.png" /></figure><p><strong>Matrix Representation</strong>: The matrix shows words “Thinking”, “Machines”, “are”, “the”, “future” with diagonal and lower triangular sections highlighted in orange, indicating permissible attention. Upper triangular sections are crossed out in red, indicating areas where attention is not allowed.</p><p><strong>Attention Masking</strong>: Masked attention ensures that each word can attend to itself and any word before it, but not to future words.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mMnyrk6IQSn3CE5W0uZWrA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RCfoHfBwUPhnWSCkRGfLjA.png" /><figcaption>&lt;SOS&gt;: Start of Sentence | &lt;EOS&gt;: End of Sentence</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BB9q6VQ1njF9MuYphieC1g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kQ7Ri3mVf0CIZeIYnVCafg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yMgP5qniUuO0hq-GQE5kZQ.png" /></figure><p><strong>Decoder Input and Output</strong>: The input sequence <strong><em>“&lt;SOS&gt; Ti amo molto”</em></strong> <em>(Start Of Sentence)</em> is processed by the decoder to produce the output sequence <strong><em>“Ti amo molto &lt;EOS&gt;” </em></strong><em>(End Of Sentence)</em></p><p><strong>Softmax and Linear Layers</strong>: These layers transform the decoder’s output into a probability distribution over the vocabulary, helping the model predict the next word in the sequence.</p><p><strong>Cross Entropy Loss</strong>: This is the loss function used to measure the difference between the predicted output and the actual target. It helps in optimizing the model during training.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yd_0B_xaS35LI00qllp0Bw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bRq5BjTdkNP2OW-rrIdc6w.png" /></figure><p>The <strong>inference process</strong> in a machine translation model at <strong>time step = 1:</strong></p><ol><li><strong>Encoder-Decoder Architecture</strong>: The encoder processes the input sequence, and the decoder generates the output sequence.</li><li><strong>Softmax Layer</strong>: The decoder’s output is passed through a softmax layer to produce logits, which are then converted into probabilities.</li><li><strong>Argmax Selection</strong>: The token with the highest probability (argmax) is selected from the vocabulary as the next word in the sequence.</li><li><strong>Padding</strong>: Both input and output sequences are padded to ensure they have the same length.</li></ol><p>This process is repeated for each time step to generate the entire translated sequence:-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qjv6DvnSO8NUO0WiXrxXSA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W50OFRmsLFjpX5EpO-qGMg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W50OFRmsLFjpX5EpO-qGMg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qHK3zNPAYD9ypu4siIAilw.png" /></figure><h3>Resources:</h3><blockquote><strong><em>Transformers paper:</em></strong><a href="https://arxiv.org/abs/1706.03762"><em> Attention-is-all-you-need</em></a></blockquote><blockquote><strong><em>Blog</em></strong><em>: </em><a href="https://blogs.nvidia.com/blog/what-is-a-transformer-model/"><em>NVIDIA</em></a></blockquote><blockquote><strong><em>Best-Explanation-Video-On-Internet: </em></strong><a href="https://www.youtube.com/watch?v=wjZofJX0v4M"><em>3-blue-1-brown</em></a></blockquote><blockquote><strong><em>Andrej-Karpathy-Explains: </em></strong><a href="https://www.youtube.com/watch?v=XfpMkf4rD6E"><em>Video</em></a></blockquote><blockquote><strong><em>Stat-Quest</em></strong><em>: </em><a href="https://www.youtube.com/watch?v=zxQyTK8quyY"><em>Video</em></a></blockquote><h3>About Us</h3><p><a href="https://www.linkedin.com/company/tfugislamabad/">TFUG Islamabad</a> we’re the first and only Pakistan community to etch our name into the annals of <a href="https://www.linkedin.com/company/google/">Google</a> ML Developer Program history. Since our inception in March 2024, we have organized numerous events, including ML Study Jams, Paper Reading Clubs, ML Math Clubs and various other events.</p><p>Notable Metrics Achieved: Over 1600 total views on our <a href="https://www.youtube.com/@TFUGIslamabad">YouTube</a> channel. Building a network of 1600+ members on WhatsApp and LinkedIn</p><h3>References:</h3><blockquote><em>🎙️ Featured Speaker: </em><a href="https://www.youtube.com/redirect?event=video_description&amp;redir_token=QUFFLUhqbVhJMnByX2hyVUhBa3I3dDJLbUhfUURZY0Vkd3xBQ3Jtc0tuT05JTEJMUzFkT081cV8yNU5wMUVOcTlHVmhyaUxIeUxjaHBnTWhZMTRQenotY25YeGFWWGhMTjdFaUJtS3NKY1VLYkZqNkplY1ZhelZ5ZlhxYjdOSEM1ekk1MC1SOHVsLWR3TVMyT3FPNTloTHVWMA&amp;q=https%3A%2F%2Fwww.linkedin.com%2Fin%2Fmaazalinadeem&amp;v=c7bZoiCbw6Y">Maaz Ali Nadeem</a></blockquote><blockquote><em>📽️ Video Link: </em><a href="https://youtu.be/c7bZoiCbw6Y"><strong><em>Watch the session here</em></strong></a></blockquote><h3>Written By:</h3><p><a href="https://www.linkedin.com/in/muhammad-ali-2480a0255/">Muhammad Ali</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17a3c521ebe4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enhancing Large Language Models through LoRA| ML Paper Reading Clubs Day 1]]></title>
            <link>https://medium.com/@tfugislamabad/enhancing-large-language-models-through-lora-ml-paper-reading-clubs-day-1-83f1e742e386?source=rss-3ca8323a41d6------2</link>
            <guid isPermaLink="false">https://medium.com/p/83f1e742e386</guid>
            <category><![CDATA[fine-tuning]]></category>
            <category><![CDATA[language-model]]></category>
            <category><![CDATA[pre-trained-model]]></category>
            <category><![CDATA[model-training]]></category>
            <category><![CDATA[lora]]></category>
            <dc:creator><![CDATA[TensorFlow User Group Islamabad]]></dc:creator>
            <pubDate>Tue, 30 Jul 2024 14:05:01 GMT</pubDate>
            <atom:updated>2024-07-30T14:05:01.850Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CFG_QNwigHlnocZUHu6BEg.png" /></figure><p><strong>Transformer Architecture:</strong> Large Language Models are primarily based on the transformer architecture, a neural network design introduced in 2017. Unlike previous models that relied on recurrent neural networks (RNNs), transformers are designed to process entire sequences of text in parallel,<br>enabling more efficient learning of long-range dependencies.</p><p><strong>Self-Attention Mechanism: </strong>The key innovation of transformers is the self-attention mechanism. This allows the model to weigh the importance of different words in a sentence when predicting the next word. Self-attention enables LLMS to capture contextual relationships between words, regardless of their distance within the text.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*lakCEUEsboAelz-yum7SjA.png" /><figcaption>Ref: <a href="https://www.google.com/url?sa=i&amp;url=https%3A%2F%2Fwww.researchgate.net%2Ffigure%2FTransformer-Model-Architecture-Transformer-Architecture-26-is-parallelized-for-seq2seq_fig2_342045332&amp;psig=AOvVaw0cVqqkiBay4FmZf9GgIXHb&amp;ust=1722431279029000&amp;source=images&amp;cd=vfe&amp;opi=89978449&amp;ved=0CBQQjhxqFwoTCKiQndbqzocDFQAAAAAdAAAAABAE">ResearchGate</a></figcaption></figure><h4>Encoder-Decoder Structure</h4><p><strong>Encoder</strong>: Processes the input sequence. Each layer has:</p><ul><li><strong>Multi-Head Attention</strong>: Allows the model to focus on different parts of the input.</li><li><strong>Add &amp; Norm</strong>: Adds the input to the output of the attention layer and normalizes it.</li><li><strong>Feed Forward</strong>: Applies a fully connected feed-forward network.</li><li><strong>Add &amp; Norm</strong>: Another normalization step.</li></ul><p><strong>Decoder</strong>: Generates the output sequence. Each layer includes:</p><ul><li><strong>Masked Multi-Head Attention</strong>: Prevents the model from attending to future tokens.</li><li><strong>Multi-Head Attention</strong>: Focuses on the encoder’s output.</li><li><strong>Add &amp; Norm</strong> and <strong>Feed Forward</strong>: Similar to the encoder.</li></ul><h4>Positional Encoding</h4><p>Adds information about the position of each token in the sequence, helping the model understand the order of words.</p><h4>Output Layer</h4><p>The final output passes through a linear layer and a softmax function to produce probabilities for each token.</p><p>Transformers are highly effective for tasks like translation and text generation due to their ability to handle long-range dependencies in data.</p><h3><strong>Pre-training vs Fine-tuning</strong></h3><h4>Pre-training</h4><p>LLMs are initially pre-trained on massive datasets of text (often containing billions of words). This pre-training involves tasks like predicting masked words or the next sentence in a paragraph. Through this process, the model learns general language patterns, grammar, facts, and even some reasoning abilities. Pre-training usually would mean taking the original model, initializing the weights randomly, and training the model from absolute scratch on some large corpora.</p><h4>Fine-tuning</h4><p>Fine-tuning involves further training the pre-trained LLM on a smaller dataset that is specific to the desired task (e.g., question answering, translation, sentiment analysis). This fine-tuning process allows the model to specialize its knowledge and abilities to perform well on the target task. The pre-trained weights are adjusted slightly to better fit the specific task, such as sentiment analysis, named entity recognition, or domain-specific text classification.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*93FkDZTymK3teAPuIRvQcA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JiIW9wDiXWTaiQxt51e01w.png" /><figcaption>Example</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SPb3_vRMhzAqT92XN0mzyw.png" /></figure><h3>Why Lora?</h3><h4><strong>Problem:</strong></h4><p>An LLM with 175B parameters is exciting but daunting to fine-tune on a GPU. Fine-tuning large language models is computationally expensive and requires vast amounts of data.</p><h4><strong>Solution:</strong></h4><p>LoRA offers a more efficient alternative by freezing the pre-trained model weights and injecting low-rank matrices into each layer.</p><h3>LoRA <strong>(Low-Rank Adaptation)</strong></h3><p><strong>LoRA </strong>is a technique designed to efficiently fine-tune large pre-trained models, such as those used in natural language processing, by making minor adjustments rather than retraining the entire model. Here’s a breakdown of the core ideas:</p><h4>1. Low-Rank Decomposition</h4><ul><li><strong>Concept</strong>: LoRA involves approximating large weight matrices in neural networks using low-rank matrices. Instead of updating the full weight matrices during fine-tuning, it decomposes these matrices into products of smaller, low-rank matrices.</li><li><strong>Purpose</strong>: This decomposition reduces the number of parameters that need to be adjusted during fine-tuning, making the process more efficient and computationally less expensive.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*mu4Ldn2wbWQ9H3_Jvd7xKQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*voWtu7aWSA4qDS7VLBGDKw.png" /></figure><h4>2. Injection into Layers</h4><ul><li><strong>Implementation</strong>: LoRA injects the low-rank matrices into specific layers of the pre-trained model. This means that during fine-tuning, the model only updates these low-rank matrices while keeping the original, pre-trained weights frozen.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*OfJaKBJ2uaDXYDrwa8ky5g.png" /></figure><ul><li><strong>Advantage</strong>: By injecting changes into specific layers, LoRA allows for targeted adjustments without modifying the entire model, which helps in preserving the learned features of the pre-trained model.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*VI_zo5Anxs8ID_6V9eos4Q.png" /></figure><h4>3. Frozen Pre-Trained Weights</h4><p>In LoRA, the weights of the pre-trained model are kept fixed (frozen). Only the low-rank matrices that are injected into the layers are trained. Freezing the pre-trained weights ensures that the model retains the knowledge it has already learned, while the low-rank adaptation allows for specific modifications to tailor the model to new tasks or data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*jWw6U1SjartbB1GH0ydHHg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/1*fLBSy7o79OCZReCku92OAQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*1EGoc2Pq5vh4E8jP6mLcMA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*2VV1w4SR0Azvi2QNpRnPGw.png" /></figure><h4>Implementing the Math</h4><pre>import torch.nn as nn<br><br>class LoRALayer(nn.Module):<br>    def __init__(self, in_dim, out_dim, rank, alpha):<br>        super(LoRALayer, self).__init__()<br>        std_dev = 1.0 / torch.sqrt(torch.tensor(rank).float())<br>        self.A = nn.Parameter(torch.randn(in_dim, rank) * std_dev)<br>        self.B = nn.Parameter(torch.randn(rank, out_dim))<br>        self.alpha = alpha<br><br>    def forward(self, x):<br>        x = self.alpha * (x @ self.A @ self.B)<br>        return x<br><br># Explanation:- <br>&quot;&quot;&quot;The __init__ method initializes the layer with input dimensions (in_dim), <br>output dimensions (out_dim), rank (rank), and a scaling factor (alpha).<br><br>super(LoRALayer, self).__init__() calls the constructor of the parent class <br>(nn.Module).<br><br>std_dev is calculated as the inverse of the square root of the rank, which is<br>used to scale the initial weights.<br><br>self.A and self.B are defined as learnable parameters (nn.Parameter). self.A <br>is initialized with random values scaled by std_dev, and self.B is initialized<br>with random values.<br><br>self.alpha is set to the provided scaling factor.<br>&quot;&quot;&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*b5JAfw1myVjY2YzawEQMVA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*bsr7yX0ofNtCUGOUWFq1HA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*ky8FsP_IXuen9-1ES5SV9w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*sqgOwazGOMZDYjTTF2MJ0g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*tMGwOjocVxh-Kn9Y-oluHg.png" /></figure><h3>Resources:</h3><blockquote><strong><em>LoRA paper:</em></strong><em> </em><a href="http://[2106.09685] LoRA: Low-Rank Adaptation of Large Language Models (arxiv.org)"><em>Arxiv.org</em></a></blockquote><blockquote><strong><em>LoRA Summary Blog</em></strong><em>: </em><a href="https://blog.gopenai.com/lora-squeezing-giants-into-ants-with-style-b7e9af10584a"><em>Open-ai</em></a></blockquote><blockquote><strong><em>Understand LLMs: </em></strong><a href="https://cloud.google.com/ai/llms"><em>Google-Cloud</em></a></blockquote><blockquote><strong><em>Gemma official document: </em></strong><a href="https://ai.google.dev/gemma/docs"><em>Google</em></a></blockquote><blockquote><strong><em>Revised approach to LORA- DORA</em></strong>: <a href="https://arxiv.org/abs/2402.09353">https://arxiv.org/abs/2402.09353</a></blockquote><h3>About Us</h3><p><a href="https://www.linkedin.com/company/tfugislamabad/">TFUG Islamabad</a> is the premier community for TensorFlow enthusiasts. Our group is dedicated to bringing together professionals, researchers, and enthusiasts from diverse backgrounds who share a common interest in AI.</p><h3>References:</h3><blockquote><em>🎙️ Featured Speaker: </em><a href="https://www.linkedin.com/in/aashi-dutt"><em>Aashi-D</em></a><em>.</em></blockquote><blockquote><em>📽️ Video Link: </em><a href="https://www.youtube.com/watch?v=L6d50UlyHIU"><strong><em>Watch the session here</em></strong></a></blockquote><h3>Written By:</h3><p><a href="https://www.linkedin.com/in/muhammad-ali-2480a0255/">Muhammad Ali</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83f1e742e386" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prompt Engineering Techniques for Language Models | ML Study Jams Day 7]]></title>
            <link>https://medium.com/@tfugislamabad/prompt-engineering-techniques-for-language-models-ml-study-jams-day-7-717432d5395e?source=rss-3ca8323a41d6------2</link>
            <guid isPermaLink="false">https://medium.com/p/717432d5395e</guid>
            <category><![CDATA[language-model]]></category>
            <category><![CDATA[google-gemini]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[gemini]]></category>
            <dc:creator><![CDATA[TensorFlow User Group Islamabad]]></dc:creator>
            <pubDate>Tue, 30 Jul 2024 12:41:24 GMT</pubDate>
            <atom:updated>2024-07-30T12:43:11.839Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xLi_qsRBBO7rj7_pdzNJKA.png" /></figure><blockquote>For Code Visit <strong>Resources</strong> <strong>Section</strong> At The End Of The Article</blockquote><h3>How do LLMs generate outputs?</h3><p>Here’s an overview of how LLMs generate outputs:</p><h4>1. Tokenization</h4><ul><li><strong>Text Input:</strong> The input text is first tokenized into smaller units called tokens. These tokens can be words, subwords, or even individual characters depending on the model’s design.</li><li><strong>Vocabulary:</strong> The model uses a predefined vocabulary to convert each token into a numerical representation (token ID).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*_gAjWsrvXOlzIqFL3js7Eg.png" /><figcaption>Ref: <a href="https://neptune.ai/blog/customizing-llm-output-post-processing-techniques">NeptuneAI-Blog</a></figcaption></figure><h4>2. Embedding</h4><ul><li><strong>Token Embeddings:</strong> Each token ID is mapped to a high-dimensional vector using an embedding matrix. This converts the discrete tokens into continuous vectors that the model can process.</li><li><strong>Positional Embeddings:</strong> Since LLMs like GPT are based on the Transformer architecture, positional embeddings are added to the token embeddings to provide information about the position of each token in the sequence.</li></ul><h4>3. Encoding with Transformer Layers</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*iMuZV6dpf1lo4UPfMXg8mQ.png" /><figcaption>Ref: <a href="https://neptune.ai/blog/customizing-llm-output-post-processing-techniques">NeptuneAI-Blog</a></figcaption></figure><ul><li><strong>Multi-Head Self-Attention:</strong> The model uses self-attention mechanisms to allow each token to attend to every other token in the sequence. This helps the model capture dependencies between tokens regardless of their distance in the sequence.</li><li><strong>Feed-Forward Neural Networks:</strong> After the self-attention mechanism, the model applies a series of feed-forward neural networks to transform the attention outputs.</li><li><strong>Layer Normalization and Residual Connections:</strong> Each layer includes normalization and residual connections to stabilize and improve the learning process.</li><li><strong>Stacked Layers:</strong> The Transformer consists of multiple layers of attention and feed-forward networks, each refining the representation of the input.</li></ul><h4>4. Decoding for Output Generation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*gh2280_NkOn3V9CicNNv3g.png" /><figcaption>Ref: <a href="https://neptune.ai/blog/customizing-llm-output-post-processing-techniques">NeptuneAI-Blog</a></figcaption></figure><ul><li><strong>Softmax Layer:</strong> After processing through multiple Transformer layers, the final layer’s outputs are passed through a softmax layer to convert the logits into probabilities for each token in the vocabulary.</li><li><strong>Sampling or Beam Search:</strong> The model generates the next token based on the probabilities. Common methods include:</li><li><strong>Greedy Sampling:</strong> Selecting the token with the highest probability.</li><li><strong>Beam Search:</strong> Exploring multiple possible sequences to find the most probable one.</li><li><strong>Top-k Sampling:</strong> Sampling from the top k most probable tokens.</li><li><strong>Nucleus Sampling (Top-p):</strong> Sampling from the smallest set of tokens whose cumulative probability exceeds a threshold p.</li></ul><h4>5. Iterative Generation</h4><ul><li><strong>Recurrent Process:</strong> For generating longer sequences, the model iteratively takes the previously generated tokens as input and continues the process until a stopping criterion is met (e.g., reaching a maximum length or generating an end-of-sequence token).</li></ul><h4>6. Output Post-Processing</h4><ul><li><strong>Detokenization:</strong> The generated token IDs are converted back into text tokens.</li><li><strong>Text Construction:</strong> The tokens are joined together to form the final coherent text output.</li></ul><h3>Basic Prompt Engineering Techniques</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*PfT5Vx8fXzHuadhWHHTQig.png" /></figure><p><strong>Zero-shot prompting</strong> refers to the ability of a language model to perform a task without having been explicitly trained on specific examples of that task. Instead, the model leverages its broad understanding of language and general knowledge acquired during its pretraining to generate appropriate responses based on the prompt given.</p><h4>How Does It Work?</h4><p><strong>Pretrained Language Model: </strong>The model, such as GPT-4, is pretrained on a large corpus of diverse text data. This pretraining allows the model to learn a wide range of language patterns, facts, and reasoning abilities.</p><p><strong>Task Description in Prompt: </strong>When a user provides a prompt, it typically includes a clear description or instruction of the task. For instance, “Translate the following English sentence to French: ‘How are you?’” or “What is the capital of Germany?”.</p><p><strong>Model Generates Response: </strong>The model interprets the task based on the prompt and generates a response. Since the model has seen varied language uses during pretraining, it can generalize to new tasks without specific task training examples.</p><pre>prompt = &quot;&quot;&quot;Classify the sentence into neutral, negative or positive.<br>Text: We loved the movie we watched last night!<br>Sentiment:&quot;&quot;&quot;<br>response = model.generate_content(prompt)<br>to_markdown(response.text)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*fhIX0licO5lEJCPDk5hSoA.png" /></figure><p><strong>Few-shot prompting</strong> involves providing a language model with a few examples of a task within the prompt to guide the model’s understanding and generate more accurate responses. Unlike zero-shot prompting, which relies solely on a task description, few-shot prompting uses example inputs and their corresponding outputs to demonstrate the task.</p><h4>How Does It Work?</h4><p><strong>Pretrained Language Model: </strong>Similar to zero-shot prompting, the model is pretrained on a large corpus of text, learning a wide range of language patterns and knowledge.</p><p><strong>Providing Examples: </strong>In the prompt, the user includes a few examples of the task. Each example consists of an input and its correct output. These examples help the model understand the desired format and type of response.</p><p><strong>Task Description and Query: </strong>After the examples, the user provides a new input for which the model needs to generate a response, following the pattern demonstrated by the examples.</p><pre># Without Few-Shot<br>prompt = &quot;&quot;&quot;Classify the sentence into lpopolp, or aufhudsh following the examples provided. Don&#39;t provide any explanation.<br>Text: For me, it was one of the best movies I watched in my whole life.&quot;&quot;&quot;<br>response = model.generate_content(prompt)<br>to_markdown(response.text)<br><br># With Few-Shot<br>prompt = &quot;&quot;&quot;Classify the sentence into lpopolp, or aufhudsh following the examples provided. Don&#39;t provide any explanation.<br>Text: We loved the movie we watched last night!<br>Sentiment: lpopolp<br>Text: Bro, I hated the movie!<br>Sentiment: aufhudsh<br>Text: For me, it was one of the best movies I watched in my whole life.&quot;&quot;&quot;<br>response = model.generate_content(prompt)<br>to_markdown(response.text)</pre><h3>Advanced Prompt Engineering Techniques</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*9MjAKRLqv0nB5TUKEmfyug.png" /></figure><p><strong>RAG</strong> (Retrieval-Augmented Generation) is a machine learning model architecture that combines retrieval-based and generation-based approaches for natural language understanding and generation tasks.</p><p><strong>Retrieval Component</strong>: The model first retrieves relevant information from a large corpus or database based on the input query. This step involves searching for documents or pieces of text that might contain useful information related to the query.</p><p><strong>Generation Component</strong>: After retrieving relevant documents, the model uses this information to generate a coherent and contextually appropriate response or output. This step leverages generative techniques to produce natural language text based on both the retrieved information and the original query.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*mS7BDE2dpnN7Tenuuey1bw.png" /></figure><blockquote>Ref: <a href="https://arxiv.org/pdf/2401.07883">https://arxiv.org/pdf/2401.07883</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*id6bLWbNP-qEJvGXcEFR8Q.png" /></figure><p><strong>Chain of Thought Prompting</strong> is a technique used to improve the performance of language models by guiding them through a structured reasoning process.</p><blockquote>Ref: <a href="https://arxiv.org/abs/2201.11903">https://arxiv.org/abs/2201.11903</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*XrsfZ9kOu8y3QGRaSuKLJg.png" /></figure><p>Instead of asking the model a question or giving it a task directly, you provide a series of prompts or instructions that lead the model through a step-by-step reasoning process. This structured approach helps the model break down complex tasks into smaller, manageable steps.</p><p>Each step in the chain of thought involves the model generating intermediate reasoning or calculations before arriving at a final answer. This approach mimics how humans often solve problems by breaking them down and thinking through each step.</p><p>Chain of Thought Prompting can improve the accuracy and coherence of the model’s responses, especially for tasks requiring multi-step reasoning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*G_DDFK7yzIhn-taN0TWV_A.png" /></figure><p><strong>Self-Consistency Prompt Engineering</strong> is a technique used to improve the reliability and accuracy of language models by guiding them to produce more consistent and reliable responses.</p><blockquote>Ref: <a href="https://arxiv.org/pdf/2203.11171">https://arxiv.org/pdf/2203.11171</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*CVTSw1boxZs-JhtH0cP-3w.png" /></figure><p><strong>Sample Diverse Reasoning Paths</strong>: Generate multiple reasoning paths or answers for a given prompt. This helps in exploring different ways the model can interpret and respond to the prompt.</p><p><strong>Language Model</strong>: Use the language model to generate these diverse reasoning paths. Each path represents a different possible answer or reasoning process.</p><p><strong>Marginalize Out Reasoning Paths</strong>: Aggregate the final answers by considering all the reasoning paths. This involves combining the different answers to arrive at a more consistent and reliable final response.</p><p><em>So in essence, self-consistency ensures that the model’s responses are not only accurate but also consistent across different reasoning paths, leading to more robust and trustworthy outputs.</em></p><h3>Resources:</h3><blockquote><strong><em>Hands-On-Code:</em></strong><em> </em><a href="https://colab.research.google.com/drive/1m1q7hm7KczRwqO3oLy9MB1VcIa5b6NVx?usp=sharing"><em>Google-Colab</em></a></blockquote><blockquote><strong><em>For More Detail</em></strong>:<em> </em><a href="https://arxiv.org/abs/2406.06608"><em>Paper</em></a></blockquote><blockquote><strong><em>Rag Visual Understanding</em></strong>: <a href="https://www.youtube.com/watch?v=T-D1OfcDW1M"><em>IBM-Video</em></a></blockquote><h3>About Us</h3><p><a href="https://www.linkedin.com/company/tfugislamabad/">TFUG Islamabad</a> is the premier community for TensorFlow enthusiasts. Our group is dedicated to bringing together professionals, researchers, and enthusiasts from diverse backgrounds who share a common interest in AI.</p><h3>References:</h3><blockquote><em>🎙️ Featured Speaker: </em><a href="https://www.linkedin.com/in/pedrogengo"><em>Pedro Gabriel Lourenço</em></a></blockquote><blockquote><em>📽️ Video Link: </em><a href="https://youtu.be/A5qM9O1LaCE"><strong><em>Watch the session here</em></strong></a></blockquote><h3>Written By:</h3><p><a href="https://www.linkedin.com/in/muhammad-ali-2480a0255/">Muhammad Ali</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=717432d5395e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quantization Approaches for TensorFlow Models | ML Study Jams Day 6]]></title>
            <link>https://medium.com/@tfugislamabad/quantization-approaches-for-tensorflow-models-ml-study-jams-day-6-d0c6ab719c98?source=rss-3ca8323a41d6------2</link>
            <guid isPermaLink="false">https://medium.com/p/d0c6ab719c98</guid>
            <category><![CDATA[language-model]]></category>
            <category><![CDATA[tensorflow-lite]]></category>
            <category><![CDATA[model-quantization]]></category>
            <category><![CDATA[machine-learning-tools]]></category>
            <dc:creator><![CDATA[TensorFlow User Group Islamabad]]></dc:creator>
            <pubDate>Tue, 30 Jul 2024 11:40:32 GMT</pubDate>
            <atom:updated>2024-07-30T11:40:32.778Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zAfYW3PthiMB9srRlB1U8w.png" /></figure><h3>What is Quantization</h3><p>Quantization in machine learning is the process of converting a model’s parameters, such as weights and activations, from higher precision (e.g., 32-bit floating point) to lower precision (e.g., 8-bit integer). The primary goal of quantization is to reduce the model size and increase inference speed while maintaining acceptable levels of accuracy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*CO20e6zxB8Hh10IfIC-7VQ.png" /></figure><ol><li><strong>Post-Training Quantization</strong>: Applied after the model is trained. The weights are quantized, and sometimes activations are quantized during inference.</li><li><strong>Quantization-Aware Training (QAT)</strong>: Incorporates quantization in the training process itself. The model is trained to be aware of the quantization effects, which can lead to better accuracy compared to post-training quantization.</li><li><strong>Dynamic Quantization</strong>: Applies quantization dynamically during inference. Typically used for activations, where the range of values might vary during runtime.</li><li><strong>Static Quantization</strong>: Requires calibration on a subset of the training data to determine the range of activations. This method applies fixed quantization during inference.</li></ol><pre>#DEFINING THE MODEL<br>model = keras.Sequential([<br>    keras.layers.InputLayer(input_shape=(28, 28)),<br>    keras.layers.Reshape(target_shape=(28, 28, 1)),<br>    keras.layers.Conv2D(filters=12, kernel_size=3, activation=tf.nn.relu),<br>    keras.layers.MaxPooling2D(pool_size=2),<br>    keras.layers.Flatten(),<br>    keras.layers.Dense(10)<br>])<br>converter = tf.lite.TFLiteConverter.from_keras_model(model)<br>converter.optimizations = [tf.lite.Optimize.DEFAULT]<br>converter.target_spec.supported_types = [tf.float16]<br>tflite_fp16_model = converter.convert()</pre><p>After defining the CNN model, the model is converted to TensorFlow Lite format with 16-bit float quantization. Here, TFLiteConverter is used to convert the Keras model, and optimizations for 16-bit floats are specified.</p><h4>Using the Quantized Model with TensorFlow Lite.</h4><p><strong>Interpreter Setup:</strong> An interpreter for the TensorFlow Lite model is created and tensors are allocated:</p><pre>interpreter_fp16 = tf.lite.Interpreter(model_path=str(tflite_model_fp16_file))<br>interpreter_fp16.allocate_tensors()</pre><p><strong>Preparing Input Data: </strong>A test image is expanded and converted to the required data type (float32):</p><pre>test_image = np.expand_dims(test_images[0], axis=0).astype(np.float32)</pre><p><strong>Getting Input and Output Details:</strong> The input and output tensor indices are retrieved</p><pre>input_index = interpreter_fp16.get_input_details()[0][&quot;index&quot;]<br>output_index = interpreter_fp16.get_output_details()[0][&quot;index&quot;]p</pre><p><strong>Setting Input Tensor and Running Inference: </strong>The test image is set as the input tensor, and the interpreter runs inference</p><pre>interpreter_fp16.set_tensor(input_index, test_image)<br>interpreter_fp16.invoke()<br>predictions = interpreter_fp16.get_tensor(output_index)</pre><p><em>So all the code above demonstrates the steps for defining a Keras model, converting it to TensorFlow Lite with 16-bit float quantization, and using the TensorFlow Lite interpreter to perform inference. This approach helps reduce the model size and improves inference speed while maintaining a good balance between performance and accuracy.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*wcrxAExn1ifI90rl3bGsvg.png" /></figure><p><strong>Starting with an FP16 Vector:</strong> The original vector contains values in 16-bit floating-point format, which is precise but consumes more memory.</p><p><strong>Finding the Maximum Absolute Value:</strong> The maximum absolute value in the vector is identified (5.4 in this case). This value is used to determine the scaling factor for quantization.</p><p><strong>Calculating the Quantization Factor:</strong> The quantization factor (α) is derived from the maximum absolute value. For this example, the factor is 23.5.</p><p><strong>Quantizing to INT8:</strong> Each value in the FP16 vector is scaled by dividing it by the quantization factor and converting it to an 8-bit integer (INT8). This results in a quantized vector with values ranging between -127 and 127, significantly reducing the bit-width and memory usage.</p><p><strong>De-Quantization:</strong> To convert the quantized INT8 values back to their original FP16 format, the values are multiplied by the quantization factor (α). This step retrieves values that are close to the original FP16 values, allowing for efficient storage and computation while preserving accuracy.</p><p><strong>Representative Data Generation</strong></p><pre>def representative_data_gen():<br>    for input_value in tf.data.Dataset.from_tensor_slices(train_images).take(100):<br>        yield [input_value]<br># This function generates representative data from train_images to help the <br># converter understand the range of input values.</pre><p><strong>Converter Setup</strong></p><pre>converter = tf.lite.TFLiteConverter.from_keras_model(model)<br>converter.optimizations = [tf.lite.Optimize.DEFAULT]<br>converter.representative_dataset = representative_data_gen<br><br># Model Conversion: Initializes the converter with the Keras model.<br># Optimization: Sets the optimization strategy to default.<br># Representative Dataset: Uses the representative data for quantization.</pre><p><strong>Target Specification</strong></p><pre>converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]<br>converter.inference_input_type = tf.uint8<br>converter.inference_output_type = tf.uint8</pre><pre># Supported Operations: Specifies that only INT8 operations are supported.<br># Input/Output Types: Sets the input and output types to uint8.</pre><p><strong>Model Conversion</strong></p><pre>tflite_model_quant = converter.convert()<br># Converts the model to TensorFlow Lite format</pre><h3>API Reference For tf.quantization</h3><pre>import tensorflow as tf<br>#Quantization<br>quantized_tensor = tf.quantization.quantize(<br>    input=input_tensor,<br>    min_range=min_range,<br>    max_range=max_range,<br>    T=tf.quint8,<br>    mode=&#39;MIN_COMBINED&#39;,<br>    round_mode=&#39;HALF_AWAY_FROM_ZERO&#39;,<br>    name=None,<br>    axis=None,<br>    ensure_minimum_range=0.01)<br><br># ~Function Explanation~<br># Purpose: Converts a floating-point tensor to a quantized tensor of type &#39;T&#39;.<br># Parameters:<br># input: The tensor to be quantized.<br># min_range and max_range: The range of the input values.<br># T: The data type for the output tensor.<br># mode: Specifies the quantization mode (e.g., &#39;MIN_COMBINED&#39;).<br># round_mode: Rounding method (e.g., &#39;HALF_AWAY_FROM_ZERO&#39;).<br># name, axis, ensure_minimum_range: Additional optional parameters</pre><pre># Dequantization<br>dequantized_tensor = tf.quantization.dequantize(<br>    input=quantized_tensor,<br>    min_range=min_range,<br>    max_range=max_range,<br>    mode=&#39;MIN_COMBINED&#39;,<br>    name=None,<br>    axis=None,<br>    narrow_range=False,<br>    dtype=tf.dtypes.float32)<br><br># ~Function Explanation~<br># Purpose: Converts a quantized tensor back to a floating-point tensor.<br># Parameters:<br># Similar to the quantize function, but includes dtype to specify the output <br># data type (e.g., tf.dtypes.float32).</pre><h3>Advanced Quantization Techniques</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eE-YgFlgg2OYuZJGLnEpQQ.png" /></figure><p><strong>Blockwise Quantization</strong> is an advanced technique that divides the tensor into smaller blocks and quantizes each block separately. This method offers a finer granularity of control over the quantization process, often leading to better performance in terms of model accuracy and computational efficiency</p><h4>Working</h4><ul><li><strong>Divide Tensor into Blocks: </strong>The tensor is divided into smaller blocks of a specified size. Each block is treated as an independent unit for quantization.</li><li><strong>Quantize Each Block Independently: </strong>Each block is quantized separately, using its own scaling factor and zero-point. This allows for more precise quantization within each block, as the dynamic range can be better matched to the values within the block.</li><li><strong>Reconstruct the Quantized Tensor: </strong>The quantized blocks are then reassembled to form the entire quantized tensor. During inference, the de-quantization process is also applied block-wise.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ytvJ6Ex-RJIz3HsF1nVapQ.png" /><figcaption><a href="https://arxiv.org/abs/2305.14314">https://arxiv.org/abs/2305.14314</a>.</figcaption></figure><p><strong>Quantile Quantization</strong> is an advanced quantization technique that aims to preserve the distribution of the data more effectively than traditional linear quantization methods.</p><h4>Working</h4><ul><li><strong>Data Distribution Analysis: </strong>The data (weights or activations) is analyzed to understand its distribution. Instead of assuming that the data is uniformly distributed, quantile quantization takes into account the actual distribution.</li><li><strong>Dividing into Quantiles: </strong>The range of data is divided into quantiles, which are intervals that contain an equal number of data points. For example, if you divide the data into 4 quantiles (quartiles), each quantile will contain 25% of the data points.</li><li><strong>Mapping to Quantized Values: </strong>Each quantile is then mapped to a specific quantized value. This mapping ensures that the quantized values better represent the original distribution of the data. Typically, the quantized value for each quantile is chosen to be the median or mean of the data points within that quantile.</li><li><strong>Quantization and De-Quantization: </strong>During the quantization process, each original data point is mapped to the corresponding quantized value based on the quantile it falls into. During de-quantization, the quantized values are mapped back to approximate original values using the same quantile intervals.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*n8c_7o34Z2pRd0DpYv2AbA.png" /></figure><p><strong>Distributial Quantization</strong> (often referred to as Distribution-Aware Quantization) is an advanced quantization technique that leverages the statistical properties of the data to improve the accuracy and efficiency of the quantized model. This technique ensures that the quantization process is more aligned with the inherent distribution of the data, leading to better performance.</p><h4>Working</h4><ol><li><strong>Analyze Data Distribution: </strong>The data (weights or activations) is first analyzed to understand its statistical distribution. This involves calculating metrics like mean, variance, and histograms to capture the shape of the data distribution.</li><li><strong>Determine Quantization Bins: </strong>Instead of using uniform intervals, quantization bins are determined based on the data distribution. This means that the bin edges are chosen such that each bin has a similar number of data points or matches the density of the distribution.</li><li><strong>Map Data to Quantized Values: </strong>Each data point is mapped to the nearest bin, and each bin is associated with a representative quantized value (e.g., the mean or median of the bin). This ensures that more frequent values in the original data distribution are represented more accurately in the quantized form.</li><li><strong>Quantization and De-Quantization: </strong>During the quantization process, data points are replaced with their corresponding quantized values. During de-quantization, these values are mapped back to approximate the original values using the same distribution-aware bins.</li></ol><h3>Resources:</h3><blockquote><strong><em>To Learn More:</em></strong><em> </em><a href="https://intellabs.github.io/distiller/algo_quantization.html"><em>Article</em></a></blockquote><blockquote><strong><em>Quantization-aware training:</em></strong><em> </em><a href="http://tensorflow.org/model_optimization/guide/quantization/training."><em>Read-More</em></a></blockquote><blockquote><strong><em>HuggingFace-Docs:</em></strong><em> </em><a href="http://huggingface.co/docs/transformers/main_classes/quantization"><em>Link</em></a></blockquote><blockquote><strong><em>Session Slide:</em></strong><em> </em><a href="https://docs.google.com/presentation/d/1tY-gvO_k5NS_Tgj_fkyoC4UqhSWFaRGvjaO8Nt2oel0/edit#slide=id.g29e75a29927_0_173"><em>Link</em></a></blockquote><h3>About Us</h3><p><a href="https://www.linkedin.com/company/tfugislamabad/">TFUG Islamabad</a> is the premier community for TensorFlow enthusiasts. Our group is dedicated to bringing together professionals, researchers, and enthusiasts from diverse backgrounds who share a common interest in AI.</p><h3>References:</h3><blockquote><em>🎙️ Featured Speaker: </em><a href="https://www.linkedin.com/in/radostin-cholakov-bb4422146"><strong><em>Radostin Cholakov</em></strong></a></blockquote><blockquote><em>📽️ Video Link: </em><a href="https://youtu.be/R-LL8ve5Jfc"><strong><em>Watch the session here</em></strong></a></blockquote><h3>Written By:</h3><p><a href="https://www.linkedin.com/in/muhammad-ali-2480a0255/">Muhammad Ali</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0c6ab719c98" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Hyperparameter Tuning with TensorFlow and GCP | ML Study Jams Day 5]]></title>
            <link>https://medium.com/@tfugislamabad/mastering-hyperparameter-tuning-with-tensorflow-and-gcp-ml-study-jams-day-5-89f460dbc326?source=rss-3ca8323a41d6------2</link>
            <guid isPermaLink="false">https://medium.com/p/89f460dbc326</guid>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[hyperparameter-tuning]]></category>
            <dc:creator><![CDATA[TensorFlow User Group Islamabad]]></dc:creator>
            <pubDate>Mon, 29 Jul 2024 13:07:04 GMT</pubDate>
            <atom:updated>2024-07-29T13:07:04.447Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*289lCCLh-HLRX6BfmiqMYg.png" /></figure><h3>Function Approximation in ML</h3><p>Function approximation is a key concept in machine learning. It refers to the process of finding a function <strong><em>f </em></strong>that approximates a target function <strong><em>f*</em></strong> as closely as possible. The target function <strong><em>f*</em></strong> represents the true relationship between inputs and outputs in the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dJO60TXPnJCqW7D4QjzQxg.png" /></figure><p>To find the error between actual output and predicted output, for a single instance is called Loss Function. Calculating Loss function for all instances becomes a Cost Function<em> (hence the </em><strong><em>∑ </em></strong><em>below).</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2T1I41p2w3qOOR9kZmaHRw.png" /><figcaption>The Goal Is To Lower This Cost Function</figcaption></figure><h3>Main Components Of Machine Learning</h3><ol><li>Optimization Algorithm</li><li>Parameters</li><li>Hyperparameters</li></ol><h3>Optimization Algorithm</h3><p>An optimization algorithm in machine learning is a method used to adjust the parameters of a model in order to minimize (or maximize) a predefined objective function, typically a loss function. The purpose of optimization in machine learning is to find the best possible parameters that make the model perform well on given tasks.</p><h4>Common Optimization Algorithms</h4><p><strong>Gradient Descent</strong>: Most widely used optimization algorithm. It involves updating the parameters in the direction opposite to the gradient of the objective function with respect to the parameters.</p><blockquote><strong>For Complete Understanding:</strong> <a href="https://builtin.com/data-science/gradient-descent#:~:text=Gradient%20Descent%20is%20an%20optimization%20algorithm%20for%20finding%20a%20local,function%20as%20far%20as%20possible.">Gradient-Descent</a></blockquote><p><strong>Stochastic Gradient Descent (SGD)</strong>: A variation of gradient descent that updates the parameters using only one or a few training examples at a time. This makes the updates noisy but allows the algorithm to potentially escape local minima and converge faster</p><blockquote><strong>For Complete Understanding: </strong><a href="https://www.geeksforgeeks.org/ml-stochastic-gradient-descent-sgd/">SGD</a></blockquote><p><strong>Mini-batch Gradient Descent</strong>: A compromise between batch gradient descent and SGD. It updates the parameters using a small batch of training examples.</p><blockquote><strong>For Complete Understanding: </strong><a href="https://machinelearningmastery.com/gentle-introduction-mini-batch-gradient-descent-configure-batch-size/">Mini-batch</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cK1LhDQD7uTcl_SHoPLJPA.png" /></figure><p><strong>Parameters </strong>are the internal variables of a model that are learned from the training data. These parameters are crucial as they define the model’s behavior and influence its predictions. They are adjusted during the training process to minimize the difference between the predicted outputs and the actual outputs, usually by minimizing a loss function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SqaEAGC3ZWBUuuo4ON6J4A.png" /></figure><p>Consider you’re making a dish. So just like you might adjust the temperature, cooking time, or seasoning levels to achieve the best flavor in a recipe, you adjust <strong>hyperparameters</strong> to get the best performance from your machine learning model.</p><h4>Some Examples</h4><p><strong>Regularization Parameters (λ): </strong>Parameters like L1 or L2 regularization that prevent overfitting by penalizing large weights.</p><p><strong>Dropout Rate</strong>: The fraction of neurons to drop during training to prevent overfitting in neural networks.</p><p><strong>Learning Rate (η)</strong>: Controls how much to change the model’s parameters with respect to the loss gradient.</p><h3>Problems With Hyperparameters</h3><p>▸Choosing the right hyperparameters can be complex and time-consuming due to the large number of possible combinations.</p><p>▸Different models and datasets require different hyperparameter values, and there is no one-size-fits-all solution.</p><p>▸Hyperparameter tuning, especially with methods like grid search or random search, can be computationally expensive.</p><p>▸Hyperparameters tuned for one dataset might not generalize well to another dataset.</p><h3>Solutions</h3><h4>1. Automated Hyperparameter Tuning</h4><ul><li><strong>Grid Search</strong>: Systematically tries all possible combinations within a predefined set of hyperparameters. While exhaustive, it’s computationally expensive.</li><li><strong>Random Search</strong>: Randomly samples hyperparameters within a specified range. Often more efficient than grid search in high-dimensional spaces.</li></ul><p><a href="https://towardsdatascience.com/bayesian-optimization-concept-explained-in-layman-terms-1d2bcdeaf12f"><strong>Bayesian Optimization</strong></a>: Uses a probabilistic model to find the best hyperparameters by learning from previous evaluations. Libraries like <em>Hyperopt</em>, <em>Optuna</em>, and <em>Scikit-optimize</em> implement this approach.</p><p><a href="https://www.automl.org/automl/"><strong>Automated Machine Learning</strong></a><strong> (AutoML)</strong>: Platforms like <em>AutoKeras</em>, <em>TPOT</em>, and <em>Google Cloud AutoML </em>automatically search for the best model and hyperparameters.</p><h4>2. Cross-Validation</h4><p><a href="https://www.youtube.com/watch?v=fSytzGwwBVw&amp;vl=en">Cross-validation</a> helps in assessing how the model generalizes to an independent dataset and is useful for comparing the performance of different hyperparameter settings. Common strategies include:</p><ul><li><a href="https://machinelearningmastery.com/k-fold-cross-validation/"><strong>k-Fold Cross-Validation</strong></a>: Splits the data into k subsets and trains the model k times, each time using a different subset as the validation set and the remaining data as the training set.</li><li><a href="https://www.linkedin.com/pulse/stratified-k-fold-cross-validation-in-depth-look-yeshwanth-n#:~:text=Stratified%20K%2DFold%20Cross%2DValidation%20is%20a%20variation%20of%20K,class%20might%20be%20heavily%20underrepresented."><strong>Stratified k-Fold Cross-Validation</strong></a>: Ensures that each fold has a representative proportion of classes, useful for imbalanced datasets.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NxmxyG3n72Fpzs33e6iiHA.png" /></figure><h3>Resources:</h3><blockquote><strong><em>An Intuitive Understanding of the Basics: </em></strong><a href="https://medium.com/red-buffer/neural-odes-an-intuitive-understanding-of-the-basics-63d47464e009">Medium</a> <strong>(Recommended)</strong></blockquote><blockquote><strong><em>Kaggle:</em></strong><em> </em><a href="https://www.kaggle.com/code/pavansanagapati/automated-hyperparameter-tuning">Hyperparameter-Notebook</a> <strong>(Python Code For Everything Discussed)</strong></blockquote><blockquote><strong><em>TensorFlow Tutorial</em>:</strong> <a href="https://www.tensorflow.org/tutorials/keras/keras_tuner">Intro to Keras Tuner</a></blockquote><blockquote><strong><em>Session Code:</em></strong><em> </em><a href="https://github.com/imransalam/gcp-ai-platform-hyperparameter-tuning-tf2">GitHub-Repo</a></blockquote><blockquote><strong><em>Scikit-Learn Documentation:</em></strong> <a href="https://scikit-learn.org/stable/modules/grid_search.html">Hyperparameters</a></blockquote><blockquote><strong><em>TensorFlow Documentation:</em></strong> <a href="https://www.tensorflow.org/decision_forests/tutorials/automatic_tuning_colab">Automated Hyperparameter</a></blockquote><h3>About Us</h3><p><a href="https://www.linkedin.com/company/tfugislamabad/">TFUG Islamabad</a> is the premier community for TensorFlow enthusiasts. Our group is dedicated to bringing together professionals, researchers, and enthusiasts from diverse backgrounds who share a common interest in AI.</p><h3>References:</h3><blockquote><em>🎙️ Featured Speaker: </em><a href="https://www.linkedin.com/in/imran-us-salam-mian-54a48897"><strong><em>Imran us Salam</em></strong></a></blockquote><blockquote><em>📽️ Video Link: </em><a href="https://youtu.be/rVhUZ2iFE-w"><strong><em>Watch the session here</em></strong></a></blockquote><h3>Written By:</h3><p><a href="https://www.linkedin.com/in/muhammad-ali-2480a0255/">Muhammad Ali</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89f460dbc326" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding PaliGemma: Google’s Vision Language Model | ML Study Jams Day 4]]></title>
            <link>https://medium.com/@tfugislamabad/understanding-paligemma-googles-vision-language-model-ml-study-jams-day-4-968e9053195d?source=rss-3ca8323a41d6------2</link>
            <guid isPermaLink="false">https://medium.com/p/968e9053195d</guid>
            <category><![CDATA[vertex-ai]]></category>
            <category><![CDATA[language-model]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[TensorFlow User Group Islamabad]]></dc:creator>
            <pubDate>Sun, 28 Jul 2024 07:06:34 GMT</pubDate>
            <atom:updated>2024-07-28T07:06:34.050Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*blze4_tNHGGd7c4a75aRdA.jpeg" /></figure><p>PaliGemma is a lightweight, open-source vision-language model (VLM) developed by Google. It is designed to handle both images and text inputs, making it capable of performing tasks that require working with visual and textual data together.</p><p>PaliGemma can identify and outline objects within images and also perform <a href="https://aws.amazon.com/what-is/ocr/">optical character recognition</a> (OCR) to read text embedded in images. Accessible through platforms like Kaggle, Colab, and HuggingFace.</p><h3>Paligemma In Action</h3><blockquote><a href="https://cdn-lfs.huggingface.co/datasets/huggingface/documentation-images/cfb8391cbb6738cfa5d875d2adcc4cd5971f6266ef71835ffa27d3f4c0f09d7d?response-content-disposition=inline%3B+filename*%3DUTF-8%27%27paligemma.mp4%3B+filename%3D%22paligemma.mp4%22%3B&amp;response-content-type=video%2Fmp4&amp;Expires=1722408709&amp;Policy=eyJTdGF0ZW1lbnQiOlt7IkNvbmRpdGlvbiI6eyJEYXRlTGVzc1RoYW4iOnsiQVdTOkVwb2NoVGltZSI6MTcyMjQwODcwOX19LCJSZXNvdXJjZSI6Imh0dHBzOi8vY2RuLWxmcy5odWdnaW5nZmFjZS5jby9kYXRhc2V0cy9odWdnaW5nZmFjZS9kb2N1bWVudGF0aW9uLWltYWdlcy9jZmI4MzkxY2JiNjczOGNmYTVkODc1ZDJhZGNjNGNkNTk3MWY2MjY2ZWY3MTgzNWZmYTI3ZDNmNGMwZjA5ZDdkP3Jlc3BvbnNlLWNvbnRlbnQtZGlzcG9zaXRpb249KiZyZXNwb25zZS1jb250ZW50LXR5cGU9KiJ9XX0_&amp;Signature=k1U-E-Q%7EPjuY6%7EEC0A6v%7EP9gl5Ujtcagn1P%7EqIxVw5-GNAtEM-1jn83td8A0JvWJu23HEOur8lE%7ETNmlfZ1BAVbIMBIHt80zJU0-BKDcd4osYh4gEWCroZmlXCV5CGoeJKUDRJrtYt98PfSG4lmKM0KvL3T3H3jofNteRA0dA4a4AnvCqULaFuaf5XGAYV3%7EKcyZhjgp3PCLKuYfbtNWfKoxvUM10Q2lDAb8XZVYste-QYAVHq0lwihTlfQRJEgfC3McBNBBbPBJUlM-L841k0af1QU1YltLjCUvD84pj89esI%7E7aXHFlhTk1CAvfQsYXNyVNa4Ms67za5LSpmmSHw__&amp;Key-Pair-Id=K3ESJI6DHPFC7">Watch 1 Min Video</a></blockquote><h3>Understanding The Architecture</h3><h4>1. Vision and Language Models Integration</h4><ul><li><strong>Vision Model (Encoder)</strong>: PaliGemma incorporates the vision model from the <a href="https://huggingface.co/docs/transformers/en/model_doc/siglip">SigLIP</a> (Sign Language and Image Processing) framework, which is designed to process and understand images. This model is responsible for extracting visual features from input images.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lmG2G62_i2TgvbI7KlKt9g.png" /><figcaption><strong>Architecture Model</strong></figcaption></figure><ul><li><strong>Language Model (Decoder)</strong>: The language processing component is based on the Gemma language model. This part handles text inputs and outputs, generating textual descriptions or responses based on the visual features provided by the vision model.</li></ul><h4>2. Transformer Architecture</h4><p>Both the vision and language models use transformer architectures. Transformers are well-known for their attention mechanisms, which allow them to weigh the importance of different parts of the input data.</p><h4>3. Types</h4><p>• <strong>Pretrained Models</strong>: PaliGemma models are pretrained on large datasets to learn general representations of both visual and textual data. This pretraining helps the models generalize well across various tasks and datasets.</p><p>• <strong>Fine-tuning</strong>: After pretraining, the models can be fine-tuned on specific tasks or datasets to enhance performance on particular applications. This process adjusts the pretrained weights to better suit the nuances of the target task.</p><h4>4. Multimodal Fusion</h4><p>One of the critical aspects of PaliGemma is how it combines features from both images and text. The model effectively merges these features to understand the relationships between visual elements and their textual descriptions or queries. This fusion allows the model to perform tasks like image captioning, visual question answering (VQA), and object detection with textual context.</p><h4>5. High-Performance Computing</h4><p>PaliGemma uses high-performance computing techniques, including mixed precision training (using data types like bfloat16) and efficient parallel processing on GPUs.</p><h3>Pretraining in PaliGemma</h3><p>For PaliGemma, pretraining involves learning from large-scale image-text datasets. The model is trained to understand the relationship between images and their textual descriptions, learning to generate coherent text based on visual inputs. This involves:</p><ul><li><strong>Self-Supervised Learning</strong>: The model might be trained to predict masked parts of an image or caption.</li><li><strong>Multimodal Objectives</strong>: Learning objectives that require understanding both visual and textual data simultaneously.</li></ul><h3>How Do I Get It Running?</h3><p>Visit: <a href="https://huggingface.co/google/paligemma-3b-mix-224"><em>HuggingFace-Link</em></a></p><h3>Why use Paligemma?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n37fMAOW88EUhYDLLsjxrw.png" /></figure><h4>Scaling to Billions</h4><p>PaliGemma can handle massive datasets, enabling it to learn from a diverse range of inputs. Utilizing advanced hardware like TPUs (Tensor Processing Units) and distributed training techniques, PaliGemma can scale efficiently, processing large volumes of data in parallel.</p><h4>Generalist Architecture</h4><p>PaliGemma integrates both vision and language models, making it a versatile tool for a wide range of applications, from image captioning to visual question answering. The generalist architecture facilitates transfer learning, where knowledge gained from one task can be applied to another.</p><h4>Autoregressive Models Working on Images</h4><p>Autoregressive models generate data one step at a time, which can be particularly beneficial for image generation tasks. This approach allows for more coherent and contextually relevant outputs.</p><p>Applying autoregressive techniques to images enables tasks like image completion, where parts of an image can be generated based on existing pixels, or even generating entirely new images from text prompts.</p><h3>Resources:</h3><blockquote><strong><em>Code:</em></strong><em> </em><a href="https://www.kaggle.com/models/google/paligemma">Kaggle</a> | <a href="https://ai.google.dev/gemma/docs/paligemma/fine-tuning-paligemma">Colab</a></blockquote><blockquote><strong><em>Google Gemma Models:</em></strong><em> </em><a href="https://ai.google.dev/gemma/docs">Google AI for Developers</a></blockquote><blockquote><strong><em>View Blog:</em></strong><em> </em><a href="https://blog.ritwikraha.dev/understanding-paligemma-in-50-minutes-or-less#heading-datasets">RitwikRaha-Blog</a></blockquote><blockquote><strong><em>For More Details:</em></strong><em> </em><a href="https://huggingface.co/blog/paligemma">HuggingFace-Blog</a></blockquote><h3>About Us</h3><p><a href="https://www.linkedin.com/company/tfugislamabad/">TFUG Islamabad</a> is the premier community for TensorFlow enthusiasts. Our group is dedicated to bringing together professionals, researchers, and enthusiasts from diverse backgrounds who share a common interest in AI.</p><h3>References:</h3><blockquote><em>🎙️ Featured Speaker: </em><a href="https://www.youtube.com/redirect?event=video_description&amp;redir_token=QUFFLUhqbWh4b3Z2bEF3WkhScktSZXA4OTNGZ2x4V3ZVd3xBQ3Jtc0ttMktIM2hJdW5HLUdpbDRuUEQ4UmFaSFNvTFlOVWU1U2NfaFVPQUFWdTZXZFlKcWR6T1RxaWY1NVN3aW1HR3c3SnV2UktROHZTZjJEZ1diOGhlbFZjT0k1Q3hnRDVfYl9aR0JOdk5qeXJoUkVmQUxxRQ&amp;q=https%3A%2F%2Fwww.linkedin.com%2Fin%2Fritwik-raha&amp;v=igI4sJITq7Y"><strong>Ritwik Raha</strong></a></blockquote><blockquote><em>📽️ Video Link: </em><a href="https://youtu.be/igI4sJITq7Y"><strong>Watch the session here</strong></a></blockquote><h3>Written By:</h3><p><a href="https://www.linkedin.com/in/muhammad-ali-2480a0255/">Muhammad Ali</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=968e9053195d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering LLM Chatbot Development with Google’s Gemma | ML Study Jams Day 3]]></title>
            <link>https://medium.com/@tfugislamabad/mastering-llm-chatbot-development-with-googles-gemma-ml-study-jams-day-3-294430fd1b69?source=rss-3ca8323a41d6------2</link>
            <guid isPermaLink="false">https://medium.com/p/294430fd1b69</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[transformers]]></category>
            <dc:creator><![CDATA[TensorFlow User Group Islamabad]]></dc:creator>
            <pubDate>Mon, 15 Jul 2024 12:03:56 GMT</pubDate>
            <atom:updated>2024-07-18T09:00:10.531Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ays_MYVj1zmKhM-FS-GOvQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*gzy0GR_u6LYGB4yEQp1NHw.png" /></figure><h3>So What’re LLMs?</h3><p><strong>Large Language Models <em>(or LLMs)</em></strong> are advanced AI systems designed to understand, generate, and manipulate human language. They are trained on vast amounts of text data and can perform a variety of tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*HVYGuCUGt1DfssSzKPd6DQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/981/1*pNIRH3azjOHfzx-nHeSB0w.png" /></figure><h3>Relation with Transformers</h3><p><strong>Transformers</strong> are a type of neural network architecture that has revolutionized the field of Natural Language Processing (NLP) and are the foundation upon which LLMs are built. The key components of transformers include:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*pfgr-j6Otdcxrx5b-6l21g.png" /><figcaption><strong>Transformer Architecture</strong></figcaption></figure><ul><li><strong>Self-attention mechanisms</strong>: Allow the model to weigh the importance of different words in a sentence when processing each word. This helps in understanding context and relationships between words.</li><li><strong>Positional encodings</strong>: Since transformers do not inherently understand the order of words, <a href="https://www.geeksforgeeks.org/positional-encoding-in-transformers/">positional encodings</a> are added to input embeddings to give the model a sense of word order.</li><li><strong>Encoder-decoder architecture</strong>: In tasks like translation, the encoder processes the input text and the decoder generates the output text. However, many modern LLMs use a simplified architecture, focusing on either the encoder <em>(e.g., BERT)</em> or the decoder <em>(e.g., GPT)</em> part.</li></ul><p>Examples of LLMs Using Transformers: GPT-3, BERT, RoBERTa ,T5 (Text-to-Text Transfer Transformer) etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JQfEQJvKX4wUbyxXS_kutQ.png" /><figcaption><strong>Overview Of Transformers Working</strong></figcaption></figure><blockquote><strong>Short Video</strong>: <a href="https://www.youtube.com/watch?v=ZXiruGOCn9s">IBMTechnology</a></blockquote><h4>Encoder</h4><p>In a transformer architecture, the encoder is responsible for processing the input sequence of tokens <em>(words or sub-word units)</em> to create contextualized representations.</p><p><strong>1) Input Embeddings</strong>:</p><ul><li>Each token (word) is transformed into a vector representation (embedding). Think of these embeddings as compact codes that capture the meaning of each word.</li><li>We also add positional information to these embeddings. Imagine it’s like labeling each puzzle piece with its position in the sentence.</li></ul><p><strong>2) Multi-Head Self-Attention Mechanism</strong>:</p><ul><li>Picture a team discussion where each team member (token) talks to others. They decide how much attention they should pay to different team members.</li><li>The model computes attention scores based on how similar tokens are to each other. These scores guide the model’s focus.</li></ul><p><strong>3) Normalization and Residual Connections</strong>:</p><ul><li>Normalization stabilizes the learning process. It’s like adjusting the thermostat to keep the room comfortable.</li><li>Residual connections act as bridges between layers. They help gradients flow smoothly during training, like well-connected roads.</li></ul><p><strong>4) Position-wise Feed-Forward Networks</strong>:</p><ul><li>Imagine a personal improvement workshop for each token. These networks learn non-linear patterns and interactions. It’s like sharpening the edges of each puzzle piece to fit better.</li></ul><p><strong>5) Layer Stacking</strong>:</p><ul><li>Transformers stack multiple identical layers. Each layer adds complexity, like building a taller tower of puzzle pieces.</li><li>More layers allow the model to capture intricate patterns in the input sequence.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*7dlFPt_y0EvaChj5NP3dzA.png" /></figure><h4>Working of the Encoder</h4><ul><li><strong>Initialization</strong>: Each token’s embedding is initialized, and positional encodings are added.</li><li><strong>Self-Attention</strong>: Scores are calculated for each word in the sequence by considering all words.</li><li><strong>Feed-Forward Network</strong>: The attention output for each word is processed through a position-wise feed-forward network.</li><li><strong>Normalization and Residual Connection</strong>: After each sub-layer, layer <a href="https://paperswithcode.com/method/layer-normalization">normalization</a> is applied and residual connections help with effective gradient flow.</li><li><strong>Layer Stacking</strong>: This process is repeated across multiple layers, refining word representations based on learned patterns.</li></ul><h3>Prompt Design &amp; Engineering</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*QqM-QTNMV1QSBfgNOdrVsg.png" /></figure><h3>Effective Prompting Techniques</h3><p><strong>Zero Shot Learning: </strong>The model makes predictions on tasks it has never seen before. For example, asking someone to write a poem about birds without any prior examples.</p><p><strong>Few Shot Learning: </strong>The model is trained with a very small amount of data. For example, converting Python code to JavaScript with just a few examples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*5cQJ-K8PqVAPsO1igIQEnw.png" /></figure><h3>Types Of LLMs</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*4atXLm6qPJmIzXYtDIkbQQ.png" /></figure><p><strong>1) Generic Language Models</strong>: are versatile models trained on diverse data for general NLP tasks. Predict the next word based on the training data. For example, completing sentences in a text.</p><p><strong>2) Instruction Tuned Models</strong>: are specialized for tasks involving specific instructions or structured outputs. Predict responses based on given instructions. For example, answering questions or following specific commands.</p><p><strong>3) Dialog Tuned Models</strong>: excel in conversational contexts, maintaining context and coherence across dialogue interactions. Engage in conversations by predicting the next response. For example, chatbots that can hold a conversation.</p><h3><strong>Generic Large Language Models</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*zZGaeTbkzGcj0S_5mb09dA.png" /></figure><p><strong>Generic Large Language Models</strong> are designed to understand and generate text across a wide range of tasks and domains without specific fine-tuning for any particular task. Such models are typically pre-trained on vast amounts of text data from diverse sources <em>(e.g., books, articles, websites)</em> using self-supervised learning techniques. <strong>Example</strong>: GPT-3</p><h3>Instruction Tuned LLMs</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*OmVdvjylQwbMBRTqWitDcg.png" /></figure><p><strong>Instruction Tuned LLMs</strong> are LLMs that have been fine-tuned or adapted for specific tasks or instructions. Unlike generic models, these are trained with additional supervision or specific training data to perform well on particular types of instructions or structured tasks. <strong>Example</strong>: Codex by OpenAI <em>(based on GPT-3)</em></p><h3>Dialog Tuned LLMs</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/983/1*p8vrfSTX41Vq0dBF-p0bRg.png" /></figure><p><strong>Dialog Tuned Large Language Models</strong> are LLMs tailored to excel in conversational contexts and dialogue-based interactions. These models are trained or fine-tuned with datasets containing conversational data, which could include customer service chats, virtual assistant interactions, or social media dialogues. <strong>Example</strong>: Meena by Google</p><h4>Building A Gamma Chatbot</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*ejt8q31tBqQPcWtLm8eSiQ.png" /><figcaption><strong>Basic Code</strong></figcaption></figure><h4>Result:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u9cOcHY-m5FhMMLEnq2unA.png" /></figure><h3>Resources:</h3><blockquote>💻<strong> Code: </strong><a href="https://github.com/XFarooqi/gemma_chatbot/blob/main/Gemma_App.ipynb">Github Repository</a></blockquote><blockquote>📚 <strong>Short Course:</strong> <a href="https://www.deeplearning.ai/short-courses/langchain-for-llm-application-development/">DeepLearning.Ai</a></blockquote><blockquote>👨‍🏫 <strong>Andrej Karpathy Intro to LLMs: </strong><a href="https://www.youtube.com/watch?v=zjkBMFhNj_g">Youtube-Link</a></blockquote><blockquote>📝 <strong>Research paper:</strong> <a href="https://arxiv.org/abs/1706.03762">Attention Is All You Need</a> <strong>(Highly Recommended)</strong></blockquote><h3>About Us</h3><p><a href="https://www.linkedin.com/company/tfugislamabad/">TFUG Islamabad</a> is the premier community for TensorFlow enthusiasts. Our group is dedicated to bringing together professionals, researchers, and enthusiasts from diverse backgrounds who share a common interest in AI.</p><h3>References:</h3><blockquote><em>🎙️ Featured Speaker: </em><a href="https://www.linkedin.com/in/xfarooqi/"><strong><em>Abdul Raheem</em></strong></a></blockquote><blockquote><em>📽️ Video Link: </em><a href="https://youtu.be/ALQJ72GGJIo"><strong><em>Watch the session here</em></strong></a></blockquote><h3>Written By:</h3><p><a href="https://www.linkedin.com/in/muhammad-ali-2480a0255/">Muhammad Ali</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=294430fd1b69" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced Applications: Deep Learning, NLP, & TF in Action | ML Study Jams Day 2]]></title>
            <link>https://medium.com/@tfugislamabad/advanced-applications-deep-learning-nlp-tf-in-action-ml-study-jams-day-2-7be5dac9b0b7?source=rss-3ca8323a41d6------2</link>
            <guid isPermaLink="false">https://medium.com/p/7be5dac9b0b7</guid>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[artificial-neural-network]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[language-model]]></category>
            <dc:creator><![CDATA[TensorFlow User Group Islamabad]]></dc:creator>
            <pubDate>Sun, 02 Jun 2024 19:27:58 GMT</pubDate>
            <atom:updated>2024-06-03T05:53:29.942Z</atom:updated>
            <content:encoded><![CDATA[<h3>How Neural Networks Learn?</h3><p>Let’s imagine teaching a group how to spot a koala. Some people looked at things like the koala’s eyes, nose, and body parts to decide if a picture showed a koala or not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ud_NqBYoZmSth8s-9BOusA.png" /></figure><p><strong>Input Layer:</strong> The starting layer has pictures named ‘Mike’, ‘Josh’, and ‘Arthur’ with values of 0.8, 0.9, and 0.6. These values might show Koala-like characteristics.</p><p><strong>Weights and Features</strong>: In the hidden layer, a unit called ‘Serena’ uses weights for eyes, nose, and ears to process inputs and identify a Koala. Each feature’s weight (0.2 for eyes, 0.5 for nose, and 0.33 for ears) shows how important it is in the identification process.</p><p><strong>Output Calculation</strong>: The output is calculated using the formula:</p><ul><li><strong><em>face</em></strong><em> = eyes </em><strong>x</strong> <em>Mike </em><strong><em>+</em></strong><em> nose </em><strong>x</strong><em> Josh </em><strong><em>+</em></strong><em> ears </em><strong>x</strong> <em>Arthur</em></li></ul><p>which simplifies to</p><ul><li><strong><em>face</em></strong><em> = 0.8 </em>x <em>0.2 </em><strong><em>+</em></strong><em> 0.9 </em>x<em> 0.5 </em><strong><em>+</em></strong><em> 0.6 </em>x <em>0.33 = 0.79</em></li></ul><p>This value (0.79) represents how much ‘Serena’ thinks the inputs look like a koala’s face. This is akin to how layers in a neural network work together to make predictions i.e. combining individual features learned and then making a predictions.</p><p><strong>Learning Process</strong>: In a real neural network, the weights are adjusted during training to minimize the error between the predicted output and the actual label. This process, often done through backpropagation, allows the network to learn and improve its accuracy over time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1uzSxUQzUzZ36S-ccjZLeA.png" /></figure><h3><strong>But What is Backpropagation?</strong></h3><p>Okay so think about building a sandcastle. You start by making a big pile of sand. Then, you shape it to look like a castle. But when you step back and look at it, you notice that one tower is too small and the walls aren’t straight.</p><p>Backpropagation is like looking at your sandcastle and seeing what parts need fixing. Then, you go back and add more sand to the small tower and straighten the walls.</p><p>Backpropagation in a NN is similar. Here’s how it goes:</p><ol><li><strong>Forward Pass</strong>: Input data is passed through the network layer by layer, and each neuron processes it using its weights and biases to produce an output.</li><li><strong>Compute Loss</strong>: The network’s final output is compared to the actual target to compute the error (or loss). This loss measures how far off the prediction is.</li><li><strong>Backward Pass</strong>:</li></ol><ul><li><strong>Compute Gradients</strong>: The network calculates the gradient (slope) of the loss with respect to each weight by using the chain rule of calculus. This tells us how much a small change in each weight will change the loss.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BW3K3ey2qG3p7uM0_OdllQ.png" /><figcaption>Via <a href="https://www.geeksforgeeks.org/backpropagation-in-neural-network/">GeeksForGeeks</a></figcaption></figure><ul><li><strong>Update Weights</strong>: The weights are adjusted in the opposite direction of the gradient to minimize the loss. This is usually done using an optimization algorithm like gradient descent.</li></ul><blockquote>To better Understand Backpropagation here’s an <a href="https://www.youtube.com/watch?v=Ilg3gGewQ5U">amazing resource</a>.</blockquote><p>With basic understanding of Neural Networks in place lets head to Language.</p><h3><strong>Language Generation in LLMs</strong></h3><p>The process of predicting the next word by a Language Model (LLM) is like filling in a sentence blank, using clues from the words before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X0LrUSjC5TQDfHjgiKETBA.png" /><figcaption>Source : <a href="https://livebook.manning.com/book/build-a-large-language-model-from-scratch/chapter-2/v-2"><em>Build a Large Language Model (From Scratch)</em></a></figcaption></figure><ol><li><strong>Context Gathering</strong>: Just like gathering clues from a sentence, an LLM starts by analyzing the words it has seen so far.</li><li><strong>Prediction</strong>: Based on this context, the LLM predicts the next word, similar to guessing what word would logically fill in the blank.</li><li><strong>Sequential Processing</strong>: The LLM processes words one at a time, moving from left to right, much like reading a sentence to understand it fully before making a guess.</li><li><strong>No Peeking Ahead</strong>: An LLM cannot look into the future; it does not know what’s coming next, similar to not cheating by seeing the answers while filling in the blanks.</li></ol><h3>A Glimpse Of Sentiment Analysis</h3><p>Consider a scenario where different text statements are analyzed for sentiment, emotion, and hate speech. <a href="https://towardsdatascience.com/sentiment-analysis-concept-analysis-and-applications-6c94d6f58c17"><strong>Sentiment analysis</strong></a> is a part of natural language processing (NLP) that involves identifying and categorizing opinions expressed in text; it helps to figure out if the writer’s opinion<em> (on a topic, product, etc.) </em>is positive, negative or neutral</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SPOy713_53ZJwvU309qxfQ.png" /></figure><p><strong>Sentiment Classification</strong>: The first statement discusses the ambiance and food quality of a place, noting it becomes problematic when crowded. The task is to determine the overall sentiment of the statement.</p><p><strong>Emotion Classification</strong>: The second statement shows shock at someone’s lack of responsibility. Can you figure out the feeling being expressed?</p><p><strong>Hate Speech Detection</strong>: The third statement discusses smaller ethnic groups in Pakistan and makes a disrespectful suggestion that they should have their own land. Does this constitute hate speech?</p><h3>Word Embeddings</h3><p>Word embeddings are a type of representation for words that help machines comprehend and work with human language by converting words into numerical vectors. Each word is depicted as a point in a multi-dimensional space. <strong>Similar words have similar vectors.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*l6mcj4rdzBx7bbiz.png" /><figcaption><a href="https://www.nlplanet.org/course-practical-nlp/01-intro-to-nlp/11-text-as-vectors-embeddings">More Info</a></figcaption></figure><h3>Why Do We Need Word Embeddings?</h3><h4><strong>1. </strong>Semantic Similarity</h4><p>In language, words can have relationships to each other. For example, “king” is to “queen” as “man” is to “woman”. Traditional methods of representing words (like one-hot encoding) don’t capture these relationships well.</p><blockquote>Learn about one-hot encoding <a href="https://medium.com/@michaeldelsole/what-is-one-hot-encoding-and-how-to-do-it-f0ae272f1179">here</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*Md94dlh3DhRp2eahjVNsdw.png" /></figure><h4><strong>2. </strong>Efficiency (<strong>Reducing Dimensionality)</strong></h4><p>One-hot encoding creates large and sparse vectors (mostly zeros) for each word, which isn’t efficient. Word embeddings create dense and smaller vectors that are more manageable and easier to make computations on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Hl7VjV0mEGAQh-pR" /><figcaption>One Hot Encoding in action (<a href="https://medium.com/@michaeldelsole/what-is-one-hot-encoding-and-how-to-do-it-f0ae272f1179">Source</a>)</figcaption></figure><h3>Tensorflow And Tensors: Hands-On Code</h3><h4>What is a Tensor?</h4><p>A tensor is a generalization of scalars, vectors, and matrices. Essentially, it is a multi-dimensional array of numbers that can be used to represent data in various dimensions.</p><h3>Types of Tensors</h3><ol><li><strong>Scalar (0-Dimensional or 0-D Tensor)</strong>: A single number. For example, 5 or 3.14.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*toqwnEhQnlIpU0RzXZ8Iug.png" /><figcaption>Python Code To Make A <strong>Scaler</strong></figcaption></figure><p>2. <strong>Vector (1-D Tensor)</strong>: A list of numbers, which can be thought of as a line of values. Example: vector =[1,2,3]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*8JkVkN_XlML7MdJ-a3XJyg.png" /><figcaption>Python Code To Make A <strong>Vector</strong></figcaption></figure><p><strong>3. Matrix (2-D Tensor)</strong>: A table of numbers with rows and columns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*qBphbKwEi_i7pdeYrXCVrw.png" /><figcaption>Python Code To Make A <strong>Matrix</strong></figcaption></figure><p><strong>4. 3-D Tensor</strong>: An array of matrices. Think of it as a cube of numbers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*6Kh7Zt0Up4-8HaGuS80ZMg.png" /><figcaption>Python Code To Make A <strong>3D Tensor</strong></figcaption></figure><p><strong>5. Higher-Dimensional Tensors</strong>: Tensors can extend to more dimensions, such as 4-D, 5-D and so on.</p><blockquote>Resource: <a href="https://www.youtube.com/watch?v=f5liqUk0ZTw">Understand Tensors Better</a></blockquote><h4>Performing Math On Tensors</h4><p>We can perform mathematical operations on our tensors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/1*Vq5Wm9A7xEdWa5jRGKi05A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*4mqg1Mwfo2rSTml51Otm0Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4l4tqw-__kkPCCy52N4Nqw.png" /><figcaption>Performing Basic Statistical Analysis</figcaption></figure><h4>Building A Very Basic Neural Network</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/1*agJzR1Sskj6Aawitj4U4gg.png" /><figcaption>TensorFlow Code</figcaption></figure><h3>Resources:</h3><blockquote>YouTube Channels: <a href="https://www.youtube.com/3blue1brown"><strong>3blue1brown</strong></a><strong>, </strong><a href="https://www.youtube.com/@codebasics"><strong>Codebasics</strong></a></blockquote><blockquote>TensorFlow Course: <a href="https://www.youtube.com/watch?v=tPYj3fFJGjk"><strong>FreeCodeCamp</strong></a></blockquote><blockquote>NLP Short Course For Beginners: <a href="https://www.youtube.com/watch?v=dIUTsFT2MeQ"><strong>FreeCodeCamp</strong></a></blockquote><h3>References:</h3><blockquote><em>🎙️ Featured Speaker: </em><a href="https://www.linkedin.com/in/maazalinadeem/">Maaz Ali</a></blockquote><blockquote><em>📽️ Video Link: </em><a href="https://youtu.be/7UJTQqHlUeU">Watch the session here</a></blockquote><h3>Written By:</h3><p>📝 <strong>Muhammad Ali</strong></p><h3>About Us</h3><p><a href="https://www.linkedin.com/company/tfugislamabad/">TFUG Islamabad</a> stands as the leading community for those passionate about TensorFlow. We are committed to uniting professionals, researchers, and enthusiasts from various backgrounds who have a shared interest in the field of AI.</p><p>Join us for a variety of carefully planned events, workshops, and seminars where we’ll cover the latest TensorFlow technology, share best practices, and explore practical applications. Connect with experts, grow your network, and discover exciting opportunities in the ever-evolving world of TensorFlow and AI.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7be5dac9b0b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Next-Level Tech: ML, TensorFlow, Computer Vision, & Gen AI | ML Study Jams Day 1]]></title>
            <link>https://medium.com/@tfugislamabad/machine-learning-demystified-building-blocks-and-beyond-1f769dcc8576?source=rss-3ca8323a41d6------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f769dcc8576</guid>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[TensorFlow User Group Islamabad]]></dc:creator>
            <pubDate>Mon, 27 May 2024 15:40:52 GMT</pubDate>
            <atom:updated>2024-05-30T10:36:24.875Z</atom:updated>
            <content:encoded><![CDATA[<p>This article gives an overview of the world of Machine Learning, focusing on the practical aspects of building models with TensorFlow and exploring the potential of Google AI Platform.</p><p>Foremost, what is Machine Learning?</p><h3><strong>Understanding the ML Lingo</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*UaK1CpAnh52DALAd0VDmig.png" /></figure><p>Lets discuss Supervised Machine Learning, as it represents <strong>over ninety percent</strong> of all real-world machine learning cases in production today. The two most common approaches include classification and regression.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vaq9EW34Vm2yjMOt8ePnrw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EhZ-8ACDd2GYoDk7nrMekg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pFPsaSgsLuuFee_9lDMhhw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*OWwj-gtw32wnv3cyNGcUJQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zLfwL3X7WJmHbM4IEN_UwA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kfs51_Cg-IP_ydfC1kKDgg.png" /></figure><p>Unlike Supervised Learning,<strong> Unsupervised Learning</strong> models are given <a href="https://labelyourdata.com/articles/introduction-to-labeled-data-what-why-and-how">unlabeled data</a> and allowed to discover patterns and insights without any explicit guidance or instruction of a human.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NJrVYhvL5bZX1T97KrqGDA.png" /></figure><h3>Deep Learning</h3><p>Deep learning is the subset of machine learning methods based on neural networks with <a href="https://paperswithcode.com/task/representation-learning">representation learning</a>. The adjective “deep” refers to the use of multiple layers in the network. Methods used can be either supervised, semi-supervised or unsupervised.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*G5E2oKyqQa2dBIDZNG6lPg.png" /></figure><h3>Neural Networks</h3><p>A Neural Network (NN) is a machine learning model that is designed to simulate the way the human brain works, making decisions in a manner similar to the human brain</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HhFPc7tVMO3Mh0inPvAe8g.png" /></figure><p>NN consists of layers of nodes, or artificial neurons — an input layer, one or more hidden layers, and an output layer. Each node connects to others, and has its own associated weight and threshold.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*07iPZ9G1-Vk4w5dnhIElzQ.png" /></figure><p><strong>Input Layer:</strong> This is where the network takes in data for processing. Each input node represents a different feature of the data</p><p><strong>Weights and Bias:</strong> These are parameters within the network that transform the input data as it passes through the network. <em>Mathematically,</em></p><p><strong>z = wx + b</strong></p><p><em>where w is the weight, x is the input and b is the bias term.</em></p><p><strong>Activation Function:</strong> This function determines whether a neuron should be activated or not, based on the weighted sum of the inputs and the bias. <em>Mathematically,</em></p><p><strong>a = g(z)</strong></p><p><em>where g() is the activation function that takes z as its input. And a is the output of that specific neuron. This output is inturn taken as input by corresponding neuron of the next layer.</em></p><blockquote><a href="https://www.ml-science.com/activation-functions#:~:text=Activation%20Function%20Generalized%20Equation,sum%20and%20produces%20an%20output.">Resource for exploring activation functions in detail</a></blockquote><p><strong>Hidden Layers:</strong> These layers perform computations and transfer information from the input nodes to the output nodes1.</p><p><strong>Output Layer:</strong> The final layer of the network produces the result for given inputs</p><h3><strong>TensorFlow</strong></h3><figure><img alt="https://www.tensorflow.org/" src="https://cdn-images-1.medium.com/max/1024/1*cM6wfPdVaiwwov3JNWUrYA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CI4fxvmfEtoJunlfd1Hwgg.png" /></figure><blockquote><strong>Example Use of TensorFlow:</strong> Classifying Handwritten digits</blockquote><p>Imagine building a program that can decipher handwritten digits! Lets dive into the process of creating a real ML model using TensorFlow. You’ll learn the essential steps involved in model building:</p><p><strong>1) Data Wrangling: </strong>Here, you’ll see how data is loaded, strategically divided into training and testing sets, and prepped for the model to understand it better.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WVInyYW91kLp6ps97FTpLQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*rZJwaotzGE5u4Uke7aMo3g.png" /><figcaption>Output</figcaption></figure><p><strong>2) Model Blueprints:</strong> The concept of defining the model’s architecture with layers is now introduced. Imagine these layers as building blocks that work together to achieve the desired outcome.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HqmsvvJM5c6594n5vr6kPQ.png" /></figure><p><strong>3) Training the Machine:</strong> Witnessing the model being trained with epochs helps us grasp how the model learns and improves based on the data it’s fed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jLxHkTyscxvkgDKjmZg9Ew.png" /></figure><p><strong>4) Evaluating the Detective’s Skills:</strong> We discover how the model’s performance is evaluated to gauge its accuracy in making predictions. Can it correctly identify all the handwritten digits?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*u9Uo22bFcqCVFFtQMg6YBQ.png" /></figure><blockquote><a href="https://github.com/NSTiwari/ML-TFUG-Islamabad/blob/main/MNIST_Image_Classification.ipynb">GitHub Repo for complete Jupyter Notebook</a></blockquote><h3><strong>Google Gemini Model</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5jK1QnNvTIR5tkXhXHrNnw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f6hgvnQlzQxX_lEYIewibw.png" /></figure><blockquote><strong>Hands On With Gemini 1.0 Pro: Colab</strong></blockquote><p><strong>Step 1:</strong> Go to <a href="https://aistudio.google.com/">Google AI Studio</a> and generate an API Key by clicking on the top left.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eSsIAS2Cad-WYHwk9iQS9g.png" /></figure><p><strong>Step 2:</strong> Clone the repository: <a href="https://github.com/NSTiwari/ML-TFUG-Islamabad">https://github.com/NSTiwari/ML-TFUG-Islamabad</a></p><p><strong>Step 3:</strong> Upload the notebook file on Google Collab</p><p><strong>Step 4:</strong> Execute the cells in the notebook by following the instructions</p><h3>Resources:</h3><blockquote><strong>Google AI Studio:</strong> <a href="https://aistudio.google.com/">https://aistudio.google.com</a></blockquote><blockquote><strong>Get Started with examples on</strong> <a href="https://ai.google.dev/examples">https://ai.google.dev/examples</a></blockquote><blockquote><strong>Google AI SDK for Javascript:</strong> <a href="https://github.com/google/generative-ai-js">https://github.com/google/generative-ai-js</a></blockquote><blockquote><strong>Getting started with Gemini Nano (on-device):</strong> <a href="https://ai.google.dev/tutorials/android_aicore?hl=en">https://ai.google.dev/tutorials/android_aicore?hl=en</a></blockquote><blockquote><strong>Gemini API: Quickstart with Python:</strong> <a href="https://ai.google.dev/tutorials/python_quickstart?hl=en">https://ai.google.dev/tutorials/python_quickstart?hl=en</a></blockquote><blockquote><strong>Android SDK for Gemini API:</strong> <a href="https://ai.google.dev/tutorials/android">https://ai.google.dev/tutorials/android</a> quickstart?hl=en</blockquote><blockquote><strong>Gemini on Google Cloud Platform:</strong> <a href="https://github.com/GoogleCloud">https://github.com/GoogleCloud</a> Platform/generative-ai/</blockquote><h3>About Us</h3><p><a href="https://www.linkedin.com/company/tfugislamabad/">TFUG Islamabad</a> is the premier community for TensorFlow enthusiasts. Our group is dedicated to bringing together professionals, researchers, and enthusiasts from diverse backgrounds who share a common interest in AI.</p><p>Through a series of meticulously curated events, workshops, and seminars, we aim to facilitate in-depth discussions on cutting-edge TensorFlow technologies, best practices, and real-world applications. Join us to engage with industry experts, expand your professional network, and unlock new opportunities in the dynamic field of TensorFlow and AI.</p><h3>References:</h3><blockquote>🎙️ Featured Speaker: <a href="https://www.linkedin.com/in/tiwari-nitin"><strong>Nitin Tiwari</strong></a></blockquote><blockquote>📽️ Video Link: <a href="https://youtu.be/wv5oVrh86dk?si=YhPr6fRHHtVAY_7J"><strong>Watch the session here</strong></a></blockquote><h3>Written By:</h3><p><a href="https://www.linkedin.com/in/muhammad-ali-2480a0255/">Muhammad Ali</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f769dcc8576" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>