<?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 Ikram Hattab on Medium]]></title>
        <description><![CDATA[Stories by Ikram Hattab on Medium]]></description>
        <link>https://medium.com/@ikramelhattab90?source=rss-a1a5c9867fc7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*ETWbUbD4sWsKW7F2</url>
            <title>Stories by Ikram Hattab on Medium</title>
            <link>https://medium.com/@ikramelhattab90?source=rss-a1a5c9867fc7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 17:59:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ikramelhattab90/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[The Next Frontier in LLMs: Cache Augmented Generation (CAG)]]></title>
            <link>https://medium.com/@ikramelhattab90/the-next-frontier-in-llms-cache-augmented-generation-cag-825a9ecef165?source=rss-a1a5c9867fc7------2</link>
            <guid isPermaLink="false">https://medium.com/p/825a9ecef165</guid>
            <dc:creator><![CDATA[Ikram Hattab]]></dc:creator>
            <pubDate>Sat, 30 Aug 2025 22:48:20 GMT</pubDate>
            <atom:updated>2025-08-30T22:48:20.536Z</atom:updated>
            <content:encoded><![CDATA[<p>Many projects still rely on <strong>RAG</strong> (retrieval-augmented generation) for large language models (LLMs). Typically, a traditional <strong>RAG</strong> workflow looks like this:</p><ul><li>Embed the text into digital vectors.</li><li>Store these embeddings in a vector database.</li><li>Query the database to retrieve relevant “chunks” of information.</li><li>Add these chunks as context to the LLM.</li></ul><p>This technology has achieved some success, but often faces challenges in production environments:</p><ul><li><strong>Potential for Retrieval Errors:</strong> The system may retrieve irrelevant or incomplete information.</li><li><strong>High Costs:</strong> Frequent retrieval requires significant computing and input/output resources.</li><li><strong>Difficulty in Tuning Performance:</strong> Optimizing the entire RAG pipeline can be a complex and time-consuming process.</li></ul><p>Let’s explore a more advanced approach: cache-assisted generation (CAG), and why it is gaining momentum.</p><p><strong>The Foundation: KV Cache — The Model’s Internal Memory</strong></p><p>Before diving into <strong>CAG</strong>, it is necessary to understand <strong>KV caching</strong>. It is an internal memory mechanism that exists in every layer and every attention head in an LLM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*65iN6LBnqFv6kCrewLLzkQ.png" /></figure><ul><li>Stores <strong>keys</strong> and <strong>values</strong> for all tokens that have already been processed.</li><li>During the <strong>pre-filling</strong> phase, the initial context is processed once. After that, the model reuses this stored memory directly to generate subsequent tokens.</li><li>The result: faster generation, lower computational power usage, and often higher accuracy.</li></ul><p><strong>Introducing CAG (Cache Augmented Generation)</strong></p><p>CAG builds its strategy directly on the KV cache. Instead of rebuilding from scratch or performing a full retrieval for each query, CAG does the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ezFjQ-FlLiarIkTN5L1iEQ.png" /></figure><ul><li>It does not regenerate from scratch or perform a full retrieval for every query.</li><li>It stores important answers or previous inference steps and reuses them directly when requested.</li><li>This significantly reduces response time, cost, and hallucinations that can arise from inaccurate retrieval.</li></ul><p><strong>Why CAG is Superior to RAG</strong></p><p>Let’s analyze the main advantages of <strong>CAG</strong> compared to <strong>RAG</strong>:</p><h4>1. Speed</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ay-4L3xiXZ3r_FzkK3egPg.png" /></figure><ul><li><strong>RAG:</strong> Each query requires encoding, querying, and re-encoding — a time-consuming process for each interaction.</li><li><strong>CAG:</strong> One-time pre-filling, followed by direct creation from memory, resulting in significantly reduced response time, especially for subsequent queries.</li></ul><h4>2. Cost</h4><ul><li><strong>RAG: </strong>Incurs recurring costs for embedding and I/O operations with each query.</li><li><strong>CAG + KV Cache:</strong> Pays once for initial pre-filling, and subsequent generations are fast and inexpensive.</li></ul><h4>3. Context Quality</h4><ul><li><strong>RAG:</strong> It relies on segmentation and classification, which may result in incomplete or out-of-context information being retrieved.</li><li><strong>CAG + KV Cache:</strong> Keeps symbols in the correct order within the model memory, ensuring better understanding and fewer errors.</li></ul><h4>4. Personalization and State</h4><ul><li><strong>CAG</strong>’s “living memory” can store user preferences, previous steps in the conversation, and outputs from various tools. This enables more personalized and coherent interactions without losing previous information.</li></ul><h4>5. Privacy and Architectural Simplicity</h4><ul><li><strong>CAG</strong> eliminates the need for complex vector databases, reordering tools, or complicated synchronization mechanisms. This makes it ideal for local deployment and handling sensitive data, as it reduces the attack surface and simplifies the overall architecture.</li></ul><h4>6. Long-Context Handling</h4><ul><li>The latest generation of large language models (LLMs) can handle extremely long contexts. Caching becomes essential here. Techniques such as prefix caching, smart grouping, and page attention are used to reduce VRAM consumption, making the processing of long contexts more efficient.</li></ul><p><strong>Conclusion</strong></p><ul><li><strong>KV Cache:</strong> Internal memory of the model that reduces redundant calculations.</li><li><strong>CAG:</strong> A strategy that leverages <strong>KV cache</strong> to store and retrieve important answers and reasoning steps.</li><li><strong>The Result:</strong> faster production, lower costs, and superior accuracy and stability compared to traditional <strong>RAG</strong> methods.</li></ul><p>As large language models (LLMs) continue to evolve, approaches such as <strong>CAG</strong>, which intelligently leverage the latent capabilities of the model, will be critical for building effective, powerful, and scalable AI applications.</p><p><strong>#AI #LLMs #RAG #CAG #MachineLearning #DeepLearning #ArtificialIntelligence #Tech #Innovation #KVcache #GenerativeAI</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=825a9ecef165" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building and Training a Neural Network on MNIST with TensorFlow and Keras: A Step-by-Step Guide]]></title>
            <link>https://medium.com/@ikramelhattab90/building-and-training-a-neural-network-on-mnist-with-tensorflow-and-keras-a-step-by-step-guide-13a8582744a8?source=rss-a1a5c9867fc7------2</link>
            <guid isPermaLink="false">https://medium.com/p/13a8582744a8</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[tensorflow]]></category>
            <dc:creator><![CDATA[Ikram Hattab]]></dc:creator>
            <pubDate>Tue, 17 Dec 2024 13:54:56 GMT</pubDate>
            <atom:updated>2024-12-17T13:54:56.785Z</atom:updated>
            <content:encoded><![CDATA[<p>Neural networks are a cornerstone of modern AI, excelling in tasks like image classification, speech recognition, and more. In this guide, we’ll take a deep dive into building and training a simple neural network to classify handwritten digits from the MNIST dataset using TensorFlow and Keras. This dataset has been a benchmark in machine learning for decades and offers a perfect playground for experimenting with neural networks.</p><p>We will cover the following:</p><ol><li><strong>Loading and understanding the MNIST dataset</strong></li><li><strong>Visualizing the data</strong></li><li><strong>Building a neural network model with Keras</strong></li><li><strong>Training and evaluating the model</strong></li><li><strong>Making predictions and interpreting results</strong></li></ol><p>By the end of this guide, you’ll have a solid understanding of how to create, train, and evaluate neural networks for basic image classification tasks.</p><p>Let’s dive into the code!</p><h3>1. Importing Required Libraries</h3><pre>import tensorflow as tf<br>from keras.layers import Input,Dense,Flatten<br>from keras.models import Sequential<br>import matplotlib.pyplot as plt<br>from keras.datasets import mnist<br>import numpy as np</pre><p>We import the necessary libraries to build and train our neural network model.</p><ul><li>tensorflow is the core framework for creating machine learning models.</li><li>keras.layers provides various neural network layers like Input, Dense, and Flatten.</li><li>Sequential is used to create a simple linear stack of layers for our neural network.</li><li>matplotlib.pyplot is used for visualizing data and results, particularly in plotting images.</li><li>mnist is a built-in dataset from Keras, consisting of handwritten digits, used here for training and testing the model.</li><li>numpy helps with array manipulations, which is crucial for working with numerical data.</li></ul><h3>2. Loading the MNIST Dataset</h3><pre>pythonpy code(train_X, train_y), (test_X, test_y) = mnist.load_data()<br>#printing the shapes of the vectors<br>print(&#39;X_train: &#39; + str(train_X.shape))<br>print(&#39;Y_train: &#39; + str(train_y.shape))<br>print(&#39;X_test:  &#39;  + str(test_X.shape))<br>print(&#39;Y_test:  &#39;  + str(test_y.shape))</pre><pre>Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz<br>11490434/11490434 [==============================] - 0s 0us/step<br>X_train: (60000, 28, 28)<br>Y_train: (60000,)<br>X_test:  (10000, 28, 28)<br>Y_test:  (10000,)</pre><p>Loads the MNIST dataset and prints the shapes of the training and testing data.</p><ul><li>train_X and test_X contain the images (28x28 pixel grayscale images).</li><li>train_y and test_y contain the corresponding labels (the digit each image represents).<br>The shapes printed help us confirm the data dimensions before proceeding with model training.</li></ul><h3>3. Visualizing the First Few Digits</h3><pre>#Displaying the n first digits in the datset<br>for i in range(9):<br>  plt.subplot(330 + 1 + i) #rows col pos<br>  plt.imshow(train_X[i], cmap=plt.get_cmap(&#39;gray&#39;))<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/334/1*NjoOaaSibpYIOfbpM8l4Sw.png" /></figure><p>We visualize the first 9 images from the training dataset to get an overview of the data.</p><ul><li>plt.subplot is used to arrange the images in a 3x3 grid.</li><li>plt.imshow displays each image, using a grayscale colormap for clarity.</li></ul><h3>4. Building the Neural Network Model</h3><pre>model = Sequential(<br>    [   Input((28,28)), <br>        Flatten(),<br>        Dense(16, activation=&quot;relu&quot;, name=&quot;layer1&quot;),<br>        Dense(16, activation=&quot;relu&quot;, name=&quot;layer2&quot;),<br>        Dense(10, activation=&quot;softmax&quot;),<br>    ]<br>)</pre><p>Here, we define a simple neural network architecture using the Sequential model.</p><ul><li>Input((28,28)) represents the input layer where each image has a shape of 28x28 pixels.</li><li>Flatten() transforms the 2D input image into a 1D vector to feed into the fully connected layers.</li><li>The first two Dense(16) layers contain 16 neurons with ReLU activation, allowing the network to learn complex patterns.</li><li>The final Dense(10) layer uses a softmax activation to output a probability distribution over the 10 possible digits (0-9).</li></ul><h3>5. Compiling the Model</h3><pre>model.compile(optimizer=&#39;adam&#39;,<br>              loss=&#39;sparse_categorical_crossentropy&#39;,<br>              metrics=[&#39;accuracy&#39;])</pre><p>We compile the model with the Adam optimizer and sparse categorical cross-entropy loss function.</p><ul><li>optimizer=&#39;adam&#39; is an adaptive learning rate optimizer that works well in most cases.</li><li>loss=&#39;sparse_categorical_crossentropy&#39; is used because the problem is a classification task with integer labels.</li><li>metrics=[&#39;accuracy&#39;] tracks the model&#39;s accuracy during training and evaluation.</li></ul><h3>6. Viewing Model Summary</h3><pre>model.summary()</pre><pre><br>Model: &quot;sequential&quot;<br>_________________________________________________________________<br> Layer (type)                Output Shape              Param #   <br>=================================================================<br> flatten (Flatten)           (None, 784)               0         <br>                                                                 <br> layer1 (Dense)              (None, 16)                12560     <br>                                                                 <br> layer2 (Dense)              (None, 16)                272       <br>                                                                 <br> dense (Dense)               (None, 10)                170       <br>                                                                 <br>=================================================================<br>Total params: 13,002<br>Trainable params: 13,002<br>Non-trainable params: 0<br>__________________________</pre><p>we view the summary of our neural network model, which provides detailed information about the architecture and parameters of the model.</p><ul><li><strong>Flatten Layer</strong>: This layer converts the 2D image input (28x28 pixels) into a 1D array of 784 units, suitable for the fully connected layers. It doesn&#39;t introduce any new parameters (hence 0 params).</li><li><strong>layer1</strong> and <strong>layer2</strong> are Dense Layers: These two layers contain <strong>16 neurons</strong> each with ReLU activation functions. They help to learn higher-level features and patterns from the data. Each Dense layer adds connections between neurons from the previous layer to its own neurons, resulting in parameters <strong>layer1</strong> having <strong>12,560</strong> parameters and <strong>layer2</strong> having <strong>272</strong>.</li><li><strong>Dense </strong>layer: The final layer uses a softmax activation function to classify images into <strong>10 classes</strong> (digits 0-9). It has <strong>170</strong> parameters.</li><li><strong>Total params</strong>: The model comprises <strong>13,002</strong> parameters in total, which are learned during training to accurately predict the labels of images in the <strong>MNIST</strong> dataset.</li></ul><p>This detailed view helps us understand the complexity of our model and provides insights into how each layer transforms the input data.</p><h3>7. Training the Model</h3><pre>model.fit(x=train_X, y=train_y, epochs=25, validation_split=0.2)</pre><pre>Epoch 1/25<br>1500/1500 [==============================] - 4s 2ms/step - loss: 0.2970 - accuracy: 0.9124 - val_loss: 0.3372 - val_accuracy: 0.9014<br>Epoch 2/25<br>1500/1500 [==============================] - 3s 2ms/step - loss: 0.2983 - accuracy: 0.9125 - val_loss: 0.3337 - val_accuracy: 0.9020<br>Epoch 3/25<br>1500/1500 [==============================] - 3s 2ms/step - loss: 0.2979 - accuracy: 0.9122 - val_loss: 0.3136 - val_accuracy: 0.9106<br>Epoch 4/25<br>1500/1500 [==============================] - 3s 2ms/step - loss: 0.2921 - accuracy: 0.9142 - val_loss: 0.3283 - val_accuracy: 0.9053<br>Epoch 5/25<br>1500/1500 [==============================] - 3s 2ms/step - loss: 0.2886 - accuracy: 0.9141 - val_loss: 0.3247 - val_accuracy: 0.9082<br>Epoch 6/25<br>1500/1500 [==============================] - 4s 2ms/step - loss: 0.2850 - accuracy: 0.9165 - val_loss: 0.3247 - val_accuracy: 0.9047<br>Epoch 7/25<br>1500/1500 [==============================] - 4s 2ms/step - loss: 0.2797 - accuracy: 0.9169 - val_loss: 0.3351 - val_accuracy: 0.9051<br>Epoch 8/25<br>1500/1500 [==============================] - 3s 2ms/step - loss: 0.2798 - accuracy: 0.9170 - val_loss: 0.3090 - val_accuracy: 0.9117<br>Epoch 9/25<br>1500/1500 [==============================] - 3s 2ms/step - loss: 0.2765 - accuracy: 0.9189 - val_loss: 0.3039 - val_accuracy: 0.9151<br>Epoch 10/25<br>1500/1500 [==============================] - 3s 2ms/step - loss: 0.2780 - accuracy: 0.9180 - val_loss: 0.3234 - val_accuracy: 0.9100<br>Epoch 11/25<br>1500/1500 [==============================] - 3s 2ms/step - loss: 0.2730 - accuracy: 0.9195 - val_loss: 0.3330 - val_accuracy: 0.9075<br>Epoch 12/25<br>1500/1500 [==============================] - 3s 2ms/step - loss: 0.2727 - accuracy: 0.9189 - val_loss: 0.3241 - val_accuracy: 0.9061<br>Epoch 13/25<br>1500/1500 [==============================] - 3s 2ms/step - loss: 0.2722 - accuracy: 0.9195 - val_loss: 0.3038 - val_accuracy: 0.9134<br>Epoch 14/25<br>1500/1500 [==============================] - 3s 2ms/step - loss: 0.2700 - accuracy: 0.9212 - val_loss: 0.3279 - val_accuracy: 0.9059<br>Epoch 15/25<br>1500/1500 [==============================] - 3s 2ms/step - loss: 0.2685 - accuracy: 0.9222 - val_loss: 0.3180 - val_accuracy: 0.9127<br>Epoch 16/25<br>1500/1500 [==============================] - 3s 2ms/step - loss: 0.2672 - accuracy: 0.9226 - val_loss: 0.3109 - val_accuracy: 0.9128<br>Epoch 17/25<br>1500/1500 [==============================] - 3s 2ms/step - loss: 0.2680 - accuracy: 0.9218 - val_loss: 0.3270 - val_accuracy: 0.9088<br>Epoch 18/25<br>1500/1500 [==============================] - 3s 2ms/step - loss: 0.2682 - accuracy: 0.9211 - val_loss: 0.3141 - val_accuracy: 0.9087<br>Epoch 19/25<br>1500/1500 [==============================] - 4s 3ms/step - loss: 0.2621 - accuracy: 0.9234 - val_loss: 0.3172 - val_accuracy: 0.9087<br>Epoch 20/25<br>1500/1500 [==============================] - 3s 2ms/step - loss: 0.2633 - accuracy: 0.9226 - val_loss: 0.3267 - val_accuracy: 0.9059<br>Epoch 21/25<br>1500/1500 [==============================] - 3s 2ms/step - loss: 0.2628 - accuracy: 0.9238 - val_loss: 0.3254 - val_accuracy: 0.9081<br>Epoch 22/25<br>1500/1500 [==============================] - 3s 2ms/step - loss: 0.2618 - accuracy: 0.9244 - val_loss: 0.3112 - val_accuracy: 0.9137<br>Epoch 23/25<br>1500/1500 [==============================] - 3s 2ms/step - loss: 0.2605 - accuracy: 0.9247 - val_loss: 0.3026 - val_accuracy: 0.9133<br>Epoch 24/25<br>1500/1500 [==============================] - 3s 2ms/step - loss: 0.2591 - accuracy: 0.9248 - val_loss: 0.3192 - val_accuracy: 0.9110<br>Epoch 25/25<br>1500/1500 [==============================] - 3s 2ms/step - loss: 0.2603 - accuracy: 0.9250 - val_loss: 0.3092 - val_accuracy: 0.9127<br>&lt;keras.callbacks.History at 0x7f10f2151690&gt;</pre><p>Here, the model is trained on the MNIST training data for 25 epochs.</p><ul><li>validation_split=0.2 means that 20% of the training data will be used for validation, allowing us to monitor the model&#39;s performance on unseen data during training.</li></ul><p>Each epoch updates the model’s weights based on the data presented during that epoch, aiming to minimize the loss function.</p><p><strong>Output for Each Epoch</strong>:</p><ul><li><strong>loss</strong>: Measures how well the model’s predictions align with the actual labels. Each epoch should show a decrease in loss, indicating that the model is learning.</li><li><strong>accuracy</strong>: Tracks the proportion of correct predictions the model makes on the training data. Initially, the model’s accuracy starts around 91%, then gradually increases as it learns to better classify the images.</li><li><strong>val_loss</strong>: The loss on the validation set, which is used to monitor generalization to unseen data. Ideally, this should not diverge too much from the training loss.</li><li><strong>val_accuracy</strong>: Similar to accuracy, but for the validation set, it gives an indication of how well the model might perform on new, unseen data.</li></ul><p>These results show a steady improvement in accuracy and a controlled decrease in loss during training, suggesting that the model is learning effectively. However, we also see that the model’s performance on the validation set is slightly lower than on the training set, indicating some overfitting. This process helps us understand how well the model is generalizing from the training data to unseen test data.</p><h3>8. Evaluating the Model on Test Data</h3><pre>model.evaluate(x=test_X,y=test_y)</pre><pre>313/313 [==============================] - 0s 1ms/step - loss: 0.3209 - accuracy: 0.9163<br>[0.32091614603996277, 0.9162999987602234]</pre><p>After training, we evaluate the model’s performance on the test dataset to determine how well it generalizes to new, unseen data. This gives us an accuracy score on the test set.</p><ul><li><strong>loss</strong>: Represents the average error in predictions across the test set. A value of <strong>0.3209</strong> indicates that the model’s predictions are fairly accurate but not perfect.</li><li><strong>accuracy</strong>: A score of <strong>91.63%</strong> indicates that the model correctly classified about <strong>91.63%</strong> of the test images. This shows that our model is fairly effective at recognizing handwritten digits, although there is still room for improvement, particularly in reducing misclassification errors.</li></ul><p>This evaluation gives us an idea of how well our model generalizes to new, unseen data and provides a benchmark for further tuning and improvements.</p><h3>9. Making Predictions and Visualizing Results</h3><pre>print(np.argmax(model.predict(np.array([test_X[9]]))))<br>plt.imshow(test_X[9])</pre><pre>1/1 [==============================] - 0s 16ms/step<br>9</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/251/1*o_YoDNjrQuSRRG2Jgoq5RQ.png" /></figure><p>we predict the label of the 10th image in the test set (test_X[9]), print the predicted label using np.argmax(), and display the image.</p><ul><li>np.argmax() returns the index of the maximum value in the prediction output, which corresponds to the predicted digit.</li></ul><p>This step-by-step guide demonstrates how to build, train, and evaluate a neural network using TensorFlow and Keras for classifying handwritten digits in the MNIST dataset. We covered the key steps from loading and visualizing the data, constructing the model, and fine-tuning its performance. By the end of this process, our model achieved over 91% accuracy on the test dataset, showcasing the power of neural networks for image classification tasks.</p><p>While the results are impressive, there’s still potential for improvement. Techniques like data augmentation, using more complex architectures, or fine-tuning hyperparameters can further enhance accuracy. This project serves as a foundation for exploring deeper neural networks and other machine learning tasks.</p><p>Happy coding, and may your neural networks always converge!</p><p>#MachineLearning #DeepLearning #NeuralNetworks #TensorFlow #Keras #MNIST #AI #ImageClassification #Python</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13a8582744a8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>