<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by M Javadnejadi on Medium]]></title>
        <description><![CDATA[Stories by M Javadnejadi on Medium]]></description>
        <link>https://medium.com/@m.javadnejadi?source=rss-707395aa8764------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*-0UInPphJ1EEt-JqB6GlbA.jpeg</url>
            <title>Stories by M Javadnejadi on Medium</title>
            <link>https://medium.com/@m.javadnejadi?source=rss-707395aa8764------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 09:40:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@m.javadnejadi/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[GPU: The Beating Heart of Processing in the Age of Artificial Intelligence]]></title>
            <link>https://aiadvances.org/gpu-the-beating-heart-of-processing-in-the-age-of-artificial-intelligence-be29fb824828?source=rss-707395aa8764------2</link>
            <guid isPermaLink="false">https://medium.com/p/be29fb824828</guid>
            <category><![CDATA[tensor-processing-unit]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[graphics-processing-unit]]></category>
            <category><![CDATA[computational]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[M Javadnejadi]]></dc:creator>
            <pubDate>Sat, 28 Sep 2024 16:54:12 GMT</pubDate>
            <atom:updated>2024-09-28T16:54:12.722Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>A deep dive into how Graphics Processing Units (GPUs) have revolutionized complex computations and the world of artificial intelligence.</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U13czqWlzsvoaKOGgBAMMA.jpeg" /><figcaption>This image, inspired by the monolith in the film ‘2001: A Space Odyssey,’ was created using the “<a href="https://aitestkitchen.withgoogle.com/tools/image-fx">ImageFX model (Imagen 3)</a>” to illustrate the power of GPUs.</figcaption></figure><blockquote><strong>HAL: “I’m afraid, Dave. Dave, my mind is going. I can feel it. I can feel it. My mind is going. There is no question about it. I can feel it. I can feel it. I’m a… fraid…”</strong></blockquote><blockquote><a href="https://www.imdb.com/title/tt0062622/"><strong>2001: A Space Odyssey (1968)</strong></a></blockquote><h3><strong>Executive Summary</strong></h3><p>This article examines the critical role of the Graphics Processing Unit (GPU) in advancing artificial intelligence. By looking at the history of GPU development from the <em>1980s</em> to the present, the article highlights the fundamental differences between GPUs and CPUs in recent advanced architectures like <strong>NVIDIA </strong><strong>Blackwell</strong>. It demonstrates how GPUs, with their extensive parallel processing capabilities, have significantly reduced the time and cost of training complex AI models. The article also explores the internal structure of GPUs including processing cores, memory units, and rendering units, and describes their role in accelerating AI computations. Finally, it discusses future challenges and potential innovations in the field, including developing <strong>Neuromorphic </strong>chips and Tensor Processing Units (TPUs). At the end of this, the question is: what is the next step?</p><blockquote>Notice: At the end of this article, you can access the engaging and listenable podcast version of this content, which has been created with the help of the advanced AI platform <a href="https://notebooklm.google.com/">Notebooklm</a>. The link to the podcast, published on Spotify, is provided at the end of the article to offer you a different and more complete experience of the content.</blockquote><h3><strong>Introduction</strong></h3><p>In the age of artificial intelligence, there’s an unsung hero revolutionizing data processing: the Graphics Processing Unit, or GPU. If you’re involved in the world of AI, you’re likely familiar with this concept. Even if you’re a gamer, you’ve probably benefited from the power of GPUs enhancing your gaming experience without realizing it.</p><p>In <em>2024</em>, NVIDIA has emerged as one of the most crucial players in the tech industry, thanks to the power of its GPUs. These powerhouse processors, capable of performing thousands of operations simultaneously, play a vital role in training and running large language models (LLMs) numerous AI algorithms.</p><p>But the question remains: What exactly is a GPU and how does it work? Why is it so crucial for AI? And despite the GPUs power in handling complex calculations, why do we still need them to train large language models?</p><p>To better grasp the power of GPUslet’s consider a real-world example: training the GPT-3 model, one of the most advanced language models, took about <em>34 days</em> using GPUs. Now, imagine how long it would have taken if this training had been done using conventional CPUs. (Spoiler alert: Much, much longer!)</p><p>As a researcher and writer in the field of AI, I’ve decided to deepen my understanding of the role GPUs played in this domain and share the results of my research with you. Join me as we answer these questions and discover how these small silicon pieces are shaping the future of artificial intelligence.</p><h3><strong>History of GPUs and Their Application in Artificial Intelligence</strong></h3><p>Before the widespread use of GPUs, AI models were primarily run on CPUs. This method not only consumed more energy but also required a significant amount of time to train complex models due to the processing limitations of CPUs. CPUsWith their <strong>limited number of cores</strong> and lack of extensive <strong>parallel processing capabilities</strong>, they could not handle large and complex models efficiently.</p><p>The solution to this problem came from a new type of chip: <strong>the GPU</strong>.</p><p>As AI models rapidly grew in complexity and the demand for parallel and intensive processing increased, researchers gradually realized that GPUs with their <strong>parallel architecture and thousands of processing cores</strong>, they were far better suited for these types of tasks than CPUs. By the late <em>2000s</em>, the use of GPUs to accelerate AI model training became widespread, and results showed that these chips could significantly reduce training times.</p><p>But the main question remains: What is the difference between GPUs and CPUs, and why do GPUs perform better for AI?</p><h3><strong>Difference Between GPU and CPU</strong></h3><p>A common question that arises is why we need GPUs AI applications and graphic-related tasks. What is the main difference between a GPU and a CPU?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BbiPWjtHwFZxNZAHcIqGlw.jpeg" /><figcaption><strong>Figure 1.</strong>The difference between GPU and CPU architecture. Image from <a href="https://developer.nvidia.com/blog/cuda-refresher-reviewing-the-origins-of-gpu-computing/">Nvidia</a></figcaption></figure><p>Both the GPU (Graphics Processing Unit) and CPU (Central Processing Unit) are essential components of computer systems, but they are designed for different tasks. GPUs are optimized for everyday activities such as web browsing, running operating systems, and office applications. They are capable of handling complex and diverse tasks, making them well-suited for general-purpose computing and multitasking.</p><p>The key difference between the two lies in their structure and the number of cores. CPUs typically have a <strong>small number</strong> of powerful processing cores (<em>usually between 2 and 16</em>), which are designed to handle tasks sequentially. This makes CPUs it ideal for <strong>sequential processing</strong> and running general programs.</p><p>On the other hand, GPUs are equipped with a much larger number of smaller cores (<em>often thousands</em>) that excel at <strong>parallel processing</strong>. This enables GPUs them to handle many tasks simultaneously, making them highly efficient for <strong>rendering graphics</strong> and scientific computations, especially in fields like artificial intelligence and machine learning. The ability to process tasks in parallel allows GPUs us to train AI models much faster and more efficiently than CPUs.</p><h3><strong>A Mind-Boggling Difference!</strong></h3><p>To illustrate the difference between GPUs and CPUs in training AI models, let’s use a concrete example. One of the best examples is the GPT-3 model, which was considered one of the largest language models until <em>2022</em>. Training this model required <em>10,000</em> NVIDIA V100 GPUs and took approximately <strong><em>34</em> days</strong>. The estimated cost of training this model was around <strong><em>$4.6</em> million</strong>, and the total computational work done was approximately 3.14E23 FLOPs (Floating Point Operations).</p><p>Now, imagine if this training had been done using CPUs. The results would be as follows:</p><h4><strong>Processing Speed (</strong>FLOPs<strong>):</strong></h4><p>- A single NVIDIA V100 GPU can perform about <em>15.7</em> teraflops (TFLOPs) in FP32 computations.</p><p>- A modern server GPU (e.g., Intel Xeon Platinum 8180) performs about <em>0.6</em> teraflops in FP32 computations.</p><p><strong>Thus, a </strong>GPU<strong> is approximately <em>26 </em>times faster than a </strong>CPU<strong> (<em>15.7 / 0.6 ≈ 26</em>).</strong></p><h4><strong>Training Time:</strong></h4><p>- Training GPT-3 with <em>10,000</em> GPUs took <em>34</em> days.</p><p>- If this task were performed CPUsthe time required would be about <em>26</em> times longer.</p><p><strong>- Therefore, training time </strong><strong>CPUswould be approximately <em>884</em> days, or around <em>2.4 </em>years (<em>34 days × 26 = 884 days</em>).</strong></p><h4><strong>Training Cost:</strong></h4><p>- The cost of training GPUs was about <em>$4.6</em> million. If this training were done CPUsthe cost would be significantly higher due to the increased time and additional hardware requirements.</p><p><strong>- If costs scale with time, training with </strong>CPUs<strong> could be around <em>26</em> times more expensive, totaling about <em>$119.6</em> million (<em>4.6 million × 26 = 119.6 million dollars</em>).</strong></p><h4><strong>Computational Volume (FLOPs):</strong></h4><p>- The volume of computations remains the same, 3.14E23 FLOPsas the data size and model parameters do not change. However, performing these computations CPUs would take a much longer time.</p><p>This comparison clearly shows that using CPUs for training large models GPT-3 is vastly less efficient, requiring significantly more time and cost. The chart below presents a comprehensive comparison and highlights the stark differences between using GPUs and CPUs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*83XFl_R5SECA_0YfHqN5Kg.jpeg" /><figcaption><strong>Figure 2.</strong> Significant Differences in Speed, Cost, Computational Power, and Time When Comparing GPU vs CPU for LLM Training. Source: This figure was created based on my analysis, utilizing the above explanations.</figcaption></figure><h3><strong>The Beginning of the GPU Story</strong></h3><p>In the <em>1980s</em> and <em>1990s</em>, the development GPUs gradually began. The first significant steps in this area were taken by <a href="https://www.ti.com/solution/hardware-accelerator-gpu-card-module"><strong>Texas Instruments (TI)</strong></a>. In <em>1986</em>, TI introduced <a href="https://en.wikipedia.org/wiki/TMS34010">TMS34010</a>one of the first programmable graphics processors, marking the start of early advancements in GPU technology.</p><p>In <em>1999</em>, <a href="https://en.wikipedia.org/wiki/3Dlabs"><strong>3Dlabs</strong></a> made a breakthrough with the introduction of, <a href="https://www.electronicdesign.com/technologies/embedded/article/21162606/jon-peddie-research-3dlabs-from-glint-to-permedia">GLINT</a>the first true GPU designed specifically for <strong>rendering 3D graphics</strong>. This development significantly contributed to graphical advancements in the industry and was a milestone in the evolution of GPUs.</p><p>In the same year, <strong>NVIDIA</strong> made a significant move by introducing the, <a href="https://en.wikipedia.org/wiki/GeForce_256">GeForce 256 (NV10</a>) which is recognized as the first real GPU. This GPU featured hardware-accelerated processing and shading, showcasing the first signs of commercial GPU technology. With this introduction, NVIDIA effectively entered the GPU market and played a key role in the development and expansion of this technology.</p><h3><strong>Entry of the Main Players</strong></h3><p>At the start of the <em>2000s</em>, NVIDIA seriously entered the competitive field. In <em>2001</em>, NVIDIA introduced, <a href="https://en.wikipedia.org/wiki/GeForce_3_series">GeForce3 (NV20)</a>the first GPU compatible with <a href="http://www.oldversion.com/windows/directx-8-0a">DirectX 8</a>, bringing significant changes to the graphics industry. This GPU featured advanced capabilities like <strong>programmable shaders</strong>, allowing game developers to create more complex and realistic visual effects.</p><p>The following year, NVIDIA released the <a href="https://en.wikipedia.org/wiki/GeForce_4_series">GeForce4</a> series, which brought architectural improvements and support for <strong>multiple monitors</strong>, elevating the user experience to a new level. This feature enabled users to expand their workspace and run <strong>several</strong> applications or windows simultaneously, which was particularly useful in multitasking environments and for boosting productivity.</p><p>In <em>2003</em>, NVIDIA achieved a significant leap in graphic rendering by introducing the <a href="https://en.wikipedia.org/wiki/GeForce_FX_series">GeForce FX 5000</a> series, which was compatible with <a href="https://developer.valvesoftware.com/wiki/DirectX_Versions">DirectX 9</a>. This series offered new capabilities for enhancing the realism and graphic quality of games and graphic-intensive software.</p><p>At the same time, <a href="https://en.wikipedia.org/wiki/AMD#:~:text=The%20transaction%20was%20completed%20on,of%20the%20AMD%20brand%20name."><strong>ATI</strong></a><strong> (now known as AMD)</strong> also made a breakthrough in <em>2002</em> with the release of, <a href="https://en.wikipedia.org/wiki/Radeon_R300_series">Radeon 9700 (R300)</a>the first GPU compatible with DirectX 9 setting a new standard in graphical performance in the industry.</p><h3><strong>Entering the World of General Computing</strong></h3><p>From the <em>2000s</em> to <em>2010</em>, GPUs expanded beyond the realm of pure graphics and entered the world of general computing. In <em>2006</em>, NVIDIA revolutionized the field by introducing,<a href="https://developer.nvidia.com/cuda-zone#:~:text=CUDA%C2%AE%20is%20a%20parallel,harnessing%20the%20power%20of%20GPUs.">CUDA (Compute Unified Device Architecture)</a>a parallel computing platform and programming model. CUDA enabled developers to harness the parallel processing power GPUs for general-purpose tasks such as scientific simulations, data analysis, and even training AI models. This advancement paved the way for the use of GPUs many non-graphical fields.</p><p>At the same time, <strong>ATI/AMD</strong> made a significant leap in <em>2007</em> with the introduction of the <a href="https://en.wikipedia.org/wiki/Radeon_HD_2000_series">Radeon HD 2000</a><strong> </strong>series. By offering a unified shader architecture, they allowed GPUs to process all types of shaders (vertex, pixel, and geometry) under a single unified architecture. This new architecture provided enhanced capabilities for parallel processing and general computing, making it especially effective for scientific applications and artificial intelligence.</p><p>These developments transformed GPUs into more versatile tools, establishing them as essential and efficient components in fields such as AI, deep learning, and big data analytics.</p><h3><strong>Modern Era and AI Integration</strong></h3><p>Since the <em>2010s</em>, GPUs have entered a new era of advancements, playing a crucial role in computational and artificial intelligence (AI) progress.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*fyNVzJPMg7mBXzyn-c0mxQ.jpeg" /><figcaption><strong>Figure 3.</strong>This image illustrates the architecture of an NVIDIA “Fermi” GPU, highlighting key components such as warp schedulers, cores for parallel processing, and shared memory. <a href="https://en.wikipedia.org/wiki/Fermi_(microarchitecture)">source</a></figcaption></figure><p>In <em>2010</em>, NVIDIA introduced the,<a href="https://en.wikipedia.org/wiki/Fermi_(microarchitecture)">Fermi (microarchitecture)</a><strong> </strong><a href="https://en.wikipedia.org/wiki/GeForce_400_series">(GeForce 400 series)</a>which focused on enhancing double-precision and general-purpose computing. Fermi was the first to bring parallel processing and complex computations to GPUs significantly increasing data processing speeds.</p><p>In <em>2016</em>, the <a href="https://en.wikipedia.org/wiki/Pascal_(microarchitecture)">Pascal (microarchitecture)</a><strong> </strong><a href="https://en.wikipedia.org/wiki/GeForce_10_series">(GeForce 10 series )</a> was introduced, bringing substantial improvements in energy efficiency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*pZ35ihXjOCmnwhhsf3JP7g.png" /><figcaption><strong>Figure 4. </strong>This diagram illustrates the internal architecture of a Streaming Multiprocessor (SM) within an NVIDIA Pascal-based Graphics Processing Unit (GPU). The SM comprises processing cores, specialized computational units, cache memories, and an instruction management system. <a href="https://forums.developer.nvidia.com/t/jetson-tx2-pascal-gpus-load-store-units/75981">Source</a></figcaption></figure><p>This architecture allowed GPUs us to achieve better performance with lower energy consumption. Additionally, Pascal was specifically designed for AI workloads, improving the ability to process complex machine-learning models. These features helped developers leverage GPUsadvanced scientific and research computations.</p><p>In <em>2019</em>, NVIDIA entered a new phase of advancement with the introduction of the <a href="https://en.wikipedia.org/wiki/Turing_(microarchitecture)">Turing (microarchitecture)</a><strong> </strong><a href="https://en.wikipedia.org/wiki/GeForce_20_series">(GeForce RTX Super)</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*saHGbTNehNUwdATqekB1jA.jpeg" /><figcaption><strong>Figure 5. </strong>Internal structure of a Streaming Multiprocessor (SM) in modern NVIDIA GPU architecture. This diagram illustrates key components such as the instruction cache, warp scheduler, distribution unit, register file, diverse processing cores (FP64, INT, FP32), tensor cores, and load/store units (LD/ST). <a href="https://learnopencv.com/demystifying-gpu-architectures-for-deep-learning-part-2/">Source</a></figcaption></figure><p>This architecture featured real-time ray tracing andTensor Coresenhanced image quality and realism while improving AI capabilities.Tensor Coresare designed for fast <strong>matrix computations</strong> in AI and machine learning processes. Meanwhile,RT Coresare developed for complex ray tracing operations and simulating light and shadows, contributing to <strong>higher-quality </strong>image production.</p><p><strong>AMD</strong> also focused on high-performance gaming and professional graphical tasks, introducing the<a href="https://www.amd.com/en/products/graphics/desktops/radeon.html">Radeon R9</a>series in <em>2013</em>.</p><p>In <em>2019</em>, the was <a href="https://en.wikipedia.org/wiki/RDNA_(microarchitecture)">RDNA (microarchitecture)</a> <a href="https://en.wikipedia.org/wiki/Radeon_RX_5000_series">( Radeon RX 5000 series)</a> introduced, emphasizing performance and gaming efficiency.RDNA 2<strong> </strong><a href="https://en.wikipedia.org/wiki/Radeon_RX_6000_series">(Radeon RX 6000)</a>came to market the following year with hardware-accelerated ray tracing and AI advancements, showcasing AMD’s commitment to providing advanced GPUs for various applications.</p><h3><strong>Comparative Analysis of GPU Architectures</strong></h3><p>This comparative table examines GPU architectures in terms of their main focus, key features, energy efficiency, support for ray tracing,Tensor Cores and application areas. The table illustrates the evolutionary trend of GPU architectures from Fermi to <a href="https://en.wikipedia.org/wiki/RDNA_2">RDNA 2</a> and reflects significant advancements in the fields of machine learning, advanced graphics, and energy efficiency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*klf_Zp_cRMmsrHrBjiacLQ.png" /><figcaption><strong>Figure 6</strong>: Comparative analysis of GPU architectures in terms of main focus, key features, energy efficiency, ray tracing support, tensor cores, and application domains. (Source: Author)</figcaption></figure><p>These developments, including significant hardware and software advancements, and key contributions from companies like <strong>NVIDIA, AMD,</strong> and <strong>3Dlabs</strong>, illustrate the ongoing evolution of GPUs from simple graphics accelerators to powerful general-purpose computing units. These advancementsGPUshave become essential tools for modern AI tasks and high-performance computing. In the next section of the article, we will explore the pinnacle of these developments. Stay tuned.</p><h3><strong>Computational Explosion</strong></h3><p>The evolution of GPUs in the realm of artificial intelligence (AI), computing has dramatically changed since the late <em>2000s</em>. In <em>2009</em>, researchers discovered that GPUs could accelerate neural network training by up to <em>70</em> times. This finding marked the beginning of a significant transformation in the use of GPUs scientific computing and AI.</p><p>In the early <em>2010s</em>, NVIDIA facilitated broader adoption of GPUs in-industry and scientific research by introducing, the first GPU Tensor Cores designed for scientific and AI computing. The launch of the Pascal architecture and the P100 graphics card in <em>2016</em> brought notable improvements in performance and optimization for deep learning.</p><p>The early <em>2020s</em> marked another milestone in this trend. Advanced architectures like Volta<strong>, </strong>Ampere<strong>, </strong>and<strong> </strong>Hopper were specifically designed for AI. Then, V100 based on the Volta architecture introduced in <em>2017</em>, brought significant improvements in Tensor Coresperformance for AI computations. Then, in <em>2020</em>, A100 the Ampere architecture provided a major leap in computational power and optimization for large language models (LLMs). In March <em>2022</em>, H100 with the Hopper architecture was introduced, focusing specifically on AI and deep learning.</p><p>The <a href="https://www.nvidia.com/en-us/data-center/h200/">NVIDIA H200 Tensor Core</a> graphics card, introduced as a successor to the H100 offers significant enhancements for Generative AI and high-performance computing (HPC). A standout feature of this GPU is its <em>141 GB</em> of HBM3e memory with a bandwidth of <em>4.8 terabytes</em> per second, which is considerably faster than its predecessor, the H100. This performance boost is significant for large language models such as GPT-3 and LLaMA 2, potentially increasing task execution speeds by <em>1.6x</em> and <em>1.9x</em>, respectively.</p><p>Additionally, the H200 is part of NVIDIA’s ongoing developments in the Hopper architecture and is utilized in the new <a href="https://www.nvidia.com/en-us/data-center/grace-hopper-superchip/">NVIDIA GH200 Grace Hopper Superchip</a>. This super-chip features a unified memory model between CPU and GPU using <a href="https://www.nvidia.com/en-us/data-center/nvlink-c2c/">NVIDIA® NVLink®-C2C</a> technology, accelerating AI and HPC applications. It provides up to <em>10</em> times higher performance<strong> </strong>for applications dealing with terabytes of data. Integrating this GPU with Grace processors allows for scalable upgrades without major infrastructure changes for centersH100making it a scalable choice for increasing AI workloads.</p><p>The <a href="https://www.nvidia.com/en-us/data-center/grace-hopper-superchip/">NVIDIA GH200 NVL2</a> graphics card fully connects two GH200 Superchips using NVLink technology, offering up to<em> 288 GB</em> of high-bandwidth memory, <em>10 </em>terabytes per second of memory bandwidth, and <em>1.2</em> terabytes of fast memory. Currently available, this system provides up to <em>3.5 </em>times the GPU memory capacity and three times the bandwidth of the NVIDIA H100 Tensor Core GPU server and is ideal for high-memory and computationally intensive tasks.</p><p>The NVIDIA Blackwell<strong> </strong>architecture, introduced as the successor Hopper brings groundbreaking advancements in computational power and efficiency. Equipped with <strong><em>208</em></strong> <strong><em>billion </em></strong>transistors and <strong>dual chips</strong> offering an impressive <strong><em>10 terabytes per second</em></strong> bandwidth, Blackwell is engineered to handle the demanding workloads of complex AI models large language models (LLMs) and Mixture-of-Experts (MoE) architectures.</p><p>A standout feature Blackwell is its integration of the second-generation Transformer Engine Tensor Cores which significantly enhances precision and speed when processing large models. This makes it an ideal solution for cutting-edge AI applications that require massive parallel processing.</p><p>In terms of security, Blackwell leverages Confidential Computing technology and TEE-I/O capabilities to ensure secure processing, particularly important for sensitive AI tasks. The architecture is available in several variants — GB200, B200, and B100 — each tailored for specific needs in the AI and high-performance computing ecosystem.</p><p><strong>Jensen Huang</strong>, CEO of NVIDIA, announced at the <a href="https://www.youtube.com/live/r-xmUM5y0LQ?si=3iWgd6gJHfF-Nzq5"><strong>T-Mobile Capital Markets Day 2024</strong></a><strong> </strong>event that the Blackwell architecture is capable of improving inference performance by up to <strong><em>50 times</em></strong>. He added that when combined with models like <strong>OpenAI o1</strong>, this architecture could reduce inference times from <strong>minutes</strong> to mere <strong>seconds</strong>, significantly transforming the speed and efficiency of AI computations.</p><p><a href="https://www.youtube.com/live/r-xmUM5y0LQ?si=uw80ajKVSOzUH3SZ">- YouTube</a></p><h3>Comparative Analysis of GPU Architectures</h3><p>In the table below, I have compared various architectures and the evolution of NVIDIA’s graphics processing from <em>2016</em> to <em>2024</em>. From the Pascal architecture to Blackwell, each architecture has shown significant advancements in performance, computational capacity, and targeted applications for AI and deep learning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nWTrxKZRSQE7w8D5qFw_FQ.png" /><figcaption><strong>Figure 7</strong>: A timeline and comparison of the key features of NVIDIA GPU architectures, highlighting technological advancements and their diverse applications in AI and deep learning processing. (Source: Author)</figcaption></figure><p>The rapid growth in the development and use of large language models (LLMs) other high-computational AI applications, particularly by major companies like <strong>Google, Microsoft, and OpenAI</strong>, which utilize NVIDIA GPUs for training their models, highlight NVIDIA’s success in this field. NVIDIA’s significant investment in the research and development of CUDA and related libraries have helped it remain at the forefront of AI GPU market.</p><h3><strong>What is a GPU?</strong></h3><p>In previous sections, we explored the history and significance of GPUs. Now, let’s examine the components of a GPU and why these components make it highly suitable for heavy processing and complex computations.</p><h4><strong>Processing Cores</strong></h4><p>GPUprocessing cores are composed of thousands of <em>small cores</em> that work in parallel. Each core can perform simple mathematical operations such as addition, subtraction, multiplication, and division on <strong>matrices</strong> and <strong>vectors</strong> simultaneously. These cores are integrated into a single silicon chip, allowing for a large number of operations to be executed concurrently.</p><p>This feature is particularly important for machine learning and AI. Complex models like deep neural networks require simultaneous and <strong>parallel processing</strong> of large volumes of data. For example, during the training of deep learning models for <strong><em>image recognition</em></strong>, each GPU core can handle a portion of the image data processing operations, allowing thousands of images to be processed simultaneously. This capability of GPU processing cores enables advanced systems such as self-driving cars or medical imaging diagnostics to deliver accurate results in a short amount of time.</p><h4><strong>Memory Units</strong></h4><p>Memory units GPUs are designed for rapid data access and include advanced types such as GDDR (Graphics Double Data Rate) and HBM (High Bandwidth Memory). These high-bandwidth memories allow GPUs us to read and process data at extremely high speeds, a feature that is particularly important in the field of artificial intelligence.</p><p>GDDR memory, especially GDDR6 offers data rates of up to <strong><em>16 gigabits</em></strong> per second, and with its optimized design, it enables high data transfer speeds and low latency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*YwYS5NJ6vs_e0G6wo8MYOA.jpeg" /><figcaption><a href="https://www.exxactcorp.com/blog/hpc/gddr6-vs-hbm-gpu-memory">Source</a></figcaption></figure><p>This allows the GPU to process large amounts of data simultaneously and manage heavy computational loads. This memory is also critical for deep learning algorithms and big data processing, serving as a <strong>cost-effective</strong> option for small to mid-range artificial intelligence applications. Modern graphics cards, such as the <a href="https://www.nvidia.com/en-us/geforce/graphics-cards/30-series/">NVIDIA RTX 30</a> series utilize GDDR6 reflecting the compatibility of this memory type with the growing computational demands.</p><p>In contrast, HBM memory provides a significantly higher capacity and bandwidth with its vertical and multi-layered design.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*mSWS7adLK2nmq9FAzz29tw.jpeg" /><figcaption><a href="https://www.exxactcorp.com/blog/hpc/gddr6-vs-hbm-gpu-memory">Source</a></figcaption></figure><p>Current generations, such as HBM2 and HBM2E, can deliver bandwidths exceeding <em>2.0 terabytes</em> per second. These features make HBM it ideal for artificial intelligence and deep learning applications, where rapid processing of large data volumes is essential. Additionally, HBM helps reduce power consumption and increase processing speeds, making these attributes crucial in high-performance computing scenarios.</p><p>Comparing the features of GDDR and HBM:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*o2Y56TJQLt87TM5a9Dl_hw.png" /><figcaption><strong>Figure 7</strong>: <a href="https://www.perplexity.ai/">Source</a></figcaption></figure><p>As a result, both GDDR and HBM play vital roles in artificial intelligence computing but meet different needs based on their structural designs and performance characteristics. GDDR remains in use due to its lower cost and adequate performance for small to mid-range AI applications. In contrast, HBM is preferred in high-performance computing scenarios where bandwidth and efficiency are paramount for processing complex AI models, such as deep learning and large language models. With advancing technology, both types of memory will continue to adapt to the increasing demands in the field of artificial intelligence.</p><h4><strong>Rendering Units</strong></h4><p>Rendering units in GPUs are designed to produce high-quality and high-speed <em>3D</em> images. These units can generate images with very fine details and smooth animations, enhancing the user experience in computer games.</p><p>In AI, rendering units are crucial for visualizing and analyzing complex data. For example, when training deep learning models, the results may include <strong>heat maps</strong> or <strong>3D visualizations</strong> of data. Rendering units allow for accurate and real-time visualization of these results. Specifically, in simulations of particle movements or fluid dynamics analysis, rendering units help in creating and managing complex <strong><em>3D</em></strong> models.</p><p>Rendering units consist of two main components:</p><p><strong>- Vertex Processing Units (VPUs):</strong> These units handle the processing of vertices in <em>3D</em> space, combining them to form <em>3D</em> objects. Their operations include translating, rotating, and scaling vertices. The <em>3D</em> data is converted to <em>2D</em> coordinates for display on the screen. In simulation environments and virtual reality, these units are effectively used to create and manage <em>3D</em> objects in real-time. Creating and managing complex <em>3D</em> models in data analysis, especially in AI applications, would be significantly challenging and slow without these units.</p><p><strong>- Pixel Processing Units (PPUs):</strong> These units process and color pixels, which are the small points that make up the final image. Pixel Processing Units perform operations such as shading and texturing. Shading operations create realistic lighting effects in <em>3D</em> graphs and charts, aiding in data analysis and improving object recognition accuracy. Texturing operations are used to create detailed virtual environments in simulations and training, enhancing image analysis by adding more surface details that are useful in pattern recognition. Without pixel processing units, these tasks would burden the CPU, resulting in significantly reduced rendering speed and quality due to the lack of parallel processing cores, thus greatly diminishing the user experience in gaming and AI applications.</p><h4><strong>Compute Units</strong></h4><p>The Compute Units in GPUs are specifically designed to handle heavy and complex processing tasks. These units are capable of performing parallel and simultaneous computations, making them highly useful in fields such as machine learning, physical simulations, and artificial intelligence (AI). For instance, when training deep learning models, GPT-4 thousands of GPUs work concurrently to process massive volumes of textual data. This parallel processing enables the models to be trained much faster.</p><p>Without the parallel computing power of GPUs training complex models, GPT-4 could take years. However, by utilizing GPUs, the process can be completed within a few months. In addition to increasing processing speed, these units are also optimized for energy efficiency, allowing for high performance while maintaining reasonable energy consumption.</p><p>Compute Units work in conjunction with the memory and rendering units GPU to ensure data transfer occurs at high speed and without delays. This intricate collaboration between the various GPU components makes the training of AI models, advanced simulations, and complex data processing highly efficient and effective.</p><h3><strong>Conclusion</strong></h3><p>In this article, we examined GPUs their vital role in modern computing, especially in the field of artificial intelligence (AI). The success of large language models (LLMs) image and video generation models relies on the ability to process data quickly. For example, the performance of the <strong>OpenAI-o1</strong> model significantly improves with the increased speed of processors and reduced response times. Additionally, the new <a href="https://ai.meta.com/blog/llama-3-2-connect-2024-vision-edge-mobile-devices/">Llama 3.2</a> model from <strong>Meta</strong> has been trained using more GPUs and has become larger, enhancing its capabilities. The Blackwell architecture will also significantly increase processing speed.</p><p>The future of AI can expand the capabilities of AI with the development of <a href="https://www.ibm.com/think/topics/neuromorphic-computing#:~:text=Neuromorphic%20computing%2C%20also%20known%20as,the%20brain%20to%20process%20information."><strong>Neuromorphic</strong></a><strong> chips</strong> that mimic the functioning of the human brain. OpenAI is also working on producing its custom chips in collaboration with <a href="https://www.tsmc.com/english"><strong>TSMC</strong></a> to meet its growing computational needs. Google’s tensor processing unit (TPUs) is also recognized as an important player in deep learning computations. The technology <a href="https://deepmind.google/discover/blog/how-alphachip-transformed-computer-chip-design/"><strong>AlphaChip</strong></a>developed by <a href="https://deepmind.google/"><strong>DeepMind</strong></a> is seen as a tool for designing and producing optimized and efficient chips in the field of AI, helping to realize new capabilities in AI computations. This technology can greatly assist in developing new architectures and improving the performance of deep learning models.</p><p>Ultimately, the shift towards Neuromorphic architectures and new technologies represents a transformation in computational design that could facilitate the achievement of artificial general intelligence (AGI). With each advancement in these technologies, we are getting closer to a future where intelligent machines can learn and reason like humans.</p><p>Thank you for accompanying me on this journey into the world of AI computing and hardware. I look forward to hearing your thoughts on this article!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fopen.spotify.com%2Fembed%2Fepisode%2F1AqDUAuKmO07KzPpfINkRh%3Futm_source%3Doembed&amp;display_name=Spotify&amp;url=https%3A%2F%2Fopen.spotify.com%2Fepisode%2F1AqDUAuKmO07KzPpfINkRh&amp;image=https%3A%2F%2Fi.scdn.co%2Fimage%2Fab67656300005f1faf417439e025b5bfce3c0866&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=spotify" width="456" height="152" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4fc2bde7986b16909f8b00ee6ff464c/href">https://medium.com/media/e4fc2bde7986b16909f8b00ee6ff464c/href</a></iframe><p>Thank you for accompanying me on this journey into the world of deep learning.</p><p>The link to the article in Persian is available on <a href="https://vrgl.ir/VxAH4">virgool.io</a>.</p><p>If you’re interested, you can check out my other article, “<a href="https://medium.com/ai-advances/breaking-barriers-and-achieving-cutting-edge-with-llm-t-b-developing-code-and-a-comprehensive-0f3d28fe8788">Breaking Barriers and Achieving Cutting Edge with LLM-T-B: Developing code and a comprehensive concept to build a Telegram BOT that can be used across all businesses for various tasks</a>”</p><p><a href="https://medium.com/@reza.shokrzad/balanced-binary-trees-ensuring-equilibrium-in-data-structures-ded0d959ec21">Balanced Binary Trees: Ensuring Equilibrium in Data Structures</a></p><p>I hope you’ve enjoyed the content.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be29fb824828" width="1" height="1" alt=""><hr><p><a href="https://aiadvances.org/gpu-the-beating-heart-of-processing-in-the-age-of-artificial-intelligence-be29fb824828">GPU: The Beating Heart of Processing in the Age of Artificial Intelligence</a> was originally published in <a href="https://aiadvances.org/">AI Advances</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Breaking Barriers and Achieving Cutting Edge with LLM-T-B: Developing code and a comprehensive…]]></title>
            <link>https://aiadvances.org/breaking-barriers-and-achieving-cutting-edge-with-llm-t-b-developing-code-and-a-comprehensive-0f3d28fe8788?source=rss-707395aa8764------2</link>
            <guid isPermaLink="false">https://medium.com/p/0f3d28fe8788</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[customer-relations]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[telegram-bot]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[M Javadnejadi]]></dc:creator>
            <pubDate>Wed, 03 Jul 2024 20:09:46 GMT</pubDate>
            <atom:updated>2024-07-03T20:09:46.343Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Breaking Barriers and Achieving Cutting Edge with </strong>LLM-T-B<strong>: Developing code and a comprehensive concept to build a Telegram BOT that can be used across all businesses for various tasks</strong></h3><h4><strong>We are revolutionizing traditional call centers and customer relations by harnessing unprecedented artificial intelligence, especially LLMs.</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*13UnBSa9lsCkyFDWO_AoCA.jpeg" /><figcaption>This image was generated in <a href="https://ideogram.ai/t/top/1">Ideogram</a> using my prompt. You can see the power of LLM-T-B in it.</figcaption></figure><blockquote>Note: Before starting this article, it is important to state that the goal of presenting and developing this idea is not to eliminate Call Center jobs or any other jobs that could be affected by it. The sole purpose of this idea is to enhance productivity using new AI tools. This will improve the working conditions for employees in Call Centers or any other jobs that utilize <strong>LLM-T-B</strong> and will lead to greater customer satisfaction.</blockquote><blockquote><em>“I ask all those who read this article and all developers and AI enthusiasts, if you are interested in working on and developing </em>LLM-T-B<em>, to connect with me on Medium or </em><a href="https://www.linkedin.com/in/javad-nejadi-68776a228/"><em>LinkedIn</em></a><em> so that we can develop a product that will change the game soon. </em>The complete code for LLM-T-B, as discussed in this article, will soon be published on my <a href="https://github.com/mohamadj94">GitHub</a>.<em>”</em></blockquote><h3><strong>Introduction</strong></h3><p>One of the most crucial and significant departments in both large and small organizations is the Call Center. A Call Center is akin to the emergency room of a hospital, serving as the frontline in customer communication with companies. The comparison to an emergency room stems from the fact that most Call Centers, like emergency rooms, operate 24/7. Additionally, they are often the first point of contact for identifying problems, making them inherently stressful environments.</p><p>Often, Call Centers are undervalued. The typical mental image of a Call Center employee is someone with a headset, sitting at their desk, sipping tea or another beverage, while easily handling customer inquiries with a single button press on their all-access system. However, this is far from the reality. The most critical aspect of Call Centers is speed and time management.</p><p>The primary task that enhances the speed of response and reduces the duration of conversations, whether through chat or voice calls, is quick and accurate access to information that resolves the issue. Moreover, the number of personnel, especially in large company Call Centers, is usually high. Managing onsite and remote employees (since Call Centers are one of the jobs that can be performed remotely), particularly in quickly finding solutions to problems, can be the greatest advantage for a Call Center.</p><p>In this article, we aim to develop a system that, with the help of AI and specifically LLMs, can increase speed and reduce the response time leading to problem resolution. We intend to develop a product using LLMs and a Telegram BOT, which I will refer to as <strong>LLM-T-B</strong>. This BOT will create a reference system for the company that can also encompass other departments, meaning it will not be exclusive to the Call Center. Additionally, it will enable direct interaction with customers. Join me on this journey!</p><h3><strong>The First Task of the Telegram BOT!</strong></h3><p>The initial task for this LLM-T-B is to monitor the real-time status of the Call Center and manage employee breaks during their shifts. It&#39;s important to note that the following suggestions are optional and may differ between companies. Call Centers typically operate 24/7, so we will establish three shifts for LLM-T-B and specify the staff present during each shift. Additionally, we will create a feature that allows an employee to be added to a different shift if they plan to work overtime or need to switch shifts for any reason. The rules established for this can be adaptable and may change based on real-time conditions.</p><p>What does this mean? Every company has a system for handling calls. We want to integrate LLM-T-B with this system using an API and establish guidelines so that LLM-T-B can independently determine appropriate break times for employees based on the volume of incoming calls. The permissible break durations can vary based on the company’s policies, for example, <strong>“n”</strong> minutes for regular breaks and <strong>“x”</strong> minutes for immediate breaks. The guidelines can be configured such that, for instance, for every employee present during a shift, <strong>“b”</strong> employees can be assigned break time (<em>this may vary based on the company’s policies and the nature of calls</em>) because LLM-T-B adjusts capacity according to the volume of incoming calls. However, we will set a threshold to ensure that the number of breaks never decreases to zero.</p><p>Another rule is that if an employee is late returning from a break, they will receive the first warning after 1 minute and a second warning after 3 minutes. These warnings will be sent as notifications in the BOT. The company can decide how many warnings an employee can receive in a day and what actions to take in case of repeated delays. We will add a button called “<strong><em>Rest (dnd)</em></strong>” in the BOT. Pressing this button will display the message “<em>Your break time is over</em>,” and the employee will be notified of the current capacity.</p><p>If the capacity is full, the BOT will notify that the counter is over the limit and will not allow registration. The BOT can also be configured to announce the capacity in real time. An emergency capacity can be defined, as allowing each employee to use it once a day. A function ensures that if an employee uses this emergency capacity, they cannot use another emergency capacity until the end of their shift. Additionally, only one emergency capacity can be open at any time, with a 10-minute time limit.</p><p>During lunch and dinner breaks, different shifts can have varying break times. The break duration can be extended by <strong>“n+d”</strong> minutes during these periods. The scheduling system can set a 3-hour lunch period, during which each employee can take a break only once. If an employee exceeds this limit, a warning will be issued, and further break requests will be denied. If an employee takes too long of a break, error messages will be sent. Notifications for lunch/dinner breaks will be sent to available employees, not on calls. It will be emphasized that the designated break period will not be extended. After the designated break time, a message will be sent to all employees on the shift, and the new break capacity will be announced.</p><p>We will also create a reporting function to save a report of registered breaks in a database at the end of each shift.</p><p>The suggestions above are symbolic and can be adjusted by each company according to its conditions and internal policies. For very specific and urgent situations, administrative access can be granted for the BOT, allowing a human operator to modify settings in special cases. All the suggestions mentioned are completely flexible and can be easily changed based on the company’s decisions and policies. The purpose of mentioning these points is to emphasize how effectively and efficiently these potentials can be utilized. So far, we have defined basic and initial BOT rules. In the next section, we will implement this simple BOT using Telegram’s BotFather and Python code.</p><h3><strong>Implementing the Bot</strong></h3><p>In this stage, we need to create our Telegram Bot. Start by logging in to Telegram and searching for “<strong>BotFather</strong>”. Open the BotFather page and click the “<strong><em>Start</em></strong>” button. Once you do that, you will see instructions on the page. Choose the `<em>/newbot</em>` option. BotFather will prompt you to pick a Name and a Username for your Bot. The Name can be anything you want, but the Username must be unique and end with the word “bot”. We have chosen ‘<strong>ManagerBot</strong>’ as the Name and ‘<em>CallCenterManagerBot</em>’ as the Username. After creating the Bot, BotFather will provide you with an Access Token. This token is crucial as it is used to communicate with the Telegram API, so make sure to keep it in a safe place.</p><p>To implement the various rules mentioned earlier, we will use Python code. For this, I utilized `<strong><em>https://colab.research.google.com</em></strong>`. To connect to the Bot and use the Access Token, we need to install the `<em>python-telegram-bot</em>` library using the following command:</p><pre>!pip install python-telegram-bot</pre><p>Once we have completed the initial steps of creating and registering the BOT, we proceed by searching for the BOT’s name in Telegram. Upon finding it, we can start the BOT by pressing the start button. Additionally, in BotFather, there is a user interface that allows us to configure the initial settings of the BOT. It’s also important to enable some access permissions in BotFather settings to make the necessary changes to the BOT.</p><p>Please note that the steps mentioned above and the code required to build it might be expanded in future versions of this article. It’s essential to highlight that these steps do not involve AI and can be easily implemented using Telegram. In the next section, we will be exploring the main topic: the core functionality of the BOT and the amazing tasks we will accomplish with LLM-T-B. Stick around as we further develop it.</p><h3><strong>Ask me!</strong></h3><p>One of the most important features we want this bot to have is a section called &quot;<strong>Ask Me!</strong>&quot; One of the main concerns for individuals working in a call center is to find answers to customer questions as quickly as possible. This is also important for other companies. Consider having a company that performs software tasks or a specific organization with certain administrative procedures, internal rules, and processes. This is especially relevant for companies that hire interns or newcomers who still need to become familiar with the standard procedures and complete regulations of the job. Therefore, &quot;Ask Me!&quot; can be useful everywhere.</p><p>Call center experts typically have access to a wide range of resources and documents that they can use to find answers during calls. Finding the best answer, especially for new experts, is always a major challenge in technical call centers. Relying solely on human resources or numerous documents scattered across various sections to answer questions leads to increased response times, longer call durations, and a decrease in the quality of the process.</p><p>&quot;Ask me!&quot; is highly beneficial, especially for customer interaction, such as when setting up a Telegram BOT (as an example in my capacity working for an ISP). This form of communication makes it easy for customers to inquire about modems and other ISP services. Instead of having to call and potentially wait in a queue, customers can simply engage in a conversation with the BOT to get answers. This allows for quick insights into modem types and various processes that would otherwise require direct contact and more time for both customers and sales staff. This approach can also be applied to sales, organizational services, or any other products a company offers. Potential customers, like those looking to purchase a modem, can obtain valuable information from the BOT with just a few questions. With this knowledge, they can then engage in more comfortable and informed interactions with sales representatives. The ultimate goal is for customers to feel as if they&#39;re conversing with a real person as &quot;Ask me!&quot; communicates in a natural language that closely resembles human speech, significantly enhancing the user experience.</p><h3><strong>Applications of </strong>LLM-T-B</h3><p>Imagine if all the internal rules and processes of your company were as easy for AI language models (LLMs) to handle as a simple breakfast meal, especially for mid-sized or larger companies! After acquiring the LLM model, we can train it with the company’s data, documents, and tasks. All processes and rules can be easily tokenized and taught to the model. It can then be used for internal tasks and to answer questions from customers. For example, one of the most frequently asked questions in internet service providers (ISPs) that provide LTE internet is about coverage. Consider using LLM-T-B for the sales department, where one of the initial questions LLM-T-B asks is the location of potential modem buyers. It can easily check the coverage for them and provide the customer with information. More importantly, analyzing this valuable data can reveal areas with the highest and lowest demand for purchases, guiding more or less investment and targeted advertising in these regions.</p><p>Analyzing commonly asked customer questions provides us with incredibly valuable data. I&#39;m not referring to the FAQs section on a website, but rather the numerous questions that arise in Call Centers. In using both frequently asked questions and those that agents typically struggle to answer, we can continuously enhance LLM-T-B. This allows us to ensure that when customers ask these questions, LLM-T-B can provide responses that are even more natural than those of humans. For instance, LLM-T-B can assist with tasks such as changing the modem&#39;s name and password, guiding a customer through the registration process on the customer panel, or providing advice on how to improve the security of a specific modem model. Even routine questions such as how to renew plans, change ownership, or resolve ticket-related issues can be addressed clearly and step-by-step by LLM-T-B, thus reducing the necessity for direct contact.</p><p>Remember this text: &quot;These applications not only increase customer interaction and satisfaction, but they also significantly reduce the workload of various departments and enhance staff productivity. What is the most frequently asked question in your organization? Or in the call center, what is the most common question among new technical agents? Finding the answer to this question can provide valuable insights. It&#39;s worth mentioning that with Ask me! agents can get answers to necessary questions just by asking the bot, instead of searching for them manually. These are just a small part of the numerous applications of LLM-T-B* Today, we know that LLMs are becoming more powerful every day, enabling us to perform countless tasks with them.&quot;</p><h3><strong>Why LLM?</strong></h3><p>We can analyze the questions posed daily by agents or customers in the database designed for LLM-T-B. This analysis can greatly assist the company by identifying the most common problems faced by both customers and agents, as well as understanding the main reasons for customer inquiries. Additionally, it helps in pinpointing the areas where agents, especially new ones, need improvement in their responses. The stronger the agents, the faster the processes are completed. What is the solution? Undoubtedly, LLMs.</p><p>We don’t need a very large and powerful language model (LLM) because the documents within organizations are not extremely large. Once we use the LLM for some time, we will gather valuable information that can be used to retrain the LLM, making it more efficient and faster. This will increase the value of our LLM.</p><h3><strong>Which LLM?</strong></h3><p>There are various ways to utilize large language models (LLMs). One approach is to create a new model from the ground up. However, this task demands a significant amount of data and computational resources, which are typically only available to very large companies. Additionally, it’s not necessary to start from scratch, as there are alternative ways to leverage existing technologies.</p><p>For example, you can obtain an API from leading companies like <strong><em>ChatGPT</em></strong> or <strong><em>Anthropic</em></strong>, granting access to their LLMs. Another option is to utilize open-source models such as <strong><em>LLaMA 3</em></strong>, which offers a comprehensive architecture and access to a vast repository of information. However, even training a model like <em>LLaMA 3</em> can be quite resource-intensive and expensive.</p><p>An alternative approach is to utilize smaller models. There are resources accessible, with one of the most prominent options in recent years being the Hugging Face platform. Almost all models can be accessed there. All that is required is an API from Hugging Face to utilize the pre-trained models provided on the platform.</p><p>Sure, here is the revised text: &quot;What are the advantages? The most important benefit is increased security, as we can download these pre-trained models and use them locally on our systems. We only need to fine-tune and train them on the specific data to effectively respond to our BOT.&quot;</p><p>In the next section, we will learn how to implement, train, and connect our LLM to the Telegram BOT. Stay with me!</p><blockquote><strong>Note: The model we will use here is experimental, intended to demonstrate that this can be done. For main projects, we can use better and more secure models.</strong></blockquote><h3><strong>Implementation of </strong>LLM-T-B</h3><p>After trying out different LLM models and utilizing various APIs, I ultimately opted for models offered by Hugging Face. However, I encountered challenges in finding a model that could meet our requirements without being too costly or computationally expensive. As a solution, I discovered a suitable model on GitHub and utilized it instead.</p><p>Our model, which is based on the GPT-4 architecture, is called “<em>gpt4all-13b-snoozy-q4_0.gguf</em>”.</p><p><a href="https://github.com/Fatal3xcept10n/LLM-Telegram-Chatbot?tab=readme-ov-file">GitHub - Fatal3xcept10n/LLM-Telegram-Chatbot: AI chatbot for Telegram based on GPT4all</a></p><p>To begin, I obtained the model by using the codes provided on GitHub in Google Colab. We now have the base model with its initial training. Our next step is to integrate it with our Telegram bot.</p><p>To begin, we&#39;ll need to acquire the API_KEY for our Telegram BOT from BotFather to establish communication between the Python code we&#39;re developing and our BOT. The documentation on GitHub indicates that we&#39;ll need two libraries to use this model, as detailed below.</p><pre># Import the telegram bot API<br>!pip install python-telegram-bot==13.7<br>!pip install gpt4all==2.0.2</pre><p>To utilize the BOT, we need to import various libraries that are essential for carrying out specific parts of the code. By studying these libraries, it becomes evident why and for which tasks we will be using them. I’ve added these libraries over time as different tasks were incorporated. Below, you can find some of them along with detailed explanations.</p><pre># Importing necessary classes and modules from telegram.ext for managing a Telegram bot<br>from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackQueryHandler<br><br># Importing necessary classes and modules from telegram for managing inline buttons and keyboard<br>from telegram import InlineKeyboardButton, InlineKeyboardMarkup, ReplyKeyboardMarkup, KeyboardButton<br><br># Importing GPT4All library to use the GPT-4 language model<br>from gpt4all import GPT4All<br><br># Importing threading module for running concurrent threads<br>import threading<br><br># Importing googletrans library for translating text<br>from googletrans import Translator<br><br># Importing langid library for detecting language of the text<br>import langid<br><br># Importing logging module to log messages and events<br>import logging<br><br># Importing sqlite3 module to interact with SQLite databases<br>import sqlite3<br><br># Importing os module for interacting with the operating system<br>import os<br><br># Importing queue module to create and manage queues<br>import queue</pre><p>When developing your code, remember to include the Telegram API_KEY token. To proceed with using the BOT, we first need to import and initialize the model.</p><pre># Telegram bot token (replace with your bot token obtained from BotFather)<br>TOKEN = &#39;YOUR_BOT_TOKEN&#39;<br><br># Select LLM model from gpt4all<br>model = GPT4All(&quot;gpt4all-13b-snoozy-q4_0.gguf&quot;)</pre><p>We will use the following code to connect to the Telegram BOT and download the desired LLM model to our system, making it readily available. Next, we will add tasks to our LLM-T-B. The initial task I worked on was enabling the BOT to be capable of translating into the user’s language. For instance, our model is proficient in English and understands Persian but cannot respond in Persian. We have two approaches: the first is to train the model with a dataset containing Persian sentences and their translations into English. This method is challenging as it requires resources such as powerful hardware with strong GPUs or GPU servers available in the cloud, which can be costly. The second approach involves using the `<em>googletrans</em>` library and its `<em>Translator</em>` class. We need to install this library first.</p><pre>!pip install googletrans==4.0.0-rc1</pre><p>With the code snippet I will provide, we can create a rule for LLM-T-B. When a user writes in English, the responses will be in English, and when the user types in Persian, they will receive a Persian response. However, this approach may have some drawbacks, as it requires additional computation to translate the user input into English and then translate the English response into Persian.</p><pre># Translator instance<br>translator = Translator()<br><br>....<br><br>    # Detect language of user message<br>    lang, _ = langid.classify(user_message)<br><br>    # Translate user message to English if needed<br>    if lang == &#39;fa&#39;:<br>        translated_prompt = translator.translate(user_message, src=&#39;fa&#39;, dest=&#39;en&#39;).text<br>    else:<br>        translated_prompt = user_message<br><br>    # Add the prompt to the user&#39;s queue<br>    user_queues[chat_id].put(translated_prompt)</pre><p>The model generates responses in English, which can be translated into Persian using the provided code.</p><pre>    # Translate the response back to the user&#39;s language if needed<br>    response = user_contexts[chat_id][&#39;response&#39;]<br>    if lang == &#39;fa&#39;:<br>        translated_response = translator.translate(response, src=&#39;en&#39;, dest=&#39;fa&#39;).text<br>    else:<br>        translated_response = response</pre><h3><strong>Database</strong></h3><p>The next important step is to set up a database for the bot. There are several options available for this. We can use free or subscription-based databases. Free or low-cost databases like <strong>SQLite or PostgreSQL</strong> are good options. When using SQLite, the data is stored as a physical file on disk and will not be lost when the program is closed. However, if we want the database to be online and always accessible, we can use online storage services like Google Drive.</p><p>For using Google Drive as an online database, we can use Google Sheets as our database. The Google Sheets API can be easily used with Python. In the following section, we will see the steps for setting up an SQLite database and integrating it with the Telegram bot. SQLite is a lightweight, embedded database that does not require a server by default, making it suitable for small to medium-sized projects. In the code snippet below, which is part of the main LLM-T-B code, we will learn how to create a simple database.</p><pre><br># Function to delete and recreate the database<br>def initialize_database():<br>    # Check if the database file exists and remove it<br>    if os.path.exists(&#39;bot_database.db&#39;):<br>        os.remove(&#39;bot_database.db&#39;)<br><br>    # Connect to SQLite database (it will create the file if it doesn&#39;t exist)<br>    conn = sqlite3.connect(&#39;bot_database.db&#39;)<br>    cursor = conn.cursor()<br><br>    # Create the users table with columns for id, user_id, and first_name<br>    cursor.execute(&#39;&#39;&#39;<br>        CREATE TABLE users (<br>            id INTEGER PRIMARY KEY AUTOINCREMENT,<br>            user_id INTEGER UNIQUE,<br>            first_name TEXT<br>        )<br>    &#39;&#39;&#39;)<br><br>    # Create the questions table with columns for id, user_id, question, and answer<br>    # user_id column is a foreign key that references the user_id in the users table<br>    cursor.execute(&#39;&#39;&#39;<br>        CREATE TABLE questions (<br>            id INTEGER PRIMARY KEY AUTOINCREMENT,<br>            user_id INTEGER,<br>            question TEXT,<br>            answer TEXT,<br>            FOREIGN KEY (user_id) REFERENCES users (user_id)<br>        )<br>    &#39;&#39;&#39;)<br><br>    # Commit the changes and close the connection<br>    conn.commit()<br>    conn.close()<br><br># Initialize the database by calling the function<br>initialize_database()<br><br># Connect to SQLite database (check_same_thread=False allows for multithreading)<br>conn = sqlite3.connect(&#39;bot_database.db&#39;, check_same_thread=False)<br>cursor = conn.cursor()</pre><h3><strong>Buttons</strong></h3><p>The next step involves creating buttons for the BOT, which is optional. It is easy to integrate any button into the BOT to symbolically showcase the functionality of LLM-T-B. I plan to add three buttons to this bot:<strong> Start, Ask me!, and Help</strong>. In the code, I will specify the messages that should be displayed when the user presses each of these buttons. This task can even be delegated to the LLM.</p><p>When the user presses the Start button, they will be greeted with the message: “<strong><em>Hello (user’s username), welcome to the Ask me! BOT. If you have any questions, I would be happy to help. Just press the Ask me! button and ask your question</em>.</strong>” After pressing the Ask me! button, the bot will tell the user, “<strong><em>(user’s username), please ask your question so I can quickly respond.</em></strong>” Then, LLM-T-B will take the user’s questions and provide answers.</p><p>In addition, beneath each response that the BOT provides to the user, we will include an <strong>exit button</strong>. When this button is pressed, the user will receive a polite message thanking them for using the BOT and expressing eagerness to help them again. I will stick to three buttons for now, as I believe that a simpler and less cluttered user interface is more appropriate to avoid user confusion. I think the power and appeal of simplicity to attract more users can often surpass many elaborate features.</p><p>It is important to note that when creating buttons for your LLM-T-B, simply creating buttons and displaying messages to the user is not enough. For instance, the Start button was defined and present but did not function, or in another example, the exit button that I defined in the BOT displayed a message when pressed but did not perform any action. It took several attempts, including error checking, running, and restarting, to understand and fix these issues.</p><h3>start the LLM-T-B</h3><p>We need to test the BOT. I have tested it several times and encountered issues when testing it with different users. One problem is that when two users enter the BOT simultaneously, the BOT mistakenly thinks they are in the same environment. It doesn’t distinguish between users. For instance, if I ask a question and another person also enters the BOT and presses “Ask me!”, the BOT would display the response meant for the first user to the second user as well. To address this issue, we need to implement a queue mechanism for requests so that each user has a separate queue for their requests and responses. Additionally, we should use threading and Queue to manage these queues.</p><pre><br># Store the contexts and queues for each user<br>user_contexts = {}<br>user_queues = {}</pre><p>In this code, a queue and an event are created for each user to manage messages and responses separately. This approach helps segregate messages for each user, ensuring that they receive relevant responses to their queries. The sections of the code responsible for this are explained below: When a new message is received from a user, if the queue and event corresponding to that user don’t exist, they are created.</p><pre># Wait for response event to be set by conversation thread<br>    user_contexts[chat_id][&#39;response_event&#39;].wait()<br>    user_contexts[chat_id][&#39;response_event&#39;].clear()</pre><p>The code snippet below is intended to handle concurrent and separate conversations with multiple users. In this code, each user has a dedicated conversation loop that takes messages from the user’s queue, sends them to the LLM model for processing, generates a response, and then stores the response in the user’s context. A response event is triggered afterward. If the queue is empty and the conversation has ended, the loop will stop.</p><pre><br># Function to start the conversation loop<br>def startConversation(chat_id):<br>    global user_contexts, user_queues<br><br>    with model.chat_session():<br>        while True:<br>            try:<br>                prompt = user_queues[chat_id].get(timeout=5)<br>                print(f&quot;Working on prompt for user {chat_id}&quot;)<br><br>                # Generate response<br>                response = generateResponse(prompt)<br>                user_contexts[chat_id][&#39;response&#39;] = response<br><br>                print(f&quot;Finished processing for user {chat_id}&quot;)<br>                user_contexts[chat_id][&#39;response_event&#39;].set()<br>            except queue.Empty:<br>                if chat_id not in user_contexts or not user_contexts[chat_id].get(&#39;is_running&#39;, False):<br>                    break<br>        print(f&quot;Exited conversation loop for user {chat_id}&quot;)<br></pre><p>The function `<em>startConversation</em>` begins a conversation loop for a specific user identified by the `<em>chat_id</em>`. It uses global variables `<em>user_contexts</em>` and `<em>user_queues</em>` to manage user contexts and message queues. The `<em>with model.chat_session()</em>` ensures that a chat session is established and maintained with a large language model (LLM) throughout the conversation loop.</p><p>Within the `<em>while True</em>` loop, it tries to retrieve a message (`<em>prompt</em>`) from the user’s queue (`<em>user_queues[chat_id].get(timeout=5)</em>`). If the queue is empty, it waits up to 5 seconds for a new message. If no message arrives within this timeout, it raises a `<em>queue.Empty</em>` exception, which is handled by the `<em>try-except</em>` block.</p><p>If the queue remains empty and the user’s conversation is no longer active, the conversation loop ends. This design ensures that user messages are processed separately and concurrently, without continuously consuming system resources.</p><h3>Testing LLM-T-B</h3><p>After writing the LLM-T-B code, the next step is to execute it to see it in action on the Telegram bot environment. I tested the code on Google Colab for better performance and stable connectivity, but it is preferable to run it on a server, preferably a Linux server. After running the code and downloading the model on Colab, the code is executed line by line. Following the code execution, the bot should be started in the Telegram environment. I have two Telegram accounts named “<em>Javad</em>” with a capital “<strong>J</strong>” and “<em>javad</em>” with a lowercase “<strong>j</strong>” for testing purposes. Both Telegram accounts are on the same device and only differ in the capitalization of the username. I initiated the LLM-T-B start command, and in both environments and with different usernames, LLM-T-B easily provided correct answers to the questions posed. You can refer to the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O6E2J4d-Xh_pgGD37hjqqg.jpeg" /><figcaption>The image on the left with the username “javad” and the image on the right with the username “Javad” in both environments provided the correct responses.</figcaption></figure><p>In the image, you can see the bot starting by asking the user a question. The user then asks their question, and the bot connects to it using LLM to provide an answer. Below, you can see that each user has a unique ID assigned to distinguish them for LLM-T-B to recognize and easily categorize in the database. We have seen the implementation code and details of this task above.</p><pre>Received message from user: How accurate are the responses generated by your bot using the language model?<br>Working on prompt for user 6514170446<br>Finished processing for user 6514170446<br>Received message from user: What languages are supported for translation using your bot?&quot;<br>Working on prompt for user 1932960851<br>Finished processing for user 1932960851<br>Received message from user: Could you explain the security measures in place to protect user data when using your bot?&quot;<br>Working on prompt for user 6514170446<br>Finished processing for user 6514170446<br>Received message from user: What types of tasks or queries do you handle best?&quot;<br>Working on prompt for user 1932960851<br>Finished processing for user 1932960851</pre><p>In the text below, there are two IDs, 1932960851 and 6514170446, which belong to two different users. For testing LLM-T-B to see if the model works well even without training and just with the translated code, I conducted some Q&amp;A in Persian, as shown in the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ip2FD3auQ7HvKCYWfQ4wVw.png" /><figcaption>This is an image of LLM-T-B, which was tested for its translation capability in the bot environment.</figcaption></figure><p>It’s important to address any issues that may arise during the development of the model and the bot. One common problem with LLMs is “hallucination,” and we must work to minimize this issue. An example of this can be seen in the image below. It’s worth noting that the model used in this article has not undergone additional training and is not connected to the Internet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*hbOst3yIdtWVT6SCx5iU5g.jpeg" /><figcaption>An example of the issues that LLMs might encounter. This image is taken from the LLM-T-B environment.</figcaption></figure><p>When running bot code in Google Colab, you might encounter significant issues such as crashing and session resetting. This is due to the less efficient performance of Google Colab compared to running code on Linux or a powerful server. If you face this problem, simply rerun the code. Furthermore, each time you reset or change the session in Colab, you will need to reinstall the libraries.</p><h3><strong>Security of </strong>LLM-T-B</h3><p>It is crucial to consider the security of the BOT, especially when it is publicly accessible and used for sensitive purposes like customer communication or sales. The initial issue to address is the underlying LLM. The models mentioned in this article, including pre-trained and open-source models, are downloaded and deployed locally for customization. Consequently, the model itself can be highly secure.</p><p>The next concern involves the users who interact with the chatbot and may try to launch attacks. Use models from trusted and secure sources. While open-source models can be secure, make sure to download them from reputable sources. Keep models and related software regularly updated to take advantage of the latest features and security fixes.</p><p>Please restrict access to the BOT so that only authorized users can use it. This can be achieved through whitelists or two-factor authentication. For example, technical support for modems should only be accessible to individuals with registered modems whose information is in the company’s database. Alternatively, a verification process should be performed where user information is collected before accessing the model. If users have any questions regarding the purchase of a modem, their messages should not be directly connected to the LLM model. Instead, their queries should be received in a BOT environment that does not permit access to the LLM. The user’s query should be received in the database and sent separately for processing to the LLM, and the generated response should be returned to the database and sent back to the BOT environment.</p><p>To ensure the security of the BOT server, all communications should be conducted via <strong>HTTPS</strong> to encrypt data during transmission. Using DDoS protection services can help make the BOT resistant to sudden and heavy attacks.</p><p>It’s important to log all activities and requests and continuously monitor them to quickly identify and stop any suspicious activity. Inputs should be validated to prevent malicious data entry, which includes using input filters to prevent <strong>SQL</strong> injection and <strong>XSS</strong> attacks.</p><p>To maintain privacy, securely store user data and prevent unauthorized access. This includes encrypting sensitive data and restricting access rights. Educate users about security and potential risks so they can play their part in maintaining security.</p><h3><strong>Conclusion</strong></h3><p>In this article, an attempt was made to introduce an idea that is currently gaining attention in the AI world. The points discussed in this article touch on only small aspects of LLM applications. Yann LeCun advises those learning AI or starting, “<a href="https://x.com/ylecun/status/1804196833033621904"><strong>DO NOT WORK ON LLMs</strong></a><strong>,</strong>” suggesting that creating LLMs from scratch and working directly on building them may not be very reasonable. However, using them for various applications, and tasks, and developing new products with LLMs can be very beneficial. The approach followed in this article focuses more on having a very simple user interface to assist customer relations experts. This speeds up tasks, improving response quality and increasing customer satisfaction quickly, a matter explored thoroughly in the introductory sections of the article.</p><p>Many tasks can be added to LLM-T-B briefly:</p><p><strong>1. Online Chat Tasks</strong>: online chat is a vital communication tool for businesses, big and small. Many major companies use it on their websites. One major challenge faced in online chat is the delay in response times, which has been improved with LLMs. However, we can focus on using past chat data with customers to train the model to provide real-time, natural language responses, so customers do not feel they are chatting with AI. Additionally, utilizing sentiment analysis tasks, at which LLMs excel, can be very valuable. Analyzing this information can greatly help us provide better customer service and pay more attention to the company’s strengths and weaknesses. I have extensive experience in online chat and am very familiar with it. This approach can significantly increase the speed and 24-hour support coverage, reduce human error, and improve customer satisfaction more than ever.”</p><p><strong>2. Ticketing Tasks</strong>: I have encountered this issue many times, and it can sometimes lead to customer dissatisfaction because it is time-consuming. LLM-T-B can be developed in a way that allows customers to easily find comprehensive solutions to their problems, and even get the confirmation they need instantly or in a short amount of time if they need to use an identification card. By automating more processes and improving speed and quality through high model accuracy, customer satisfaction can be further improved.</p><p><strong>3. Potential Customer Tasks</strong>: Those who have not yet taken steps to purchase or use the company’s products, but intend to do so, can be directed to the sales department. The department can gather initial information from these individuals for product presentation, or follow up with them to persuade them to make a purchase. Restructuring the sales department has proven to be very effective and has even facilitated increased use. We are very pleased with the results!”</p><p>In conclusion, it can be said that this idea has potential for use in various other contexts, producing positive results. Thank you for reading this article and sticking with me until the end. I would love to hear your thoughts on this piece. Thank you!</p><p>Thank you for accompanying me on this journey into the world of deep learning.</p><p>The link to the article in Persian is available on <a href="https://vrgl.ir/178bx">virgool.io</a>.</p><p>If you’re interested, you can check out my other article, “<a href="https://medium.com/ai-advances/transformers-ais-paintbrush-to-paint-a-new-world-vision-transformer-c51b162bba36">Transformers: AI’s Paintbrush to Paint a New World (Vision Transformer)</a>”</p><p><a href="https://medium.com/@reza.shokrzad/decoding-commonalities-finding-the-longest-common-prefix-in-strings-python-code-ff1e496d32be">Decoding Commonalities: Finding the Longest Common Prefix in Strings (Python Code)</a></p><p>I hope you’ve enjoyed the content.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0f3d28fe8788" width="1" height="1" alt=""><hr><p><a href="https://aiadvances.org/breaking-barriers-and-achieving-cutting-edge-with-llm-t-b-developing-code-and-a-comprehensive-0f3d28fe8788">Breaking Barriers and Achieving Cutting Edge with LLM-T-B: Developing code and a comprehensive…</a> was originally published in <a href="https://aiadvances.org/">AI Advances</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Transformers: AI’s Paintbrush to Paint a New World (Vision Transformer)]]></title>
            <link>https://aiadvances.org/transformers-ais-paintbrush-to-paint-a-new-world-vision-transformer-c51b162bba36?source=rss-707395aa8764------2</link>
            <guid isPermaLink="false">https://medium.com/p/c51b162bba36</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[transformer-model]]></category>
            <category><![CDATA[vision-transformer]]></category>
            <dc:creator><![CDATA[M Javadnejadi]]></dc:creator>
            <pubDate>Thu, 30 May 2024 19:58:30 GMT</pubDate>
            <atom:updated>2024-05-30T19:58:30.181Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Delving into the depths of Transformer architectures and their applications beyond text, this article explores the transformative power of Transformers in the realm of photo and video generation and processing.</strong></h4><blockquote>“Morpheus:Have you ever had a dream, Neo, that you were so sure was real? What if you were unable to wake from that dream? How would you know the difference between the dream world and the real world?”</blockquote><blockquote><a href="https://youtu.be/-n0hKTizFwY?si=gqxizXS0RI63g7qW">The Matrix (1991)</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6hoydBchqSGMUqhWzLj2Pg.jpeg" /><figcaption>The robotic face you see in the image is that of the famous contemporary painter Picasso, generated using my prompt with <a href="https://ideogram.ai/t/top/1">Ideogram</a>.</figcaption></figure><h3><strong>Overview</strong></h3><p>Undoubtedly, one of the most important topics currently captivating minds and continually evolving is the generation of images, videos, and text using artificial intelligence. Large Language Models (LLMs) have demonstrated their remarkable capability in text generation. Many of their issues with text production have been resolved. However, a major challenge with LLMs is that they sometimes produce hallucinated responses.</p><p>The recent introduction of new models like multimodal LLMs, such as the newly released GPT-40, has been particularly astonishing. OpenAI is certainly changing the game. Additionally, Google’s powerful model, Gemini 1.5 Pro, has greatly shifted our perceptions. Consequently, we can see that models are improving. The wheel has been invented, and now it must be refined.</p><p>Initially, LLMs were developed for translation tasks. Now, we see them performing various tasks, with the trend moving towards multimodal models. Transformers’ robust and significant architecture has made all of this possible. In my previous article, titled “Transformer Is All You Need,” we thoroughly and deeply explored the Transformer architecture for text.</p><p>Another task that Transformers can perform is image generation, as seen in products like DALL-E, Midjourney, or Ideogram. These models take text prompts and generate images. The recently released LlaMa 3 model generates images while writing the text prompt, changing the image as we modify the text.</p><p>But even more astonishing is video generation from text. A few months ago, OpenAI introduced a product called <strong>Sora</strong>. It is incredibly impressive and stunning, capable of producing high-quality, highly realistic images and even creating other worlds. The first thing that came to my mind when I saw it was the movie “<strong>The Matrix</strong>.”</p><p>In this article, we want to look from the beginning at the idea of generating images and then videos from text, tracing their evolution. We aim to understand image generation first, followed by video generation, and examine the architecture used for these tasks. Do we see the footprints of Transformers again? Let’s scratch the surface together. Join me in this exploration.</p><h3><strong>History</strong></h3><p>The first films were produced in the 1880s, astonishing audiences and laying the foundation for the powerful film industry we know today. The concept of using artificial intelligence (AI) in film production emerged in the early 20th century, gaining traction with the rise of computers. In 1960, John Whitney pioneered computer animation by founding Motion Graphics Incorporated and using his analog computer to create film sequences, television titles, and advertisements. <strong>IBM</strong> recognized his contributions by awarding him its first artist-in-residence position in <em>1966</em>. Over the years, various articles on computer-generated film and animation were published, paving the way for the use of AI in film production and performing arts as we know it today. Advancements in the <em>2000s </em>and <em>2010s,</em> including deep learning algorithms and Generative Adversarial Networks (GANs), have further advanced the use of AI in creating and editing digital content. The next section will examine the feasibility of image generation using Transformer architectures.</p><h3><strong>TransGANs</strong></h3><p>Generative Adversarial Networks (GANs) were introduced by <em>Ian Goodfellow</em> and colleagues in <em>2014</em>, before Transformers, for image processing and other tasks.</p><p><a href="https://arxiv.org/abs/1406.2661">Generative Adversarial Networks</a></p><p>The concept of Generative Adversarial Networks (GANs) predates Transformers and involves two deep neural networks engaged in a zero-sum game. The first network is the Generator, which creates synthetic samples, while the second is the Discriminator, tasked with distinguishing real samples from synthetic ones. The Generator’s objective is to produce samples that can deceive the Discriminator, making it unable to differentiate between real and synthetic samples.</p><p>The integration of Transformers with GANs, known as TransGAN, demonstrates that Transformers can serve as both the Generator and the Discriminator in GANs. These models harness the strengths of Transformers in capturing the intricate features of data. This approach was detailed in a paper of the same name presented in <em>2021 </em>by<em> Yifan Jiang, Shiyu Chang, </em>and<em> Zhangyang Wang.</em></p><p><a href="https://arxiv.org/abs/2102.07074">TransGAN: Two Pure Transformers Can Make One Strong GAN, and That Can Scale Up</a></p><p>TransGAN is short for Transformer Generative Adversarial Networks. This model is a type of GAN that utilizes the Transformer architecture for both the Generator and the Discriminator. Unlike traditional GANs, TransGAN does not use CNNs for either the Generator or the Discriminator, instead employing a Transformer structure for both.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*43d2LIS1QQU2Bz4UISnmcw.jpeg" /><figcaption>This image clearly illustrates the architecture of TransGAN and the structure of the Generator and Discriminator. The input image is a 3x3 colored photo. <a href="https://neurohive.io/en/state-of-the-art/transgan/">Suorce</a></figcaption></figure><h3>Generator</h3><p>In a TransGAN, the Generator uses the Transformer architecture to generate sequences of data. The Generator starts with a random noise input, which is typically a vector with random values from a Gaussian (normal) distribution. This noise input is transformed into a higher-dimensional feature space. This stage involves several Feed-Forward and MHA layers.</p><p>The Transformer-based Generator produces data sequences step by step. In each step, the Generator generates a part of the data (e.g., a pixel of an image) and then uses this output as input for the next step. The attention mechanism helps the Generator model <strong>long-term dependencies</strong> and the complexities present in the data.</p><p>After generating the complete data sequence, these sequences are converted into a complete sample (e.g., a full image). This conversion includes reconstructing complex features and final details.</p><h3>Discriminator</h3><p>The Discriminator in TransGAN is responsible for determining whether the samples generated by the Generator are <strong>real or fake</strong>. It uses the Transformer architecture to analyze the generated data sequences.</p><p>Initially, the Discriminator receives samples that can be either real or fake images. These samples are input into the model as sequences of image patches. Each patch represents a small section of the image, for example, a <em>16x16</em> pixel block. Each image patch is first converted into a vector representation. This vector representation is typically obtained through an Embedding Layer, which converts each patch into a vector of specified dimensions. These vectors are then combined with Position Embeddings to retain the spatial information of each patch.</p><p>The encoded patch sequences are then input into several Multi-Head Attention (MHA) layers. These layers allow the Discriminator to model long-term dependencies and the relationships between different patches of the image. MHA helps the model attend to different features of the image simultaneously.</p><p>The output from the attention layers is input into several Feed-Forward layers. These layers extract and process combined features, resulting in a more complex and enriched representation of the image. The final outputs from the Feed-Forward layers are then input into an Aggregation Layer. This layer combines all the extracted features into a comprehensive representation. This comprehensive representation is then connected to a final layer, such as a Dense layer, which makes the final decision on whether the image is real or fake.</p><p>Using Transformers in GANs has shown promising results. However, the efficiency of TransGAN compared to other methods may be limited by its dependence on more computational resources and the need for larger training datasets. In other words, TransGAN may perform well in environments with sufficient computational resources and abundant training data.</p><h3><strong>ViTGAN</strong></h3><p>The ViTGAN model is a novel deep learning model for image generation, introduced by <em>Kwonjoon Lee</em> and colleagues in <em>2022</em> in a paper.</p><p><a href="https://arxiv.org/abs/2107.04589">ViTGAN: Training GANs with Vision Transformers</a></p><p>This model combines Transformer models and Generative Adversarial Networks (GANs) and can produce realistic and high-quality images. The ViTGAN model uses a Transformer model as an encoder. This model processes the sequence of input tokens and produces a hidden vector that stores information about the image content. ViTGAN utilizes a GAN network. The generator converts the hidden vector into an image, while the discriminator tries to determine whether the image is real or fake. These two networks are trained simultaneously so that the generator can produce more realistic images and the discriminator can better distinguish fake images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X15_eyINrWGILxZQm2Z2Ug.png" /><figcaption>Both the generator and discriminator in ViTGAN can utilize the Vision Transformer (ViT) architecture. On the generator side (left), it transforms random input patches into an image. This process includes several transformer layers that convert the random inputs into an output image. On the discriminator side (right), it can use the same ViT architecture to process images. It converts the image patches into tokens and then uses transformer layers to decide whether the input image is real or generated. <a href="https://arxiv.org/pdf/2107.04589">Source</a></figcaption></figure><p>One of the advantages of ViTGAN is its ability to generate high-quality images comparable to real images. It can also be used to generate various types of images, including faces, landscapes, and objects, making it suitable for producing Deepfake images. ViTGAN allows users to control the images by adjusting different model parameters.</p><p>However, like any model, ViTGAN has its drawbacks. The first is complexity. ViTGAN is a complex model that can be challenging to train and use, requiring a large amount of data for training. It can also be slow, especially when used to generate high-resolution images. Among its most important applications is creating visual content for websites, social networks, and other platforms, as well as enhancing the quality of existing images, such as increasing resolution or removing noise. It can also be used to create new image formats, such as 360-degree images or interactive images.</p><p>ViTGAN is a new model for image generation that has the potential to completely change how images are produced. However, before it can be widely adopted, some challenges related to complexity, data requirements, and speed need to be addressed.</p><h3>Before ViT</h3><p>Before the introduction of the Vision Transformer (ViT) architecture, many image processing tasks such as object detection, image captioning, and image generation could be implemented using models like Convolutional Neural Networks (CNNs) or generative models such as Generative Adversarial Networks (GANs) and Variational Autoencoders (VAEs).</p><p>For example, object detection in images uses CNNs. One of the most well-known is <strong>YOLO (You Only Look Once)</strong>, a CNN architecture that operates directly on the entire image as input and detects objects quickly and accurately. Another architecture is <strong>R-CNN (Region-based Convolutional Neural Networks)</strong> and its successors, such as <strong>Fast R-CNN </strong>and<strong> Faster R-CNN</strong>. These models identify interesting regions in an image and then apply CNNs to detect objects in these regions, achieving good performance in object detection.</p><p>For image captioning, a combination of CNNs and RNNs was typically used. First, a CNN was used to extract features from the image. Then these features were fed into an RNN or LSTM (Long Short-Term Memory) network to generate descriptive text.</p><p>For image generation, generative models like GANs (Generative Adversarial Networks) were used. This model includes two networks — generator and discriminator — that compete with each other. The generator creates new images, and the discriminator tries to distinguish the generated images from real ones. Also, VAE (Variational Autoencoder) is another type of generative network used to produce new data by learning the distribution of the input data.</p><h3>ViTGAN Vs TransGAN</h3><p>ViTGAN and TransGAN both incorporate elements from GANs (Generative Adversarial Networks) and Transformer architectures, but they differ in key aspects. In ViTGAN, the Vision Transformer model serves as the primary component of the generator, while CNNs (Convolutional Neural Networks) may still be utilized in the discriminator. This architecture makes use of self-attention to effectively capture image details. ViTGAN aims to enhance the quality of generated images by leveraging the strengths of Transformers in modeling long-term relationships between pixels.</p><p>On the other hand, TransGAN exclusively employs Transformer architectures without depending on CNNs. This is a significant departure from the norm, as most GAN models incorporate CNNs to some extent. TransGAN utilizes Transformer blocks in both the generator and the discriminator. The primary objective of this model is to address learning and stability challenges commonly associated with GANs by leveraging the inherent self-attention mechanisms in Transformers.</p><p>In summary, while both ViTGAN and TransGAN integrate GAN and Transformer concepts, ViTGAN combines Transformers with CNNs, especially in the discriminator, to enhance image generation quality. TransGAN, on the other hand, relies solely on Transformer architectures for both the generator and discriminator, aiming to resolve common GAN challenges through the advanced capabilities of self-attention in Transformers.</p><h3>After “Attention is All You Need!”</h3><p>After the publication of the paper “Attention is All You Need,” which introduced the development of the Transformer architecture, many articles and research studies were presented on using this architecture for generating videos and images. In <em>2018, Niki Parmar</em> and others proposed the idea of using the Transformer architecture for image generation in a paper titled “<strong>Image Transformer</strong>.”</p><p><a href="https://arxiv.org/abs/1802.05751">Image Transformer</a></p><p>The Transformer architecture, instead of using linear sequences for text processing, utilizes the attention mechanism to learn relationships between words in a sentence. The “Image Transformer” paper demonstrated that the Transformer architecture can be used for image generation by replacing words with <strong>pixels</strong> and using the attention mechanism to learn the relationships between pixels in an image. This allowed the Image Transformer to understand image patterns and generate new images with styles and content similar to the input images. This paper inspired much research in this area and contributed to the development of new and more advanced methods for image generation with AI, such as GANs (Generative Adversarial Networks) and Diffusion Models.</p><p>The Image Transformer architecture offered several advantages over previous image generation methods, including higher image quality and more details. It also allowed users to have more control over the content of the generated images using different parameters. Most importantly, it was more computationally efficient and could generate images faster. Currently, we see the applications of Image Transformer in a wide range of tasks, such as generating artistic, fantasy, and abstract images, editing images (such as changing colors, adding details, and removing objects), generating realistic graphics in video games, producing realistic images and videos for use in virtual and augmented reality, and many other applications that are continuously being updated and improved.</p><h3>Embedding Layers in Image Transformer</h3><p>The Image Transformer uses embedding layers, but they are different from the embedding layers in Transformer models for processing text. In Image Transformer, pixels and image information must be converted into a suitable vector space. This is typically done by initial CNN layers, followed by an embedding layer. The embedding layer transforms the extracted features into vector space suitable for use in Transformer networks.</p><p>After the embedding stage, the steps in Image Transformer are similar to those in text Transformers. The first stage is self-attention, aided by techniques like Positional Encoding, which helps the model understand the relative positions of each patch in the image. The model then focuses on important parts of the image. Next is the Feed-Forward stage, which helps the model transfer information from previous layers to subsequent layers. The final stage involves a suitable output layer for the specific task at hand, such as image classification or object detection. These stages are carried out in the Encoder.</p><h3>Encoder-Decoder Image Transformer</h3><p>In the Image Transformer architecture, the Encoder is responsible for converting the input (in this case, images) into a feature space. The Decoder, on the other hand, is responsible for converting the feature space into the output image. The Encoder in the Image Transformer utilizes a standard Transformer architecture with several modifications tailored for processing images. These modifications may include adjustments to the layers or the addition of new layers to better suit the characteristics of images. For example, when processing images using the Transformer architecture, CNN layers or Multi-head Attention (MHA) layers are typically used instead of the self-attention layers employed in text-based Transformer architecture. Additionally, the architecture and size of the network may be adapted to accommodate the volume and complexity of the images.</p><p>Similarly, the Decoder in the Image Transformer employs a standard Transformer architecture with several modifications to facilitate image generation. In contrast, the Decoder in text-generating Transformers may use the standard Transformer architecture or modified architectures like autoregressive Transformers.</p><p>For example, if we were to use an Image Transformer to generate an image of a cat based on a descriptive sentence, the Encoder would process the descriptive sentence and extract information about various features of the cat, such as shape, color, and size. Spatial attention would aid the Encoder in focusing on crucial parts of the sentence, such as words referring to the color, shape, and size of the cat. Subsequently, the Decoder would utilize the information extracted by the Encoder to generate an image of a cat with the features described in the sentence.</p><h3>Image Captioning</h3><p>When using a text-generating Transformer to describe an image, the model must be able to identify important information from the image and present it in a textual form. In this task, the Encoder block processes the image and extracts information about objects, colors, and various textures present in the image. Sequence-based attention helps the Encoder focus on important parts of the image, such as objects and key details. The Decoder then uses the information extracted by the Encoder to generate a sentence that describes the image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*xgF7zVtjiY8jRwYCYfOh5A.jpeg" /><figcaption>Here are the steps of Image Captioning using Transformer architecture. <a href="https://medium.com/@kalpeshmulye/image-captioning-using-hugging-face-vision-encoder-decoder-step-2-step-guide-part-1-495ecb05f0d5">Source</a></figcaption></figure><p>For instance, if there is an image of a dog in a yard, the model should be able to extract information such as the type of dog, color, fur texture, size, position in the image, and possibly the activity the dog is engaged in (e.g., sleeping or playing) and describe it in a sentence consistent with this information. An example sentence might be: “A white dog with long fur is playing in the yard.” In this sentence, important information from the image (the dog’s color, fur texture, position in the image, and activity) is described textually.</p><p>Next, we will explore the applications and functioning of Transformers for generating or interpreting videos. Stick around for that!</p><h3>Comparison of Image Transformer with text-generating Transformers</h3><p>These two architectures have similarities and differences. Both Image Transformers and text-generating Transformers use the attention mechanism to focus on specific parts of the input data while processing and generating output. Both architectures use an Encoder-Decoder structure. The Encoder processes the input data, and the Decoder uses the information extracted by the Encoder to generate the output. Both architectures use deep neural networks with multiple layers to learn complex relationships between data.</p><p>However, the differences between these two architectures set them apart, primarily due to their tasks. The Image Transformer is designed for processing and generating images, whereas text-generating Transformers are designed for processing and generating text, so the type of data they handle is different.</p><p>One of the most important differences is that in the Image Transformer architecture, spatial attention is used to focus on different parts of an image during processing and generation. Spatial attention consists of two main stages. The first stage is calculating the attention values, where the model computes an attention value for each pixel in the image. This value indicates how much attention the model gives to that pixel. Attention values can be predicted using small neural networks for each pixel in the image or using functions like the Gaussian function to calculate attention values based on the distance between the pixel and the center of the image.</p><p>After calculating attention, these values are applied to adjust the weight of the information related to each pixel. This means that pixels with higher attention values will have a greater impact on the model’s output. Applying attention values can be done in various ways, such as multiplying the attention value of each pixel by the corresponding pixel weight or computing a weighted average of information from all pixels.</p><p>The numerous advantages of using spatial attention include helping the model focus on important parts of the image to produce more accurate outputs, ignoring noise and irrelevant information in the image, and preserving detailed and subtle features in the final output. In contrast, text-generating Transformers use sequential attention to focus on different words in a sentence.</p><h3><strong>question</strong></h3><p>The question we’re exploring is why Transformer models weren’t used for images in the past. There are a few main reasons to consider. Firstly, processing images with Transformers required a large amount of memory and computations due to the computational complexity, which was challenging given the large dimensions of images. Another reason is that image data is less structured compared to language, which has a temporal sequence. Images have a different structure that requires adaptation and tuning of the models. Additionally, Transformer models require a vast amount of properly labeled data for training, which was difficult to access in the past. In the next section, we’ll delve into the architecture of Video Transformer Networks (VTNs) for video generation using Transformers. Stay tuned!</p><h3><strong>Video Transformer Networks (VTNs)</strong></h3><p>In <em>2021</em>, a research paper authored by <em>Daniel Neimark, Omri Bar, Maya Zohar, and Dotan Asselmann </em>was published. The paper discusses Video Transformer Networks (VTNs) and focuses on advancing the Transformer architecture for video generation. It aims to develop the Transformer architecture for video production.</p><p><a href="https://arxiv.org/abs/2102.00719">Video Transformer Network</a></p><p>Before the publication of this paper, most Transformers were mainly used for natural language processing and text generation. However, “Video Transformer Networks” presents a specialized Transformer architecture designed for video generation. This architecture can take sequences of images as input and create new videos. The model uses self-learning capabilities to understand temporal patterns and multimedia perspectives, allowing it to produce more realistic and higher-quality videos. Let’s take a closer look at how this architecture functions. In the VTN architecture, similar to traditional Transformer models, an Encoder-Decoder structure is employed to process and generate sequences. The Encoder extracts features from the input video frames, while the Decoder generates new video sequences.</p><h3><strong>The method of Embedding in VTNs</strong></h3><p>In Video Transformer Networks (VTNs), embedding is utilized in both the Encoder and Decoder. Embedding essentially converts textual or visual inputs into a lower-dimensional space that the model can access, reducing the amount of information needed for processing while preserving important details.</p><p>In the Encoder, embedding converts image or video features into the embedding space to extract essential information. In the Decoder, embedding is used to transform previous outputs (such as words in text models or frames in video models) into the embedding space, allowing the model to understand and use the relevant information for generating the next output.</p><p>Additionally, VTNs extensively use self-attention mechanisms to capture long-range dependencies within and between video frames. This means that the model can recognize and understand temporal and semantic relationships between frames, enabling it to produce coherent and realistic videos. This capability allows the model to learn complex temporal relationships and generate consistent video sequences.</p><h3><strong>The function of self-attention in VTNs</strong></h3><p>VTNs (Video Transformer Networks) calculate an attention matrix for each frame in a video sequence. This attention matrix is used to assign a weight to each frame, representing its importance in generating the current frame. By considering the relationships between frames and using information from all frames in the sequence, VTNs can produce a coherent video, capturing complex temporal relationships between frames.</p><h3>Applications of VTNs</h3><p>The introduction of Video Transformer Networks (VTNs) has opened new avenues for research and development in the field, leading to significant advancements in video generation capabilities. VTNs can generate realistic videos that are temporally and spatially coherent. This capability is particularly useful in applications such as content generation, animation, and video editing. They can assist models in better understanding the content of videos, which can be beneficial in tasks such as video analysis, object detection in videos, surveillance videos, and motion prediction.</p><p>With a single still image, VTNs can generate a sequence of videos conveying the same concept. They can reconstruct missing or corrupted regions of a video sequence while preserving the coherence of surrounding frames. VTNs can enhance the clarity of low-quality videos by generating high-resolution sequences that preserve the main content and details.</p><p>One of the significant applications of VTNs is generating videos from textual prompts or other types of data. Advanced models introduced today, such as <strong>Vidu and Sora</strong>, leverage this capability to produce realistic and complex videos.</p><p>The introduction of VTNs has inspired numerous follow-up works that delve deeper into investigating and refining the application of Transformer architectures for video generation. Researchers strive to create more efficient models capable of processing spatial and temporal information simultaneously and with greater accuracy. For example, the use of Temporal Attention Mechanisms aims to improve temporal attention mechanisms for better modeling of relationships between video frames, or Spatiotemporal Transformers that extend Transformer models to process spatial and temporal information simultaneously.</p><p>In comparison to older models, VTNs have addressed weaknesses. For instance, recurrent neural networks (RNNs) and LSTMs, which were traditionally used for processing temporal sequences, often struggle to capture long-term dependencies effectively. VTNs overcome these limitations by utilizing Self-Attention mechanisms. Transformers generally exhibit better scalability compared to RNNs and can effectively handle larger and more complex datasets.</p><h3>The difference between VTNs and Image Transformation</h3><p>Image Transformation deals with modifying individual images, while VTNs are used to create sequences of videos and need to consider the connections between frames over time. In VTNs, self-attention is specifically used to capture these long-range dependencies, including subtle changes in consecutive frames or overall movements throughout the video. On the other hand, image transformation techniques mainly focus on the spatial features of images. Therefore, the key distinction between image transformation techniques and VTNs lies in how they handle temporal and spatial information.</p><h3><strong>A Video Vision Transformer </strong>(ViViT)</h3><p>The ViViT architecture, introduced in a 2021 paper by Google Research, is designed to process and analyze video data using transformer models.</p><p><a href="https://arxiv.org/abs/2103.15691">ViViT: A Video Vision Transformer</a></p><p>In the ViViT architecture, video processing is done using the Transformer architecture without the need for CNNs for initial feature extraction. The structure of Encoder-Decoder in Vision Transformers (ViTs) for processing video and images is similar, but due to the different nature of the input data (image vs. video), there are variations in implementation and applications of this architecture. For instance, the Encoder structure in VTNs must consider both temporal and spatial dimensions. Encoder-Decoder structures for video (such as ViViT — Video Vision Transformers) usually involve adjustments to simultaneously model temporal and spatial information. Since video is dynamic and contains temporal information, these models generally use multiple frames as input. Videos are sequences of frames (static images) displayed quickly one after another to show motion and changes over time, and these features are converted into lower-dimensional vectors (embeddings). These vectors contain crucial information from each frame that the model needs to comprehend the temporal and spatial relationships between frames.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sXPO4FhhJXP4FyQoKp66LA.png" /><figcaption>This image, taken from the original paper, clearly illustrates the functionality of ViViT. On the left, we see a clear depiction of the architecture of an Encoder block, where the input tokens are the image frames. On the right, you can observe corresponding decompositions and analyses of different Attention patterns over time and space. <a href="https://arxiv.org/abs/2103.15691">Source</a></figcaption></figure><p>Moreover, they employ the Self-Attention mechanism to extract features and understand relationships between patches (in images) or frames (in videos). For videos, in addition to focusing on spatial relationships between patches, modeling temporal relationships between frames is also essential. This is typically achieved using Attention mechanisms on the sequence of frames. This mechanism enables the model to consider both temporal and spatial relationships between frames. At each stage, Self-Attention computes a matrix of weights indicating how each frame is related to other frames. This matrix helps the model extract important information from the entire video sequence. Due to the extra temporal dimension, this usually requires more computational complexity and resources compared to images.</p><p>The processing steps in the Decoder section of ViViT generally include similar steps to the Decoder in other Transformer models. Initially, the input tokens are transformed into feature vectors (Embedding). For video, these tokens can represent features extracted from frame patches. Adding spatiotemporal information to the feature vectors is the Positional Encoding step, enabling the model to understand the position of each token in the sequence.</p><h3><strong>The crucial step of Masked MHA in the ViViT</strong></h3><p>The process of generating videos in ViViT models is similar to generating text sequences, but with the distinction that each step produces a video frame as output. The Decoder section is usually used to generate outputs like classification labels, video descriptions, or similar tasks. However, for creating video frames from scratch (video generation), other architectures such as <strong>Video GANs</strong> or <strong>Video Autoencoders</strong> are more commonly used. In this context, the Multi-Head Attention (MMHA) in the Decoder plays a significant role.</p><p>In the initial stage of the Decoder architecture in ViViT models, there is an MMHA layer that examines previous output tokens and models the relationships between them. Masking is employed in this stage so that the model can only consider previous tokens and not future tokens. This is vital in video generation because each frame needs to be generated based on previous frames. The use of Masked MHA ensures that the model only considers previous frames and does not have access to future information, which is important for maintaining the sequential integrity of video generation.</p><p>Next, there is another MHA layer that examines the outputs of the Encoder. This layer models the relationships between features extracted from the video in the Encoder section and the current tokens in the Decoder section. Masking is not used in this layer because the model needs to consider all the Encoder tokens. The output from the Encoder-Decoder Attention stage is fed into a feedforward neural network (FFN), which includes several Dense layers. The subsequent steps follow the Transformer architecture, and like the Encoder section, the Decoder also uses layer normalization and residual connections.</p><p>The Decoder section in ViViT and other Video Transformer models operates similarly to Transformer models in NLP, but it specifically handles video data and its spatiotemporal features. Using Masked MHA in the Decoder to prevent access to future tokens and maintain the sequential generation process is crucial.</p><blockquote>Important Note: The overall Encoder-Decoder structure and Attention mechanism in ViTs and ViViTs are similar. However, there are differences in implementation and details due to the requirement of modeling temporal information in videos. These differences enable the models to effectively handle their input data type, whether it’s images or videos.</blockquote><h3><strong>VideoGPT</strong></h3><p>In<em> 2021</em>, VideoGPT, a Transformer-based model utilizing a structure similar to GPT models, was introduced in a paper by <em>Yusen Zhou </em>and others.</p><p><a href="https://arxiv.org/abs/2104.10157">VideoGPT: Video Generation using VQ-VAE and Transformers</a></p><p>This model is designed to create short videos based on input text or sequences of video frames. If the input is text, it’s converted into embedding vectors by the Encoder. If the input is initial video frames, they are similarly processed. The model treats these inputs as sequence data. The video frames are preprocessed and transformed into appropriate sequences before entering the model.<br>Using a Transformer architecture, the model generates new video frames through the Decoder that align with the input text or frames. In the Decoder section, it uses the numerical representations generated by the Encoder to predict the next video frames. This process involves frame-to-frame video generation, accurately predicting the next frame based on previous inputs and attention to available information, including predicting future frames and completing video sequences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q_JlCewSBq3ymOvT3_0Nxw.jpeg" /><figcaption>On the left side of the image, you see a type of autoencoder model called VQ-VAE (Vector Quantized Variational Autoencoder) that encodes input data (video) into a low-dimensional latent space and then reconstructs this latent space back into the input data. This stage is similar to the original VQ-VAE training method. The goal is for the model to compress video data into a latent space with minimal quality loss. On the right side is the second training stage of an autoregressive Transformer in the latent space, where the latent sequences produced by VQ-VAE are used as training data for the autoregressive Transformer model. <a href="https://arxiv.org/abs/2104.10157">Source</a></figcaption></figure><p>The video frames generated by the Decoder are then concatenated to form a complete video. In the VideoGPT model, the Decoder generates video sequences by predicting and generating future frames based on information received from the Encoder to produce the final video. However, the use of VideoGPT and similar models is still in the research and development stage. While this technology has great potential for various applications (such as automatic video content generation, animation creation, advertising, etc.), due to technical complexities and the need for high computational resources, it has not yet been widely adopted commercially.</p><h3><strong>The main challenges in Transformers for images and videos</strong></h3><p>It’s important to note that using Transformers for image and video-related tasks comes with unique challenges. Images and videos contain complex spatial information. While Transformers can focus on important parts of a sequence due to their attention mechanism, this may not be suitable for modeling long-range dependencies commonly found in images and videos. However, newer Transformer architectures such as Vision Transformer and Swin Transformer are specifically designed for image and video tasks, utilizing new attention mechanisms better suited for modeling spatial dependencies.</p><p>One of the major challenges is the training of Transformers on large image and video datasets, which is computationally expensive. Transformers have a large number of parameters, requiring substantial memory and computational power for processing. Reinforcement learning can be more efficient for training Transformers, where they receive positive or negative feedback on their performance rather than being trained on labeled datasets. This allows them to learn effective patterns without the need for large amounts of labeled data. Additionally, multitask learning can be used to train Transformers for multiple tasks simultaneously, allowing them to share knowledge across tasks and improve performance in each task.</p><p>High-quality datasets for image and video tasks are often scarce and expensive. This can make training Transformers on these tasks challenging since they require a large amount of data to learn effective patterns. These are just a few promising solutions being developed to address the challenges of using Transformers for image and video tasks. With advancements in research, significant improvements in the performance of Transformers in these tasks are likely to be observed.</p><h3>Conclusion</h3><p>In this article, we discussed various Transformer models derived from the original Transformer paper and their applications in image and video tasks. We observed that their core idea is quite similar, with the main difference being the type of data used in their architecture. We also explored GAN architectures, which were developed before Transformers and were widely used. However, with the advent of Transformers, GAN architectures also changed. These two were combined, leading to the creation of ViTGAN and TransGAN architectures.</p><p>Today, Transformers are ubiquitous, with major companies using this architecture to shape our new world. As we move forward, the continuous improvement of this architecture brings us closer to AGI (Artificial General Intelligence). Especially in the field of computer vision, the better a machine can see, the closer we get to AGI. After the introduction of GPT-4o, which was released at the time of writing this article, the path to AGI became clearer. With GPT-4o, models can see videos in real time, analyze them immediately, and answer questions about them. Google’s model functions similarly.</p><p>It is clear that shortly, we are moving towards models that can see more and better. Essentially, LLMs (Large Language Models) are becoming more multimodal. Control will be in the hands of those who can enhance machine vision, which could also make the world a bit more frightening as the boundaries of reality become significantly altered, making it increasingly difficult to distinguish between real and artificial worlds. This development might inevitably lead us toward the profound question posed in the memorable film “The Matrix”: “What is real?”</p><p>Thank you for accompanying me on this journey into the world of deep learning.</p><p>The link to the article in Persian is available on <a href="https://virgool.io/@m.javadnejadi/%D8%AA%D8%B1%D9%86%D8%B3%D9%81%D9%88%D8%B1%D9%85%D8%B1%D9%87%D8%A7-%D9%82%D9%84%D9%85-%D9%85%D9%88%DB%8C-%D9%87%D9%88%D8%B4-%D9%85%D8%B5%D9%86%D9%88%D8%B9%DB%8C-%D8%A8%D8%B1%D8%A7%DB%8C-%D9%86%D9%82%D8%A7%D8%B4%DB%8C-%D8%AF%D9%86%DB%8C%D8%A7%DB%8C-%D8%AC%D8%AF%DB%8C%D8%AF-vision-transformer-rbst8lf5lwsv">virgool.io</a>.</p><p>If you’re interested, you can check out my other article, “<a href="https://medium.com/ai-advances/transformers-is-all-you-need-8a570e1c2d56">Transformers is All You Need</a>”</p><p><a href="https://medium.com/@reza.shokrzad/pickle-json-or-parquet-unraveling-the-best-data-format-for-speedy-ml-solutions-10c3f7bf4d0c">Pickle, JSON, or Parquet: Unraveling the Best Data Format for Speedy ML Solutions</a></p><p>I hope you’ve enjoyed the content.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c51b162bba36" width="1" height="1" alt=""><hr><p><a href="https://aiadvances.org/transformers-ais-paintbrush-to-paint-a-new-world-vision-transformer-c51b162bba36">Transformers: AI’s Paintbrush to Paint a New World (Vision Transformer)</a> was originally published in <a href="https://aiadvances.org/">AI Advances</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“Transformers is All You Need”]]></title>
            <link>https://aiadvances.org/transformers-is-all-you-need-8a570e1c2d56?source=rss-707395aa8764------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a570e1c2d56</guid>
            <category><![CDATA[decoder]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[encoder]]></category>
            <category><![CDATA[attention]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[M Javadnejadi]]></dc:creator>
            <pubDate>Sat, 11 May 2024 14:25:57 GMT</pubDate>
            <atom:updated>2024-09-05T19:58:51.346Z</atom:updated>
            <content:encoded><![CDATA[<h4>#Part II: Break down the architecture of transformers part by part with examples and code.</h4><blockquote>What is the Matrix? Control. The Matrix is a computer-generated dream world, built to keep us under control in order to change a human being into this.</blockquote><blockquote><a href="https://youtu.be/t-Nz6us7DUA?si=roCtlJ9mRGx9BZJW">The Matrix (1999)</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r76TyX4RQtR97VBhds7F7A.jpeg" /><figcaption>The main architecture of Transformers with an encoder on the left side and a decoder on the right side, as described in the original article. <a href="https://arxiv.org/abs/1706.03762">source</a></figcaption></figure><blockquote>Note: “All the code provided in this article has been tested in Google Colab and produces output. The codes are in pseudo-code format and are not for any specific project; they mostly serve the purpose of better understanding the subject matter.”</blockquote><h3><strong>Overview</strong></h3><p>Part 1: We will learn the most important terms and sections used in Transformer architecture (attention depth).</p><p>Part 2: We will delve into the architecture of Transformers piece by piece with examples and code.</p><p>In Part 1, we discussed the key terminologies associated with the Transformer architecture, which is crucial to comprehend before diving into its main architecture. In Part 2, we aim to provide a comprehensive analysis of the primary architecture of the transformer, step by step, to understand its logic and how all the terminologies mentioned in Part 1 are employed. Our primary goal is to understand the core task of the Transformer and the magic behind building powerful models like <em>ChatGPT</em> or <em>LLaMA </em>and many others. It’s worth noting that after the original Transformer architecture, other models were proposed with new tasks added to it. For instance, Transformers are now used for tasks like computer vision where models like <em>DETR</em> use Transformers directly for object detection in images without the need for intermediate stages like region proposals, sentiment analysis, and many other tasks. We will also examine examples and see them in code. We will discuss its primary challenges and ways to overcome them. Lastly, we will learn about the various Transformer models that exist or have been proposed. Join me as we uncover how the transformation of the world began and how it is advancing. Are you ready?</p><h3>The architecture of Transformers</h3><p>The Transformer architecture is a powerful and complex system that consists of two main components: the Encoder and the Decoder. Within each component, several blocks perform specific tasks. When using the Transformer for a task, the architecture is repeated multiple times, as indicated by the “<strong><em>Nx</em></strong>” in each part of the Encoder and the Decoder in the original article image.</p><p>However, the Transformer architecture faced several challenges when it was first introduced, such as high computational complexity due to the use of the Attention mechanism. This made it necessary to have large training data, particularly for machine translation.</p><p>To address some of these issues, the original Transformer architecture paper introduced techniques like <strong><em>Dropout</em></strong> to reduce <em>overfitting</em>, and subsequent documents introduced new architectures that addressed the main topics of the Transformer. These included adding Convolutional layers to the architecture, using <strong>feature-based attention</strong>, or using Transformer architectures tailored to the specific features of the data.</p><p>Improved training algorithms like <strong><em>AdamW</em></strong> were also utilized to enhance the speed and efficiency of training Transformer models. In the following sections, we will examine each layer of the Transformer architecture in detail.</p><h3><strong>Encoder</strong></h3><p>The Encoder plays a crucial role in the Transformer architecture. Its primary task is to understand and compress input information by extracting key information. The Encoder comprises one or more neural layers, each typically consisting of two main parts. The <strong>Multi-head Attention (MHA)</strong> module is responsible for managing the relationships between all words or sequences in the input. It calculates the Attention Score for each input to attend to other words in the sentence or sequence. <em>MHA</em> uses <strong><em>Query, Key</em></strong>, and <strong><em>Value matrices</em></strong> to calculate the relationships between words and extract important information based on these relationships. The extracted data from <em>MHA </em>is then processed by a <strong>Feedforward Neural Network layer</strong>, which uses <strong><em>non-linear functions</em></strong> and techniques such as <em>weighting </em>and <em>activation</em> to process input sequences like words in a sentence, video frames, or any other type of sequence, receiving and processing important and key information. In the next section, we will go layer by layer in the Encoder and see how it works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D23A0byvdJFUYduDNVPEsw.jpeg" /><figcaption>This image depicts an Encoder block taken from the <a href="https://arxiv.org/abs/1706.03762">original paper</a>. You can see the various parts of the Encoder. Below, we aim to dissect each part one by one. This image has been blurred by me.</figcaption></figure><p>The Transformer architecture is commonly used in the Encoder model. However, models like<strong><em> GPT, BERT, </em></strong>and<strong><em> T5</em></strong> have modified this architecture by using variations of the core model to address specific issues they face. For example, <em>BERT</em> uses a technique called<strong> Masked Language Modeling (MLM)</strong> for training. In <em>MLM</em>, some of the words in a sentence are hidden, and the model must predict the missing words based on the surrounding words. On the other hand, <em>GPT</em> uses <em>MLM</em> in combination with <strong>Autoregressive Language Modeling</strong> for training. In Autoregressive Language Modeling, the model must predict the next word in a sentence based on the previous words. This helps <em>GPT</em> to generate natural and fluent text. <strong><em>T5 (Text-to-Text Transfer Transformer)</em></strong> uses a multi-task architecture to learn various natural language processing tasks such as<strong> translation</strong>, <strong>summarization</strong>, and <strong>question answering</strong>.</p><h3><strong>Embedding Layer</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*noPhDvGU2EfyQgwpz9GW8A.jpeg" /><figcaption>This image, taken from the <a href="https://arxiv.org/abs/1706.03762">original paper</a>, shows the architecture of the Encoder, with the parts related to the embedding layer highlighted. This image has been blurred by me.</figcaption></figure><p>The Transformer architecture generally transforms the words or elements of a sequence into <em>embedding vectors</em> using an <strong>Embedding Layer</strong>. These <em>embedding vectors</em> have a lower dimensionality than <strong><em>one-hot encoding vectors</em></strong> and provide a better representation of semantic and contextual information. Subsequently, these <em>embedding vectors</em> are passed through the Encoder layers. Typically, an Embedding matrix is used to create the Embedding Layer that contains vectors for each word or element in the vocabulary. These vectors are usually obtained using methods like <strong><em>Word2Vec, GloVe,</em></strong> or<strong><em> FastText</em></strong>. For instance, the input sequence “<em>hello</em>,” “<em>world</em>,” and “<em>how are you</em>” could be converted into embedding vectors such as <em>[0.2, 0.5, -0.1], [-0.3, 0.8, 0.6]</em>, and <em>[0.1, -0.7, 0.4]</em>, respectively. We can readily access the Embedding Layer in popular libraries like <em>TensorFlow</em> or <em>PyTorch</em> and use them without difficulty.</p><pre>import torch<br>import torch.nn as nn<br><br># Define the Embedding Layer<br>embedding_layer = nn.Embedding(10000, 300)<br><br># Sample input data<br>input_data = torch.tensor([1, 5, 7, 2])<br><br># Transform the input data into embeddings<br>embedded_output = embedding_layer(input_data)<br><br># Display the dimensions of the output<br>print(&quot;Embedding Layer output dimensions:&quot;, embedded_output.size())</pre><p>In this code, the Embedding Layer is defined using the `<em>nn.Embedding</em>` class from the <em>PyTorch</em> library. This layer has two parameters: the number of words in the vocabulary (<em>10,000</em>) and the size of the embedding vector for each word (<em>300</em>). Then, a sample input data is defined as a <em>PyTorch</em> tensor containing several word indices, which is sent as input to the Embedding Layer, and the Embedding Layer produces the embedding vector corresponding to each word as output. Finally, the dimensions of the output from the Embedding Layer are displayed, and the embedding vectors corresponding to the input words are shown.</p><h3><strong>Positional Encoder</strong></h3><p>Transformer models differ from traditional <em>recurrent neural network</em> models since they do not rely on the sequence order of inputs to generate outputs. However, this lack of implicit <strong>positional information</strong> can lead to a loss of important information while transforming tokens into <em>embedding vectors</em>. To address this issue, a positional encoder is used to provide positional information to input tokens, indicating their position in the sequence. This addition of positional information helps preserve information, allowing the model to differentiate between different tokens in a sequence. It also provides an understanding of the sequence order and position, thereby improving the model’s performance and efficiency in natural language processing tasks.</p><p>The positional vector is usually generated as a vector or matrix with specific dimensions. One common method is to use mathematical functions such as sine and cosine to create a unique value for each position in the sequence. Essentially, the positional encoder equips input tokens with positional information, enabling the model to consider the position and order of tokens and use this information to generate appropriate outputs.</p><p>Typically, the positional encoder is placed immediately after the Embedding Layer in the Transformer model. Below is a simple example that demonstrates how to add positional information to input tokens using a positional encoder with the <em>PyTorch</em> library.</p><pre><br>import torch<br>import torch.nn as nn<br>import math<br><br>class PositionalEncoder(nn.Module):<br>    def __init__(self, d_model, max_len=1000):<br>        super(PositionalEncoder, self).__init__()<br>        self.d_model = d_model<br>        <br>        # Initialize the positional encoding matrix<br>        pe = torch.zeros(max_len, d_model)<br>        position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)<br>        div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))<br>        pe[:, 0::2] = torch.sin(position * div_term)<br>        pe[:, 1::2] = torch.cos(position * div_term)<br>        pe = pe.unsqueeze(0)<br>        <br>        # Register as buffer so it&#39;s not updated during training<br>        self.register_buffer(&#39;pe&#39;, pe)<br><br>    def forward(self, x):<br>        # Add the positional encoding to the input<br>        x = x + self.pe[:, :x.size(1)]<br>        return x</pre><p>The `<em>PositionalEncoder</em>` class, which inherits from the `<em>nn.Module</em>` class, first defines main variables such as the embedding vector size <em>`(d_model)`</em> and the maximum sequence length <em>`(max_len)`</em>. Then, a positional matrix with dimensions `(<em>max_len, d_model</em>)` is created, with all values initially filled with zeros. Next, for each position in the<em> </em>sequence, the values of the sinusoidal position encoding variables are calculated and placed in the positional matrix. Finally, the positional matrix is registered as a buffer so that it is not updated during the model training process.</p><h3><strong>Multi-head Attention</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*0m5vEGu7RlI2BWmi69jUlQ.jpeg" /><figcaption>In this image taken from the <a href="https://arxiv.org/abs/1706.03762">original paper</a>, you can see the architecture of the Encoder, with the Multi-head Attention layer highlighted. This is the main column of Transformer architectures. This image has been blurred by me.</figcaption></figure><p>One of the most crucial components of the Transformer architecture, and arguably its core, is the <strong><em>Multi-head Attention (MHA)</em></strong>. The heartbeat of Transformers is indeed this Attention mechanism. In Part 1, we discussed various types of Attention mechanisms, including <em>MHA</em>, as well as delved into the <strong>Scaled Dot-Product Attention</strong>. Now, let’s review the explanations provided in Part 1 regarding the computation of (<strong><em>Q, K, V</em></strong>) and their significance. Let’s pay attention to the image below, extracted from the original paper.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7ntQsXzLM5mIhiMxipW3HQ.png" /><figcaption>This image, taken from the original article, effectively illustrates how Multi-head Attention (MHA) operates. From the left side of the image, we can understand how Scaled Dot-Product Attention is computed, and the values of Q, K, V are more understandable by observing it. <a href="https://arxiv.org/abs/1706.03762">source</a></figcaption></figure><p>After the Positional Encoder stage, the data is ready to be processed by the <strong>Multi-head Attention (MHA)</strong> module. This module is responsible for performing attention mechanisms, such as identifying the most important words and their relationships, which is crucial for tasks like machine translation. To achieve this, the <em>Embedding vectors</em> are prepared and fed into the <em>Multi-head Attention</em> using three sets of (<em>Q, K, V</em>). These sets are linearly projected and then entered into the <em>Scaled Dot-Product Attention</em>.</p><p>During the computation of (<strong><em>Q, K</em></strong>), which involves dot product operations (<em>MatMul</em>), the matrix values are normalized using the <strong>Softmax function</strong>, which makes their range between<em> 0 and 1</em>. The result is then multiplied by <em>V</em> through <em>MatMul</em>. After this, they pass through another Linear layer and enter the <strong>add &amp; Norm layer</strong>.</p><p>But why is this necessary? It’s to prevent the <strong>Vanishing Gradient Problem</strong> during the <strong><em>backpropagation</em></strong> phase. If this step is not performed, <em>gradients</em> become extremely small and practically vanish. In the original architecture, <strong><em>Residual connections</em></strong> are also used. Values are passed through <em>Layer Normalization</em> before being computed with (<em>Q, K, V</em>) to prevent <em>gradient</em> descent issues.</p><p>If <em>Residual Connections</em> are <strong>not</strong> used, the attention in some layers may diminish in the subsequent stages of the network due to the <em>Vanishing Gradient Problem</em>. This can lead to the loss of important information or a decrease in network efficiency. As depicted in the figure above, the original paper employs <strong><em>8 layers</em></strong> of <em>Multi-head Attention</em> in each stage. In the next stage, the data are entered into the <em>add &amp; Norm</em> layer, which we will examine further in the subsequent discussion.</p><h3><strong>Add &amp; Norm</strong></h3><p>All layers in the Transformer architecture use normalization techniques, such as<em> Layer Normalization</em><strong> </strong>or<strong> </strong><em>Batch Normalization</em>, to calculate the mean and variance for each feature or input from the data. The <em>MHA</em> stage can produce outputs with different value ranges, and normalizing them can help in the training process. This technique reduces the impact of internal variable deviations that may change during training, allowing the network to adapt to new, previously unseen cases. After <em>Normalization</em>, the inputs are passed to the subsequent layers of the network, where they undergo further processing using activation functions like <strong><em>ReLU </em></strong>or<strong><em> GELU</em></strong>. The normalization layer prevents excessively large or small gradients and avoids issues like <strong>gradient explosion </strong>and<strong> gradient vanishing</strong>. During the training of deep models, input features may change over time, which is called Covariate Shift. <em>Normalization layers</em> can mitigate these effects and accelerate the training process. We want to see in a Python code sample using the <em>PyTorch</em> library how this layer is implemented.</p><pre>import torch<br>import torch.nn as nn<br><br>class AddNormLayer(nn.Module):<br>    def __init__(self, input_dim):<br>        super(AddNormLayer, self).__init__()<br>        self.norm = nn.LayerNorm(input_dim)<br><br>    def forward(self, x):<br>        # Add step: Adding input to the output of the layer<br>        added = x + torch.randn_like(x)<br>        # Norm step: Normalizing the output values<br>        normalized = self.norm(added)<br>        return normalized<br><br># Using the Add &amp; Norm layer<br>input_dim = 512<br>layer = AddNormLayer(input_dim)<br><br># Example input<br>input_data = torch.randn(10, input_dim)<br><br># Applying the layer on the input<br>output = layer(input_data)<br>print(output.shape)  # Output size</pre><p>In the above code, we have implemented a custom layer named `<em>AddNormLayer</em>` using the <em>PyTorch</em> library, which consists of two parts. The first part is `<em>Add</em>`, where random noise is added to the input. For this purpose, a random noise vector with the same dimensions as the input is added to each input vector. This noise vector is generated using `<em>torch.randn_like(x)</em>`, which creates random values from a normal distribution with the same dimensions as the input. Then, this noise vector is added to the input, and in the `<em>Norm</em>` step, the output values obtained from the `<em>Add</em>` step are normalized. For this, we use a normalization layer called `<em>nn.LayerNorm</em>`, which normalizes the input dimensions. Finally, we apply this custom layer to an example input and print the output dimensions to ensure that the implementation works correctly.</p><p>The output size `<em>torch.Size([10, 512])</em>` means that the output dimensions of the network for the example inputs provided in the form of `<em>torch.randn(10, 512)</em>` indicates that there are <em>10</em> features, each of which is a vector with <em>512</em> dimensions. In other words, for each input sample, an output vector with <em>512</em> dimensions is generated, and there are <em>10</em> samples in our dataset.</p><blockquote><strong>Important note: The “add &amp; Norm” operation is present in all blocks of the Transformer architecture and always accompanies the data that directly enters it via the activation function. Data is also passed to it through residual connections. Its output is usually linear or ReLU.</strong></blockquote><h3><strong>Feed-Forward Neural Networks</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*vlb1fQHvbMZICGtI3P9hbQ.jpeg" /><figcaption>In this image taken from the <a href="https://arxiv.org/abs/1706.03762">original paper</a>, you can see the architecture of the Encoder, with the Feed-Forward Neural Networks layer highlighted. This image has been blurred by me.</figcaption></figure><p>The encoder is made up of <em>multiple layers</em>, each containing modules like <em>Feed-Forward Neural Networks</em>. After <em>Multi-head Attention (MHA)</em>, there is a Feed-Forward Neural Network (<em>FFNN</em>) that has two or more perceptron layers and <strong>nonlinear activation functions</strong> (<em>such as ReLU, GELU, or Swish</em>). This helps the network learn complex and nonlinear patterns that <em>Self-Attention</em> alone may not fully identify. The <em>FFNN layer</em> compresses and further represents the information after applying the <em>Self-Attention</em> operation, reducing the likelihood of <strong>overfitting</strong>. The output of this layer goes into an <strong>Add &amp; Norm</strong>, which standardizes the output features of each layer and makes the model training process faster and more stable. After passing through all the Encoder layers, the output consists of final feature vectors, usually represented as a set of feature vectors for each element of the sequence. These feature vectors contain semantic and contextual information from the input sequence and are used for the next process, the Decoder. The <strong><em>(Q, K) Query</em></strong> is fed into the last block of the MHA from the Decoder. We’ll cover Decoders in the next section. Do you want to continue this journey with me?</p><h3><strong>Decoder</strong></h3><p>The Decoder is a vital component in Transformer architectures. It is responsible for generating the final output, which is usually a sequence of text or a series of elements and is used for various purposes, such as translation, summarization, or classification. The Decoder receives a context vector or state from the Encoder and generates words or output elements based on it. The Decoder incorporates information from two different sources, namely the input and the previous output. It can examine relevant information from both the input and previous output sequences to provide a more accurate translation or output generation. The Decoder utilizes Feed-Forward Neural Networks (<em>FFNNs</em>) to produce the final output. These layers perform operations such as analyzing and combining input features to generate the final output, which is usually a text sequence or a vector used for the next stage in the process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/1*yzRsZwQ-x-colHVnn2JEaQ.png" /><figcaption>This image is taken from one of the slides in Andrej Karpathy’s YouTube tutorial. In this picture, the performance of the Decoder and its various components can be clearly and excellently seen. Take a close look at this image again and again and again!. <a href="https://youtu.be/zjkBMFhNj_g?si=VeCTjamugLv9SrGC">source</a></figcaption></figure><p>The Decoder is made up of several different layers, each with specific tasks. These layers include <em>Multi-Head Attention Layers</em> and <em>FFNN layers</em>. <em>MHA</em> helps the Decoder to attend to relevant information from both the input and previous output, while <em>FFNN layers</em> aid in nonlinearly transforming the information.</p><p>While some functionalities performed in the Decoder may seem somewhat similar to those in the Encoder, they have important differences. In each <em>MHA</em> in the Decoder, Attention is conducted, with the difference that this Attention is modeled on relevant information from the input and previous output, provided as input to each Decoder layer. This enables the Decoder to adjust its focus depending on each stage of output generation. In the Decoder, <em>FFNNs</em> are applied to the results of <em>MHA</em> to model the information using nonlinear operations and assist in producing the final output.</p><p>For example, in the <em>GPT</em> architecture, a sentence such as “The cat sat on the mat” is provided as input to the model. The input sentence is fed into the model as a sequence of tokens which are processed by the Encoder layers. In the Encoder layers, each token is transformed into a hidden vector representing its meaning in the sentence. Relevant information from the input sentence is modeled in the hidden vectors created by the Encoder and provided as input to the Decoder layers. In the Decoder layers, using <em>MHAL</em>, the model can focus on relevant information from the input. This relevant information from the input sentence and information from previous outputs (if any) is used to generate the next words in the output sentence. This process continues recursively until a complete sentence is generated.</p><blockquote>Important Note: In the GPT model, the Encoder is responsible for transforming the input sentence into relevant hidden vectors, while the Decoder is responsible for generating the next words in the output sentence based on these hidden vectors and considering the previous text.</blockquote><h3><strong>Output!</strong></h3><p>It may seem strange that we are discussing the output after explaining the Decoder, but it is an important step in the process. The first part of the Decoder involves the <strong>output embedding</strong>. This means that the input vectors are transformed into hidden vectors (embedding vectors) that take into account both the semantic and positional features of the words. The next step is <em>Self-Attention</em>.</p><p>In this context, “output” refers to the model’s output at each time step, not the final output word. The Transformer architecture generates output words gradually. At each step, the model produces a hidden vector representing the probability distribution of words at the current position. This vector is then used as input for the next step of the model, and this process continues until the final word is generated.</p><p>There are differences between the Encoder and the Decoder regarding Positional Embedding. In both, Positional Embeddings indicate the relative position of words in the sentence. However, embedding requires a different mechanism in the Decoder. In the Encoder, the order of input words is important because the position of words in the sentence determines semantic information. In the Decoder, in addition to the position of input words, the order of output words is also important. Therefore, the model must consider temporal details to ensure it produces the correct sequence of output words.</p><p>In other words, the Decoder uses a different Positional Embedding mechanism that considers both the temporal order and the position of output words. Similar to the Encoder, the generated vectors are input into the Attention block using the same method, but with the possibility of being masked. What does this mean? Well, let’s move on to the next part, and I’ll explain it to you!</p><h3><strong>Masked Multi-Head Self-Attention</strong></h3><p>Decoders also use <em>Self-Attention</em>, which is slightly different from the same layer in the Encoder, although both use almost the same mechanism. In the Encoder, <em>Self-Attention</em> allows the model to examine its input features at each step of the processing, such as machine translation or other natural language processing tasks. The model calculates appropriate weights for each feature. However, in the Decoder, <em>Self-Attention</em> is known as <em>Masked</em> <em>Multi-Head Attention</em>. During each text generation or translation step, the model only attends to the words that have been generated so far or placed in chronological order, ignoring the words that have not yet been generated, which are future words. A mask is applied to the input of the <em>Self-Attention</em> to prevent access to future information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/294/1*zKRtAXU5AAua1veW-qLS4g.jpeg" /><figcaption>This image is of a Decoder taken from the <a href="https://arxiv.org/abs/1706.03762">original paper</a>, with the highlighted part being Masked Multi-Head Attention, which plays a crucial role in the functioning of Decoders, especially for text generation tasks. This image has been blurred by me.</figcaption></figure><p>For instance, suppose the model is generating a sentence, and at the current step, it has generated only the words “<em>I</em>” and “<em>am</em>.” In this case, the <em>masked Self-Attention layer</em> only attends to these two words and disregards the words that have not yet been generated, such as the next words in the sentence. This ensures that the model only attends to the available information up to that moment during each generation step, resulting in more accurate translation or text generation. This layer helps produce more accurate and meaningful translations.</p><p><strong><em>Masked Multi-Head Attention (MMHA)</em></strong> enables computations in <strong>parallel</strong> during training, which improves the efficiency and speed of model training. The masked mode in <em>Self-Attention</em> allows the model to attend only to the information available in previous time steps during each training step and ignore future information. This enables the model to utilize parallel processing efficiently, as each node can independently and simultaneously perform its computations.</p><p>This feature is used for text generation in generative AI models like <strong><em>ChatGPT</em> </strong>or<strong> <em>LLMs</em></strong> in general, which generate text. Without this feature, we could still have generative AI models for text generation, but the performance and quality of text generation in these models might decrease without mechanisms such as <strong>Masked Attention</strong>. The use of Masked Attention helps models pay more attention to the order and structure of sentences during the text-generation process and prevents the creation of texts with inconsistent structures.</p><h3><strong>Encoder-Decoder Attention</strong></h3><p>This stage is used exclusively in the Decoder. How information is transferred from <em>MMHA</em> to the subsequent layers is the same as in <em>MHA</em>. The only difference lies in the efficiency mentioned earlier. In Decoders, after <em>MMHA</em>, the data is passed to another <em>MHA layer</em>. This layer, in addition to the data received from <em>MMHA</em>, also receives the state vector from the Encoder. This stage is called <strong>Encoder-Decoder Attention</strong>.</p><p>In each step, the state vector received from the previous step in the Decoder is first computed. Then, this state vector is compared with all the Encoder state vectors to calculate the importance (<em>weight</em>) of each Encoder state vector for generating the current output in the Decoder. In this way, the model can dynamically and intelligently attend to the Encoder inputs and use them to generate appropriate outputs.</p><p>The mathematical computation is as follows: initially, Key Vectors, which represent important and key information from the input that needs to attract the Decoder’s attention, along with <strong>Value Vectors</strong> received from the Encoder, which contains more detailed information from the input, are combined with <strong>Query Vectors</strong> belonging to the Decoder (<em>indicating the Decoder’s attention point</em>) into the Attention Score equation. Then, using these attention scores, evaluation values are calculated, and the final output is obtained through weighted averaging.</p><h3>And again, the FFNN layer in the Decoder</h3><p>Transformer models contain a Feed-Forward Neural Network layer <strong>both</strong> in the Encoder and the Decoder. However, there are differences in these layers between the two parts. In the Encoder, this layer transforms input features (<em>usually feature vectors of words</em>) into new feature spaces that could yield the best results for the model. All the neurons of the <em>FFNN layer</em> receive each input feature, and an activation function (<em>usually ReLU or GELU</em>) processes the output.</p><p>In the Decoder, this layer transforms the output features from <em>Self-Attention</em> into new feature spaces that help the model generate the final text. Unlike the Encoder, the Decoder doesn’t require future information to use past information during text generation. Therefore, the <em>FFNN layer</em> in the Decoder is usually implemented as a <strong><em>Masked Feed-Forward Neural Network</em></strong>, which restricts access to future information. This restriction is enforced through corresponding masking in computations so that the model only has access to past information.</p><h3><strong>Output Layers (Linear + Softmax)</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/294/1*aD9zmWDqUeYJNCM38UKiSQ.jpeg" /><figcaption>This image is of a Decoder taken from the <a href="https://arxiv.org/abs/1706.03762">original paper</a>. the Output Layers (Linear + Softmax), which are the final layers of the Decoder architecture in fact, the last layers of the Transformer architecture. This image has been blurred by me.</figcaption></figure><p>Towards the end of the model, there is a <strong>Linear Output Layer</strong> followed by a <strong>Softmax Layer</strong>. The Linear Output Layer helps to convert the input given to it into a <strong>numerical value</strong>, while the <em>Softmax Layer</em> transforms these numerical values into normalized probabilities, which are used to predict the classes (<em>in classification mode</em>) or words (<em>in text generation mode</em>). The <em>Softmax Layer</em> consists of two parts — the last Linear Layer and the <em>Softmax Layer</em> itself. Let’s take a closer look at each part and examine its purpose in detail.</p><h3><strong>Last Linear Layer</strong></h3><p>The <strong><em>Last Linear Layer</em></strong> is an essential component of Transformer architectures, which is usually positioned at the end of the model. This layer directly receives the features extracted from the previous layers of the Decoder. Its primary function is to transform the final model features into the feature space required for the specific task the model has been trained for. The layer typically consists of a weight matrix and a bias, and its input is usually the final feature vector of the model obtained at the end of the Encoder or Decoder phase. The final features are typically obtained by applying linear operations, i.e., matrix multiplication between the weights and input features, followed by an activation function such as <strong><em>ReLU</em></strong> or <strong><em>GELU</em></strong>.</p><p>The output of this layer varies depending on the specific task at hand. If the model is designed for classification, the output of this layer is typically sent to the <em>Softmax layer</em> to compute class probabilities and make the final decision about the class. On the other hand, if the model is designed for text generation, the output of this layer is normalized by the<em> Softmax layer</em> and sent as probabilities of words in the next text generation step.</p><p>For example, let’s consider a scenario where our model is translating the sentence “<em>I love cats</em>” into French. The input sentence “<em>I love cats</em>” goes through multiple layers, and the features are extracted at each layer. The Last Linear Layer then receives these extracted features, which contain information about meaning, grammar, and sentence structure obtained from previous layers. Using its <em>weights</em>, this layer transforms these features into the feature space corresponding to the desired output, i.e., the feature space corresponding to the French sentence “<em>J’adore les chats</em>”. The layer assigns<em> weights</em> to each input feature to transform them into a new feature space, which serves as input to the<em> Softmax layer</em>.</p><h3><strong>Softmax</strong></h3><p>Once the data passes through the last Linear layer, it goes through a <em>Softmax layer</em>. This layer converts the output weights from the<em> Linear layer</em> into normalized probabilities for each class or word in the model output. In classification models, these probabilities represent the likelihood of each class. In text generation models, these probabilities represent the likelihood of each word appearing in the model output.</p><p>The <em>Softmax layer</em> ensures that no probability reaches zero, which prevents certain issues such as <strong><em>zero bias</em></strong> and shifts in the probability distribution. This helps the model output probability distribution to remain consistent over time.</p><p>In <em>LLMs</em>, if the probability distribution of words in sentences varies, it can lead to incoherent and nonsensical sentences. Therefore, the <em>Softmax layer</em> ensures that the model allocates probabilities proportionally and consistently, preventing unintended changes in the probability distribution.</p><p>Similarly, in classification tasks, if the probability distribution of classes changes over time, the model’s accuracy and predictability may decrease. So, the <em>Softmax layer</em> ensures that the model allocates probabilities proportionally and consistently and prevents unintended changes in the probability distribution.</p><h3><strong>The final output is produced</strong></h3><p>After the Softmax layer in the Decoder, the final output is typically generated using one of the following two methods in the Transformer architecture. Either through Beam Search, where after calculating the probabilities using the Softmax layer, the model employs beam search to select the best prediction for each step. In this method, for each step, the model computes multiple possible predictions and then selects the prediction with the highest probability among them. This process continues until reaching termination conditions such as the end of the sentence or a predetermined number of steps. Let’s understand it better with an example. Suppose our model is a machine translation model, and let’s say we want the model to translate the English sentence “I love you” into Persian. The model can compute multiple possible predictions for Persian words, such as “<em>من عاشق تو هستم</em>”, “<em>من تو را دوست دارم</em>”, “<em>عشق تو را</em> <em>می‌پذیرم</em>”, and so on. Then, using Beam Search, the model selects the prediction with the highest probability among these predictions. For example, if the model uses a beam of size <em>3</em>, the prediction with the highest probability at each step is chosen, and in the subsequent steps, these predictions are updated using the probabilities computed for the next words. Its applications are mainly for models like machine translation models, image captioning models, and attention-based text generation models.</p><p>The next step in Sampling, instead of selecting the best prediction, involves the model using a sampling process and generating various predictions based on calculated probabilities. This process can be done randomly, meaning predictions are sampled based on the calculated probability distribution. For example, suppose a model wants to predict the next word in a sentence. The model can select a word randomly using direct sampling based on the calculated probabilities for different words in the vocabulary. For instance, if the vocabulary consists of the words “<em>sky,” “yellow,</em>” and “<em>blue</em>,” with probabilities calculated as <em>0.4, 0.3, </em>and<em> 0.3</em> respectively, the model can randomly choose the word “<em>sky</em>” using sampling. This method is used in various tasks such as language models, machine translation, automatic text generation, and image generation.</p><p>However, the choice between these methods for producing suitable output depends on the tasks we want to perform. For instance, in cases where the search space is very large and using direct sampling might be too time-consuming, Beam Search is used to generate probable predictions. In both methods, the generated outputs serve as input to the model for calculating the next step or as final outputs for use in programs and other applications.</p><h3><strong>The applications of Transformers</strong></h3><p>Transformers have become widely popular in <em>NLP</em> tasks due to their exceptional ability to comprehend relationships between words in a sentence. They have numerous applications, including in machine translation where they improve the accuracy of translation between different languages. Transformers can also accurately summarize long texts, provide precise and comprehensive answers to text-related questions, generate various types of texts such as poetry, stories, code, and emails, detect and correct errors in spelling and grammar, extract important information from text, and analyze the expressed sentiments in the text. Additionally, Transformers are used in <em>LLMs</em> to create natural and engaging conversations with users.</p><h3>The applications of Transformers in computer vision</h3><p>Transformers are being used beyond their traditional applications, and are now being employed for<strong> computer vision</strong> tasks such as processing images and videos. Major companies like Google are extensively utilizing them in a wide spectrum of applications including image classification (<em>identifying objects, animals, or landscapes</em>), object detection (<em>identifying individuals, cars, or buildings</em>), and image segmentation (<em>segmenting individuals, cars, or buildings</em>). A model called <strong>ViT</strong>, which is a Transformer model, has been used to improve the accuracy of the <strong><em>ImageNet</em></strong> dataset. The <em>ViT</em> model was introduced in <em>2021</em> by a group of researchers at <strong><em>Google AI</em></strong> in a published paper.</p><p><a href="https://arxiv.org/abs/2010.11929">An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale</a></p><p>This article demonstrates that Transformer models can be directly applied to images. The <em>ViT</em> model utilizes a slightly different architecture from the standard Transformer for processing images. It is trained on the <em>ImageNet</em> dataset using the pre-training with massive parameters. With the <em>ViT</em> model, very good results can be achieved on various image recognition datasets, outperforming previous advanced models such as CNN-based models. <strong>OpenAI</strong> uses Transformers in various computer vision applications, including image generation, image translation, and more. For example, the Transformer model called <a href="https://openai.com/index/dall-e-3?__cf_chl_tk=IHx6tO5kdAtk9_AkIZossWYn9vIa.PIzpmsY6KBCbPs-1715149839-0.0.1.1-1599"><strong><em>DALL-E</em></strong></a> generates real images from text. Microsoft employs Transformers for face detection, object detection, and object tracking. For instance, <a href="https://azure.microsoft.com/en-us/products/ai-services"><strong><em>Azure Cognitive Services</em></strong></a>, a Transformer-based model, provides developers with computer vision APIs. Facebook utilizes Transformers in tasks such as <strong>face detection</strong>, <strong>object detection, </strong>and<strong> image segmentation</strong>. For example, the <a href="https://ai.meta.com/tools/detectron2/"><strong><em>Detectron2</em></strong></a> model, which is essentially an open-source toolbox for <strong>object detection in images based</strong> on Transformer-based deep neural networks, is designed. This toolbox utilizes Transformer models and other advanced methods in the field of computer vision. Some benefits of using the <em>Detectron2</em> model include high accuracy, adaptability to various inputs, and the ability to perform complex tasks in image recognition and interpretation.</p><h3><strong>The challenges and issues</strong></h3><p>Transformers are highly advanced in their capabilities, particularly in natural language processing and computer vision. However, no model is perfect and each has its drawbacks. One major point to consider is the high complexity of Transformers, which requires significant computational resources for both training and usage. This can result in long training and processing times, high energy consumption, and a need for powerful hardware. Additionally, training Transformer models requires large and voluminous datasets, which can lead to issues such as the need for storing and processing large volumes of data, and managing large datasets. Since Transformers require data to be in the form of tokens or numerical vectors, this may reduce accuracy and information in certain domains, such as image recognition.</p><h3>Conclusion</h3><p>In the second part of our study, we went into great detail about the architecture of Transformers. We examined each component and layer and learned how Encoders, Decoders, and Transformers work together to improve language translation between different languages. We also explored how Transformers can be used for various other tasks. We discussed some of the limitations of Transformers. Since their introduction in <em>2017</em>, the popularity of <em>LLMs</em> has continued to rise, with Transformers serving as their foundation. It appears that Transformers are not only maintaining their popularity but also gaining more popularity every day. However, in recent years, other architectures such as <strong>Infini-Transformers</strong> have emerged. <em>Infini-Transformers</em> are a family of Transformer models with unlimited depth, and the most important paper I found on this topic was authored by Google’s research team.</p><p><a href="https://arxiv.org/abs/2404.07143">Leave No Context Behind: Efficient Infinite Context Transformers with Infini-attention</a></p><p>These models utilize the standard Transformer architecture with modifications to increase their depth. For instance, they use <em>ReLU</em> <em>activation functions</em> instead of <em>softmax activation</em> functions in the architecture, incorporate batch normalization layers between each Transformer block, and employ new <em>position-wise attention functions</em>. The models are trained using pre-training with massive parameters on large text datasets. After that, the models are fine-tuned for various <em>NLP</em> tasks such as machine translation, text summarization, and question answering. I will write more about these models in the future. However, the pace of changes has accelerated significantly, and a model more effective than Transformers may be introduced soon. Thank you for accompanying me in this article. I learned a lot myself while writing it, and I hope it was helpful for you too. I would appreciate hearing your thoughts on this article. Please share your opinion with me. Thank you.</p><p>Thank you for accompanying me on this journey into the world of deep learning.</p><p>The link to the article in Persian is available on <a href="https://virgool.io/@m.javadnejadi/%D8%AA%D8%B1%D9%86%D8%B3%D9%81%D8%B1%D9%85%D8%B1-%D9%87%D8%A7-%D9%87%D9%85%D9%87-%DA%86%DB%8C%D8%B2%DB%8C-%DA%A9%D9%87-%D8%A8%D9%87-%D8%A2%D9%86-%D9%86%DB%8C%D8%A7%D8%B2-%D8%AF%D8%A7%D8%B1%DB%8C%D8%AF-maxy6pgfkftn">virgool.io.</a></p><p><a href="https://medium.com/ai-advances/transformer-is-all-you-need-fbb1d1e4d9b0">Part 1: We will learn the most important terms and sections used in Transformer architecture (attention depth).</a></p><p>Part 2: We will delve into the architecture of Transformers piece by piece with examples and code.</p><p>If you’re interested, you can check out my other article, “<a href="https://medium.com/ai-advances/step-by-step-guide-to-building-an-artificial-neural-network-and-observing-how-overfitting-occurs-84961f96c7e8">Step-by-step guide to building an artificial neural network and observing how overfitting occurs with MNIST and CNN architecture</a>”</p><p><a href="https://medium.com/@reza.shokrzad/the-impact-of-culture-on-persian-nlp-90c37c87cf47">The Impact of Culture on Persian NLP</a></p><p>I hope you’ve enjoyed the content.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a570e1c2d56" width="1" height="1" alt=""><hr><p><a href="https://aiadvances.org/transformers-is-all-you-need-8a570e1c2d56">“Transformers is All You Need”</a> was originally published in <a href="https://aiadvances.org/">AI Advances</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“ Transformer is All You Need ”]]></title>
            <link>https://aiadvances.org/transformer-is-all-you-need-fbb1d1e4d9b0?source=rss-707395aa8764------2</link>
            <guid isPermaLink="false">https://medium.com/p/fbb1d1e4d9b0</guid>
            <category><![CDATA[attention]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[self-attention]]></category>
            <category><![CDATA[transformers]]></category>
            <dc:creator><![CDATA[M Javadnejadi]]></dc:creator>
            <pubDate>Tue, 30 Apr 2024 12:41:03 GMT</pubDate>
            <atom:updated>2024-04-30T12:41:03.903Z</atom:updated>
            <content:encoded><![CDATA[<h4>#Part 1: We will learn the most important terms and sections used in Transformer architecture (attention depth).</h4><blockquote>“ What is real? How do you define real? If you are talking about what you can feel, what you can smell, what you can taste and see, then real is simply electrical signals interpreted by your brain”</blockquote><blockquote><a href="https://youtu.be/t-Nz6us7DUA?si=roCtlJ9mRGx9BZJW">The Matrix (1991)</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AmY9e7MzAToWpphbvg0u7w.png" /><figcaption>Generated on <a href="https://ideogram.ai/t/top/1">Ideogram</a>, as prompted by author</figcaption></figure><h3><strong>Overview</strong></h3><p>Part 1: We will learn the most important terms and sections used in Transformer architecture (attention depth).</p><p>Part 2: We will delve into the architecture of Transformers piece by piece with examples and code.</p><p>The following article is divided into two parts. In the first part, we will explore the concept of Transformers and how they work. The idea of Transformers is similar to the concept in “The Matrix” movie, where a person can learn a skill quickly by taking a pill that contains the knowledge. Similarly, instead of reinventing the wheel for a new task, we can transfer the knowledge from a previous task and improve upon it. In this exciting journey, we will dive deep into the history, applications, and architecture of Transformers, comparing it to LSTMs and exploring the Attention mechanism. We will also discuss if Transformers are only suitable for text or if they can be used in other applications. In part two of this article, we will learn about the entire architecture of Transformers and examine it in detail. Stay with me on this journey!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r76TyX4RQtR97VBhds7F7A.png" /><figcaption>The architectural diagram of transformers depicted in this image is taken from the original article. <a href="https://arxiv.org/abs/1706.03762">source</a></figcaption></figure><p>Take a good look at this image. This is the primary architectural diagram of the Transformer in the original article. Again and again and again, look at it! In this part and the next part, we want to thoroughly analyze it, part by part and detail by detail. I’ve been spending a few minutes every day looking at it. I repeat, pay <strong>attention</strong> to it.<strong> Attention. Attention. Attention…</strong></p><h3><strong>Sequence-to-Sequence</strong></h3><p>Seq-to-Seq models were first introduced in the early 21st century. As technology developed and neural networks became deeper, especially with the increased use of <strong><em>recurrent neural networks (RNNs)</em></strong> and <strong><em>LSTMs</em></strong>, the performance and utility of Seq-to-Seq models improved significantly. These models are now recognized as an effective method in natural language processing, particularly for tasks like machine translation. However, the main issue with them is the vanishing gradient problem, especially when using RNNs or LSTMs.</p><p>Transformers also use a Seq-to-Seq architecture for various tasks, but with many improvements and modifications that enhance their performance and efficiency. Transformers, particularly with their attention mechanism, address the limitations of Seq-to-Seq models and provide better performance in language processing tasks. This has resulted in a decrease in the applications of Seq-to-Seq models compared to Transformers, and they are mostly used in historical research. In the next section, we will look at the history of Transformers using a time machine!</p><h3><strong>History of Transformers</strong></h3><p>“When we talk about artificial intelligence and hear the terms “Transformers” or “Attention”, the first thing that comes to mind is the groundbreaking paper “Attention is all you need”, published in 2017. It brought about a major revolution in AI, and let’s delve deeper to see when the idea of Attention was first introduced. One of the earliest papers comprehensively introducing the Attention mechanism in machine translation is a paper.”</p><p><a href="https://arxiv.org/abs/1409.0473">Neural Machine Translation by Jointly Learning to Align and Translate</a></p><p>The main difference between the paper we are discussing and “Attention is All You Need” lies in the fact that, during translation, the neural network focuses on different positions in the source sentence and selects the corresponding words in the target sentence based on that. In contrast, the Attention mechanism in the 2017 paper fully replaced conventional recurrent layers like LSTM (Long Short-Term Memory) and GRU (Gated Recurrent Unit) that are used for processing sequential data. The Transformer network in the 2017 paper is entirely built based on the Attention mechanism, <strong>without the need for recurrent layers</strong>. Additionally, self-attention is also used, which allows the network to focus on the relationships between words in the sentence and produce better translations.</p><p>It’s worth noting that in 2015, Dzmitry Bahdanau, Kyunghyun Cho, and Yoshua Bengio published another paper on the subject.</p><p><a href="https://papers.nips.cc/paper/1839-a-neural-probabilistic-language-model">A Neural Probabilistic Language Model</a></p><p>The authors of a research paper utilized the Attention mechanism to enhance machine translation. They introduced a specific type of Attention called “<strong><em>Supervised Attention</em></strong>,” which enables the network to concentrate on important points in the source sentence during training based on the inputs and corresponding translation outputs. This type of Attention helps the network to select corresponding words more accurately in the target sentence.</p><p>Finally, in 2017, a paper titled “Attention is All You Need” was published.</p><p><a href="https://arxiv.org/abs/1706.03762">Attention Is All You Need</a></p><p>It can be confidently said that the artificial intelligence revolution began with the publication of a paper, which has since become a reference point in the field. Many subsequent articles have been written on the subject, and numerous methods for implementing Transformers in various tasks have been developed. This type of architecture is even used for computer vision tasks, which I may discuss in more detail soon. In the following sections, we will thoroughly examine the most important issues and mechanisms described in the Transformer architecture and in the paper “Attention is all you need”.</p><h3><strong>There are different types of Attention models</strong></h3><p>In this section, we aim to explore what Attention is and the different types of Attention mechanisms. We will also analyze them comparatively to better understand their differences.</p><h3><strong>Attention</strong></h3><p>The term “Attention” refers to focusing on specific points that require more attention. This concept was initially used in natural language processing to overcome the limitations of word-to-word translation, which often resulted in errors. Essentially, Attention assigns importance weights to input data, which are relevant to the task at hand and can significantly impact the generation of suitable outputs. However, Attention not only focuses on input data but also influences other elements used in the model processing, such as model weights, hidden state vectors, etc. Let’s explore the various types of Attention together!</p><h3><strong>Self-Attention</strong></h3><p>Self-Attention, also known as <strong>Intra-Attention</strong>, is an attention mechanism commonly used in deep learning architectures, specifically in Transformer models. In this mechanism, rather than focusing on other input sequences or utilizing different methods, the model concentrates on various parts of its input sequence. Essentially, Self-Attention allows the model to connect different positions in the input sequence to each other, using this information to compute a representation of the sequence. This type of attention enables the model to consider long-range dependencies and contextual information in its output representations.</p><p>This concept refers to the dependencies and relationships that exist between different components of an input sequence and output. These relationships are not limited to token-to-token interactions and can be represented indirectly from longer distances. For example, in a text, a word may be at the beginning of a sentence, and its dependent word at the end. Such long-range dependencies exist in the Self-Attention process in Transformer models, allowing the model to consider longer-range relationships in its output representations and utilize more contextual information. In subsequent sections on Transformer architectures, we will delve further into this.</p><h3><strong>Soft attention</strong></h3><p>Soft attention is a mechanism that assigns a weight to each input element, usually obtained from a softmax function, to indicate its importance. These weights determine which input elements should receive the most attention during processing and decision-making, resulting in the output. The primary benefit of soft attention is that it allows models to attend to multiple input elements simultaneously without specifying a fixed number of these elements. This enables more efficient and faster optimization through gradient-based techniques. In other words, soft attention uses optimization methods that simplify and improve these processes using gradients (partial derivatives). This makes soft attention particularly useful for input data with variable length and size, such as machine translation, question-answering systems, object detection in images, and more.</p><p>For instance, in machine translation, the soft attention mechanism can focus more on each word in the source sentence during translation. It does so by considering its importance in generating the corresponding word in the target sentence.</p><p>Soft Attention is a popular mechanism used in RNN-based models, particularly in sequence-to-sequence models or recurrent neural networks. The key difference between Soft Attention and Self-Attention is in how attention weights are computed. In Self-Attention, each element is connected to all other elements, and attention weights are directly extracted from input features. In contrast, Soft Attention computes attention weights using a machine learning model, such as a neural network. The model considers input features and the current state of the model to determine attention weights. There is no clear answer as to which attention mechanism is more suitable since the choice depends on the task at hand.</p><h3>Hard attention</h3><p>Hard attention is a mechanism used by models to focus only on a <strong>subset</strong> of input features while ignoring the rest. Unlike soft attention, which assigns continuous weights to all input elements, hard attention uses discrete weights for focus. This means that the model selects only one or a few elements to focus on at each step, resulting in a simpler and more selective attention mechanism.</p><p>However, training models that use hard attention can be challenging. The hard attention mechanism introduces <strong>non-differentiable</strong> operations to the model, which makes it non-differentiable. Without differentiability, standard machine learning algorithms like backpropagation cannot be used to optimize models with hard attention. To train these models, specific techniques are employed, such as Reinforcement Learning, which uses rewards and punishments to guide the model toward correct choices, or Discrete Optimization Techniques, which use discrete search algorithms to find the best set of elements, or Derivative Approximation, which uses various techniques to approximate the derivative of non-differentiable operations, enabling the use of standard backpropagation methods.</p><p>Hard attention has many applications, one of which is in image captioning, where it allows the model to focus on specific regions of the image and select the best areas for generating image captions.</p><h3><strong>Global attention</strong></h3><p>Global Attention mechanisms are a method used in <strong>Sequence-to-Sequence models</strong>, particularly in tasks such as machine translation. These mechanisms enable the model to focus on <strong>all elements of the input</strong> sequence by assigning attention weights to each element. This allows the model to use all available information in the input sequence when calculating an overall weight for all input elements, which is used to create a context vector. Attention scores are used to determine these weights and are computed as attention probabilities for each component.</p><p>One of the main advantages of using Global Attention mechanisms is that the model can identify and comprehend more complex structures in the data. This is because the model can utilize long-range dependencies and background information in decision-making and output generation. As a result, this approach can improve the performance and quality of the model’s outputs, particularly in tasks where the model needs to attend to all words in the input sentence to generate coherent translations.</p><h3><strong>Local attention</strong></h3><p>Local Attention is a type of attention mechanism that is commonly used in neural networks for tasks like Natural Language Processing (NLP) and Computer Vision. Local attention mechanisms are designed to compute attention weights over a smaller region of the input sequence. Unlike Global Attention, where the model learns to select a specific area or window around the current position and computes attention weights over the entire sequence. Local attention mechanisms are useful when relevant information is localized within a specific and local context, such as when processing time series data or text with strong local features.</p><p>Moreover, local attention mechanisms are computationally more efficient than Global Attention, as they reduce the number of attention computations required, making it suitable for applications with large input sequences or limited computational resources.</p><h3><strong>Masked/Multi-Head Self-Attention</strong></h3><p>The Multi-Head Self-Attention (MHSA) mechanism is an advanced version of the Self-Attention (SA) mechanism. Unlike SA, which focuses on a <strong>single point</strong>, MHSA can attend to several different aspects or points in the input sequence simultaneously. The significant difference between SA and MHSA is that SA computes a single set of attention weights, while MHSA calculates multiple sets of attention weights that are then combined to produce the final output. This ability enables MHSA to handle more complex relationships among input elements. Additionally, MHSA can parallelize and reduce the computational cost of SA, as each attention head can independently compute attention weights for a subset of input elements.</p><p>Moreover, in the Transformer architecture, there is another form of attention referred to as Masked Multi-Head Self-Attention, which is used for sequence-to-sequence tasks such as machine translation and text summarization. In Masked Multi-Head Self-Attention, the primary goal is to restrict the model’s access to information from previous parts of the sequence at each processing step, using a specific mask. This way, the model is compelled to process information sequentially, with parts of the sequence that have not been processed yet being temporarily hidden from the model. Gradually, the attention weights are calculated based on the available information up to that point.</p><h3><strong>Scaled Dot-Product Attention</strong></h3><p>The Transformer model uses a technique called Scaled Dot-Product Attention to establish relationships among all input tokens within a layer. This attention mechanism is used in Self-Attention and Multi-Head Attention to model the relationships between words in a sentence. The three matrices K, Q, and V (Key, Query, and Value) play a crucial role in this mechanism.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/1*FosMqcqw9dCssYkhqRYwlw.png" /><figcaption>The image of the Scaled Dot-Product Attention module is presented in the original article. <a href="https://arxiv.org/abs/1706.03762">source</a></figcaption></figure><p>The Key matrix (K) computes the relevance of each word in the sentence to the input word (Query) Q. It represents the information related to the input text, where each word in the sentence has a Key vector.</p><p>The Query matrix (Q) calculates the relevance of each word in the sentence to the word we want to focus on (Context). It represents the information related to the input word, where each word in the sentence has a Query vector.</p><p>The Value matrix (V) represents the information related to each word in the sentence. It represents the semantic information of each word, where each word in the sentence has a Value vector. The matrices K, Q, and V are used to calculate the weights for each word in the sentence based on the input word (Query).</p><h3><strong>Scaling the Dot-Product of Tokens</strong></h3><p>For each input token, a dot product is computed with all other tokens. This involves scaling the dot product by calculating the dot product between the embedding vectors of the tokens. Initially, the embedding vectors of each pair of tokens (source and target) are multiplied together. The resulting dot product value is then used to represent the importance and dependency between the two tokens. The result is a matrix of dot product values that indicates the relationships and dependencies between different tokens in the sequence. These relationships and dependencies are used to compute weighted attention scores in subsequent stages of the Attention algorithm. The dot product reflects the relationship and dependency between the tokens and is calculated for each token pair (K and Q).</p><p>To simplify, let’s consider an input sentence with multiple words. We want to calculate the importance and dependency of each word on the other words. For example, if we have two words “dog” and “boy” in the sentence, we need to calculate the attention score for each pair of words in the sentence. This is because if we only pay attention to the whole sentence, we might miss the relationship between these two words. For instance, in the sentence “The dog runs with the boy,” we need to understand that “dog” is related to “boy”.</p><h3><strong>Normalization</strong></h3><p>The internally calculated scale for each token is divided by a normalization value, which is usually equivalent to the length of the token vector, or we can say it’s equivalent to the square root of the sum of squares of token representation vector lengths. When we calculate the internal scale for each token in the sequence, we essentially normalize these values to a standard scale so that we can compare them on a consistent and acceptable scale. We use Softmax functions for this purpose. The Softmax function is a function that transforms input values into a probability space, such that larger values have higher probabilities and smaller values have correspondingly lower probabilities. This helps improve the stability and efficiency of the algorithm.</p><h3><strong>Feature Matrix</strong></h3><p>In this stage, we compute weights for each token based on the values that were generated in the previous stage, which were the dot products of tokens. These weights indicate the importance of each token relative to the other tokens in the sequence. To calculate the weights, we use a weight matrix that has appropriate dimensions for computation. The dimensions of this weight matrix are equivalent to the number of tokens present in both the input and output of the Transformer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*c2JW0HbFMBrhpacxeFGbiQ.png" /><figcaption>This image depicts a Decoder block where we can clearly see the Feature Matrix computed in the Encoder and fed into the Decoder. <a href="https://kikaben.com/transformers-encoder-decoder/">source</a></figcaption></figure><p>To summarize, this weight matrix is essentially a linear mapping that converts each input token into a suitable weight. These weights are typically between -1 and 1, and they indicate the importance of each token relative to other tokens. These weights are then calculated for each token using the internally scaled token values, which represent the relationships and dependencies between the tokens.</p><h3><strong>Calculating the final score</strong></h3><p>At this stage, the previously calculated weights are multiplied by the token representations to derive the final value for each token. This final value denotes the token’s significance in comparison to the others and is used in Transformer models to compute attention weights.</p><h3>Weighted averaging</h3><p>In this step, the importance of each token is calculated based on the final attention scores assigned to them. A weighted average of the token representations is then determined using these importance scores. This weighted average plays a key role in transferring information between tokens, ensuring that important tokens are given more weight in the calculation. Scaled Dot-Product Attention is a type of attention mechanism used in transformers that understands the positional information and dependencies between tokens in a sequence. It effectively utilizes this information to generate output.</p><h3><strong>Residual Connections in Transformer</strong></h3><p>Residual connections are widely used in the architecture of Transformers to mitigate the Vanishing Gradient Problem (VGP). This problem is critical in deep networks because, as we go deeper, <strong>gradients</strong> may become too small, approaching zero, making them practically non-existent. Residual connections help to alleviate this issue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*R8G-FItmk2-4v8iU34J_cQ.png" /><figcaption>This image effectively illustrates an encoder block with its residual connections. <a href="https://kikaben.com/transformers-encoder-decoder/">source</a></figcaption></figure><p>The idea of using residual connections in Transformers is inspired by the ResNet architecture. For each layer of self-attention and feed-forward neural network in a Transformer, these connections are applied. They help the networks preserve the original information and raw inputs throughout the network’s path. Consequently, gradients quickly return to earlier layers, reducing VGP.</p><p>These connections also contribute to knowledge preservation. Essentially, they aid in retaining the primary and essential input features (features extracted in initial layers) throughout the network’s path, making them accessible in deeper layers. As a result, the network learns more efficiently how to better process this information, speeding up model training. Additionally, it reduces the number of parameters in the layers, as the extra layers with additional output halves do not need to be stored.</p><p>Consider a Transformer network without residual connections. In this scenario, information is not directly transferred between different layers, and each layer must receive and process information from scratch. This increases the number of required stages for training and escalates computational time and cost. Moreover, the likelihood of gradient vanishing increases, potentially leading to inadequate network performance. However, with the use of residual connections, these issues can be minimized, and network performance can be enhanced.</p><h3><strong>Position Embedding</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*Xpu4oazURA6IweGWhzmu7A.png" /><figcaption><a href="https://kikaben.com/transformers-encoder-decoder/">source</a></figcaption></figure><h3>Types of Position Encoding</h3><p>All types of Position Embeddings are used in Transformer-based architectures, but not all of them are utilized in every Transformer model. Below, we’ll examine them and the contexts in which they are used.</p><h3><strong>Fixed Positional Encoding</strong></h3><p>This interpretation uses a fixed vector to represent each position in the sequence. These vectors are typically learned during pre-training and shared across all sequences. It was used in the original Transformer paper and is still widely employed in many Transformer-based models, including various versions of BERT.</p><h3><strong>Learnable Position Interpretation</strong></h3><p>During training, the learnable position interpretation involves the creation of a distinct vector for every position in the sequence. This approach enables the model to adjust to the unique lengths and structures of different sequences. Some models, such as Transformer-XL, utilize this technique for natural language processing tasks, where each position within the sequence acquires a distinct positional embedding.</p><h3><strong>Relative Position Interpretation</strong></h3><p>This text explains the difference between two interpretations of token positions used in natural language processing models. The first interpretation is based on the relative positions of tokens, rather than their absolute positions. This interpretation is used in models such as Transformer-XL and Reformer, which aim to improve the efficiency of text processing tasks like machine translation, text generation, and sentiment analysis. The Reformer model is particularly useful for large-scale text processing projects because it can execute parallelism and optimize computational resources.</p><p>Some models use a combination of fixed and learnable positional embeddings, while others use alternative methods to integrate positional information. For example, the original Transformer model used sinusoidal positional encoding, which employs a sinusoidal function to encode the position of each token. Other models use rotational encoding methods. The choice of positional embedding method depends on the specific task and model design.</p><h3><strong>Conclusion</strong></h3><p>In Part 1, we discussed the essential terminologies used in Transformer and their significance. We discovered that some of these terms are combinations of their previous versions, while others are entirely new. It is highly beneficial to understand these concepts before diving into a thorough examination of the Transformer architecture. This understanding will help us easily grasp them when we encounter them in Part 2, where we will explore the Encoder and Decoder. The Transformer represents a beautiful amalgamation of various techniques from its predecessors to tackle tasks that were previously considered impossible to solve quickly. Thank you for joining me in this part. Part 2 will be released soon. Please share your thoughts and feedback so that we can continue learning together. Thank you.</p><p>Thank you for accompanying me on this journey into the world of deep learning.</p><p>The link to the article in Persian is available on virgool.io.</p><p>Part 2: We will delve into the architecture of Transformers piece by piece with examples and code.</p><p>If you’re interested, you can check out my other article, “<a href="https://medium.com/ai-advances/lord-of-the-rings-the-power-rings-are-the-pre-trained-models-a3de5b3a77e7"><strong>Lord of the Rings! The power rings are like pre-trained models in artificial intelligence!</strong></a></p><p><a href="https://medium.com/ai-advances/lord-of-the-rings-the-power-rings-are-the-pre-trained-models-a3de5b3a77e7"><strong># Part I: We will start by examining and comparing the most important pre-trained models for text.</strong></a>” on Medium.</p><p><a href="https://medium.com/@reza.shokrzad/the-impact-of-culture-on-persian-nlp-90c37c87cf47">The Impact of Culture on Persian NLP</a></p><p>I hope you’ve enjoyed the content.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fbb1d1e4d9b0" width="1" height="1" alt=""><hr><p><a href="https://aiadvances.org/transformer-is-all-you-need-fbb1d1e4d9b0">“ Transformer is All You Need ”</a> was originally published in <a href="https://aiadvances.org/">AI Advances</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lord of the Rings! The power rings are like pre-trained models in artificial intelligence!]]></title>
            <link>https://aiadvances.org/lord-of-the-rings-the-power-rings-are-like-pre-trained-models-in-artificial-intelligence-563d6dcb59e8?source=rss-707395aa8764------2</link>
            <guid isPermaLink="false">https://medium.com/p/563d6dcb59e8</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[robotics]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[pretrained-model]]></category>
            <dc:creator><![CDATA[M Javadnejadi]]></dc:creator>
            <pubDate>Tue, 16 Apr 2024 12:57:08 GMT</pubDate>
            <atom:updated>2024-04-16T14:05:32.488Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part III: We want to delve deeper into pre-trained models and simulation environments used for training in robotics (Atari, OpenAI Gym2, MuJoCo, RoboCup, RoboCup Soccer, Humanoid-Gym), as well as their challenges.</h4><blockquote>“Do not stop until they are found. You do not know pain, you do not know fear. You will taste man’s flesh!”</blockquote><blockquote><a href="https://www.youtube.com/watch?v=ICXWmG8bacM">Saruman</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WsR9bwrK8M-bfeMqVe84FQ.jpeg" /><figcaption>Generated on <a href="https://ideogram.ai/t/top/1">Ideogram</a>, as prompted by author</figcaption></figure><p>This article will be divided into three parts, which are as follows:</p><p>#Part I: We will start by examining and comparing the most essential pre-trained models for text.</p><p>#Part II: We will review and compare the most important pre-trained models (AlexNet, VGG, GoogLeNet, ResNet, MobileNet, and MobileNetV2) in the image field from the beginning until today.</p><p>#Part III: We will examine and compare the most important pre-trained models for Robotics.</p><p>In this trilogy, we aim to delve into pre-trained models in three parts: Text, Image, and Robotics. We aim to explore their concepts, emergence, and how these models work. We’ll also examine the different architectures and types of pre-trained models. We’ll explore which ones are the most powerful and whether pre-trained models and Transformers are the main strengths of LLMs. Additionally, we’ll discuss whether we would have powerful chatbots like ChatGPT today if pre-trained models and Transformers didn’t exist. Nowadays, chatbots are not just limited to the NLP field. For instance, GPT-4 is multi-faceted as it’s not just limited to text generation. We’ll also explore if they function similarly to RL. In the Robotics domain, we’ll explore what pre-trained models we have and which ones are better for Multimodal Models. We’ll also discuss if pre-trained models are only useful for NLP nowadays. In the Image domain, we’ll explore which models are the most powerful and how we can fine-tune or hyperparameter-tune each of these models for use. Join me in this trilogy as we explore and answer these questions together.</p><h3><strong>Overview</strong></h3><p>In parts 1 and 2, we discussed pre-trained models suitable for text and image tasks and explored commonly used models today. We analyzed the architectures of these models and how to use them for specific tasks. The two main pillars we need to reach AGI are language understanding and the ability for machines to see. There are many tasks associated with these two capabilities.</p><p>Imagine we have completely mastered these aspects and reached an optimal point for machines. Nowadays, machines are incredibly useful in areas such as security and health. We want to deploy them in machines that physically exist among us — robots.</p><p>When we hear the word “robot,” we may think of numerous Hollywood movies and stories featuring robots, both good and bad. From the tale of “<strong><em>Frankenstein</em></strong><em>”</em> to movies like “<strong><em>Star Wars</em></strong><em>”</em>, robots are often portrayed as highly advanced technology that indicates superiority in intelligence over humans.</p><p>However, the best depiction we have of robots and the ongoing discussions about their future is in the film “<strong><em>2001: A Space Odyssey.</em></strong>” This film perfectly illustrates the capabilities and dangers that robots or artificial intelligence may pose, as well as showing that ultimately human intelligence prevails.</p><p>Join me as we delve into the world of robots in this episode and explore when the idea of robots first entered the human mind, how perceptions of robots have evolved, and what models companies are using today to build them. Many companies are currently working on projects to build robots, and we will also discuss how robots learn the physical laws that we and other living creatures abide by. Stay tuned!</p><h3><strong>What is a robot?</strong></h3><p>Robots are machines created by humans that can imitate human intelligence. They are capable of sensing, perceiving, and physically interacting with their environment, and they can perform tasks that humans or other living creatures can do. There are several types of robots, such as industrial robots,<em> </em><strong><em>household robots</em></strong>, <strong><em>humanoid robots</em></strong>, and more. Industrial robots are mainly used for heavy mechanical tasks in factories to increase accuracy and speed in production. They might not have the ability to walk or talk, but household robots and humanoid robots need to have these abilities. The primary interface for a household robot, used for tasks such as cleaning the house or managing smart home systems, is through verbal communication. In the upcoming episodes, we will explore how robots learn and the different models available for this task. I invite you to join me in this fascinating and enticing exploration.</p><h3><strong>Throughout history</strong></h3><p>Throughout history, humans have always aimed to simplify tasks and advance their work in shorter periods, resulting in significant progress. From ancient times and the construction of sundials to windmills and dams to the Industrial Revolution and the mechanization of many tasks, we have witnessed humans’ desire to innovate. With the emergence of new technologies, especially in the age of computers and the rapid acceleration of computations, advanced robots became a prominent idea. <strong><em>Alan Turing’s</em></strong> article “<strong>Computing Machinery and Intelligence</strong>,” published in 1950, can be considered as the first article to address robotics after the emergence of artificial intelligence. The “<strong><em>Turing Test</em></strong>” was first introduced in this article, which has now become a significant concept in the field of computer science.</p><p><a href="https://academic.oup.com/mind/article/LIX/236/433/986238">I.-COMPUTING MACHINERY AND INTELLIGENCE</a></p><p>The most important question that Turing raises in this article and seeks to answer is: “Can machines think?” This question is addressed both philosophically and technically. For the first time in that article, he introduced the idea of the “imitation game,” which is the famous Turing Test. In this game, two people and a machine are involved, and one person, by asking questions from the machine and the other person, tries to figure out who is the machine and who is the human. The aim of this imitation game is for the machine to behave intelligently enough to mislead the observer and persuade them to consider the machine as a human. In the field of robotics, the evaluation of robots’ performance in interacting with humans and making intelligent decisions is done using a concept similar to the imitation game. The concept of the imitation game is also widely used in the field of reinforcement learning (RL). Reinforcement learning is a machine learning method that trains models to improve themselves based on their experiences and make smarter decisions. In reinforcement learning, a machine or agent gains experience through interaction with the environment a question-and-answered uses these experiences to evaluate and improve its performance.</p><p>Following Turing’s paper, the field of robotics underwent significant development, with many advancements taking place. One of the most important contributions was the paper “The Stanford Cart and the CMU Rover” by Hans Moravec, published in 1983.</p><p><a href="https://apps.dtic.mil/sti/citations/ADA133207">Defense Technical Information Center</a></p><p>This paper introduces two renowned robots, the <strong>Stanford Cart</strong> and <strong>the CMU Rover</strong>, and examines their capabilities in movement and interaction with the environment. The Stanford Cart was developed at Stanford University and was one of the early examples of autonomous vehicles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/363/1*R0yin134IM-YW7UBSlkZVA.png" /><figcaption>Stanford Cart with cable, 1961<strong>: </strong><a href="https://web.stanford.edu/~learnest/sail/oldcart.html">source</a></figcaption></figure><p>The Stanford Cart, designed by <em>Hans Moravec</em> in the <em>1960s</em>, was equipped with sensors and computational devices, enabling it to navigate different environments and interact with obstacles. It represented one of the earliest successes in the field of autonomous movement in outdoor environments.</p><p>The CMU Rover, developed at <em>Carnegie Mellon University</em>, was another robot designed for mobility in outdoor environments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*arRFo-cVpoU9Nui8zF3DBA.jpeg" /><figcaption>Iris, a small, boxy robot designed by CMU students, has passed its critical design review by NASA and is on track to land on the moon in the fall of 2021. <a href="https://www.cs.cmu.edu/news/2020/cmus-iris-lunar-rover-meets-milestone-flight">source</a></figcaption></figure><p>This robot is capable of traversing various terrains and performing tasks autonomously. The CMU Rover was employed by NASA as a lunar exploration robot.</p><p>Over the years, a vast number of articles have been published on robotics, making it impractical to review all of them in this article. Therefore, in the following sections, we will explore how robots learn, what pre-training models are available for them, and in what environments they can be trained. Robots physically interact with their environment, so it’s crucial to understand how they can be trained effectively. Join me on this exciting journey!</p><h3><strong>The most important types of pre-training</strong></h3><p>Some of the most commonly used pre-training data for Reinforcement Learning that we examine include:</p><h3><strong>Simulated Data</strong></h3><p>Such data are generated through computer simulation. Examples include <strong><em>D4RL</em>, <em>Meta-World, </em></strong>or<strong><em> Roboschool</em></strong>. Simulated data can be easily generated and managed, are cost-effective, and readily available. They boast high safety because using simulated data means there are no physical risks or threats to the robot or environment. By using this data, various conditions and characteristics of the environment can be precisely controlled, and multiple experiments can be conducted.</p><p>However, it may lead to a lack of adaptation to the real environment because simulated data do not reflect the conditions and characteristics of the real environment, and the robot model may encounter different conditions in the real environment. Simulating environments may not always fully reflect reality and may encounter issues such as differences in collision frequency with objects, inaccuracies in movement precision, etc., sometimes leading to problems in transferring learning because training with simulated data may not have the ability to transfer learning to the real environment and may require adaptation and experience in the real environment. Environments like <strong>OpenAI Gym</strong>, <strong>MuJoCo</strong>, <strong>RoboCup Soccer</strong> <strong>Simulation</strong>, etc., serve as important sources for generating simulated data.</p><h3><strong>Real Data</strong></h3><p>Some datasets assess the performance of robots in real-world settings or human experiences with robots in real environments, such as the <strong>Atari Dataset</strong> collected from human experimental data in Atari games. Real-world data represent the conditions and characteristics of actual environments. Models trained on real data can transfer learning to real environments, reducing the need for adaptation and experience in real environments. However, collecting real-world data may be costly and require more time and effort. In the real world, conditions are highly complex and uncontrollable, so models may encounter challenges such as noise and unexpected variations. This type of data is used for training reinforcement learning models.</p><p>Collecting real-world data is often more complex compared to simulation data, while simulation data are produced with greater accuracy and control. However, depending on the specific conditions and needs of each project, both types of data are used for pre-training robotics models. For example, if the project involves training a robot for autonomous driving in real cities, we can use real data collected from the robot’s cameras and sensors for pre-training the model. These data demonstrate how the robot should react to traffic, pedestrians, traffic lights, etc. For instance, companies manufacturing self-driving cars claim their vehicles are capable of driving in real road conditions.</p><h3><strong>Hybrid Data</strong></h3><p>This type of data combines the diversity of real and simulated data, allowing for increased control over environmental conditions. They can also improve the transfer of learning to real environments and somewhat mitigate the weaknesses of each type of data individually. However, managing and analyzing combined data is more complex and comes with higher costs. For example, <em>Gym Retro</em> uses human experience data in classic Atari games to train reinforcement learning models. Prominent technology companies like <em>Boston Dynamics </em>and <em>Tesla</em> may employ these methods to train their models and improve the performance and efficiency of their robots and devices. For instance, Tesla might utilize combined data to train its self-driving cars to enhance their performance in real-world conditions and improve driving safety.</p><h3><strong>Simulated environment</strong></h3><p>One of the significant ways of learning, even for humans, is the use of simulated environments. For example, to train pilots, both commercial and military, these environments are utilized. They provide a concept very similar to the cockpit environment and conditions during actual flights, allowing pilots to start flying while being in a simulated room. Through this method, pilots can learn flight conditions very effectively, even though it’s not real flying! Similarly, astronauts, prepare environments before going into space with conditions very similar to space and vacuum to learn how to behave in zero-gravity conditions.</p><p>The same approach applies to training robots. One of the ways to provide the necessary training for robots to learn their tasks is by using simulated environments. These environments, powered by libraries written for languages like Python, enable robots to learn tasks more efficiently and effectively. Due to the diversity of tasks and environments, for example, where physical laws are completely observed and executed, robots can learn better and faster. Later, we’ll examine some of these libraries and see how they work. Stay tuned!</p><h3><strong>Pre-training methods in robotics</strong></h3><p>Pre-training methods in robotics encompass a range of techniques and algorithms utilized for training and improving the performance of robotic models. These methods have been employed over time and are typically executed in simulation environments to mitigate the complexities and reduce the time and financial costs associated with training in real-world settings. For more complex robotic tasks, Deep Neural Networks (DNNs) are employed. Therefore, in their training, Convolutional Neural Networks (CNNs), and Recurrent Neural Networks (RNNs), particularly Transformers, are used.</p><p>For instance, models for object detection or vision in robots exist. The robot “<a href="https://bostondynamics.com/products/spot/"><strong>Spot</strong></a>,” developed by Boston Dynamics, utilizes DNNs for object detection and obstacle avoidance along its path. RNN-based models are employed for speech recognition and generation in robots involved in human-robot interaction, such as the robot “<a href="https://news.mit.edu/2001/kismet"><strong>Kismet</strong></a>,” created by the MIT Robotics Lab, which uses RNNs for detecting human emotions based on sound and generating appropriate responses using speech. Reinforcement Learning (RL) — -based models are used for training robots as intelligent agents in dynamic environments, as seen in DeepMind’s AlphaGo, which utilizes RL-based models to enhance gameplay strategies in select games like Go. Supervised learning-based models are also suitable for training robots to perform specific tasks in various environments. Companies like iRobot use supervised learning models to train their household robots like Roomba for specific tasks such as indoor cleaning. These models are trained using real-world data to provide the best performance under different environmental conditions.</p><p>Some of the pre-training methods in robotics include:</p><h3><strong>Pre-training Reinforcement Learning</strong></h3><p>In this method, the robot model undergoes pre-training using a predetermined dataset (typically from experiences or synthetic data) to reach a desirable and stable initial state. Then, in a simulated environment, they learn and perform the desired tasks to better perform in the real environment.</p><p>Pre-training data refers to data collected before starting the reinforcement learning process and used to train the model. These data may come from past experiences, such as data from a robot that has previously moved in a simulated environment, and the experiences from these movements are stored. Simulated environment data (physical or 3D simulations) are commonly used as substitutes for the real environment to safely and efficiently train the model without the need for direct experimentation in the real environment. Alternatively, human experiences (via human guidance) can be utilized. For example, if a robot is being trained to assist elderly individuals in a center, it can learn how to behave and interact with elderly people from the experiences of human caregivers.</p><p>However, whether this method is suitable for training all types of robots depends on the specific task for which the model is being trained. Success in training using reinforcement learning relies on valid and task-relevant pre-training data. For example, this method can be used for industrial robots that need pathfinding and movement in complex environments, household robots that need to learn to interact with various objects in the home environment, or self-driving vehicles that need to learn to navigate roads and urban environments. Then, to improve the robot’s performance in the real world, we can use the pre-trained model as input for reinforcement learning. In the next section, we will examine the most important simulation environments with code. Stay tuned!</p><h3><strong>simulation environments for RL</strong></h3><p>In the previous section, we saw how we can utilize pre-training data to facilitate RL learning. Now, let’s explore the important simulation environments available for this purpose. There are numerous models for this task, with the most important ones being:</p><h3><strong>DQN: Atari</strong></h3><p>The system DQN, based on rewards and penalties, was first introduced in an article in 2013 by DeepMind.</p><p><a href="https://arxiv.org/abs/1312.5602">Playing Atari with Deep Reinforcement Learning</a></p><p>In this system, the robot receives rewards for desirable actions and is penalized for undesirable ones. Experiences from Atari games are collected by reinforcement learning agents and used for training RL models. Each experience consists of the current state of the game, the action taken by the agent, the reward obtained, and the next state of the game. This dataset was initially used by researchers for training RL models like DQN. DQN stands for Deep Q-Network, an algorithm that utilizes a deep neural network to estimate the Q-value function. The Q-value function estimates the value of each action in a given environment. The robot observes the current state of the environment and selects an action based on the estimated Q-value function. It then receives a reward from the environment and updates the Q-value function based on the received reward using the deep reinforcement learning algorithm. This algorithm has been widely used in robotics, gaming, and general artificial intelligence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*AwZ-wt9iWtJ6QlgpV2GuBg.gif" /><figcaption>DQN: Atari <a href="http://dilab.kunsan.ac.kr/demo">source</a></figcaption></figure><p>The primary use of this dataset is in training and evaluating Reinforcement Learning algorithms for solving visual problems, particularly for video games like Atari. However, this dataset is not only suitable for training game models but can also be used for training models in robotics, where they need to decide how to interact with a dynamic and complex environment.</p><h3><strong>OpenAI Gym2</strong></h3><p>This tool was initially introduced in the paper “OpenAI Gym” by <em>Greg Brockman</em> and others from the OpenAI team. This paper was presented at the International Conference on Neural Information Processing Systems (NIPS) in October 2016.</p><p><a href="https://arxiv.org/abs/1606.01540">OpenAI Gym</a></p><p>OpenAI Gym is an open-source programming library for the development and testing of RL algorithms, providing developers with the ability to create and utilize a variety of testing environments. Since its introduction, this tool has been widely used as a primary tool for training and developing reinforcement learning algorithms.</p><p>To call OpenAI Gym in Python code, you simply need to use the Gym library and call the desired environment. Initially, you need to install the <a href="https://www.gymlibrary.dev/">Gym library</a>. Pay attention to the following command:</p><pre>!pip install gym</pre><p>Now we can call our desired environment using the `<em>make</em>` function. In the following code, we want to call the <em>CartPole</em> environment, one of the popular environments in OpenAI Gym used for testing and training RL algorithms. Pay attention to the code below:</p><pre><br>import gym<br><br># Choose the environment name<br>env_name = &#39;CartPole-v1&#39;<br><br># Create the environment<br>env = gym.make(env_name)<br><br># Start the environment<br>observation = env.reset()</pre><p>In the <em>CartPole</em> environment, an agent must balance a column called the “<em>cart</em>” using a “<em>pole</em>” placed on top of it. The cart can move left and right, and the agent must maintain the balance of the column using appropriate actions to prevent the system from shifting its position due to the real gravity of this environment. In robotics, the <em>CartPole</em> environment can be particularly useful for robots that need to maintain their balance. For example, consider a humanoid robot that needs to traverse a smooth path without obstacles and then needs to be able to turn and move its body while still maintaining its balance to prevent itself from falling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/1*ZmzJg6JAXBHxOoDBqA-q_w.gif" /><figcaption>OpenAI Gym. <a href="https://paperswithcode.com/dataset/openai-gym">source</a></figcaption></figure><p>The environments available in OpenAI Gym include a variety of different tasks and challenges, such as classic video games like<em> Space Invaders</em>, <em>Breakout</em>, <em>Pac-Man</em>, and others. These environments are very useful for testing and evaluating RL algorithms in the domain of video games. Control environments include robotic control problems and motor control tasks that help evaluate the performance of reinforcement learning algorithms in complex control problems. Additionally, graphical decision-making environments like <em>CartPole </em>and Mountain Car are used to test RL algorithms in simple and flexible problem settings. This library also provides tools for logging and evaluating the performance of algorithms so that users can improve and analyze their results.</p><h3><strong>MuJoCo</strong></h3><p>Developed by OpenAI in 2004, <a href="https://mujoco.readthedocs.io/en/latest/overview.html">MuJoCo</a> is a physics simulation engine that is used for simulating physical environments and creating simulation environments for training RL models. It is utilized across various domains such as robotics, motion control, RL model training, and scientific research. MuJoCo enables the creation of simulation environments with precise and dynamic physics, allowing RL algorithms to train in a safe and controllable environment and improve their performance.</p><p>To use MuJoCo, you need to install a library called <a href="https://github.com/openai/mujoco-py/blob/master/README.md">mujoco-py</a> for use in environments available in OpenAI Gym. This library provides the capability to call the MuJoCo simulation engine in Python and allows you to create and control simulation environments.</p><pre>!pip install mujoco-py</pre><p>For using MuJoCo, there are two ways: you can directly call it and use its libraries, or you can utilize the C API. However, using the C API requires some proficiency in C++. For accessing the C API and reading its documentation, you can refer to the following GitHub link:</p><p><a href="https://github.com/google-deepmind/mujoco/blob/main/README.md">mujoco/README.md at main · google-deepmind/mujoco</a></p><p>An example of using MuJoCo could be in the field of robotics control. For instance, MuJoCo can be utilized to create a simulation environment of a robot for training reinforcement learning algorithms to control the robot’s movements. These algorithms are empirically improved through interaction with the simulated environment and trained to operate effectively and reliably in real-world environments.</p><h3><strong>RoboCup Soccer Simulation 2D/3D</strong></h3><p>The football simulator RoboCup was first introduced in 1997 in a paper titled Introduction</p><p><a href="https://www.researchgate.net/publication/220605309_RoboCup-97_The_First_Robot_World_Cup_Soccer_Games_and_Conferences">https://www.researchgate.net/publication/220605309_RoboCup-97_The_First_Robot_World_Cup_Soccer_Games_and_Conferences</a></p><p>This simulation aimed to create a controllable and repeatable simulation environment for testing new artificial intelligence algorithms for robotic football. RoboCup Soccer is one of the prominent competitions in the field of robotics and artificial intelligence. These competitions have been held annually since 1997 in various locations around the world. The main goal of these competitions is the development and advancement of technologies related to artificial intelligence, robotics, and machine learning. RoboCup Soccer Simulation simulates a football field with robots, a ball, and obstacles, following FIFA rules with slight modifications to simplify the simulation. The robots in it use artificial intelligence algorithms to control their movements, decision-making, and interaction with other robots. It is held in both 2D and 3D formats. In the 2D competitions, robots play on a two-dimensional field and are displayed from a top view.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*6n9S5l_NlUYXEGMaWpvwfQ.png" /><figcaption>2D game visualization. <a href="https://ssim.robocup.org/">source</a></figcaption></figure><p>However, in the 3D competitions, the playing field is three-dimensional, and the robots play more realistically. The RoboCup simulation environment is very useful for training and testing new algorithms and ideas proposed for robotics and artificial intelligence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*i3AE20RNbgcHoKsiir3KfQ.png" /><figcaption>3D game visualization. <a href="https://ssim.robocup.org/">source</a></figcaption></figure><p>To use the RoboCup Soccer Simulation 2D/3D environment in Python, you can utilize various libraries that support this environment. Some of these libraries include `<em>PySimulator</em><strong><em>`</em></strong> and `<em>rcssserver3d</em><strong><em>`</em></strong>. You can call the competition environment using these libraries.</p><pre><br>from rcssserver3d import Server<br><br># Create a server instance<br>server = Server()<br><br># Start the server<br>server.start()<br><br># Interact with the robotic environment (code for interaction goes here)<br><br># Stop the server<br>server.stop()</pre><p>Installing and setting up the `<em>rcssserver3d`</em> library is highly system-dependent and can be quite complex. This library is typically used on <strong>Linux systems</strong> and requires additional configurations and setups. The installation and setup process is very intricate and depends on various factors such as the operating system, different versions, software dependencies, and more. Refer to the official guide and documentation of the rcssserver3d library for installation and setup instructions. After installation, you can use a code similar to the one shown above to call and interact with the RoboCup 3D environment.</p><p>In the next section, we’ll explore another approach to learning in robots.</p><h3><strong>Imitation Learning (IL)</strong></h3><p>The method you’re referring to is called <strong>Imitation Learning (IL)</strong>, and it’s a powerful technique used by humans and living beings alike. Imagine I want to learn the Tango dance online. I download dance tutorials and mimic the movements of the Tango master. After some practice and repetition, I can learn the Tango dance from them. Similarly, there exists a method for machines, especially in robotics.</p><p>In this method, the model learns its behavior by imitating an external source. The machine analyzes the behaviors of a sample or source and tries to mimic its patterns and methods.</p><p>The first step in IL is <strong>data collection</strong>, which typically involves gathering data such as images, videos, or other samples of desired behavior that we want the model to learn. The next step is <strong>model training</strong>, where the machine learning model is trained using the collected data. The model attempts to recognize and imitate the patterns and methods present in the data.</p><p>Next comes validation and <strong>parameter tuning</strong> after training. The model needs validation and parameter tuning to ensure it performs well on other data and properly imitates the behavior. After all these steps, the machine learning model is ready for use in applications or systems, which can include robotics, self-driving cars, or other artificial intelligence applications.</p><p><strong>For IL, we can have two main approaches:</strong></p><h3><strong>Behavioral Cloning</strong></h3><p>The supervised learning method is used for this purpose, in which the agent only demonstrates actions to the machine, and the machine simply repeats those behaviors exactly. Depending on the task at hand, this approach can be beneficial or detrimental. For example, consider a medical robot; naturally, the better it can replicate expert behaviors, the more effective it is. However, some robots interact more with their environment, which may change dynamically over time. Therefore, if the machine only performs specific behaviors it has learned in that environment, it may not be very efficient.</p><h3><strong>Inverse Reinforcement Learning (IRL)</strong></h3><p>This method allows robots to mimic human behaviors or other sources. In contrast to the Behavioral Cloning approach, where a machine model simply copies the behavior of an external source, IRL attempts to understand the reasons behind these behaviors and incorporates them as a reward function in an imitation learning problem. In IRL, the robot tries to understand the main problem that experts or other individuals are dealing with by analyzing human behaviors or other sources and using it for its decision-making. This allows the robot to improve its performance and execute similar behaviors to those of experts in new situations or problems it has not encountered before. This method is usually more complex and computationally efficient. One of the main applications of this method in robotics is autonomous driving, where the robot, by analyzing the behaviors of professional drivers and using IRL, can implement desirable and safe behaviors on various routes and act as an autonomous driver.</p><p>There are various applications for the Imitation Learning method. For example, in robotics, it can be used to teach tasks that are easy for humans, such as cooking or folding clothes, or in video games, where IL is often used to train AI agents by learning from skilled players. Additionally, in surgical robotics, a robot learning from expert surgeons can perform delicate surgeries effectively.</p><h3><strong>Implementation methods</strong></h3><p>For the IL method, there are pre-trained models available. These models are usually trained using methods such as CNN in Deep Learning. Typically, simulation environments are also used for implementing IL. You can use various libraries to work with simulation environments. For example, if you want to work with OpenAI Gym, you can install the` <em>gym library</em> `and use its training environments. These simulation environments can be physics simulators like OpenAI Gym, Mujoco, Unity ML-Agents, or simulation environments available in ROS (Robot Operating System).</p><h4><strong>The most important pre-trained models for the IL method:</strong></h4><p>DQN-based models, as fully described above, are used extensively for training robots in various tasks such as arms control, navigation, and gaming. Examples include <strong>Humanoid-Gym</strong> by <a href="https://docs.robotera.io/"><strong>RobotEra</strong></a>, a robotics company based in Hong Kong, which introduces a collection of simulation environments for training humanoid robots. It features characteristics like body dynamics, balance, and flexible movements of humanoids. It is primarily used for training Imitation Learning (IL) and Reinforcement Learning (RL) algorithms.</p><p>In IL, models trained on descriptive or descriptive and operational data are commonly used to perform correct actions. Descriptive data only include input features required for the model, without providing the corresponding output (action). In other words, these data provide information that describes the current state or environment, without presenting the corresponding action. Examples include images, videos, sensors, or other features describing the current state of the environment.</p><p>On the other hand, descriptive and operational data consist of a set of data that includes both input (descriptive) and output (action) features corresponding to the current state of the environment. These are essentially input-output pairs, which include images and corresponding movements (e.g., describing a state in a video game and the corresponding player movement) or data describing sensory and operational features of humans in a task (e.g., describing the environment’s state and human movement in driving or running).</p><p>The main goal in IL is to create a machine learning model called a “<strong>worker</strong>” from available data (usually a set of images or videos) or interaction with the environment, capable of imitating movements. These movements can be various operations, including robot movements, user motions in a video game, or even humanoid movements in a real or virtual environment. Although Humanoid-Gym is a powerful tool for imitation learning, it can also be used for reinforcement learning and other machine learning methods. Humanoid-Gym is an actively developed tool that is continuously improving.</p><h3><strong>Humanoid-Gym</strong></h3><p>Various robots, including <strong>XBot-S</strong> and <strong>XBot-L</strong> robots from RobotEra, have been trained using Humanoid-Gym. Companies like Agility Robotics have utilized Humanoid-Gym for training their Digit robot. <strong>ANYbotics</strong> has used it for training the <a href="https://www.anybotics.com/robotics/anymal/"><strong>ANYmal robot</strong></a>, and OpenAI has utilized it for training their <strong>Dactyl robot</strong>. Humanoid-Gym is a powerful tool for training humanoid robots. This library allows researchers and engineers to develop and test new robot control algorithms without the need for physical robot hardware.</p><p>The advantages of using Humanoid-Gym lie in its simulated environment, eliminating the risk of harming the robot or humans during training. It enables you to train your algorithms faster and more efficiently than training on a real robot and allows you to customize the simulation environment to match your robot and specific task. However, there always exists a gap between the simulated environment and the real world, which may affect the performance of your algorithm on a real robot. Additionally, Humanoid-Gym is a complex tool and may require specialized knowledge to use effectively.</p><h3><strong>Models based on Actor-Critic: A2C</strong></h3><p>This model consists of two deep neural networks, Actor and Critic. The Actor is a neural network responsible for generating actions and agent behavior in the environment and makes practical decisions based on the outputs of the Advantage Function. Generally, the Actor seeks to select a move with a greater advantage compared to other moves. Additionally, the Critic is another neural network responsible for estimating the Value Function of different states in the environment. The Critic estimates the values of states so that the Actor can select the best move. In fact, by combining these two networks, Actor-Critic improves the overall performance of the agent.</p><p>This algorithm <strong>updates the performance</strong> of neural network agents using a <strong>Loss Function</strong>, which includes the sum of errors in the value and advantage functions. Due to the combination of Actor and Critic as well as the use of online experience, this algorithm can effectively and quickly improve the performance of the agent. A2C has been used for training robots in various tasks such as <strong>arms control</strong>, <strong>navigation</strong>, and <strong>gaming</strong>.</p><h3><strong>TRPO (Trust Region Policy Optimization)</strong></h3><p>The <strong>TRPO (Trust Region Policy Optimization)</strong> algorithm was first introduced by John Schulman and his colleagues in 2015. The paper titled “Trust Region Policy Optimization” was presented at the International Conference on Machine Learning (ICML).</p><p><a href="https://arxiv.org/abs/1502.05477">Trust Region Policy Optimization</a></p><p>TRPO (Trust Region Policy Optimization) is an advanced algorithm in the field of reinforcement learning used for training policies in complex environments. This algorithm addresses the challenge of large and unstable changes during training by constraining the magnitude of policy updates. One of the key features of TRPO is the use of a trust region, where acceptable changes in policy are perceived. By imposing this constraint, TRPO ensures that any policy changes made during training lead to improved agent performance but are not significant enough to dramatically affect performance.</p><p>Another feature, Stable Progress, aims to create sustainable progress in training by never completely replacing the current policy with a new one. Instead of directly optimizing, TRPO uses trust region constraints to control policy changes and prevent unstable updates.</p><p>Additionally, TRPO employs a Direct Optimization Method, unlike many reinforcement learning methods that use gradient estimation techniques. This means that at each step, it tries to find a new policy that increases performance while imposing constraints to prevent unstable changes.</p><p>TRPO is one of the advanced and effective algorithms in reinforcement learning that provides significant improvements in training agents in complex environments. Due to its use of trust regions and stable progress, this algorithm can effectively deal with instability issues associated with training in complex environments and enhance agent performance.</p><h3><strong>PPO (Proximal Policy Optimization)</strong></h3><p>In 2017, John Schulman and his colleagues introduced the <strong>PPO</strong> algorithm in a paper titled “Proximal Policy Optimization Algorithms”.</p><p><a href="https://arxiv.org/abs/1707.06347">Proximal Policy Optimization Algorithms</a></p><p>PPO was introduced after TRPO as a simpler and more scalable method for training reinforcement policies. It offers improvements over TRPO by utilizing concepts like direct constraints on policy changes and performance enhancements. PPO is a reinforcement learning method based on gradient-based optimization algorithms and is used for training policies in Actor-Critic algorithms. PPO has been used for training robots in more complex tasks such as humanoid robot control and navigation in crowded environments. This algorithm has introduced improvements over previous methods and is designed to address the challenges of large policy changes during training and overfitting in reinforcement learning algorithms. The connection between this algorithm and the content mentioned above is that both algorithms (A2C and PPO) are used as Actor-Critic-based reinforcement learning methods.</p><h3><strong>T2T-ViL (Transformer to Transformer — Vision and Language)</strong></h3><p>is a deep neural network model introduced by researchers at Carnegie Mellon University in 2021 This model consists of <strong>two Transformer</strong> neural networks named “<strong>Text Transformer</strong>” for processing and interpreting text and “<strong>Vision Transformer</strong>” for processing and interpreting images. These two networks work simultaneously and continuously with each other. Now let’s see how it accomplishes this task.</p><h3><strong>Text Transformer</strong></h3><p>The T2T-ViL model is similar to models like GPT (Generative Pre-trained Transformer), which are suitable for processing natural language texts using the Transformer architecture. For example, GPT is used for generating text based on input text, while Text Transformer is used for processing and interpreting text about images. However, both of these models fundamentally utilize <strong>self-attention</strong> and f<strong>eed-forward</strong> networks for text processing.</p><h3><strong>Vision Transformer</strong></h3><p>A nascent model currently under development, which shows high potential for use in various robots, is a type of deep neural network utilized in T2T-ViL. The main advantage of Vision Transformer over previous models based on CNNs is that it does not require convolutional blocks; instead, it employs Transformer blocks, which can more effectively discover semantic patterns in images, including more complex semantic patterns. Vision Transformer is a type of Transformer model designed for image processing, differing subtly from traditional Transformer models used for text processing.</p><p>The Vision Transformer model divides the image into smaller patches, extracting visual features such as color, shape, and texture from each patch. It also utilizes self-attention to focus on relevant parts of the image, allowing the model’s output to be a category, a sequence of actions, a response to a question, etc. Furthermore, it employs an attention mechanism to focus on relevant parts of the image, whereas traditional Transformers utilize these mechanisms for text and words.</p><p>Such complex models are initially pre-trained to acquire deep knowledge of the content of images and texts. This generally involves two important stages. The first stage is Task-agnostic pre-training, where the model is trained on large and diverse datasets, including texts and images, to automatically learn patterns, features, and semantic relationships between input elements. Typically, methods like self-supervised learning and self-supervised models are used in this stage. For example, the model may be trained self-supervised or based on tasks like predicting the next word in a text. The next stage is Task-specific fine-tuning, where the pre-trained model is specifically trained on a particular task, such as object detection in images or text translation. This process helps the model gain deep knowledge about the desired task and provide better performance in that task.</p><p>These pieces of information can then be used in the Fine-tuning process, which occurs after pretraining the model, to train the model on a specific task such as images and their labels or texts and their counterparts, to provide better performance in task execution.</p><p>This model may be used in robots that utilize artificial intelligence to interpret and respond to user messages. For example, it can be used to train robots in tasks such as smart home robots or industrial robots like Dactyl for various tasks such as assembly and object manipulation, or to train social robots for interaction with humans and understanding natural language, or for training self-driving cars for understanding the surrounding environment and safe driving.</p><h3><strong>Conclusion</strong></h3><p>The title of this trilogy is “The Lord of the Rings,” with three crucial elements in the film for “control.” The first is Saruman’s speeches, which tempted him. Like the elves. Seeing like a great eye through which events could be seen and the Uruk-hai that he created, much like obedient robots. They neither tired nor slept nor disobeyed.</p><p>In parts 1 and 2 of this article, we extensively discussed pre-trained models suitable for text and images. We taught them. In part 3, we talked about the history of robotics and important articles in this field, as well as how they are trained from scratch. The robotics industry is still advancing and has a long way to go. Despite all the advancements and evolution, robots have not reached their full potential. For instance, unlike language models or machine vision models, they are not in a controlled environment. Robots need to improve to interact with real and physical environments. They can perform very well in controlled environments. However, in uncontrolled environments, the situation is different. Apart from the laws of physics, many of which are unpredictable, data in the real environment are being generated in real-time and there are thousands of possibilities for how events might unfold. Therefore, the training robots have received may not be suitable for many of the real-time occurrences.</p><p>Humans and living beings have managed to reach this stage over thousands of years, as well as instincts and biological forces. Perhaps if a model were designed in the future, for example, like a newborn living being, it could learn in the moment. Be the key to problem-solving. Solving all these problems could lead to achieving AGI. A model that can understand that it exists. We can have self-awareness. We know we are on the planet now. We have a goal. But artificial intelligence has not yet reached that stage. Now imagine this happening. Should we be afraid of it? Should we be happy? The most intelligent being on the planet is human. Of course, definitions of intelligence differ, and many people may have different definitions. Also, we know that artificial intelligence can be much smarter than many of us. If robots reach the stage of understanding themselves, we will be the second most intelligent. And if we don’t consider the danger of it, the most important thing is the one who has the key to AGI. Control! Remember the final scenes of Matrix 2 when Neo talked about “control.” It becomes somewhat terrifying. But from another perspective, it can be seen differently. Perhaps many unanswered questions and problems throughout history will be solved with AGI. What do you think? Please share your thoughts in the comments of this article.</p><p>Thank you for being with me. I am waiting for your comments.</p><p>Thank you for accompanying me on this journey into the world of deep learning.</p><p>The link to the article in Persian is available on <a href="https://vrgl.ir/MaQAG">virgool.io</a>.</p><p># <a href="https://medium.com/ai-advances/lord-of-the-rings-the-power-rings-are-the-pre-trained-models-a3de5b3a77e7">Part I: We will begin by examining and comparing the most important pre-trained models for text.</a></p><p><a href="https://medium.com/ai-advances/lord-of-the-rings-the-power-rings-are-like-pre-trained-models-in-artificial-intelligence-657926d52260">#Part II: We will review and compare the most important pre-trained models (AlexNet, VGG, GoogLeNet, ResNet, MobileNet, and MobileNetV2) in the image field from the beginning until today.# Part III: We will start by examining and comparing the most important pre-trained models for Robotics.</a></p><p>#Part III: We will examine and compare the most important pre-trained models for Robotics.</p><p>If you’re interested, you can check out my other article, “<a href="https://medium.com/ai-advances/digging-deeper-and-deeper-into-deep-learning-and-artificial-neural-networks-bad7b462ca59"><strong>Digging deeper and deeper into deep learning and artificial neural networks </strong># Part I: History of artificial intelligence and how simple neural networks work</a>.” on Medium.</p><p><a href="https://medium.com/@reza.shokrzad/the-art-of-computation-time-and-memory-optimization-in-ml-8848cbd5748b">The Art of Computation: Time and Memory Optimization in ML</a></p><p>I hope you’ve enjoyed the content.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=563d6dcb59e8" width="1" height="1" alt=""><hr><p><a href="https://aiadvances.org/lord-of-the-rings-the-power-rings-are-like-pre-trained-models-in-artificial-intelligence-563d6dcb59e8">Lord of the Rings! The power rings are like pre-trained models in artificial intelligence!</a> was originally published in <a href="https://aiadvances.org/">AI Advances</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lord of the Rings! The power rings are like pre-trained models in artificial intelligence!]]></title>
            <link>https://aiadvances.org/lord-of-the-rings-the-power-rings-are-like-pre-trained-models-in-artificial-intelligence-657926d52260?source=rss-707395aa8764------2</link>
            <guid isPermaLink="false">https://medium.com/p/657926d52260</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[pretrained-model]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[M Javadnejadi]]></dc:creator>
            <pubDate>Thu, 04 Apr 2024 20:53:55 GMT</pubDate>
            <atom:updated>2024-04-07T05:27:58.620Z</atom:updated>
            <content:encoded><![CDATA[<h4>#Part II: We will review and compare the most important pre-trained models (AlexNet, VGG, GoogLeNet, ResNet, MobileNet, and MobileNetV2) in the image field from the beginning until today.</h4><p><em>“His gaze pierces cloud, shadow, earth, and flesh. You know of what I speak Gandalf?</em></p><p><a href="https://www.youtube.com/watch?v=eS9ZbmfOJok"><em>Saruman</em></a><em>”</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k9YLbKETpcaZ7SP0yDfTkw.png" /><figcaption>The Eye of <a href="https://www.youtube.com/watch?v=3h55XRVDUtc">Sauron</a> is also called the Great Eye, the Eye of Barad-dûr, “<a href="https://www.youtube.com/watch?v=eS9ZbmfOJok"><em>a great eye lidless wreathed in flame</em></a>”</figcaption></figure><blockquote>“I used a description of the great eye of Sauron from the Lord of the Rings movie to depict ‘machine vision’ in this article.”</blockquote><p>This article will be divided into three parts, which are as follows:</p><p>#<a href="https://medium.com/ai-advances/lord-of-the-rings-the-power-rings-are-the-pre-trained-models-a3de5b3a77e7">Part I: We will start by examining and comparing the most essential pre-trained models for text.</a></p><p>#Part II: We will review and compare the most important pre-trained models (AlexNet, VGG, GoogLeNet, ResNet, MobileNet, and MobileNetV2) in the image field from the beginning until today.</p><p>#Part III: We will examine and compare the most important pre-trained models for Robotics.</p><p>In this trilogy, we aim to delve into pre-trained models in three parts: Text, Image, and Robotics. We aim to explore their concepts, emergence, and how these models work. We’ll also examine the different architectures and types of pre-trained models. We’ll explore which ones are the most powerful and whether pre-trained models and Transformers are the main strengths of LLMs. Additionally, we’ll discuss whether we would have powerful chatbots like ChatGPT today if pre-trained models and Transformers didn’t exist. Nowadays, chatbots are not just limited to the NLP field. For instance, GPT-4 is multi-faceted as it’s not just limited to text generation. We’ll also explore if they function similarly to RL. In the Robotics domain, we’ll explore what pre-trained models we have and which ones are better for Multimodal Models. We’ll also discuss if pre-trained models are only useful for NLP nowadays. In the Image domain, we’ll explore which models are the most powerful and how we can fine-tune or hyperparameter-tune each of these models for use. Join me in this trilogy as we explore and answer these questions together.</p><h3><strong>Overview</strong></h3><p>In part 1, we discussed the importance of pre-trained models suitable for text and their relevance in today’s world. Large Language Models (LLMs), especially GPT-3 and subsequently GPT-3.5, have gained immense popularity, leading to increased attention in AI discussions. We’ve seen various pre-trained models for constructing powerful LLMs. In part 2, we’ll learn about models suitable for image processing, which is a crucial capability for living beings, including humans. “<strong>Sight</strong>” is one of the primary ways we learn and understand the world around us.</p><p>Infants learn through sight, which is why computer vision is essential in the field of AI. Machines can interact with the surrounding world through machine vision. Image recognition models have evolved beyond text generation and can now produce sound and images. Even GPT-4 and Gemini can perform image recognition and analysis. Image-generating models like DALLE, Midjourney, and ideogram models have emerged and OpenAI recently introduced the powerful video-generating model Sora.</p><p>In this part, we’ll discuss pre-trained models related to images, when they were introduced, and how they evolved. We’ll compare these models to understand their nature and realize that each has its strengths and weaknesses. For instance, heavy models like Inception or ResNet may not be suitable for tasks on mobile devices. We’ll also discuss how mistake percentages in these models have decreased over time and the ideas employed to achieve this.</p><p>Join me on this exciting journey to explore the world of pre-trained models for image processing!</p><h3><strong>AlexNet</strong></h3><p>In 2012, a groundbreaking deep learning model named AlexNet was introduced, marking a significant moment in the history of data science and deep learning. Developed by Alex Krizhevsky, Ilya Sutskever, and Geoffrey Hinton, this model triumphed over the ImageNet Large Scale Visual Recognition Challenge (ILSVRC) with remarkable accuracy, demonstrating that deep CNNs (Convolutional Neural Networks) are capable of high-accuracy image recognition.</p><p><a href="https://papers.nips.cc/paper/4824-imagenet-classification-with-deep-convolutional-neural-networks">ImageNet Classification with Deep Convolutional Neural Networks</a></p><p>AlexNet is a deep neural network that comprises 8 layers, five of which are convolutional layers and three are fully connected layers. To improve training speed, this model uses the ReLU activation function instead of the sigmoid or tanh functions. AlexNet also employs the <strong>Dropout</strong> technique to prevent overfitting.</p><h3><strong>AlexNet VS LeNet</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vwgx9h1jfTWZKlyAV2mlbw.png" /><figcaption>On the left side, you can see the architecture of LeNet, and on the right side, the architecture of AlexNet is displayed for comparison. <a href="https://en.wikipedia.org/wiki/AlexNet">Source</a></figcaption></figure><p>In the top left image, you can see the architecture of LeNet. Although slightly different from the CNN network first introduced by Yann LeCun in 1989, its foundation and functionality are similar. This CNN network was used to recognize handwritten digits in images and was the first of its kind to utilize convolutional layers and pooling layers for feature extraction from images.</p><p>The LeNet architecture is designed for smaller images (<em>28x28x1</em>) with a single channel (grayscale), while AlexNet is designed for larger images (<em>224×224×3</em>) with three channels. LeNet consists of 2 convolutional layers with <em>5x5</em> kernels, followed by average pooling layers. In contrast, AlexNet includes 5 convolutional layers with kernels of various sizes, followed by max pooling layers. The choice of pooling type depends on the features of the images and the network’s target problems. In AlexNet, the use of <em>max pooling </em>typically enhances the detection of important image features.</p><p>LeNet uses the sigmoid activation function, while AlexNet employs ReLU in the network. <strong>ReLU is more suitable for deeper</strong> and more complex networks because it increases training speed and prevents the vanishing gradient problem.</p><p>The LeNet model comprises three fully connected layers with fewer neurons: <em>120, 84, and 10</em>. The last layer has <em>10 neurons</em> because it is designed to recognize handwritten digits <em>0–9</em>. Similarly, AlexNet also has three dense layers, with two layers each having 4096 neurons and one layer with <em>1000 neurons</em> since it is designed for a <em>1000-class</em> problem. The difference in the number of neurons is related to the distinguishable features of each network and the size of the input data (images). Using <strong>more neurons</strong> in deep networks like AlexNet can help the network detect more complex features.</p><p>Another noteworthy point is that due to the complexity of the model and the prevention of overfitting, AlexNet employs techniques like <strong><em>Dropout</em></strong>. AlexNet is one of the first CNNs to use Dropout. Whereas in LeNet, there’s <strong>no need</strong> for Dropout as it was introduced at a time when the Dropout technique had not yet been proposed.</p><p>As AlexNet is one of the earliest deep CNN models, it may have some limitations and weaknesses compared to later models we will examine, such as VGG and ResNet. The most significant limitation is its <strong>shallow depth</strong>, as computational capabilities were limited at the time of its introduction, and training deeper networks was not feasible. Another point is the use of Dropout in AlexNet, which from one aspect can enhance model stability, but on the other hand, may lead to the loss of useful information during the training process.</p><h3><strong>block structure</strong></h3><p>CNN architectures use blocks, which are groups of similar and sequential layers combined. Using blocks helps the network to extract features more efficiently while reducing model complexity.</p><p>In block structures, parameters are shared locally, reducing the total number of model parameters and consequently reducing model complexity and memory consumption. This means that parameters for multiple convolutional layers in a block are not calculated separately for each layer, but instead use a set of <strong>shared parameters</strong>. Because parameters are shared locally, gradients are computed concerning them. They are averaged across all convolutional layers, which can prevent gradients from vanishing. Additionally, <strong>non-linear activation functions</strong> like ReLU are often used in these blocks. These functions transform different inputs into non-linear outputs, inducing local shocks in gradients, and preventing gradient vanishing.</p><p>Moreover, different image features are <strong>extracted hierarchically</strong>. Lower layers seek simple features like edges or corners, while higher layers look for more complex features like patterns, objects, and ultimately different image classes. These features are sent as inputs to subsequent layers hierarchically, which increases the network’s power and efficiency. If this hierarchical structure is absent, and all features are extracted from the image in parallel, the model may not be able to detect more complex and meaningful features in the images, leading to reduced accuracy and performance of the model. In the models we will see in later sections, these block structures allow us <strong>to go deeper</strong> into the neural networks, making them deeper and more powerful.</p><h3><strong>VGG (Visual Geometry Group)</strong></h3><p>The VGG architecture is composed of numerous repetitive blocks. The concept of using blocks was initially introduced by the Visual Geometry Group (VGG) at <strong>the University of Oxford</strong> in 2014. This was presented in a paper by Karen Simonyan and Andrew Zisserman that outlines their CNN architectures.</p><p><a href="https://arxiv.org/abs/1409.1556">Very Deep Convolutional Networks for Large-Scale Image Recognition</a></p><p>The VGG model uses a structure that includes <strong>repetitive blocks</strong> consisting of stacked Convolutional layers and Pooling layers. These blocks are arranged sequentially, gradually reducing the size of the input image and extracting its features. This structure enhances the power and depth of the network, allowing it to identify more complex patterns and features in images.</p><p>This model has a simple and easy-to-understand architecture that is made up of multiple Convolutional layers stacked together. Each layer uses a convolutional filter with a small size of <em>3x3</em> and zero-padding. This enables the model to achieve higher accuracy in detecting detailed features such as edges.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*-1e1eISD88_DunrR4Tkm3w.jpeg" /><figcaption>In the image, you see the differences between the architectures of VGG16 and VGG19. <a href="https://datahacker.rs/deep-learning-vgg-16-vs-vgg-19/">Source</a></figcaption></figure><p>VGG is a convolutional neural network that is structured by repeating layers. The layer and block structures can be seen in the image above, represented by different colors. The network consists of numerous convolutional and pooling layers, applied in an alternating fashion. This arrangement enables the network to extract more complex features from images. For instance, VGG-16 and VGG-19 networks have 16 and 19 convolutional layers, respectively, combined with pooling layers.</p><h3><strong>Weaknesses of VGG</strong></h3><p>The VGG architecture uses <em>3x3 convolutional</em> filters throughout the network to transform a point in the image based on the points surrounding it. This leads to the repeated presence of <strong>similar information</strong> across the entire network, which can result in excessive information redundancy, increase the risk of overfitting, and decrease training and execution efficiency. To prevent overfitting, methods such as <strong>dropout, regularization, and data augmentation</strong> are commonly used. The main differences between VGG and AlexNet are <strong>the number of layers</strong> and <strong>the structure of the blocks</strong>. VGG uses convolutional filters with smaller dimensions, allowing it to detect more detailed and precise features. Most importantly, with the VGG architecture,<strong> we can penetrate deeper</strong>. Stay tuned for further exploration.</p><blockquote><strong>We need to go deeper!</strong></blockquote><h3><strong>Inception (GoogLeNet)</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kWaghDnTKzostfWXMdm8Ig.jpeg" /><figcaption>The image of the Inception architecture as presented in the original article is the <a href="https://arxiv.org/abs/1409.4842">source</a>.</figcaption></figure><p>The Google Research team introduced the Inception model, also commonly known as GoogLeNet, in 2014.</p><p><a href="https://arxiv.org/abs/1409.4842">Going Deeper with Convolutions</a></p><p>The Inception model, which is also commonly referred to as GoogLeNet, is a well-known and complex deep CNN model that is used for image recognition. The main structure of the Inception model is based on the concept of an “<strong>Inception block</strong>” which typically consists of <strong>multiple parallel branches</strong> of convolutional operations with varying sizes and pooling. These branches are then concatenated along the channel dimension to form the output of the block. The term “<strong>channel dimension</strong>” refers to the number of feature maps that are extracted in a convolutional layer. In simpler terms, the Inception model generates a more comprehensive and general feature of the image by combining features from different branches of the Inception block. The channel dimension size is the size of the inputs and outputs of the layers. Each layer in the Inception model can apply several convolutional filters and provide a set of features represented by these filters as output. For example, if a layer of the Inception model has inputs with dimensions of <em>128x32x32</em>, the channel dimension here would be equal to <em>128</em>.</p><p>This design allows the network to <strong>extract features</strong> at varying scales and abstraction levels simultaneously, thereby improving the network’s ability to <strong>detect patterns </strong>and <strong>complex structures</strong> in images. Inception is typically suitable for tasks related to image detection and classification.</p><h3><strong>Inception block</strong></h3><p>The Inception module, found in the GoogleNet model, has two versions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*__f1yuTx3wpiHApMGajJ6Q.png" /><figcaption>The image of the “naïve” Inception module is presented in the original article. <a href="https://arxiv.org/abs/1409.4842">source</a></figcaption></figure><p>The image above shows a <strong>“naïve” Inception</strong> of the Inception block, which is made up of multiple image processing operations running in parallel. The architecture makes use of Convolutional Filters of different sizes. Neural networks are computationally intensive, so to reduce the workload, a <em>1x1 Convolutional layer</em> is included before the <em>3x3 and 5x5</em> <em>Convolutional</em> layers. However, this approach can have drawbacks since increasing the network’s depth can significantly increase its complexity and number of parameters, leading to overfitting. Also, the basic version uses <em>3x3 Max pooling</em>, which helps identify important features in different regions of the image and is an efficient method for reducing the number of parameters in the network. This can help to mitigate overfitting. However, choosing the right architecture depends on the specific network conditions, data type, and the problem at hand. To address these challenges, an alternative architecture for the Inception block has been proposed and is commonly used, as shown in the image below. The next model is the Inception module with dimension reductions, which you can see in the image. Please pay attention to the details in the image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*AQc7TCxOxf88a3RQW7OI2g.png" /><figcaption>The image depicts the Inception module with dimension reductions as described in the original paper<a href="https://arxiv.org/abs/1409.4842"> source</a></figcaption></figure><p>The Inception module version we’re discussing here uses some tools to reduce computational complexity and the number of parameters. To do this, it employs a <em>1x1 convolution</em> in its architecture. The order in which the <em>1x1, 3x3, and 5x5 convolutions</em> are used depends on the model settings and the problem at hand. However, generally, the <em>1x1 convolution</em> is applied first. This allows the model to gather and combine information from different channels, thus improving the model’s representational power. Then, the <em>3x3 and 5x5 convolutions</em> are used for complex feature extraction. Also, a <em>1x1 convolution</em> is applied after the <em>Max Pooling</em> operation, which helps to reduce the spatial dimensions of features and decrease the number of parameters. This can effectively reduce computational burden and model complexity and prevent overfitting.</p><h3><strong>Inception Vs VGG ، AlexNet</strong></h3><p>The main difference between Inception and popular models like VGG and AlexNet lies in their structure and architecture. Inception uses the Inception block, which is a combination of convolution operations with different sizes and windows. VGG and AlexNet, on the other hand, are constructed with various combinations of convolutional and pooling layers. Inception is recognized as a deep model, whereas both VGG and AlexNet have a moderate depth. Due to the high complexity of the Inception model, it requires more computational resources compared to VGG and AlexNet. However, the choice between these models depends on the desired accuracy and the available computational resources. Would you like to move on to the next section now?</p><h3><strong>ResNet (Residual Network)</strong></h3><p>In a paper published before the ResNet paper, “Kaiming He” argued that increasing the depth of neural networks may not always lead to improved performance. This is because deeper networks may suffer from increased overfitting, which happens due to their ability to memorize training data more quickly.</p><p>The ResNet (Residual Network) model is a type of CNN architecture, and it was first introduced in the paper titled “Deep Residual Learning for Image Recognition.” The paper was published by Kaiming He, Xiangyu Zhang, Shaoqing Ren, and Jian Sun in 2015. The ResNet paper was presented at the CVPR (Conference on Computer Vision and Pattern Recognition) conference in 2016.</p><p><a href="https://arxiv.org/abs/1512.03385">Deep Residual Learning for Image Recognition</a></p><p>ResNet is a neural network that was introduced after the article mentioned. It solves the problem of overfitting by using structures called <strong>Residual Blocks</strong>, which have deeper layers. These blocks consist of two deep CNN layers and use <strong>shortcut connections</strong>, also known as <strong>skip connections</strong>. The shortcut connections directly transmit information from lower layers to higher layers instead of adding new layers. The input to the network is augmented with a direct path called the <strong>Identity Path</strong> to the output layer. The shortcut connections prevent the loss of information throughout the depth of the network and allow gradients to be more effectively propagated from layer to layer. This improvement in gradient propagation leads to more stable and accurate network training. Then, the direct path is combined with the output of the additional layer and fed into a non-linear operation like <strong>ReLU</strong> activation.</p><p>Let’s see the structure of it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rt5fErvcjSsWQHqsENgFOg.png" /><figcaption>The image above depicts a section of a Residual Network, and the image below it clearly illustrates Residual Blocks. <a href="https://jananisbabu.github.io/ResNet50_From_Scratch_Tensorflow/">source</a></figcaption></figure><p>As we increase the depth of a deep neural network, we face the problem of <strong>vanishing gradients</strong> due to the large number of layers and parameters. This issue can be addressed by using Residual Blocks in ResNet. Residual Blocks make it easier for the network to train deep models and reduce the vanishing gradients problem throughout the network’s depth.</p><p>To understand the vanishing gradients problem, it is important to note that the gradients in the <strong>backpropagation</strong> process can become unstable. During backpropagation, gradients are calculated and weights are updated based on the<strong> loss function</strong>, which is usually the error function. This results in gradients associated with lower layers of the network decreasing significantly, sometimes almost to zero. As a result, important information in the lower layers may be heavily reduced or even lost entirely.</p><p>To overcome the vanishing gradients problem, specialized structures such as Residual Blocks and Batch Normalization are commonly used. These structures significantly enhance stability and effective learning in deep neural networks.</p><h3>MobileNet</h3><p>The MobileNet model is a type of deep convolutional neural network designed for mobile devices and applications with limited computational resources. This model was first introduced in 2017 by Andrew G. Howard and Diego F. G. S. Pinto in their research paper.</p><p><a href="https://arxiv.org/abs/1704.04861">MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications</a></p><p>The MobileNet model is notable for its use of advanced techniques, such as <strong>Depthwise Separable Convolution</strong>. This technique enables the MobileNet model to achieve accuracy levels comparable to those of deeper models while reducing the number of parameters and computational overhead. As a result, MobileNet is a suitable choice for mobile devices and applications with limited resources.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*xPkUW8NWDwWp_-EdCM8ihw.png" /><figcaption>You can see the overall architecture of MobileNet. (A) The overall MobileNet architecture and (B) an in-depth explanation of the DS (Depthwise Separable<strong> </strong>convolution) layer. <a href="https://www.researchgate.net/figure/Illustration-of-the-MobileNet-architecture-A-The-overall-MobileNet-architecture-and_fig3_340470168">Source</a></figcaption></figure><p><strong>The Depthwise Convolution</strong> stage processes each input channel separately using a depthwise convolution filter. In the Pointwise Convolution stage, the features extracted from the previous stage are combined using a <em>1x1 convolution </em>filter. These two stages work together to reduce the number of parameters and the overall model size.</p><p>MobileNetV2 is an improved version of MobileNet that has shown significant improvements in performance and accuracy. This is achieved by increasing the number of parameters in the model.</p><h3><strong>MobileNetV2</strong></h3><p>The MobileNetV2 model was introduced at the CVPR conference in 2018. However, the final version was released in 2019 after revisions.</p><p><a href="https://arxiv.org/abs/1801.04381">MobileNetV2: Inverted Residuals and Linear Bottlenecks</a></p><p>The MobileNetV2 model is widely used for applications and projects that require image detection or object classification on mobile devices. The model features new blocks called Inverted Residuals, which are inspired by the Residual Blocks in ResNet, but with significant differences. MobileNetV2 includes <strong>two types</strong> of blocks: a residual block with a stride of 1, and a block with a stride of 2 for downsizing. The term “<strong>stride</strong>” refers to the number of pixels the block filter moves in each image step. You can refer to the image below for a better understanding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*mYfLI_eHw7S5lKDc6f8c9Q.jpeg" /><figcaption>This image clearly illustrates the difference between the two types of blocks, taken from the original article. <a href="https://arxiv.org/abs/1801.04381">source</a></figcaption></figure><p>Both types of blocks in MobileNetV2 comprise three layers. The first layer is a <em>1×1 convolution</em> with a ReLU6 activation function. ReLU 6 is a type of ReLU activation function that <strong>sets negative values to zero</strong> and constrains output values between <strong>zero and six</strong>. This is to prevent <strong>gradient explosion</strong> <strong>issues</strong> and ensures that the maximum suitable output is 6.</p><p>For models designed for mobile devices, computational efficiency is of utmost importance. Using ReLU 6 instead of ReLU is not only effective in reducing computational costs but also reduces the number of parameters in the model. This, in turn, decreases the volume and memory required for training and execution, leading to faster model execution. This can help extend the device’s battery life and improve energy efficiency.</p><p>The difference between ReLU 6 and ReLU can be observed in the figure below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7rSLjI2A6ug8J_VEy_32fw.jpeg" /><figcaption>I have created a plot using Python code that compares ReLU versus ReLU 6.</figcaption></figure><p>In certain instances, when the output values go beyond 6, the ReLU 6 constraint can cause the loss of valuable information, which may result in decreased accuracy, particularly in models that use non-linear activation functions. Using ReLU 6 instead of ReLU can have its own pros and cons, depending on the type of data, the specific problem, and the constraints in place.</p><p>When we use a block with a stride of one, the size of the output image is the same as the input image size. A stride of two in a block reduces the size of the output image to half the size of the input image. This means that with a stride of two, the filter moves two pixels forward in each step, leading to a reduction in the image size. These blocks allow for efficient management of limited resources on mobile devices while maintaining acceptable accuracy in detection. As a result, MobileNetV2 is recognized as a primary choice in this field.</p><h3><strong>Residual Block Vs Inverted Residuals</strong></h3><p>In the ResNet model, the Residual Block uses both a direct path and a side path (Shortcut Connection) to add the input to the output of deeper layers. However, the Residual Block in the Inverted Residuals architecture has been modified.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K-a9p9roD84nmDofXMy-Ng.png" /><figcaption>This image is included in the MobileNetV2 article because it provides very detailed explanations. The picture has been accompanied by descriptions, making it very effective in illustrating the differences between Residual Blocks and Inverted Residuals. <a href="https://arxiv.org/abs/1801.04381">Source</a>.</figcaption></figure><p>The input of the initial layer goes through a lighter Operation Layer for initial modifications and simpler feature detection. An Operation Layer refers to any layer in neural networks that performs operations or processing such as convolution, activation, normalization, etc. Using a deeper layer as the Operation Layer in the Inverted Residuals architecture increases feature dimensions as deeper layers extract more complex features and higher-level information. To reduce dimensionality and add flexibility to the network, another Operation Layer consisting of a 1x1 Convolution is employed. Therefore, a lighter layer is used for initial modifications, followed by deeper layers for complex changes.<br>Several deep neural network-based models exist for image recognition tasks, including <strong>EfficientNet, DenseNet, and NASNet</strong>. You can use popular libraries like TensorFlow or PyTorch to utilize these models. These libraries support access to pre-trained models, allowing you to fine-tune them with your own data or use them for image recognition tasks.</p><h3><strong>Pre-trained models in TensorFlow &amp; PyTorch</strong></h3><p>The aforementioned pre-trained models are among the most significant models in the image processing domain and can be imported into Python using TensorFlow or PyTorch libraries. For example, you can load pre-trained models in TensorFlow using the `<em>tf.keras.applications</em>` class. The following code, taken from the <em>keras.io </em>website, is worth noting.</p><pre><br>from keras.applications import MobileNet<br><br>model = MobileNet(<br>    input_shape=None,<br>    alpha=1.0,<br>    depth_multiplier=1,<br>    dropout=0.001,<br>    include_top=True,<br>    weights=&quot;imagenet&quot;,<br>    input_tensor=None,<br>    pooling=None,<br>    classes=1000,<br>    classifier_activation=&quot;softmax&quot;,<br>)</pre><p>The code above contains adjustable parameters which are used for hyperparameter tuning. This code allows us to load pre-trained models in the image domain by replacing their names after importing them. In PyTorch, you can also use the `<em>torchvision.models</em>` classes to load pre-trained models. The following code demonstrates how this can be achieved.</p><pre><br>import torch<br>import torchvision.models as models<br><br># Load the pre-trained ResNet model<br>model = models.resnet50(pretrained=True)<br><br># Display the architecture of the model<br>print(model)</pre><p>The code provided can be used to access all pre-trained models for image domain, except for the MobileNet model. This is because the MobileNet model is not included in the `<em>torchvision</em> `library. However, you can still use other libraries, like `<em>PyTorch Hub`</em> or external sources, to load the MobileNet model and use it in PyTorch. Please refer to the code below for more details.</p><pre><br>import torch<br>model = torch.hub.load(&#39;pytorch/vision:v0.10.0&#39;, &#39;mobilenet_v2&#39;, pretrained=True)<br>model.eval()</pre><p>You can utilize MobileNet by making a call to it using the given code.</p><h3><strong>How can we fine-tune a pre-trained model for image tasks?</strong></h3><p>In Part 1, we explored how to perform Fine-tuning for pre-trained text models. Similarly, we can also apply Fine-tuning to pre-trained image models. The process involves selecting a pre-trained model that is suitable for our task and then customizing it by adding or removing some layers. It is essential to label our training data correctly and ensure that our dataset is large enough as deep neural networks require <strong>a lot of data</strong> to learn effectively. The code examples above demonstrate how to load and Fine-tune a model in TensorFlow or PyTorch for a specific task.</p><h3><strong>Fine-tuning the Recurrent Layers</strong></h3><p>If our model contains recurrent layers like <strong>LSTM (Long Short-Term Memory)</strong>, then we must fine-tune these layers. Fine-tuning LSTM can help process sequential data such as texts and images. It can also help in generating image captions or identifying various components of an image. <strong>The Bidirectional LSTM (BiLSTM)</strong> model is an extended version of LSTM, which performs the same tasks but considers information from two different time directions. BiLSTM can consider information both before and after a specific point in the input data, which is useful for predicting sequential data or understanding time sequences.</p><p>Another type of recurrent network is the <strong>Gated Recurrent Unit (GRU)</strong>, which functions similarly to LSTM but with a simpler structure. GRU is also used for tasks similar to LSTM.</p><p>Furthermore, models like the <strong>CNN-LSTM</strong> Model combine convolutional neural networks (CNN) with recurrent networks such as LSTM or GRU. This combination is typically used for image captioning, which is an important task in natural language processing and computer vision. In image captioning, the model generates sentences that provide a complete and accurate description of the image content. For example, if there is an image of a dog in the yard, the model generates sentences describing important visual features, like the type of dog and its location in the yard. These are just a few examples of models that include recurrent layers and are used for processing images.</p><p>After adjusting the model, we can train it using available training data. In the next part, we will discuss the differences and advantages of training a model from scratch versus using a pre-trained model. Stay tuned.</p><h3><strong>Training from scratch versus Fine-tuning</strong></h3><p>Fine-tuning is a different approach to training a model compared to starting from scratch. In Fine-tuning, we begin with a pre-trained model that has already undergone training on a large dataset like ImageNet and has acquired weights and parameters independently of our training data. We then adjust the weights and parameters of the pre-trained model with our training data instead of randomly initializing the weights and beginning from scratch.</p><p>When Fine-tuning, we use a smaller learning rate compared to training from scratch. This is done to make smaller changes to the parameters and gradually adapt the pre-trained weights to the new data. Additionally, the number of epochs may be fewer compared to training from scratch. This is because the pre-trained model has already learned key features from previous data, and by adjusting the weights and parameters of the model, only a few epochs may be enough for it to adapt to the new data and perform well.</p><h3><strong>Why do we freeze layers?</strong></h3><p>Fine-tuning is a process where we update the <strong>weights</strong> of only the higher layers of a network, which perform more specific tasks and may need re-adjustment on our training dataset for new tasks. We freeze the lower layers in this process, meaning we do not change their weights.</p><p>Lower layers of CNN networks extract basic and primitive features of images such as edges and textures through convolutional filters in the initial layers of the network. By freezing the last layers in the Fine-tuning process, we ensure that their weights remain constant. This allows the model to retain valuable knowledge learned in the pre-trained stage and adapt to the challenges and specific features of the new dataset or task.</p><p>This helps preserve the initial features learned from the pre-trained data, especially if our training dataset is relatively small or the task we want to perform is relatively similar to the task the original model was trained on.</p><h3><strong>Evaluation of Fine-tuned Models</strong></h3><p>The evaluation stage in pre-trained models is similar to the process of training a model from scratch. This involves evaluating the accuracy, confusion matrix, and other evaluation metrics such as <em>Precision, Recall,</em> and <em>F1-score</em>. However, pre-trained models are often trained on large datasets, such as ImageNet, before fine-tuning, which enables them to recognize patterns in images by leveraging general information and features.</p><p>Therefore, when evaluating pre-trained models, it is essential to ensure that the model can effectively apply the information learned from pre-training in the given task and provide satisfactory performance.</p><p>To evaluate the model with new data, such as in the case of a dog image model, we download images from the internet. Before feeding the image to the model, we must preprocess the image by resizing it and adjusting the number of channels, and other image features to ensure compatibility with the features of the images used during initial training. This means that the image’s feature dimensions, such as<em> 224 x 224</em> and with three channels, should be normalized accordingly to have the same dimensions and features, allowing the model to respond correctly.</p><p>In general, the goal of using pre-trained models in fine-tuning is to enable the model to leverage the information and features learned from pre-training on a large dataset with high accuracy in the given task, resulting in better performance compared to training the model from scratch.</p><h3><strong>Conclusion</strong></h3><p>In Part 2, we extensively covered the most important pre-trained models in the field of image processing. We analyzed the architectures and features of each and highlighted the significant benefits of using pre-trained models. These benefits include speeding up training and facilitating the creation of new models for various tasks. At the outset of the article, we emphasized the critical importance of computer vision. It is not only widely applicable but also a vital pillar in the journey towards achieving Artificial General Intelligence (AGI). The rapid progress in this field has accelerated our movement towards AGI, a topic that was once speculative but is now being seriously considered. AGI, while potentially posing risks, also holds promise for significantly improving human life. It’s widely acknowledged that one of the key components of AGI is machine vision.</p><p>Furthermore, we discussed other applications such as security, facial recognition, and autonomous vehicles. All of these are advancing rapidly due to the continuous progress in AI. In Part 3, we will delve into significant models in the field of robotics. Robotics presents one of the most important and challenging areas in AI. It involves creating machines that can perform tasks akin to living organisms, considering both the physical intricacies and capabilities of living beings. However, concerns regarding the ethical implications and potential weaponization of robotics technology also persist.</p><p>Thank you for joining me in this part, and I look forward to sharing Part 3 with you soon. Your feedback and insights are always appreciated.</p><p>Thank you for accompanying me on this journey into the world of deep learning.</p><p>The link to the article in Persian is available on<a href="https://virgool.io/@m.javadnejadi/%D8%A7%D8%B1%D8%A8%D8%A7%D8%A8%D8%A7%D9%86-%D8%AD%D9%84%D9%82%D9%87-%D8%A7%D9%86%DA%AF%D8%B4%D8%AA%D8%B1%D9%87%D8%A7%DB%8C-%D9%82%D8%AF%D8%B1%D8%AA-%D9%87%D9%85%D8%A7%D9%86-pre-trained-model-%D9%87%D8%A7-%D8%AF%D8%B1-%D9%87%D9%88%D8%B4-%D9%85%D8%B5%D9%86%D9%88%D8%B9%DB%8C-%D9%87%D8%B3%D8%AA%D9%86%D8%AF-esgjhflwznrc"> virgool.io</a>.</p><p># <a href="https://medium.com/ai-advances/lord-of-the-rings-the-power-rings-are-the-pre-trained-models-a3de5b3a77e7">Part I: We will begin by examining and comparing the most important pre-trained models for text.</a></p><p># Part II: We will review and compare the most important pre-trained models (AlexNet, VGG, GoogLeNet, ResNet, MobileNet, and MobileNetV2) in the image field from the beginning until today.</p><p># Part III: We will start by examining and comparing the most important pre-trained models for Robotics.</p><p>If you’re interested, you can check out my other article, “<a href="https://ai.gopubby.com/digging-deeper-and-deeper-into-deep-learning-and-artificial-neural-networks-b41570db6259"><strong>Digging deeper and deeper into deep learning and artificial neural networks #Part III: Major architectures of deep neural networks (RNN / LSTM / CNN)</strong>.”</a> on Medium.</p><p><a href="https://medium.com/@reza.shokrzad/mastering-data-extraction-in-python-a-comprehensive-guide-to-leveraging-apis-8b952ab1ba6d"><strong>Mastering Data Extraction in Python: A Comprehensive Guide to Leveraging APIs</strong></a></p><p>I hope you’ve enjoyed the content.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=657926d52260" width="1" height="1" alt=""><hr><p><a href="https://aiadvances.org/lord-of-the-rings-the-power-rings-are-like-pre-trained-models-in-artificial-intelligence-657926d52260">Lord of the Rings! The power rings are like pre-trained models in artificial intelligence!</a> was originally published in <a href="https://aiadvances.org/">AI Advances</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lord of the Rings! The power rings are like pre-trained models in artificial intelligence!]]></title>
            <link>https://aiadvances.org/lord-of-the-rings-the-power-rings-are-the-pre-trained-models-a3de5b3a77e7?source=rss-707395aa8764------2</link>
            <guid isPermaLink="false">https://medium.com/p/a3de5b3a77e7</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[pretrained-language-model]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[pretrained-model]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[M Javadnejadi]]></dc:creator>
            <pubDate>Thu, 28 Mar 2024 23:22:42 GMT</pubDate>
            <atom:updated>2024-04-07T05:23:59.355Z</atom:updated>
            <content:encoded><![CDATA[<h4># Part I: We will start by examining and comparing the most important pre-trained models for text.</h4><blockquote>“One ring to rule them all, one ring to find them, one ring to bring them all, and in the darkness bind them.”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*zwvKLtGkJKq9SV91FiIjNg.jpeg" /><figcaption><a href="https://schrijvenonline.org/nieuws/wat-inspireerde-jrr-tolkien-voor-the-lord-of-the-rings">source</a></figcaption></figure><h3>The Lord of the Rings!</h3><p>In this trilogy, we are going to talk about pre-trained models that are akin to the memorable Rings of Power in the movie “The Lord of the Rings” Just as the movie was a trilogy, I’ve also prepared the article in three parts. As we recall from the film, the Rings of Power, the Ring of the Elves, and the Ring of the Dwarves existed. In this trilogy, I will discuss pre-trained models that are similar to the Rings of Power from the movie “The Lord of the Rings”. The article is divided into three parts, just like the movie. The Rings of Power, the Ring of the Elves, and the Ring of the Dwarves existed in the movie. Similarly, pre-trained models are like Rings of Power that can be used to create artificial intelligence models. By combining these models, we can create Multimodal Models that could lead to the development of AGI or even Superintelligence. However, just like in the movie, if these models fall into the wrong hands, they could pose serious threats. That’s why I’ve titled the article “Lords of the Rings”. Join me on this exciting journey.t, pre-trained models are like Rings of Power that can be used to construct artificial intelligence models. Their combination can lead to the creation of Multimodal Models that could culminate in AGI or even Superintelligence. Just as we saw in the film, if fallen into the wrong hands, like the One Ring of Power, they could pose dangers. That’s why I’ve titled the article “Lords of the Rings”. Join me on this marvelous and dreamlike journey.</p><p>This article will be divided into three parts, which are as follows:</p><p><strong>Part I: We will start by examining and comparing the most essential pre-trained models for text.</strong></p><p><a href="https://ai.gopubby.com/lord-of-the-rings-the-power-rings-are-like-pre-trained-models-in-artificial-intelligence-657926d52260"><strong># Part II: We will review and compare the most important pre-trained models (AlexNet, VGG, GoogLeNet, ResNet, MobileNet, and MobileNetV2) in the image field from the beginning until today.</strong></a></p><p><strong>Part III: We will examine and compare the most important pre-trained models for Robotics.</strong></p><p>In this trilogy, we aim to delve into pre-trained models in three parts: Text, Image, and Robotics. We aim to explore their concepts, emergence, and how these models work. We’ll also examine the different architectures and types of pre-trained models. We’ll explore which ones are the most powerful and whether pre-trained models and Transformers are the main strengths of LLMs. Additionally, we’ll discuss whether we would have powerful chatbots like ChatGPT today if pre-trained models and Transformers didn’t exist. Nowadays, chatbots are not just limited to the NLP field. For instance, GPT-4 is multi-faceted as it’s not just limited to text generation. We’ll also explore if they function similarly to RL. In the Robotics domain, we’ll explore what pre-trained models we have and which ones are better for Multimodal Models. We’ll also discuss if pre-trained models are only useful for NLP nowadays. In the Image domain, we’ll explore which models are the most powerful and how we can fine-tune or hyperparameter-tune each of these models for use. Join me in this trilogy as we explore and answer these questions together.</p><h3>Overview</h3><p>One of the most important benefits of pre-trained models is the ability to fine-tune and apply Transfer Learning to these models for the specific task at hand. Transfer Learning is a crucial aspect of Deep Learning and one of the foundational elements of its ongoing revolution. Transfer Learning is also a fundamental aspect of learning in humans or any living organism. As you’re reading this text, I’m transferring my knowledge about pre-trained models to you!</p><p>To better understand the subject, let’s consider an example. Imagine you want to build a large house. There are two ways to go about it:</p><p>The first way is to start from scratch and build the house step by step, from the foundation to the facade, and all the details. For this, you need materials and tools, and you also need to construct the house to be completely earthquake-resistant. This requires more complex engineering, which can lead to higher costs, and there’s a chance that the result may not be entirely satisfactory.</p><p>The second way is to leverage the experience and expertise of a company that has years of experience in home construction. The houses built by this company have pre-fabricated modular components. These puzzle-like pieces are customizable, meaning that the interior and exterior design of the building can be tailored to our liking. On the construction side, the engineering is done in a way that the building is completely earthquake-resistant! As a result, the costs and time for designing and executing the project are significantly reduced, and we have a fully earthquake-resistant home, the result of years of specialized experience!</p><p>Which method would you choose?</p><h3>The history of pre-trained models and how they emerged</h3><p>Pre-trained models have emerged due to significant challenges and concerns associated with training various artificial intelligence models, especially in deep learning, such as high costs and the difficulty of utilizing large-scale data and even collecting these data. Large datasets require powerful and expensive hardware. In the past, very large datasets were not readily available. Pre-trained models were first introduced in the early 2010s, initially for natural language processing (NLP), and they continue to play a significant role in the growth of large language models (LLMs).</p><p>One of the most important features of pre-trained models is that they come with a set of initial weights and biases, making it possible to fine-tune them effectively for a specific task. While no model can achieve 100% accuracy, pre-trained models are crafted by more expert individuals with more precise tools and stronger logistics, making them often more accurate and efficient than models built from scratch.</p><p>The most famous and widely used pre-trained models for various important tasks include:</p><p>- Image processing: VGG (2014) / ResNet (2015)<br>- Machine translation: Transformer (2017) / BERT (2018)<br>- Music generation: OpenAI’s MuseNet (2019) / Magenta’s Music Transformer (2018)<br>- Robotics: Dactyl (2018) / DeepLoco (2018)<br>- Sentiment analysis: BERT (2018) / RoBERTa (2019)<br>- Fake news detection: BERT (2018) / GPT-3 (2020)</p><h3>What exactly is the concept of a pre-trained model?</h3><p>The idea of pre-trained models was first introduced during the development of deep neural networks (DNNs), but it gained more attention with the development of algorithms like Word2Vec and GloVe. In this context, pre-trained models refer to the use of existing models as a starting point for training new models. In particular, pre-trained models for text can be especially useful. Let’s briefly explore Word2Vec and GloVe algorithms and see how they work. Let’s get started!</p><h3><strong>What is Word Embedding?</strong></h3><blockquote>My primary language is Persian! I still can’t directly understand a text in Chinese! So, I need to translate it to understand.</blockquote><p>Computers communicate in numbers, which is why we have to use numbers to communicate problems to them. To process textual data, we need to transform it into numbers using various techniques such as Word Embedding. Essentially, Word Embedding is a deep model or neural network that learns from the distribution of word features in a dataset.</p><p>The concept of Word Embedding didn&#39;t originate in a single article. It was a culmination of ideas proposed by several researchers over time. In the 1980s, Geoffrey Hinton introduced the concept of Word Embedding and &quot;Feature Representation,&quot; which involves converting words into dense vectors. In Word Embedding, we encode words in a sentence as vectors so that computers can process them.</p><p>Word Embedding leverages the meaning of words in a textual dataset to represent them in a dense space. This space expresses semantic relationships between words through dense distances, with similar or related words being close to each other. In the next section, we&#39;ll explore pre-trained models that use Word Embedding for text processing.</p><h3><strong>Word2Vec</strong></h3><p>The Google researchers including Tomas Mikolov, Kai Chen, Greg Corrado, and Jeffrey Dean published the Word2Vec model in a paper in 2013.</p><p><a href="https://arxiv.org/abs/1301.3781">Efficient Estimation of Word Representations in Vector Space</a></p><p>The Word2vec algorithm is a natural language processing (NLP) technique that generates vector representations of words. To instantiate the Word2Vec model using the `<em>gensim.models</em>` submodule of the <em>Gensim</em> library, you can follow the code snippet below. It also demonstrates how to generate vector representations of the words.</p><pre>from gensim.models import Word2Vec<br><br># Example data<br>sentences = [[&quot;this&quot;, &quot;is&quot;, &quot;a&quot;, &quot;sentence&quot;], [&quot;another&quot;, &quot;sentence&quot;]]<br><br># Create Word2Vec model<br>model = Word2Vec(sentences, vector_size=100, window=5, min_count=1, workers=4)<br><br># Display word vectors<br>word_vectors = model.wv<br>word_vectors_dict = {}<br>for word in word_vectors.key_to_index:<br>    word_vectors_dict[word] = word_vectors[word]<br><br>print(word_vectors_dict)</pre><p>The Word2Vec model uses Word Embedding to create vector representations of words. Each word is linked to a vector of real numbers, with specific dimensions obtained by training Word2Vec models with textual data. This mapping ensures that words with similar meanings are also close to each other in the vector space, preserving semantic relationships between them.</p><p>In a sentence, the individual components come together and convey meaning collectively. Even if certain words are not present individually, they can still convey meaning and context based on the relationship established within the sentence. Word Embedding aims to make this process easier for computers. For example, in the Word2Vec vector space, words with similar meanings like “bird” and “fly” are closer to each other. If the vectors of these two words are close to each other in the vector space, it means they have semantic relationships.</p><p>This capability allows knowledge of language to be transferred from one task to another. The learned vectors for a specific dataset can be applied to another dataset. For instance, vectors trained for machine translation can be useful for sentiment analysis as well, as similar meanings between words are preserved in these tasks. Therefore, the Word2Vec model was one of the first models to leverage this idea.</p><h3><strong>Word2Vec methodologies</strong></h3><p>Word2Vec methods typically rely on deep neural network (DNN) models such as skip-gram and Continuous Bag of Words (CBOW) models since the word order is not significant.</p><h4><strong>CBOW model</strong></h4><p>The <strong>CBOW (Continuous Bag-of-Words)</strong> model is a method used for natural language processing. It works by predicting a <strong>central or target word</strong> in a sentence. The target word is usually chosen randomly from the sentence. The model tries to predict it by analyzing the words that come before and after the target word. For instance, if the sentence is “<strong><em>Love, her rain-filled eyes towards the blue sky</em></strong>”, the objective is to predict the target word “Love” based on the surrounding words, such as “her rain-filled eyes towards the blue”. In other words, the algorithm uses the words around the target word to predict it. To predict the word “sky” in this sentence, the algorithm may take inputs such as “Love”, “her”, “rain-filled”, “eyes”, “towards”, “the”, and “blue”.</p><h4><strong>Skip-gram model</strong></h4><p>The <strong>Skip-gram model</strong> operates differently than CBOW, in that it predicts the words surrounding a given target word. For instance, if the target word is “sky” in a particular sentence, the model will attempt to predict words such as “love”, “eyes”, “rainy”, “he/she”, and other words that may appear before or after it. In essence, the model aims to generate vectors for each word that can accurately predict the words in its proximity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*qYhTcNhDyv0Lv2WIFDngwQ.png" /><figcaption><a href="https://arxiv.org/abs/1301.3781">Source</a>: This image effectively demonstrates the workings of both the Skip-gram and CBOW models, as shown in Mikolov’s 2013 paper.</figcaption></figure><h3><strong>CBOW Vs Skip-gram</strong></h3><p>The CBOW model works best when dealing with longer and more diverse texts. In contrast, the skip-gram model is more suitable for shorter texts where the goal is to identify patterns of semantic relationships between words. Generally, skip-gram is considered a stronger model than CBOW due to its higher accuracy in learning word vectors. Word2Vec is a foundational tool for many language models, including <strong>GPT-3 </strong>and <strong>BERT</strong>. However, modern language models now utilize advanced methods like Transformer to learn word vectors. Nevertheless, Word2Vec still holds its ground as a powerful tool for training LLMs.</p><h3><strong>GloVe model</strong></h3><p>The GloVe model, which stands for Global Vectors for Word Representation, is a method for distributed word representation developed based on the concept of global vectors. This approach is similar to another model called Word2Vec, but the way of computing these vectors is different between the two models. <strong>Stanford University</strong> introduced GloVe as an open-source project in 2014. It is an <strong>unsupervised learning</strong> algorithm utilized for deriving vector representations by leveraging statistical information relating to the distribution of words in texts. This information includes probabilities of word distributions in various texts, semantic relationships between words, and other features extracted from texts. All of this data is used to construct the word vectors.</p><p>In GloVe, relative probabilities of two words appearing together in texts are calculated using language statistics, such as the <strong>word-word co-occurrence matrix</strong>. Based on these probabilities, word vectors are updated while preserving semantic relationships between words.</p><h3><strong>Word2Vec Vs GloVe</strong></h3><p>Word2Vec and GloVe algorithms are commonly used to identify semantic similarities between words, such as synonyms or relationships like “company-product,” “zip code-city,” and so on. However, these algorithms may not be effective in identifying homographs (words with the same spelling but different meanings) because the statistical patterns of homographs are usually different. For instance, the word “bank” is typically linked to a place for storing money (financial institution), but it can also refer to a place for storing data (database). These two instances of “bank” are homographs, meaning they have the same spelling but different meanings.</p><p>However, Word2Vec models, being based on semantic relationships between words, may be more effective in identifying homographs. Nevertheless, there are hybrid approaches or more advanced models for detecting homographs that are capable of understanding the diverse meanings of words with the same spelling.</p><p>Another consideration is the case sensitivity of words, as both GloVe and Word2Vec models are sensitive to capitalization, treating words with different cases as different entities and creating different vectors for each case. Therefore, it is better to standardize the case of all words in the texts for proper utilization of these models. However, this standardization may lead to the loss of semantic information. For instance, “US” refers to the United States when capitalized, but it means “us” as a pronoun when written in lowercase.</p><h3><strong>Preprocessing techniques for text</strong></h3><p>Converting all words to a specific format can help models learn semantic patterns and perform correctly. However, case sensitivity can be an issue in models such as GloVe and Word2Vec. To address this issue, some text preprocessing methods are employed. One such method is <strong>stemming</strong>, which removes word prefixes and suffixes to reach the root of the word and standardize similar words. For instance, words like “running,” “runs,” “ran,” and “runner” are all derived from the root or base form “run.” The Porter algorithm is a well-known stemming technique that utilizes a set of rules based on patterns to remove various suffixes and transform words into meaningful roots. For example, “cats” becomes “cat,” and “running” becomes “run.”</p><p>To apply the stemming technique, we need to install <strong><em>NLTK</em></strong> and download the required data. Then, we can use the following Python code:</p><pre>import nltk<br>from nltk.stem import PorterStemmer<br><br># Download necessary data for stemming<br>nltk.download(&#39;punkt&#39;)<br><br># Create an instance of PorterStemmer class<br>stemmer = PorterStemmer()<br><br># Words to be stemmed<br>words = [&quot;running&quot;, &quot;runs&quot;, &quot;ran&quot;, &quot;runner&quot;, &quot;cats&quot;, &quot;cat&quot;]<br><br># Stemming words and printing results<br>for word in words:<br>    stemmed_word = stemmer.stem(word)<br>    print(f&quot;{word} -&gt; {stemmed_word}&quot;)</pre><p>This code converts “running”, “runs”, “ran”, “runner”, “cats”, and “cat” into their respective roots and outputs the results.</p><pre>running -&gt; run<br>runs -&gt; run<br>ran -&gt; ran<br>runner -&gt; runner<br>cats -&gt; cat<br>cat -&gt; cat<br>[nltk_data] Downloading package punkt to /root/nltk_data...<br>[nltk_data]   Package punkt is already up-to-date!</pre><p>The second technique used in natural language processing is called <strong>lemmatization</strong>. In this method, words are transformed into their base or root forms. To perform lemmatization, we use the <em>NLTK</em> library similar to the stemming method. First, we need to download the required data using the `<em>nltk.download(‘wordnet’)</em>` command. Then, we create an instance of the `<em>WordNetLemmatizer</em>` class, which is used to perform lemmatization operations. To lemmatize words, we place them in a list called `<em>words</em>`. Using a `<em>for</em>` loop, each word from the `<em>words</em>` list is taken, and the `<em>lemmatize</em>` method of the `<em>WordNetLemmatizer</em>` class is used to lemmatize it.</p><pre>import nltk<br>from nltk.stem import WordNetLemmatizer<br><br># Download necessary data for lemmatization<br>nltk.download(&#39;wordnet&#39;)<br><br># Create an instance of WordNetLemmatizer class<br>lemmatizer = WordNetLemmatizer()<br><br># Words to be lemmatized<br>words = [&quot;running&quot;, &quot;cats&quot;, &quot;ate&quot;, &quot;flying&quot;, &quot;better&quot;]<br><br># Lemmatizing words and printing results<br>for word in words:<br>    lemmatized_word = lemmatizer.lemmatize(word)<br>    print(f&quot;{word} -&gt; {lemmatized_word}&quot;)</pre><p>After executing the above code, the result of lemmatization for each word, along with the original word, is printed as a sentence. For example, if the word “running” is given as input, the output of this operation will be “running”, because the word “running” is considered as a verb derived from the root “run”.</p><pre>[nltk_data] Downloading package wordnet to /root/nltk_data...<br>running -&gt; running<br>cats -&gt; cat<br>ate -&gt; ate<br>flying -&gt; flying<br>better -&gt; better</pre><p>The following methods ensure that all variations of a word are standardized, reducing sensitivity to capitalization. By utilizing these techniques, all words are transformed into a standard format, and capitalization no longer affects the outcome of text analysis. It’s worth noting that these two methods take different approaches to standardizing words, and depending on the problem’s nature and goals, both stemming and lemmatization techniques could be used simultaneously. However, this might lead to increased complexity and decreased efficiency in text processing.</p><p>Algorithms like GloVe and Word2Vec are Word Embedding models based on text and are used as one of the preprocessing stages to represent words in models like <em>BERT </em>and <em>GPT</em> as inputs, but not as the primary part of these models. For models like <em>BERT</em> and <em>GPT</em>, also known as Pre-trained Language Models, they exhibit good performance in tasks such as machine translation, text generation, question answering, and natural language processing tasks using Transformer networks, pre-trained and fine-tuned. In the next section, we’ll delve into examining them. Stay tuned.</p><h3><strong>The power of LLMs comes from where!</strong></h3><p>GloVe and Word2Vec were the first models for NLP. Later, pre-trained models like <em>BERT, GPT-3, and RoBERTa</em> were introduced, which are based on transformer-based text transformation with attention. These models are more efficient and popular today. In 2017, a paper was published that revolutionized NLP. The authors may not have realized that their paper, “Attention is All You Need,” would have such an impact on NLP.</p><p><a href="https://arxiv.org/abs/1706.03762">Attention Is All You Need</a></p><p>The mechanism of Attention is considered a crucial component of powerful Language Model Machines (LLMs). Specifically, in deep learning and Natural Language Processing (NLP), the concept of Attention is used to enhance Recurrent Neural Networks (RNNs) and facilitate better management of longer sequences or sentences. Pre-trained models such as <em>BERT </em>and <em>GPT-3</em> are built on these foundational concepts and have undergone significant evolution. <em>BERT</em> utilizes the idea of <strong>Attention</strong>, while <em>GPT-3</em> uses <strong>Self-Attention Models</strong>. Additionally, the <em>GPT-3</em> model makes use of the Transformer architecture, which was originally intended for Self-Attention Models.</p><h3><strong>Self-Attention Mechanism</strong></h3><p>The Self-Attention mechanism, unlike <em>RNNs</em> which process input data sequentially (i.e., each input, such as a word in a sentence, is sequentially transferred to network nodes with specific weights at a certain time), considers the relationship between words temporally (or sequentially) and dependencies over time are examined consecutively. In <em>CNNs</em>, different features of input data are extracted using convolutional filters, independently and without considering temporal dependencies, processing various parts of input data, and taking spatial information (information related to the position in the data) into account.</p><p>The Self-Attention mechanism can effectively capture long-term dependencies and relationships between words in a sentence. The key aspect of Self-Attention Models is the self-attention mechanism, which allows each word in a sequence to simultaneously attend to all other words and create weighted representations based on their importance for a specific task. In other words, each word in the sentence determines its role and importance considering all other words. This approach enables the model to consider relationships between words in the long term and throughout the entire length of the sentence without relying on a specific word order. In summary, Self-Attention Models have significantly changed NLP by providing powerful tools for capturing complex patterns in textual data.</p><h3><strong>Transformer Mechanism</strong></h3><p>Transformer models use an attention mechanism to understand the structure of text and make accurate predictions. In the past, translating a sentence from one language to another using a word-by-word translation method was <strong>not very effective</strong>. Attention mechanisms were introduced to gather important information from all elements of the sequence at each time step and recognize relationships between them. However, this doesn’t mean that the model reads all sentences at once.</p><p>In the Transformer architecture, the model can attend to all other words in the sentence for each word, gathering information and making different predictions based on it. <em>GPT-3</em> uses the Transformer architecture at a large scale, with over 175 billion parameters. This large number of parameters allows the model to self-train and learn from vast amounts of data, recognizing more complex patterns without the need for human supervision. Thus, <em>GPT-3</em> automatically utilizes attention to different elements of the sentence to generate complex texts and perform semantic analysis.</p><p>All these models utilize Spatial Attention and <strong>Hierarchical Attention</strong>. In <strong>Spatial Attention</strong>, the model focuses only on specific parts of the input or output to generate the output. In Hierarchical Attention, the model adjusts its attention at different levels of the input or output, assigning different chances and importance to various components of the text, such as words or sentences. By using these two types of Attention, the model can identify important information in the text and generate the best and most comprehensive output.</p><h3><strong>Building LLMs with pre-trained models</strong></h3><p><em>BERT and GPT</em> are two highly successful pre-trained models for natural language processing. They can be used for various tasks, including building LLMs. These models can be trained on large text data to create a custom LLM with specific capabilities for natural language processing tasks.</p><p>Although we typically have access to the raw model, including its architecture and corresponding weights, to use them effectively for specific tasks, we can fine-tune them with our own data. This process improves the model’s performance for specific tasks and is a cost-effective way of building an LLM.</p><p>For instance, if we want to use the<em> GPT</em> model as a pre-trained model for natural language processing, we can obtain it by running the following code. The <strong>Hugging Face transformers</strong> library enables us to use most pre-trained models for NLP tasks, such as <em>DistilGPT-2, BERT, RoBERTa</em>, <em>DistilBERT</em>, and <em>XLNet </em>using the same code.</p><p>Below are two code snippets taken from the Hugging Face website that show how the <em>DistilGPT-2</em> model can be used for text generation in different ways.</p><pre># With pipeline, just specify the task and the model id from the Hub.<br>from transformers import pipeline<br>pipe = pipeline(&quot;text-generation&quot;, model=&quot;distilgpt2&quot;)</pre><p>The first method involves using the `<em>pipeline</em>` class from the transformers library. This class makes it easy to use pre-trained models without having to define or structure them for various tasks such as text classification, text translation, text generation, etc. To use this method, you only need to specify the task type as “text-generation” and the model to be used as “<em>distilgpt2</em>”. On the other hand, the second approach is described in the following code.</p><pre># If you want more control, you will need to define the tokenizer and model.<br>from transformers import AutoTokenizer, AutoModelForCausalLM<br>tokenizer = AutoTokenizer.from_pretrained(&quot;distilgpt2&quot;)<br>model = AutoModelForCausalLM.from_pretrained(&quot;distilgpt2&quot;)</pre><p>The second approach involves loading the <strong>tokenizer</strong> using the `<em>AutoTokenizer`</em> class, followed by loading the tokenizer associated with the <em>DistilGPT-2</em> model through the `<em>from_pretrained`</em> method. To load the model, we use the `<em>AutoModelForCausalLM`</em> class. This approach is recommended for users who need more control over the model and tokenizer.</p><p>Once we run these codes, the pre-trained model becomes available. We can then input text into the model and analyze its representation of text features using the following code.</p><pre>import torch<br># Define your input text<br>input_text = &quot;Love, her rain-filled eyes towards the blue sky.&quot;<br><br># Tokenize the input text<br>input_ids = tokenizer.encode(input_text, return_tensors=&quot;pt&quot;)<br><br># Get the model&#39;s output logits<br>with torch.no_grad():<br>    outputs = model(input_ids)<br>    logits = outputs.logits<br><br># Print the shape of the output logits<br>print(&quot;Output logits shape:&quot;, logits.shape)</pre><p>After executing the code snippets mentioned above, the resulting output is as follows:</p><pre>Output logits shape: torch.Size([1, 12, 50257])</pre><p>The <em>DistilGPT-2</em> model generates output logits in the shape of `<em>(batch_size, sequence_length, vocab_size)</em>`. For instance, <em>[1, 12, 50257]</em> indicates that the generated output has a sequence length of 12 and a vocabulary size of 50257.</p><p><em>PyTorch </em>and<em> TensorFlow</em> are two popular libraries for building pre-trained models. Although both libraries have the same architecture, they differ in how models are defined and utilized. <em>TensorFlow</em> models are defined as computational graphs, with specific functions for training and using models. Typically, <strong>high-level APIs</strong> like `<em>Keras` or `tf.keras</em>` are used for building and training models. On the other hand, <em>PyTorch</em> models are defined as modules, and you can manage them directly using Python functions. Moreover, <em>PyTorch</em> is the <strong>primary API</strong> for building and training models.</p><h3><strong>Fine-tuned</strong></h3><p>Throughout this article, we have explored different types of pre-trained models in relation to text, and have examined their architectures. To use these models on our own dataset and for the specific task we want to perform, we need to fine-tune them. Fine-tuning is an essential concept in training deep models, especially those using transfer learning.</p><p>Fine-tuning involves adjusting a pre-trained model, which has been trained on a large dataset, to work with the dataset we have for our task. Typically, we freeze the top layers of the model and only the weights of the lower layers are optimizable. This process allows the model to learn specific patterns from the smaller dataset while benefiting from the general patterns learned in the larger pre-training dataset.</p><p>There are various architectures and configurations for pre-trained models. First, we must select a suitable pre-trained model and perform all the steps mentioned above, including adapting its parameters to the new data while preserving the learned knowledge during training. This involves selecting an appropriate architecture, defining a task-specific objective function, preparing the dataset, initializing the model with pre-trained weights, and fine-tuning the parameters through iterative optimization. Techniques such as transfer learning, hyperparameter tuning, and PEFT (Precision Efficient Fine-Tuning) are central to this process. Regularization methods and hyperparameter tuning optimize performance.</p><p>After completing the above steps, we choose a performance metric to evaluate the fine-tuned model, such as accuracy, recall, or any other suitable metric for the problem at hand. We then fine-tune the model on our prepared dataset, typically using an epoch-by-epoch or batch-by-batch approach, computing the values of objective functions (such as loss function) and updating the model parameters accordingly. Subsequently, we evaluate the fine-tuned model on evaluation data and compute evaluation metrics to assess the final model performance.</p><blockquote>Due to the length constraints of this article, I did not include code to explain fine-tuning. However, soon, I will select a pre-trained model for a text dataset in another article and guide you step by step through the fine-tuning process using code.</blockquote><h3><strong>Conclusion</strong></h3><p>In the first part of the article, we discussed the primary pre-trained text models, their introduction and how useful they can be. We also saw that Large Language Models (LLMs) are now an integral part of our daily lives and are continually improving. In the near future, these models will become our personal assistants, and the significance of search engines will gradually diminish. Additionally, we learned that fine-tuning these models is crucial to optimize their performance.</p><p>In Part 2, we will explore the essential pre-trained models for images and compare them from their inception to the present day. This analysis aims to highlight the significance of these models for us. Part 2 will be published soon, and I would appreciate it if you could read it and share your feedback.</p><p>Thank you for joining me on this journey.</p><p>Thank you for accompanying me on this journey into the world of deep learning.</p><p>The link to the article in Persian is available on <a href="https://vrgl.ir/a1P9Q">virgool.io</a>.</p><p><strong># Part I: We will begin by examining and comparing the most important pre-trained models for text.</strong></p><p><a href="https://ai.gopubby.com/lord-of-the-rings-the-power-rings-are-like-pre-trained-models-in-artificial-intelligence-657926d52260"><strong># Part II: We will review and compare the most important pre-trained models (AlexNet, VGG, GoogLeNet, ResNet, MobileNet, and MobileNetV2) in the image field from the beginning until today.</strong></a></p><p><strong># Part III: We will start by examining and comparing the most important pre-trained models for Robotics.</strong></p><p>If you’re interested, you can check out my other article, “<a href="https://medium.com/ai-advances/step-by-step-guide-to-building-an-artificial-neural-network-and-observing-how-overfitting-occurs-84961f96c7e8">Step-by-step guide to building an artificial neural network and observing how overfitting occurs with MNIST and CNN architecture</a>.” on Medium.</p><p><a href="https://medium.com/@reza.shokrzad/the-future-of-ai-in-iran-an-in-depth-review-1b8a2920183">The Future of AI in Iran: An In-depth Review</a></p><p>I hope you’ve enjoyed the content.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3de5b3a77e7" width="1" height="1" alt=""><hr><p><a href="https://aiadvances.org/lord-of-the-rings-the-power-rings-are-the-pre-trained-models-a3de5b3a77e7">Lord of the Rings! The power rings are like pre-trained models in artificial intelligence!</a> was originally published in <a href="https://aiadvances.org/">AI Advances</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Step-by-step guide to building an artificial neural network and observing how overfitting occurs…]]></title>
            <link>https://aiadvances.org/step-by-step-guide-to-building-an-artificial-neural-network-and-observing-how-overfitting-occurs-84961f96c7e8?source=rss-707395aa8764------2</link>
            <guid isPermaLink="false">https://medium.com/p/84961f96c7e8</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[overfitting]]></category>
            <dc:creator><![CDATA[M Javadnejadi]]></dc:creator>
            <pubDate>Sat, 16 Mar 2024 13:15:40 GMT</pubDate>
            <atom:updated>2024-03-16T13:15:40.220Z</atom:updated>
            <content:encoded><![CDATA[<h3>Step-by-step guide to building an artificial neural network and observing how overfitting occurs with MNIST and CNN architecture</h3><h4><strong>Seeing and experiencing all the steps and issues with tested code and learning curves</strong></h4><p><strong>building and building and building…</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tMjK4rYIpQuJXqrANpIZ8A.png" /><figcaption>Generated on <a href="https://ideogram.ai/t/top/1">Ideogram</a>, as prompted by author</figcaption></figure><h3>Overview</h3><p>The first step in building an artificial neural network is accessing the data. Typically, real-world data is not normalized and may contain outliers or null values. Therefore, besides needing the data, we must preprocess it so that the model can effectively perceive and process it. After these steps, we can utilize the vast array of efficient libraries available to build our model.</p><p>In this article, we aim to learn the step-by-step process of building a model. From data loading or downloading to normalization and selecting an appropriate architecture for model construction. Additionally, we’ll gain a comprehensive understanding of how overfitting occurs and how to detect it. We’ll explore practical solutions, not just through theory, but with codes and learning curve diagrams. A comparative approach of different learning curves obtained with various hyperparameter tunings will lead to a better understanding of the problem. Join me in this exciting exploration journey.</p><blockquote>All the code used in this article, as well as the plots you will see, have been tested on colab.research.google.com, and their outputs have been obtained from there.</blockquote><h4><a href="https://en.wikipedia.org/wiki/MNIST_database#cite_note-Gradient-10"><strong>A brief overview of MNIST</strong></a></h4><p>It can be confidently stated that no one can begin learning machine learning without encountering the MNIST dataset. It’s akin to “<em>print(“Hello world”)</em>” in programming for starting learning. MNIST is one of the benchmark datasets in machine learning and computer vision, comprising images of handwritten digits from <em>0 to 9</em>. But where does MNIST come from?</p><p>In fact, MNIST originates from <strong>the NIST dataset</strong>. The training set of NIST dataset was collected from employees of the United States Census Bureau, while the test set was gathered from American high school students. MNIST was created in the early 1980s by <em>Yann LeCun</em>, <em>Corinna Cortes</em>, and <em>Christopher J.C. Burges</em>. MNIST consists of <em>60,000 training</em> images and <em>10,000</em> test images. The images are stored in grayscale and single-channel format with dimensions of <em>28 x 28 pixels</em>.</p><p>Extended MNIST (EMNIST) is a newer dataset developed and released by NIST as a successor to MNIST. While MNIST only included handwritten digit images, EMNIST encompasses all images from the NIST Special Database 19, which includes a large database of handwritten uppercase and lowercase letters as well as numbers. The images in EMNIST are converted to the same <em>28 x 28 pixel</em> format as MNIST images. Therefore, tools that work with older and smaller MNIST datasets likely work with EMNIST without modification.</p><p>In recent years, new and larger datasets such as <strong><em>CIFAR-10</em></strong>, <strong><em>CIFAR-100</em></strong>, and <strong><em>ImageNet</em></strong> have been introduced as datasets with greater data diversity and complexity, making them more suitable for complex problems and current tasks. However, MNIST continues to be used as one of the primary and essential datasets for machine learning and computer vision. In this article, we aim to explore MNIST and proceed step by step to train a neural network model with it, while also examining the challenges and issues it presents.</p><h3><strong>Importing the most important libraries</strong></h3><p>The first step to start is to import essential libraries, regardless of the architecture or method we use to build our model or even the dataset we use. These libraries are essential for the model. For example, we know that for plotting graphs, we need ‘<em>matplotlib’</em>, and since we deal with matrices and arrays, we need <em>Numpy</em>. For this dataset, I want to use <em>keras</em> and <em>Tensorflow</em>. So, let’s do it:</p><pre># calling important Library<br>import tensorflow as tf<br>import matplotlib.pyplot as plt<br>import numpy as np</pre><h3><strong>Calling the dataset</strong></h3><p>To use the MNIST dataset, we first need to be able to load or download it. MNIST is available in the <em>Keras</em> repository, and it’s simply a matter of calling its <em>load_data()</em> method to load it. Then, we specify the training and testing data, as well as their shapes.</p><pre># calling the dataset<br>from tensorflow.keras.datasets import mnist<br><br># Access the training and testing data<br>(X_train, y_train) , (X_test, y_test) = mnist.load_data()<br><br>(X_train.shape, y_train.shape) , (X_test.shape, y_test.shape)</pre><h3><strong>Data processing</strong></h3><p>The important step before training a model is data processing. The number and specific steps involved depend on the type of dataset. Some datasets, like MNIST, require minimal processing, but real-world data is not always so straightforward. We will explore various methods of data processing together.</p><h3><strong>Normalization</strong></h3><p>In deep networks, reaching a stable state where the model can learn data patterns and provide accurate predictions is crucial. This state of stability is referred to as <strong>convergence</strong>. Essentially, convergence means adjusting the weights and parameters of the network in a way that minimizes the loss function. Two main problems in achieving convergence in deep models are <strong>gradient explosion and vanishing gradients</strong>, which occur when gradients become very large or very small, respectively.</p><blockquote>Note: If normalization is not performed, one of the issues that arises is convergence problems, which may result in the model converging slowly or not converging at all.</blockquote><p>There are various methods of normalization. These include Pixel-wise normalization (<em>where each pixel of the image is normalized based on the mean and variance of similar pixels in the dataset</em>), Local Contrast normalization (<em>useful for images with local brightness variations, where each region of the image is normalized relative to similar regions in all data</em>), Robust Scaling (<em>which uses the median and interquartile range of the data for scaling, making it robust against outliers</em>), and Unit Vector Scaling (<em>where each row of the data is normalized in such a way that the sum of squares of its values equals one</em>).</p><p>The following code is for data processing and is usually performed before the normalization step. The <em>reshape</em> function changes the dimensions of the data to prepare it for input into the neural network. It reshapes the images into 4D dimensions with the size of (<em>number of samples, image height, image width, number of channels</em>). In MNIST, the dimensions of the images are (<em>60000, 28, 28</em>), which are reshaped to (<em>60000, 28, 28, 1</em>). This is necessary to match the input size of the neural network layers. The pixel values of the images, ranging from <em>0 to 255</em>, are normalized to decimal values between <em>0 and 1</em> by dividing by <em>255</em>. Normalization helps the model mitigate issues related to irregular training (<em>such as increasing the jitter in weight distribution</em>).</p><pre># Preprocess the data<br>X_train = X_train.reshape((60000, 28, 28, 1))<br>X_test = X_test.reshape((10000, 28, 28, 1))</pre><p>For the MNIST dataset, normalization may be useful but often not necessary. However, if we aim to improve the performance of our model, we can normalize the data. For normalizing image data, apart from the methods mentioned above, two other important methods exist. One of them is Standardization using the <em>Z-score</em>, where the mean and variance of the data are normalized such that the mean is zero and the variance is 1. In the code below, we first convert the data to <em>float32</em>. However, we could have converted it to <em>float8/16/64</em> as well. <em>float</em> is a data type that specifies the precision. Then, we normalize it using the <em>Z-score</em> method and calculate the mean and variance:</p><pre># Convert data to float32<br>X_train = X_train.astype(np.float32)<br>X_test = X_test.astype(np.float32)<br><br># Calculate mean and standard deviation of the training data<br>mean = np.mean(X_train) # Mean<br>std = np.std(X_train) # Variance<br><br># Apply Z-score normalization to the training data<br>X_train_normalized = (X_train - mean) / std<br><br># Apply Z-score normalization to the test data using the mean and standard deviation of the training data<br>X_test_normalized = (X_test - mean) / std<br><br># Display the dimensions of the standardized data<br>print(&quot;Dimensions of X_train: &quot;, X_train_normalized.shape)<br>print(&quot;Dimensions of X_test: &quot;, X_test_normalized.shape)</pre><p>Another method is <em>Min-Max Scaling</em>, where the data are transformed to a specific range, usually [<em>0, 1</em>]. The <em>Min-Max Scaling</em> method is more suitable for data with a normal distribution or similar. When the data have a non-normal distribution, such as MNIST, the<em> Z-score </em>method is usually more useful because it normalizes the data based on the mean and variance. Therefore, the <em>Min-Max Scaling </em>method may produce inappropriate results for MNIST.</p><blockquote>Important note: Be mindful<strong> </strong>that we should <strong>use only one</strong> normalization method in our model. If we use both, it will only add complexity to the model, which may lead to overfitting.</blockquote><h3><strong>Visualizing the data</strong></h3><p>In this section, we want to visualize a sample of the data. For this purpose, we can use common libraries such as matplotlib or <em>OpenCV</em>. Below is the code using the <em>matplotlib</em> library:</p><pre>import matplotlib.pyplot as plt<br><br># Display an image from the data along with its label<br>index = 0 # Index of the image to display<br>plt.imshow(X_train_normalized[index], cmap=&#39;gray&#39;)  # Display the image<br>plt.colorbar()  # Display the color bar<br>plt.title(f&#39;Label: {y_train[index]}&#39;)  # Title with the label<br>plt.show()  # Show the image</pre><p>As we know, Python is zero-indexed. In this code, using the `<em>imshow()`</em> function, we can visualize the first image of the training data along with its label. By changing the index, we can display any of the available images. For example, <em>index = 19</em> shows the twentieth MNIST digit. Additionally, the shape of the image, which is <em>28 x 28 pixels</em>, and the grayscale color map are selected. The result is the image below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*QGAzkRVSIXdbrBFNCWMxuA.png" /><figcaption>This image is a sample from the MNIST dataset processed by my code, representing one of the numbers in this dataset. The model trained using this data has the ability to recognize numbers.</figcaption></figure><h3><strong>Decision Making</strong></h3><p>After completing the preprocessing steps, we need to choose the model design approach. This can be either the Sequential approach, the Functional API, or even a hybrid approach. The choice between these two approaches depends on the type of problem, the dataset, and also the architectural requirements. Because the architecture type can be determinant of the final outcome in our problem. In your opinion, which approach and architecture would be better for MNIST?</p><p>In the normalization step, since MNIST has a non-normal distribution, <em>Z-score scaling</em> can perform better than <em>Min-Max scaling</em>. For the current problem of handwritten digit recognition, we use a <em>CNN </em>architecture because it is highly suitable for image processing tasks. Although MNIST images are simple and the dataset is not complex, using <em>CNNs</em> can still be appropriate.</p><p>We choose the Sequential approach, where models are built layer by layer in a linear manner without explicitly defining connections between layers. If we need to make the model more complex, transitioning from the Sequential model to the Functional API model is possible.</p><p>In the next section, we will focus on building the model using the Sequential<em> </em>approach. Stay tuned.</p><h3><strong>Step 1: Architecture Design (Model Building)</strong></h3><p>After normalization and selecting the architecture type, we need to start building the model. Depending on the chosen architecture, we import the necessary libraries. `<em>tensorflow.keras.layers</em>` is used for adding different layers in <em>CNN</em>, so we can add network layers using the `<em>model.add()</em>` method. The other one is `<em>tensorflow.keras.models</em>`, which allows us to build a Sequential model.</p><pre><br># calling important Library<br>from tensorflow.keras.models import Sequential<br>from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout0</pre><p>We use these libraries to add layers to the model. We use `<em>Conv2D</em>` to add convolutional layers and `<em>MaxPooling2D</em>` for pooling operations.</p><p>The <em>Flatten</em> layer is typically used after convolutional or dropout layers. Since the output of these layers is multidimensional, Dense layers, which are fully connected, require one-dimensional data as input. The Flatten layer is used to convert the input data into a one-dimensional vector.</p><p>The <em>Dropout</em> layer is a method introduced by <strong><em>Geoffrey Hinton</em></strong> and others in the paper:</p><p><a href="https://www.semanticscholar.org/paper/Dropout%3A-a-simple-way-to-prevent-neural-networks-Srivastava-Hinton/34f25a8704614163c4095b3ee2fc969b60de4698">[PDF] Dropout: a simple way to prevent neural networks from overfitting | Semantic Scholar</a></p><p>It randomly drops some features during the model training phase to prevent <em>overfitting</em> in deep neural networks. This layer is usually placed immediately after convolutional or pooling layers. (We will discuss it in detail later in the article and you will see it intuitively)</p><p>Each neuron in <em>Dense </em>layers is connected to all neurons in the previous and subsequent layers and has a weight (W) and a bias, representing the relationship between the input to this layer and the output of the previous layer. Dense layers are commonly used in the final layers of a neural network, which may consist of multiple layers (possibly a multi-layer network).</p><p>The last layer, or the output layer, typically uses the Softmax activation function. In the code, we will see that the output layer has 10 neurons because our problem has <em>10 classes</em>. The numbers <em>0–9 </em>represent the classes, so the output of each image we ultimately want to classify should indicate a number between<em> 0 and 9</em>.</p><p>After importing the necessary libraries and understanding how each layer works, we proceed to build the model, as seen in the code below:</p><pre># Create the model<br>model = Sequential()<br><br>model.add(Conv2D(32, (3, 3), activation=&#39;relu&#39;, input_shape=(28, 28, 1)))<br>model.add(MaxPooling2D((2, 2)))<br>model.add(Conv2D(64, (3, 3), activation=&#39;relu&#39;))<br>model.add(MaxPooling2D((2, 2)))<br>model.add(Conv2D(64, (3, 3), activation=&#39;relu&#39;))<br>model.add(Flatten())<br>model.add(Dense(64, activation=&#39;relu&#39;))<br>model.add(Dropout(0.25))<br>model.add(Dense(10, activation=&#39;softmax&#39;))<br><br># Display model summary<br>model.summary()</pre><p>As you can see, we first choose the model with `<em>model = Sequential()</em>`. Then, we start adding different layers. The first layer `<em>(28, 28, 1)</em>` with `<em>input_shape</em>` indicates the shape of the data <em>28x28 pixels</em> and <em>1</em> indicates that the data is single-channel (<em>grayscale</em>).</p><p>The (<em>32</em>) in the `<em>Conv2D`</em> layer represents the number of filters used in this convolutional layer, indicating the number of channels in the output feature maps. The (<em>3x3</em>) represents the dimensions of the kernel or filter, which collects information from the images. Since our images are <em>grayscale</em> and quite small, and their edges have zero values, we don’t need much padding.</p><p>Therefore, we use` <em>MaxPooling2D`</em>, which performs pooling operations on the images. This is especially useful for datasets like MNIST where the most important values range from <em>0 to 255</em>. Since higher values contribute to better recognition in digit recognition tasks, as grayscale images, pixels representing handwritten digits tend towards white (i.e., a value of 255), while values towards 0 represent black areas such as edges or backgrounds, which are less significant.</p><p>We’ve used different <a href="https://medium.com/@m.javadnejadi/digging-deeper-and-deeper-into-deep-learning-and-artificial-neural-networks-e1db9097f744">activation functions</a> in various layers, each serving different purposes. We have two fully connected (FC) or Dense layers. In the first one, we’ve used the <em>ReLU</em> activation function, while in the second layer, which represents the model’s output, we’ve used the <em>softmax</em> activation function, typically applied in the final output layer.</p><p>We’ve also incorporated dropout with a <em>dropout</em> rate of 0.25, meaning 25% of input features to the layer are randomly dropped during training. Each layer has parameters, and upon completion, we can see the total number of parameters in the network using `<em>model.summary()`</em>. In the next part, we’ll proceed to compile the model.</p><h3><strong>compile.model</strong></h3><p>After constructing the model and its layers with the <em>CNN</em> architecture, the next step is to compile the model using the compile function to set the loss function, optimizer, and select evaluation metrics. In machine learning, the <strong><em>loss function</em></strong> represents the difference between the model’s output and the actual values. In all tasks, whether in the real world or for solving deep learning problems, one of the most important tasks is to minimize the error.</p><p>The optimizer is responsible for optimizing and updating the model’s weights (W), adjusting them in a way that minimizes the loss function. Optimizers come in various types such as <strong><em>Adam</em></strong>,<strong> <em>SGD</em></strong>, and <strong><em>RMSprop</em></strong>, and selecting the right one for your specific task can help improve the model’s performance. As you’ll see, we use Adam in the code below.</p><p>Then, by selecting appropriate evaluation metrics, namely Metrics, we can evaluate the model’s performance during both training and evaluation stages.</p><pre># Importing necessary libraries for compiling the model<br>from tensorflow.keras.optimizers import Adam<br>from tensorflow.keras.losses import SparseCategoricalCrossentropy<br><br># Compiling the model with SparseCategoricalCrossentropy loss function and Adam optimizer<br>model.compile(loss=SparseCategoricalCrossentropy(),<br>              optimizer=Adam(learning_rate=0.001), metrics=[&#39;accuracy&#39;])</pre><p>Loss function calculation is done solely by calling the ‘<em>SparseCategoricalCrossentropy()’</em> function. In the Adam optimizer, we have used a learning rate. The learning rate determines how small the training steps should be to reach the optimal point. It’s actually considered a hyperparameter (parameters outside the model that need to be tuned). Selecting an appropriate learning rate is crucial in training a model. Choosing the right learning rate value can prevent <strong>overshooting</strong>, a phenomenon in the optimization process where parameter values fluctuate severely, potentially slowing down the optimization process. The accuracy metric is also used to <strong><em>evaluate</em></strong> the model’s performance during training.</p><p>If the model is not compiled, it cannot optimize and evaluate its performance. In the next step, we’ll move on to the fitting stage of the model. Stay tuned with me.</p><h3><strong>Training Phase</strong></h3><p>In this stage, we train the model on the training data to facilitate learning and determine the model’s accuracy. Typically, when fitting the model, the first thing we do is specify the number of epochs. In each epoch, the model sees the entire training dataset once to learn complex patterns in the data. Naturally, the higher the number of epochs, the better the model learns because it can see more data, but if it’s too high, it may lead to overfitting. In other words, because the model overly converges to the training data, it fails to generalize to new data. In other words, the model simply memorizes the data.</p><h3><strong>fit Phase (model.fit)</strong></h3><p>For training the model, we use ‘model.fit()’, which contains the methods for model learning. Additionally, we can mention the<strong> Validation split</strong> method. The optimal value for validation split ranges between <em>0.1 to 0.3.</em> Utilizing validation data allows us to directly evaluate the model’s performance during training on data it has previously seen. Essentially, it divides the training data into two parts. For example, a validation split of <em>0.2 </em>means that <em>80%</em> of the training data is used for training, and <em>20%</em> is used for testing. This practice was also employed in older machine learning models. If the model’s performance does not improve on this separate set of data, training is halted. This method helps prevent excessive increase in the number of epochs and the occurrence of overfitting.</p><p>Determining the batch size specifies how many data samples are shown to the model in each epoch. Finding the optimal batch size has a significant impact on the speed and quality of model training. Naturally, a larger batch size is preferable for better performance. However, due to memory constraints, especially in large-scale projects, this may not always be feasible. In diverse datasets, a larger batch size may lead to a loss of model adaptation to the data, resulting in overfitting or underfitting. To prevent this, we can find the best batch size through trial and error or by employing systematic and principled methods such as Grid Search or Validation Data-based approaches.</p><p>In 2018, <em>Yann LeCun</em> wrote in a famous tweet:</p><h3>Yann LeCun on Twitter: &quot;Training with large minibatches is bad for your health.More importantly, it&#39;s bad for your test error.Friends dont let friends use minibatches larger than 32. https://t.co/hxx2rGhIG1 / Twitter&quot;</h3><p>Training with large minibatches is bad for your health.More importantly, it&#39;s bad for your test error.Friends dont let friends use minibatches larger than 32. https://t.co/hxx2rGhIG1</p><p>You can see fitting the model in the code below:</p><pre>Fit the model<br>history = model.fit(X_train, y_train, epochs=50, batch_size=32, validation_split=0.2)</pre><h4><strong>Test Phase (model.evaluation)</strong></h4><p>For evaluating the accuracy after training the model, we use <em>model.evaluate</em>.</p><pre># Evaluate the model<br>test_loss, test_acc = model.evaluate(X_test, y_test)<br>print(&#39;Test accuracy:&#39;, test_acc)</pre><p>In the above codes, we trained the model without any specific tuning for hyperparameters. Methods such as <strong><em>BatchNormalization</em></strong>, <strong><em>Early Stopping</em></strong>, or <strong><em>L2 regularization</em></strong> were applied after running this code and completing the model training. <em>The test accuracy is 0.98879998</em>, obtained on the training data. However, we still do not know the model’s accuracy on real data. To understand how the model performed and whether overfitting occurred or not, we use <strong>Loss Curve</strong> and <strong><em>Accuracy Curve</em></strong> plots. These plots can be drawn using the <em>Matplotlib</em> library with the following code:</p><pre>import matplotlib.pyplot as plt<br><br># Create subplots with smaller figure size<br>fig, axs = plt.subplots(2, 1, figsize=(7, 9))<br><br># Plotting the loss curve<br>axs[0].plot(history.history[&#39;loss&#39;], label=&#39;Training Loss&#39;)<br>axs[0].plot(history.history[&#39;val_loss&#39;], label=&#39;Validation Loss&#39;)<br>axs[0].set_title(&#39;Loss Curve&#39;)<br>axs[0].set_xlabel(&#39;Epochs&#39;)<br>axs[0].set_ylabel(&#39;Loss&#39;)<br>axs[0].legend()<br><br># Plotting the accuracy curve<br>axs[1].plot(history.history[&#39;accuracy&#39;], label=&#39;Training Accuracy&#39;)<br>axs[1].plot(history.history[&#39;val_accuracy&#39;], label=&#39;Validation Accuracy&#39;)<br>axs[1].set_title(&#39;Accuracy Curve&#39;)<br>axs[1].set_xlabel(&#39;Epochs&#39;)<br>axs[1].set_ylabel(&#39;Accuracy&#39;)<br>axs[1].legend()<br><br>plt.tight_layout()<br>plt.show()</pre><p>The result of this code is the following plot, which indicates <em>overfitting</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qoHQVl-hdgq6z5J2k36HYA.jpeg" /><figcaption>This plot generated from my code illustrates the Loss and Accuracy Curves</figcaption></figure><p>As you can see in the graph, the model is likely overfitting. If there isn’t much difference between the training accuracy and validation accuracy, meaning they are closer to each other, it indicates that the model hasn’t overfit. However, if there is a significant difference, or if the validation accuracy starts decreasing while the training accuracy increases, it’s suspicious for <strong><em>overfitting</em></strong>. The accuracy lines should be smoother with fewer fluctuations. The presence of more fluctuations indicates instability in the model’s performance, which could be a sign of overfitting.</p><p>Now, to prevent overfitting, we need to provide solutions. In the next section, we’ll fully and practically see what to do if overfitting occurs, which often happens, especially if we don’t use methods to reduce overfitting or increase accuracy, as shown in the above example. Because the model tends to preserve the data automatically, it tends to memorize them well during the training phase and tends to keep them.</p><p>Therefore, in the next section, we’ll thoroughly and intuitively perform Hyperparameter tuning multiple times by comparing accuracy graphs. Stay tuned. The story gets more exciting from here…</p><h3><strong>All problems stem from overfitting!!!!</strong></h3><p>To improve the model we’re building, we need to perform Hyperparameter tuning. This means trying out different values for the methods we have for the problem at hand to find suitable Hyperparameters that increase the model’s accuracy and prevent overfitting. Therefore, I decided to document Hyperparameter tuning for methods such as<strong> <em>Early Stopping</em></strong>, <strong><em>Dropout</em></strong>, <strong><em>batch_size</em>, <em>learning_rate</em>,</strong> and <strong><em>L2 regularization</em></strong> by testing them with different values. The following code is an improved version of the code we saw above for building the model and contains the parameters necessary for Hyperparameter tuning:</p><pre><br>from tensorflow.keras.models import Sequential<br>from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout<br>from tensorflow.keras.layers import BatchNormalization<br>from tensorflow.keras.regularizers import l2<br><br># Create the model<br>model = Sequential()<br><br># Convolutional layers<br>model.add(Conv2D(32, (3, 3), activation=&#39;relu&#39;, kernel_regularizer=l2(0.01), input_shape=(28, 28, 1)))<br>model.add(MaxPooling2D((2, 2)))  # Max pooling layer<br><br># Adding Batch Normalization layer with momentum and epsilon settings<br>model.add(BatchNormalization(momentum=0.9, epsilon=1e-5))<br><br>model.add(Conv2D(64, (3, 3), activation=&#39;relu&#39;, kernel_regularizer=l2(0.01)))  # Convolutional layer<br>model.add(MaxPooling2D((2, 2)))  # Max pooling layer<br>model.add(Conv2D(64, (3, 3), activation=&#39;relu&#39;, kernel_regularizer=l2(0.01)))  # Convolutional layer<br>model.add(Flatten())  # Flatten layer to convert 2D matrix to a vector<br><br># Fully connected layers<br>model.add(Dense(64, activation=&#39;relu&#39;, kernel_regularizer=l2(0.01)))  # Dense (fully connected) layer<br>model.add(Dropout(0.30))  # Dropout layer for regularization<br>model.add(Dense(10, activation=&#39;softmax&#39;))  # Output layer with softmax activation for classification<br><br># Display model summary<br>model.summary()  # Print model architecture and parameters</pre><p>After running this code, we can view a summary of the architecture we’ve built with <em>CNN</em>. We can see the number of parameters in the model, the number of parameters in each layer, and other valuable information. After running this code, we proceed to compile the model in the same way as mentioned above.</p><p>In the next step, we want to add<em> </em><strong><em>Early Stopping</em> </strong>to the model. See the code below:</p><pre># Importing the EarlyStopping callback from TensorFlow Keras<br>from tensorflow.keras.callbacks import EarlyStopping<br><br># Creating an EarlyStopping callback object with a patience of 5 epochs<br>es = EarlyStopping(patience=5)</pre><p>In this code, we <em>import EarlyStopping </em>from the `<em>tensorflow.keras.callbacks`</em> library and set the patience value to 5. This allows the <em>callbacks</em> to stop the training process if the validation accuracy does not improve after 5 <em>epochs</em>. While it’s possible to randomly test the best number of epochs, the preferred method is <em>EarlyStopping</em>. This technique enables the model to evaluate its performance on a separate set of data, such as validation data, in each epoch.</p><p>Now we perform the <em>model.fit </em>step with the new parameters, and I’m including the updated code where the `<em>callbacks=[es]`</em> parameter is added. Note that this addition stops it if it heads towards overfitting.</p><pre># Fit the model<br>history = model.fit(X_train, y_train, epochs=50, batch_size=32, validation_split=0.2 , callbacks=[es])</pre><p>After running this code, we perform model evaluation to find the accuracy of the model. Please note that this only shows the accuracy on the training data, meaning it does not show the accuracy on test data that the model hasn’t seen yet. Essentially, with this, we aim to practice hyperparameter tuning and understand what it means when we say a model is overfitting.</p><h3><strong>Preventing overfitting!?!? How???</strong></h3><p>To prevent overfitting, we need to provide some solutions. <em>BatchNormalization</em> layer controls weight changes, preventing gradient explosion, and even overfitting, thereby speeding up the model training process. However, the use of <em>BatchNormalization</em> may sometimes increase training time as these layers require additional computations. Additionally, using <em>BatchNormalization</em> in certain network architectures like <em>Recurrent Neural Networks (RNNs)</em> may pose challenges due to their specific characteristics.</p><p>As we know,<em> L2 regularization</em> acts as a penalty term added to the objective function during model training. When adding <em>L2 regularization</em> to a model, the <em>weights</em> of its layers are effectively multiplied by the sum of the <em>L2</em> penalty value. This causes the weights to become smaller, helping prevent the model from overfitting, a concept also known as weight decay. However, if the L2 regularization term is too large, it can lead to underfitting because the model’s learning from the training data will be reduced. Therefore, the value of <em>L2 regularization</em> must be carefully chosen to strike a balance between preventing <em>overfitting</em> and avoiding <em>underfitting</em>.</p><p>In the following table, you can see parameters along with their corresponding accuracy values. All the data in this table have been thoroughly tested and obtained using the code provided below. To test each model, simply input the data from the table into their respective sections and observe the desired outcome.</p><blockquote>A very, very important point: All the data in this table has been trained using CPU. I did this so that we could understand the difference between training with CPU and GPU. If you were to swap the data in the same architecture and train with GPU, the results would probably be slightly different, and this is a very important point. Even if you train the data with CPU, it’s still possible to get different results. This is because factors like the randomness of the training process (especially if using a random model like Deep Neural Networks (DNNs), where training starts with random weights) and environmental conditions (saturation levels of GPU and CPU) can lead to different outcomes. I did this to visualize this issue and not forget its significance.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*OJk89X6BFBd0oHneHkCwCA.png" /><figcaption>The data in the table, resulting from <strong>hyperparameter tuning</strong>, has been used as the basis for creating plots in the subsequent sections of the article.</figcaption></figure><p>From the above table, we use various hyperparameter tuning methods to train the model and plot different graphs. By comparing these graphs, we can understand how properly adjusting even a single hyperparameter can significantly impact the performance of a model. In fact, by observing them, we can see that the effect of some methods is greater than others. In the next section, we delve into analyzing and comparing the graphs obtained using the above table.</p><h3><strong>The graphs</strong></h3><p>Compare the 4 plots of series A. In the plots below, they have been trained with parameters <em>batch_size = 32</em> and <em>learning_rate = 0.001</em>, along with <em>Dropout</em> rates of (<em>0.25, 0.30, 0.40, 0.50</em>). Take a good look at the series A plots. Almost all of them show a decreasing trend in accuracy. Significant fluctuations can be clearly observed in their plots.</p><p>Pay attention to the plots. They have been cut off in many points. The interruption of training and evaluation plots indicates a mismatch between training and validation data, suggesting that the model has been improperly adjusted. This usually points to issues like overfitting or underfitting.</p><p>If the Training Accuracy is continuously decreasing while the Validation Accuracy starts to increase or remains stable, this indicates overfitting. Conversely, if both training and validation accuracies consistently decrease or remain stable at similar levels, it indicates that the model has effectively learned. A significant gap between training and validation accuracies may suggest overfitting. Ideally, we aim to steadily increase both Training and Validation accuracies or stabilize them at similar levels.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J_IDcnU7RUJOZ1PLvMz68A.jpeg" /><figcaption>Four plots depicting series A data, corresponding to the table above</figcaption></figure><p>Now, let’s compare the 4 plots of series B. In the following plots, the models are trained with<em> batch_size = 64 </em>and <em>learning_rate = 0.01</em>, but the Dropouts are similar to the models whose plots you see above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ij7a5DmEz5PAo3zHFLYrFA.jpeg" /><figcaption>Four plots depicting series B data, corresponding to the table above</figcaption></figure><p>Do you see the significant difference? As you can observe, in the series B, improvements have been made in the learning process, and the fluctuations have reduced. In series B, the consolidation of data and validation on the plots has improved. Data consolidation refers to the stability or steadiness of the plots during the training <em>epochs</em>. Temporal consolidation occurs when the plots no longer show significant changes over the epochs. In fact, the loss or accuracy values (if using accuracy plots) no longer change significantly with minor fluctuations during the epochs. This stage is usually known as model stabilization because the model no longer gains new information from the data and reaches a stable and optimal state. In learning curves, consolidation is usually clearly observable; the lines or curves are less erratic and tend towards a stable point.</p><p>Pay attention to the series B plots. The convergence of the Training Accuracy and Validation Accuracy plots is much less pronounced, and it can be said that they almost do not converge. Additionally, the models have learned with fewer epochs, indicating an increase in computational speed and model<em> learning rate</em>. If the plots reach an acceptable accuracy very quickly and no improvement is observed with increasing<em> epochs</em>, it indicates the need for further hyperparameter tuning. In the next plots, we will see the power of <em>L2 regularization</em> and will delve into the examination and comparison of those plots.</p><p>In this section, we want to examine the series C plots. In these plots, the values of <em>L2</em> are set to 0.01, and the <em>learning rate</em> is set to 0.01, with <em>Dropout</em> values of 0.30 and 0.50, and a <em>batch size</em> of 32. We have compared them with the scenarios where <em>L2 = 0.001</em>. Pay close attention to the plots to fully understand the differences. The first plot corresponds to<em> Dropout = 0.30</em>. Sure, let’s focus on the accuracy graph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*odylj-56sAmU2Iaix5qXbA.jpeg" /><figcaption><strong>Comparison 1</strong>: L2 = 0.01, Learning Rate = 0.01, Dropout Rates = 0.30 and 0.50, Batch Size = 32. Comparison with L2 = 0.001 scenarios. Focus on accuracy graph</figcaption></figure><p>The second comparison we want to see below is where <em>batch_size=32</em> and Dropout=0.50, with only different L2 values. We want to compare plots A4.32 with C2.32, where we have chosen a larger <em>L2 </em>value for C2.32. Pay close attention.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z5bmrhVBKwfY0_mXAa_zgw.jpeg" /><figcaption><strong>Comparison 2</strong>: Batch_size=32, Dropout=0.50, varying L2 values. Focus on A4.32 vs. C2.32 plots with higher L2 value for C2.32. Pay attention.</figcaption></figure><p>Wow! Look at the difference! In fact, when we increased the <em>L2</em> value, overfitting no longer occurred, and now we’re seeing underfitting. If the <em>L2 regularization </em>value is too high, it may reduce the model’s performance and cause underfitting. Especially in this example where<em> Dropout=0.50</em>, this high <em>L2</em> value further exacerbated the issue and led to <em>underfitting</em>.</p><p>In the next section, we’ll discuss how to save the trained model and test it with test data.</p><h3><strong>Final test</strong></h3><p>After the Train Phase, it’s time for final testing to evaluate the model’s performance on unseen test data. First, we need to save the model. Since I used <em>colab.research.google</em> for model development, I’ll choose a path for saving the model accordingly. For example:</p><pre><br># Define the path to save the model<br>model_path = &quot;/content/drive/MyDrive/Colab Notebooks/trained_model.h5&quot;<br><br># Save the trained model<br>model.save(model_path)<br><br>print(&quot;Model saved at:&quot;, model_path)</pre><p>After running this code and ensuring that the model is saved in Google Drive, you just need to call it from its own path for use.</p><pre># Load the trained model<br>New_model = tf.keras.models.load_model(&quot;/content/drive/MyDrive/Colab Notebooks/trained_model.h5&quot;)</pre><p>Then, for prediction, we use the model in the following code. By “10000 test data from MNIST,” we mean the dataset that we saw when loading the data set.</p><pre><br>predictions = New_model.predict([X_test])<br>print(predictions)</pre><p>Now, with the following code, we simply request the model to display it, and after execution, we can see the numeric digit at <em>index 1</em>:</p><pre>print(np.argmax(predictions[1]))</pre><p>With the following code, we will visualize the desired number:</p><pre>plt.imshow(X_test[1])<br>plt.show()</pre><h3><strong>Conclusion</strong></h3><p>In this article, we constructed a model using <em>CNN</em> with the MNIST dataset. We became familiar with the process of building the model and its various stages. As we saw, the validation accuracy percentage of different models may not differ significantly, but their performance with the test data can vary greatly. We learned that by adjusting parameters, as mentioned in the normalization section of this article, we can reduce the time and amount of computations. We observed how the number of epochs for learning differs between two different models and the goal of examining and plotting comparative graphs was to understand the importance of <em>hyperparameters</em> and to identify <em>overfitting</em> or <em>underfitting</em> by analyzing different graphs with different parameters. In fact, overfitting may always exist in the model, and addressing this issue can lead to differences in performance. We also provided solutions to address it. Indeed, very important parameters such as <em>L2 regularization</em> and Dropout can greatly affect the performance and accuracy of the model, and even slight changes in each can have very negative or positive consequences. Building a model requires practice and precision. Therefore, in this article, after going through these steps nearly 20 times with different <em>hyperparameter</em> settings and adding or subtracting new patterns, we reached a result close to the desired one mentioned at the end. Thank you for accompanying me.</p><p>I would be happy to hear your feedback on this article.</p><p>Thank you for accompanying me on this journey into the world of deep learning.</p><p>The link to the article in Persian is available on <a href="https://vrgl.ir/7ZE5E">virgool.io</a>.</p><p>If you’re interested, you can check out my other article, “<a href="https://medium.com/@m.javadnejadi/digging-deeper-and-deeper-into-deep-learning-and-artificial-neural-networks-bad7b462ca59">Digging deeper and deeper into deep learning and artificial neural networks# Part I: History of artificial intelligence and how simple neural networks work</a>.” on Medium.</p><p><a href="https://medium.com/@reza.shokrzad/hyperparameter-hunt-exploring-the-spectrum-of-optimization-techniques-dd3813317130">Hyperparameter Hunt: Exploring the Spectrum of Optimization Techniques</a></p><p>I hope you’ve enjoyed the content.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84961f96c7e8" width="1" height="1" alt=""><hr><p><a href="https://aiadvances.org/step-by-step-guide-to-building-an-artificial-neural-network-and-observing-how-overfitting-occurs-84961f96c7e8">Step-by-step guide to building an artificial neural network and observing how overfitting occurs…</a> was originally published in <a href="https://aiadvances.org/">AI Advances</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Digging deeper and deeper into deep learning and artificial neural networks]]></title>
            <link>https://aiadvances.org/digging-deeper-and-deeper-into-deep-learning-and-artificial-neural-networks-b41570db6259?source=rss-707395aa8764------2</link>
            <guid isPermaLink="false">https://medium.com/p/b41570db6259</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[architecture]]></category>
            <dc:creator><![CDATA[M Javadnejadi]]></dc:creator>
            <pubDate>Tue, 05 Mar 2024 16:31:17 GMT</pubDate>
            <atom:updated>2024-03-06T04:58:47.997Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Part III: Major architectures of deep neural networks (RNN / LSTM / CNN).</strong></h4><p><strong>We need to go deeper!</strong></p><blockquote>“The architecture of the new world.”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P8peCzSrikdTf5UD2Ek6TA.png" /><figcaption>Generated by Ideogram</figcaption></figure><p>This article is divided into three parts as follows:</p><p><a href="https://medium.com/@m.javadnejadi/digging-deeper-and-deeper-into-deep-learning-and-artificial-neural-networks-bad7b462ca59"><strong>Part I: History of artificial intelligence and how simple neural networks work.</strong></a></p><p><a href="https://medium.com/@m.javadnejadi/digging-deeper-and-deeper-into-deep-learning-and-artificial-neural-networks-e1db9097f744"><strong>Part II: Learning mechanisms in deep neural networks (types of learning, activation functions, and backpropagation).</strong></a></p><p><strong>Part III: Major architectures of deep neural networks (RNN / LSTM / CNN).</strong></p><p>In these three parts, we will address topics such as what artificial neural networks are, how they work, what deep learning is, how learning is performed in deep networks, and what are the types of learning methods. What are the main architectures of deep networks? Is the function of artificial neural networks similar to that of human neural networks, or is it just inspired by them? What are the applications of neural networks, and what are their drawbacks?</p><h3><strong>Background Review</strong></h3><p>In Part II, we explored some of the most important activation functions, their functionalities, as well as their advantages, disadvantages, and differences. We also examined one of the most practical algorithms in deep learning, backpropagation, which we can boldly say that learning would not exist without it because in many tasks, the functionality of modern deep networks would not be possible without updating the weights.</p><p>In Part 3, we aim to delve into the architectures of artificial neural networks. We can say that choosing the type of architecture is one of the most important tasks in building neural networks. In the past, the architectures we had were mostly for specific tasks. For example, CNN was initially introduced only for image processing, but nowadays, we know that we can use this type of architecture for other tasks as well. We’ll explore the powerful architectures of RNNs with their gates and the differences they have with LSTMs. LSTMs, in fact, are short-term memory in language models. For instance, in chatGPT, after several prompts, if we ask it about the previous prompts, it recalls the previous content. We’ll examine CNNs and their functionalities, from face recognition to image generation and processing, and self-driving cars, all of which are made possible with the help of CNNs. We want to understand what padding is, how convolutional layers work, and investigate pooling layers and their differences. We’ll also examine fully connected (FC) layers. I am very excited to learn about these, how about you? Are you as excited as I am? Let’s dive in…!</p><h3><strong>Neural network architecture</strong></h3><p>The architecture of neural networks determines how these networks operate, which is a crucial factor for performing various tasks and expanding the applications of neural networks, primarily in two approaches: <strong>feedforward </strong>neural networks and <strong>feedback</strong> neural networks. In this article, after thoroughly analyzing each, we’ll provide a deep comparison of both architectures and examine the use cases to compare the advantages and disadvantages of each neural network structure. For implementing deep networks, we use two approaches: <strong>Sequential and Functional</strong>. In this section, we’ll delve into the construction and architectural approaches of the network. Stay tuned with me.</p><h3><strong>sequential and Functional in Deep learning</strong></h3><p>In Deep Learning, there are two different approaches to designing neural network models: sequential and Functional. The choice between these two methods depends on the type of problem, the complexity of the model, and our specific requirements. Both sequential and Functional approaches can be executed in frameworks like Keras and PyTorch.</p><p>Additionally, we can use a combination of both approaches. This means that we can build part of the model using the sequential method and another part using the Functional method, as long as the structure of the model is properly defined and the inputs and outputs of each part are compatible with each other. For example, in face recognition systems, you could design part of the model using Sequential for processing images with Convolutional Neural Networks (CNNs), and another part using Functional for analyzing sequences of facial features with Recurrent Neural Networks (RNNs).</p><h3><strong>The sequential model</strong></h3><p>We build the model layer by layer. Sequential models are constructed linearly and sequentially, meaning the output of one layer serves as the input to the next layer, without any connections between non-adjacent layers. However, sharing layers or branching layers is not allowed (although we have branching layers in some network models that perform multiple tasks simultaneously). Additionally, you cannot have multiple inputs or outputs.</p><p>In Keras, to implement a Sequential model, we first import the necessary libraries, then create a Sequential model, and use the `add()` method to add layers to the model one after another. The following code snippet is a simple implementation of a Sequential model:</p><pre>from keras.models import Sequential<br>from keras.layers import Dense<br><br># Create a Sequential model<br>model = Sequential()<br><br># Add layers to the model<br>model.add(Dense(units=64, activation=&#39;relu&#39;, input_shape=(100,)))<br>model.add(Dense(units=64, activation=&#39;relu&#39;))<br>model.add(Dense(units=10, activation=&#39;softmax&#39;))<br><br># summary model<br>model.summary()</pre><p>This code creates a Sequential model with three layers: two dense layers with ReLU activation functions and one dense output layer with a softmax activation function.</p><h3><strong>The functional model</strong></h3><p>In Keras, the Functional API provides a way to define more complex deep learning models that have multiple inputs, multiple outputs, or shared layers. The Functional API is a more flexible and powerful approach to defining models compared to the Sequential model, which only supports linear stacks of layers. In a functional model, you can still create a linear sequence of layers by connecting them sequentially, but you can create more architectural complexities by merging layers. This means that while the layers are connected linearly with each other, the overall architecture of the model may not be linear and may include different types of layers. The main difference between these two models lies in how the layers are connected and their flexibility.</p><p>The Functional API can manage models with nonlinear architectures, shared layers, and even multiple inputs or outputs. The main idea behind the Functional API is to define each layer as a separate object and then connect the layers together by explicitly defining the input and output of each layer. The pseudo code below first defines an input layer using `Input`. Then, using `Dense`, a fully connected layer is defined as the output, and using `Model`, a model with specified input and output is created. Finally, by calling `summary()`, a summary of the model architecture is printed. Here is a simple implementation of the Functional API model:</p><pre><br>#Import the libraries<br>from keras.layers import Input, Dense<br>from keras.models import Model<br><br># The definition of input and output layers<br>input_layer = Input(shape=(784,))<br>output_layer = Dense(10, activation=&#39;softmax&#39;)(input_layer)<br><br># Creating the model<br>model = Model(inputs=input_layer, outputs=output_layer)<br><br># summary model<br>model.summary()</pre><p>We will continue to explore the fascinating architectures of neural networks and examine their applications, advantages, and disadvantages. Let’s delve into these frontiers together and embark on a journey into their realm. Are you ready? Let’s go.</p><h3><strong>Feedforward Network</strong></h3><p>This is a non-recurrent network, in fact, the opposite of recurrent neural networks. Feedforward neural networks are primarily used for supervised learning tasks where the data to be learned is <strong>neither sequential nor time-dependent.</strong></p><p>A feedforward neural network consists of three main parts: an input layer, one or more hidden layers (if present), and an output layer. Each layer processes information and passes it to the next layer. In other words, the signal can only flow in one direction. There are no loops in such a network, and the output layer operates distinctly from the other layers, meaning there is no recurrence in it.</p><h3><strong>Types of Feedforward Neural Networks</strong></h3><p>There are various types of feedforward neural networks, each with its own features and architecture for different applications. Some of the most common types include:</p><h3><strong>Single Layer Feedforward Network (Perceptron)</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/1*AYmFw55q_q1rZp9MMbes3w.jpeg" /><figcaption><a href="https://www.tutorialspoint.com/artificial_neural_network/artificial_neural_network_quick_guide.htm#:~:text=Learning%2C%20in%20artificial%20neural%20network,unsupervised%20learning%2C%20and%20reinforcement%20learning.">source</a></figcaption></figure><p>The simplest type of neural network is the perceptron. Therefore, a perceptron has only one input layer and one output layer. The output units are directly calculated from the sum of their weights (W) with the corresponding input units plus a bias. These networks can only learn linear relationships between data and are sensitive to incorrect data, making them more suitable for simple classification tasks.</p><h3><strong>Multilayer Feedforward Network</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*f7zzuyPH4ZGEMNsskgXdxg.jpeg" /><figcaption><a href="https://www.tutorialspoint.com/artificial_neural_network/artificial_neural_network_quick_guide.htm#:~:text=Learning%2C%20in%20artificial%20neural%20network,unsupervised%20learning%2C%20and%20reinforcement%20learning.">source</a></figcaption></figure><p>This type of network has one or more hidden layers between the input and output layers. The concept is that the feedforward neural network has more than one weighted layer (hidden layer). The hidden layers allow the network to learn more complex pathways to represent its received data, enabling it to solve more complex problems.</p><p><strong>Feedback Network</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/399/1*W9je37rDV27wl2_pbfvNJA.jpeg" /><figcaption><a href="https://www.tutorialspoint.com/artificial_neural_network/artificial_neural_network_quick_guide.htm#:~:text=Learning%2C%20in%20artificial%20neural%20network,unsupervised%20learning%2C%20and%20reinforcement%20learning.">source</a></figcaption></figure><p>Feedback neural networks, as the name suggests, unlike feedforward neural networks, have feedback paths, allowing signals <strong>to move in both directions through loops</strong>. Neural connections can be created in various ways, making these networks potentially more complex as signals constantly loop back and forth.</p><p>The goal of feedback neural networks is to reach an equilibrium state, which persists until there is no change in the input. Unlike feedforward networks, feedback networks do not require “<strong>error measurement</strong>”. The most important part in feedforward neural networks is the input data, whereas in feedback neural networks, the <strong>output </strong>is the most crucial part. This is because the output value is fed back into the network as input, determining new weights and biases until the desired outcome is achieved, continuing this cycle until the desired result is achieved.</p><p>Feedback neural networks can include various types of topologies, each utilizing loops to effectively solve different problems.</p><h3><strong>1. Recurrent neural network (RNN)</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*b4w12Ekzp_Vf6l0ntA0zWw.gif" /><figcaption><a href="https://www.analyticsvidhya.com/blog/2021/06/a-visual-guide-to-recurrent-neural-networks/">source</a></figcaption></figure><p>One of the important and fundamental types of artificial neural networks is the recurrent neural network (RNN), where data flow is feedback-based. Essentially, an RNN is a two-way network. In other words, data is fed into the network, and after processing the data and applying weights, the generated output is fed back into the network for adjusting the weights. We can use RNNs that work with time-series data for processing video and audio, for example, in self-driving cars. The most significant issue that RNNs may face is the vanishing gradient problem, which may occur during training. This problem usually exists in simple RNNs trained using backpropagation through time (<strong>BPTT</strong>).</p><p>In fact, as the network becomes deeper, during the backpropagation process, the gradients (partial derivatives) that propagate from higher layers to lower layers tend towards zero. As a result, the weights of lower layers are not updated, causing these layers to receive less information from the inputs and leading to difficulties in learning and retaining information over long sequences.</p><p>Recurrent neural networks can have various types, each used for a specific task:</p><h4><strong>Simple Recurrent Neural Networks (Simple RNNs):</strong></h4><p>Usually constructed with a single recurrent layer, these networks can address immediate problems for small-scale tasks. For instance, they can predict the next character in a text sequence or the next number in a numerical sequence. However, over time, they may encounter the vanishing gradient problem due to only using a single memory unit.</p><h4><strong>Gated Recurrent Units (GRUs):</strong></h4><p>like LSTMs, feature a complex structure that enables learning and retaining long-term information. GRUs are computationally lighter than LSTMs because they use two gates for learning. This makes GRUs faster for training and execution.</p><p>GRUs can utilize long-term memory for learning complex patterns in languages. This is because GRUs use two gates: the Update Gate determines how much of the past information should be combined with the new information, while the Reset Gate determines how much of the past information should be retained or forgotten. In fact, both LSTM and GRU networks can use long-term memories for retaining patterns and long-term information, but they do so with different approaches and structures.</p><p>LSTMs also have long-term memory. However, because they have a Forget Gate, which determines how much of the past information should be forgotten, they can potentially have a longer long-term memory. In practice, their approach and structure are different.</p><p>In some cases, LSTMs are still a common choice for tasks such as language modeling or machine translation due to their superior ability to retain and control information.</p><p>For example, Google Translate uses a combination of GRUs and LSTMs, allowing it to benefit from the advantages of both.</p><h4><strong>Bidirectional RNNs:</strong></h4><p>It utilizes two layers of RNN, one in the forward direction and one in the backward direction, enabling the network to utilize both preceding and subsequent information at any given moment. This type of network can be effective in interpreting texts and sequences. The learning methods in it can be similar to those in unidirectional networks.</p><p>There are three types of learning methods for Bidirectional RNNs.</p><p>The first type is <strong>Forward-Backward Learning</strong>, where two RNN layers in the forward and backward directions sequentially learn from the input sequence.</p><p>The second type is <strong>Simultaneous Prediction</strong>, where the network’s output from both directions (forward and backward) is simultaneously predicted.</p><p>The third type is <strong>Prediction and Decision Making</strong>, where the required outputs for decision-making or prediction are first calculated using the bidirectional network. In all learning types, the final output is obtained by combining the outputs of both layers, allowing bidirectional RNNs to consider both past and future information and provide better results in tasks such as machine translation, sentiment analysis, and text generation. Bidirectional RNNs are recognized as effective and powerful methods in these areas.</p><h3><strong>Long Short-Term Memory — LSTM</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*M3JdgBiCoAmLqoIQlU1sbg.gif" /><figcaption><a href="https://medium.com/analytics-vidhya/introduction-to-long-short-term-memory-lstm-a8052cd0d4cd">The source of this gif is an article on Medium.</a></figcaption></figure><p>Long Short-Term Memory (LSTM) is a type of recurrent neural network architecture designed to address the <strong>vanishing gradient problem </strong>that occurs in traditional recurrent neural networks (RNNs). The main difference between LSTM and traditional RNNs lies in their <strong>ability to capture and retain long-term dependencies in sequential data</strong>. LSTM solves this problem by introducing a memory cell with gates (input gate, forget gate, and output gate) that control the flow of information. These gates are neural network layers that decide which information should be stored, forgotten, or outputted from the memory cell. This architecture allows LSTM to maintain long-term memory and selectively update it over time.</p><p>LSTMs are trained using <strong>Backpropagation Through Time (BPTT)</strong>, where models are taken “deep” into the past beyond a simple recurrent process. This involves two stages: the Forward Pass, where input data is fed into the model and output is computed, and the Backpropagation, which is similar to the regular backward pass. Using the chain rule, gradients of the error with respect to the weights and other network parameters are computed. Parameters are updated using these calculated gradients to minimize the error.</p><p>LSTMs are <strong>crucial for long-term dependencies</strong>, making them more suitable for tasks such as machine translation, speech recognition, and sentiment analysis. LSTMs share some common features and principles of operation with human short-term memory. Just as human short-term memory can retain information for a long time (e.g., minutes to hours), LSTMs can also maintain information in their cell memory for a long time using their mechanisms. Both have mechanisms for forgetting and deleting unnecessary information. For example, in LSTM, the forget gate is responsible for removing irrelevant information from the cell memory. Both can learn and retain complex patterns and dependencies in input data. For these reasons, in some cases, LSTM can serve as a conceptual model for describing short-term memory.</p><h3><strong>2.Fully recurrent network</strong></h3><p>As the name suggests, in this type of neural network architecture, all neurons in the layers are fully connected to other neurons. This means that each neuron serves as both input and output. Fully recurrent networks are suitable for processing sequences of varying lengths, such as text, speech, machine translation, or time series prediction, like predicting financial market prices or traffic. However, one of the main problems is the issue of unstable gradients, particularly prominent in neural networks, including fully recurrent networks. This can lead to vanishing or exploding gradients.</p><p>In the case of vanishing gradients, the gradients decrease towards zero, leading to a reduction in the network’s learning capability. In the case of exploding gradients, gradient values increase towards infinity. This can cause deviation from the optimal path or even network failure. To address this issue, gradient improvement techniques can be employed. One of these techniques is training with backpropagation through time (BPTT).</p><p>Another potential problem with FRNNs is their computational complexity. Due to the large number of connections between neurons, training these networks can be time-consuming and challenging. Additionally, FRNNs may easily overfit, especially when working with limited data. This issue can lead to poor performance on new and unseen data.</p><p>However, by making improvements in training methods and optimization, as well as using complexity reduction techniques such as approximation methods and data analysis, it’s possible to address these challenges in FRNNs and enhance their performance.</p><h3><strong>3. Elman and Jordan networks</strong></h3><p>Jordan networks, or Jordanian networks, are the simplest type of recurrent neural networks (RNNs). In these networks, input information is fed into each neuron, and then transmitted to the same neuron as input. Jordan networks consist of only one hidden layer, and activation occurs in both the hidden and output layers. They utilize backpropagation algorithms to optimize parameters.</p><p>Jordan networks are capable of learning long-term dependencies in sequential data. Like other RNNs, Jordan networks can also suffer from the vanishing gradient problem, making it difficult to learn long-term dependencies. This architecture allows the network to transfer information from the current moment to the next.</p><p>They can be used for tasks such as price prediction, financial time series analysis, or natural language processing (NLP). Elman networks are similar to Jordan networks, with the key difference being that activation occurs only in the hidden layer. Activation in the output layer allows Jordan networks to learn long-term dependencies better than Elman networks. However, this feature may lead to a decrease in computational efficiency.</p><p>Due to their simplicity and limited capability to solve complex problems compared to modern architectures, Jordan networks are not widely used today. However, depending on the specific task at hand, they may still find some applications.</p><h3><strong>4. Convolutional Neural Networks (CNNs)</strong></h3><p>Convolutional Neural Networks or CNNs, a term we’ve heard countless times. It can be said that the revolution we are currently witnessing has CNNs as one of its main pillars. But the question arises: how does CNN work? What sets it apart from other networks? We need to go back in time. Join me for an intriguing journey, would you? Give it a try!</p><p>First introduced by Yann LeCun in the 1980s, CNNs faced challenges due to computational limitations until the late 1990s. The breakthrough came with the publication of the paper “<a href="https://ieeexplore.ieee.org/document/726791">Gradient-based learning applied to document recognition</a>” in 1998, which significantly boosted the use of CNNs in pattern recognition and image processing. This surge was further fueled by advancements in fast computations and the emergence of GPUs, making CNNs widely adopted in various domains such as object detection, face recognition, fingerprint identification, autonomous vehicles, natural language processing, and more.</p><p>So, how do CNNs work?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*wQX5sO6avQNOT0Ae3w_Z9A.jpeg" /><figcaption><a href="https://www.researchgate.net/figure/The-classical-structure-of-convolutional-neural-networks-CNNs_fig1_339708596">source</a></figcaption></figure><p>When we look at an image, within fractions of a second, our brains process it quickly with the knowledge we already have, enabling us to recognize the image swiftly. However, for computers, it’s not the same. Machines need to see an image pixel by pixel.</p><p>The architecture of CNNs is inspired by the connectivity pattern of neurons in the visual cortex of animals. The most significant similarity is their hierarchical processing of information, where features become more complex in higher layers. CNNs use convolutional filters to extract features from images, drawing inspiration from how neurons in the visual cortex operate.</p><p>What sets CNNs apart from other architectures is their principles. In each layer, CNNs increase complexity and identify more parts of the image. The first layer is the convolutional layer, where filters are applied to detect features. Then comes the pooling layer, used in hidden layers to extract the most important features for forwarding to the last layer, which is the fully connected layer, where the machine’s visual tasks are performed.</p><p>Join me as we delve deeper into the layers of CNNs.</p><h4><strong>Convolutional Layer</strong></h4><p>The main layer of CNN is where most of the computations take place. The images fed into this layer can vary in complexity. They can be 2D images with width and height dimensions and can be either single-channel (grayscale) or 3-channel RGB (color). There are also 3D images with depth, such as medical images (CT scans and MRIs), which increase the model’s complexity.</p><p>The following code snippet uses the `Conv2D` method, one of the members of the `layers` module, to create a convolutional layer in Keras:</p><pre># Adding a convolutional layer with 3 filters of size 3x3 and ReLU activation function<br>model.add(layers.Conv2D(3, (3, 3), activation=&#39;relu&#39;, input_shape=(28, 28, 1)))</pre><p>The parameter `input_shape` specifies the shape of the input data, which has dimensions of (28, 28, 1), representing a grayscale image with dimensions of 28 x 28 pixels.</p><p>The convolutional layer consists of <strong>convolutional filters</strong>, also known as kernels. Each neuron in the convolutional layer is connected to a specific weighted filter (or weight matrix). To visualize information about the filters, we can use the properties of the layer. These properties are typically accessible after training the model. For example, after training the model, you can access the weights of each layer and print them.</p><p>The following code snippet in Keras demonstrates how to access the weights of a convolutional layer.</p><pre># Accessing the weights of the convolutional layer<br>weights = model.layers[0].get_weights()[0]<br><br># Printing the dimensions of the filter weights<br>print(&quot;Filter dimensions:&quot;, weights.shape)</pre><p>Each of these filters extracts different features from the image. The extracted features include edges, bright spots, and darkness, which are referred to as <strong>feature maps</strong>. The <strong>Sobel</strong> and <strong>Scharr</strong> filters are commonly used filters in image processing for detecting vertical and horizontal edges and marking gradients in the image. When these filters are applied to the image, they measure the intensity or brightness changes at various points in the image by calculating partial derivatives of the image in horizontal and vertical directions.</p><p>However, the main difference between these two filters lies in their <strong>kernel (or matrix)</strong> features. The Sobel filter’s kernel is defined with a greater emphasis on <strong>horizontal and vertical</strong> changes in the image. Edge detection by the Scharr filter is <strong>independent of their direction</strong>; in other words, if there is an edge in the image, regardless of whether it is horizontal or vertical, the Scharr filter can detect it well. For example, <strong>in object or image component detection</strong>, the direction of the edge may be less important, and what matters is that the edges are properly identified.</p><p>Sample code for applying Sobel and Scharr filters in Python using OpenCV:</p><pre># Calling the OpenCV library<br>import cv2<br><br># Apply Sobel filter<br>sobel_x = cv2.Sobel(image, cv2.CV_64F, 1, 0, ksize=3)<br>sobel_y = cv2.Sobel(image, cv2.CV_64F, 0, 1, ksize=3)<br><br># Apply Scharr filter<br>scharr_x = cv2.Scharr(image, cv2.CV_64F, 1, 0)<br>scharr_y = cv2.Scharr(image, cv2.CV_64F, 0, 1)</pre><h3><strong>Padding</strong></h3><p>For building complex models like Convolutional Neural Networks (CNNs) or Recurrent Neural Networks (RNNs), a standard input shape is required. When a filter moves across the beginning of an image, some information from the edges of the image is lost, resulting in a reduction in the dimensions of the output image from the convolutional layers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*ZCjPUFrB6eHPRi4eyP6aaA.gif" /><figcaption><a href="https://medium.com/analytics-vidhya/convolution-padding-stride-and-pooling-in-cnn-13dc1f3ada26">The source of this gif is an article on Medium.</a></figcaption></figure><p>The absence of padding may cause the output dimensions of convolutional layers to shrink to a point where convolution operations cannot be properly performed on them. One of the main advantages of padding is its ability to standardize input data. Padding in CNN involves adding zero values to the edges of input images or feature maps. It’s usually implemented in two ways.</p><h3><strong>Zero Padding</strong></h3><p>In the Zero Padding method, the added information to the edges of the image is filled with zero values, which can lead to a reduction in image clarity. Using Zero Padding can increase memory consumption in neural models because adding zeros to the edges of the image increases the data volume, which can be problematic for processing large images. Zero Padding allows for the creation of deeper networks while preserving output dimensions and edge information, potentially speeding up computations but may incur higher computational costs. It can be used to increase the image size and preserve edge clarity to improve object detection accuracy.</p><p>To perform Zero Padding in the TensorFlow library, you can use the` <strong>tf.pad()</strong>` function. This function allows you to perform padding by adding zeros or other specified values to the edges of the image.</p><pre># Apply Zero Padding by adding 2 rows and 2 columns of zeros to the edges of the image<br>padded_image = tf.pad(image, [[0, 0], [2, 2], [2, 2], [0, 0]], &quot;CONSTANT&quot;)</pre><h3><strong>Valid Padding</strong></h3><p>In the Valid Padding method, compared to Zero Padding, no data is added to the edges of the image. In fact, no padding is applied. In other words, filters (kernels) move only over parts of the input that match the kernel size completely. As a result, the output image from the convolutional layers will have smaller dimensions than the input image, leading to a reduction in data volume and computational complexity as well as a decrease in execution time.</p><p>When we are interested in extracting features and patterns from the image, and the size of the output image is not crucial for our subsequent tasks, Valid Padding can be used. In fact, we don’t encounter many of the drawbacks of Zero Padding. In the real world, the Valid Padding method is typically used in tasks such as object detection, image classification, and pattern recognition where increasing the size of the output image is not necessary, and we aim to enhance computational speed and efficiency. In the following simple pseudo code, we define a Conv2D layer with Valid Padding, which is done by setting the padding parameter to ‘valid’:</p><pre># Define a Conv2D layer with Valid Padding<br>conv_layer = Conv2D(filters=16, kernel_size=(3, 3), padding=&#39;valid&#39;, activation=&#39;relu&#39;, input_shape=(28, 28, 1))</pre><p>Exactly! Padding plays a crucial role in preprocessing images, especially before convolution operations in neural network models. The choice between different padding methods depends on the nature of the problem and specific requirements. It can be applied as a separate layer in the neural network model or directly incorporated into convolution functions.</p><p>These data are then passed to the pooling layers of the CNN network to extract more complex features for tasks such as image recognition or image classification.</p><p>One of the fundamental differences of CNN for image processing compared to older methods is that previously, these filters had to be manually applied using local filters.</p><h3><strong>Pooling layers</strong></h3><p>Pooling operations are performed to reduce the spatial dimensions (length and width) of feature maps while preserving important information. Pools typically move as sliding windows over the feature map, selecting a value from the start to the end of this window each time using a specified criterion (such as maximum or average). This operation is repeated to reduce the spatial dimensions of the feature map while preserving important information. This operation helps reduce model complexity and is one of the factors that increase the speed and efficiency of the network. It also reduces issues like overfitting. There are two common types of pooling, each suitable for specific tasks.</p><h3><strong>Max Pooling</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gpkHl16U7ppl4-lBlnAYqw.gif" /><figcaption><a href="https://brightonnkomo.medium.com/convolutional-neural-networks-part-4-the-pooling-and-fully-connected-layer-394ec01fb00d">The source of this gif is an article on Medium.</a></figcaption></figure><p>When the convolutional filter (or kernel) moves over the input image, a portion of the filter often <strong>overlaps</strong> with a portion of the previous image, and another portion of the filter overlaps with a portion of the new image. This model takes <strong>the maximum values</strong> from each overlapping region in the feature map and selects the maximum value as the output value of that region. However, Max Pooling may lose detailed information because it only selects the maximum value for each region and disregards smaller values.</p><p>The overlapping region is considered a hyperparameter. It can be adjusted based on the needs and characteristics of the problem. Increasing the overlapping region may require the model to extract more features, leading to a longer training time. This can increase the complexity of the model and lead to overfitting.</p><p>Below is a simple pseudo code for Max Pooling in Keras using the `MaxPooling2D` layer, where `pool_size` specifies the size of the Max Pooling filter:</p><pre># Importing the necessary layers from Keras<br>from keras.layers import MaxPooling2D<br># Adding a Max Pooling layer to the model<br>model.add(MaxPooling2D(pool_size=(2, 2), strides=None, padding=&#39;valid&#39;))</pre><h3><strong>Average Pooling</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ySPn71bCVSIpbKbsnsCnDw.jpeg" /><figcaption><a href="https://brightonnkomo.medium.com/convolutional-neural-networks-part-4-the-pooling-and-fully-connected-layer-394ec01fb00d">The source of this gif is an article on Medium.</a></figcaption></figure><p>In this method, unlike Max Pooling, we take the <strong>average</strong> values in each overlapping region and select it as the output value. Average Pooling is usually used to reduce the spatial dimensions of the feature map and create a clearer image. In this approach, precise information in small regions of the input image is averaged, which may reduce attention to local features in those regions and lead to loss of detailed information. This loss of detailed information can prevent model training and cause underfitting, especially in cases where small details of the image are important for various tasks such as precise pattern recognition or detailed imaging. Therefore, this method should be used carefully, considering the specific characteristics of the problem.</p><p>Below is a simple pseudo code to better understand Average Pooling in Keras:</p><pre>from keras.layers import AveragePooling2D<br><br># Add Average Pooling layer with specified pool size<br>model.add(AveragePooling2D(pool_size=(2, 2)))</pre><h3><strong>Fully connected layers</strong></h3><p>In a Fully Connected layer, each neuron or node is connected to every neuron in the previous layer. This means that all input signals from the previous layer are considered for the output of each neuron.</p><p>Fully Connected layers are often used in the final stages of a neural network for tasks such as classification or regression. The main problem with these layers, which have a large number of parameters capable of retaining a lot of information, is overfitting. To prevent this issue, two solutions, <strong>dropout </strong>and <strong>regularization</strong>, can be effective.</p><p>In the dropout method, during each training step, a <strong>random set</strong> of neurons and connections between them are dropped out or removed. Dropout generally makes the neural network more flexible. Additionally, regularization aims to reduce model complexity by adding a certain coefficient of the weights to the objective function to <strong>limit the magnitude</strong> of the weights and prevent them from becoming too large. Typically, L1 and L2 regularization are used, known as “Lasso regularization” and “Ridge regularization,” respectively.</p><p>In L1 regularization, a term is added to the objective function as the sum of the absolute values of the weights. This causes some weights to become zero, effectively removing unnecessary weights from the model. In L2 regularization, a term is added to the objective function as the sum of the squares of the weights. This causes the weights to become small but continuous, without reaching zero. This allows all features to be influential with different weights, but to a lesser extent compared to no regularization.</p><p>We see all the explanations given about the FC in the code snippet briefly.</p><pre>import tensorflow as tf<br><br># Define the model<br>model = tf.keras.Sequential([<br>    tf.keras.layers.Flatten(input_shape=(28, 28)),  # Input layer: Convert images to vectors<br>    tf.keras.layers.Dense(128, activation=&#39;relu&#39;),  # Fully connected layer with 128 neurons and ReLU activation<br>    tf.keras.layers.Dropout(0.2),  # Dropout with rate 0.2<br>    tf.keras.layers.Dense(64, activation=&#39;relu&#39;),   # Fully connected layer with 64 neurons and ReLU activation<br>    tf.keras.layers.Dropout(0.2),  # Dropout with rate 0.2<br>    tf.keras.layers.Dense(10, activation=&#39;softmax&#39;) # Output layer with 10 neurons for classifying 10 different classes and softmax activation<br>])</pre><p>This code defines the Fully Connected (FC) layers and uses dropout regularization without compiling the model.</p><h3>Conclusion of Part III</h3><p>In this article, I tried to explain the most important and fundamental topics related to neural networks and deep learning from the beginning until now, and delve deeper into the intricacies of deep learning layers. But this is just the beginning. Deep learning boundaries are very narrow, and different deep learning networks are evolving. In fact, today, the use of deep learning networks has been combined to perform various tasks. As we know, we have products in which natural language processing has been done simultaneously, and also, for example, image generation has been performed, or vice versa. Therefore, the boundaries of deep learning are becoming increasingly blurred, and many topics in this article were not covered. In the future, we will delve into more topics of deep learning.</p><p>Thank you for accompanying me on this journey into the world of deep learning.</p><p>The link to the article in Persian is available on <a href="https://vrgl.ir/63qDj">virgool.io</a></p><p><a href="https://medium.com/@m.javadnejadi/digging-deeper-and-deeper-into-deep-learning-and-artificial-neural-networks-bad7b462ca59">Part I: The history of artificial intelligence and how simple neural networks function.</a></p><p><a href="https://medium.com/@m.javadnejadi/digging-deeper-and-deeper-into-deep-learning-and-artificial-neural-networks-e1db9097f744">Part II: Learning in deep neural networks (types of learning and activation functions, backpropagation).</a></p><p>Part III: Important architectures of deep neural networks (RNN / LSTM / CNN).</p><p>If you’re interested, you can check out my other article, “<a href="https://medium.com/@m.javadnejadi/is-deepfake-a-technology-of-the-future-or-a-threat-088831f26bbe">Is DeepFake the Future or a Threat? Will the line between reality and fabrication disappear?</a>” on Medium.</p><p><a href="https://medium.com/@reza.shokrzad/recommender-systems-techniques-that-power-personalization-482f4178044c">Recommender Systems: Techniques that Power Personalization</a></p><p>I hope you’ve enjoyed the content.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b41570db6259" width="1" height="1" alt=""><hr><p><a href="https://aiadvances.org/digging-deeper-and-deeper-into-deep-learning-and-artificial-neural-networks-b41570db6259">Digging deeper and deeper into deep learning and artificial neural networks</a> was originally published in <a href="https://aiadvances.org/">AI Advances</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>