컴퓨터는 단 한 순간도 인간의 글자를 직접 읽거나 이해한 적이 없습니다. 웹 브라우저나 터미널 화면에서 보는 '사과', '강아지', '트랜스포머'라는 단어는 소스 코드와 인공신경망 내부로 들어가는 순간 오직 실수 숫자의 집합과 대규모 행렬 연산으로 번역됩니다.
일반 소프트웨어 개발자나 비-머신러닝 기술 직군이 ChatGPT, Claude, Llama 같은 거대 언어 모델(LLM)을 다룰 때 가장 자주 마주치는 기술 용어가 있습니다. 바로 임베딩(Embedding), 원핫 인코딩(One-Hot Encoding), RNN, 트랜스포머(Transformer), 그리고 Q, K, V 셀프 어텐션(Self-Attention)입니다.
이 개념들이 어떤 엔지니어링 한계 속에서 탄생했고, 어떤 수학적 연산을 거쳐 문맥을 파악하는지 기초부터 실무 연계까지 차근차근 다뤄봅니다.
1. 첫 번째 장벽: 글자를 숫자로 바꾸는 딜레마
일반적인 웹 개발에서 조건문을 작성할 때 if (word1 === word2)는 두 텍스트의 UTF-8 바이트 시퀀스가 일치하는지만 판별합니다. 컴퓨터는 '사과'와 '배'가 비슷한 과일인지, '사과'와 '자동차'가 완전히 다른 범주인지 알 수 없습니다.
인공신경망이 언어를 다루려면 글자를 텐서(Tensor)라 불리는 숫자 배열로 바꿔야 합니다. 초기 자연어 처리(NLP) 연구자들이 가장 먼저 시도한 방식은 가장 단순하고 직관적인 원핫 인코딩(One-Hot Encoding)이었습니다.
원핫 인코딩(One-Hot Encoding)의 구조와 문제점
사전에 등록된 단어가 10만 개라면, 10만 차원의 거대한 배열을 만듭니다. 그리고 각 단어마다 고유한 한 위치에만 1을 부여하고 나머지는 모두 0으로 채웁니다.
사과 = [1, 0, 0, 0, 0, ..., 0] (10만 차원 중 1번만 1)배 = [0, 1, 0, 0, 0, ..., 0] (10만 차원 중 2번만 1)자동차 = [0, 0, 1, 0, 0, ..., 0] (10만 차원 중 3번만 1)
이 방식은 직관적이지만 두 가지 치명적인 딜레마에 부딪혔습니다.
- 메모리 폭발 (Sparse Vector): 단어 몇 개만 표현하려 해도 99.99%가 0으로 차 있는 수십만 차원의 희소 벡터가 생성되어 시스템 메모리가 낭비됩니다.
- 의미적 직교성 (Zero Similarity): 수학적으로 모든 원핫 벡터는 서로 직교(Orthogonal)합니다. 즉 두 원핫 벡터를 내적(Dot Product)하면 결과는 언제나 0입니다. 컴퓨터 관점에서는 '사과'와 '배'의 관계나 '사과'와 '자동차'의 관계가 완전히 동일하게 아무런 관련 없는 값으로 처리됩니다.
2. 돌파구: 의미의 공간을 만드는 밀집 임베딩 (Dense Embedding)
이 한계를 극복한 기술이 바로 밀집 임베딩(Dense Embedding)입니다. 10만 차원의 0으로 가득 찬 희소 공간 대신, 수백 차원(예: 512차원, 1536차원)의 연속된 실수 좌표(Dense Vector)로 단어를 표현합니다.
사과 = [0.24, -0.81, 0.45, 0.12, ...] (512차원 실수 좌표)배 = [0.21, -0.79, 0.41, 0.09, ...] (사과와 유사한 좌표)자동차 = [-0.91, 0.15, -0.88, 0.73, ...] (사과와 먼 좌표)
다차원 의미 공간과 좌표 비유
도시의 위치를 표현할 때 '위도', '경도', '고도'라는 3개 축을 사용하듯, 단어 임베딩은 수백 개의 축을 가진 다차원 의미 공간(Vector Space)을 만듭니다.
- 의미의 인접성: 문맥상 비슷한 맥락에서 자주 등장하는 단어일수록 공간상에서 가깝게 배치됩니다.
- 벡터 연산으로 작동하는 의미: 단어 벡터 간의 덧셈과 뺄셈이 인간의 직관과 일치하게 작동합니다. 유명한 예시로
King - Man + Woman ≈ Queen연산이 가능해집니다.
임베딩 표 (Lookup Table)와 역전파 (Backpropagation)
초기 임베딩 표(Embedding Lookup Table)의 실수 좌표들은 무작위 수(Random Float)로 시작합니다. 모델이 문장을 학습하면서 다음 단어를 예측하고, 오차가 발생하면 역전파(Backpropagation)를 통해 경사하강법(Gradient Descent)으로 이 좌표들을 조금씩 이동시킵니다.
수백만 개의 문장을 학습한 뒤에는 비슷한 의미를 가진 단어들이 스스로 거리를 좁히며 촘촘하고 정교한 의미 지도가 완성됩니다.
일반 개발자가 만나는 실무 연결: Vector DB
최근 RAG(Retrieval-Augmented Generation) 시스템이나 LLM 애플리케이션 개발 시 접하는 Vector DB(Pinecone, pgvector, Qdrant 등)는 바로 이 밀집 임베딩 좌표를 저장하고 검색하는 시스템입니다.
사용자의 질의문(Query)을 밀집 임베딩 좌표로 바꾼 뒤, DB에 저장된 문서 임베딩들과 코사인 유사도(Cosine Similarity)를 계산하여 의미적으로 가장 가까운 문서를 찾아내는 원리가 바로 임베딩 공간의 연산입니다.
3. 두 번째 장벽: 순차 처리의 늪과 기억의 한계 (RNN vs LSTM)
단어를 성공적으로 실수 좌표로 바꿨지만, 단어 하나만으로는 문맥을 파악할 수 없습니다. "사과를 먹었다"의 사과(과일)와 "사과를 표했다"의 사과(사죄)는 문장 전체의 조화를 읽어야만 구분할 수 있습니다.
RNN (Recurrent Neural Network)의 작동 원리
순차적 문맥을 다루기 위해 등장한 초기 신경망이 RNN입니다. RNN은 문장을 첫 단어부터 마지막 단어까지 순서대로 읽으며, 이전 단어까지의 맥락 정보가 담긴 은닉 상태(Hidden State) 벡터를 다음 단어로 전달했습니다.
[단어 1] → [RNN Cell] → 은닉 상태 h1 전달 ↓[단어 2] → [RNN Cell] → 은닉 상태 h2 전달 ↓[단어 3] → [RNN Cell] → 은닉 상태 h3 전달
RNN과 LSTM이 직면한 두 가지 한계
- 순차 연산으로 인한 GPU 병렬화 불가능: step N을 계산하려면 반드시 step N-1의 연산 결과가 나와야 합니다. 수천 개의 연산 코어를 가진 GPU를 장착해도 순차적 루프 때문에 병렬 처리를 하지 못하고 학습 속도가 극도로 느려졌습니다.
- 장기 기억 상실 (Vanishing Gradient): 문장이 길어질수록 앞쪽 단어의 정보가 은닉 상태를 거치면서 점점 희석됩니다. LSTM이 Cell State라는 통로를 추가해 이 문제를 완화했으나, 100단어가 넘어가는 긴 문맥을 유지하기에는 여전히 한계가 명확했습니다.
4. 대전환: 트랜스포머(Transformer)와 셀프 어텐션 (Self-Attention)
2017년 Google Research팀(Vaswani et al.)이 발표한 논문 "Attention Is All You Need"는 이 순차적 읽기 방식을 완전히 폐기했습니다.
"문장을 단어 순서대로 읽지 말고, 문장 전체를 한 번에 GPU 행렬 연산으로 입력받아 모든 단어가 서로를 동시에 직접 바라보게 만들자"라는 발상의 전환이 일어난 것입니다. 이것이 현대 모든 LLM의 근간인 트랜스포머(Transformer) 아키텍처입니다.
5. Q, K, V 셀프 어텐션 행렬 연산의 입체적 파해
트랜스포머의 핵심 연산인 셀프 어텐션(Self-Attention)이 어떻게 한 번의 행렬 곱으로 문장 전체의 맥락을 계산하는지 직관적으로 알아봅니다.
교실 질의응답 비유 (Q, K, V의 개념)
어느 교실에 학생(단어)들이 모여 공부를 하고 있다고 가정해 봅니다.
- Q (Query - 질문): 어떤 학생이 특정 지식을 찾기 위해 던지는 질문 ("Redis 캐싱 구조 잘 아는 사람 있나요?")
- K (Key - 명찰): 다른 학생들이 각자 가슴에 달고 있는 전문 분야 표식 ("나 DB 전문", "나 UI 전문", "나 캐싱 전문")
- V (Value - 지식 내용): 각 학생이 머릿속에 담고 있는 실제 지식 패일로드
질문(Q)을 던진 학생은 교실 안 모든 학생의 명찰(K)을 한 번에 스캔합니다. 명찰의 연관성이 높을수록(Q와 K의 일치도가 높을수록) 그 학생의 지식 내용(V)에 더 높은 주의(Attention) 기울임을 부여하여 답변 정보를 모읍니다.
셀프 어텐션 수식 분석
Attention(Q, K, V) = softmax( (Q × Kᵀ) / √d_k ) × V
입력 임베딩 행렬 X에 학습 가중치 행렬 W_Q, W_K, W_V를 각각 곱해 Q, K, V 행렬을 동시에 만듭니다. 그 후 위 수식을 4단계 행렬 연산으로 실행합니다.
- 병렬 연관성 계산 (Q × Kᵀ): 쿼리 행렬 Q와 키 행렬의 전치(Kᵀ)를 행렬 곱셈합니다. 이 단 한 번의 행렬 곱으로 문장 안의 모든 단어쌍 간 유사도 점수(Attention Score)가 동시 계산됩니다.
- 스케일링 (/ √d_k): 차원이 커질수록 행렬 곱 결과값이 지나치게 커져 Softmax 함수의 기울기(Gradient)가 소멸되는 현상을 막기 위해 차원 수의 제곱근으로 나눕니다.
- 확률 정규화 (Softmax): 점수들을 합이 1이 되는 확률 분포로 바꿉니다. 이제 "단어 A는 단어 B에 70%, 단어 C에 20% 주의를 기울여야 한다"는 가중치가 완성됩니다.
- 문맥 가중합 (× V): 정규화된 확률 가중치를 실제 지식 내용인 V 행렬과 곱합니다. 결과적으로 문장 내 모든 단어의 맥락 정보가 풍부하게 융합된 새로운 단어 벡터가 단 한 번의 행렬 연산으로 새로 태어납니다.
6. 멀티헤드 어텐션(Multi-Head Attention)과 위치 인코딩
여러 시각으로 동시에 바라보는 멀티헤드 어텐션
단어 관계는 단 하나의 관점만으로 설명할 수 없습니다. "그녀가 그에게 사과를 건넸다"라는 문장에서:
- 첫 번째 헤드(Head 1): 문법적 주어-동사 관계 (그녀가 → 건넸다)
- 두 번째 헤드(Head 2): 대명사 지칭 관계 (그녀가 → 누구?)
- 세 번째 헤드(Head 3): 목적어 동사 관계 (사과를 → 건넸다)
트랜스포머는 Q, K, V를 여러 개(예: 8개 또는 16개)로 쪼개어 서로 다른 관점에서 동시에 셀프 어텐션을 수행하는 멀티헤드 어텐션(Multi-Head Attention)을 적용합니다.
위치 인코딩 (Positional Encoding)
문장 전체를 한 번에 입력받으면 "사과가 강아지를 물었다"와 "강아지가 사과를 물었다"를 구분할 수 없게 됩니다. 트랜스포머는 순차 구조를 버린 대신, 단어 임베딩에 위치 정보를 나타내는 주기 함수(Sin/Cos) 좌표인 위치 인코딩(Positional Encoding)을 더해 단어의 순서 정보를 보존합니다.
7. 일반 개발자를 위한 실무 시사점 Summary
마지막으로 이 수학적 아키텍처가 실무 LLM 엔지니어링과 비용 구조에 어떤 영향을 미치는지 정리합니다.
- 토큰 길이에 따른 연산 비용 폭발 ($O(N^2)$): 셀프 어텐션은 모든 단어가 서로를 참조하므로 문장 길이 N에 대해 $O(N^2)$ 크기의 행렬을 만듭니다. 컨텍스트 윈도우(Context Window)가 길어질수록 LLM API 비용과 GPU 메모리가 급격히 증가하는 이유가 바로 $Q \times Kᵀ$ 행렬 연산의 특성 때문입니다.
- GPU가 LLM의 필수재인 이유: 트랜스포머 연산의 90% 이상은 대규모 행렬 곱셈($A \times B$)입니다. 수천 개의 자잘한 코어로 단순 곱셈을 병렬 처리하는 GPU와 NPU가 LLM 학습 및 추론 서버의 핵심 인프라인 이유입니다.
- RAG와 프롬프트 엔지니어링의 본질: LLM에 긴 문맥을 주입하는 RAG 시스템은 결국 모델의 Q, K, V 셀프 어텐션 연산 공간 안에 정확한 참치(Context)를 집어넣어, Attention 가중치가 정답 단어를 강하게 가리키도록 유도하는 기술입니다.
컴퓨터가 글자를 숫자로 바꾼 밀집 임베딩부터, GPU 병렬화를 가능하게 만든 트랜스포머의 셀프 어텐션까지—현대 LLM은 거대한 행렬 연산 위에서 지능적 언어 처리를 수행하고 있습니다.
Computers have never directly read or understood human text. Words like "apple," "dog," or "transformer" on a terminal or web interface are translated into mathematical arrays of floating-point numbers and matrix operations the moment they enter a software environment.
For general software developers and non-ML technical professionals working with Large Language Models (LLMs) like ChatGPT, Claude, or Llama, terms like Embedding, One-Hot Encoding, RNN, Transformer, and Q, K, V Self-Attention appear constantly.
This article explores why these core mechanisms were invented, how they operate step-by-step through matrix operations, and what practical engineering takeaways they offer.
1. The Initial Barrier: Translating Words to Numbers
In standard software development, evaluating if (word1 === word2) simply compares UTF-8 byte sequences. The computer has no intrinsic knowledge of whether "apple" and "pear" are related fruits, or if "apple" and "automobile" belong to entirely different categories.
For neural networks to process human language, words must be converted into numerical arrays called Tensors. Early Natural Language Processing (NLP) researchers first attempted the simplest approach: One-Hot Encoding.
One-Hot Encoding Structure and Limitations
If a vocabulary contains 100,000 words, a 100,000-dimensional array is created. Each word is assigned a single index set to 1, while all other indices remain 0.
apple = [1, 0, 0, 0, 0, ..., 0] (Index 1 is 1)pear = [0, 1, 0, 0, 0, ..., 0] (Index 2 is 1)automobile = [0, 0, 1, 0, 0, ..., 0] (Index 3 is 1)
While intuitive, this approach created two critical engineering bottlenecks:
- Memory Explosion (Sparse Vectors): Representing even a small sentence generated multi-hundred-thousand dimensional sparse vectors where 99.99% of values were zeros, severely wasting memory.
- Semantic Orthogonality (Zero Similarity): Mathematically, all one-hot vectors are orthogonal to one another. The dot product of any two one-hot vectors is always 0. To the computer, the relationship between "apple" and "pear" was identical to the relationship between "apple" and "automobile"—completely unrelated.
2. Breakthrough: Dense Embeddings in Semantic Space
Dense Embedding solved this dilemma by replacing 100,000-dimensional sparse arrays with continuous floating-point coordinates across lower-dimensional spaces (e.g., 512 or 1,536 dimensions).
apple = [0.24, -0.81, 0.45, 0.12, ...] (512-dimensional floats)pear = [0.21, -0.79, 0.41, 0.09, ...] (Close coordinates to apple)automobile = [-0.91, 0.15, -0.88, 0.73, ...] (Far coordinates from apple)
Multidimensional Coordinate Analogy
Just as city locations are identified using 3 axes (Latitude, Longitude, Altitude), word embeddings map tokens across hundreds of continuous coordinate axes in a Vector Space.
- Proximity: Words appearing in similar contexts sit near each other in coordinate space.
- Vector Arithmetic: Mathematical addition and subtraction reflect intuitive human concepts (e.g.,
King - Man + Woman ≈ Queen).
Lookup Tables and Backpropagation
Initial coordinate values in an Embedding Lookup Table start as random floats. As the neural network trains to predict upcoming words, prediction errors trigger Backpropagation, using Gradient Descent to iteratively adjust coordinate positions.
After processing millions of sentences, words with similar meanings converge toward one another, forging a dense semantic map.
Practical Developer Connection: Vector Databases
In modern LLM applications, Vector Databases (Pinecone, pgvector, Qdrant) store and index these dense embedding vectors.
When a user submits a search query, the system converts the query into a dense embedding vector and computes Cosine Similarity against stored document vectors. Finding semantically relevant passages relies directly on this vector space math.
3. The Second Barrier: The Sequential Loop Bottleneck (RNN vs. LSTM)
Converting individual words into continuous vectors solved representation, but single words cannot resolve context. For example, "bank" in "river bank" versus "bank account" requires examining the surrounding sentence.
Recurrent Neural Networks (RNNs)
To process sequential context, early architectures used RNNs. An RNN processes sentences word-by-word in order, passing a Hidden State vector ($h_t$) to subsequent steps.
[Word 1] → [RNN Cell] → Passes Hidden State h1 ↓[Word 2] → [RNN Cell] → Passes Hidden State h2 ↓[Word 3] → [RNN Cell] → Passes Hidden State h3
Two Severe Bottlenecks of RNNs and LSTMs
- Inability to Parallelize on GPUs: Computing step N requires the output of step N-1. Thousands of GPU cores sat idle because the sequential loop prevented parallel matrix execution.
- Vanishing Gradient and Memory Loss: As sentence length increased, information from early words diluted over recurrent steps. LSTMs added a Cell State highway to mitigate this, but maintaining long-range context across long passages remained difficult.
4. The Turning Point: Transformers and Self-Attention
In 2017, Vaswani et al. published "Attention Is All You Need," abandoning sequential recurrent processing.
Instead of reading words step-by-step in sequence, the Transformer ingests the entire sentence simultaneously through matrix multiplication, allowing every word to attend to every other word concurrently.
5. Deconstructing Q, K, V Self-Attention Matrix Operations
Understanding how Self-Attention evaluates sentence-wide relationships in a single matrix pass requires looking at Query, Key, and Value vectors.
The Classroom Analogy (Q, K, V Concepts)
Imagine students (words) sitting in a classroom:
- Q (Query): A student asking a specific question ("Who understands Redis caching?").
- K (Key): Public badge tags worn by each student ("DB Expert," "UI Expert," "Caching Expert").
- V (Value): The actual knowledge payload held in each student's mind.
The asking student (Query) scans all student badges (Keys) simultaneously. Higher tag compatibility yields higher Attention weight, drawing more knowledge payload (Value) from relevant peers.
Step-by-Step Breakdown of the Self-Attention Formula
Attention(Q, K, V) = softmax( (Q × Kᵀ) / √d_k ) × V
Input embedding matrix X multiplies learned weight matrices W_Q, W_K, and W_V to generate Q, K, and V matrices. The formula executes across four matrix operations:
- Parallel Relevance Matrix (Q × Kᵀ): Multiplying Query (Q) by Key transpose (Kᵀ) evaluates all pairwise token relationships across the sentence in a single matrix multiplication.
- Scaling (/ √d_k): Dividing by the square root of key dimension prevents dot products from blowing up in high dimensions, protecting Softmax gradients from vanishing.
- Probability Normalization (Softmax): Softmax converts scores into probability weights that sum to 1 (e.g., Token A attends 70% to Token B and 20% to Token C).
- Contextual Weighted Sum (× V): Multiplying normalized weights by Value matrix V synthesizes a updated, context-aware representation vector for every token concurrently.
6. Multi-Head Attention and Positional Encoding
Multi-Head Attention: Viewing Context from Multiple Angles
A single attention pass cannot capture all relationship types at once. In "She handed him the apple":
- Head 1: Grammatical Subject-Verb relationship (She → handed)
- Head 2: Pronoun reference relationship (She → Who?)
- Head 3: Object-Verb relationship (apple → handed)
Multi-Head Attention splits Q, K, and V across multiple subspaces (e.g., 8 or 16 heads), processing distinct grammatical and semantic relationships simultaneously.
Positional Encoding
Because Transformers process all tokens at once, "dog bit man" and "man bit dog" would appear identical without ordering information. Positional Encoding adds sinusoidal coordinate values to token embeddings, preserving word order without requiring sequential loops.
7. Summary of Engineering Takeaways for Developers
- Quadratic Attention Cost ($O(N^2)$): Because every token attends to every other token, Self-Attention generates $O(N^2)$ matrix dimensions relative to sentence length N. This quadratic scaling is why long Context Windows consume significant GPU memory and API costs.
- Why GPUs Are Essential: Over 90% of Transformer computation consists of large-scale parallel matrix multiplications ($A \times B$). GPUs and NPUs with thousands of small arithmetic cores are essential for LLM training and inference servers.
- The Core of RAG and Prompting: Retrieval-Augmented Generation (RAG) injects relevant context directly into the model's Q, K, V attention space, guiding Self-Attention weights to focus on factual source tokens.
From dense embeddings to parallel Self-Attention, modern LLMs execute language comprehension through continuous, structured matrix operations.

댓글
GitHub 계정으로 로그인하면 댓글을 남길 수 있습니다. 댓글은 GitHub Discussions를 통해 운영됩니다.