页面简介
Learn Vibe Coding from Zero to Advanced - Master AI programming with Claude Code, Cursor, and other AI IDE tools
正文摘录
Principles of Large Language Model Operation 💡 Learning Guide: This chapter requires no programming background. Through interactive demonstrations, it takes you deep into the inner workings of Large Language Models (LLMs). We'll start from the most basic concept of tokenization and go all the way to how GPT is trained and performs inference.🤖 LLM First Look: From Chat to Business WorkflowsLarge models are not just chatbots. Try how they handle these practical requests: 💼 Choose a business scenario to begin.🤔Give me a reason to ask for leave🐍Write a Python web scraper🎩Compliment me in a literary tone📊Analyze this sales trend📝Write social copy for this coffee cup0. Introduction: From Human Language to Machine Computation Humans communicate through language; computers compute through numbers. The essence of a Large Language Model (LLM) is a bridge connecting these two worlds.Its core task is singular: transform the problem of "understanding language" into a problem of "mathematical computation."To achieve this goal, we need to solve three core challenges:Translation: How do we turn text into numbers? (Tokenization & Embedding)Efficiency: How do we make computers compute fast? (Matrix operations)Memory: How do we make computers understand context? (The Transformer model)This tutorial will take you from zero, step by step, through the construction of this bridge.1. 分词(Tokenization) A computer cannot read the word "hamburger" — it only understands numbers. So our first task is: break text into the smallest units a computer can process.1.1 Overview of Tokenization Tokenization is the process of splitting a sentence into individual "word units" (Tokens).English: Words are naturally separated by spaces, making tokenization easy (e.g., I love AI).Chinese: There are no spaces, so algorithms are needed to segment the text (e.g., 我爱人工智能).Tokenizer The program that performs tokenization is called a Tokenizer. It acts like an interpreter, responsible for translating human text into sequences of numbers that machines can read.Modern LLMs (such as GPT-4) typically use Subword Tokenization techniques (like the BPE algorithm). The clever part: common words stay intact, rare words get split.Here is a real BPE tokenization example (based on the GPT-4 Tokenizer):Input: "The quick brown fox jumps over the lazy dog. \n今天天气真不错!"Token List:textindex=791, string='The' index=4062, string=' quick' index=14198, string=' brown' index=39935, string=' fox' index=83368, string=' jumps' <-- if split, might be ' jump' + 's' index=927, string=' over' index=279, string=' the' index=16053, string=' lazy' index=3290, string=' dog' index=13, string='.' index=198, string='\n' <-- newline character index=33838, string='今天' <-- common word merged directly index=54580, string='天气' index=20265, string='真' index=57672, string='不错' index=171, string='!'On handling rare characters: If a character not present in the vocabulary is encountered (suppose "今" were very rare), the model falls back to Byte-level encoding.Raw Input: 今Bytes: \xE4 \xBB \x8ABPE Lookup: first look for \xE4\xBB\x8A -> not found -> split into \xE4\xBB (ID=1001) + \x8A (ID=2002).Final Tokens: [1001, 2002].This mechanism guarantees that no matter what characters are input, the model can process them — there is never an OOV (Out Of Vocabulary) problem.Input TextThe quick brown fox jumps over the lazy dog. Today is a nice day!AlgorithmBPE (GPT-4)Word (Legacy)Character (Raw)29Tokens66Characters ⬇ The34049 32quick47501 32brown11702 32fox1583 32jumps37109 32over23444 32the14801 32lazy14548 32dog49644.46 1002Today31793 32is3370 32a97 32nice31085 32day49228!33💡Note: LLMs do not directly process words. They process numbers, called token IDs. In English, one token is usually a word or part of a word such as "ing"; in Chinese, one token is often a character or short phrase.Key point: LLMs process not words, but Token IDs (a sequence of numeric indices).2. The Core Challenge: Approach to making Computers "Compute" Language Our task is to process language. But computers only understand numbers. The most direct idea: assign each word an ID number.apple -> ID 10banana -> ID 202.1 Motivation for Noting Just Use Simple IDs If we only use IDs, the computer would think "10" and "20" are just two unrelated numbers. Moreover, if the vocabulary has 100,000 words, we might need an array of length 100,000 to represent a single word (One-Hot encoding), where 99,999 positions are 0 and only one position is 1.Drawback 1: Too wasteful (sparse — One-Hot arrays are too large).Drawback 2: No semantics (cannot represent that "apple" and "banana" are both fruits).2.2 The Solution: Embedding (Dense Vectors) To represent a word efficiently and meaningfully, we invented Embedding. Instead of using a long 0/1 array, it uses a shorter array filled with decimals (e.g., 512 numbers) to describe a word.For example: [0.8 (is fruit), 0.1 (red), 0.9 (sweet)...] This way, we not only compress the data but also turn word meanings into computable "coordinates."Semantic clustersVector arithmeticWords with similar meaning appear closer together in vector space.3. From Words to Matrices Having solved the problem of representing "a single word," we now need to solve the problem of representing "a sentence."3.1 Motivation for Matricesing Because a sentence contains many words.One word = one row of numbers (a vector).One sentence = many rows of numbers stacked together. This is a matrix.The reason we assemble them into matrices is that the core hardware of modern computers — GPUs (Graphics Cards) — are inherently designed for matrix operations. Only by turning language into matrices can we leverage the parallel processing power of GPUs to achieve efficient inference and training.3.2 The Complete Pipeline Let's review how data flows:Tokenization: Chop the text into pieces.Indexing: Convert pieces into IDs.Embedding: Convert IDs into vectors (for semantics and compression).Stacking: Assemble vectors into matrices (for efficient GPU computation).← Previous Step 1 / 4 Next →Step 1: TokenizationThe computer first splits text into small semantic units called tokens. (This demo simplifies tokenization. Real models often use BPE, so a phrase may become one token.) I love AI3.5 Interlude: What Exactly Overview of a "Model" Before diving into specific architectures, let's understand the term "model" in plain terms.In the AI field, a Model is essentially a super complex function or black box.Input: A bunch of numbers (like the Token IDs above).Processing: Inside the black box are billions of parameters (think of them as billions of adjustable knobs) that perform frenzied addition, subtraction, multiplication, and division on the input data.Output: Another bunch of numbers (representing predictions, such as the probability of the next word).An analogy:You can think of a model as an experienced master chef:Input (ingredients): You give them beef, potatoes, and tomatoes.Model (the chef's brain): Based on the thousands of recipes they've learned (training data), they rapidly compute in their head: dice the beef, peel the potatoes, control the heat...Output (the dish): They serve up a plate of braised beef brisket with potatoes.What we call Training is the process of having this chef start as an apprentice, making mistakes billions of times. If it's too salty, tweak the "salt knob"; if too bland, tweak the "heat knob" — until they can consistently produce delicious dishes.Today's LLMs are "super chefs" who have "read every book in human history" — except what they cook isn't food, but text.4. The Evolutionary Path: From RNN to Transformer With data (Tokens) and a chef (Model) in hand, let's look at how this chef thinks.In AI's evolutionary history, there have been two main "ways of thinking" (architectures): RNN and Transformer.4.1 The Old Clumsy Way: RNN (The Telephone Game) Early models (RNNs, Recurrent Neural Networks) processed a sentence like playing the Telephone Game.How it works:Read word 1, "I", memorize it, pass it to step 2.Read word 2, "love", combine with the previous memory, update the mental note, pass to step 3.Read word 3, "eating", update memory again......until the last word is read.This brings two fatal drawbacks:Slow (no parallelism): You must wait for one person to finish passing the message before the next can begin. You can't have 100 people working at the same time.Forgetful (long-distance forgetting): By the time the message reaches the 100th person, they may have long forgotten whether the first person said "I" or "you." This causes models to lose coherence when writing long passages.4.2 The Modern Genius Design: Transformer (The Roundtable Meeting) In 2017, Google proposed a completely new architecture — the Transformer. It fundamentally changed the rules, turning the "Telephone Game" into a Roundtable Meeting.How it works: The Transformer no longer passes messages one by one; instead, it has all words sit down at the table at once.Bird's-eye view (Parallel Computation): All words enter simultaneously — no queue. Everyone writes their information on paper and lays it out in the middle of the table.Attention Mechanism: This is its killer feature. Every word can directly look at any other word's information on the table. For example, when reading the word "it," the model doesn't need to recall earlier messages — it directly spots "the kitten" earlier in the sentence and instantly understands "it = the kitten."This perfectly solves RNN's pain points:Fast: Everyone reviews materials simultaneously — the GPU can run at full throttle, maximizing efficiency.Never forgets: No matter how long the sentence, the distance between the 1st word and the 10,000th word is just "one step away" — you can look at whoever you want.In summary:RNN: Like navigating a maze, step by step, easy to get lost.Transformer: Like viewing a map from a bird's-eye view — both the start and finish are in sight.Why Do We Still Need "Positional" Informa