Skip to content

[SOFT-2972] what is the transformers#49

Merged
opus24 merged 7 commits intomainfrom
SOFT-2972-what-is-the-transformers
Mar 11, 2026
Merged

[SOFT-2972] what is the transformers#49
opus24 merged 7 commits intomainfrom
SOFT-2972-what-is-the-transformers

Conversation

@opus24
Copy link
Copy Markdown
Contributor

@opus24 opus24 commented Mar 9, 2026

기본적인 Transformer 연산을 GPT-2를 예시로 설명한 글입니다.

하단의 리스트를 중점적으로 봐주시면 감사드립니다.

  • 나열한 연산 중 틀린 부분이 있는지
  • 전체적으로 적당한 깊이로 설명했는지
  • 이해가지 않는 비유는 없는지

@opus24 opus24 requested a review from a team as a code owner March 9, 2026 03:57
@gemini-code-assist
Copy link
Copy Markdown
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

이 PR은 Transformer 아키텍처에 대한 심층적인 이해를 돕기 위한 새로운 콘텐츠를 추가합니다. LLM의 핵심 구성 요소와 작동 방식, 그리고 성능 최적화를 위한 KV 캐시 관련 기법들을 상세히 설명하며, 독자들이 내용을 쉽게 파악할 수 있도록 영어와 한국어 두 가지 언어로 제공됩니다. 또한, 콘텐츠의 명확성을 검증하기 위한 질문 목록도 포함되어 있습니다.

Highlights

  • 새로운 Transformer 아키텍처 설명 글 추가: Transformer 아키텍처의 기본 원리, 주요 구성 요소(Token Embedding, Layer Normalization, Self-Attention, Residual Connection, FFN, LM Head) 및 GPT-2를 예시로 한 상세한 동작 방식을 설명하는 글이 영어와 한국어 버전으로 각각 추가되었습니다.
  • KV 캐시 최적화 기법 소개: Attention 연산의 병목 현상과 KV 캐시의 메모리/대역폭 문제를 다루고, 이를 해결하기 위한 MHA, MQA, GQA, MLA 등 다양한 KV 캐시 아키텍처 비교 및 장단점이 설명되었습니다.
  • 독자 검증용 질문 목록 추가: 한국어 Transformer 설명 글의 이해도를 검증하기 위한 8가지 질문 목록이 별도 파일로 추가되었습니다.
Changelog
  • content/posts/what-is-the-transformers/index.en.md
    • 새로운 영어 Transformer 아키텍처 설명 글을 추가했습니다.
  • content/posts/what-is-the-transformers/index.ko.md
    • 새로운 한국어 Transformer 아키텍처 설명 글을 추가했습니다.
  • content/posts/what-is-the-transformers/reader-test-questions.md
    • 한국어 Transformer 글에 대한 독자 검증용 질문 목록을 추가했습니다.
Activity
  • 현재까지 특별한 리뷰 활동이나 코멘트는 없습니다.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.


트랜스포머 세상, 어텐션이 핵심이라, LLM이 춤춘다.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a new, comprehensive blog post titled "Transformer World: A Deep Dive into the Building Blocks of LLMs," available in both English and Korean. The post explains the Transformer architecture, covering its three main stages (Token Embedding, Decoder Block, LM Head), detailing the six steps within the Decoder Block (Layer Normalization, Multi-Head Attention, Residual Connection, Feed-Forward Network), and elucidating concepts like Query, Key, and Value using analogies. It also delves into optimization techniques, specifically discussing KV Cache and comparing Multi-Head, Multi-Query, Grouped-Query, and Multi-Head Latent Attention architectures. Review comments primarily focus on improving the Korean version's readability and adherence to style guidelines, including adding spaces around bolded text, shortening long sentences, and formatting links descriptively. Additionally, both language versions need a description field for SEO and the removal of redundant H1 titles from the body. A supporting reader-test-questions.md file also requires an update to correct an inconsistency in the analogy used for Q, K, V, ensuring it aligns with the actual blog post content.

Note: Security Review has been skipped due to the limited scope of the PR.

Comment on lines +59 to +60
Transformer의 첫 단계는 사람의 언어를 컴퓨터가 이해할 수 있는 언어로 바꾸는 것입니다. 이를 **Token Embedding**이라고 부르며, 각 **토큰(token)** 을 긴 숫자 리스트, 즉 벡터로 바꿉니다. (실제로는 한 단어가 한 토큰으로 1:1 대응되지는 않습니다만, 이해의 편의를 위해 1:1 대응된다고 가정하겠습니다.) 이렇게 변환을 하게 되면 각 단어가 긴 숫자 리스트로 변환되고, 이를 벡터라고 부르며, 이 벡터가 대응되는 단어의 의미를 갖게 됩니다. 같은 단어라도 문장 안에서 어디에 있느냐에 따라 의미가 달라지기 때문에 **Positional Embedding**이라는 작업도 수행합니다.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

critical

블로그 스타일 가이드 1.1절에 따라, 굵은 글씨와 뒤따르는 한글 조사/어미 사이에 공백을 추가해야 합니다. 이 문단에서 여러 위반 사례가 발견되었습니다. (**Token Embedding**이라고, **토큰(token)**을, **Positional Embedding**이라는)

Suggested change
Transformer의 첫 단계는 사람의 언어를 컴퓨터가 이해할 수 있는 언어로 바꾸는 것입니다. 이를 **Token Embedding**이라고 부르며, 각 **토큰(token)** 을 긴 숫자 리스트, 즉 벡터로 바꿉니다. (실제로는 한 단어가 한 토큰으로 1:1 대응되지는 않습니다만, 이해의 편의를 위해 1:1 대응된다고 가정하겠습니다.) 이렇게 변환을 하게 되면 각 단어가 긴 숫자 리스트로 변환되고, 이를 벡터라고 부르며, 이 벡터가 대응되는 단어의 의미를 갖게 됩니다. 같은 단어라도 문장 안에서 어디에 있느냐에 따라 의미가 달라지기 때문에 **Positional Embedding**이라는 작업도 수행합니다.
Transformer의 첫 단계는 사람의 언어를 컴퓨터가 이해할 수 있는 언어로 바꾸는 것입니다. 이를 **Token Embedding** 이라고 부르며, 각 **토큰(token)** 을 긴 숫자 리스트, 즉 벡터로 바꿉니다. (실제로는 한 단어가 한 토큰으로 1:1 대응되지는 않습니다만, 이해의 편의를 위해 1:1 대응된다고 가정하겠습니다.) 이렇게 변환을 하게 되면 각 단어가 긴 숫자 리스트로 변환되고, 이를 벡터라고 부르며, 이 벡터가 대응되는 단어의 의미를 갖게 됩니다. 같은 단어라도 문장 안에서 어디에 있느냐에 따라 의미가 달라지기 때문에 **Positional Embedding** 이라는 작업도 수행합니다.
References
  1. 굵은 글씨 마커 ** 바로 뒤에 한글 조사나 어미가 올 경우, 렌더링 오류를 방지하기 위해 사이에 공백을 추가해야 합니다. (link)


![AI 도구 예시](images/AI_tools.png)

어떤 도구라도 잘 쓰기 위해서는 도구가 어떻게 생겼는지 자세하게 알아야 한다고 생각합니다. 따라서 이번 글에서는 Transformer 연산이 어떤 배경에서 등장하게 되었는지 먼저 알아보고, 연산이 어떻게 생겼는지 이해한 후, 마지막으로 연산의 병목과 이를 해결하기 위한 기초적인 최적화 기법 몇 가지를 살펴보고자 합니다.
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

블로그 스타일 가이드 2.1절에 따라 가독성을 위해 문장을 50자 내외로 작성하는 것을 권장합니다. 이 문장은 145자로 매우 길어 독자가 이해하기 어려울 수 있습니다. 글의 목적을 여러 문장으로 나누어 설명하면 더 명확하게 전달할 수 있습니다.

Suggested change
어떤 도구라도 잘 쓰기 위해서는 도구가 어떻게 생겼는지 자세하게 알아야 한다고 생각합니다. 따라서 이번 글에서는 Transformer 연산이 어떤 배경에서 등장하게 되었는지 먼저 알아보고, 연산이 어떻게 생겼는지 이해한 후, 마지막으로 연산의 병목과 이를 해결하기 위한 기초적인 최적화 기법 몇 가지를 살펴보고자 합니다.
따라서 이번 글에서는 Transformer 연산이 어떤 배경에서 등장하게 되었는지 먼저 알아봅니다. 그다음으로 연산이 어떻게 생겼는지 이해하고, 마지막으로 연산의 병목과 이를 해결하기 위한 기초적인 최적화 기법 몇 가지를 살펴보겠습니다.
References
  1. 가독성을 위해 문장 길이는 50자 내외로 유지하고, 복잡한 설명은 여러 문장으로 나누는 것을 권장합니다. 이 문장은 145자로 매우 깁니다. (link)

Comment on lines +1 to +14
---
date: '2026-03-05T10:00:00+09:00'
draft: false
title: 'Transformer World: A Deep Dive into the Building Blocks of LLMs'
cover:
image: "images/transformer-cover.png"
alt: "Transformer Architecture"
caption: "Transformer Architecture"
relative: true
authors: [Hyunjun Park]
tags: ["Transformer", "LLM", "Attention", "GPT", "LLaMA", "KV Cache"]
categories: ["AI", "Deep Learning"]
summary: 'A hands-on walkthrough of Transformer-based LLM internals — from each module's role to key optimization techniques.'
comments: true
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

블로그 스타일 가이드 4절에 따르면, description 필드는 SEO 최적화를 위해 필요한 항목입니다. summary와 비슷하거나 조금 더 긴 설명을 추가하는 것을 권장합니다.

comments: true
---

# Transformer World: A Deep Dive into the Building Blocks of LLMs
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

블로그 스타일 가이드 3.1절에 따르면, H1 제목(#)은 frontmatter의 title로 자동 생성되므로 본문에서는 사용하지 않아야 합니다. 중복된 제목이므로 이 줄을 삭제하는 것이 좋습니다.


### KV Cache Architecture Comparison (MHA, MQA, GQA, MLA)

There are four main approaches depending on how KV is stored and shared: MHA, MQA, GQA, and MLA. The core trade-off is between **accuracy (expressiveness)** and **KV cache size (memory/bandwidth)**. A paper that visually illustrates these differences well is attached below. (https://arxiv.org/pdf/2503.11486)
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

블로그 스타일 가이드 3.3절에 따라, 링크는 [설명 텍스트](URL) 형식을 사용해야 합니다. 독자가 링크의 내용을 쉽게 파악할 수 있도록 설명 텍스트를 추가하는 것이 좋습니다.

Suggested change
There are four main approaches depending on how KV is stored and shared: MHA, MQA, GQA, and MLA. The core trade-off is between **accuracy (expressiveness)** and **KV cache size (memory/bandwidth)**. A paper that visually illustrates these differences well is attached below. (https://arxiv.org/pdf/2503.11486)
There are four main approaches depending on how KV is stored and shared: MHA, MQA, GQA, and MLA. The core trade-off is between **accuracy (expressiveness)** and **KV cache size (memory/bandwidth)**. A [paper](https://arxiv.org/pdf/2503.11486) that visually illustrates these differences well is attached below.

comments: true
---

# Transformer World: LLM의 기본 구조 뜯어보기
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

블로그 스타일 가이드 3.1절에 따르면, H1 제목(#)은 frontmatter의 title로 자동 생성되므로 본문에서는 사용하지 않아야 합니다. 중복된 제목이므로 이 줄을 삭제하는 것이 좋습니다.

References
  1. H1(#)은 페이지 제목에만 사용해야 하며, 본문에서는 H2(##)부터 시작해야 합니다. 본문의 H1 제목은 frontmatter의 title과 중복됩니다. (link)


### KV Cache Architecture 비교 (MHA, MQA, GQA, MLA)

KV를 어떻게 저장·공유하느냐에 따라 크게 4가지 방식(MHA, MQA, GQA, MLA)으로 나눌 수 있습니다. 핵심 trade-off는 **정확도(표현력)** 와 **KV cache 크기(메모리·대역폭)** 사이의 균형이며, 이 차이를 시각적으로 잘 풀어준 논문이 있어 사진자료 첨부드립니다.(https://arxiv.org/pdf/2503.11486)
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

블로그 스타일 가이드 3.3절에 따라, 링크는 [설명 텍스트](URL) 형식을 사용해야 합니다. 독자가 링크의 내용을 쉽게 파악할 수 있도록 설명 텍스트를 추가하는 것이 좋습니다.

Suggested change
KV를 어떻게 저장·공유하느냐에 따라 크게 4가지 방식(MHA, MQA, GQA, MLA)으로 나눌 수 있습니다. 핵심 trade-off는 **정확도(표현력)****KV cache 크기(메모리·대역폭)** 사이의 균형이며, 이 차이를 시각적으로 잘 풀어준 논문이 있어 사진자료 첨부드립니다.(https://arxiv.org/pdf/2503.11486)
KV를 어떻게 저장·공유하느냐에 따라 크게 4가지 방식(MHA, MQA, GQA, MLA)으로 나눌 수 있습니다. 핵심 trade-off는 **정확도(표현력)****KV cache 크기(메모리·대역폭)** 사이의 균형이며, 이 차이를 시각적으로 잘 풀어준 [논문](https://arxiv.org/pdf/2503.11486)이 있어 사진자료 첨부드립니다.
References
  1. 링크는 [descriptive text](URL) 형식을 사용하여 독자가 내용을 쉽게 파악할 수 있도록 해야 합니다. 단순 URL을 그대로 노출하는 것은 피해야 합니다. (link)

→ 문서: 직렬 vs 병렬, "Attention Is All You Need" 섹션에서 설명됨.

3. **Query, Key, Value는 각각 무슨 의미인가요?**
→ 문서: Q=질문/찾고 싶은 것, K=색인/태그, V=실제 내용, fluffy blue creature 비유로 설명됨.
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

이 검증 질문에서는 Q, K, V의 의미를 'fluffy blue creature' 비유로 설명했다고 언급되어 있지만, 실제 블로그 본문(index.ko.md)에는 해당 비유가 사용되지 않았습니다. 본문에서는 '명찰', '질문', '내용' 등의 비유를 사용하고 있습니다. 검증 질문이 본문 내용과 일치하도록 수정이 필요합니다.

@opus24 opus24 changed the title Soft 2972 what is the transformers [SOFT-2972] what is the transformers Mar 9, 2026
authors: [Hyunjun Park]
tags: ["Transformer", "LLM", "Attention", "GPT", "LLaMA", "KV Cache"]
categories: ["AI", "Deep Learning"]
summary: 'A hands-on walkthrough of Transformer-based LLM internals — from each module's role to key optimization techniques.'
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

여기서 문장의 시작과 끝이 ' '로 되어 있어서 hugo server 시에 에러가 발생합니다. (The Hugo build error is caused by an unescaped apostrophe ('s) inside a single-quoted YAML string. The ' in module's prematurely closes the string.)

아래처럼 수정하면 될 것 같습니다!

summary: "A hands-on walkthrough of Transformer-based LLM internals — from each module's role to key optimization techniques."

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

감사합니다 수정완료 하였습니다!


#### Q, K, V 생성과 직관적 의미

GPT-2 Medium의 입력토큰은 1024개를 넘을 수 없습니다. 각 토큰은 크기가 1024인 벡터로 변환되므로, 해당 모델의 Attention Input은 최대 [1024, 1024](=[seq_len, N_embed])가 됩니다. 여기에 서로 다른 **가중치 행렬** W_Q, W_K, W_V를 곱해 **Query(Q)** , **Key(K)** , **Value(V)** 라는 행렬을 만듭니다. 임베딩 차원(N_embed=1024)은 헤드 수(N_head=16)와 헤드당 차원(head_dim=64)로 나눠져 최종적으로 Q·K·V 행렬은 각각 [N_position, N_head, head_dim] 형태가 됩니다.
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

N_embed -> N_position 용어가 달라졌습니다.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

예리한 지적 감사드립니다 수정완료 하였습니다.


아까 N_head개만큼 헤드가 있다고 말씀드렸는데요, 하나의 헤드 안에서 Q와 K의 크기는 [N_position, head_dim] 입니다. K를 전치해 Kᵀ [head_dim, N_position]로 두고 **Score = Q · Kᵀ** 를 계산하면 [N_position, N_position] 행렬이 나옵니다. 행은 "현재 Query를 가진 토큰", 열은 "참조 가능한 모든 위치"이고, (i, j) 원소는 i번째 토큰이 j번째 토큰을 얼마나 중요하게 보는지에 대한 스코어입니다. Query와 Key 벡터가 가까울수록(정렬될수록) 내적이 커집니다.

사람도 왼쪽에서 오른쪽으로 글을 읽듯, Attention 연산에서도 **미래 토큰이 과거 토큰을 알 수 없도록** 해야 하고, 이를 위해 **마스킹** 기법을 사용합니다. "나보다 뒤에 있는 위치"의 Score를 Softmax 전에 −∞로 두면, Softmax 후에는 0이 되어, 뒤쪽 토큰은 앞쪽 토큰에 영향을 주지 않습니다. 즉 "뒤 토큰이 앞 토큰을 바꾸는 것"을 막는 것입니다.
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

과거 토큰이 미래 토큰을 알 수 없어야 하는거 아닌가요

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

예리한 지적 감사드립니다 수정완료 하였습니다2


- **장점**: KV cache를 원래 차원보다 훨씬 작은 latent 차원으로 압축하므로, GQA보다도 메모리 효율이 좋습니다. 동시에 head마다 독립적인 Q를 유지해 표현력을 크게 희생하지 않습니다.
- **단점**: latent projection을 위한 추가 연산(압축·복원 행렬곱)이 필요하고, 구현 복잡도가 높습니다. 압축 과정에서 정보 손실이 발생할 수 있어, 압축 비율을 잘 조절해야 합니다.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

잘 읽었습니다! 전 개인적으로 이런 튜닝포인트가 있는데 ,
어떤 상황에서 뭘 써야하는거야? 라든가, 빠른 개발로 인해 잊혀가는 것들도 있을 것 같은데, 그런 걸 좀 더 추가해주시면 어떨까요?

모든 튜닝이 항상 맞지는 않고 적절한 상황에 맞게 써야 의미가 있을 것 같은데 검토 부탁드립니다!

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

안그래도 part3가 다소 빈약하다고 생각하고 있었습니다. 좋은 피드백 감사드립니다!

![다음 단어 예측](images/next_prediction.png)

**Large Language Model(LLM)** 의 동작 방식을 수학적으로 표현하면 "주어진 텍스트에 이어질 다음 단어를 예측하는 정교한 수학 함수"입니다. 단, 한 단어를 확정적으로 고르는 것이 아니라, 가능한 모든 다음 단어에 **확률** 을 부여합니다. 그 확률 분포에서 매번 하나를 샘플링하기 때문에, 같은 질문을 해도 실행할 때마다 다른 답이 나올 수 있습니다. 학습은 엄청난 양의 텍스트를 처리하면서 이 예측을 점점 정확하게 만드는 과정입니다.
사람이 LLM에게 짧은 영화 대본을 물어보는 장면으로 예시를 들어보겠습니다. 사용자는 LLM에게 대본을 입력하고, LLM은 "어떤 문장이든 넣으면 그다음에 올 단어를 그럴듯하게 예측해 주는 마법의 기계"입니다. 우리는 그 기계에 대본을 넣고, 예측된 단어를 이어 붙이고, 다시 넣는 과정을 반복해 대본을 완성할 수 있습니다. 이것이 바로 우리가 채팅봇과 대화할 때 실제로 일어나는 일입니다.
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
사람이 LLM에게 짧은 영화 대본을 물어보는 장면으로 예시를 들어보겠습니다. 사용자는 LLM에게 대본을 입력하고, LLM은 "어떤 문장이든 넣으면 그다음에 올 단어를 그럴듯하게 예측해 주는 마법의 기계"입니다. 우리는 그 기계에 대본을 넣고, 예측된 단어를 이어 붙이고, 다시 넣는 과정을 반복해 대본을 완성할 수 있습니다. 이것이 바로 우리가 채팅봇과 대화할 때 실제로 일어나는 일입니다.
실 사용에서 LLM은 "어떤 문장이든 넣으면 그다음에 올 단어를 그럴듯하게 예측해 주는 마법의 기계"입니다. 사람이 LLM에게 짧은 영화 대본을 물어보는 장면으로 예시를 들어보겠습니다. 사용자는 LLM에게 대본을 입력하면, 이 마법의 기계는 예측된 단어를 이어 붙이고, 다시 넣는 과정을 반복해 대본을 완성합니다. 이것이 바로 우리가 채팅봇과 대화할 때 실제로 일어나는 일입니다.

요렇게 쓰면 어떨까요

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

두괄식 좋은 것 같습니다. 수정하였습니다 감사합니다!

Comment on lines +49 to +55
1. **Layer Normalization**
2. **Multi-Head Attention**
3. **Residual Connection**
4. **Layer Normalization**
5. **Feed-Forward Network (FFN)**
6. **Residual Connection**

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

그림으로 목록화 대체하는게 어떨까요?

Suggested change
1. **Layer Normalization**
2. **Multi-Head Attention**
3. **Residual Connection**
4. **Layer Normalization**
5. **Feed-Forward Network (FFN)**
6. **Residual Connection**


#### Attention이 해결하는 문제: 문맥에 따른 의미 결정

**tower** 로 예시를 들어보겠습니다. 처음에는 임베딩을 수행하면 "높은 구조물"이라는 일반적인 의미 방향으로 1024차원의 벡터가 생성됩니다. 이때 바로 앞에 **Eiffel** 이 오면, 그 벡터가 tower 쪽으로 정보를 보내 "에펠 탑"에 가까운 방향으로 갱신됩니다. 앞에 **miniature** 까지 있으면 "큰 것"과의 연관이 줄어들고 더 구체적인 의미로 바뀝니다. 한 토큰에서 다른 토큰으로의 정보 전달은 단어 하나를 넘어 긴 거리, 풍부한 문맥까지 포함할 수 있습니다. 추리 소설 끝부분 "Therefore the murderer was..."에서 다음 단어를 맞추려면, 마지막 벡터 **was** 가 앞선 전체 문맥의 정보를 흡수해야 합니다. Attention이 바로 그 "어떤 토큰이 어떤 토큰을 얼마나 참조할지"를 계산합니다.
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Image

그림이 하나 있으면 예시 상황 이해에 도움이 될 것 같습니다.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

허락받고 이미지 도용하겠습니다 감사합니다. (사실 이미 넣었습니다)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

영광입니다 ㅎㅎ


![Feed-Forward Network (FFN)](images/FFN.png)

이쯤되서 다시 리마인드해보면, 하나의 디코더 레이어는 총 6단계(Layernorm-Attention-Residual-Layernorm-FFN-Residual)로 이루어져 있습니다. Layernorm과 Residual은 중복이므로 **Feed-Forward Network(FFN)**을 마지막으로 살펴보겠습니다. FFN은 두 개의 **Linear** 레이어와 그 사이의 **Activation Function** 로 구성됩니다. 입력 [N_position, N_embed]에 첫 번째 Linear로 차원을 **확장** 하고, 활성화(예: GeLU)를 거친 뒤, 두 번째 Linear로 다시 차원을 **축소** 하여 [N_position, N_embed]를 만듭니다. 각 위치마다 독립적으로 같은 MLP가 적용된다고 보시면 되고(**position-wise FFN**), 이 연산은 Attention에서 모인 정보를 비선형 변환으로 더 복잡한 특징 공간에 매핑하는 역할을 합니다. 앞에서 말했던 6단계를 모두 수행하면 하나의 디코더 블록 연산이 끝이 나고, 동일 과정을 N번(GPT-2의 경우 24번) 반복하면 Decoder Block 연산이 모두 끝이 나게 됩니다.
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

렌더링 에러

Suggested change
이쯤되서 다시 리마인드해보면, 하나의 디코더 레이어는 총 6단계(Layernorm-Attention-Residual-Layernorm-FFN-Residual)로 이루어져 있습니다. Layernorm과 Residual은 중복이므로 **Feed-Forward Network(FFN)**을 마지막으로 살펴보겠습니다. FFN은 두 개의 **Linear** 레이어와 그 사이의 **Activation Function** 로 구성됩니다. 입력 [N_position, N_embed]에 첫 번째 Linear로 차원을 **확장** 하고, 활성화(예: GeLU)를 거친 뒤, 두 번째 Linear로 다시 차원을 **축소** 하여 [N_position, N_embed]를 만듭니다. 각 위치마다 독립적으로 같은 MLP가 적용된다고 보시면 되고(**position-wise FFN**), 이 연산은 Attention에서 모인 정보를 비선형 변환으로 더 복잡한 특징 공간에 매핑하는 역할을 합니다. 앞에서 말했던 6단계를 모두 수행하면 하나의 디코더 블록 연산이 끝이 나고, 동일 과정을 N번(GPT-2의 경우 24번) 반복하면 Decoder Block 연산이 모두 끝이 나게 됩니다.
이쯤되서 다시 리마인드해보면, 하나의 디코더 레이어는 총 6단계(Layernorm-Attention-Residual-Layernorm-FFN-Residual)로 이루어져 있습니다. Layernorm과 Residual은 중복이므로 **Feed-Forward Network(FFN)** 을 마지막으로 살펴보겠습니다. FFN은 두 개의 **Linear** 레이어와 그 사이의 **Activation Function** 로 구성됩니다. 입력 [N_position, N_embed]에 첫 번째 Linear로 차원을 **확장** 하고, 활성화(예: GeLU)를 거친 뒤, 두 번째 Linear로 다시 차원을 **축소** 하여 [N_position, N_embed]를 만듭니다. 각 위치마다 독립적으로 같은 MLP가 적용된다고 보시면 되고(**position-wise FFN**), 이 연산은 Attention에서 모인 정보를 비선형 변환으로 더 복잡한 특징 공간에 매핑하는 역할을 합니다. 앞에서 말했던 6단계를 모두 수행하면 하나의 디코더 블록 연산이 끝이 나고, 동일 과정을 N번(GPT-2의 경우 24번) 반복하면 Decoder Block 연산이 모두 끝이 나게 됩니다.


Part 2에서 가장 중요한 연산은 단연 Attention인데요, Query와 Key를 곱하여 나오는 Score 행렬의 크기는 **context size의 제곱** 입니다. 토큰이 N개면 N×N 행렬이므로, 문맥이 길어질수록 연산량과 메모리가 빠르게 늘어납니다. 추론 시에는 이전 스텝에서 계산한 **Key** 와 **Value** 를 다시 쓰기 위해 **KV cache** 에 저장하지만, 문맥이 길수록 이 캐시가 너무나 커져서 문맥 길이·메모리·대역폭이 큰 병목이 됩니다.

예를 들어 **LLaMA-3-70B** 를 **bfloat16(bf16)** 기준으로 100만 토큰 문맥으로 돌린다고 하겠습니다. 모델 파라미터 70B × 2 byte ≈ 140GB입니다. KV cache는 2(K,V) × 배치 1 × 레이어 80 × KV head 8 × head 차원 128 × 시퀀스 1M × 2 byte 식으로 잡으면 약 328GB 수준이 될 수 있습니다. 한 토큰을 생성할 때 읽어야 할 메모리가 모델 + KV cache로 약 468GB이고, 초당 20 토큰을 만들려면 이론상 10TB/s급 메모리 대역폭이 필요하다는 식으로 이해하시면 됩니다.
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

10TB/s에 대한 감이 없는 독자를 위해....

Suggested change
예를 들어 **LLaMA-3-70B****bfloat16(bf16)** 기준으로 100만 토큰 문맥으로 돌린다고 하겠습니다. 모델 파라미터 70B × 2 byte ≈ 140GB입니다. KV cache는 2(K,V) × 배치 1 × 레이어 80 × KV head 8 × head 차원 128 × 시퀀스 1M × 2 byte 식으로 잡으면 약 328GB 수준이 될 수 있습니다. 한 토큰을 생성할 때 읽어야 할 메모리가 모델 + KV cache로 약 468GB이고, 초당 20 토큰을 만들려면 이론상 10TB/s급 메모리 대역폭이 필요하다는 식으로 이해하시면 됩니다.
예를 들어 **LLaMA-3-70B****bfloat16(bf16)** 기준으로 100만 토큰 문맥으로 돌린다고 하겠습니다. 모델 파라미터 70B × 2 byte ≈ 140GB입니다. KV cache는 2(K,V) × 배치 1 × 레이어 80 × KV head 8 × head 차원 128 × 시퀀스 1M × 2 byte 식으로 잡으면 약 328GB 수준이 될 수 있습니다. 한 토큰을 생성할 때 읽어야 할 메모리가 모델 + KV cache로 약 468GB이고, 초당 20 토큰을 만들려면 이론상 10TB/s급 메모리 대역폭이 필요하다는 식으로 이해하시면 됩니다. 최신 GPU인 NVIDIA B100의 메모리 대역폭이 최대 8TB/s이며 메모리 용량은 192GB에 불과하다는 것을 생각하면 어느정도 수준인지 감이 오실 겁니다.

Copy link
Copy Markdown
Contributor

@DongHyunnn DongHyunnn left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM! 좋은 글 잘 읽고 갑니다.

@opus24 opus24 merged commit 27af795 into main Mar 11, 2026
1 check passed
@opus24 opus24 deleted the SOFT-2972-what-is-the-transformers branch March 11, 2026 08:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants