Learn How to Make AI Models w/ ML: 2. Transformers
▶ YouTube 원본01한국어 번역 · Korean
트랜스포머(Transformer) 완벽 해부: 머신러닝으로 AI 모델 만들기 2편
원본: https://www.youtube.com/watch?v=4KcY7pdIVj0 · 업로드: 2026-04-03 · 길이: 45m · 채널: Onchain AI Garage
들어가며
이 시리즈의 두 번째 에피소드에 오신 것을 환영한다. 1편이 파이토치(PyTorch)라는 “도구”를 익히는 시간이었다면, 이번 편은 그 도구로 짓는 “건물의 설계도” 자체를 이해하는 자리다. GPT, 클로드(Claude), 라마(Llama) 같이 우리가 아는 거의 모든 대형 언어 모델은 예외 없이 트랜스포머(Transformer) 아키텍처 위에 서 있다. 그래서 이 한 편은 특히 중요하다.
1. 트랜스포머 이전: RNN과 LSTM의 한계
2017년 이전, 최고의 언어 모델은 RNN(Recurrent Neural Network)과 LSTM(Long Short-Term Memory) 구조를 사용했다. 이들은 텍스트를 앞에서부터 한 단어씩 순차적으로 처리한다. 여기엔 두 가지 고질적인 문제가 있었다.
첫째는 속도다. 다섯 번째 단어를 처리하려면 네 번째 단어의 결과가 필요하고, 네 번째는 세 번째 결과가 있어야 한다. 병렬화가 원천적으로 불가능하니 학습이 고통스럽게 느리다. 둘째는 메모리다. 200번째 단어에 도달할 즈음이면 1번째 단어의 정보는 이미 흐릿해져 있다. 긴 사슬을 지나면서 정보가 압축되고 소실되는 것이다. 장기 프로젝트를 오래 진행하다 보면 초반에 무슨 이야기를 했는지 기억하기 어려워지는 것과 비슷하다.
2. “Attention Is All You Need”: 혁명의 시작
트랜스포머는 이 두 문제를 한 방에 해결했다. 단어를 하나씩 읽는 대신 모든 단어를 동시에 처리하고, 어떤 단어든 다른 어떤 단어를 직접 “참조”할 수 있게 한 것이다. 200번째 단어가 1번째 단어를 곧바로 쳐다볼 수 있으니, 사슬을 타고 정보를 전달할 필요가 없다. 결과적으로 모델은 더 빨라졌고, 긴 문맥에서도 강해졌다.
이 아이디어를 담은 논문 제목이 바로 “Attention Is All You Need”다. 핵심은 이름 그대로다. 이제 필요 없어진 것은 순차 재귀 처리이고, 제대로 설계된 어텐션(attention) 하나면 충분하다는 선언이다.
3. 어텐션이란 무엇인가
어텐션의 직관은 간단하다. “어떤 단어는 다른 단어보다 더 중요하다.” 예를 들어 “The cat sat on the mat because it was tired”라는 문장을 읽다가 “it”에 도달했다고 해 보자. 우리의 뇌는 이전 단어 전체에 똑같은 비중을 주지 않는다. 자동으로 가장 관련된 단어, 여기서는 “cat”에 집중하고 “mat”은 상대적으로 덜 본다. 우리가 너무나 자연스럽게 하는 이 과정을 수식으로 정리한 것이 어텐션이다.
모델이 어떤 단어를 처리할 때, 그 단어는 다른 모든 단어에 대해 “지금 너는 나에게 얼마나 관련 있니?”라는 점수를 계산한다. 점수가 높으면 집중해야 할 대상이고, 낮으면 거의 무시해도 되는 대상이다. 이 메커니즘 덕분에 1번 단어와 500번 단어가 바로 옆 단어만큼이나 쉽게 소통할 수 있다. RNN이 한 사람씩 귓속말을 전하는 “전화 게임”이었다면, 트랜스포머는 방 안의 모든 사람이 서로 직접 대화할 수 있는 구조다.
4. Query, Key, Value: 어텐션의 삼위일체
단어들이 서로를 “찾을” 수 있으려면 메커니즘이 필요하다. 그래서 모든 단어는 세 종류의 벡터를 만들어 낸다. 쿼리(Query, Q), 키(Key, K), 밸류(Value, V)다.
- 쿼리는 그 단어가 던지는 “질문”이다. 앞선 예에서 “it”의 쿼리는 “나의 지시 대상은 누구인가?”에 해당한다. 물론 모델이 영어로 묻는 건 아니고, 숫자 벡터로 “지금 내가 어떤 정보를 원하는지”를 암호화한다.
- 키는 각 단어가 달고 있는 “이름표”다. “cat”의 키는 “나는 명사이고 주체이며 동물이다” 같은 정보를 담는다.
- 밸류는 실제로 전달될 “내용물”이다. 쿼리가 키와 잘 맞아떨어지면, 그 단어의 밸류가 실제 의미 정보로서 흘러간다.
검색 엔진 비유가 잘 맞는다. 쿼리(질문)를 던지면, 각 문서의 키(메타데이터)와 대조해 가장 잘 맞는 것을 찾고, 그 문서의 밸류(본문)를 돌려받는 것이다. 중요한 점은 Q, K, V가 사람이 손으로 설계한 게 아니라는 것이다. 각 단어의 임베딩(embedding)에 세 개의 학습 가능한 가중치 행렬을 곱해서 얻는다. “명사를 찾아라” 같은 규칙은 아무도 프로그래밍해 주지 않는다. 모델이 학습 과정에서 스스로 발견한다.
5. 어텐션 계산: 4단계
어텐션 계산은 네 단계로 이루어진다.
- 비교(Compare): 각 쿼리를 다른 모든 단어의 키와 내적(dot product)한다. 방향이 비슷한 벡터일수록 점수가 크고, 무관할수록 작다.
- 스케일(Scale): 벡터 차원이 커질수록 내적 값이 너무 커지니, 차원의 제곱근으로 나눠 준다. 한 단어가 수치상 지배하지 못하도록 하는 실용적인 장치다.
- 소프트맥스(Softmax): 원시 점수를 확률 분포로 바꾼다. 예컨대 8, 2, 0.5 같은 점수가 0.85, 0.12, 0.03 처럼 합이 1이 되는 가중치로 변환된다.
- 가중합(Weighted Sum): 각 단어의 밸류에 가중치를 곱한 뒤 모두 더한다. 결과는 “가장 관련 있는 단어들의 정보가 섞인 새로운 벡터”다.
이 과정의 핵심은 이렇다. 모든 단어는 문맥 속에서 자신에게 중요한 단어들의 정보를 흡수한 새로운 표현(representation)으로 거듭난다. 예문의 “it”은 이제 “cat”의 의미를 상당 부분 품은 벡터가 되는 것이다.
6. 멀티헤드 어텐션(Multi-Head Attention)
한 번의 어텐션만으로는 한 가지 유형의 관계만 잡아낼 수 있다. 그러나 단어는 여러 관계를 동시에 맺는다. “The tired cat sat”에서 “cat”은 “tired”와는 형용사-수식 관계, “sat”과는 주어-동사 관계, “The”와는 한정사 관계를 갖는다. Q/K/V 가중치 하나만으론 이 다양한 관계를 전부 포착하기 어렵다.
해법은 여러 개의 어텐션을 병렬로 돌리는 것이다. 각각 독립된 Q/K/V 가중치 행렬을 갖는 이 병렬 유닛을 헤드(head) 라 부른다. 8개 헤드를 쓰면 8개의 독립 어텐션 연산이 동시에 돌아간다. 재미있는 점은 어느 헤드가 무엇을 맡아야 할지 아무도 지정해 주지 않는다는 것이다. 학습 손실을 줄이는 과정에서 각 헤드는 자연스럽게 서로 다른 패턴으로 분화한다. 연구에 따르면 어떤 헤드는 구문(syntax), 어떤 헤드는 지시어 해소(co-reference), 어떤 헤드는 의미(semantics)를 추적하는 식으로 역할이 갈린다.
모든 헤드의 출력은 옆으로 이어 붙인 뒤 선형층(linear layer)을 거쳐 하나의 표현으로 합쳐진다. GPT-small은 12 헤드, GPT-3는 96 헤드, Llama 2 70B는 64 헤드를 쓴다.
7. 포지셔널 인코딩(Positional Encoding): 순서가 중요하다
어텐션은 모든 단어 쌍의 유사도를 계산하지만, 단어들을 “집합”처럼 취급할 뿐 순서를 모른다. 그래서 “dog bites man”과 “man bites dog”가 같은 점수를 낼 위험이 있다. 영어는 물론 대부분의 언어에서 어순은 의미 그 자체다.
해결책은 어텐션이 수행되기 전에 각 단어 임베딩에 고유한 “위치 패턴”을 더해 주는 것이다. 원 논문은 사인·코사인 기반의 고정된 파형을 썼지만, 현대 모델들은 대체로 RoPE(Rotary Position Embedding) 를 사용한다. RoPE는 위치값을 더하는 대신, 위치에 비례한 각도만큼 쿼리와 키 벡터를 회전시킨다. 학습 없이 작동하는 수학적 연산이면서도 상대 거리를 우아하게 표현할 수 있어 최신 LLM의 표준이 되었다.
8. 트랜스포머 블록: 반복되는 네 층
트랜스포머는 거대한 하나의 덩어리가 아니다. 작은 “블록”이 여러 번 반복된 구조다. GPT-2는 12개, GPT-3는 96개의 블록을 쌓는다. 각 블록의 구성은 동일하다.
- 멀티헤드 어텐션: 단어들이 서로 “이야기”하며 관련 정보를 모으는 수집 단계.
- 레이어 정규화(Layer Normalization)와 잔차 연결(Residual Connection): 값이 지나치게 커지거나 작아지지 않도록 재조정한다. 잔차 연결은 입력이 직접 출력으로 건너뛰는 지름길을 만들어, 깊은 네트워크에서 원래 정보가 소실되지 않게 한다. 복사본의 복사본의 복사본이 되어 신호가 흐려지는 일을 막는 장치다.
- 피드 포워드 네트워크(Feed-Forward Network): 어텐션이 수집해 준 문맥을 각 단어가 독립적으로 가공한다. 단어 간 상호작용은 없다. 세 단계로 구성되는데, 먼저 확장(expand) 단계에서 차원을 4배로 부풀린다(예: 3,072개의 “검출기”를 만드는 셈이다). 다음 활성화(activate) 단계에서 ReLU나 GLU 같은 함수를 거쳐 관련 없는 검출기는 0으로 눌러 버린다. 마지막 수축(contract) 단계에서 원래 차원으로 돌아온다. 연구에 따르면 이 피드 포워드 층은 일종의 “지식 저장소” 역할을 한다. 어떤 뉴런은 수도 도시 이름에, 어떤 뉴런은 과거 시제 동사에, 또 어떤 뉴런은 파이썬 문법에 반응하는 식이다.
- 또 한 번의 레이어 정규화: 다음 블록으로 넘어가기 전에 출력값을 안정화한다.
블록이 쌓일수록 표현은 점점 정교해진다. 초반 블록은 기본적인 구문을, 중간 블록은 의미를, 후반 블록은 추상적 추론과 과제 특화 패턴을 담는 경향이 있다.
9. 인코더, 디코더, 그리고 디코더 온리
트랜스포머를 활용하는 방식은 세 가지다. 인코더(Encoder) 는 양방향(bidirectional)으로 작동해 모든 단어가 왼쪽과 오른쪽 단어를 모두 본다. 이해에 강해서 BERT가 대표 사례다. 텍스트를 생성하진 않는다. 디코더(Decoder) 는 각 단어가 자기보다 앞선 단어만 볼 수 있다. 텍스트 생성, 챗봇, 코드 완성에 쓰이며 GPT, Claude, Llama 등 현대 LLM은 모두 디코더 온리(decoder-only) 구조다. 인코더-디코더 는 원 논문의 형태이지만 요즘은 드물어졌다.
디코더 구조에서는 학습 중 미래 단어를 “훔쳐보지” 못하도록 코절 마스크(causal mask) 를 쓴다. 허용/차단 관계를 담은 삼각 행렬로 구현되며, 위치 5의 단어를 예측할 때는 1~4 위치만 볼 수 있게 강제한다. 학습 시에는 효율을 위해 전체 시퀀스를 한 번에 넣기 때문에, 마스크가 없으면 모델이 정답을 보고 답을 맞히는 꼴이 된다. 생성 시점에는 애초에 미래 토큰이 존재하지 않으므로 이 제약은 자연스럽다.
모델은 한 번에 한 토큰(token) 씩 텍스트를 생성한다. 토큰은 대략 3~4글자 정도로, 흔한 단어는 대개 하나의 토큰이지만 긴 단어는 여러 토큰으로 쪼개진다. 이 분할은 토크나이저(tokenizer)가 담당한다. 각 출력이 다음 단계의 입력이 되는 방식을 자기 회귀(auto-regressive) 생성 이라 부른다. 모델 내부는 병렬이지만 생성 그 자체는 순차일 수밖에 없다.
10. 전체 흐름: 원문에서 예측까지
트랜스포머의 전 과정은 다음과 같다.
- 토큰화: 원문을 토큰 ID 시퀀스, 즉 숫자 벡터 집합으로 변환한다.
- 임베딩 + 포지셔널 인코딩: 각 토큰을 벡터로 바꾸고 위치 정보를 주입한다.
- 트랜스포머 블록 N회: 어텐션과 피드 포워드를 반복해 표현을 다듬는다.
- 예측: 마지막 토큰의 표현을 어휘 사전 크기의 점수 벡터로 투영하고, 점수가 가장 높은 토큰이 다음 단어가 된다. “the price of” 다음에 “bitcoin”이 72%, “ethereum”이 8% 같은 분포가 나오는 식이다.
11. 실전: 미니 GPT를 밑바닥부터 만들어 보기
이론을 끝내고 영상 후반부는 실습이다. 원피스(One Piece) 위키 시놉시스를 학습 데이터로 삼고, 문자 단위 토크나이저로 어휘를 작게 유지한 뒤 작은 디코더 온리 모델을 짜 본다. 단일 헤드 어텐션을 만들어 4단계(비교 → 스케일 → 소프트맥스 → 가중합)를 직접 관찰하고, 이를 nn.Module로 감싸 4 헤드, 32차원 멀티헤드 어텐션으로 확장한다. torch.tril로 삼각 마스크를 만들어 코절 마스킹을 구현하고, 피드 포워드(확장-활성화-수축)와 잔차 연결까지 얹어 트랜스포머 블록을 완성한다.
전체 미니 GPT는 임베딩(약 46K 파라미터), 어텐션(약 262K), 피드 포워드(약 526K)로 구성돼 총 85만 파라미터 정도다. 피드 포워드가 가장 큰 비중을 차지하는데, 이는 앞서 설명한 “4배 확장” 때문이다. 3MB 남짓한 원피스 텍스트로 3,000 스텝을 돌리자 학습 손실이 1.5 밑으로 떨어지고, 검증 손실도 함께 떨어져 과적합 조짐은 아직 없다. 생성 결과는 뜻이 통하는 문장은 아니지만 “Luffy”, “Buggy”, “Sanji” 같은 고유명사가 등장하고, 쉼표·마침표, 대문자 시작 같은 구조적 패턴이 잡힌다. “원피스 풍의 의미 없는 말”, 그러나 분명 “원피스 풍”이다.
이어 온도(temperature) 개념도 살핀다. 소프트맥스에 들어가기 전 점수를 온도로 나눈다. 온도가 낮으면 점수 차이가 극대화돼 가장 확률 높은 토큰만 뽑히니 출력이 안전하고 반복적이 되고, 온도가 높으면 격차가 줄어들어 더 창의적이지만 엉뚱해지기 쉽다. 0.3, 1.0, 1.5 세 값으로 비교해 보면 저온 쪽이 그나마 문장 형태를 지니고, 고온은 거의 무작위 글자 나열이 된다.
마지막으로 스텝 수를 3,000에서 10,000으로 늘리자 학습 손실은 1.15까지 떨어진다. 다만 검증 손실은 1.37 근처에서 정체하며 약간의 과적합 조짐을 보인다. 이 크기의 모델에겐 한계가 있는 셈이다. 그래도 결과물은 눈에 띄게 나아져, 대부분 실제 영어 단어로 구성된 문장이 나온다.
12. 기억해야 할 다섯 가지
- 어텐션(Attention): 모든 단어가 다른 모든 단어를 보고 관련 문맥을 찾는 메커니즘. Q, K, V가 핵심 도구다.
- 멀티헤드 어텐션: 여러 어텐션을 병렬로 돌려 다양한 유형의 관계를 동시에 포착한다.
- 포지셔널 인코딩: 단어 순서를 명시적으로 주입하는 장치. 현대 모델은 RoPE가 표준이다.
- 트랜스포머 블록: 어텐션 → 정규화 → 피드 포워드 → 정규화가 한 단위로 반복된다. 피드 포워드 층은 모델 파라미터의 약 2/3를 차지하는 실질적 “지식 창고”다.
- 디코더 온리와 코절 마스킹: 현대 LLM은 디코더 온리 구조로 한 번에 한 토큰씩 생성하며, 학습 중 미래 토큰을 못 보도록 마스킹한다.
마치며
다음 편은 허깅 페이스(Hugging Face)다. 이번처럼 밑바닥부터 학습하는 대신, 인터넷 규모 데이터로 이미 사전 학습된 모델을 가져와 활용하는 방식으로 넘어갈 예정이다. 트랜스포머의 뼈대를 이해한 지금이 그 다음 단계로 넘어가기에 가장 좋은 시점이다.
02리서치 문서 · Document
트랜스포머(Transformer)는 어떻게 현대 AI의 표준이 되었나 — 어텐션, 멀티헤드, 디코더 온리까지
원본 영상: YouTube — Learn How to Make AI Models w/ ML: 2. Transformers · 채널: Onchain AI Garage · 업로드: 2026-04-03
서론 — 왜 지금도 “트랜스포머”인가
ChatGPT 이후 수년이 흐른 지금도 우리는 여전히 2017년에 발표된 한 편의 논문 위에 살고 있다. 구글의 연구자 8인이 쓴 “Attention Is All You Need”는 순환 신경망(RNN)과 합성곱 신경망(CNN)을 모두 걷어내고, 오직 어텐션만으로 언어 모델을 만들 수 있음을 보인 논문이다. 위키피디아의 정리에 따르면 이 논문은 “어텐션 메커니즘에 기반한 트랜스포머 아키텍처를 소개한, 딥러닝 역사의 획을 그은 문서”로 기록된다(Attention Is All You Need — Wikipedia).
Onchain AI Garage의 머신러닝 시리즈 두 번째 에피소드는 바로 이 트랜스포머의 뼈대를 풀어 설명하고, 작은 디코더 온리 모델을 직접 파이토치로 구현해 학습시키는 실습으로 마무리된다. 이 글에서는 영상의 흐름을 따라가며, 트랜스포머가 왜 이렇게 강력한지, 그리고 2026년 현재까지도 이 구조가 어떻게 진화하고 있는지를 정리한다.
본론 1. RNN의 벽을 넘어서 — 병렬성과 장거리 의존
트랜스포머 이전의 자연어 처리는 RNN, 특히 LSTM이 주도했다. 문제는 두 가지였다. 첫째, 시퀀스를 앞에서 끝까지 하나씩 흘려보내야 하니 병렬화가 불가능 했다. 둘째, 긴 시퀀스에서 초반 정보가 점차 흐려지는 장거리 의존(long-range dependency) 문제 가 심각했다. 200번째 단어를 처리할 무렵이면 첫 단어의 기억은 이미 압축되어 희미해진다.
트랜스포머는 이 두 가지를 “모든 단어가 모든 단어를 직접 본다”는 한 줄로 돌파했다. 위키피디아의 트랜스포머 설명이 강조하듯, 트랜스포머는 재귀와 합성곱을 완전히 버리고 순수하게 어텐션 메커니즘만으로 작동한다. 그 결과 GPU 병렬 연산과 맞물려 학습 속도가 폭발적으로 빨라졌고, 모델이 수백~수천 토큰 떨어진 단어까지 동일한 비용으로 참조할 수 있게 됐다.
영상 화자는 이 변화를 “RNN은 귓속말을 돌리는 전화 게임, 트랜스포머는 방 안 모든 사람이 서로 직접 대화할 수 있는 구조”라는 비유로 표현한다. 정보의 손실 없이, 단어 간 거리가 0처럼 느껴지는 새로운 연산 공간이 열린 셈이다.
본론 2. 어텐션의 심장 — Query, Key, Value
어텐션의 핵심 직관은 “어떤 단어는 다른 단어보다 더 중요하다”는 사실이다. 모델이 어떤 단어를 처리할 때, 그 단어는 다른 모든 단어에 대해 “너는 지금 나에게 얼마나 관련 있니?”라는 점수를 매긴다. 이 점수를 소프트맥스로 확률 분포화한 뒤, 각 단어의 “내용물”을 가중합해 새로운 표현을 얻는다.
이 과정을 구현하기 위해 모든 단어는 학습된 세 가지 투영(projection)을 통해 쿼리(Query), 키(Key), 밸류(Value) 벡터를 만든다. Jay Alammar의 고전 설명글 The Illustrated Transformer가 보여 주듯, 이 셋은 검색 엔진에 비유하면 가장 직관적이다. 쿼리는 질문, 키는 각 문서의 메타데이터, 밸류는 실제 본문이다. 쿼리와 키가 비슷한 방향을 가리킬수록 내적 값이 커지고, 그 값이 어텐션 가중치가 된다.
중요한 포인트는 Q, K, V가 수작업으로 설계된 것이 아니라는 사실이다. 세 개의 가중치 행렬은 학습을 통해 결정되며, “무엇을 찾아야 하는가”는 모델이 데이터에서 스스로 발견한다. 누구도 “대명사의 선행사를 추적하라”고 가르치지 않지만, 손실을 줄이는 과정에서 모델은 그 패턴을 자연스럽게 학습한다.
본론 3. 멀티헤드 어텐션 — 여러 렌즈로 문맥을 보기
단어가 맺는 관계는 한 종류가 아니다. “The tired cat sat”에서 “cat”은 “tired”와는 수식 관계, “sat”과는 주어-동사 관계, “The”와는 한정사 관계를 동시에 맺는다. 단 한 세트의 Q/K/V로는 이 모든 관계를 균형 있게 담기 어렵다. 평균화가 오히려 각 관계의 선명도를 지워 버린다.
해답은 여러 개의 어텐션을 병렬로 돌리는 것 이다. 원 논문은 8개의 헤드를 사용했고, 각 헤드는 차원을 d_model / h = 64로 줄여 계산량을 단일 헤드 수준으로 유지한다. Towards AI의 “Attention Is All You Need” 딥다이브는 각 헤드가 “서로 다른 표현 부분공간(subspace)으로 입력을 투영해 데이터의 상이한 측면에 주목할 수 있게 한다”고 요약한다. 어떤 헤드는 단기 문법 관계를, 어떤 헤드는 장기 의미 맥락을 추적하는 식으로 자연스럽게 분업이 일어난다.
흥미로운 점은 이 분업이 전혀 지시되지 않는다는 것이다. 손실 함수라는 경쟁 압력만으로 헤드들은 서로 다른 전문화를 택한다. GPT-3는 96개의 헤드를, Llama 2 70B는 64개의 헤드를 쓰며, 모델이 커질수록 “관계의 차원”이 넓어진다. Poloclub의 Transformer Explainer 같은 시각화 도구를 쓰면 실제 모델에서 각 헤드가 어느 단어 쌍에 집중하는지를 눈으로 확인할 수 있다.
본론 4. 순서를 주입하는 법 — 사인파에서 RoPE까지
어텐션은 단어들을 집합처럼 취급한다. 그대로 두면 “dog bites man”과 “man bites dog”를 구분하지 못한다. 그래서 트랜스포머는 어텐션 이전에 각 토큰 임베딩에 위치 정보 를 주입한다. 원 논문은 사인·코사인 기반의 고정된 파형을 더하는 방식을 제안했지만, 현대 LLM의 사실상 표준은 RoPE(Rotary Position Embedding) 다.
RoFormer 논문이 제안한 RoPE는 위치값을 단순히 더하는 대신, 쿼리와 키 벡터를 위치에 비례한 각도만큼 “회전”시킨다. 이 회전은 복소 평면에서 절대 위치를 인코딩하면서도, 셀프 어텐션 내부에서는 자연스럽게 상대 위치 의존성으로 작동한다는 수학적 장점을 가진다. Medium의 RoPE 가이드에 따르면 RoPE는 “학습 파라미터가 0이고, 수학적으로 우아하며, 대규모 LLM에서 확장성이 증명된” 방식이어서 LLaMA, PaLM, GPT-NeoX 같은 대표적 모델이 모두 채택했다.
핵심은 이 설계가 긴 문맥으로의 외삽(extrapolation)에 훨씬 유리하다는 점이다. 학습 시 본 적 없는 길이에도 비교적 안정적으로 작동하기 때문에, 최근의 초장문 컨텍스트 모델에는 사실상 필수 재료가 되었다.
본론 5. 반복되는 블록과 디코더 온리의 승리
트랜스포머 본체는 거대한 단일 구조가 아니라 작은 블록의 반복 이다. 블록 하나는 “멀티헤드 어텐션 → 레이어 정규화 + 잔차 연결 → 피드 포워드 네트워크 → 레이어 정규화”로 구성된다. GPT-2는 12개, GPT-3는 96개를 쌓는다. 블록이 쌓일수록 표현은 점점 추상적이 된다. 초반 블록은 구문을, 중간은 의미를, 후반은 과제 특화 패턴을 담는 경향이 관찰된다.
특히 주목할 것은 피드 포워드 층이다. 이 층은 입력 차원을 4배로 부풀린 뒤 활성화 함수(ReLU나 GLU 계열)로 불필요한 “검출기”를 꺼 버리고 다시 원 차원으로 수축시킨다. 연구에 따르면 이 층은 모델이 배우는 사실성 지식의 주된 저장소 역할을 한다. 수도 이름, 과거 시제, 프로그래밍 문법처럼 개별 뉴런이 특정 개념에 반응하는 식이다. 영상 화자가 언급하듯, 피드 포워드는 흔히 모델 파라미터의 약 2/3을 차지한다.
사용 방식은 크게 세 가지다. 양방향 인코더(BERT), 단방향 디코더(GPT 계열), 그리고 원 논문의 인코더-디코더 다. Cameron Wolfe의 “Decoder-Only Transformers” 글이 지적하듯, 대부분의 현대 생성 LLM은 디코더 온리 구조로 수렴했다. 이유는 단순하다. 생성 시점에는 어차피 미래 토큰이 존재하지 않으니, 코절 마스킹으로 학습과 추론의 환경을 일치시키면 자연스럽고, 단일 구조로 모든 걸 처리할 수 있어 엔지니어링이 간결하다. Hugging Face 학습 플레이북의 모델 아키텍처 섹션 역시 “GPT 원안의 구조가 오늘날 대부분의 LLM에 거의 그대로 유지되고 있다”고 정리한다.
핵심 인사이트
- 어텐션은 ‘거리’를 없앤 연산이다. RNN에서 O(N)이었던 의존성 거리가 O(1)로 평탄해졌고, 이는 장문 이해와 병렬 학습을 동시에 가능하게 했다.
- Q/K/V는 학습되는 검색 엔진이다. 규칙을 프로그래밍하지 않아도, 손실 함수만으로 “무엇을 찾고 무엇을 드러낼지”가 결정된다. 이는 전통적 NLP와 결정적으로 다른 지점이다.
- 멀티헤드는 다차원 관계의 병렬 탐색 장치다. 헤드는 지시받지 않고도 서로 다른 전문화를 택한다. 모델 스케일이 커질수록 이 “렌즈의 수”가 같이 늘어나는 이유다.
- 포지셔널 인코딩은 철학의 차이를 만든다. 절대 위치 사인파에서 회전 기반 RoPE로의 이동은 단순한 기법 교체가 아니라, “상대 관계”를 본질로 삼겠다는 설계 관점의 전환이다.
- 디코더 온리의 승리는 엔지니어링의 승리이기도 하다. 학습·추론의 일관성, 구조 단순성, 스케일 확장성이라는 실전 이점이 아키텍처 다양성을 정리해 버렸다.
- 피드 포워드가 지식을 담는다. 파라미터의 2/3을 차지하는 이 층은 사실상 모델의 “기억”이며, 최근 활발한 해석 가능성(interpretability) 연구의 주요 타겟이기도 하다.
더 알아보기
- Attention Is All You Need — 원 논문 (arXiv) — 모든 것의 출발점.
- The Illustrated Transformer — Jay Alammar — 그림으로 이해하는 Q/K/V와 멀티헤드.
- The Annotated Transformer — Harvard NLP — 논문을 줄줄이 코드로 풀어낸 고전적 노트.
- Transformer Explainer — Poloclub — 실제 LLM에서 어텐션 분포를 눈으로 확인할 수 있는 인터랙티브 도구.
- RoFormer: Rotary Position Embedding — RoPE 원 논문.
- Decoder-Only Transformers: The Workhorse of Generative LLMs — 왜 디코더 온리가 사실상 표준이 됐는지를 상세히 정리한 글.
03찬반 토론 · Debate
토론: “디코더 온리 트랜스포머는 AGI로 가는 충분한 아키텍처인가”
논제: 현대 LLM이 수렴한 “디코더 온리 트랜스포머 + 어텐션” 구조는, 근본적으로 진정한 범용 지능(AGI)에 도달하기에 충분한 설계인가, 아니면 머지않아 구조적 한계에 부딪힐 임시 해법인가?
영상 “Learn How to Make AI Models w/ ML: 2. Transformers”는 GPT, Claude, Llama 등 현대 LLM이 모두 디코더 온리 트랜스포머 위에 서 있고, 이 한 가지 설계가 사실상 AI의 표준이 되었음을 강조한다. 그런데 이 성공은 “이게 정답”임을 뜻할까, 아니면 “이게 지금까지 발견된 가장 스케일 잘 되는 지역 최적해”에 불과할까. 이 토론은 그 질문을 정면으로 겨눈다.
Round 1
🟢 Pro — “어텐션과 스케일만으로 충분하다”
첫째, 스케일링 법칙(scaling law)은 수년째 깨지지 않고 있다. 파라미터, 데이터, 컴퓨트를 늘리면 손실이 예측 가능한 곡선으로 떨어진다. “Attention Is All You Need” 이후 등장한 GPT-2, GPT-3, GPT-4로 이어지는 연쇄는 아키텍처가 거의 동일한 채로 능력이 질적으로 도약했음을 보여 준다. 새로운 구조적 돌파 없이도 추론, 코딩, 다언어 번역이 가능해졌다는 사실은 이 설계가 단순한 임시 해법이 아니라 본질적으로 표현력이 충분함을 시사한다.
둘째, 디코더 온리 구조의 수학적 단순성은 축복이다. 어텐션은 순서와 거리를 자연스럽게 희석하고, 피드 포워드는 방대한 사실성 지식을 담는 창고 역할을 하며, 블록의 반복은 점점 추상화되는 표현 계층을 만든다. 이것은 “모든 시퀀스 문제”를 하나의 구조로 환원할 수 있는 범용 계산기에 가깝다. 멀티모달에서도 이미지·오디오·비디오를 토큰화해 동일한 트랜스포머에 넣는 접근이 주류가 된 것이 증거다.
셋째, 진정한 병목은 아키텍처가 아니라 데이터와 학습 신호 쪽에 있다. 최근 추론 능력 향상의 상당 부분은 RLHF, DPO, 프로세스 보상 모델, 자기 훈련(self-play) 같은 학습 기법에서 나왔고, 모델 구조는 거의 그대로였다. 구조가 병목이라면 이런 개선이 먹히지 않았을 것이다.
🔴 Con — “트랜스포머는 비용·기억·추론 세 갈래에서 한계에 닿는다”
첫째, 이차(quadratic) 복잡도 는 피할 수 없는 구조적 제약이다. 시퀀스 길이 N에 대해 어텐션은 N²의 연산과 메모리를 요구한다. 컨텍스트를 100만 토큰으로 늘리는 것만으로도 막대한 엔지니어링 곡예가 필요하며, 이는 평생 대화를 기억하는 수준의 “진짜 장기 기억”을 흉내 낼 때 파탄난다. 어텐션은 거리 문제를 해결한 게 아니라, 비용을 거리 차원에서 시퀀스 차원으로 옮겨 놓았을 뿐이다.
둘째, 디코더 온리 구조는 본질적으로 자기 회귀 텍스트 생성기 다. 다음 토큰의 확률 분포를 모델링할 뿐, 진정한 의미의 계획(planning)이나 역방향 추론을 구조적으로 지원하지 않는다. 최근 o1 계열의 추론 모델들이 “긴 사고의 연쇄”를 생성하도록 훈련되는 이유는 바로 이 한계 때문이다. 이는 구조적 해답이 아니라 일종의 우회로다.
셋째, 지식 저장 방식의 비효율 이 심각하다. 피드 포워드 층은 사실을 파라미터에 분산 인코딩하는데, 이는 업데이트가 어렵고, 사실의 진위를 구분하지 못하며, 환각(hallucination)의 구조적 원인이 된다. 사람의 뇌가 명시적 기억과 암묵적 기억을 분리하듯, 진정한 일반 지능은 파라미터 외부의 구조화된 기억 과 검색을 품어야 한다. 현재 트랜스포머는 그 분리를 내장하고 있지 않다.
Round 2
🟢 Pro (재반론)
Con의 첫째 주장인 이차 복잡도 문제를 보자. 이미 이 한계를 공격하는 실질적 진전이 쏟아지고 있다. FlashAttention과 그 후속 최적화는 상수 계수를 크게 낮췄고, 슬라이딩 윈도우 어텐션, Longformer, BigBird 같은 희소 어텐션 변형들은 실제 제품에 쓰인다. 더 근본적으로 Mamba나 RWKV, RetNet 같은 상태 공간·선형 어텐션 모델들이 등장했지만, 이것들이 트랜스포머를 “폐기”하는 게 아니라 오히려 하이브리드 로 흡수되는 추세다. 즉 이차 복잡도는 구조의 사망 선고가 아니라 최적화 과제일 뿐이며, 트랜스포머라는 패러다임은 이 흡수를 감당할 만큼 유연하다.
Con의 둘째 주장인 “자기 회귀는 계획을 못 한다”는 비판도 과장이다. 최근 o1, o3, R1 계열 모델들은 특별한 구조 변경 없이 같은 디코더 온리 트랜스포머 로 긴 사고 연쇄를 수행하고 수학 올림피아드 수준의 문제를 푼다. 이는 “계획 능력이 구조에 없다”가 아니라 “학습 목적과 보상 설계만 바꿔 주면 이 구조가 계획을 학습할 수 있다”는 증거다. 구조가 닫힌 감옥이라면 이런 전이가 불가능했을 것이다.
Con의 셋째 인 환각·기억 비판에 대해서는, 검색 증강 생성(RAG)과 도구 사용이 이미 표준 패턴이 되었다. 파라미터에 모든 사실을 구겨 넣는 게 아니라 외부 데이터베이스와 결합해 쓰는 방식은 트랜스포머의 자연스러운 확장이지 대체가 아니다. 여기서도 트랜스포머는 “환경 속에서 도구를 쓰는 에이전트”의 몸체로 충분히 기능한다.
🔴 Con (재반박)
Pro의 첫째 주장인 스케일링 법칙의 지속을 짚어 보자. 스케일링 법칙은 “손실이 내려간다”는 곡선일 뿐, 그 손실 지표가 지능의 진정한 대리지표 라는 보증은 없다. 이미 다수의 벤치마크에서 수익체감이 관찰되고, 단순 다음 토큰 예측 손실은 사실적 정합성이나 장기 추론 정확도와 직선적으로 연결되지 않는다. 스케일링 법칙이 아직 안 깨졌다는 건 “구조가 충분하다”의 증거가 아니라 “아직 벽에 부딪히지 않았다”의 관찰일 뿐이다.
Pro의 둘째 인 “모든 모달을 토큰화해 넣을 수 있다”는 주장도 반박이 필요하다. 이 접근은 작동하긴 하지만, 토큰화는 본질적으로 정보 손실을 수반하며 특히 고해상도 비디오나 연속 제어(로봇) 영역에서는 대단히 비효율이다. 토큰화가 “트랜스포머의 장점”이라기보다는 “트랜스포머에 넣기 위해 치르는 대가”라는 점을 간과하고 있다.
Pro의 셋째 인 “병목은 데이터와 학습 신호”라는 말은 오히려 Con 쪽 논거를 보강한다. 만약 구조가 완전했다면 학습 기법만으로 인간 수준 추론을 이끌어 냈어야 한다. 그런데 우리는 여전히 RLHF, 프로세스 보상, 검증자(verifier) 모델, 외부 검색 같은 수많은 외부 스캐폴딩 을 덧대야만 의미 있는 성과를 얻는다. 이는 구조가 “홀로 충분하지 않다”는 명확한 방증이다.
Round 3
🟢 Pro — Con 재반박을 정면으로 받는다
Con의 Round 2 첫째 에서 나온 “스케일링 법칙은 진정한 지능의 대리지표가 아니다”라는 지적은 철학적으로는 맞지만 실증적으로는 약하다. 다음 토큰 예측 손실이 완벽한 지표가 아니라는 것과, 그 손실의 개선이 실제로 측정 가능한 능력(코딩, 수학, 자연과학 추론)의 향상을 “예측해 왔다”는 것은 다른 이야기다. 우리에겐 지금 그 상관관계가 깨졌다는 결정적 증거가 없다. 오히려 최근 프론티어 모델들은 새로운 평가 스위트를 계속 갱신하며 “벽”으로 보였던 지점을 차례로 넘어서고 있다.
Con의 Round 2 둘째 에서 지적한 토큰화 비용도 재반박 가능하다. 연속 신호를 이산 토큰으로 바꾸는 손실은 분명 존재하지만, 그 대가로 얻는 것은 임의의 모달리티를 같은 연산 엔진에 던져 넣을 수 있는 보편성 이다. 이미 Gemini, GPT-4o, Llama 4 멀티모달 변형들은 이 손실을 감수하고도 단일 모델로 텍스트·이미지·오디오를 아우르는 성능을 달성했다. 비효율은 공학적 문제이고, 보편성은 아키텍처 수준의 이점이다. 두 시소에서 지금은 보편성 쪽이 결정적으로 무겁다.
Con의 Round 2 셋째 인 “외부 스캐폴딩이 필요한 건 구조가 불충분한 증거”라는 주장은 비약이다. 인간의 지능 역시 종이와 연필, 책, 대화 상대 같은 외부 스캐폴딩 없이 지금의 수준에 도달하지 못했다. 도구 사용과 외부 기억의 결합은 지능의 결함이 아니라 지능의 정의의 일부일 수 있다. 그 관점에서 디코더 온리 트랜스포머는 “외부 도구와 결합되는 범용 엔진”으로서 이미 충분한 역할을 수행한다.
🔴 Con — Pro 재반박을 정면으로 받는다
Pro의 Round 2 첫째 가 든 FlashAttention·Mamba 등 하이브리드 흡수론은 사실 Con의 주장을 간접적으로 인정한다. 순수 디코더 온리 트랜스포머만으로는 긴 컨텍스트 문제가 풀리지 않으니 상태 공간 모델, 선형 어텐션, 외부 메모리 같은 이질적 요소를 덧대야 한다는 뜻이기 때문이다. “패러다임이 유연해서 흡수한다”고 표현하지만, 다른 관점에서는 트랜스포머의 정체성이 희석되는 과정 이다. AGI에 도달할 즈음에는 우리가 지금 “트랜스포머”라 부르는 것은 거의 남지 않을 수 있다.
Pro의 Round 2 둘째 인 o1 계열의 성공 사례는 인상적이지만, 그 모델들이 보이는 비용 구조가 한계를 폭로한다. 한 번의 추론에 수십 초, 수분, 심지어 수 분 이상을 쓰고 수만 토큰의 내부 사고를 생성해야만 난이도 있는 수학 문제가 풀린다. 이는 “구조가 계획을 한다”가 아니라 “구조가 매우 비싼 방식으로 계획을 흉내 낸다”에 가깝다. 뇌가 비슷한 문제를 푸는 에너지 효율과 비교하면 간격은 몇 자릿수 수준이다.
Pro의 Round 2 셋째 인 RAG·도구 사용이 “자연스러운 확장”이라는 말은, 결국 순수 트랜스포머 + 스케일링은 충분하지 않다 는 Con의 원래 주장과 실질적으로 같다. “자연스러운 확장”이라는 수사는 문제의 소재지를 가릴 뿐 해결하지 않는다. 환각과 지식 업데이트 문제는 여전히 현장에서 가장 큰 골칫거리이고, 이는 구조 바깥을 덧대는 것만으로는 뿌리가 뽑히지 않는다.
🧭 종합
합의 지점
두 입장 모두 디코더 온리 트랜스포머가 지금까지 발견된 가장 강력한 범용 시퀀스 학습기 라는 사실은 공유한다. 스케일링이 실제로 작동해 왔고, 다양한 모달리티를 단일 구조로 흡수할 수 있으며, 엔지니어링의 단순성이 생태계 전체의 속도를 올렸다는 평가에도 이견이 없다. 또한 두 쪽 모두, 구조 자체를 완전히 폐기하는 혁명보다는 구조 안팎에서의 점진적 개선 이 단기 미래를 주도할 가능성이 높다는 데 암묵적으로 동의한다. 차이는 그 점진적 개선의 총합이 결국 “같은 트랜스포머 패러다임 안”으로 수렴할지, 아니면 “그 바깥의 무언가”로 벗어날지에 대한 전망뿐이다.
또한 양쪽 모두 “순수한 아키텍처만의 문제”는 아니라는 점을 인정한다. 학습 목적, 보상 설계, 외부 도구·기억과의 결합 방식이 결과적 능력을 결정적으로 좌우한다는 인식은 공통이다.
열린 질문
- 이차 복잡도의 구조적 해법 은 결국 Mamba·RWKV 같은 선형 계열이 주류가 되는 방식일까, 아니면 하이브리드 트랜스포머가 표준이 될까? 둘 중 어느 쪽이든, 우리가 10년 뒤 “트랜스포머”라 부를 것은 지금과 얼마나 같을까.
- 사실성 지식 을 파라미터가 아닌 외부 구조화 메모리에 저장하는 모델은 구조적으로 어떻게 설계되어야 할까. 그 메모리와 어텐션의 경계는 어디에 그어야 할까.
- 자기 회귀 생성만으로 진짜 계획과 역추론이 가능한가, 아니면 별도의 전방위 추론 모듈(세계 모델, 시뮬레이터, 검증자)이 구조 수준에서 요구되는가.
- 에너지·추론 비용 의 간극을 어떻게 메울 것인가. o1 스타일의 “오래 생각하기”가 비용 대비 합리적 영역은 어디까지인가.
더 나아간 관점
이 논쟁의 흥미로운 점은 “구조냐, 학습 신호냐, 스캐폴딩이냐”라는 삼자 구도에서 답이 하나로 모이지 않는다는 사실이다. 아마도 가장 정직한 대답은 이것이다. 디코더 온리 트랜스포머는 AGI로 가는 마지막 아키텍처가 아니지만, AGI로 가는 길에서 우리가 가장 오래 쓰게 될 “몸체” 일 가능성은 매우 높다. 지난 10년을 지배한 패러다임이 하루아침에 폐기되는 일은 드물다. 대신 주변 구조가 꾸준히 덧대어지고, 내부 최적화가 쌓이고, 어느 순간 돌아보면 이름은 같지만 실체는 상당히 다른 무언가가 되어 있을 것이다.
그렇다면 실무자에게 주는 교훈도 분명해진다. 첫째, 트랜스포머의 기본기(어텐션, Q/K/V, 멀티헤드, 포지셔널 인코딩, 블록 구조)는 앞으로도 오래 유효한 투자다. 둘째, 그러나 “트랜스포머만으로 충분하다”는 만능주의에 갇히지 말고, 외부 메모리·도구·검증자·하이브리드 시퀀스 모델 같은 주변 생태계 변화를 함께 읽어야 한다. 셋째, 영상이 보여 주듯 밑바닥부터 미니 GPT를 한 번 짜 보는 경험은, 이 긴 논쟁의 어느 한 편에 휩쓸리지 않고 자신의 판단을 세우기 위한 가장 확실한 기초 체력이 된다.
결국 이 토론의 진짜 가치는 어느 쪽이 이기느냐가 아니라, “우리는 지금 어떤 가정 위에서 AI를 만들고 있는가”를 드러내는 데 있다. 그 가정들을 의식하는 순간, 우리는 다음 세대 아키텍처를 설계할 자격을 갖추게 된다.
04영문 원본 · Transcript
So welcome to the second episode in this series where we're going to learn about machine learning and how to build AI models. Episode two is going to be about transformers, and this is a big one. In episode one, we learned about PyTorch, and that was basically about learning the tool you use. This is about understanding the blueprint of the building. Every major AI model you've ever heard of, GPT, Claw, Lama, it's all built on this transformer architecture. So understanding this is very important. So a little bit of background. Before 2017, the best language models used architectures called RNNs, Recurrent Neural Networks, and LSTMs, Long Short Term Memory. So these process text one at a time in order. The two problems with this was obviously speed. It's very slow. You can't process words in parallel. So word five depends on the output of word four, which depends on the output. Word three, you know, you have to wait for each one. And so this made training painfully slow. The other issue was memory. By the time the model reached word 200, say, it had fuzzy, degraded memory of word one. Information gets compressed and lost as it passes through the chain. So think of this like context, right? If you're working on a long term project, a lot of times after a few times, the context is compressed. It's very hard for models to remember very early on what you were talking about. So this was a similar concept just with the models themselves. So the transformer former solved this instead of reading on reading one word at a time, it processed all the words simultaneously. So any word can directly attend to any other word. So, for example, word 200 can directly look at word one. There was no need to go through that whole chain. And this made models both faster and better at long text. So this was the paper title, attention is all you need, and that is the key insight. It's literal what you don't need is this kind of recurrent one by one process, attention alone done right is enough. So let's talk about that. What is attention? And this is going to be important to understand some words matter more. And the core idea is that when you're reading and you hit the word it here in this sentence, the cat sat on the mat because it was tired, right? When you're reading this and you hit the word it, your brain doesn't give equal weight to every previous word, right? You automatically focus on the most relevant one, which is cat and mostly ignore, you know, Matt, the it's not as important as cat, which is obviously it's referring to. You do this so naturally that most of us don't even notice this. So this idea of attention is basically the same process, but formulized as a math. When the model is processing any given word. It computers. A score for every other word that answers how relevant are you to me right now? High score means you have to pay attention. Low score means no, you can mostly ignore it. So why was this idea revolutionary? Because before attention, the model's understanding of it in the sentence was based on whatever compressed information had survived from this whole telephone chain of earlier words with attention, it can reach directly back to cat and pull its meaning forward. So the distance does. It doesn't really matter. Word one and word 500 can communicate just as easily as words that are right next to each other. So once again, it's the previous method RNNs were like a game of telephone where each person whispers to the next transformers like this are like everyone in the room being able to talk to everyone else directly. So a very important structural change. Next, we need to understand query key and value because attention needs a mechanism for words to find the. Write other words, right? It does this through three vectors that every word produces, and these are query, Q, key, K, and value V. So query, think of this as a question to the word, a question. The word is asking when processing that word it from before the query is essentially asking who is the subject, who am I referring to here? The model literally doesn't ask this in English. You know, it's just a vector of numbers that encodes. What? Kind of. What information this word needs in this case, it's looking for a noun. It refers to K. The key, think of this as a label that each word wears cat has the key saying that it's a noun, right? It's an animal. It's the subject. Again, this is not in English. Obviously the vector, it's just a vector of numbers that describes what this word contains. And lastly, value. So value is the actual data, the actual information. Once the query matches. A key, and these are, have a high similarity score, the value is what you get back. It carries the actual semantic content of the matched word. So I think the search engine analogy works well here. You type a search query, right? Who is the subject of the sentence? What is the subject? It matches against the keys until it finds a proper match, and then it returns the content, which is the values. So it's a important thing to understand. Here query, key, and value aren't handcrafted. They're produced by multiplying the words embedding by three different learned weight matrices. The model discovers during training, what makes useful queries, keys, and values. So nobody programs look for nouns. It figures this out on its own. And that's part of the process. And next, how does attention compute? So there's four steps here. Uh, not a crazy formula or anything. Step one is compare for each query. Uh, you multiply it against every other words. Key. Um, this is just a dot product. If you understand that concept, uh, the same operation we were talking about from the previous episode, if two vectors point in a similar direction, right? The dot product is very large. If they're unrelated, it's small. So words with related Q and K values, Q and Ks, uh, get higher scores. So step two is scale and you take the raw dot products, uh, which can be very large numbers, especially with big vectors. Um, you need to divide them by the square root. Of the vector size, keeping the numbers manageable. So this is kind of a, just a practical detail. It doesn't change the core concept, but you need to scale them down to prevent one word from dominating. Step three is soft max. And you will remember me talking about this. If you watched, uh, the most recent video about, uh, turbo quant, and basically in this context, soft max converts the raw scores into probability distribution. If the scores for cat, Matt, and the were say eight, uh, two and 0.5. Softmax will then transform them into 0.8, 5.1, 2.03, right? Uh, so then they become percentages that add up to a hundred percent. So now each word has a clear attention to weight. Um, and it's very clear that in that case, the word cat would dominate step four. You take the weighted sum. So you take each word's value vector, uh, multiply it by its attention weight and add them all up. So if Kate cat got a weight of 0.8, five. And Matt got 0.1, two, the result is 85% cat's information and 12% Matt's information. The output is a new vector that blends the most relevant words. A little bit complicated, but the end result, and this is the most important part to understand from this slide is each word gets a new representation that incorporates the context from the words that matter. Most it in that sentence, uh, now carries information about cat because the attention mechanism here discovered. That con connection. Uh, so next we have multi head attention and a single attention operation. Like I just described, you can only capture one type of relationship, but words relate to each other in many ways simultaneously in the tired cat sat that little, that sentence, the word cat is related to tired, obviously. Right. Uh, cause that's a adjective relationship describing it. And sat is a verb describing its action. And then it has the word, the. Which is a determiner. So just having one set of query key value weights might learn the, to find the adjective relationship. So tired, but it might miss the subject or the determiner relationships. So the solution is to run multiple attention operations in parallel, each with its own query key value weight matrices. And each of these are called a head. Um, if you remember my audio auto research videos, we talked about this concept heads. So if you have eight heads, you have eight independent attention computations, uh, that process from before you'll have eight of them going on at the same time. And it's important to understand that nobody tells heads what to specifically specialize in during the training of the models. Each head naturally gravitates towards tracking a different type of pattern because that's, what's going to reduce loss, right? Uh, research has found that different heads do end up specializing. Some tracks syntax, some track, uh, co-reference, uh, some tracks, semantics. So after all the heads are done running, in this case, we have four heads here at it, their outputs are going to be stuck together side by side, and then pass through a linear layer that combines them into a single representation. So this means every word gets multifaceted understanding that captures many types of relationships simultaneously, all four of these in this case. So modern models use different type of different number of heads. Uh, GBT small uses 12 heads. GBT three uses 96 Lama two 70 B uses 64 though more heads mean more types of relationships. The model can track in parallel. Next, we're going to talk about positional encoding. And the key here is that order matters. Attention computes similarity between all pairs of words, but it treats them all as a set, not as a sequence. It has no idea which words come first, second, or last just sees a bunch of words. So the attention. Scores would be identical, whether you fed in here, dog bites, man, or man bites dog, it's the same words, right, but completely different meaning. And this is obviously a problem in English and in most languages, word order is fundamental to meaning. So the fix is this positional encoding concept, which is before any attention happens, uh, you add a unique pattern of numbers to each words embedding based on its position. So word one gets one pattern. Word two gets a different pattern. Word 50 gets a different pattern. You know, this injects position information directly into the data before you do any of the processing. Uh, now the original paper used fixed wave patterns. Um, but more recently they've been using this ROPE, uh, fixed mathematical rotations. And ROPE is rotary position embeddings. So instead of adding these positions to the embedding, ROPE rotates the query and key vectors by an amount. Proportional. To their position. So this is a fixed mathematical operation. It's not learned, uh, it elegantly encodes relative distance. So the model can easily tell, you know, these two words are three positions apart rather than just a fixed position. You know, this word is at position 75, you know, most modern models, uh, use this type of method. So the key to understand here is that position data has to be explicitly injected. The model can't figure out word order. On its own. When we use this system. Uh, so that is the foundation. And now we're going to get into the transformer block. Now this is four layers and these are repeated. A transformer model. Isn't one huge monolithic thing. It's not one giant structure. It's a small block of operations repeated many, many, many times. GDP two stacks, 12 blocks of these GDP three stacks 96. So the key part to understand here is that each of these blocks have the. Same four components. And first it's the multi head attention that I described before. And this is the gathering step. Each word looks at all the other words and collects relevant information. This is where the words kind of talk to each other and where the relationships between words are captured. Then you go into layer normalization. And this is just an information processing layer that rescales the numbers. So they don't grow too large or too small as they pass through the different layers. If they do, it would just break down the model. Yeah. And especially in very deep networks like those with 96 blocks, the signal can really degrade as it passes through each layer. Think of it like a photocopy of a photocopy of a photocopy, right? The residual connection here ensures the original information always has a direct path through, so it never gets completely lost. And that stabilizes the values. So then three, we go into the feed forward network. And this one gets its own slide because it's a little bit complicated. After attention has gathered. It's got a lot of context from other words, each word then passes through this feed forward network on its own. So there's no word to word interaction here. This is all just individual processing. It has three steps here. Expand, which means the linear layer grows four times wider. And this creates a much larger internal workspace. Think of it like 3,072 individual detectors. Each checking for a different pattern or piece of knowledge. Each checking for a different pattern or piece of knowledge. knowledge. Part two is activate. And this applies an activation function. If you remember the relu function from episode one, it's this or GLU, which is a more modern approach, basically decides which of all of these detectors 3000 plus detectors are relevant right now, irrelevant ones get zeroed out or suppressed. And this is where the selectivity happens, the models choosing choosing what actually matters. And step two, step three, rather is contract, it goes back to the original size. You remember in our training loop from the first episode, it basically did a mini version of this process. So what does it actually learn through this? So research suggests that feed forward layers act as a knowledge store. Individual neurons activate for specific concepts. One might fire for capital cities and other for past tense verbs, another for Python syntax. The attention mechanism figures out what could be used to activate a new layer. And this is where the relu function is. And then the feed forward network here, figures out where the model is going to store and then retrieve what it knows, this is the real knowledge storage area, basically. So going back to these four layers, after you go through that whole feed forward network, processing the information, then you're going to go back and do one more layer of layer normalization. And it's the same idea as over here, you're stabilizing the output before it goes to the next block. So each block refines the representation. Early blocks might capture basic syntax, middle blocks might capture semantics, later blocks might capture abstract reading, and task specific patterns. By stacking together a bunch of blocks, the model builds increasingly sophisticated understandings. So that's the basic structure architecture of a transformer. So now we're going to talk about encoder versus decoder. And there are three ways to use a transformer. There's encoder, which is bi directional, each word sees all the other words, both left and right. And that's good for understanding input. And BERT is the most common example of this. And this doesn't generate text like you would see in a normal model, modern model, it just understands text. So decoder, and this is the most important one to understand, because this is what modern models actually use. Each word can only see the words that came before it, nothing that is coming in the future. So this is the architecture for text generation, chatbots, code completion, writing. So everything, GBT, Claude, Lama, they all do that. So this is the architecture for text generation, chatbots, code completion, writing. So everything, GBT, Claude, Lama, they all do that. So everything, GBT, Claude, Lama, all use decoder only. And the casual constraint exists, because during generation, future words literally don't exist yet. And encoder decoder incorporates both and this was in the original paper. But it's less common now this decoder only method as kind of one out. So casual masking with our decoder approaches, we need to prevent the model from cheating by looking at future words during training. And the way this is enforced with this masking, a matrix of allowed and blocked connections if you look at this little chart over here so you could see the only can see the cat can only see the cat sack can only see the cat sat you can't see any of the words coming after it right and why does this matter during training during training we feed the model an entire sequence at once for efficiency so without this kind of mask when predicting the word at position five here the model could peak at position five's actual answer which would make the training useless right the mask here forces the model to do honest learning you have to predict the position at five uh using only what came before it and this is only used in trading uh to simulate this constraint and like i said modern llms are decoder only every major uh large language model uses decoder only architecture and they generate text one token at a time so here we have this sentence the price of the coin step one the price the price of the price of bitcoin it just goes one token at a time now a token isn't necessarily a full word like i did here just for simplification um it's roughly three to four characters so one word could actually be split into multiple tokens depending on how large it is most common words are just one token though and this process is handled by the tokenizer which we'll see in later episodes and if you did any auto research experiments you saw a tokenizer there so this is called the tokenizer tokenizer tokenizer tokenizer tokenizer tokenizer tokenizer auto regressive generation and it means each output becomes the input of the next step so this is why generation is sequential even though the model itself can process in parallel you can't process the word bitcoin until the previous word of exists you can't jump straight from two to four in this case uh so lastly this is the full transformer everything we just learned so first you tokenize you start with the raw text right the price of and then you tokenize it splitting it into these token ids which are just numbers and it becomes a large vector of numbers a giant matrix so at the end of this step we just have this sequence of vectors then we go on to the position embedding like i said before positional encodings are added to each embedding uh in some method so the model knows the order then we get into the transformer blocks and this is the main the four layer process that i discussed earlier with the tension and then the rescaling and then feed forward and there could be many blocks obviously each block applies attention and then feed forward process and the representation gets refined at each layer and finally predict the final representation of the last token is projected to a vector with one score per every token in vocabulary so the token with the highest score is the prediction so bitcoin might get 72 percent you know ethereum maybe eight gold three and it will generate whatever is most likely so this is the full transformer from start to finish so five key things this is it we finally got through the knowledge portion as we keep going these are going to probably get longer and longer as the concepts more become more complicated but the five key things to remember if you forgot everything else that i said is this idea of attention attention is the mechanism that lets every word look at every other word to find relevant context it uses query uses key it uses value and this is the core innovation of the transformer multi head attention and this is running multiple attention operations in parallel each learning different relationship types this is why transformers are so expressive they capture many kinds of word relationships simultaneously positional encoding right explicitly injects word order transformer block and this is the repeating unit like i said attention feed forward and then the normalization layers the feed forward layers act as the model's knowledge store containing roughly two-thirds of all parameters so if you stack 12 to 96 of these you get a modern language model and remember that modern llms are decoder only they generate text one token at a time and use the casual masking method to prevent looking at future tokens okay so that was it that was our knowledge section for the transformers it's a bit much but i hope you understood most of it and these are the core concepts that we're going to implement in the next video so thank you for watching and i'll see you in the next video in our work section that we're going to do right now and in today's project we're going to build a mini gbt from scratch piece by piece and training it to generate text so let's get started with the little mini project okay so we're going to get started on our mini gbt here and like in the previous video we're going to do this step by step basically going through and actually doing the steps that i talked about in the slides earlier and we need some text in order to train this mini gbt and what we're going to be using is these these are one piece synopsis from wikipedia this was from a previous failed uh auto research video i was trying to do so i have all this data downloaded and processed properly so and it just happens to be a good size for what we need to do for this so that's what we're going to be training the data on so hopefully we'll have some fun output uh once it's done training and like i said this is not going to be perfect a lot of it's probably going to be nonsense but it'll give you an idea that we're going from absolutely zero into training a model that can produce something like this kind of one-piece themed text so this is the first time i'm in vs code here this is the first script we're going to do the first step which is going to be building attention from scratch um and the top part here is just about loading the text that i just showed you those synopsis files so then we're going to build a simple vocabulary And usually tokenizers will split text into words or sub words. But for this, we're going to treat every single character as a token instead of parts of words. So Luffy becomes L-U-F-F-Y, five different tokens, because it's going to keep the vocabulary tiny here. A real tokenizer will have a lot of tokens, but smaller vocabulary for this means a smaller, faster model and will be good for our demo here. So moving on, this is where we have the attention that we were talking about, right? And just to give you the example here, we have a sentence, Luffy punched the enemy. And then we're going to break it into tokens. Like I said, we have the length of the string. It's going to print this out once we actually run the script. But we're going to create random embeddings for each character. Normally, these are learned, but just for this. And then we're going to get into the query. Key and value weight matrices. And these are the learned weights that produce queries, keys, and values. In a real model, these are trained. Here, we're just going to initialize them randomly. So each token produces its own Q, K, and V by multiplying with its embedding. So these are all going to be unique because you need to transform the tokens into these different values so that the model can actually read it. So then we get into the four steps of attention that we talked about, right? We're going to compare. Each token, and each token has a score against every other token, to try to find which are similar. You're going to scale it, which is a processing step. Then use softmax, which, like we said, converts it to probabilities. And then we get weighted sum. And at the end of this, each token will contain a blend of the most relevant tokens. Then we have the attention weights. And this will print out a kind of visualization for us to see. So that is. This is going to be the first step, which is going to be attention. So let's run this script, and you'll actually see what we get here. Okay, so I ran the script. We could see the output, what we printed out. It loaded a little over three million characters of one piece text, saved it to a text file. These are our unique characters, sample of what we get. So single head attention. Like I said, Luffy punched the enemy. So these are the tokens that it broke it into, 23 characters. And you could see we're using PyTorch. Obviously, but the embedding shape is going to be 23 for the 23 characters and then 16, which is the dimensions we set. And this is small enough just to make this little demo fast. Larger models have a lot more dimensions. Larger dimensions means more expressive, but also more memory, and it's a lot slower. So we did a small amount for just this demo to make it fast. So we have the shape here defined for the query key and value, which is the same 2316. So step one, we compared the tokens against each other. So each token has a score against every other token. Step two, we did the scaling that we needed to do. Step three, soft max to make them probabilities. So each row sums to one, and then we got the weighted sum. So let's see how we actually got it. These are the attention weights. Now these are going to random because we haven't trained the model yet. Um, but higher means more attention. So formatting is a little bit. Let me see. If I can make it smaller. Sorry, I made it tiny, but it's the only way to get the, get it to look right. You could see how the higher number means more attention. So for instance, this L is paying most attention to, uh, what is N over here. Um, and like I said, these are random. We need to train them. So let's do that. This was just showing you an example of the process of attention. So let's move on to the next step, which is going to be the multi head attention and casual mask. So in the first step, we had one set of Q, K, and L, one attention operation. Now we need to wrap that into the NN module. You remember from the previous video, the pie torch video, and we're going to run four of these attention heads in parallel, each with its own Q, K, and V weights. And this is just to give you a comparison. This is a single head attention as a module. You can see just the one. And you get attention scores, but we're going to look at the multi head attention, and this is going to use 32 dimensions and four heads. So each head is going to work with those 32. So each will have eight dimensions of their own. Maybe easier to see when we actually process the, the script, but this is also the casual mask. And this is a triangular matrix that you saw from the slide, right? So the script builds it with this one line here. Casual math using torch dot trill, T-R-I-L. And this means lower triangle gives you ones below the dimension zeros above it. Okay, so let's actually run this script. So you can actually see it's going to print out most of this, which might be easier to understand. Okay, I ran the script and you can see this is the multi head attention. The configuration is with 32 dimensions, four heads, and that means eight dimensions per head. So the input shape into torch is one. One batch, 10 tokens, 32 dimensions. And this is the mask mask visualization. You could see these are blocked. The kind of pound keys here mean can attend these dots means it's masked out. So token one can only see itself. Token five can see tokens one to five token. 10 can see everything. And these are the attention patterns per head using the casual mask. You could see when it starts with token one. Obviously it's 1.0, it's everything, but as it goes further along, the percentage goes lower, but these are random right now because we haven't trained in it after training, each head would specialize into a different relationship type. So let's see that in action. Let's move on to the next step. And this is step three of this process. And this is kind of the key part before was just giving you a demo. Now we're going to actually build the complete mini GVT architecture piece by piece. So this is once again, rebuilding the casual self attention. So this is a multi head attention operation with the casual mask built in, which I showed you in the previous step. So in this step, though, we need the feed forward network, right? Remember that four part four layer transformer block I showed you. So this is the attention part, which is step one. And this is the third part, which is the feed forward network. And the. Feed forward class here, does the expansion, activate and contract that we talked about, you could see it right here in this line, it expands from four times the dimensions, runs whatever activation, smooth relu variant G Lu here, which zeroes out the irrelevant parts and keeps the useful signals, and then contracts it back to the original size. So this is the transformer block. And this is what I showed you. Earlier in actual simple code form. And you can see the different elements of it has the attention part, the feed forward part, and then the two layer normalization parts. So this is the process. This is the one block. So we have the attention operation, plus the normalization, also called residual connection. And that's what the plus is for. So the original input is added back to the output. So the original input is added back to the output. So the information can skip through. And then you have the feed FF here, which is going to be the feed forward. Class from up here. And then the full mini GBT that we're building. So this is the class mini GBT complete the former transformer decoder for text generation tokenize embed position, the transformer blocks predicts the next dose token. So this is putting it all together. And you can see each part the embedding here position embeddings, stacks of the transformer blocks, final normalization. And then we have. Lastly, we're gonna have a little demo to load the vocab from step one. Right. And it will print out the results. So let's actually run the script and then we can go through what the output actually will be. And I ran the script and this is what it printed out for us to kind of show you a visualization. our mini GPT architecture the token embeddings position embeddings and these are the blocks the transformer blocks with the attention and feed forward aspects you can see the entire parameters here the embeddings a little over 46,000 attention 262 thousand plus feed forward 526 thousand plus so total parameters eight hundred and fifty one thousand parameters and you can see feed forward has the most parameters and that's because like I showed in the slide it does that expansion step right and then it goes back after activating the operation goes back to the original size so it's not a trillion parameters like some frontiers but this will be a good little project so this was our little forward pass test it there was a fake input that went in and it was a fake input that went in and it was a fake input that went in and scored for every character came out and like I said this is untrained so these are random percentages but just to give you an idea this would be kind of the prediction you would get for position one so this is the core architecture and now it's time to actually go into the training process and this is where the model actually is going to learn to write or the one piece synopsis we're gonna give it so first we're gonna define the model which is the same step we just did so I won't go through this all again but it's the same stuff you saw transformer blocks that whole process then we're gonna load data and configure it so that we can properly read it do the train validation split and this is gonna be our training setup 64 batch size you can see all the different configurations we're gonna do like we said if you watch the first episode you touched on some of this stuff and then we're gonna do the training loop which I just am, happened previously but I believe and such believe and what it really will remind us is that we will Run over a couple of parts which again we're gonna run another patch before I even finish this video so we'll start selected with data pick so this piece here I just want to kind of Octave that we use in the presentation of course this one we're giving it a bunch of builds we're gonna day let's run this up the really pretty that I think the way my computer actually runs it all is toанные no wonder it does this since they're basically rolling over the sort of node that this base and center on the actually performing and counting up here you can see the data set up here is big and looks perfect we can move on to the next step which is the evaluation and simulation right which we damital I said we did in the PI torch episode and we're going to estimate the loss the training loss and validation loss like before chunks of 256 characters each you can see starts out the training loss is very high. It's going to print the progress every 300 steps like this. So we're going to see if the loss goes too low decreases over time. And we want to see both the training loss and validation loss going down. We're using cross entropy loss. So this is the standard loss for kind of pick one out of many options type of models, the model is going to output a score for each of the 100 plus characters in the vocabulary and cross entropy is going to measure how much probability it puts on the correct next character. See, it's starting to drop a bit both training and validation loss. And the training task here is simple. Given a sequence of characters, it's just being asked to predict the next one at every position. If it if the input is l u f f, it should be able to predict that the the next character is y. And at the end, it'll have actual generation. Just to see if it picked up some of the patterns up from the one piece synopsis. We're getting good results though so far it's dropping. And validation loss is also dropping, which is a good sign. Means we're not overfitting too much continuing almost almost done, we're gonna do 3000 steps. IPC is is humming along. So right now the model is learning which characters follow which. So through each of these steps, the data is going through those four blocks, the transformer blocks. But the blocks themselves don't change a number. It's just the weights inside that change each step as the model learns. see we got to 3000 here did very nicely both train loss and validation loss decreased over time we actually got under 1.5 which is nice validation loss also so this is our quick generation test the prompt was luffy um it generated obviously gibberish but there's remember this is trained completely from scratch like it's actually generating words most of these are actual words uh in a way she to tear tell obviously it doesn't work as a sentence uh but like there's actual names buggy is here tom sanji is here um so it actually did learn some patterns obviously as a sentence it doesn't make sense but that's actually a pretty great result um got a lot of character names a lot of the one piece vocabulary here the sentences are kind of structured like sentences with comma period at the end like names have proper capitalization as well um so it's gibberish but it's clearly one piece themed gibberish right and considering i trained this from scratch in a couple minutes three minutes uh that's a pretty decent result so this is going to be the last step and this is going to be generation um it loads the trained model that we just trained at the beginning of this stuff and then it's going to do three things we're going to get multiple prompts it's going to generate from three uh five different starting points uh these are the five different prompts it's going to start with luffy the straw hat episode 100 zorro drew his the ship sailed so we're going to see how the model continues differently based on what kind of opening prompt it's given um so then we're going to do the temperature comparison so for this one the prompt is going to be the same luffy and his crew and it's going to test with three different temperatures and we didn't talk about temperature so to explain temperature after the model predicts scores for every possible next character soft max converts those scores into probabilities like you saw before so temperature is the number you divide the scores by before soft max so a low temperature is dividing by a small number which always makes the scores more extreme so a character that scored slightly higher than the others now dominates so the model always picks the most likely option and the output is more safe and repetitive um we're also going to be looking at the score of the model and we're going to be looking at the score of the model and we're also doing point uh that's 0.3 kind of a low temperature middle range which should have a a good balance between it and then the high temperature 1.5 and this is dividing by a large number so the gap between the best and second best character shrinks the model picks from a wider range of options so the output is more surprising possibly more creative but it also is more liable to make mistakes so that's that's the idea behind temperature and lastly we're going to plot the loss curves just so you can see how loss dropped over training but i think we got pretty good results from that so let me run this script okay so we can see the different text generation results luffy luffy he claims making thought the own the country uh once again this is gibberish because we just trained it for a couple minutes but you can see the different results that we get the straw hats will doing episode 100 and the crew uh zorro drew his letting into the rest different different results from each of them the ship sailed you can see because the the word ship was here we got to see sunny in the original luffy uh it has straw hats so you can see how different prompts can create different results coming from it it's not just the same thing um and once again this is gibberish but it's very one piece themed gibberish you can see a lot of the names still zorro's in here this one's got a lot of different levels of in the same way uh so it's a lot of different things going on it's a lot of different things to compare um but the one i like the most is is the temperature comparison and this is the temperature comparison the same prompt got different temperatures the conservative one uh luffy this is all starts with luffy and his crew luffy and his crew the ships are in the treats the crew of the new stair of the rest um i'm more balanced um um um it's perhaps too creative. That's kind of gibberish. Even more so. The first one, the conservative one actually reads kind of like a sentence. It doesn't make sense. But you can see there's proper words at least. Whereas the high temperature one is just a string of random letters pretty much. So that's pretty, it gives you a good idea of temperature. And this is the training loss image that I showed you. And this is pretty good result. It started high, went down the whole way. If we continue to train it, we might get better results. And important once again, that the validation, this blue line went down along with the training. So lastly, I think we got decent results. But lastly, I'm going to increase the number of steps from 3000 to 10,000. And see if we get a better result here. So each step is going through the training loop again. So everything else is staying the same. I'm just increasing over three times the number of steps. So let me, let me see at a certain point. There's kind of a ceiling with a model this tiny. But we'll see if we can get a better result here. So you can see we're around step 6000 ish. And it's starting, we got lower than what we previously had gotten, which was around slightly under 1.5. For the training loss. That was around 3000, where we stopped last time. And you can see we're getting lower down to 1.2. And what's nice is validation loss is continuing to drop. But we're starting now in this 6000s, we're starting to kind of even out, plateau. So that might be the best we get. But let's wait till it finishes. Okay, we got down the training loss of 1.15. Our validation loss kind of plateaued, and probably started to overfit a little bit here in the last couple rounds, got down to 1.37 ish, and then kind of stayed there, up down a little bit at the end. But we can see the generation test from Luffy, Luffy showing the still attacks Luffy ready to and had frisks the platform. However, Luffy is angered this miss servants. After after her death, the words ship to which Luffy ever misdreams his friend. So still not proper English, but definitely considering we train this from scratch. In just a bit, you can see the previous one we got. It's definitely better than the previous one. We only did 3000 steps on like this is not even there's a bunch of garbled, like non words in here. This one, at least all of these are mostly words. Miss servants, I guess is not a word. wrists is not a word. But most of these are actual proper English words. And it might have might have overfit at the end there. But I was I thought that was interesting, just to compare the two. But that's gonna be it for this video. It's ended up being a very long one. But this has been about transformers. Episode two of this machine learning series. I hope you learned a lot. I know I did. And we're going to move on to hugging face in the next video. So we just built a transformer from scratch and trained to generate text one character at a lot at a time. But we started from nothing right random weights, tiny vocabulary trained on three megabytes of data. What if the entire instead of building from scratch, you could take a model that's already been trained. On the entire internet billions of pages of text and just use it. So that's what hugging face gives you. So that's going to be the next episode. Instead of going through the pain of training these completely from scratch, we're going to start with free pre trained models, and then build up from there. So please look forward to that. Please subscribe, leave a comment, leave a like, and I will see you in the next video. Thank you for watching.