Jump to ratings and reviews
Rate this book

Hands-On Large Language Models: Language Understanding and Generation

Rate this book
AI has acquired startling new language capabilities in just the past few years. Driven by rapid advances in deep learning, language AI systems are able to write and understand text better than ever before. This trend is enabling new features, products, and entire industries. With this book, listeners will learn practical tools and concepts they need to use these capabilities today.

You'll understand how to use pretrained large language models for use cases like copywriting and summarization; create semantic search systems that go beyond keyword matching; and use existing libraries and pretrained models for text classification, search, and clusterings.

This book also helps you understand the architecture of Transformer language models that excel at text generation and representation; build advanced LLM pipelines to cluster text documents and explore the topics they cover; build semantic search engines that go beyond keyword search, using methods like dense retrieval and rerankers; explore how generative models can be used, from prompt engineering all the way to retrieval-augmented generation; and gain a deeper understanding of how to train LLMs and optimize them for specific applications using generative model fine-tuning, contrastive fine-tuning, and in-context learning.

Audible Audio

Published September 16, 2025

Loading...
Loading...

About the author

Jay Alammar

6 books15 followers

Ratings & Reviews

What do you think?
Rate this book

Friends & Following

Create a free account to discover what your friends think of this book!

Community Reviews

5 stars
144 (44%)
4 stars
131 (40%)
3 stars
50 (15%)
2 stars
1 (<1%)
1 star
0 (0%)
Displaying 1 - 30 of 38 reviews
Profile Image for Emre Sevinç.
186 reviews456 followers
October 8, 2024
This is an excellent and very up-to-date book for those who want to get up to speed with both open source, as well as proprietary Large Language Model based systems (such as ChatGPT). For those who want to have a more detailed and technical look into the workings of transformer architecture, there is of course "Natural Language Processing with Transformers, Revised Edition", and for those who want to build quick and dirty applications without understanding much of what's going on behind the scenes there is "Developing Apps with GPT-4 and ChatGPT: Build Intelligent Chatbots, Content Generators, and More" and "Prompt Engineering for Generative AI: Future-Proof Inputs for Reliable AI Outputs". But if you want something in between with great explanatory diagrams, up-to-date techniques, and a lot of source code which you can quickly and cheaply run on public GPU-powered notebooks (such as Google Colab) then look no further and dive right into this exciting book!

Needless to say, the field of Large Language Model (LLM) based AI systems is moving at a breakneck speed, and the biggest technology companies are in a cut throat competition to push the state of the art and provide smarter systems at ever decreasing prices, which, in turn, fuels even more research to come up with better systems. Just to give a concrete example, even before I finished the book, I learned about a new development where two researchers from Cornell University developed "Contextual Document Embeddings". At this pace, some parts of the book will probably be outdated in at most a few years, so practitioners that build and integrated LLM-powered AI systems still have some time to put this valuable knowledge into real-life work.

As final remarks, I also appreciate that authors dedicated some chapters to the excellent Sentence Transformers (a.k.a. SBERT) Python library and its practical use-cases, as well as SetFit framework for efficient few-shot learning with Sentence Transformers. I also liked the nod to the venerable spaCy in one of the diagrams! ;)
Profile Image for Regis Hattori.
163 reviews13 followers
January 28, 2025
This book strikes a good balance in how deeply the subject is presented.
It is not as shallow as what we usually see in blog posts, nor as deep as an academic paper. I think this level of detail is ideal for developers and engineering managers who want to gain a better understanding of LLMs without delving too deeply into the mathematics. Additionally, it includes a lot of code examples.

The book also features numerous diagrams that help explain the topics.

However, it has some drawbacks. Not all subjects are well explained. At times, it presents diagrams without further explanation, as if they were self-explanatory—but that is not always the case. Furthermore, the chapter on LLM fine-tuning contains significantly fewer code examples than the others.

Overall, it is a very good book on a topic and at a level of detail that is not well covered by other books. However, there is room for improvement.
Profile Image for Alexandre Mare.
61 reviews1 follower
April 2, 2025
Hands-On Large Language Models by Jay Alammar and Maarten Grootendorst is a very practical and accessible guide for those with a solid background in applied math and some hands-on Python experience. The book stands out for its clear, well-designed diagrams that help demystify key concepts and make learning faster. However, some sections—particularly on image generation—lack clarity and could use more depth. It’s also a bit frustrating that the book doesn’t explore the inner workings of transformers in more detail, especially since Jay Alammar has already created excellent visual content on this topic in his blog. A bonus chapter on advanced techniques like GQA or Mixture of Experts would have been a great addition. Still, I give it 4 stars because it allowed me to progress quickly without diving too deep into GPU or devops topics, which made it very effective for my learning needs.
Profile Image for Lucía.
18 reviews
April 13, 2026
Ni puta gracia leerse esto en un solo día
Profile Image for Joe.
175 reviews6 followers
May 26, 2025
I picked up a copy of this book just before Christmas 2024. Several AI-related YouTube channels I follow had recommended it, and for good reason. This book is exactly what the title says "Hands-On" and is a great follow along way to get up to speed on running and using LLM's. The visual illustrations are stunning - very detailed and rich. One of the best ways to learn about technology is with visual intuitions and this book doesn't disappoint.

Although the book came out in October 2024 (which may seem like a long time ago in AI), it's aged very well and still very relevant. The author shares all of his code on GitHub so you can be assured of updates to the material as advances are made.

I was so inspired by this book that I decided to run an LLM locally on my Macbook. You can read about that in my blog post - https://blog.marketingdatascience.ai/...

So if you want to dabble in the technology and know a little Python, this book is for you. It's not a reference (you can find those online), nor is it a tutorial (you have YouTube for that). It's a great hands-on experience. Just reading about AI doesn't quite make it all sink in, sometimes you have to do AI and that's what this book is for. Enjoy.
Profile Image for brooklyn harden.
57 reviews
July 23, 2025
This is not my typical book, but I dont particularly mind reading about concepts I have little knowledge on to get a better understanding of them.

This definitely was very helpful in understanding what Large Language Models are, and how they are use. I started this book after I read the article that talked about Transformers. The article attempted to break down the complex subject in a way that made it easy for a person who had no knowledge about LLMs and Transformers and what they do and how we initially use them everyday.

This is definitely an interesting book and I would recommend if you're into technology.
Profile Image for Mohit Jain.
27 reviews
May 13, 2025
This book is a must-read for anyone who wants to deeply understand how modern LLMs like GPT, CLIP, and BLIP-2 actually work not just use them.
Profile Image for Vlad Ardelean.
194 reviews36 followers
October 20, 2026
Nice book.

Personal notes, taken while reading:

## 12 Fine-tuning generation models
pre-training
supervised fine-tuning
preference tuning
AI safety goes here
"Parameter efficient transfer learning for NPL" describes "adapters" - algorithms that speed up fine-tuning of models ( https://arxiv.org/abs/1902.00751 )
download adapters from https://adapterhub.ml/

LLM Arena: some site that you can go to, to ask a question to 2 LLMs (without knowing which one). You'll then rank your answers.

Goodheart's law: When a good measure becomes a target, it ceases to be a good measure

preference tuning, alignment: RLHF

reword model: a model that outputs a score, based on another model's inputs&outputs
llama2 uses 2 reward models. One for orrectness, one for safety
Proximal Policy Optimization (PPO)
LoRA = low rank adaptation; PEFT process for creating layers;
DPO Direct Preference Optimization (alternative to PPO)
SFT
ORBO - processes the combined SFT and DPO into 1 training loop


## 11 - fine-tuning representation models
Representation models = models that group things together (good for embeddings)
discriminative models = they make decisions (yes/no; cat/dog)
generative models = those that create text/img/sound/etc

SetFit: framework for efficient training with few training examples
MLM = masked language modeling
named entity recognition

## 10 - creating text-embedding models!!
contrastive learning: similar docs get closer, disimilar get further
sentence-transformers
temperature = applies specifically to loss functions, like softmax: https://www.youtube.com/watch?v=oJU6-... or cosine similarity etc
losses.MultipleNegativesRankingLoss (MNR) -> good for larger batch sizes

Augmented s-bert
TSDAE - a techniques for fine-tuning embeddings models, using unsupervised learning (masks words, asks the embedding model to predict them)
mean pooling
CLS token


hard negatives = examples of sentences that are quite close but completely different;
Example:
q: "How many people live in AMsterdam?"
a: "About 1.000.000 people"
HARD NEGATIVE: "More than 1.000.000 people live in Utrecht, more than in Amsterdam"
An easy negative is typically unrelated to both the question and answer.
A semi-hard negative has some similarities to the topic of the question and answer but is
somewhat unrelated.
A hard negative is very similar to the question but is generally thewrong answer.

## 9 Multimodal LLMs
"an image is worth 16x16 words" (paper)
ViT model for images
CLIP - embeddings for both images and text
BLIP 2 - connects a pre-trained image encoder and pre-trained llm (so u don't need to train your own model). it uses a "querying transformer" (q-former)


## 8 semantic search and rag
google uses BERT for searching
"pretrained transformers for text tanking bert and beyond" for text search (up to 2021)

dense retrieval
reranking

the sequence_transformers library can be used for creating a RAG system (retrieval + reranking) locally
https://oreil.ly/jJOhV -> redirects to: https://www.sbert.net/

mean average precision - a way to calculate precision, for comparing 2 systems

RAG paper: "Retrieval-augmented generation for knowledge-intenssive NLP tasks" (2020)
multi-hop-rag ("what's the difference beetween sales in 2024 and 2025)
query routing (search multiple data sources)
the question is about policies, search the HR data
but if the question is about tasks, search JIRA
Agentic RAG (using tools)
cohere R+ is an open source free model
"Evaluating veriafiability in generative search systems"
Evaluate RAG systems by
fluency
perceived utility
citation recall
citation precision
LLM as a judge
RAGist -> framework for implementing RAG

## ch7, advanced text generation techniques and tools (agents and memory)
"a visual guite to quantization" (martin rutendorst)
quantization = compression of models
use at least 4-bit quantization
.gguf = quantized model
phi-3 requires a specific prompt template
REACT = reasoning + acting = for agents

## prompt engineering
top_p -> a parameter which toggles creativity vs stability. top_p=1 means "use the entire vocabulary for choosing the next potential token; top_p=0.2 = from the most to least probable token, use only as many tokens as you get so when summing their probabilities, you get at most 0.2"
Chain Prompting: Breaking up the Problem

tree of thought ( technique / framework): for reasoning

## Topic modeling with BERTopic



https://www.youtube.com/watch?v=v3SeP...
keybertinspired -> reranks keywords in bert topics (reranks based on representative docs). removes stopwords BUT removes abbreviations (which are sometimes quite important)
Maximal Marginal Relevance -> reranks, removing duplicates

## Chapter 4, Text classification
Fine-tuning a representation model (BERT) for text classification is hard (need lots of compute). General purpose embeddings can be used. So classification = embeddings + classifier (logistic regression)
python packages:
datasets
sentence_transformers

## TOKENIZERS
BPE-Tokenizer = byte-pair encodings (used by gpt)
Word-piece -> used by BERT

Tokenizers are also trained!

Tokenizers can make better use of the context window (fitting more meaning into fewer tokens), and reducing costs.
For Python, especially, tokenizers that group multiple spaces into one token, dramatically decrease the costs

Book: "Designing large language model applications" (apparently discusses tokenizers in great detail)
book: "Natural Language Processing with Transformers (Revised Edition)" (training tokenizers)

There are tokenizers that work for entire phrases
## end tokenizers
https://github.com/HandsOnLLM/Hands-O...
https://rbmediaglobal.com/audiobooks/... -> there you can search for the book and find the bonus material (pdf)
(Working link pointing to the PDF: https://rb-sample-assets.s3.amazonaws... )

Bert is NOT auto-regressive
Transformers are auto-regressive (its output is then fed back again to its input). Bert is a text-representation model, as opposed to text-generation mdel.


attention mechanism, attention head,
projection matrices:
query projection matrix
key projection m.
value projection m.
local vs sparse attention
attention can only look at previous tokens, whereas BERT can look at "both sides" (BERT = Bidirectional blabla)
grouped-query-attention
Transformer paper describes MULTI-HEAD-attention
Grouped-query attention allows us to have fewer attention heads (though more than one - where multi-query-attention uses just 1). Each group of attention heads shares key/value matrices but NOT query matrices
FLASH-shared-attention
Attention: https://www.youtube.com/watch?v=eMlx5...
Let's say we have the words "a fluffy blue creature roamed the verdant forest"
First, each token has its own embedding vector that represents the word in isolation -> E = the embedding vector.
Second, there exists a Wq matrix, learned during training, that says how much each token cares about all of the other ones -> Wq
Third, important, each token ALSO has a vector (smaller-sized one) representing what it could interact with (for instance, looking for nouns, preceeding (well for EN, it's preceding, for RO adjectives would be looking for nouns preceeding)) -> Q = the query = E x Wq
Q is normalized using softmax Q -> exp(Q)/Sum(exp(Q))
Masking: before applying softmax, set the values for tokens N+k to be -infinity when attending to tokens N (So future tokens don't influence current ones). Masking is very important DURING TRAINING, because otherwise, a model could cheat when predicting words, and just look at the next words in the sequence it's supposed to predict, and predict that.
Q is the size of (context size)^2
Fourth, there's also a VALUE matrix, Wv, which is something like "How should we change token N to turn it into token K).



Transformer - the important parts of a transformer are: Feed-forward neural network + Attention layer ; There is also normalization
in 2024+ era transformers, normalization happens before attention, and then, before feed-forward (this reduces training tine). Paper "On layer normalization in the Transformer architecture)

Positional embeddings: ROPE

Packing paper: "efficient sequence packing without self-contamination" (basically, small documents are grouped together when training models with huge context windows. Rotary embeddings allow one to train models using multiple documents in the same window. As such, the model can then use positional information, but also ignore the positions of previous documents.
Profile Image for bimri.
Author 2 books13 followers
February 15, 2025
There's so much to love about this book! The illustrative nature that fortifies one's intuition over the extensive & expansive knowledge base in rapid AI development: is timely & apt! Maestro to Alammar & Grootendorst!
Profile Image for Vajihe Nikkhah.
105 reviews6 followers
March 16, 2025
As a junior in the field of Large Language Models (LLMs), I found this book to be incredibly informative and well-structured. It provided a comprehensive overview of key concepts, including LLM architecture, embeddings, prompt engineering, and fine-tuning. The explanations were clear and accessible, making complex topics easier to grasp for someone still building their foundational knowledge.

What stood out to me was the practical approach the author took, offering actionable insights and examples that helped solidify my understanding.
Profile Image for David Martínez.
19 reviews
February 4, 2026
This book made me more curious about LLM and made me think of it as something complicated in some way, but with some study of the basics and an understanding of the logic, it’s possible to quickly get into this topic. It also made me realize how powerful and useful current LLM tools are for solving business problems.
I picked up this book because I wanted to have a better understanding of large Language models due to their current importance in new technologies and their relevance in solving business problems.
I liked how the author clearly explained how LLMs work and their structure. I also liked the useful tools that the authors mentioned, such as libraries and frameworks for solving problems, fine-tuning, rag, etc. I think these tools will help me a lot to structure solutions to problems.
The only "bad part" of the book is that I struggled with the final section about fine-tuning. I think this topic is relevant and could have been introduced better to improve understanding of the different fine-tuning approaches mentioned by the authors.
If you want to understand how LLMs such as ChatGPT, Claude or Gemini work, or if you have unstructured business data that you want to structure it and think LLMs could be a solution to this problem, this book is a good place to start to understand the basics and determine if it could be an approach to business problems.
Profile Image for Erika RS.
929 reviews277 followers
October 25, 2026
Published a couple years ago, this book isn't going to give you the latest and greatest on LLMs (e.g., decision models like Jev or modern agent harnesses). However, by focusing on the core concepts, it does provide a strong foundation for the underlying ideas on LLMs.

The authors introduce LLMs and their general architecture. They talk about tokens and embeddings. They deep dive on text clustering, topic modeling, and semantic analysis. They talk about prompt engineering, text generation, text+image models, and semantic search. They also talk about fine tuning.

While conceptually valuable, probably the biggest shortcoming of this book from a practitioners perspective is that a lot of the specifics (e.g., on prompt engineering) have been "bitter lessoned" as models have gotten better. That doesn't mean that what the book tells you is wrong so much as that it will need to be modified in practice.

Still, if you're looking for an overview that's straightforward and can provide a good foundation for understanding the more recent advances, it's a reasonable place to start.
Profile Image for katia.
19 reviews1 follower
October 9, 2025
Great high level overview of how LLMs are built, trained and evaluated. The concepts in these book aren’t always the easiest to grasp but the diagrams were helpful in those moments. The book covered various embedding models, the various components of LLMs and how they evolved over time, how LLMs are used (with RAG and prompt engineering) and how LLMs are trained for specific use cases. There were also some code examples to follow throughout the book that seemed useful but I didn’t get chance to try.
Profile Image for Daniel.
2 reviews2 followers
January 15, 2025
I have read quite a few books on data science and machine learning because I teach professional education courses at Eindhoven University of Technology.

This book is currently in the top of the list of standard books that I use in my class. It is well-written, practical and does an excellent job in providing intuitive, visual explanations how large language models work, without having to go all out with linear algebra and intricate math.
6 reviews
January 30, 2025
I liked the balance this book struck between delving into the theory of the models/architectures and their applications. It’s probably the most up to date book on the field of NLP out there right now and it does a good job of getting readers up to speed with the latest applications. My only gripe would be that the last chapter was a little rushed given how important SFT is to making LLM applications work.
3 reviews
August 17, 2025
One of the best books I've read. If you want to understand the basic concepts of LLM and also get hands-on writing and trying out code, look no further. The book is structured to explain the concepts first and then do some hands-on exercises on that specific concept. Almost like a training. Also, the illustrations were simply great and lots of them to ingest the material much better. Worth the investment!
Profile Image for Cairo Cananea.
59 reviews
May 19, 2026
Uma excelente referência quando o assunto é LLM. Os fundamentos são bem explorados e explicados pelos autores. Todos capítulos possuem notebook no Github para rodar localmente e fazer os mais diversos testes.

Essencial para quem quer aprender a resolver problemas com modelos de linguagem sem ficar preso a modelos proprietários, neste livro aprendemos um pouco sobre como configurar e interagir com qualquer modelo (proprietário ou aberto).
Profile Image for Josua Naiborhu.
98 reviews6 followers
January 13, 2025
This book brings so much clarity for many terms about LLM. From the building blocks of transformer and fine-tune tokenizer, embedding, self-attention in Transformer architecture all the way to various real use-cases of utilizing LLM for solving various problems. I really recommend this amazing book. Concise and easy to comprehend.
Profile Image for Ita Cirovic Donev.
12 reviews
March 17, 2025
Very beginner friendly book on the practical use of LLMs in practice. If you have some experience with LLMs and NLP along with some problems on hand this will be a quick guide to get you started. It combines well the overall understanding of the topic and the practical examples via presented Python code. The author use transformers library for their examples.
Profile Image for Afonso.
10 reviews
September 16, 2026
Great book for beginners to the field or simply enthusiasts who want to review the basics of how LLMs work. The writing style is not too dense and the examples and notebooks that accompany the book are clear and understandable. Could warrant a new edition with a few more chapters on the latest developments, but overall a solid recommendation.
4 reviews1 follower
October 11, 2026
I think this book has a good scope and covers important parts of the AI technology stack. However, I often found that it lacked depth on important topics. I needed to consult other resources to understand them well enough for my needs. In the end, the missing explanations were often relatively small, but I still felt the book wasn’t self-contained enough.
Profile Image for Mikhail Filatov.
463 reviews23 followers
January 28, 2025
Illustrations were useful in many cases, but also misleading in some.
Overall, a bit too theoretical with concepts, like LLM fine tuning explained using very “artificial” examples instead of real scenarios.
1 review1 follower
May 22, 2025
focused and concise

Focused, concise and to the point. Good structure. Well chosen subjects. Hope the book will be continue to be updated and expanded to cover more “ground” as “the field evolves”.
Profile Image for Kristoffer Roupé.
43 reviews1 follower
September 17, 2025
Its been a long read. I’ve learned a lot and I think I might come back to this book. I would have gained more knowledge by doing all the examples, but I simply didn’t have the time to prioritize that right now
Profile Image for Noura.
1 review1 follower
December 20, 2025
Enjoyable read, it covers an overview of the basics of natural language processing which I found to be a nice refresher before going through the more recent LLM concepts. I liked that the book covered preference tuning / human alignment in the last chapter.
Profile Image for Alexei Shmidman.
13 reviews1 follower
February 12, 2026
The book gives a good start into the world of LLM. Some chapters have lack of general description for overloaded samples sake, however, this does not prevent of getting the main idea. This book could be recommended for LLM beginners.
641 reviews13 followers
May 25, 2025
A solid book on LLMs that explains what is going on in enough details to understand it while not too deep so that you would need a math degree.
Profile Image for Valeria Luzardo.
37 reviews1 follower
September 23, 2025
This is an excellent introduction to LLMs and how they work. It is a bit technical, but with the accompanying notebooks, non-technical readers like myself can grasp the ideas of this field.
Displaying 1 - 30 of 38 reviews