A understanding on LLM with Python code

An LLM, or Large Language Model, is a type of artificial intelligence (AI) that is trained on vast amounts of text data to understand and generate human-like language. Think of it as a highly advanced autocomplete system that can predict the next word in a sentence with incredible accuracy, enabling it to perform a wide range of language-based tasks.

At its core, an LLM is a complex neural network, which is a computing system inspired by the human brain. This network has a massive number of parameters, sometimes in the billions, which are adjusted during a training process. This training involves feeding the model enormous datasets of text and code from the internet and digital books. Through this process, the LLM learns the patterns, grammar, context, and nuances of human language.


How LLMs Work: The Transformer Architecture

The key technology behind most modern LLMs is the transformer architecture. This design, introduced by Google in 2017, allows the model to weigh the importance of different words in a sentence when processing it. This “attention mechanism” enables the model to understand the context and relationships between words, even if they are far apart in a text. This is a significant improvement over older models that processed text sequentially.

For example, in the sentence, “The cat, which was on the roof, chased the mouse,” a transformer-based LLM can understand that “the cat” is the one doing the chasing, even though the phrase “which was on the roof” separates the subject from the verb.


Common Applications of LLMs

The ability of LLMs to understand and generate natural language has led to a wide array of applications, including:

  • Content Creation: Writing emails, articles, social media posts, and even creative fiction.
  • Summarization: Condensing long documents or articles into key points.
  • Translation: Translating text between different languages with increasing accuracy.
  • Chatbots and Virtual Assistants: Powering conversational AI like customer service bots and personal assistants.
  • Code Generation: Assisting programmers by writing or suggesting code in various programming languages.
  • Question Answering: Providing direct answers to questions by searching and synthesizing information from its training data.

Prominent Examples of LLMs

You have likely already interacted with or heard of several prominent LLMs. Some of the most well-known examples include:

  • GPT (Generative Pre-trained Transformer) series: Developed by OpenAI, with models like GPT-3 and GPT-4 powering applications such as ChatGPT.
  • Gemini: Google’s family of multimodal models capable of understanding and processing text, code, images, and video.
  • Llama (Large Language Model Meta AI): A series of open-source models released by Meta (formerly Facebook).
  • Claude: A family of models developed by Anthropic with a focus on AI safety.

In essence, Large Language Models represent a significant leap forward in artificial intelligence, enabling more natural and sophisticated interactions between humans and computers. They are a versatile technology with the potential to transform numerous industries and aspects of daily life.

Key Concepts

ConceptDescription
TransformerA neural network architecture that enables efficient language modeling
TokensWords or parts of words; LLMs process text as sequences of tokens
ParametersThe “knobs” of the model; GPT-4, for example, has hundreds of billions
Pre-trainingLearning general language patterns from a massive dataset
Fine-tuningAdditional training for specific tasks or domains
InferenceUsing the trained model to generate or process language

Here are more detailed explanations of the key concepts you’ve listed, which are fundamental to understanding how Large Language Models (LLMs) work:

Transformer

A Transformer is a revolutionary neural network architecture that has become the foundation for most modern and powerful Large Language Models, including the likes of GPT-4 and Google’s Gemini. Introduced by Google in 2017, its key innovation is the “attention mechanism.” This allows the model to weigh the importance of different words (tokens) within an input text. Unlike older models that processed text sequentially, a Transformer can process all tokens at once and dynamically determine which words are most relevant to each other, regardless of their position in the sequence. This ability to understand long-range dependencies and context is what enables LLMs to grasp nuance, handle complex sentences, and generate highly coherent and contextually relevant text.

Tokens

In the realm of LLMs, tokens are the fundamental units of text that the model processes. While we think in terms of words, an LLM breaks down text into a sequence of these tokens. A token can be a whole word (e.g., “apple”), a part of a word (e.g., “un-“, “friend-“, “-ly”), or even just a single character or punctuation mark. For example, the sentence “LLMs are fascinating!” might be broken down into tokens like ["LLMs", "are", "fascinat", "ing", "!"]. This process, called tokenization, allows the model to handle a vast vocabulary and understand grammatical structures more flexibly than if it were limited to whole words alone. The model then performs mathematical operations on these sequences of tokens to understand and generate language.

Parameters

Parameters are the internal variables or “knobs” that a neural network learns from data during its training phase. In an LLM, these parameters are the weights and biases within the vast network of interconnected nodes. The number of parameters is often used as a rough measure of a model’s size and potential power; for instance, models like GPT-4 are described as having hundreds of billions of parameters. During pre-training, these parameters are adjusted over and over again as the model learns to predict the next token in a sentence. The final values of these parameters store the “knowledge” the model has acquired about language, including grammar, facts, reasoning abilities, and stylistic nuances.

Pre-training

Pre-training is the initial, foundational, and most resource-intensive stage of building an LLM. During this phase, the model is exposed to an enormous and diverse dataset of text and code, often scraped from the internet and digitized books. The goal is not to teach it any specific task, but for it to learn the general patterns, structures, and statistical relationships of human language. This is typically done through a self-supervised learning objective, such as predicting the next word in a sentence or filling in missing words. This unsupervised pre-training is what imbues the model with its broad, general-purpose understanding of the world and language, forming the base upon which more specific abilities can be built.

Fine-tuning

Fine-tuning is a secondary training process that adapts a pre-trained LLM for a specific task or to follow instructions in a particular style. After the general-purpose pre-training is complete, developers take the base model and train it further on a smaller, more specialized dataset. For example, a pre-trained model can be fine-tuned on a dataset of question-and-answer pairs to become a better conversational agent, or on a collection of medical texts to improve its expertise in that domain. Fine-tuning is what tailors the broad capabilities of the pre-trained model, making it more accurate and reliable for specific applications like customer service bots, code generation assistants, or content summarizers.

Inference

Inference is the process of actually using the trained and fine-tuned LLM to perform a task. When you give a prompt to an LLM (like asking a question or giving a command), the model is performing inference. It takes your input text, converts it to tokens, and processes it through its neural network using the learned parameters to generate a response, one token at a time. This is the “live” or operational phase where the model applies its stored knowledge to generate text, translate languages, summarize documents, or answer questions. Unlike training, which is about learning, inference is about applying that learning to produce a useful output.

Overview: What is a Transformer?

The Transformer is a deep learning model architecture introduced by Google in the 2017 paper “Attention is All You Need”. It was revolutionary because it removed the need for recurrence (used in RNNs) and replaced it with something more powerful: self-attention.

It’s designed to understand the relationship between words in a sentence, no matter how far apart they are.


⚙️ Main Components of the Transformer

The Transformer has two main parts:

1. Encoder – Understands the input sentence

2. Decoder – Generates output (used in tasks like translation or text generation)

In models like GPT, only the decoder is used (for generation). In BERT, only the encoder is used (for understanding).

Let’s focus on the core building blocks of both:


🔩 Building Blocks of Transformer

1. Embedding Layer

  • Converts words into vectors (high-dimensional numbers).
  • Each word/token becomes a dense numerical representation that captures meaning.

2. Positional Encoding

  • Since transformers don’t have loops (like RNNs), they need a way to know the position of words in a sentence.
  • Positional encoding adds information like “this word is first,” “this word is second,” etc., to the embeddings.

3. Self-Attention (Scaled Dot-Product Attention)

This is the heart of the transformer.

It lets the model “pay attention” to different words in the sentence to understand context.

📌 Example:

In the sentence:

“The cat sat on the mat because it was tired.”

The word “it” refers to “the cat.”
Self-attention helps the model figure this out.

🔢 How does it work?

Each word is transformed into:

  • Query (Q)
  • Key (K)
  • Value (V)

The model computes how relevant other words are by calculating: Attention Score=Q⋅KTdk\text{Attention Score} = \frac{Q \cdot K^T}{\sqrt{d_k}}Attention Score=dk​​Q⋅KT​

Then it uses these scores to weigh the Values (V) and combine them into a new representation of the word.

This happens in parallel for all words.


4. Multi-Head Attention

Instead of using one set of Q, K, and V, the model uses multiple heads (like multiple attention mechanisms) to focus on different parts of the sentence simultaneously.

This allows the model to understand:

  • Syntax
  • Semantics
  • Relationships between words
    …all at once.

5. Feed-Forward Neural Network

After attention, each word’s vector goes through a regular fully connected neural network (same for each position).

6. Layer Normalization & Residual Connections

  • Residuals: Help prevent information loss (like adding a shortcut).
  • Layer norm: Helps with training stability and speed.

🔁 Stacking Layers

Transformers are deep. GPT-4 or BERT-base has many layers of the above blocks (e.g., 12, 24, or even 96+).
Each layer makes the model understand the text more deeply.


🧠 Why Is the Transformer So Powerful?

Parallelization: Unlike RNNs, it processes all tokens at once → faster training.
Long-range understanding: Captures context from far-away words.
Scalability: Can scale to billions of parameters.
Transferable knowledge: Works well with pretraining + fine-tuning.

What is Attention?

Attention is a method that allows a model to focus on important words in a sentence when processing language — just like humans do when reading or listening.


🎯 The Goal

Let’s say we have a sentence:

“The cat sat on the mat because it was tired.”

The model needs to understand what “it” refers to. Attention helps by assigning more weight to important words, like “cat”, instead of irrelevant ones like “on” or “the”.


🧠 Basic Concept: Query, Key, Value

Every word (token) in the sentence is transformed into three vectors:

RoleDescription
Query (Q)What you’re looking for (like a question)
Key (K)What each word offers (like an index)
Value (V)The actual content/meaning of each word

🧮 Step-by-Step Process (Scaled Dot-Product Attention)

Your step-by-step breakdown of how Scaled Dot-Product Attention works is particularly clear:

  1. Computing Scores with Query and Key vectors to measure relevance.
  2. Scaling to maintain training stability.
  3. Applying Softmax to convert scores into a meaningful probability distribution (the attention weights).
  4. Creating the Output Vector by taking a weighted sum of the Value vectors.

This process elegantly allows the model to create a new, context-rich representation for each word by blending information from other relevant words in the sequence. The Q, K, V roles and the room analogy are excellent ways to build intuition around this complex process.

Let’s say we’re calculating attention for a word like “it”.

Step 1: Compute Attention Scores

We compute dot products between the Query vector of “it” and the Key vectors of all other words: Score(Q,Ki)=Q⋅Ki\text{Score}(Q, K_i) = Q \cdot K_iScore(Q,Ki​)=Q⋅Ki​

This gives us a score for each word — how relevant it is to “it”.


Step 2: Scale the Scores

To avoid very large values, we scale them by: score=Q⋅Kidk\text{score} = \frac{Q \cdot K_i}{\sqrt{d_k}}score=dk​​Q⋅Ki​​

(where dkd_kdk​ is the size of the key vectors)


Step 3: Apply Softmax

We convert these scores into probabilities (attention weights): Attention Weighti=escorei∑jescorej\text{Attention Weight}_i = \frac{e^{\text{score}_i}}{\sum_j e^{\text{score}_j}}Attention Weighti​=∑j​escorej​escorei​​

Now we know how much attention to pay to each word.


Step 4: Weighted Sum of Values

We multiply each Value vector by its attention weight and sum them: Output Vector=∑(Attention Weighti×Vi)\text{Output Vector} = \sum (\text{Attention Weight}_i \times V_i)Output Vector=∑(Attention Weighti​×Vi​)

This output becomes the new vector for the word “it” — and now it “knows” that “cat” is important!


🔁 Self-Attention

This process is done for every word in the sentence, all in parallel.
Each word attends to every other word, including itself.


🤹 Multi-Head Attention

Instead of doing this once, the model uses multiple attention heads — each one looking at different relationships or aspects of the sentence.

E.g.:

  • One head focuses on syntax
  • One head on coreference (e.g., what “it” refers to)
  • Another on word meaning

The results are combined and passed to the next layer.


🖼️ Analogy: Looking Around a Room

Imagine you’re in a room (a sentence) and you’re focusing on different people (words).
When someone says “he,” you look around to find who they’re talking about — maybe based on:

  • Who spoke earlier (context)
  • Who seems important (attention)

Attention helps models do this — focus only on the relevant information.


✅ Summary

StepWhat it Does
Q, K, VConvert input into search criteria, lookup, and content
Dot productMeasure similarity (relevance)
SoftmaxTurn similarities into weights
Weighted sumCombine important information

Attention is about understanding how related words are to each other within the current input, not about predicting the next word.

Let’s break that down:

  • NOT for Predicting the Next Word: The final step of an LLM like GPT is to predict the next word. While the context built by the attention layers is used for that prediction, the attention mechanism itself is not doing the predicting. Its job is to prepare the information first.
  • YES for Measuring Relatedness: Look at the visualization from the code. The heatmap shows how much each word (on the Y-axis) pays attention to every other word (on the X-axis). It’s a way for the model to answer questions like:
    • When I’m looking at “Word 3”, how important are “Word 1” and “Word 2” to its meaning?
    • If “Word 2” is a pronoun like “it”, should I pay more attention to the nouns that came before it?

So, think of self-attention as a context-building step. Before the model tries to do anything (like predict the next word or classify a sentence), it uses attention to allow the words to “talk to each other” and figure out their relationships.

What is Epoch and Loss

Let’s break down these two fundamental concepts in machine learning: Epoch and Loss.

Epoch

An epoch represents one complete pass of the entire training dataset through the neural network.

Think of it like studying for an exam.

  • The Dataset is your textbook.
  • One Epoch is like reading the entire textbook from the first page to the last.

In the training loop you provided:

Python

for epoch in range(100):
    # ... code to train on the data ...

This means the model will “read” the entire dataset 100 times. Why do this? Because, just like rereading a textbook, the model learns and reinforces its understanding with each pass.

  • In the first epoch, the model is just starting to see the data and its predictions are likely to be random and inaccurate.
  • By the 10th epoch, it has seen all the data 10 times and has started to learn the underlying patterns.
  • By the 100th epoch, it has refined its knowledge significantly, hopefully becoming much more accurate.

Going through too few epochs can lead to underfitting (the model hasn’t learned enough), while too many can sometimes lead to overfitting (the model memorizes the training data instead of learning general patterns).


Loss (or Loss Function)

Loss is a number that measures how wrong the model’s prediction is compared to the actual correct answer. You can think of it as a penalty for being wrong.

  • High Loss: The model’s prediction was very far from the true answer (it made a big mistake).
  • Low Loss: The model’s prediction was very close to the true answer (it was nearly correct).

The goal of training a model is to minimize the loss.

In your code:

Python

# 🔍 Compute loss between prediction & true answer
loss = loss_fn(output, y)

  1. output is the model’s prediction.
  2. y is the correct answer.
  3. loss_fn (in your case, CrossEntropyLoss) is the function that calculates the “error score” or loss.

The entire training process is a continuous cycle of adjusting the model’s parameters to make this loss value as low as possible. When you see the printout during training:

✅ Epoch 20 - Loss: 1.4321
✅ Epoch 40 - Loss: 0.9876
✅ Epoch 60 - Loss: 0.6543
✅ Epoch 80 - Loss: 0.4123

This is great news! It shows that with each set of epochs, the model is making smaller and smaller errors—it is learning successfully.

Summary

ConceptWhat it isAnalogyGoal
EpochOne full cycle through the training data.Reading a textbook from start to finish.Complete enough epochs to learn without memorizing.
LossA measure of the model’s prediction error.A score in a game where low is good.Minimize this value to make the model more accurate.

Export to Sheets

In short, over multiple epochs, the model tries to minimize its loss by continuously learning from the data.

🧮 What Do Loss Values Look Like?

In your training loop, you might see output like this:

textCopyEdit✅ Epoch 0 - Loss: 1.8974
✅ Epoch 20 - Loss: 0.5432
✅ Epoch 40 - Loss: 0.1521
✅ Epoch 60 - Loss: 0.0356
✅ Epoch 80 - Loss: 0.0120

📉 How to interpret this:

EpochLossMeaning
01.89Model is starting out and making poor guesses
200.54Model is improving; it’s learning patterns
600.03Very close to the correct answers now
800.01Almost perfect for this toy dataset!

🎯 What’s a “Good” Loss?

It depends on:

  • The loss function used (you used CrossEntropyLoss)
  • The scale of logits and predictions
  • The complexity of the dataset

In your case (very small dataset):

  • Loss < 0.1 usually means the model has learned it almost perfectly.
  • Loss ≈ log(vocab_size) (e.g. log(6) ≈ 1.79) means the model is just guessing randomly at first.

📌 Why is CrossEntropyLoss used?

Because it:

  • Measures how close the predicted probability distribution is to the correct one.
  • Penalizes wrong answers more than correct guesses.
  • Works perfectly for classification tasks, like “what’s the next word?”

파이썬 코드를 활용한 LLM 이해

LLM ( 대규모 언어 모델 )은 방대한 텍스트 데이터를 학습하여 인간과 유사한 언어를 이해하고 생성하는 인공지능(AI)의 한 유형입니다. LLM 은 문장의 다음 단어를 놀라운 정확도로 예측하여 다양한 언어 기반 작업을 수행할 수 있는 고도로 발전된 자동 완성 시스템으로 볼 수 있습니다.

LLM은 본질적으로 복잡한 신경망으로, 인간의 뇌에서 영감을 받은 컴퓨팅 시스템입니다. 이 네트워크는 수십억 개에 달하는 엄청난 수의 매개변수를 가지고 있으며, 이러한 매개변수는 학습 과정에서 조정됩니다. 이 학습은 인터넷과 디지털 서적에서 방대한 양의 텍스트와 코드 데이터셋을 모델에 입력하는 과정을 포함합니다. 이 과정을 통해 LLM은 인간 언어의 패턴, 문법, 맥락, 그리고 뉘앙스를 학습합니다.


LLM 작동 방식: Transformer 아키텍처

대부분의 최신 LLM의 핵심 기술은 트랜스포머 아키텍처 입니다 . 2017년 구글이 도입한 이 설계는 모델이 문장을 처리할 때 각 단어의 중요성을 가늠할 수 있도록 합니다. 이 “주의 메커니즘”을 통해 모델은 텍스트에서 단어가 서로 멀리 떨어져 있더라도 맥락과 단어 간의 관계를 이해할 수 있습니다. 이는 텍스트를 순차적으로 처리하던 기존 모델에 비해 크게 개선된 것입니다.

예를 들어, “지붕에 있던 고양이가 쥐를 쫓았다”라는 문장에서 변환기 기반 LLM은 “지붕에 있던”이라는 구가 주어와 동사를 구분하더라도 “고양이”가 쥐를 쫓는 존재라는 것을 이해할 수 있습니다.


LLM의 일반적인 응용 프로그램

LLM이 자연어를 이해하고 생성하는 능력은 다음을 포함한 광범위한 응용 분야로 이어졌습니다.

  • 콘텐츠 제작: 이메일, 기사, 소셜 미디어 게시물, 심지어 창의적인 소설까지 작성합니다.
  • 요약: 긴 문서나 기사를 핵심 요점으로 축약하는 것.
  • 번역: 다양한 언어 간의 텍스트를 점점 더 정확하게 번역합니다.
  • 챗봇과 가상 비서: 고객 서비스 봇과 개인 비서와 같은 대화형 AI를 강화합니다.
  • 코드 생성: 다양한 프로그래밍 언어로 코드를 작성하거나 제안하여 프로그래머를 지원합니다.
  • 질의응답: 훈련 데이터에서 정보를 검색하고 종합하여 질문에 직접 답변을 제공합니다.

LLM의 대표적인 사례

여러분은 이미 여러 저명한 LLM들과 교류하거나 그들의 이야기를 들어보셨을 것입니다. 가장 잘 알려진 사례는 다음과 같습니다.

  • GPT(Generative Pre-trained Transformer) 시리즈: OpenAI에서 개발했으며, GPT-3 및 GPT-4와 같은 모델이 ChatGPT와 같은 애플리케이션을 구동합니다.
  • 제미니: 텍스트, 코드, 이미지, 비디오를 이해하고 처리할 수 있는 구글의 멀티모달 모델 제품군입니다.
  • Llama(대규모 언어 모델 메타 AI): Meta(구 Facebook)가 공개한 일련의 오픈소스 모델입니다.
  • 클로드: AI 안전에 초점을 맞춰 Anthropic이 개발한 모델 패밀리입니다.

본질적으로, 대규모 언어 모델은 인공지능 분야에서 획기적인 발전을 이루어 인간과 컴퓨터 간의 더욱 자연스럽고 정교한 상호작용을 가능하게 합니다. 이 기술은 다양한 산업과 일상생활의 여러 측면을 혁신할 잠재력을 지닌 다재다능한 기술입니다.

핵심 개념

개념설명
Transformer효율적인 언어 모델링을 가능하게 하는 신경망 아키텍처
Tokens단어 또는 단어의 일부; LLM은 텍스트를 토큰 시퀀스로 처리합니다.
Parameters모델의 “노브”; 예를 들어 GPT-4에는 수천억 개가 있습니다.
Pre-training대규모 데이터 세트에서 일반 언어 패턴 학습
Fine Tuning특정 작업이나 도메인에 대한 추가 교육
Inference훈련된 모델을 사용하여 언어 생성 또는 처리

대규모 언어 모델(LLM)의 작동 방식을 이해하는 데 기본이 되는 주요 개념에 대한 자세한 설명은 다음과 같습니다.

트랜스포머

트랜스포머  GPT-4와 구글 제미니를 포함한 대부분의 현대적이고 강력한 대규모 언어 모델(LLM)의 기반이 된 혁신적인 신경망 아키텍처입니다. 구글이 2017년에 도입한 이 모델의 핵심 혁신은 “어텐션 메커니즘”입니다. 이를 통해 모델은 입력 텍스트 내 다양한 ​​단어(토큰)의 중요성을 평가할 수 있습니다. 텍스트를 순차적으로 처리하던 기존 모델과 달리, 트랜스포머는 모든 토큰을 한 번에 처리하고 시퀀스 내 위치와 관계없이 어떤 단어가 서로 가장 관련성이 높은지 동적으로 판단할 수 있습니다. 이러한 장거리 의존성과 맥락을 이해하는 능력 덕분에 LLM은 미묘한 뉘앙스를 파악하고, 복잡한 문장을 처리하며, 매우 일관되고 맥락적으로 관련성 있는 텍스트를 생성할 수 있습니다.

토큰

LLM 영역에서 토큰은 모델이 처리하는 텍스트의 기본 단위입니다. 우리는 단어 단위로 생각하는 반면, LLM은 텍스트를 이러한 토큰의 시퀀스로 분해합니다. 토큰은 전체 단어(예: “apple”), 단어의 일부(예: “un-“, “friend-“, “-ly”), 또는 단일 문자나 구두점일 수 있습니다. 예를 들어, “LLM은 매혹적이다!”라는 문장은 와 같은 토큰으로 분해될 수 있습니다 ["LLMs", "are", "fascinat", "ing", "!"]. 토큰화라고 하는 이 과정을 통해 모델은 방대한 어휘를 처리하고 전체 단어로만 제한될 때보다 문법 구조를 더 유연하게 이해할 수 있습니다. 그런 다음 모델은 이러한 토큰 시퀀스에 대해 수학 연산을 수행하여 언어를 이해하고 생성합니다.

매개변수

매개변수 는 신경망이 학습 단계에서 데이터로부터 학습하는 내부 변수 또는 “노브”입니다. LLM에서 이러한 매개변수는 상호 연결된 노드로 구성된 광대한 네트워크 내의 가중치와 편향입니다. 매개변수의 수는 종종 모델의 크기와 잠재적 성능을 대략적으로 측정하는 데 사용됩니다. 예를 들어, GPT-4와 같은 모델은 수천억 개의 매개변수를 가지고 있다고 합니다. 사전 학습 과정에서 이러한 매개변수는 모델이 문장의 다음 토큰을 예측하는 방법을 학습함에 따라 반복적으로 조정됩니다. 이러한 매개변수의 최종 값은 문법, 사실, 추론 능력, 문체적 뉘앙스를 포함하여 모델이 언어에 대해 습득한 “지식”을 저장합니다.

사전 훈련

사전 학습은 LLM 구축의 초기 단계이자 기초 단계이며, 가장 많은 리소스를 소모하는 단계입니다. 이 단계에서 모델은 방대하고 다양한 텍스트와 코드 데이터세트에 노출되는데, 이러한 데이터세트는 종종 인터넷이나 디지털화된 책에서 스크랩한 것입니다. 목표는 특정 작업을 가르치는 것이 아니라, 인간 언어의 일반적인 패턴, 구조, 그리고 통계적 관계를 학습하는 것입니다. 이는 일반적으로 문장의 다음 단어를 예측하거나 빠진 단어를 채우는 것과 같은 자기 지도 학습 목표를 통해 이루어집니다. 이러한 비지도 사전 학습을 통해 모델은 세상과 언어에 대한 광범위하고 일반적인 이해를 얻게 되며, 이는 더욱 구체적인 능력을 구축할 수 있는 기반을 형성합니다.

미세 조정

미세 조정은 사전 훈련된 LLM을 특정 작업에 맞게 조정하거나 특정 스타일의 지침을 따르도록 하는 보조 훈련 프로세스입니다. 범용 사전 훈련이 완료된 후, 개발자는 기본 모델을 더 작고 전문화된 데이터셋에 대해 추가로 훈련합니다. 예를 들어, 사전 훈련된 모델은 질문-답변 쌍으로 구성된 데이터셋을 기반으로 미세 조정하여 더 나은 대화형 에이전트가 되거나, 의학 텍스트 모음을 기반으로 미세 조정하여 해당 분야에 대한 전문성을 향상시킬 수 있습니다. 미세 조정은 사전 훈련된 모델의 광범위한 기능을 맞춤 설정하여 고객 서비스 봇, 코드 생성 도우미, 콘텐츠 요약기와 같은 특정 애플리케이션에 대해 더욱 정확하고 신뢰할 수 있도록 만듭니다.

추론

추론은 훈련되고 미세 조정된 LLM을 실제로 사용하여 작업을 수행하는 과정입니다. LLM에 프롬프트(질문이나 명령 등)를 제공하면 모델은 추론을 수행합니다. 입력 텍스트를 받아 토큰으로 변환하고, 학습된 매개변수를 사용하여 신경망을 통해 처리하여 한 번에 토큰 하나씩 응답을 생성합니다. 이는 모델이 저장된 지식을 적용하여 텍스트를 생성하고, 언어를 번역하고, 문서를 요약하고, 질문에 답하는 “실시간” 또는 운영 단계입니다. 학습을 위한 학습인 훈련과 달리, 추론은 학습된 내용을 적용하여 유용한 출력을 생성하는 것입니다.

개요: Transformer 란 무엇인가?

트랜스포머  구글이 2017년 논문 “Attention is All You Need” 에서 소개한 딥러닝 모델 아키텍처 입니다 . RNN에서 사용되는 재귀 연산의 필요성을 제거 하고 더 강력한 셀프 어텐션( self-attention )으로 대체 했기 때문에 혁신적이었습니다 .

이 기능은 문장 속 단어 사이의 관계를 이해 하도록 설계되었으며 , 단어 간의 거리는 중요하지 않습니다.


⚙️ Transformer의 주요 구성 요소

변압기는 두 가지 주요 부분으로 구성되어 있습니다.

1. 인코더 – 입력 문장을 이해합니다.

2. 디코더 – 출력을 생성합니다(번역이나 텍스트 생성과 같은 작업에 사용됨)

GPT 와 같은 모델에서는 디코더만 사용(생성용)하고, BERT 에서는 인코더만 사용(이해용)합니다.

두 가지의 핵심 구성 요소 에 초점을 맞춰 보겠습니다 .


🔩 트랜스포머의 구성 요소

1. 임베딩 레이어

  • 단어를 벡터 (고차원 숫자) 로 변환합니다 .
  • 각 단어/토큰은 의미를 포착하는 밀도 있는 숫자 표현이 됩니다 .

2. 위치 인코딩

  • 변환기에는 루프(RNN과 같음)가 없으므로 문장에서 단어의 위치를 ​​알 수 있는 방법이 필요합니다.
  • 위치 인코딩은 “이 단어가 첫 번째입니다”, “이 단어가 두 번째입니다” 등의 정보를 임베딩에 추가합니다.

3. 자기 주의(스케일링된 점곱 주의)

이것이 변압기의 심장 입니다 .

이 기능을 사용하면 모델이 문장 속의 다양한 단어에 “주의를 기울여” 맥락을 이해할 수 있습니다.

📌 예시:

문장에서:

“고양이는 피곤해서 매트에 앉았어요.”

“그것”이라는 단어는 “고양이”를 가리킵니다.
셀프 어텐션은 모델이 이를 파악하는 데 도움이 됩니다.

🔢 어떻게 작동하나요?

각 단어는 다음과 같이 변환됩니다.

  • 질의(Q)
  • 키(K)
  • 가치(V)

모델은 다음을 계산하여 다른 단어의 관련성을 계산합니다. 주의 점수 = Q⋅KTdk\text{주의 점수} = \frac{Q \cdot K^T}{\sqrt{d_k}}주의 점수 = dk​​Q⋅KT​

그런 다음 이 점수를 사용하여 값(V)을 평가 하고 이를 결합하여 단어의 새로운 표현을 만듭니다.

이는 모든 단어에 대해 병렬로 발생합니다 .


4. 멀티헤드 어텐션

Q, K, V의 한 세트를 사용하는 대신, 이 모델은 여러 개의 헤드 (다중 주의 메커니즘과 같음)를 사용하여 문장의 여러 부분에 동시에 집중합니다.

이를 통해 모델은 다음을 이해할 수 있습니다.

  • 통사론
  • 의미론
  • 단어들 사이의 관계가
    한꺼번에 나타납니다.

5. 피드포워드 신경망

주의가 집중된 후, 각 단어의 벡터는 일반적인 완전 연결 신경망 (각 위치마다 동일)을 거칩니다.

6. 레이어 정규화 및 잔여 연결

  • 잔여물: 정보 손실(바로가기 추가 등)을 방지하는 데 도움이 됩니다.
  • 레이어 표준: 훈련의 안정성과 속도에 도움이 됩니다.

🔁 레이어 쌓기

트랜스포머는 깊습니다 . GPT-4 또는 BERT-base는 위 블록의 여러 레이어 (예: 12, 24 또는 96+)를 가지고 있습니다.
각 레이어는 모델이 텍스트를 더욱 깊이 이해하도록 합니다.


🧠 Transfomer가 왜 그렇게 강력한가요?

✅ 병렬화 : RNN과 달리 모든 토큰을 한 번에 처리하여 학습 속도가 빨라집니다.
✅ 장거리 이해 : 멀리 있는 단어의 맥락을 파악합니다.
✅ 확장성 : 수십억 개의 매개변수로 확장할 수 있습니다.
✅ 이전 가능한 지식 : 사전 학습 + 미세 조정과 잘 작동합니다.

Attention 란 무엇인가?

주의는 언어를 처리할 때 모델이 문장 속 중요한 단어에 집중할 수 있게 해주는 방법입니다 . 이는 사람이 읽거나 들을 때와 같습니다.


🎯 목표

다음과 같은 문장이 있다고 가정해 보겠습니다.

“고양이는 피곤 해서 매트에 앉았어요 .”

모델은 ” it “이 무엇을 가리키는지 이해해야 합니다. 주의는 “on”이나 “the”처럼 관련성이 없는 단어 대신 “cat”처럼 중요한 단어에 더 많은 가중치를 부여하여 도움이 됩니다 .


🧠 기본 개념: 쿼리, 키, 값

문장의 모든 단어(토큰)는 ​​세 개의 벡터로 변환됩니다.

역할설명
질의(Q)당신이 찾고 있는 것(질문과 같은)
키(K)각 단어가 제공하는 것(색인과 같음)
가치(V)각 단어의 실제 내용/의미

🧮 단계별 프로세스(확장된 점곱 주의)

Scaled Dot-Product Attention이 작동하는 방식에 대한 단계별 분석은 특히 명확합니다.

  1. 관련성을 측정하기 위해 쿼리 및 키 벡터를 사용하여 점수를 계산합니다 .
  2. 훈련 안정성을 유지하기 위한 확장 .
  3. 소프트맥스를 적용하여 점수를 의미 있는 확률 분포(주의 가중치)로 변환합니다.
  4. 값 벡터의 가중합을 구하여 출력 벡터를 생성합니다 .

이 과정을 통해 모델은 시퀀스 내 다른 관련 단어의 정보를 혼합하여 각 단어에 대한 새롭고 맥락이 풍부한 표현을 우아하게 생성할 수 있습니다. Q, K, V 역할과 방 비유는 이 복잡한 과정에 대한 직관을 구축하는 훌륭한 방법입니다.

” it ” 과 같은 단어에 대한 주의를 계산한다고 가정해 보겠습니다 .

1단계: 주의 점수 계산

우리는 “it”의 Query 벡터와 다른 모든 단어 의 Key 벡터 사이의 점곱을 계산합니다 : Score(Q,Ki)=Q⋅Ki\text{Score}(Q, K_i) = Q \cdot K_iScore(Q,Ki​)=Q⋅Ki

이를 통해 각 단어에 대한 점수가 매겨집니다. 즉, “그것”과 얼마나 관련이 있는지를 나타냅니다.


2단계: 점수 조정

매우 큰 값을 피하기 위해 다음과 같이 크기를 조정 합니다 . score=Q⋅Kidk\text{score} = \frac{Q \cdot K_i}{\sqrt{d_k}}score=dk​​Q⋅Ki

(여기서 dkd_kdk​는 키 벡터의 크기입니다)


3단계: 소프트맥스 적용

이러한 점수를 확률 (주의 가중치) 로 변환합니다 . 주의 가중치i=escorei∑jescorej\text{주의 가중치}_i = \frac{e^{\text{score}_i}}{\sum_j e^{\text{score}_j}}주의 가중치i​=∑j​escorej​escorei

이제 우리는 각 단어에 얼마나 많은 주의를 기울여야 하는지 알게 되었습니다.


4단계: 값의 가중합

각 값 벡터를 주의 가중치로 곱하고 합산 합니다 . 출력 벡터 = ∑(주의 가중치 i×Vi)\text{출력 벡터} = \sum (\text{주의 가중치}_i \times V_i) 출력 벡터 = ∑(주의 가중치 i​×Vi​)

이 출력은 단어 “it”에 대한 새로운 벡터가 됩니다. 그리고 이제 “cat”이 중요하다는 것을 “알게” 되었습니다!


🔁 자기 주의

이 과정은 문장의 모든 단어 에 대해 병렬로 수행됩니다 .
각 단어는 자신을 포함하여 다른 모든 단어에 영향을 미칩니다 .


🤹 멀티헤드 어텐션

이 모델은 한 번만 수행하는 것이 아니라 여러 개의 주의 헤드를 사용합니다 . 각 헤드는 문장의 다른 관계나 측면을 살펴봅니다.

예:

  • 한 머리는 구문 에 집중합니다
  • 공동 참조에 대한 한 가지 측면 (예: “그것”이 무엇을 가리키는지)
  • 또 다른 단어의 의미

결과는 결합되어 다음 계층으로 전달됩니다.


🖼️ 비유: 방을 둘러보는 것

당신이 방(문장)에 있고 여러 사람(단어)에 집중하고 있다고 상상해 보세요.
누군가 “그”라고 말하면, 당신은 그 사람이 누구를 말하는지 보기 위해 주위를 둘러봅니다 . 아마도 다음과 같은 이유 때문일 것입니다.

  • 누가 앞서 말했나요? (맥락)
  • 누가 중요해 보이는가 (주의)

주의는 모델이 관련 정보 에만 집중할 수 있도록 도와줍니다 .


✅ 요약

단계그것이 하는 일
큐, 케이, 브이입력을 검색 기준, 조회 및 콘텐츠로 변환
점곱유사성(관련성) 측정
소프트맥스유사점을 가중치로 변환
가중합계중요한 정보를 결합하세요

주의는 다음 단어를 예측하는 것이 아니라 현재 입력 내에서 단어가 서로 얼마나 관련되어 있는지 이해하는 것입니다 .

이를 자세히 살펴보겠습니다.

  • 다음 단어 예측에는 적합하지 않음: GPT와 같은 LLM의 마지막 단계는 다음 단어를 예측하는 것입니다. 주의 계층에서 구축된 맥락이 예측에 사용 되지만 , 주의 메커니즘 자체는 예측을 수행하지 않습니다. 주의 메커니즘의 역할은 정보를 먼저 준비하는 것입니다.
  • 관련성 측정에 대한 예: 코드의 시각화를 살펴보세요. 히트맵은 각 단어(Y축)가 다른 모든 단어(X축)에 얼마나 주의를 기울이는지 보여줍니다. 이는 모델이 다음과 같은 질문에 답하는 방식입니다.
    • “단어 3″을 볼 때, “단어 1″과 “단어 2″는 의미에 얼마나 중요합니까?
    • “Word 2″가 “it”과 같은 대명사라면, 그 앞에 나오는 명사에 더 주의를 기울여야 할까요?

그러니 셀프 어텐션을 맥락 구축 단계 로 생각해 보세요 . 모델이 어떤 작업(예: 다음 단어 예측이나 문장 분류)을 시도하기 전에, 어텐션을 사용하여 단어들이 “서로 대화”하고 관계를 파악할 수 있도록 합니다.

에포크와 손실이란 무엇인가

머신 러닝의 두 가지 기본 개념인 Epoch 와 Loss를 살펴보겠습니다 .

시대

에포크  신경망을 통한 전체 학습 데이터 세트의 한 번의 완전한 통과를 나타냅니다.

시험공부를 하는 것과 같다고 생각해보세요.

  • 데이터 세트 는 교과서입니다.
  • 한 에포크는 첫 페이지부터 마지막 ​​페이지까지 교과서 전체를 읽는 것과 같습니다.

교육 루프에서 다음을 제공했습니다.

파이썬

for epoch in range(100):
    # ... code to train on the data ...

즉, 모델은 전체 데이터 세트를 100번 “읽는다”는 의미입니다. 왜 이렇게 할까요? 마치 교과서를 다시 읽는 것처럼, 모델은 매번 읽을 때마다 학습하고 이해도를 높이기 때문입니다.

  • 첫 번째 시대 에는 모델이 데이터를 막 확인하기 시작했기 때문에 예측이 무작위적이고 부정확할 가능성이 높습니다.
  • 10번째 시대가 되면 모든 데이터를 10번 보고 기본 패턴을 학습하기 시작합니다.
  • 100번째 시대 가 되자 지식이 상당히 개선되어 훨씬 더 정확해졌기를 바랍니다.

에포크가 너무 적으면 과소적합 (모델이 충분히 학습하지 못함) 이 발생할 수 있고 , 에포크가 너무 많으면 과대 적합 (모델이 일반적인 패턴을 학습하는 대신 훈련 데이터를 기억함)이 발생할 수 있습니다.


손실(또는 손실 함수)

손실은 모델의 예측이 실제 정답과 비교했을 때 얼마나 틀렸는지를 측정하는 숫자입니다.그것은 틀렸을 때의 처벌 이라고 생각할 수 있습니다 .

  • 높은 손실 : 모델의 예측이 실제 답과 매우 달랐습니다(큰 실수가 있었습니다).
  • 낮은 손실 : 모델의 예측은 실제 답에 매우 가깝습니다(거의 정확했습니다).

모델을 학습하는 목적은 손실을 최소화하는 것 입니다 .

코드에서:

파이썬

# 🔍 Compute loss between prediction & true answer
loss = loss_fn(output, y)

  1. output모델의 예측입니다.
  2. y정답은 입니다.
  3. loss_fn(귀하의 경우 CrossEntropyLoss)는 “오류 점수” 또는 손실을 계산하는 함수입니다.

loss전체 학습 과정은 이 값을 가능한 한 낮게 만들기 위해 모델의 매개변수를 조정하는 지속적인 순환입니다 .훈련 중에 출력물을 볼 때:

✅ Epoch 20 - Loss: 1.4321
✅ Epoch 40 - Loss: 0.9876
✅ Epoch 60 - Loss: 0.6543
✅ Epoch 80 - Loss: 0.4123

좋은 소식이네요! 각 에포크마다 모델이 점점 더 작은 오류를 범하고 있음을 보여줍니다. 즉, 모델이 성공적으로 학습하고 있다는 뜻입니다.

요약

개념그것은 무엇입니까유추목표
시대훈련 데이터를 한 번 완전히 순환합니다.교과서를 처음부터 끝까지 읽는다.암기하지 않고도 배울 수 있을 만큼 충분한 에포크를 완료하세요.
손실모델의 예측 오차를 측정한 값입니다.낮은 점수가 좋은 게임에서의 점수.모델의 정확도를 높이려면 이 값을 최소화하세요.

시트로 내보내기

간단히 말해서, 모델은 여러 시대 에 걸쳐 데이터로부터 지속적으로 학습하여 손실 을 최소화하려고 노력합니다.

🧮 손실 값은 어떻게 되나요?

훈련 루프에서 다음과 같은 출력이 표시될 수 있습니다.

텍스트복사편집✅ Epoch 0 - Loss: 1.8974
✅ Epoch 20 - Loss: 0.5432
✅ Epoch 40 - Loss: 0.1521
✅ Epoch 60 - Loss: 0.0356
✅ Epoch 80 - Loss: 0.0120

📉 해석 방법:

시대손실의미
01.89모델이 시작되고 잘못된 추측을 하고 있습니다.
200.54모델이 개선되고 있습니다. 학습 패턴입니다.
600.03이제 정답에 매우 가깝습니다
800.01이 장난감 데이터 세트에는 거의 완벽해요!

🎯 “좋은” 손실이란 무엇인가요?

이는 다음에 따라 달라집니다:

  • 사용된 손실 함수 (당신이 사용한 CrossEntropyLoss)
  • 로짓 과 예측 의 규모
  • 데이터 세트의 복잡성

귀하의 경우(매우 작은 데이터 세트):

  • 손실 < 0.1은 일반적으로 모델이 거의 완벽하게 학습했다는 것을 의미합니다.
  • 손실 ≈ log(vocab_size) (예 log(6) ≈ 1.79)는 모델이 처음에는 무작위로 추측한다는 것을 의미합니다.

📌 왜 CrossEntropyLoss사용되나요?

왜냐하면:

  • 예측된 확률 분포가 정확한 분포 에 얼마나 가까운지를 측정합니다 .
  • 정답을 맞힌 것보다 틀린 답변을 하면 더 큰 처벌을 받습니다.
  • “다음 단어는 무엇일까?”와 같은 분류 작업 에 완벽하게 작동합니다 .

Leave a Comment

Your email address will not be published. Required fields are marked *