📄 Page
1
(This page has no text content)
📄 Page
2
The Practical Guide to Large Language Models Hands-On AI Applications with Hugging Face Transformers Ivan Gridin
📄 Page
3
The Practical Guide to Large Language Models: Hands-On AI Applications with Hugging Face Transformers ISBN-13 (pbk): 979-8-8688-2215-5 ISBN-13 (electronic): 979-8-8688-2216-2 https://doi.org/10.1007/979-8-8688-2216-2 Copyright © 2025 by Ivan Gridin This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed. Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights. While the advice and information in this book are believed to be true and accurate at the date of publication, neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or omissions that may be made. The publisher makes no warranty, express or implied, with respect to the material contained herein. Managing Director, Apress Media LLC: Welmoed Spahr Acquisitions Editor: Celestin Suresh John Editorial Assistant: Gryffin Winkler Cover designed by eStudioCalamar Distributed to the book trade worldwide by Springer Science+Business Media New York, 1 New York Plaza, New York, NY 10004. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail orders-ny@springer-sbm.com, or visit www.springeronline.com. Apress Media, LLC is a Delaware LLC and the sole member (owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation. For information on translations, please e-mail booktranslations@springernature.com; for reprint, paperback, or audio rights, please e-mail bookpermissions@springernature.com. Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook versions and licenses are also available for most titles. For more information, reference our Print and eBook Bulk Sales web page at http://www.apress.com/bulk-sales. Any source code or other supplementary material referenced by the author in this book is available to readers on GitHub https://github.com/Apress/The-Practical-Guide-to-Large-Language-Models. For more detailed information, please visit https://www.apress.com/gp/services/source-code. If disposing of this product, please recycle the paper Ivan Gridin Vilnius, Lithuania
📄 Page
4
To my beautiful wife, Tamara
📄 Page
5
v Table of Contents About the Author ����������������������������������������������������������������������������������������������������� xi About the Technical Reviewer ������������������������������������������������������������������������������� xiii Introduction �������������������������������������������������������������������������������������������������������������xv Part I: LLM Basics ������������������������������������������������������������������������������������������� 1 Chapter 1: Discovering Transformers ����������������������������������������������������������������������� 3 What Is a Large Language Model? ������������������������������������������������������������������������������������������������ 4 About Hugging Face ���������������������������������������������������������������������������������������������������������������������� 5 Setting Up the Environment ���������������������������������������������������������������������������������������������������������� 6 Python ������������������������������������������������������������������������������������������������������������������������������������� 6 PyTorch ������������������������������������������������������������������������������������������������������������������������������������ 6 Transformers ��������������������������������������������������������������������������������������������������������������������������� 7 Disk Size ���������������������������������������������������������������������������������������������������������������������������������� 8 CUDA ���������������������������������������������������������������������������������������������������������������������������������������� 8 Source Code ���������������������������������������������������������������������������������������������������������������������������� 9 Quick Intro to Transformers����������������������������������������������������������������������������������������������������������� 9 Exploring Common NLP Tasks ����������������������������������������������������������������������������������������������������� 11 Zero-Shot Classification �������������������������������������������������������������������������������������������������������� 12 Summarization ���������������������������������������������������������������������������������������������������������������������� 14 Translation ����������������������������������������������������������������������������������������������������������������������������� 16 Text Generation ���������������������������������������������������������������������������������������������������������������������� 17 Question Answering ��������������������������������������������������������������������������������������������������������������� 20 Feature Extraction ����������������������������������������������������������������������������������������������������������������� 25 Fill-Mask �������������������������������������������������������������������������������������������������������������������������������� 30 Token Classification ��������������������������������������������������������������������������������������������������������������� 32 Text Classification ������������������������������������������������������������������������������������������������������������������ 33
📄 Page
6
vi Surfing the Hugging Face Website ���������������������������������������������������������������������������������������������� 39 Project: Building a Simple LLM Chat Application ������������������������������������������������������������������������ 47 Summary������������������������������������������������������������������������������������������������������������������������������������� 55 Chapter 2: LLM Internals and Evaluation ���������������������������������������������������������������� 57 Overview of Large Language Models ������������������������������������������������������������������������������������������ 57 ELMo �������������������������������������������������������������������������������������������������������������������������������������� 58 GPT (Generative Pretrained Transformer) ������������������������������������������������������������������������������ 59 BERT (Bidirectional Encoder Representations from Transformers) ��������������������������������������� 59 GPT-2 ������������������������������������������������������������������������������������������������������������������������������������� 60 RoBERTa (Robustly Optimized BERT Pretraining Approach) �������������������������������������������������� 60 T5 (Text-to-Text Transfer Transformer) ���������������������������������������������������������������������������������� 60 GPT-3 ������������������������������������������������������������������������������������������������������������������������������������� 61 Jurassic-1 (AI21 Labs) ����������������������������������������������������������������������������������������������������������� 61 Megatron-Turing NLG (MT-NLG) ��������������������������������������������������������������������������������������������� 62 LLaMA (Meta) ������������������������������������������������������������������������������������������������������������������������ 62 Qwen (Alibaba Cloud) ������������������������������������������������������������������������������������������������������������ 62 DeepSeek ������������������������������������������������������������������������������������������������������������������������������ 63 Models, Tokenizers, and Pipelines Explained ������������������������������������������������������������������������������ 63 Model, Architecture, and Checkpoint ������������������������������������������������������������������������������������������ 70 Running an LLM on a Server ������������������������������������������������������������������������������������������������������� 75 VRAM/RAM ���������������������������������������������������������������������������������������������������������������������������� 75 Quantization �������������������������������������������������������������������������������������������������������������������������� 76 LLM Comparison ������������������������������������������������������������������������������������������������������������������������� 83 Dataset ���������������������������������������������������������������������������������������������������������������������������������� 84 Judge ������������������������������������������������������������������������������������������������������������������������������������� 87 Leaderboards ������������������������������������������������������������������������������������������������������������������������������ 90 Project: Select the Best Model for a Specific Task ���������������������������������������������������������������������� 90 Summary������������������������������������������������������������������������������������������������������������������������������������� 92 Table of ConTenTs
📄 Page
7
vii Chapter 3: Improving Chat Model Responses ��������������������������������������������������������� 93 How Language Models Generate Text ����������������������������������������������������������������������������������������� 93 Base and Instruction-Tuned (Chat) Models ��������������������������������������������������������������������������������� 98 Chatting with an LLM ���������������������������������������������������������������������������������������������������������������� 100 add_generation_prompt ������������������������������������������������������������������������������������������������������ 101 continue_final_message ����������������������������������������������������������������������������������������������������� 104 Text Generation Recipes ����������������������������������������������������������������������������������������������������������� 106 Few-Shot Prompting������������������������������������������������������������������������������������������������������������ 106 Selecting the Best Response Using the Judge Approach ���������������������������������������������������� 109 Excluding Banned Words ����������������������������������������������������������������������������������������������������� 112 Stopping Criteria ������������������������������������������������������������������������������������������������������������������ 114 Structured Output ��������������������������������������������������������������������������������������������������������������������� 116 Gradio ���������������������������������������������������������������������������������������������������������������������������������������� 120 Project: Interactive Data Mining App ����������������������������������������������������������������������������������������� 126 Summary����������������������������������������������������������������������������������������������������������������������������������� 130 Part II: Empowering LLM Applications with RAG and Agents ��������������������� 131 Chapter 4: Enriching the Model’s Knowledge with Retrieval-Augmented Generation ������������������������������������������������������������������������������������������������������������ 133 What Is the Context and How Does It Help? ������������������������������������������������������������������������������ 134 Context Size and Document Split ���������������������������������������������������������������������������������������������� 137 How to Choose the Best Context ����������������������������������������������������������������������������������������������� 142 Building a RAG Engine �������������������������������������������������������������������������������������������������������������� 144 LangChain ��������������������������������������������������������������������������������������������������������������������������������� 151 LangChain Loaders ������������������������������������������������������������������������������������������������������������������� 152 LangChain Splitters ������������������������������������������������������������������������������������������������������������������� 155 LangChain Embeddings and Vector Store ��������������������������������������������������������������������������������� 161 Project: Hugging Face Model Mentor Assistant ������������������������������������������������������������������������ 162 Summary����������������������������������������������������������������������������������������������������������������������������������� 173 Table of ConTenTs
📄 Page
8
viii Chapter 5: Building Agent Systems ���������������������������������������������������������������������� 175 Levels of LLM Involvement in Program Control������������������������������������������������������������������������� 175 Simple Processor����������������������������������������������������������������������������������������������������������������� 176 Router ���������������������������������������������������������������������������������������������������������������������������������� 176 Tool Calling �������������������������������������������������������������������������������������������������������������������������� 180 Multi-step Agent ������������������������������������������������������������������������������������������������������������������ 182 Multi-agent �������������������������������������������������������������������������������������������������������������������������� 183 Code Agents ������������������������������������������������������������������������������������������������������������������������� 187 Hugging Face API ���������������������������������������������������������������������������������������������������������������������� 190 ReAct Framework ��������������������������������������������������������������������������������������������������������������������� 192 Smolagents ������������������������������������������������������������������������������������������������������������������������������� 193 Code Agent �������������������������������������������������������������������������������������������������������������������������� 197 Tool �������������������������������������������������������������������������������������������������������������������������������������� 198 Executor ������������������������������������������������������������������������������������������������������������������������������ 199 Prompt ��������������������������������������������������������������������������������������������������������������������������������� 200 Memory ������������������������������������������������������������������������������������������������������������������������������� 201 Execution Errors ������������������������������������������������������������������������������������������������������������������ 202 Planning Step ���������������������������������������������������������������������������������������������������������������������� 203 Final Answer Checks ����������������������������������������������������������������������������������������������������������� 204 Interactive Execution ����������������������������������������������������������������������������������������������������������� 206 Project: Human Resources Agent ���������������������������������������������������������������������������������������������� 207 Summary����������������������������������������������������������������������������������������������������������������������������������� 223 Part III: LLM Advances �������������������������������������������������������������������������������� 225 Chapter 6: Mastering Model Training ������������������������������������������������������������������� 227 Fine-Tuning vs� Training from Scratch �������������������������������������������������������������������������������������� 227 Your First Fine-Tuned Model ����������������������������������������������������������������������������������������������������� 230 Fine-Tuning vs� RAG ������������������������������������������������������������������������������������������������������������������ 238 Managing Datasets ������������������������������������������������������������������������������������������������������������������� 242 Table of ConTenTs
📄 Page
9
ix Hugging Face Datasets �������������������������������������������������������������������������������������������������������� 242 Dataset Library �������������������������������������������������������������������������������������������������������������������� 245 Custom Dataset ������������������������������������������������������������������������������������������������������������������� 247 Hugging Face Training �������������������������������������������������������������������������������������������������������������� 249 Training with TensorBoard �������������������������������������������������������������������������������������������������������� 253 Fine-Tuning for Multi-class Classification ��������������������������������������������������������������������������������� 254 Causal Language Model Training ���������������������������������������������������������������������������������������������� 268 Domain Adaptive Pretraining ���������������������������������������������������������������������������������������������������� 270 Supervised Fine-Tuning ������������������������������������������������������������������������������������������������������������ 278 Project: Ancient Rome AI Assistant ������������������������������������������������������������������������������������������� 288 Summary����������������������������������������������������������������������������������������������������������������������������������� 293 Chapter 7: Unpacking the Transformer Architecture �������������������������������������������� 295 What Is the Architecture of a Neural Network? ������������������������������������������������������������������������� 295 It All Started with attention ������������������������������������������������������������������������������������������������������� 302 Embeddings ������������������������������������������������������������������������������������������������������������������������������ 304 Intuition Behind the attention Mechanism �������������������������������������������������������������������������������� 307 Positional Encoding ������������������������������������������������������������������������������������������������������������������� 313 How Transformer Works ������������������������������������������������������������������������������������������������������������ 320 Project: Transformer from Scratch �������������������������������������������������������������������������������������������� 323 Summary����������������������������������������������������������������������������������������������������������������������������������� 347 Index ��������������������������������������������������������������������������������������������������������������������� 349 Table of ConTenTs
📄 Page
10
xi About the Author Ivan Gridin is an artificial intelligence expert, researcher, and author with extensive experience in applying advanced machine learning techniques in real-world scenarios. His expertise includes natural language processing (NLP), predictive time series modeling, automated machine learning (AutoML), reinforcement learning, and neural architecture search. He also has a strong foundation in mathematics, including stochastic processes, probability theory, optimization, and deep learning. In recent years, he has become a specialist in open source large language models, including the Hugging Face framework. Building on this expertise, he continues to advance his work in developing intelligent, real-world applications powered by natural language processing. He is a loving husband and father and collector of old math books. You can learn more about him on LinkedIn: https://www.linkedin.com/in/ survex/.
📄 Page
11
xiii About the Technical Reviewer Shibsankar Das is currently working as a senior data scientist at Microsoft. He has 10+ years of experience working in IT where he has led several Data Science initiatives, and in 2019, he was recognized as one of the top 40 Data Scientists in India. His core strength is in GenAI, Deep Learning, NLP, and Graph Neural Networks. Currently, he is focusing on his research on AI Agents and Knowledge Graphs. He has experience working in the domain of Foundational Research, FinTech, and ecommerce. Before Microsoft, he worked at Optum, Walmart, Envestnet, Microsoft Research, and Capgemini. He pursued a master’s from the Indian Institute of Technology, Bangalore.
📄 Page
12
xv Introduction Artificial intelligence (AI) is transforming the modern world faster than almost any other invention in human history. When OpenAI released ChatGPT in November 2022, it marked a turning point that revealed the potential of large language models (LLMs) for a wide range of real-world applications. Since then, public interest in LLMs and their capabilities has continued to grow, driving new research and exploration across the field. Vision for openness began to take shape once the drawbacks of closed commercial systems, such as ChatGPT, became impossible to ignore. Engineers, scientists, and independent developers across the world started working together with a shared belief that knowledge should be accessible and transparent. Sharing insights, they formed an open source community that thrived on creativity rather than competition. New models like DeepSeek soon showed that open collaboration could achieve results equal to, and sometimes greater than, what closed proprietary systems had accomplished. As this philosophy spread, openness itself became one of the defining forces shaping the next era of artificial intelligence. Most books on LLMs open with complex theoretical material and only later move toward practical work. This book takes a different approach. We begin with concrete examples and hands-on experience using open source LLMs, uncovering the ideas and mechanisms that lie beneath LLMs. The goal is to make the topic clear, demonstrating that large language models are not mysterious black boxes but understandable tools that anyone can learn to use. Chapter 1 introduces the Transformers library by Hugging Face, one of the most popular tools for working with open source large language models (LLMs). We’ll explore how to set up the necessary environment for LLM-based development and walk through hands-on examples covering the most common natural language processing (NLP) tasks. By the end of the chapter, we’ll build a simple chatbot application powered by an LLM that can respond to user questions. In Chapter 2, we’ll dive deeper into the inner workings of LLMs. We’ll discuss the nuances of running LLMs on a server and learn how to compare popular models in terms of efficiency and computational requirements.
📄 Page
13
xvi The chapter finishes with a practical project focused on selecting the best- performing model for a specific real-world task. Chapter 3 takes a closer look at how LLMs actually generate text. We’ll examine the difference between base and fine-tuned (instruction) models and learn how to engage in meaningful conversations with LLMs. You’ll also explore various text generation strategies and learn how to obtain structured output from models. At the end, we’ll develop an interactive data mining application using Gradio and an LLM. In Chapter 4, we’ll explore the concept of Retrieval-Augmented Generation (RAG), an approach that allows LLMs to access up-to-date information from external sources. We’ll discuss the idea of context and how to correctly retrieve information from a knowledge base to guide LLM reasoning. By the end of this chapter, we’ll build an intelligent Hugging Face assistant capable of answering questions using real-time documentation data. Chapter 5 shifts the focus to how LLMs can be used for automation and programmatic control. We’ll explore the Smolagents library, which implements the concept of LLM-based agents. This agent-based approach enables the creation of intelligent assistants that can perform complex tasks through interaction with users and external systems. The chapter terminates with the development of a human resources (HR)–focused agent that assists in recruitment. In Chapter 6, we’ll examine the process of LLM fine-tuning on domain-specific data. Fine-tuning allows LLMs to adapt to specialized tasks and significantly enhances their performance. Using this approach, readers will learn how to create their own customized models tailored to particular needs. By the end, we’ll fine-tune a pretrained LLM to build an AI assistant on Ancient Rome, trained on historical datasets. Finally, Chapter 7 takes us deep into the architecture of LLMs, uncovering how transformers actually work. We’ll thoroughly analyze the attention mechanism, the core principle that enables modern LLMs to process and understand natural language so effectively. The chapter concludes with a project in which we build a transformer from scratch to learn its internal logic. This book provides a practical guide to working with open source large language models using the Hugging Face Transformers library. It combines hands-on projects with essential theory, helping readers quickly gain confidence and understand how a modern LLM works. The book is designed for developers, researchers, and data scientists who want not only to apply LLMs in real-world tasks but also to understand the principles that make these models work. It assumes intermediate Python skills and a basic understanding of machine learning (ML) concepts. InTroduCTIon
📄 Page
14
3 © Ivan Gridin 2025 I. Gridin, The Practical Guide to Large Language Models, https://doi.org/10.1007/979-8-8688-2216-2_1 CHAPTER 1 Discovering Transformers In recent years, there has been a significant surge in the efficiency of artificial intelligence models. Video generators create clips that are difficult to distinguish from actual footage, image generation services produce logos better than professional designers, and chatbots based on large language models have completely revolutionized people’s attitudes toward AI. Needless to say, the release of OpenAI’s ChatGPT had a tremendous impact on the market. Many people were shocked by the capabilities of this model and began using ChatGPT for everyday tasks, while professionals started delegating their work to this service. At the time of writing this book, the artificial intelligence industry is still rapidly evolving. People continue to debate about the ethics of using certain models for specific tasks, and there is a widespread fear that many professions may soon disappear as they become completely replaced by artificial intelligence models. For some time, ChatGPT dominated the market. The ChatGPT model is closed source, which significantly affected researchers, scientists, and developers as a whole. However, through the efforts of many large companies, a powerful open source ecosystem for machine learning model development was created. Initially, all open source models were significantly inferior to proprietary commercial models like ChatGPT. Still, the advantage of open source development is that the efforts of different scientists and developers allow them to build on each other’s work. There is no need to go through the same path that someone else has already taken; instead, it is possible to make a small breakthrough starting from the previous point. All these collaborative efforts led to the emergence of a powerful open source model like DeepSeek, which in January 2025 caused the stock prices of many IT companies to plummet. Here, I would like to quote Yann LeCun, one of the pioneers of practical machine learning: “Thanks to the power of open source, AI is not a zero-sum game. When innovations are open-sourced and published openly, progress accelerates for everyone.”
📄 Page
15
4 In this book, we will discuss the open source ecosystem of Hugging Face and the transformers library for large language models, allowing users to leverage the work of thousands of scientists and developers while creating something of their own. Many authors of books dedicated to language models take a theory-first approach before moving on to practice. Since the mathematical theory of language models is quite complex, an unprepared reader may find it difficult to reach the practical application stage. In this book, we will take a different approach. We will move from practice to theory. First, we will explore various practical aspects of applying language models, and only then will we move on to studying theoretical concepts, which undoubtedly also significantly contribute to practical work. In this chapter, the reader is introduced to the transformers library and the Hugging Face ecosystem and immediately begins working on practical natural language processing tasks without the need to delve deep into theory. This chapter aims to give users confidence and eliminate any fear of language models, especially if they are working with them for the first time. The chapter concludes with a hands-on project involving the development of a simple yet immensely powerful chatbot. What Is a Large Language Model? Many different practical tasks are solved using various neural network architectures: computer vision, audio processing, image generation, natural language processing, and many others. This book is dedicated to natural language processing (NLP) tasks that can be effectively addressed with the help of large language models (LLMs). In essence, different LLMs are capable of solving a broad spectrum of problems related to text comprehension, transformation, and generation. The use of these models has become so universal that they now cover the overwhelming majority of practical applications for diverse categories of users. A large language model (LLM) can be defined as a class of advanced artificial intelligence systems designed to interpret, process, and produce human-like text. Such models are trained on massive amounts of textual resources, including books, scientific articles, and digital content, which enables them to acquire knowledge of grammar, facts, reasoning strategies, and linguistic patterns. The impressive efficiency of these models is achieved through original mathematical solutions embedded within them, as well as their training on massive amounts of textual data. Chapter 1 DisCovering transformers
📄 Page
16
5 The term “large” emphasizes that these models are large in terms of deep learning architecture, meaning they contain a vast number of weights. At the time of writing this book, many LLMs consist of tens or even hundreds of billions of parameters, allowing them to extract highly complex semantic structures from unstructured text. A significant portion of the information surrounding us is presented in text form. Text is how we express our thoughts, tell stories, and communicate, which is why LLMs are used in a wide variety of fields: text generation (stories, reports), sentiment analysis (analyzing review tone, spam filters, etc.), text translation into other languages, and more. Recently, breakthroughs have been made in the development of LLMs capable of generating highly meaningful mathematical reasoning, making them valuable scientific assistants. In addition, LLMs are extremely useful when it comes to searching for specific information within large textual documents, where the traditional CTRL+F search method is ineffective. LLM-based assistants have become indispensable tools in fields such as programming, law, economics, medicine, and many others. About Hugging Face Over time, developers of language models quickly realized that the quality of a model strongly depends on the size of the training dataset, which led to an increase in the number of parameters (neural network weights). Of course, architectural and mathematical solutions still played an important role, but the number of parameters in a neural network became a cornerstone for creating an effective language model. As training datasets grew, so did the computational costs of training language models. The training process began to take weeks and months, and the number of parameters increased from millions (DistilBERT—https://huggingface.co/distilbert/distilbert-base-uncased, 67 million parameters) to hundreds of billions (DeepSeek-R1—https://huggingface.co/ deepseek-ai/DeepSeek-R1, 685 billion parameters). The scientific community quickly realized that the only way to achieve progress in this field was to work together and build on the efforts of previous developers to create new models, which could, in turn, serve as the foundation for future innovations. This led to the rapid emergence of specific standards in AI open source development, which resulted in the creation of the transformers library and the Hugging Face ecosystem. Chapter 1 DisCovering transformers
📄 Page
17
6 Hugging Face is a platform designed to make using existing machine learning models as easy as possible for both professional researchers and practical developers who simply want to integrate existing models into their solutions. De facto, Hugging Face is already a standard platform for sharing and developing open source machine learning models, just as Arxiv (https://arxiv.org/) is a crucial platform for publishing scientific papers. Note on many websites, official documentation, and articles, hugging face is represented by the emoji . i do not find this designation convenient, and in this book, i will refer to hugging face using letters. however, remember that you may encounter this emoji in articles related to LLms, where it will refer to the hugging face platform. Setting Up the Environment Correctly setting up the development environment is an important aspect of working with LLMs in practice. Please pay close attention to this section. Python We will work with Python >= 3.10.14 in this book. To install Python, please refer to the official documentation: https://www.python.org/. PyTorch PyTorch is better suited for working with open source models on Hugging Face than any other machine learning framework. There are several reasons for this: • Native Support: Hugging Face primarily develops its libraries (Transformers, Accelerate, PEFT) with PyTorch as a priority, ensuring better integration and ease of use. • Flexibility and Ease of Debugging: PyTorch uses dynamic computation graphs (eager execution), which simplifies research experiments and debugging compared with static graphs in TensorFlow. Chapter 1 DisCovering transformers
📄 Page
18
7 • More Active Community: In the open source domain, PyTorch has gained widespread adoption, especially among researchers and ML engineers, leading to more models, repositories, and various solutions. • Compatibility with Accelerators: Graphics processing unit (GPU) support and CUDA integration are simpler in PyTorch, and acceleration tools (such as FlashAttention and DeepSpeed) work more efficiently. • Extensive Model Support: Most models on Hugging Face are initially developed for PyTorch and later adapted for other frameworks. Here, we will be using PyTorch version 2.7.0 or higher. To install PyTorch, please refer to the official documentation: https://pytorch.org/. Transformers This book’s key components are the Transformers library and related Hugging Face libraries. They can be installed as follows: In this book, we will use the following Hugging Face library versions: • transformers == 4.56.2 • datasets == 4.1.1 • accelerate == 1.10.1 • evaluate == 0.4.3 • tokenizers == 0.22.1 • sentencepiece == 0.2.1 • sacremoses == 0.1.1 To install them, run the following commands: pip install transformers==4.56.2 pip install datasets==4.1.1 pip install accelerate==1.10.1 pip install evaluate==0.4.3 Chapter 1 DisCovering transformers
📄 Page
19
8 pip install tokenizers==0.22.1 pip install sentencepiece==0.2.1 pip install sacremoses==0.1.1 Disk Size As mentioned in the previous section, language models can sometimes reach enormous sizes. When a specific model is requested for the first time, the Transformers framework downloads the model if it has not already been stored locally. Some models can be tens of gigabytes in size. Specific scenarios in this book will require using multiple models simultaneously. Therefore, to be comfortable working with models and datasets, I recommend having at least 100GB of free space on the local machine where you will run the scripts. CUDA The rapid growth of deep learning models over the past decade is directly linked to increasing computational power, particularly with the active development of graphics processing units (GPUs). The speed of LLMs can be tens or even hundreds of times faster when executed using a GPU. Having a GPU on your local machine is not a strict requirement, but I strongly recommend using a GPU with at least 4GB of memory. This will significantly accelerate model execution on your local machine and make the workflow much more comfortable. Some sections of this book will assume the presence of a GPU on your local machine. In such cases, I will display the specifications of the GPU used for executing specific scenarios, as shown below. Please check whether a CUDA device is currently available on your local machine using the following script: import torch if torch.cuda.is_available(): print("CUDA is available!") else: print("CUDA is not available.") Chapter 1 DisCovering transformers
📄 Page
20
9 If a CUDA device is unavailable, this is not a critical blocker to further study. However, I encourage readers to improve their development environment to enable CUDA support. You can refer to the official documentation, which explains how to install CUDA on a local machine: https://docs.nvidia.com/cuda/index.html. The installation and configuration of CUDA are beyond the scope of this book. The practical setup process may vary depending on the user’s operating system and other factors. Pay close attention to this section to make further study and practical experiments faster and more efficient. Source Code Since this book is a practical guide, we’ll be working extensively with code. Therefore, make sure to download the source code that accompanies this book: https://github. com/Apress/The-Practical-Guide-to-Large-Language-Models. You can also refer to the deps.txt file in the source code to install all the necessary dependencies used throughout this book. Quick Intro to Transformers Let’s get started with the classic Hello World scenario. We will look at an example of a classifier that determines the sentiment of a given text as either POSITIVE or NEGATIVE, a task commonly referred to as sentiment analysis. A sentiment analysis model is designed to extract the emotional tone of a text, usually classifying it as POSITIVE or NEGATIVE. Figure 1-1 illustrates the concept of a sentiment analysis model. Chapter 1 DisCovering transformers