SlideShare a Scribd company logo
1 of 262
Download to read offline
집현전 최신반 1조
고현웅 김대웅 이윤재
Large-scale LM에 대한
얕고 넓은 지식들 (part 1)
1
요즘 우리(NLPer)들의 모습…...
2
요즘 우리(NLPer)들의 모습…...
솔직히 도저히 못 따라가겠습니다. …^^
다른분야는 3년 전 논문이면 최신논문인데,
여기(AI)에서는 3년이면 강산이 바뀜 ㅋ
LSTM이요? 그게 뭐죠? 기억이 안나는데…...
3
그래서 준비해봤습니다.
최신 이론과 기술들, 핵심만 말씀드릴게요!
ps. 깊게 공부하고 싶으면 더 찾아보셔야 합니다.
ps. 발표가 다소 길어요. 바쁘시면 유튜브로 챙겨보셔도 좋습니다.
4
Index
1. 🤖 History of LM: Google vs OpenAI (Part1)
1. OpenAI: GPT-1 (110M)
2. Google: BERT (340M)
3. OpenAI: GPT-2 (1.5B)
2. 🔥 Parallelism: Theory and Practice (Part1)
1. Fundamentals
2. Data Parallelism
3. Model Parallelism
4. Pipeline Parallelism
5. Deep Speed
5
4. Google: T5 (11B)
5. OpenAI: GPT-3 (175B)
6. Google: Switch Transformers (1T)
3. 🤗 NEO & NEOX: Let's open it up! (Part 2)
1. GPT-NEO & NEOX
2. Sparsity
3. Positional Embeddings
4. Normalizations
4. 🌱 Beyond Fine-tuning: New methods (Part 2)
1. Prompt Programming Overview
2. Discrete Prompt Search
3. Continuous Prompt Search
4. Pattern Exploiting Training
Index
6
Chapter 1
🤖 History of LM: Google vs OpenAI
(Background 연구 설명)
7
GPT-1 (110M)
8
OpenAI
GPT-1 (OpenAI 2018, size: 110M)
- Transformer를 대량의 웹 데이터로 Pre-training해서 언어를 이해시켰다.
- Supervised Dataset은 수가 적어 언어의 보편적인 특성을 배우기 어렵다.
- 웹에 많은 데이터가 있으니 이를 활용해 모델의 성능을 높이기 위함.
- 단어들이 주어지면 그 다음 단어를 예측하는 방식으로 Pre-training을 했음.
- 이후에 NLU 태스크의 데이터셋으로 모델을 Fine-tuning 해서 사용한다.
- 주어진 태스크의 데이터셋에 맞게 입력만 변경, Transformer는 고정한다.
- Transformer Layer위에 새로운 Linear-layer를 붙여서 예측을 수행한다.
History of LM: Google vs OpenAI
9
GPT-1 (OpenAI 2018, size: 110M)
- Transformer Decoder만 사용하여 만든 Causal LM.
- Decoder에는 Masked Multi-head Attention만 존재.
- Encoder가 없기 때문에, Cross-Attention도 제거됨.
- 즉, GPT는 Uni-directional Attention만 참조할 수 있는 모델임.
- 그 위에 2개의 Linear-layer가 탑재되어있다.
- Text-classifier: Fine-tuning에 사용.
- Text-prediction: Pre-training + Auxiliary Loss에 사용.
- Auxiliary Loss는 GPT-2부터는 사라지게 되었음.
History of LM: Google vs OpenAI
10
BERT (340M)
Google
11
BERT (Google 2018, size: 340M)
- 마찬가지로 대량의 웹 데이터를 사용, 2가지 Objective로 Pre-training.
- MLM: 단어를 [MASK]로 랜덤하게 (15%) 변경하고 원래 토큰 맞추기
- NSP: 두 문장을 [SEP]으로 연결해서 입력, 연결된 문장인지 아닌지 맞추기
- 이후에 원하는 태스크의 데이터셋으로 모델을 Fine-tuning 해서 사용.
- Span prediction: size=2인 Linear-layer 붙여서 Start, End를 예측.
- Pair prediction: 문장 두개 넣고 [CLS]토큰을 Linear-layer로 분류
- Single prediction: 문장 하나 넣고 [CLS] 토큰을 Linear-layer로 분류
- Sequence tagging: 각 토큰의 출력 Repr을 Linear-layer로 예측
- 도전한 모든 Task에서 당시 SoTA를 찍고 2010년대를 대표하는 LM이 됨.
History of LM: Google vs OpenAI
12
BERT (Google 2019, size: 340M)
- BERT는 Transformer Encoder만 사용하여 만든 Encoder LM.
- Activation 함수를 ReLU가 아닌 GeLU를 사용해서 성능을 개선.
- 3개의 Embedding을 더해서 Token Representation으로 활용.
- Token Embedding + Pos Embedding + Segment Embedding
- Pos Embedding: Sinusoidal Encoding 보다 Embedding Matrix가 더 좋음.
- Segment Embedding: 두개의 문장이 입력될 때, 각 문장에 다른 임베딩 부여.
History of LM: Google vs OpenAI
13
GPT-2 (1.5B)
14
OpenAI
GPT-2 (Google 2019, size: 1.5B)
- 요즘 NLP 모델들은 Specialist이다. 그러나 사람은 Generalist이다.
- BERT와 같은 모델은 Fine-tuning 하여 특정 태스크만 풀 수 있는 Specialist이다.
- 이들은 사람처럼 여러 작업을 수행하지 못하고 단 하나의 태스크만 풀 수 있다.
- Generalist는 “Fr” = translation(“En”)이 아닌, “Fr” = general(“En”, “translation”)
- Prompt Programming의 문을 열다.
- GPT-2는 GPT-1과 동일한 구조이지만 더 많은 데이터와 파라미터를 사용했다.
- 성능이 좋지는 않았지만 Fine-tuning 없이도 여러가지 태스크를 풀 수 있었다.
- 가령 Text를 넣고, TLDR; 을 붙이면 요약이 되고, 몇개의 예제를 주면 번역을 해냈다.
History of LM: Google vs OpenAI
15
VS
GPT-2 (Google 2019, size: 1.5B)
- Byte level BPE (BBPE)
- 기존의 BPE는 Unicode level (Character level BPE, CBPE) OOV의 발생이 잦았다.
- CBPE로 OOV가 없으려면 Vocab 사이즈가 13만 이상이여야 하는데 너무 큰 수치이다.
- 그러나 토큰을 Byte-level (Byte-level BPE, BBPE)로 쪼개면 256개면 OOV를 없앨 수 있다.
- Merging by category
- BPE 학습시 특수기호가 캐릭터에 merge 되면 해당 단어의 Repr이 학습되는 것을 방해한다.
- Dog! Dog? 같은 토큰들이 Transformer 모델이 Dog의 Repr을 학습하는 것을 방해한다.
- 따라서 GPT2는 다른 카테고리의 토큰끼리는 병합되지 않도록 BPE 학습을 설계했다.
History of LM: Google vs OpenAI
16
GPT-2 (Google 2019, size: 1.5B)
- Pre-Layer Normalization (Pre-LN)
- Transformer는 Layer가 깊어지면 Gradient가 커지는데, Pre-LN은 Layer와 Gradient가 반비례함.
- 따라서 Post LN은 Layer를 깊게 쌓으면 Gradient가 폭발하여 학습이 안되는 경우가 자주 발생함.
- Pre-LN은 Gradient가 상쇄되어 Layer가 깊어도 기존보다 안정적으로 학습되는 경향이 있음.
- Normalization Scaling
- Post-LN의 경우 Residual Branch: x + f(x)에서 f(x) 부분의 종속성이 강함.
- 그러면 학습이 진행되면서 학습 초기와 후반의 Output change가 커져서 학습이 불안정해짐.
- 따라서 이 Residual Branch에 1/sqrt(n_layer)를 곱해줘서 학습을 안정하게 만듦.
- https://github.com/kakaobrain/nlp-paper-reading/blob/master/notes/Admin.md 참고.
History of LM: Google vs OpenAI
17
T5 (11B)
18
Google
T5 (Google 2019, size: 11B)
- T5는 모든 태스크를 Seq2Seq 형태로 풀기위해 개발한 커다란 LM.
- 분류, 태깅, 요약, 번역 등의 모든 태스크를 Seq2Seq으로 풀었음.
- 파라미터의 수가 11B로 당시 최고 사이즈의 언어모델로 기록되었음.
- 각종 Objective, Architecture를 비교, 최고의 LM을 만들고자 함.
History of LM: Google vs OpenAI
19
T5 (Google 2019, size: 11B)
- 여러 아키텍처 중에서 Seq2Seq 아키텍처가 가장 좋다.
- Seq2Seq, Uni-LM, CLM(GPT) 중에서 Seq2Seq이 가장 우수.
- 다음 단어를 예측하는 GPT의 CLM보다 Denoising 하는게 더 좋다.
History of LM: Google vs OpenAI
20
T5 (Google 2019, size: 11B)
- 여러 Objective 중에서 Span-level Denosing이 제일 좋다.
- BERT나 MASS가 수행했던 Token-level Denoising 보다 SpanBERT
나 BART가 수행했던 Span-level Denosing의 성능이 더 좋음.
- Span length는 3 ~ 5, corruption ratio는 15% 정도가 적당함.
History of LM: Google vs OpenAI
21
T5 (Google 2019, size: 11B)
- 데이터의 양이 아주 많지 않다면, Unsupervised Pre-training이 좋다.
- 번역을 제외하고는 Unsupervised PT+ FT가 가장 우수함.
- mBART 논문에 따르면 Fine-tuning Training Dataset의 수가 너무 많으면 pre-training 때 배운 weight를 지워버림.
- 따라서 이런 경우는 pre-training이 큰 힘을 쓰지 못하기 때문에 supervised multi-task learning이 좋은 성능을 보임.
History of LM: Google vs OpenAI
22
23
갑자기 선을 넘어버리는 OpenAI...
NLP 연구자들
GPT-3 (175B)
24
OpenAI
GPT-3 (OpenAI 2020, size: 175B)
- OpenAI가 MS와 협업을 통해 1750억개의 파라미터를 가진 GPT-3를 발표.
- 21년 현재까지도 역사상 최고의 Language Model이라는 찬사를 받고 있음.
- Non-MoE Transformer 중에 현존하는 가장 큰 사이즈의 LM.
- 진짜 Generalist의 출현을 알리다.
- GPT-2때 가능성만 보여줬던, In-context learning (학습하지 않고 추론하는 것) 의 성능
을 웬만한 Supervised SoTA 모델 급의 성능까지 끌어올렸음
- 빅모델, 즉 Large-scale LM이라는 용어가 이 때 처음 유행하기 시작했으며 더 이상 특정
태스크를 위한 학습(파라미터 업데이트)이 필요 없게 되는 Paradigm Shift를 일으킴.
History of LM: Google vs OpenAI
25
GPT-3 (OpenAI 2020, size: 175B)
- GPT-3는 같은 해, 본인들이 연구했던 Scaling Law에 기반하였다.
- LM의 성능은 파라미터 수 N, 데이터 크기 D, 연산능력 C와 관계 있으며, 모델의 형태는 중요하지 않다.
- 즉, 컴퓨팅 파워가 세질수록, N과 D의 크기에 따라 LM 성능이 좌우된다.
- 모델의 오버피팅을 막기 위해서는 N이 10배 수준으로 커질 때, D도 5.5배 수준으로 커져야 한다.
- N이 큰 모델은 더 적은 데이터와 스텝만으로 N이 작은 모델과 동일한 수준에 도달할 수 있다.
- N이 고정되었을 때, 하이퍼 파라미터(n_layer, d_ff, n_head)는 Loss에 큰 영향은 주지 않는다.
- 따라서 Optimal Compute Budget allocation을 위해서는 컴퓨팅의 대부분을 N을 늘리는데 써야한다.
History of LM: Google vs OpenAI
26
GPT-3 (OpenAI 2020, size: 175B)
- GPT-3의 아키텍처는 GPT-2와 거의 유사하지만 사이즈에서 큰 차이가 있다.
- Scaling Law에 따라 Hyperparamter를 설정하였음.
- 최소 125M 부터 최대 175B에 해당하는 모델을 학습하였음.
- 여기서 설정한 175B은 당시 개발된 ZeRO-2의 최고 학습 사이즈.
- 하지만 이제 ZeRO-infinity가 나왔다고 하는데... (흠좀무)
- 연산 효율성을 위해 Sparse한 Local Attention을 사용했다.
- 이는 Sparse Transformer의 Attention과 유사함.
- Full Attention은 O(n^2)의 복잡도를 가지기 때문에 큰 모델에 적합하지 않음.
History of LM: Google vs OpenAI
27
GPT-3 (OpenAI 2020, size: 175B)
- 프롬프트에 Few-shot Examples의 수를 늘릴 수록 성능이 개선된다.
- 프롬프트에 들어가는 Few-shot Examples의 수에 따라 성능을 비교했다.
- Examples의 수가 늘어날 수록 성능이 일관되게 개선됨을 확인했다.
- 프롬프트에 Natural Language Description이 추가되면 성능이 개선된다.
- Natural Language Description은 T5에서 제안한 것과 유사하다.
- 이러한 Description을 프롬프트에 추가하면 성능이 개선되었다.
History of LM: Google vs OpenAI
28
GPT-3 (OpenAI 2020, size: 175B)
History of LM: Google vs OpenAI
29
30
킹받은 Google
회심의 일격을 준비하는데...
Switch Transformers (1T)
31
Google
Switch Transformers (Google 2021, size: 1T)
- 구글이 Trillion (1조) parameter를 가지는 Switch Transformers를 발표.
- 이전에 발표된 MoE Transformer와 GShard를 개선한 논문.
- MoE (Mixture of Experts) Transformer
- FFN을 여러개로 쪼갠 후, 토큰별로 FFN을 선택해서 사용.
- Mixture of Experts는 전문가의 연합이라는 뜻 (각각 FFN이 각 분야의 전문가)
- 꽤 오래전에 제안된 개념으로 각각 Expert가 서로 다른 능력을 배울 것이라고 가정
- Gating Network를 통해 토큰들이 특정 FFN 레이어를 배정받는 메커니즘.
- Gating Network 역시 Trainable Parameter로 다른부분들과 함께 학습됨.
History of LM: Google vs OpenAI
32
Switch Transformers (Google 2021, size: 1T)
- MoE Transformers는 하나의 토큰을 2개 이상의 FFN에 게이팅 되도록 하였다.
- 예를 들면 23번 토큰이 19번 FFN에도 할당되고 41번째 FFN에도 할당 되는 것.
- 한 토큰이 여러 FFN들 중에서 어떤 것에 더 적합한지 비교하는 능력을 배울 것이라는 가설.
- GShard: Scaling Giant Models with Conditional Computation and Automatic Sharding
- GShard는 각각의 FFN들을 각각의 Device에 나눠담는 방식.
- Attention, Norm등 파라미터는 모든 Device에 올리고, FFN만 각각 Device에 저장
- n번째 토큰이 k번째 FFN에 할당되면 k번째 FFN이 있는 Device로 포워딩되어 연산.
History of LM: Google vs OpenAI
33
Switch Transformers (Google 2021, size: 1T)
- GShard의 문제1: Load Balancing Problem
- 여러개의 FFN 중에서 일부의 FFN에만 토큰들이 엄청나게 몰리도록 학습 되었음.
- 예를 들면 100개의 FFN 중에서 5번, 8번만 자주 쓰이고 나머지 98개는 잘 안쓰는것.
- 특정 Device에만 부하가 걸리면 작업이 모두 끝날때까지 다른 Device는 기다려야함.
- 이로 인해 전체적인 프로세싱 효율이 매우 떨어졌음.
- GShard의 문제2: Gating Network의 Complexity
- 하나의 토큰을 FFN 여러개에 포워딩 하기 때문에 Gating 과정이 매우 복잡하고 느렸음.
History of LM: Google vs OpenAI
34
Switch Transformers (Google 2021, size: 1T)
- Switch Transformers: Scaling to Trillion Parameter Models with Simple and Efficient Sparsity
- GShard가 가진 문제들을 해결하기 위해 여러가지 메커니즘을 도입한 모델.
- Switch Routing (Top-1 Routing)
- 한 토큰 당 하나의 FFN에 할당해도 기존 가설과 다르게 성능에 큰 문제가 없었음.
- Routing Computation이 감소하고 Expert로 쏠리는 부하가 적어지며 구현도 심플해졌음.
History of LM: Google vs OpenAI
35
Switch Transformers (Google 2021, size: 1T)
- Capacity Factor
- 한개의 Expert가 입력받을 수 있는 최대 토큰의 수를 지정하고, 그 이상은 입력되지 않도록 함.
- 예를 들어 배치에 20,000개의 토큰이 있고 Expert의 수가 1,000개라면 capacity factor가 1.0
일 때, 한개의 Expert는 최대 20개의 Token을 입력받고 2.0이면 최대 40개의 토큰을 입력받음.
- 만약 특정 Expert에 최대치를 넘어서는 토큰이 할당되면 Logit 순서로 제외.
- 아예 FFN에 입력이 안되는 토큰도 생기는데 성능은 큰 차이가 없었고 속도도 빨랐음.
History of LM: Google vs OpenAI
36
Switch Transformers (Google 2021, size: 1T)
- Load Balancing Loss
- 높은 확률을 갖는 Expert의 Logit을 줄이는 Loss를 추가하여 학습.
- 이를 통해 토큰들이 특정 Expert에만 쏠리는 현상을 방지할 수 있었음.
- Smaller Parameter Initialization & Expert Dropout
- Initialization distribution의 scale을 작게 하니 성능이 많이 좋아짐.
- Expert / Non-Expert의 Dropout을 각각 다르게 적용.
History of LM: Google vs OpenAI
37
History of LM: Google vs OpenAI
38
Switch Transformers (Google 2021, size: 1T)
- Experiments
- 큰 모델일 수록 더 성능이 좋으며 낮은 Loss에 빠르게 도달한다.
- Sparse Model이기 때문에 파라미터가 많아도 FLOPS가 낮음.
- 따라서 동일 FLOPS의 T5와 비교해서 성능이 우수하다고 함. (약간 억지 같기도?)
- 재밌는건 T5-large (739M)의 성능이 Switch-Base (7.4B)보다 성능이 좋음.
History of LM: Google vs OpenAI
39
Switch Transformers (Google 2021, size: 1T)
- Distillation
- T5 223M 모델을 0%, Switch-base 3.8B 모델을 100%라고 가정.
- Switch-base를 T5 모델로 Distillation 했을 때, 30% 정도 성능을 개선시킬 수 있었음.
Chapter 2
🔥 Parallelism: Theory and Practice
(nn.DataParallel to ZeRO-infinity)
40
Fundamentals
(Parallelism Introduction, Message Passing)
41
Fundamentals
- Parallelism (병렬화)
- 병렬화는 여러개를 동시에 처리하는 기술을 의미함.
- 머신러닝에서는 주로 여러개의 디바이스에서 연산을 병렬화 하여 속도나 메모리 효율성을 개선하기 위해 사용
- 머신러닝 영역에서는 주로 세가지 병렬화 기법이 존재함.
Parallelism: Theory and Practice
42
Fundamentals
- Data Parallelism (데이터 병렬화)
- 데이터가 많을 때, 데이터를 병렬처리 하여 학습속도를 끌어올리는 작업.
- 모든 디바이스에 모델을 복사하고 서로 다른 데이터를 각 디바이스에 입력함.
- 이로 인해 배치사이즈를 디바이스 수의 배수만큼 더 많이 입력할 수 있음.
- 그러나 이러한 데이터 병렬화는 모델 하나가 디바이스 하나에 완전히 올라갈 때만 가능함.
Parallelism: Theory and Practice
43
Fundamentals
- Data Parallelism (데이터 병렬화)
- 데이터가 많을 때, 데이터를 병렬처리 하여 학습속도를 끌어올리는 작업.
- 모든 디바이스에 모델을 복사하고 서로 다른 데이터를 각 디바이스에 입력함.
- 이로 인해 배치사이즈를 디바이스 수의 배수만큼 더 많이 입력할 수 있음.
- 그러나 이러한 데이터 병렬화는 모델 하나가 디바이스 하나에 완전히 올라갈 때만 가능함.
Parallelism: Theory and Practice
44
배치 1~4
배치 5~8
배치 9~12
배치 12~16
Fundamentals
- Model Parallelism (모델 병렬화)
- 만약 모델이 너무 커서 하나의 디바이스에 담을 수 없을 때 파라미터를 쪼개서 올리는 방법.
- 각 디바이스에 모델의 파라미터 일부분들이 담겨있음.
- 이로 인해 큰 모델도 작은 디바이스 여러개를 이용하면 디바이스에 올릴 수 있음.
Parallelism: Theory and Practice
45
Fundamentals
- Model Parallelism (모델 병렬화)
- 만약 모델이 너무 커서 하나의 디바이스에 담을 수 없을 때 파라미터를 쪼개서 올리는 방법.
- 각 디바이스에 모델의 파라미터 일부분들이 담겨있음.
- 이로 인해 큰 모델도 작은 디바이스 여러개를 이용하면 디바이스에 올릴 수 있음.
Parallelism: Theory and Practice
46
레이어 1
레이어 3
레이어 2
레이어 4
Fundamentals
- Pipeline Parallelism (파이프라인 병렬화)
- 만약 Layer 단위로 모델 병렬화를 수행했다면 반드시 레이어들을 순서대로 실행해야함.
- 따라서 Layer 단위의 모델 병렬화를 수행하면 연산과정의 순서가 생길 수 밖에 없음.
- 이 연산과정을 병렬적으로 파이프라이닝 하는 것이 파이프라인 병렬화임. (뒤에서 자세히 다시 설명할 예정)
Parallelism: Theory and Practice
47
Parallelism: Theory and Practice
48
동시에 2개
레이어 처리
동시에 3개
레이어 처리
동시에 4개
레이어 처리
동시에 1개
레이어 처리
동시에 1개
레이어 처리
동시에 1개
레이어 처리
파이프라인 모델 병렬화 기존 모델 병렬화
device들의
쉬는 시간이 많음
Fundamentals
- Pipeline Parallelism (파이프라인 병렬화)
- 만약 Layer 단위로 모델 병렬화를 수행했다면 반드시 레이어들을 순서대로 실행해야함.
- 따라서 Layer 단위의 모델 병렬화를 수행하면 연산과정의 순서가 생길 수 밖에 없음.
- 이 연산과정을 병렬적으로 파이프라이닝 하는 것이 파이프라인 병렬화임. (뒤에서 자세히 다시 설명할 예정)
Fundamentals
- Message Passing (메시지 패싱)
- Message Passing은 동일한 주소 공간을 공유하지 않는 프로세스들이 데이터를 주고받을 수 있도록 메시지라는 간접
정보를 전달하고 주고 받는 것.
- 예를 들면 Process1이 특정 태그가 달린 데이터를 메시지 큐에 Send 하도록, Process2는 해당 태그가 달린 데이터를
메시지에서 Receive 받도록 코딩 해놓으면 메모리 공유 없이도 두 프로세스가 데이터를 주고 받게 됨.
Parallelism: Theory and Practice
49
Fundamentals
- MPI (Message Passing Interface)
- Message Passing에 대한 표준 인터페이스를 의미
- 대표적으로 OpenMPI라는 오픈소스 Message Passing 라이브러리가 있음.
- 프로세서간 Message Passing에 사용되는 여러가지 연산들이 정의되어 있음.
Parallelism: Theory and Practice
50
Fundamentals
- MPI (Message Passing Interface) 기본 용어
- Node: 일반적으로 컴퓨터라고 생각하면 됨. 하나의 Node에 여러대의 Device가 존재 가능.
- Global Rank: ML에서는 GPU의 ID라고 생각하면 됨 (원래는 프로세스의 우선순위)
- Local Rank: ML에서는 Node 안에서의 GPU ID라고 생각하면 됨. (원래는 노드내 프로세스의 우선순위)
- Size (World Size): ML에서는 전체 GPU의 수 (원래는 총 프로세스의 수)
Parallelism: Theory and Practice
51
Node 0: GPU0, GPU1, GPU2, GPU3
Node 1: GPU0, GPU1, GPU2, GPU3
Node 2: GPU0, GPU1, GPU2, GPU3
Node 0의 GPU1: Global Rank=01, Local Rank=01
Node 1의 GPU0: Global Rank=04, Local Rank=00
Node 2의 GPU3: Global Rank=11, Local Rank=03
Size: 12
Fundamentals
- Collective Communication
- MPI에서 제공하는 병렬처리 연산들. 더 많은 종류가 있는데 여기에서는 주요 4개 + 2개만 소개.
- 여러 프로세스들이 협력해서 통신하는 것이기 때문에 Collective Communication임.
- GPU에서 데이터나 Gradient 등을 전송할 때, 실제로 이러한 Collective Communication을 수행함.
Parallelism: Theory and Practice
52
Fundamentals
- Collective Communication: Broadcast
- 특정 Process에서 하나의 값을 복사해서 여러 Process들로 전송하는 연산.
Parallelism: Theory and Practice
53
Fundamentals
- Collective Communication: Scatter
- 특정 Process가 가진 배열의 값들을 다른 Process들로 쪼개서 전송하는 연산
Parallelism: Theory and Practice
54
Fundamentals
- Collective Communication: Gather
- 각 Process가 가진 값들을 특정한 하나의 Process에게 모으는 연산.
Parallelism: Theory and Practice
55
Fundamentals
- Collective Communication: Reduce
- 각 Process가 가진 값들을 특정한 하나의 Process에게 연산해서 모으는 연산.
- Gather와 비슷할 수도 있는데, 각 Process가 가진 연산을 하나의 값으로 만드는 것이 차이점.
Parallelism: Theory and Practice
56
Fundamentals
- Collective Communication: 정리
Parallelism: Theory and Practice
57
복사하기 쪼개기 모으기 연산하기
Fundamentals
- Collective Communication: All + ???
- 기본적인 4개의 연산 이외에 All + ???와 같은 이름을 가진 연산들도 있음.
- 이름 앞에 All이 붙으면 연산 결과를 참여한 모든프로세스가 동일하게 반환받는 연산임.
Parallelism: Theory and Practice
58
Fundamentals
- Collective Communication: All-Gather
- Gather 연산을 수행해서 모인 값들을 참여한 모든 Process가 반환받음.
- 기존 Gather 연산에서 하나의 Process가 결과를 반환받는 것과 대조됨.
Parallelism: Theory and Practice
59
Fundamentals
- Collective Communication: All-Reduce
- 마찬가지로 Reduce 연산을 수행해서 계산된 결과를 참여한 모든 Process가 반환받음.
- 기존 Reduce 연산에서 하나의 Process가 결과를 반환받는 것과 대조됨.
Parallelism: Theory and Practice
60
Fundamentals
- Collective Communication: NCCL (Nvidia Collective Communication Library)
- Nvidia에서 개발한 GPU 특화 Collective Communication Library (‘Nickel’이라고 읽음)
- Nvidia GPU에서 사용시 다른 도구에 비해 월등히 탁월한 성능을 보이는 것으로 알려져 있음.
- Nvlink (다중 GPU 연결 인터페이스)를 직접 활용하여 매우 높은 대역폭에서 전송 가능.
Parallelism: Theory and Practice
61
Nvlink
Data Parallelism
(Pytorch, Horovod, Pytorch-distributed)
62
Data Parallelism
- nn.DataParallel( )
- Data Parallelism은 All-reduce 연산을 활용하기 전과 후로 나뉨.
- 가장 먼저 우리에게 익숙한 torch의 nn.DataParallel(model)의 동작방식에 대해 알아봄.
- nn.DataParallel( )은 single-node & multi-gpu에서 모델을 학습하기 위한 멀티 쓰레드 모듈.
https://medium.com/daangn/pytorch-multi-gpu-학습-제대로-하기-27270617836b
Parallelism: Theory and Practice
63
Data Parallelism
- nn.DataParallel( ): Forward Pass
- 1) 입력된 mini-batch를 scatter하여 각 디바이스로 전송.
- 2) GPU1에 저장된 모델의 파라미터를 GPU 2, 3, 4로 replicate하여 전송.
- 3) 각 device로 복사된 모델로 Forward 하여 출력값을 구함.
- 4) 출력값들을 gather하여 GPU1에 모음.
https://medium.com/daangn/pytorch-multi-gpu-학습-제대로-하기-27270617836b
Parallelism: Theory and Practice
64
Data Parallelism
- nn.DataParallel( ): Backward Pass
- 1) GPU1의 Gather된 출력값과 Label을 이용하여 각각의 Loss를 계산.
- 2) 계산된 각각의 Loss를 각각의 device에 scatter함.
- 3) 전달받은 Loss를 이용해서 각 device에서 backward를 수행.
- 4) 모든 gradient를 GPU1로 reduce하여 GPU1의 모델 파라미터를 업데이트.
https://medium.com/daangn/pytorch-multi-gpu-학습-제대로-하기-27270617836b
Parallelism: Theory and Practice
65
Data Parallelism
- nn.DataParallel( ): 혹시나 모르시는 분들을 위해…...
- loss.backward( ): 기울기를 미분해서 Gradient만 계산 (parallel)
- optimizer.step( ): Gradient를 이용해서 파라미터 업데이트 (sequential)
- Computation Cost는 backward( ) > step( )
https://medium.com/daangn/pytorch-multi-gpu-학습-제대로-하기-27270617836b
Parallelism: Theory and Practice
66
optimizer.step()
loss.backward()
+ 모멘텀, Weight Decay 등
Data Parallelism
- nn.DataParallel( ): Codes
- 사용할 땐, `nn.DataParallel(model)`만 호출해주면 됨.
https://medium.com/daangn/pytorch-multi-gpu-학습-제대로-하기-27270617836b
Parallelism: Theory and Practice
67
import torch


import torch.nn as nn


model = BERT(args)


model = nn.DataParallel(model)


model.cuda()


...


for i, (inputs, labels) in enumerate(train_loader):


outputs = model(inputs)


loss = criterion(outputs, labels)




optimizer.zero_grad()


loss.backward()


optimizer.step()
Data Parallelism
- nn.DataParallel( ): Codes
- `nn.DataParallel(model)`의 forward를 코드로 나타내면 다음과 같음.
https://medium.com/daangn/pytorch-multi-gpu-학습-제대로-하기-27270617836b
Parallelism: Theory and Practice
68
def data_parallel(module, input, device_ids, output_device):


inputs = nn.parallel.scatter(input, device_ids)


# 입력 데이터를 device_ids들에 Scatter함


replicas = nn.parallel.replicate(module, device_ids)


# 모델을 device_ids들에 복제함.




outputs = nn.parallel.parallel_apply(replicas, inputs)


# 각 device에 복제된 모델이 각 device의 데이터를 Forward함.


return nn.parallel.gather(outputs, output_device)


# 모델의 출력값을 output_device(하나의 device)로 모음
Data Parallelism
- nn.DataParallel( ): Codes
- torch-lightning을 사용하면 매우 쉽게 사용 가능.
https://medium.com/daangn/pytorch-multi-gpu-학습-제대로-하기-27270617836b
Parallelism: Theory and Practice
69
from pytorch_lightining import Trainer


lightning_model = ...


trainer = Trainer(


args,


accelerator=‘dp’, # <—— 여기 한줄만 바꾸면 됨.


)


Trainer.fit(


lightning_model, train_loader, val_loader,


)
Data Parallelism
- nn.DataParallel( ): Codes
https://medium.com/daangn/pytorch-multi-gpu-학습-제대로-하기-27270617836b
Parallelism: Theory and Practice
70
0번 디바이스에 Output들이
Gather되기 때문에 사용량이 많음.
근데 만약에 GPU 잘못 꽂아서
0번 Device가 8GB이고, 1번 Device가 32GB면?
—> 아… 빼서 다시 꽂아야 하나…
Data Parallelism
- nn.DataParallel( ): Codes
- `os.environ[‘CUDA_VISIBLE_DEVICE’]`를 이용해 사용할 GPU 선택
- `nn.DataParallel(model)`에 output_device를 설정하여 output을 gather 받을 device 선택
https://medium.com/daangn/pytorch-multi-gpu-학습-제대로-하기-27270617836b
Parallelism: Theory and Practice
71
import os


import torch.nn as nn


os.environ["CUDA_VISIBLE_DEVICES"] = '0, 1, 2, 3’


# 4개의 device를 사용함


model = nn.DataParallel(model, output_device=1)


# Gradient를 1번 device에 Gather함.
Data Parallelism
- nn.DataParallel( ): 문제점
- (1) 멀티쓰레드 모듈이기 때문에 python에서 비효율적임 (GIL 참고)
- (2) GPU1에서 업데이트된 모델을 매 스텝마다 모든 device로 replicate 해야 함.
- (3) 메모리 불균형이 일어나서 GPU를 100% 활용할 수 없음.
https://medium.com/daangn/pytorch-multi-gpu-학습-제대로-하기-27270617836b
Parallelism: Theory and Practice
72
Data Parallelism
- nn.DataParallel( ): 문제점
- (1) 멀티쓰레드 모듈이기 때문에 python에서 비효율적임 (GIL 참고) ——> 멀티 쓰레드의 문제
- (2) GPU1에서 업데이트된 모델을 매 스텝마다 모든 device로 replicate 해야 함.
- (3) 메모리 불균형이 일어나서 GPU를 100% 활용할 수 없음.
https://medium.com/daangn/pytorch-multi-gpu-학습-제대로-하기-27270617836b
Parallelism: Theory and Practice
73
Data Parallelism
- nn.DataParallel( ): 문제점
- (1) 멀티쓰레드 모듈이기 때문에 python에서 비효율적임 (GIL 참고) ——> 멀티 쓰레드의 문제
- (2) GPU1에서 업데이트된 모델을 매 스텝마다 모든 device로 replicate 해야 함.
- (3) 메모리 불균형이 일어나서 GPU를 100% 활용할 수 없음.
https://medium.com/daangn/pytorch-multi-gpu-학습-제대로-하기-27270617836b
Parallelism: Theory and Practice
74
Data Parallelism
- nn.DataParallel( ): Memory Imbalance
- 메모리 불균형이 일어나는 이유는 Loss 함수가 Parallel 하지 않기 때문.
- Loss 함수가 Parallel하지 않기 때문에 GPU 1개로 모든 Output을 모아서 Loss를 계산함
- => Parallel Loss 함수를 구현해서 Output을 모으지 않고 각 device에서 계산하면 됨.
https://medium.com/daangn/pytorch-multi-gpu-학습-제대로-하기-27270617836b
Parallelism: Theory and Practice
75
Data Parallelism
- nn.DataParallel( ): Memory Imbalance
https://medium.com/daangn/pytorch-multi-gpu-학습-제대로-하기-27270617836b
Parallelism: Theory and Practice
76
1. Scatter Labels
2. Parallel Loss Computation
Data Parallelism
- nn.DataParallel( ): Memory Imbalance
https://medium.com/daangn/pytorch-multi-gpu-학습-제대로-하기-27270617836b
Parallelism: Theory and Practice
77
from torch.nn.parallel.data_parallel import DataParallel


class DataParallelCriterion(DataParallel):


def forward(self, inputs, *targets, **kwargs):


targets, kwargs = self.scatter(targets, kwargs, self.device_ids)


# 라벨을 각 device들로 Scatter함.


replicas = self.replicate(self.module, self.device_ids)


# self.module(loss함수)을 device들에 복제함.


outputs = _criterion_parallel_apply(replicas, inputs, targets, kwargs)


# 병렬 criterion을 이용해 각 device의 loss를 계산 

return Reduce.apply(*outputs) / len(outputs), targets


# 계산한 outputs을 Reduce하여 Backward 연산을 할 수 있도록 함.
Data Parallelism
- nn.DataParallel( ): Memory Imbalance
https://medium.com/daangn/pytorch-multi-gpu-학습-제대로-하기-27270617836b
Parallelism: Theory and Practice
78
import torch


import torch.nn as nn


from parallel import DataParallelModel, DataParallelCriterion


model = BERT(args)


model = DataParallelModel(model)


model.cuda()


...


criterion = nn.NLLLoss()


criterion = DataParallelCriterion(criterion)


for i, (inputs, labels) in enumerate(trainloader):


outputs = model(inputs)


loss = criterion(outputs, labels)


optimizer.zero_grad()


loss.backward()


optimizer.step()
커스텀 ParallelCriterion 사용
커스텀 ParallelCriterion을 사용하면 nn.DataParallel( )이 아니라
nn.DataParallelModel( )을 사용해야 함.
nn.DataParallel( )은 기본적으로 Outputs을 Gather하게 구현 됨.
Data Parallelism
- nn.DataParallel( ): Memory Imbalance
https://medium.com/daangn/pytorch-multi-gpu-학습-제대로-하기-27270617836b
Parallelism: Theory and Practice
79
GPU 사용량이 감소했음.
Data Parallelism
- nn.DataParallel( ): 문제점
- (1) 멀티쓰레드 모듈이기 때문에 python에서 비효율적임 (GIL 참고) ——> 멀티 쓰레드의 문제
- (2) GPU1에서 업데이트된 모델을 매 스텝마다 모든 device로 replicate 해야 함.
- (3) 메모리 불균형이 일어나서 GPU를 100% 활용할 수 없음.
Parallelism: Theory and Practice
80
Data Parallelism
- nn.DataParallel( ): 문제점
- (1) 멀티쓰레드 모듈이기 때문에 python에서 비효율적임 (GIL 참고) ——> 멀티 쓰레드의 문제
- (2) GPU1에서 업데이트된 모델을 매 스텝마다 모든 device로 replicate 해야 함.
- (3) 메모리 불균형이 일어나서 GPU를 100% 활용할 수 없음.
Parallelism: Theory and Practice
81
Data Parallelism
- nn.DataParallel( ): All-reduce
- 하나의 GPU에서 파라미터를 업데이트하고 업데이트된 파라미터를 매 스텝마다 replicate 해야함.
- 만약 Gradient를 Reduce 하지 않고 평균을 계산해서 모든 device로 전송할 수 있다면? ——> All-reduce
- Gradient의 평균으로 각 device에서 파라미터를 업데이트 한다면 모델을 매번 replicate 하지 않아도 됨.
Parallelism: Theory and Practice
82
Data Parallelism
- nn.DataParallel( ): All-reduce
- 따라서 기존의 nn.DataParallel( )을 개선하려면 All-reduce를 사용해서 Gradient의 평균을 모든 device로 전송하면 됨.
- 그러나 All-reduce는 상당히 비용이 높은 연산임.
- All-reduce의 구현:
- (1) Reduce ——> Broadcast
Parallelism: Theory and Practice
83
- (1) Gradient를 Reduce하여 평균을 GPU1에 저장
- (2) 평균값을 다른 디바이스로 Broadcast
마스터 프로세스(GPU1)의 부하가 심해지며,
프로세스(GPU) 수가 증가할 때마다 통신비용이 매우 커짐.
Data Parallelism
- nn.DataParallel( ): All-reduce
- 따라서 기존의 nn.DataParallel( )을 개선하려면 All-reduce를 사용해서 Gradient의 평균을 모든 device로 전송하면 됨.
- 그러나 All-reduce는 상당히 비용이 높은 연산임.
- All-reduce의 구현:
- (2) All-to-All (Collective Communication 연산 중 하나)
Parallelism: Theory and Practice
84
- (1) 모든 디바이스가 개별 통신을 하여 값을 전송함.
- (2) n개의 장비가 있을 때, 약 n^2의 통신이 발생함.
마찬가지로 프로세스 수가 증가할 때마다 통신비용이 심하게 커진다.
Data Parallelism
- nn.DataParallel( ): All-reduce
- 그러나 Baidu에서 Ring All-reduce라는 알고리즘을 제안.
- Ring All-reduce를 이용하면 All-reduce를 매우 효과적으로 수행 할 수 있음.
- All-reduce의 구현:
- (3) Ring All-reduce
Parallelism: Theory and Practice
85
GPU: 0
GPU: 3 GPU: 1
GPU: 2
g0
g2
g1
g3
Data Parallelism
- nn.DataParallel( ): All-reduce
- 그러나 Baidu에서 Ring All-reduce라는 알고리즘을 제안.
- Ring All-reduce를 이용하면 All-reduce를 매우 효과적으로 수행 할 수 있음.
- All-reduce의 구현:
- (3) Ring All-reduce
Parallelism: Theory and Practice
86
GPU: 0
GPU: 3 GPU: 1
GPU: 2
g0
g1
g2
g3
g = g0 + g1 + g2 + g3를 계산해서 모든 GPU로 전송해야 함.
Parallelism: Theory and Practice
87
GPU: 0
GPU: 3 GPU: 1
GPU: 2
g0
g2
g1
g3
g0
Data Parallelism
- nn.DataParallel( ): All-reduce
- 그러나 Baidu에서 Ring All-reduce라는 알고리즘을 제안.
- Ring All-reduce를 이용하면 All-reduce를 매우 효과적으로 수행 할 수 있음.
- All-reduce의 구현:
- (3) Ring All-reduce
Parallelism: Theory and Practice
88
GPU: 0
GPU: 3 GPU: 1
GPU: 2
g0
g2
g0 + g1
g3
g0
Data Parallelism
- nn.DataParallel( ): All-reduce
- 그러나 Baidu에서 Ring All-reduce라는 알고리즘을 제안.
- Ring All-reduce를 이용하면 All-reduce를 매우 효과적으로 수행 할 수 있음.
- All-reduce의 구현:
- (3) Ring All-reduce
Parallelism: Theory and Practice
89
GPU: 0
GPU: 3 GPU: 1
GPU: 2
g0
g2
g0 + g1
g3
g0 + g1
Data Parallelism
- nn.DataParallel( ): All-reduce
- 그러나 Baidu에서 Ring All-reduce라는 알고리즘을 제안.
- Ring All-reduce를 이용하면 All-reduce를 매우 효과적으로 수행 할 수 있음.
- All-reduce의 구현:
- (3) Ring All-reduce
Parallelism: Theory and Practice
90
GPU: 0
GPU: 3 GPU: 1
GPU: 2
g0
g0 + g1 + g2
g0 + g1
g3
g0 + g1
Data Parallelism
- nn.DataParallel( ): All-reduce
- 그러나 Baidu에서 Ring All-reduce라는 알고리즘을 제안.
- Ring All-reduce를 이용하면 All-reduce를 매우 효과적으로 수행 할 수 있음.
- All-reduce의 구현:
- (3) Ring All-reduce
Parallelism: Theory and Practice
91
GPU: 0
GPU: 3 GPU: 1
GPU: 2
g0
g0 + g1 + g2
g0 + g1
g3
g0 + g1 + g2
Data Parallelism
- nn.DataParallel( ): All-reduce
- 그러나 Baidu에서 Ring All-reduce라는 알고리즘을 제안.
- Ring All-reduce를 이용하면 All-reduce를 매우 효과적으로 수행 할 수 있음.
- All-reduce의 구현:
- (3) Ring All-reduce
Parallelism: Theory and Practice
92
GPU: 0
GPU: 3 GPU: 1
GPU: 2
g0
g0 + g1 + g2
g0 + g1
g0 + g1 + g2 + g3
g0 + g1 + g2
Data Parallelism
- nn.DataParallel( ): All-reduce
- 그러나 Baidu에서 Ring All-reduce라는 알고리즘을 제안.
- Ring All-reduce를 이용하면 All-reduce를 매우 효과적으로 수행 할 수 있음.
- All-reduce의 구현:
- (3) Ring All-reduce
Parallelism: Theory and Practice
93
GPU: 0
GPU: 3 GPU: 1
GPU: 2
g0
g0 + g1 + g2
g0 + g1
g = g0 + g1 + g2 + g3
Data Parallelism
- nn.DataParallel( ): All-reduce
- 그러나 Baidu에서 Ring All-reduce라는 알고리즘을 제안.
- Ring All-reduce를 이용하면 All-reduce를 매우 효과적으로 수행 할 수 있음.
- All-reduce의 구현:
- (3) Ring All-reduce
Parallelism: Theory and Practice
94
GPU: 0
GPU: 3 GPU: 1
GPU: 2
g0
g0 + g1 + g2
g0 + g1
g
Data Parallelism
- nn.DataParallel( ): All-reduce
- 그러나 Baidu에서 Ring All-reduce라는 알고리즘을 제안.
- Ring All-reduce를 이용하면 All-reduce를 매우 효과적으로 수행 할 수 있음.
- All-reduce의 구현:
- (3) Ring All-reduce
Parallelism: Theory and Practice
95
GPU: 0
GPU: 3 GPU: 1
GPU: 2
g0
g0 + g1 + g2
g0 + g1
g
g
Data Parallelism
- nn.DataParallel( ): All-reduce
- 그러나 Baidu에서 Ring All-reduce라는 알고리즘을 제안.
- Ring All-reduce를 이용하면 All-reduce를 매우 효과적으로 수행 할 수 있음.
- All-reduce의 구현:
- (3) Ring All-reduce
Parallelism: Theory and Practice
96
GPU: 0
GPU: 3 GPU: 1
GPU: 2
g
g0 + g1 + g2
g0 + g1
g
g
Data Parallelism
- nn.DataParallel( ): All-reduce
- 그러나 Baidu에서 Ring All-reduce라는 알고리즘을 제안.
- Ring All-reduce를 이용하면 All-reduce를 매우 효과적으로 수행 할 수 있음.
- All-reduce의 구현:
- (3) Ring All-reduce
Parallelism: Theory and Practice
97
GPU: 0
GPU: 3 GPU: 1
GPU: 2
g
g0 + g1 + g2
g0 + g1
g
g
Data Parallelism
- nn.DataParallel( ): All-reduce
- 그러나 Baidu에서 Ring All-reduce라는 알고리즘을 제안.
- Ring All-reduce를 이용하면 All-reduce를 매우 효과적으로 수행 할 수 있음.
- All-reduce의 구현:
- (3) Ring All-reduce
Parallelism: Theory and Practice
98
GPU: 0
GPU: 3 GPU: 1
GPU: 2
g
g0 + g1 + g2
g
g
g
Data Parallelism
- nn.DataParallel( ): All-reduce
- 그러나 Baidu에서 Ring All-reduce라는 알고리즘을 제안.
- Ring All-reduce를 이용하면 All-reduce를 매우 효과적으로 수행 할 수 있음.
- All-reduce의 구현:
- (3) Ring All-reduce
Parallelism: Theory and Practice
99
GPU: 0
GPU: 3 GPU: 1
GPU: 2
g
g0 + g1 + g2
g
g
g
Data Parallelism
- nn.DataParallel( ): All-reduce
- 그러나 Baidu에서 Ring All-reduce라는 알고리즘을 제안.
- Ring All-reduce를 이용하면 All-reduce를 매우 효과적으로 수행 할 수 있음.
- All-reduce의 구현:
- (3) Ring All-reduce
Parallelism: Theory and Practice
100
GPU: 0
GPU: 3 GPU: 1
GPU: 2
g
g
g
g
g
Data Parallelism
- nn.DataParallel( ): All-reduce
- 그러나 Baidu에서 Ring All-reduce라는 알고리즘을 제안.
- Ring All-reduce를 이용하면 All-reduce를 매우 효과적으로 수행 할 수 있음.
- All-reduce의 구현:
- (3) Ring All-reduce
Parallelism: Theory and Practice
101
GPU: 0
GPU: 3 GPU: 1
GPU: 2
g
g
g
g
Weight Update
Data Parallelism
- nn.DataParallel( ): All-reduce
- 그러나 Baidu에서 Ring All-reduce라는 알고리즘을 제안.
- Ring All-reduce를 이용하면 All-reduce를 매우 효과적으로 수행 할 수 있음.
- All-reduce의 구현:
- (3) Ring All-reduce
w ← w - α · g
w ← w - α · g
w ← w - α · g
Parallelism: Theory and Practice
102
GPU: 0
GPU: 3 GPU: 1
GPU: 2
w ← w - α · g
Weight Update
Data Parallelism
- nn.DataParallel( ): All-reduce
- 그러나 Baidu에서 Ring All-reduce라는 알고리즘을 제안.
- Ring All-reduce를 이용하면 All-reduce를 매우 효과적으로 수행 할 수 있음.
- All-reduce의 구현:
- (3) Ring All-reduce
Parallelism: Theory and Practice
103
w ← w - α · g
GPU: 0
GPU: 3 GPU: 1
GPU: 2
Weight Update
w ← w - α · g
w ← w - α · g
w ← w - α · g
- (1) 마스터 프로세스를 사용하지 않기 때문에 특정 device로 부하가 쏠리지 않음.
- (2) All-to-All 처럼 비효율적인 연산을 수행하지 않음.
- (3) 효율적인 방식으로 모든 device의 파라미터를 동시에 업데이트하기 때문에 파라
미터를 매번 replicate 하지 않아도 됨.
Data Parallelism
- nn.DataParallel( ): All-reduce
- 그러나 Baidu에서 Ring All-reduce라는 알고리즘을 제안.
- Ring All-reduce를 이용하면 All-reduce를 매우 효과적으로 수행 할 수 있음.
- All-reduce의 구현:
- (3) Ring All-reduce
Data Parallelism
- Horovod
- Ring All-reduce를 사용, Uber에서 개발한 Distributed Deep Learning Library.
- Tensorflow, Pytorch, MXNet, Keras 등 다양한 백엔드 지원.
- single/multi-node & multi-gpu 모델을 학습하기 위한 멀티프로세싱 모듈.
Parallelism: Theory and Practice
104
Data Parallelism
- Horovod
- All-reduce를 사용하면 마스터 프로세스 개념이 없어지기 때문에 학습 과정이 매우 심플해짐.
Parallelism: Theory and Practice
105
2. Forward 수행 3. Backward 수행 4. Gradient
All-reduce
5. 파라미터 업데이트
1. 데이터 Scatter
Data Parallelism
- Horovod: Parameter Server
- All-reduce가 도입되기 이전의 multi-node distributed training은 주로 Parameter Server를 통해 이루어졌음.
- Parameter Server는 nn.DP에서 Gradient를 Reduce 받는 마스터 프로세스와 비슷한 역할을 하는 서버임.
- 노드의 개수가 많아지면, Parameter Server 한대로는 감당이 안되기 때문에 여러대의 서버를 사용하기도 하였음.
Parallelism: Theory and Practice
106
Data Parallelism
- Horovod: Parameter Server 문제점
- (1) 몇대의 워커 노드와 몇대의 파라미터 서버를 쓰는지에 따라 속도 차이가 생기는데 이것을 configure하기 어려움.
Parallelism: Theory and Practice
107
워커 노드
파라미터 서버
Data Parallelism
- Horovod: Parameter Server 문제점
- (2) 또한 Communication이 느리고 Worker가 줄어들기 때문에 Ideal한 속도에 비해 한참 못 미치는 속도를 보여줌.
Parallelism: Theory and Practice
108
Data Parallelism
- Horovod
- Horovod는 Ring All-reduce를 사용해서 문제를 해결하였음.
- Parameter Server 없이 모든 노드를 Worker로 사용하여 성능을 개선했음.
Parallelism: Theory and Practice
109
Data Parallelism
- Horovod
- Horovod는 Ring All-reduce를 사용해서 문제를 해결하였음.
- Parameter Server 없이 모든 노드를 Worker로 사용하여 성능을 개선했음.
Parallelism: Theory and Practice
110
Data Parallelism
- Horovod: Tensor Fusion
- 또한 Horovod는 Tensor Fusion이라는 기술을 통해 성능을 더 개선했음. (65%↑)
- 전송하는 데이터의 크기가 작은 경우, All-reduce 연산시에 오버헤드가 매우 많이 발생해서 성능이 떨어졌다고 함.
- 그래서 일정한 사이즈의 버퍼를 만들어놓고 텐서를 저장하다가, 버퍼가 가능 차면 전송하는 방식을 채택함.
- 이후에 말할 DDP의 Gradient Bucketing과 비슷한 메커니즘. 이후에 더 자세히 설명함.
Parallelism: Theory and Practice
111
Data Parallelism
- Horovod: RDMA
- RDMA는 Remote device의 memory에 직접 access하여 값을 쓰거나 읽는 방식.
- TCP 통신에 비해 RDMA가 속도가 더 빨랐다고 함.
Parallelism: Theory and Practice
112
Data Parallelism
- Horovod: Codes
- (1) 먼저 Open MPI 설치
- https://www.open-mpi.org/software/ompi/v4.0/ 다운로드 후 압축 해제
- (2) 그리고나서 NCCL 설치
- https://docs.nvidia.com/deeplearning/sdk/nccl-install-guide/index.html
- (3) 마지막으로 Horovod를 설치
Parallelism: Theory and Practice
113
$ cd openmpi-VERSION


$ ./configure —-prefix=/usr/local


$ make all install
$ HOROVOD_GPU_ALLREDUCE=NCCL pip install horovod
Data Parallelism
- Horovod: Codes
- Horovod 코드 작성
Parallelism: Theory and Practice
114
import torch


import horovod.torch as hvd


from torch.utils.data.distributed import DistributedSampler


from torch.utils.data import DataLoader


hvd.init()


# horovod initialization 수행


torch.cuda.set_devices(hvd.local_rank())


# Local rank로서 사용할 GPU 고정


train_dataset = ...


# 데이터셋 정의


train_sampler = DistributedSampler(


train_dataset,


num_replicas=hvd.size(), # replication할 device 개수


rank=hvd.rank(),


)


# sampler 생성


train_loader = DataLoader(


train_dataset,


batch_size=...,


sampler=train_sampler,


)


# 데이터로더 생성
Parallelism: Theory and Practice
115
model = BERT(args)


model.cuda()


# 모델 생성


optimizer = torch.optim.SGD(model.parameters())


optimizer = hvd.DistributedOptimizer(


optimizer,


named_parameters=model.named_parameters(),


)


# 옵티마이저를 DistributedOptimizer로 만들어줘야 함.


Data Parallelism
- Horovod: Codes
- Horovod 코드 작성
hvd.broadcast_parameters(


model.state_dict(),


root_rank=0


)


# all-reduce 기반의 프레임워크들은 최초 1회만 모델을 Broadcast.


for epoch in range(100):


for idx, (data, target) in enumerate(train_loader):


optimizer.zero_grad()


output = model(data)


loss = torch.nn.functional.nll_loss(output, target)


loss.backward()


optimizer.step()


# 학습 수행
Parallelism: Theory and Practice
116
Data Parallelism
- Horovod: Codes
- np: number of process (world size)
- H: hosted servers + “:n_gpu”
$ horovodrun —np=8 


-H XXX.XXX.XXX.XXX:4, YYY.YYY.YYY.YYY:4 


python train.py
Parallelism: Theory and Practice
117
Data Parallelism
- Horovod: Codes
- torch-lightning을 사용하면 매우 쉽게 사용 가능.
$ horovodrun -np=8 


-H XXX.XXX.XXX.XXX:4, YYY.YYY.YYY.YYY:4 


python train.py
from pytorch_lightining import Trainer


lightning_model = ...


trainer = Trainer(


args,


accelerator=‘horovod’, # <—— 여기 한줄만 바꾸면 됨.


)


Trainer.fit(


lightning_model, train_loader, val_loader,


)
Parallelism: Theory and Practice
118
Data Parallelism
- nn.parallel.DistributedDataParallel( )
- Pytorch로 구현된 All-reduce distributed training 모듈.
- single/multi-node & multi-gpu에서 모델을 학습하기 위한 멀티 프로세싱 모듈.
Parallelism: Theory and Practice
119
Data Parallelism
- nn.parallel.DistributedDataParallel( )
- backward( )와 step( ) 중에서 언제 All-reduce를 실행하는게 좋은지 실험.
2. Forward 수행 3. Backward 수행 4. Gradient
All-reduce
5. 파라미터 업데이트
1. 데이터 Scatter
import torch


import torch.nn as nn


import torch.optim as optim


net = nn.Linear(10, 10)


opt = optim.SGD(net.parameters())


input, target = ...


out = net(input)


loss = nn.MSELoss(out, target)


loss.backward()


opt.step()


Which one is better?
Data Parallelism
- nn.parallel.DistributedDataParallel( )
- 결과적으로 backward( )에서 수행하는 것이 훨씬 효율적임.
- 분석 결과 backward( )가 훨씬 무거운 연산임.
- 따라서 Computation과 Communication을 더 많이 Overlap 시킬 수 있어서 효율적.
Parallelism: Theory and Practice
120
Backward의
Computation이 훨씬 큼
Backward( )
Step( )
Data Parallelism
- nn.parallel.DistributedDataParallel( )
- backward( ) 연산을 수행하면서 중간중간 나온 Gradient를 계속 All-reduce 하는 것임.
- backward( ) 연산을 수행하는 동시에 All-reduce 하는 것이 기다렸다가 시작하는 것 보다 효율적.
Parallelism: Theory and Practice
121
step( ) 때 실행
(Overlap을 하지 않은 경우)
backward( ) 도중에 실행
(Overlap을 한 경우)
Data Parallelism
- nn.parallel.DistributedDataParallel( )
- Q1: backward( ) 연산 중에 Gradient가 다 계산되지 않았는데 어떻게 All-reduce를 수행합니까?
- A1: backward( )는 뒤쪽 Layer부터 순차적으로 이루어지기 때문에 계산이 끝난 것을 먼저 전송하면 됩니다.
- Q2: 그렇다면 언제마다 All-reduce가 수행되나요? 기준이 있나요?
- A2: Gradient Bucketing을 수행합니다. Bucket이 가득차면 그 때 All-reduce를 수행합니다.
Parallelism: Theory and Practice
122
Data Parallelism
- nn.parallel.DistributedDataParallel( ): Gradient Bucketing
- Horovod의 Tensor Fusion과 유사한 방식, backward( ) 연산 도중에 뒤쪽 부터 계산된 Gradient를 버킷에 저장.
- 버킷의 용량이 가득차게 되면 All-reduce를 수행해서 각 device에 Gradient의 평균을 전달함.
- 그림 때문에 헷갈릴 수도 있는데, 버킷에 저장되는 것은 모델의 파라미터가 아닌, 해당 레이어에서 나온 Gradient임.
- 모든 Bucket은 일정한 size를 가지고 있으며 `bucket_size_mb`라는 인자를 통해 버킷 사이즈를 변경 가능. (Mega byte level)
Parallelism: Theory and Practice
123
Backward
가장 뒤쪽 레이어의 Gradient를 가장 먼저
All-reduce로 평균을 계산하여 교환함
2개 이상의 Layer에서 출력된 Gradient가 1개의 Bucket에
들어갈 수도 있음. Gradient와 버킷의 크기에 따라 다름.
Bucket1에 해당하는 Layer가 Backward를 수행할 땐,
Bucket2, 3은 All-reduce를 수행하고 있을 수 있음.
Data Parallelism
- nn.parallel.DistributedDataParallel( ): Codes
- 프로세스 그룹 초기화 및 학습 코드 작성
Parallelism: Theory and Practice
124
def worker(rank, ngpus_per_node, args):


torch.cuda.set_device(rank)


# 현재 프로세스에서 사용중인 디바이스 등록


dist.init_process_group(


backend='nccl',


init_method='tcp://127.0.0.1:FREEPORT',


world_size=args.world_size,


rank=rank


)


# 프로세스 그룹 초기화


model = Bert(args)


model.cuda(rank)


model = DistributedDataParallel(model, device_ids=[args.gpus])


# model = DistributedDataParallel(model, device_ids=[args.gpus], bucket_size_mb=???)


# DistributedDataParallel으로 모델 wrapping


for i in range(args.num_epochs):


... 학습 루프 ...
Data Parallelism
- nn.parallel.DistributedDataParallel( ): Codes
- DDP 학습 실행코드 작성.
Parallelism: Theory and Practice
125
import torch.distributed as dist


import torch.multiprocessing as mp


from torch.nn.parallel import DistributedDataParallel


def main():


args = parser.parse_args()


ngpus_per_node = torch.cuda.device_count()


mp.spawn(


worker,


nprocs=ngpus_per_node,


args=(ngpus_per_node, args),


join=True


)


# 멀티프로세싱 spawn 시작


if __name__ == “__main__”:


main()
python -m torch.distributed.launch 


—-nproc_per_node=4 main.py 


—-world_size 2 


—-gpus 0 1 2 3 


—-num_epochs 10 


--batch_size 60
학습 시작
Data Parallelism
- nn.parallel.DistributedDataParallel( ): Codes
- torch-lightning을 사용하면 매우 쉽게 사용 가능.
Parallelism: Theory and Practice
126
from pytorch_lightining import Trainer


lightning_model = ...


trainer = Trainer(


args,


accelerator=‘ddp’, # <—— 여기 한줄만 바꾸면 됨.


)


Trainer.fit(


lightning_model, train_loader, val_loader,


)
Model Parallelism
(Mesh-tensorflow, Megatron-LM, Examples)
127
Model Parallelism
- Inter-layer model parallelism
- 아까 그림에서 봤던 것 처럼 Layer-wise로 모델을 병렬화 하는 방식.
- n번째 layer를 forward 하기 위해서는 반드시 n-1 번째 layer를 forward 해야 함.
- 따라서 주로 GPipe나 Pipedream과 같은 Pipeline parallelism 도구를 함께 사용함.
Parallelism: Theory and Practice
128
Model Parallelism
- Intra-layer model parallelism
- 모델을 Layer-wise로 쪼개는 것이 아니라 Column 혹은 Row 방향으로 쪼개서 병렬화 하는 방식.
- 대표적으로 Mesh-tensorflow나 Megatron-LM이 이러한 방식을 사용하고 있음.
Parallelism: Theory and Practice
129
디바이스 1
디바이스 2
Model Parallelism
- Mesh-tensorflow
- Google에서 개발한 오픈소스 모델/데이터 병렬처리 도구.
- Tensorflow와 연동되며 TF Graph와 Operation을 만들어 줌.
- All-reduce 기반의 Data Parallelism + Intra-layer model parallelism 지원
- Tensorflow 2.X 지원하지 않음. 1.X 인터페이스 사용 (ㅎㅎㅎ...)
Parallelism: Theory and Practice
130
Model Parallelism
- Mesh-tensorflow
- Mesh: 프로세서들이 포함될 수 있는 가상의 n-차원 배열
- Mesh-shape: Mesh 배열의 shape, 사용자가 원하는대로 병렬화 가능.
- 예를 들면 32개의 TPU core가 있을 때, (4 x 4 x 2)와 같은 mesh-shape으로 병렬화 가능.
- Mesh-shape은 가상의 shape임. 실제 device topology와는 상관 없음.
- Layout Rules: 각각의 mesh-dimension에 원하는 대상을 부여하는 것.
- 예를 들면 (4:batch, 4:hidden, 2:embd)와 같이 부여 할 수 있음.
- 4:batch는 All-reduce 기반의 Data Parallelism 수행
- 4:hidden과 2:embd는 Intra-layer model parallelism 수행
Parallelism: Theory and Practice
131
Hidden
Embd
Batch
Model Parallelism
- Mesh-tensorflow
- Example: (4:batch x 4:hidden x 2:embd)
Parallelism: Theory and Practice
132
데이터 배치 데이터 배치 데이터 배치 데이터 배치
Batch
Embd
Hidden
Model Parallelism
- Mesh-tensorflow
- Example: (4:batch x 4:hidden x 2:embd)
Parallelism: Theory and Practice
133
Batch
Embd
Hidden
Model Parallelism
- Mesh-tensorflow
- Example: (4:batch x 4:hidden x 2:embd)
Parallelism: Theory and Practice
134
Hidden
Embd
Batch
Model Parallelism
- Mesh-tensorflow: Codes
Parallelism: Theory and Practice
135
w1 = mtf.get_variable(


mesh,


“w1”,


[rows_dim, cols_dim, hidden_dim]


)


w2 = mtf.get_variable(


mesh,


“w2”,


[hidden_dim, classes_dim]


)


# 가중치 생성


hidden = mtf.einsum(


images,


w1,


output_shape=[batch_dim, hidden_dim]


)


hidden = mtf.relu(hidden)


logits = mtf.einsum(


hidden,


W2,


output_shape=[batch_dim, classes_dim]


)


# forward 수행
import mesh_tensorflow as mtf


graph = mtf.Graph()


mesh = mtf.Mesh(graph, “my_mesh”)


# graph와 mesh 생성


batch_dim = mtf.Dimension(“batch”, 100)


rows_dim = mtf.Dimension(“rows”, 28)


cols_dim = mtf.Dimension(“cols”, 28)


# 인풋에 관련된 constants


hidden_dim = mtf.Dimension(“hidden”, 1024)


classes_dim = mtf.Dimension(“classes”, 10)


# 모델에 관련된 constants


images = mtf.import_tf_tensor(


mesh,


mnist_images,


shape=[batch_dims, rows_dim, cols_dim]


)


# 이미지 텐서 입력


Labels = mtf.import_tf_tensor(


mesh,


mnist_labels,


shape=[batch_dim]


)


# 라벨 텐서 입력
Model Parallelism
- Mesh-tensorflow: Codes
Parallelism: Theory and Practice
136
output_label = mtf.one_hot(


labels,


classes_dim


)


# one-hot label 생성


loss = mtf.layers.softmax_cross_entropy_with_logits(


logits,


onehot_labels,


classes_dim


)


loss = mtf.reduce_mean(loss)


# loss 계산


w1_grad, w2_grad = mtf.gradients(


[loss],


[w1, w2],


)


# gradient 계산


update_w1 = mtf.assign(w1, w1 - w1_grad * 0.001)


update_w2 = mtf.assign(w2, w2 - w2_grad * 0.001)


# 가중치 업데이트 연산 생성
devices = [“gpu:0”, “gpu:1”, “gpu:2”, “gpu:3”]


# devices 정의


mesh_shape = [("all", 4)]


layout_rules = [("batch", "all")]


# mesh-shape, layout_rules 정의


mesh_impl = mtf.placement_mesh_impl.PlacementMeshImpl(


mesh_shape,


layout_rules,


devices


)


lowering = mtf.Lowering(


graph,


{mesh: mesh_impl}


)


# mesh-tf -> tf Lowering 객체 생성


tf_update_ops = [


lowering.lowered_operation(update_w1),


lowering.lowered_operation(update_w2)


]


# tensorflow 연산객체 획득
Model Parallelism
- Mesh-tensorflow: Codes
Parallelism: Theory and Practice
137
mesh_shape = [


("x", 4),


("y", 4)


("z", 2)


]


layout_rules = [


("batch", "X"),


("hidden", "y"),


("embd", "y"),


]


# user-defined rules


layout_rules = mtf.auto_mtf.layout(


graph,


mesh_shape,


outputs


)


# auto-searched rules
GPT-NEO 2.7B Configs
Model Parallelism
- Megatron-LM
- Nvidia에서 개발한 Large-scale parallel transformer LM.
- Pytorch로 작성, Intra-layer model parallelism 지원.
- Transformer 각 부분에 대한 병렬화 전략에 대해서 이야기 함.
Parallelism: Theory and Practice
138
Model Parallelism
- Megatron-LM: Row & Column Parallel Linear Layer
- FFN Weight: [D, D] (e.g. 512 x 512)가 있을 때, 두가지 방식으로 병렬화 가능.
- Row Parallel Linear: [D/2 x D] (e.g. 256 x 512)
- 입력(T x D)이 들어오면 scatter 하고 내적 후에 reduce 수행 (addition)
- X (T x D/2) ・ A (D/2 x D) = Y_list [(T x D), (T x D)]= Y_1 (T x D) + Y_2 (T x D) = Y (T x D)
- Column Parallel Linear: [D x D/2] (e.g. 512 x 256)
- 입력(T x D)이 들어오면 replicate 하고 내적 후에 gather 수행 (concatenation)
- X (T x D) ・ A (D x D/2) = Y_list [(T x D/2), (T x D/2)] = Y_1 (T x D/2) ◎ Y_2 (T x D/2) = Y (T x D)
Parallelism: Theory and Practice
139
Row-wise
Model Parallelism
- Megatron-LM: Row & Column Parallel Linear Layer
- FFN Weight: [D, D] (e.g. 512 x 512)가 있을 때, 두가지 방식으로 병렬화 가능.
- Row Parallel Linear: [D/2 x D] (e.g. 256 x 512)
- 입력(T x D)이 들어오면 scatter 하고 내적 후에 reduce 수행 (addition)
- X (T x D/2) ・ A (D/2 x D) = Y_list [(T x D), (T x D)]= Y_1 (T x D) + Y_2 (T x D) = Y (T x D)
Parallelism: Theory and Practice
140
Row-wise
Column-wise
Parallelism: Theory and Practice
141
Model Parallelism
- Megatron-LM: Row & Column Parallel Linear Layer
- FFN Weight: [D, D] (e.g. 512 x 512)가 있을 때, 두가지 방식으로 병렬화 가능.
- Column Parallel Linear: [D x D/2] (e.g. 512 x 256)
- 입력(T x D)이 들어오면 replicate 하고 내적 후에 gather 수행 (concatenation)
- X (T x D) ・ A (D x D/2) = Y_list [(T x D/2), (T x D/2)] = Y_1 (T x D/2) ◎ Y_2 (T x D/2) = Y (T x D)
Model Parallelism
- Megatron-LM: Row & Column Parallel Linear Layer
- FFN Weight: [D, D] (e.g. 512 x 512)가 있을 때, 두가지 방식으로 병렬화 가능.
- Row Parallel Linear: [D/n x D]
- 입력(T x D)이 들어오면 scatter 하고 내적 후에 reduce 수행 (addition)
- X (T x D/2) ・ A (D/n x D) = Y_list [(T x D), ... , (T x D)]= Y_1 (T x D) + ... + Y_n (T x D) = Y (T x D)
- Column Parallel Linear: [D x D/n]
- 입력(T x D)이 들어오면 replicate 하고 내적 후에 gather 수행 (concatenation)
- X (T x D) ・ A (D x D/n) = Y_list [(T x D/n), ..., (T x D/n)] = Y_1 (T x D/n) ◎ ... ◎ Y_n (T x D/n) = Y (T x D)
Parallelism: Theory and Practice
142
n개로
병렬화
가능
Model Parallelism
- Megatron-LM: h ⇒ 4h로 가는 mlp layer는 column-wise로 병렬화
- GeLU 영역에서 Synchronization point를 만들지 않기 위함임.
Parallelism: Theory and Practice
143
Model Parallelism
- Megatron-LM: h ⇒ 4h로 가는 mlp layer는 column-wise로 병렬화
- GeLU 영역에서 Synchronization point를 만들지 않기 위함임.
- Row-wise로 연산하면 반드시 GeLU 영역에서 All-reduce를 해야 함.
Parallelism: Theory and Practice
144
class RowParallelLinear(torch.nn.Module):


def __init__(self):


super(RowParallelLinear, self).__init__()


chunked = torch.chunk(w, 2, dim=0)


self.a1 = chunked[0] # [3, 6]


self.a2 = chunked[1] # [3, 6]


def forward(self, x):


# Parallel O: GeLU(X1A1) + GeLU(X2A2)


# 각 device에서 GeLU를 따로 연산


# Parallel X: GeLU(X1A1 + X2A2)


# 값을 더해서 병렬화 안한 상태서 GeLU 연산




# 계산해보면 두 값이 다르기 때문에,


# 두 device에 X1A1 + X2A2의 값이 있어야 함.


x1, x2 = torch.chunk(x, 2, dim=1)


y1 = gelu(x1 @ self.a1) + gelu(x2 @ self.a2)


y2 = gelu(x1 @ self.a1 + x2 @ self.a2)


return torch.all(y1 == y2) # False


병렬화: GeLU(XA1) + GeLU(XA2)
동기화: GeLU(XA1 + XA2)
연산 결과가 동일해야 Stability를 보장 가능.
RowParallelLinear는 GeLU 영역을
병렬화, 동기화시의 값이 다름.
따라서 RowParallelLinear를 사용하려면
All-reduce 해서 두개의 device가 동일하게
X1A1 + X2A2의 값을 가져야 함.
=> Communication cost 발생!
Model Parallelism
- Megatron-LM: h ⇒ 4h로 가는 mlp layer는 column-wise로 병렬화
- GeLU 영역에서 Synchronization point를 만들지 않기 위함임.
- Row-wise로 연산하면 반드시 GeLU 영역에서 All-reduce를 해야 함.
Parallelism: Theory and Practice
145
All-reduce 연산 필요.
Communication 발생
병렬화: GeLU(XA1) + GeLU(XA2)
동기화: GeLU(XA1 + XA2)
연산 결과가 동일해야 Stability를 보장 가능.
RowParallelLinear는 GeLU 영역을
병렬화, 동기화시의 값이 다름.
따라서 RowParallelLinear를 사용하려면
All-reduce 해서 두개의 device가 동일하게
X1A1 + X2A2의 값을 가져야 함.
=> Communication cost 발생!
Model Parallelism
- Megatron-LM: h ⇒ 4h로 가는 mlp layer는 column-wise로 병렬화
- GeLU 영역에서 Synchronization point를 만들지 않기 위함임.
- Column-wise로 연산하면 계산결과가 동일하여 통신없이 수행 가능.
Parallelism: Theory and Practice
146
병렬화: GeLU(XA1) cat GeLU(XA2)
동기화: GeLU(XA1 cat XA2)
연산 결과가 동일해야 Stability를 보장 가능.
ColumnParallelLinear는 GeLU 영역을
병렬화, 동기화시의 값이 동일함.
따라서 ColumnParallelLinear를 사용하면
Communication 없이 연산 수행이 가능함
class ColumnParallelLinear(torch.nn.Module):


def __init__(self):


super(ColumnParallelLinear, self).__init__()


chunked = torch.chunk(w, 2, dim=1)


self.a1 = chunked[0] # [6, 3]


self.a2 = chunked[1] # [6, 3]


def forward(self, x):


# 어떻게 연산하던 값이 동일하기 때문에 Column-wise가 타당함.


# GeLU(X1A1 cat X2A2) == GeLU(X1A1) cat GeLU(X2A2)




y1 = torch.cat([gelu(x @ self.a1), gelu(x @ self.a2)], dim=1)


y2 = gelu(torch.cat([(x @ self.a1), (x @ self.a2)], dim=1))


return torch.all(y1 == y2) # True
Model Parallelism
- Megatron-LM: 4h ⇒ h로 가는 mlp layer는 row-wise로 병렬화
- 이는 이전 Layer의 Output을 Concat 하는데에 들어가는 비용을 줄이기 위함임.
- GeLU(XA1)과 GeLU(XA2)를 Concat 하려면 All-Gather 연산을 해야해서 비효율적임.
Parallelism: Theory and Practice
147
Column-wise
Model Parallelism
- Megatron-LM: 4h ⇒ h로 가는 mlp layer는 row-wise로 병렬화
- 이는 이전 Layer의 Output을 Concat 하는데에 들어가는 비용을 줄이기 위함임.
- GeLU(XA1)과 GeLU(XA2)를 Concat 하려면 All-Gather 연산을 해야해서 비효율적임.
Parallelism: Theory and Practice
148
Column-wise
All-Gather 연산 필요.
Communication 발생.
출력: D/2
병합: D
입력: D
Model Parallelism
- Megatron-LM: 4h ⇒ h로 가는 mlp layer는 row-wise로 병렬화
- 이는 이전 Layer의 Output을 Concat 하는데에 들어가는 비용을 줄이기 위함임.
- GeLU(XA1)과 GeLU(XA2)를 Concat 하려면 All-Gather 연산을 해야해서 비효율적임.
Parallelism: Theory and Practice
149
Row-wise
Column-wise
Row-wise 사용시 어차피
다시 Scatter를 해야 함.
출력: D/2 입력: D/2 (Scatter 필요)
병합: D
All-Gather 연산 필요.
Communication 발생.
Model Parallelism
- Megatron-LM: 4h ⇒ h로 가는 mlp layer는 row-wise로 병렬화
- 이는 이전 Layer의 Output을 Concat 하는데에 들어가는 비용을 줄이기 위함임.
- GeLU(XA1)과 GeLU(XA2)를 Concat 하려면 All-Gather 연산을 해야해서 비효율적임.
Parallelism: Theory and Practice
150
Row-wise
Column-wise
그냥 안 합치고 바로 감.
이 방법이 제일 효율적임.
All-Gather 필요 없음.
Communication 없음.
출력: D/2 입력: D/2
Row-wise
Column-wise
다음 layer로 넘길 때
All-reduce 수행
Forward Pass
Model Parallelism
- Megatron-LM: 따라서 단 2번 (Forward, Backward)의 All-reduce만으로 FFN 구현 가능.
- Forward, Backward 때 반드시 합쳐야 하는 부분에서만 All-reduce 연산이 일어남.
Parallelism: Theory and Practice
151
Parallelism: Theory and Practice
152
Row-wise
Column-wise
이전 layer로 넘길 때
All-reduce 수행
Backward Pass
Model Parallelism
- Megatron-LM: 따라서 단 2번 (Forward, Backward)의 All-reduce만으로 FFN 구현 가능.
- Forward, Backward 때 반드시 합쳐야 하는 부분에서만 All-reduce 연산이 일어남.
Parallelism: Theory and Practice
153
Model Parallelism
- Megatron-LM: 따라서 단 2번 (Forward, Backward)의 All-reduce만으로 FFN 구현 가능.
- Forward, Backward 때 반드시 합쳐야 하는 부분에서만 All-reduce 연산이 일어남.
Forward 때는
여기서 All-reduce.
Backward 때는
여기서 All-reduce.
Parallelism: Theory and Practice
154
Model Parallelism
- Megatron-LM: Attention도 Column ⇒ Row로 병렬화해서 최소의 통신만 수행.
- 마찬가지로 Column ⇒ Row로 병렬화하면 동기화 없이 수행할 수 있음.
- 따라서 Forward, Backward 때 반드시 합쳐야 하는 부분에서만 All-reduce가 일어남.
Column-wise 통신 (Gather) 없이 쭉 가려면
앞쪽에서는 Column-wise, 뒤쪽에서는 Row-wise를 써줘야 함.
Row-wise
Parallelism: Theory and Practice
155
Model Parallelism
- Megatron-LM: Attention도 Column ⇒ Row로 병렬화해서 최소의 통신만 수행.
- 마찬가지로 Column ⇒ Row로 병렬화하면 동기화 없이 수행할 수 있음.
- 따라서 Forward, Backward 때 반드시 합쳐야 하는 부분에서만 All-reduce가 일어남.
Forward 때는
여기서 All-reduce.
Backward 때는
여기서 All-reduce.
Parallelism: Theory and Practice
156
Model Parallelism
- Megatron-LM: LayerNorm과 Dropout은 병렬화 하지 않음.
- 이들의 연산 Cost나 파라미터의 크기는 별로 크지 않음.
- 모든 Device에 별도의 Dropout과 LayerNorm Layer가 있음. ⇒ 여기에선 All-reduce가 일어나지 않음.
No All-Reduce !
Parallelism: Theory and Practice
157
Model Parallelism
- Megatron-LM: Decoding을 위한 Embedding Layer와 CrossEntropy Layer를 Fuse 했음.
- Representation을 Embedding Matrix에 곱한 뒤 나오는 Logit의 사이즈는 [bsz, seq_len, vocab_size]
- vocab_size는 보통 수만개 단위이기 때문에 All-gather 후 Loss를 구하는 것은 비용이 큼.
- 따라서 Logit을 All-gather 하지 않고 Loss까지 계산이 모두 끝나고나서 All-reduce 하여 Backprop 수행.
방법 1) All-gather 방식
- Vocab_size: 50000
- n개의 Device에 [bsz, seq_len, 50000 / n]의 Logit이 존재.
- 모든 Logit을 All-gather 해서 concat ⇒ [bsz, seq_len, 50000]
- 병합된 Logit으로 부터 Loss 계산 후 Backprop 수행.
⇒ Communication Cost가 매우 크다.
방법 2) Masking 방식 (채택)
- Vocab_size: 50000
- n개의 Device에 [bsz, seq_len, 50000 / n]의 Logit이 존재.
- Partitioning 된 Vocab의 범위에 해당이 안되면 Masking 처리.
- Loss 계산 후 All-reduce로 Loss의 평균을 내서 Backprop 수행.
⇒ Communication Cost가 적긴한데, 이게 된다고...? (의문)
Parallelism: Theory and Practice
158
Model Parallelism
- Megatron-LM: Decoding을 위한 Embedding Layer와 CrossEntropy Layer를 Fuse 했음.
- Representation을 Embedding Matrix에 곱한 뒤 나오는 Logit의 사이즈는 [bsz, seq_len, vocab_size]
- vocab_size는 보통 수만개 단위이기 때문에 All-gather 후 Loss를 구하는 것은 비용이 큼.
- 따라서 Logit을 All-gather 하지 않고 Loss까지 계산이 모두 끝나고나서 All-reduce 하여 Backprop 수행.
Parallelism: Theory and Practice
159
Model Parallelism
- Megatron-LM: (당시 기준) WikiText와 Lambada 태스크 등에서 SoTA를 달성.
- 학습속도가 매우 빨랐으며 Intra-layer model parallelism을 해도 좋은 성능을 뽑을 수 있었음.
- 추가적으로 Layer Normalization에 대한 분석을 진행.
- Pre-LN 구조 사용시 Residual 이후에 Normalization을 해야 안정적인 학습이 가능했음. (원래 이렇게 하긴 했음)
Parallelism: Theory and Practice
160
Model Parallelism
- Examples: Inter-layer model parallelism on Pytorch - .to( )
- Pytorch로 Inter-layer 병렬화를 할 때는 아래와 같은 방법으로 수행할 수 있음.
.to( ) 활용 (single-node)
제일 기본적인 방법이고 많이 쓸 수 있는 방법.
Parallelism: Theory and Practice
161
Model Parallelism
- Examples: Inter-layer model parallelism on Pytorch - RPC
- Pytorch로 Inter-layer 병렬화를 할 때는 아래와 같은 방법으로 수행할 수 있음.
RPC 활용 (multi-node)
process간 P2P 통신 수행을 통해 다른 노드에게 값 전달
Model Parallelism
- Examples: Inter-layer model parallelism on Huggingface Transformers (standalone)
- 앞선 방법들은 우리가 모델을 새로 짤 때, 가능한 기법들이다. 그럼 Pre-trained 모델은 어떨까?
- Huggingface Transformers의 GPT2와 T5는 아래와 같이 병렬화 함수를 지원한다.
- 그런데 유저 PR 이라 정식 업데이트에서 transformers standalone 병렬화를 기대하는 것은 어려울듯.
- Standalone은 Transformers 자체만을 의미. (물론 Deepspeed 등을 붙이면 모델 병렬화 가능함)
Parallelism: Theory and Practice
162
그럼 병렬화를 지원하지 않는 모델은?
Parallelism: Theory and Practice
163
Model Parallelism
- Examples: Inter-layer model parallelism on Huggingface Transformers (standalone)
- 그만 알아보자... (텐서를 일일이 찾아다니면서 전부 다 .to( )를 찍어야 함)
Parallelism: Theory and Practice
164
Model Parallelism
- Examples: Inter-layer model parallelism on Huggingface Transformers (deepspeed)
- 물론 플러그인 등을 사용하면 여러개 GPU를 활용할 수 있음.
$ deepspeed --num_gpus 2 inference.py
Parallelism: Theory and Practice
165
Model Parallelism
- Examples: Inter-layer model parallelism on Fairseq (standalone)
- Fairseq에는 ModelParallelTransformer라는 클래스가 있는데, 이는 Megatron LM을 기반으로 한다.
- model_parallel_size > 1로 설정하면 기본 모델이 Megatron LM으로 변경된다.
- Fairseq Standalone으로 더 이상의 모델 병렬화 기능은 보이지 않는다. (마찬가지로 Fairscale 등 붙일 수 있음)
Parallelism: Theory and Practice
166
Model Parallelism
- Examples: Inter-layer model parallelism on Parlai
- Parlai는 내부적으로 모델 병렬화를 지원하고 있다.
- `parlai.utils.torch.PipelineHelper`를 이용하면 모델 병렬화가 가능하다.
- 학습할 땐, --model_parallel=True로 설정하면 된다.
from parlai.utils.torch import PipelineHelper


from parlai.core.agents import create_agent_from_model_file


pf = PipelineHelper()


model = create_agent_from_model_file(“zoo:blender/blender_3B/model”)


model = pf.make_parallel(model)


# 모델 병렬화 수행


model.observe({"text": "Hello !"})


model.act()


# 대화 수행
Pipeline Parallelism
(GPipe, PipeDream, Interleaved Schedules, 3D Parallelism)
167
Parallelism: Theory and Practice
168
Pipeline Parallelism
- GPipe: 주로 Inter-layer model parallelism 속도를 개선하기 위해 사용.
- Inter-layer model parallelism의 경우 레이어들의 연산을 순차적으로 수행함.
- 때문에 동시에 한 layer의 연산이 수행 중일 때, 다른 layer가 저장되어 있는 device는 Idle 상태로 존재하게 됨.
Parallelism: Theory and Practice
169
Pipeline Parallelism
- GPipe: 주로 Inter-layer model parallelism 속도를 개선하기 위해 사용.
- GPipe는 이러한 Idle 상태를 줄이기 위해 고안된 것.
- mini-batch를 micro-batch로 쪼개서 학습과정을 파이프라이닝함. ⇒ Idle 상태 최소화
https://kakaobrain.com/blog/66
Parallelism: Theory and Practice
170
Pipeline Parallelism
- GPipe: 주로 Inter-layer model parallelism 속도를 개선하기 위해 사용.
- GPipe는 이러한 Idle 상태를 줄이기 위해 고안된 것.
- mini-batch를 micro-batch로 쪼개서 학습과정을 파이프라이닝함. ⇒ Idle 상태 최소화
https://kakaobrain.com/blog/66
Parallelism: Theory and Practice
171
Pipeline Parallelism
- GPipe: 주로 Inter-layer model parallelism 속도를 개선하기 위해 사용.
- GPipe는 이러한 Idle 상태를 줄이기 위해 고안된 것.
- mini-batch를 micro-batch로 쪼개서 학습과정을 파이프라이닝함. ⇒ Idle 상태 최소화
https://kakaobrain.com/blog/66
Parallelism: Theory and Practice
172
Pipeline Parallelism
- GPipe: 주로 Inter-layer model parallelism 속도를 개선하기 위해 사용.
- GPipe는 이러한 Idle 상태를 줄이기 위해 고안된 것.
- mini-batch를 micro-batch로 쪼개서 학습과정을 파이프라이닝함. ⇒ Idle 상태 최소화
https://kakaobrain.com/blog/66
Parallelism: Theory and Practice
173
Pipeline Parallelism
- GPipe: 주로 Inter-layer model parallelism 속도를 개선하기 위해 사용.
- GPipe는 이러한 Idle 상태를 줄이기 위해 고안된 것.
- mini-batch를 micro-batch로 쪼개서 학습과정을 파이프라이닝함. ⇒ Idle 상태 최소화
Parallelism: Theory and Practice
174
Pipeline Parallelism
- GPipe: 주로 Inter-layer model parallelism 속도를 개선하기 위해 사용.
- 파이프라이닝을 해도, Bubble Time은 존재 할 수 밖에 없으며, Bubble Time은 M(micro-batch)와 K(partition)과 관계 있음.
- 정량적 분석 결과 M >= K x 4 정도가 되면 Bubble Time을 거의 무시할 수 있다고 함.
Parallelism: Theory and Practice
175
Pipeline Parallelism
- GPipe: Remarterialization - GPU 메모리 절약 기술
- 대부분의 Layer는 내부에 Forward 입력을 가지고 있음. (Checkpointing)
- 예를 들면 Max Pooling Layer의 미분계수는 오른쪽 Matrix와 같은데, Foward 입력이 있어야 이걸 계산할 수 있음.
0 0 0
0 0
0
0 0
0
0 0 0
1
1
1
1
미분 계수
Parallelism: Theory and Practice
176
Pipeline Parallelism
- GPipe: Remarterialization - GPU 메모리 절약 기술
- 대부분의 Layer는 내부에 Forward 입력을 가지고 있음. (Checkpointing)
- 아래는 CNN numpy scratch 구현 예시임. `self.last_input`에 저장된 값을 `backward( )`시에 사용함.
Parallelism: Theory and Practice
177
Pipeline Parallelism
- GPipe: Remarterialization - GPU 메모리 절약 기술
- Remarterialization은 Layer 내부에 Input Checkpoint를 저장하지 않게 해서 메모리를 절약함.
- Backward 할 때 Forward를 한번 다시해서 필요한 값만 얻어냄.
- 대신 이렇게 하면 Forward를 2번 해야한다는 단점이 있는데 GPipe는 그것을 슬기롭게 극복함.
Input Checkpoint
Parallelism: Theory and Practice
178
Pipeline Parallelism
- GPipe: Remarterialization - GPU 메모리 절약 기술
- Remarterialization은 Layer 내부에 Input Checkpoint를 저장하지 않게 해서 메모리를 절약함.
- Backward 할 때 Forward를 한번 다시해서 필요한 값만 얻어냄.
- 대신 이렇게 하면 Forward를 2번 해야한다는 단점이 있는데 GPipe는 그것을 슬기롭게 극복함.
Input Checkpoint
Parallelism: Theory and Practice
179
Pipeline Parallelism
- GPipe: Remarterialization - GPU 메모리 절약 기술
- (1) 중간 Layer 들의 결과값은 가지고 있어서 맨 처음부터 Forward 하지는 않게 하였음.
- (2) 자신의 Backward 타임이 오기 전에 (Bubble Time 동안) 미리 Forward를 연산해둠
중간 레이어들의
결과만 Checkpointing
Forward를 한 스텝 먼저 진행해서
Rematerialization으로 발생하는 오버헤드 완화
Parallelism: Theory and Practice
180
Pipeline Parallelism
- Torch GPipe: 이제는 Pytorch에 내장된 기본 Pipelining 모듈
- Kakaobrain에서 개발한 torch GPipe가 torch 안에 내장되어서 이제 torch의 기본 모듈이 되었음.
- 아래와 같이 사용 가능하며, 마찬가지 동일하게 torch.distributed.pipeline.sync.Pipe로 사용 가능함.
from torchgpipe import GPipe

import torch.nn as nn

model = nn.Sequential(a, b, c, d)

model = GPipe(
model, 

balance=[2, 2],


devices=[0, 1],


chunks=8
)
Parallelism: Theory and Practice
181
Pipeline Parallelism
- Torch GPipe: 이제는 Pytorch에 내장된 기본 Pipelining 모듈
- Kakaobrain에서 개발한 torch GPipe가 torch 안에 내장되어서 이제 torch의 기본 모듈이 되었음.
- 아래와 같이 사용 가능하며, 마찬가지 동일하게 torch.distributed.pipeline.sync.Pipe로 사용 가능함.
import fairscale


import torch.nn as nn


model = nn.Sequential(a, b, c, d)


model = fairscale.nn.Pipe(


model,


balance=[2, 2],


devices=[0, 1],


chunks=8


)
Parallelism: Theory and Practice
182
Pipeline Parallelism
- Fairscale: Facebook에서 개발한 병렬처리 도구 (ZeRO, GPipe 등 다양한 기능 지원)
- Fairscale의 nn.Pipe를 이용해도 동일하게 사용 가능함. (완전히 동일한 api를 제공함)
Parallelism: Theory and Practice
183
Pipeline Parallelism
- Pytorch-lightning: Fairscale Plugin을 이용해 학습에 쉽게 사용할 수 있도록 지원.
Parallelism: Theory and Practice
184
Pipeline Parallelism
- PipeDream: MS의 파이프라인 병렬화 솔루션
- Pipe Dream은 MS에서 개발한 파이프라인 병렬화 솔루션.
- Google GPipe와 약간 다른 파이프라이닝 구조를 가지고 있음.
- Pipeline Parallelism은 다음과 같은 챌린지들이 존재한다.
- (1) Weight Version Managing
- (2) Work Partitioning
Parallelism: Theory and Practice
185
Pipeline Parallelism
- PipeDream: MS의 파이프라인 병렬화 솔루션
- Pipeline Parallelism의 챌린지 (1): Weight Version Managing
- GPipe의 경우 하나의 Weight 버전만 운용하지만 주기적으로 Pipeline Flush가 일어난다.
- Pipeline Flush는 계산된 Gradients를 이용해 파라미터를 업데이트하는 과정
- 이러한 Flush 과정에서 Forward, Backward 연산도 하지 않기 때문에 처리효율이 떨어진다.
Parallelism: Theory and Practice
186
Pipeline Parallelism
- PipeDream: MS의 파이프라인 병렬화 솔루션
- Pipeline Parallelism의 챌린지 (1): Weight Version Managing
- Pipe Dream은 이러한 Flush 과정 없이 파라미터 상태를 지속적으로 관리한다.
- 만약 최신버전의 파라미터만 저장하면 이전 Layer의 출력이 다음 Layer로 전송될 때, 다음
Layer의 파라미터 부분이 이미 업데이트 되어버렸을 수도 있다.
Parallelism: Theory and Practice
187
Pipeline Parallelism
- PipeDream: MS의 파이프라인 병렬화 솔루션
- Pipeline Parallelism의 챌린지 (1): Weight Version Managing
Forward
Parallelism: Theory and Practice
188
Pipeline Parallelism
- PipeDream: MS의 파이프라인 병렬화 솔루션
- Pipeline Parallelism의 챌린지 (1): Weight Version Managing
Backward
Parallelism: Theory and Practice
189
Pipeline Parallelism
- PipeDream: MS의 파이프라인 병렬화 솔루션
- Pipeline Parallelism의 챌린지 (1): Weight Version Managing
Update
1
Parallelism: Theory and Practice
190
Pipeline Parallelism
- PipeDream: MS의 파이프라인 병렬화 솔루션
- Pipeline Parallelism의 챌린지 (1): Weight Version Managing
Forward
Parallelism: Theory and Practice
191
Pipeline Parallelism
- PipeDream: MS의 파이프라인 병렬화 솔루션
- Pipeline Parallelism의 챌린지 (1): Weight Version Managing
Backward
Parallelism: Theory and Practice
192
Pipeline Parallelism
- PipeDream: MS의 파이프라인 병렬화 솔루션
- Pipeline Parallelism의 챌린지 (1): Weight Version Managing
Update
2
Parallelism: Theory and Practice
193
Pipeline Parallelism
- PipeDream: MS의 파이프라인 병렬화 솔루션
- Pipeline Parallelism의 챌린지 (1): Weight Version Managing
Forward
Parallelism: Theory and Practice
194
Pipeline Parallelism
- PipeDream: MS의 파이프라인 병렬화 솔루션
- Pipeline Parallelism의 챌린지 (1): Weight Version Managing
Backward
Parallelism: Theory and Practice
195
Pipeline Parallelism
- PipeDream: MS의 파이프라인 병렬화 솔루션
- Pipeline Parallelism의 챌린지 (1): Weight Version Managing
Update
3
Parallelism: Theory and Practice
196
Pipeline Parallelism
- PipeDream: MS의 파이프라인 병렬화 솔루션
- Pipeline Parallelism의 챌린지 (1): Weight Version Managing
Forward
Parallelism: Theory and Practice
197
Pipeline Parallelism
- PipeDream: MS의 파이프라인 병렬화 솔루션
- Pipeline Parallelism의 챌린지 (1): Weight Version Managing
Backward
Parallelism: Theory and Practice
198
Pipeline Parallelism
- PipeDream: MS의 파이프라인 병렬화 솔루션
- Pipeline Parallelism의 챌린지 (1): Weight Version Managing
Update
4
Parallelism: Theory and Practice
199
Pipeline Parallelism
- PipeDream: MS의 파이프라인 병렬화 솔루션
- Pipeline Parallelism의 챌린지 (1): Weight Version Managing
빨간색 시점에서 Update가 일어남.
빨간색 숫자 n은 n번 데이터에 대한 업데이트임.
1 2 3 4
Parallelism: Theory and Practice
200
Pipeline Parallelism
- PipeDream: MS의 파이프라인 병렬화 솔루션
- Pipeline Parallelism의 챌린지 (1): Weight Version Managing
5번 micro-batch 부터는 Forward & Backward
과정 중에 계속 파라미터 업데이트가 일어남.
결과적으로 매 스텝마다 다른
파라미터를 가지고 Forward하게 됨.
=> 정확하지 못한 계산으로 이어짐.
1 2 3 4
Parallelism: Theory and Practice
201
Pipeline Parallelism
- PipeDream: MS의 파이프라인 병렬화 솔루션
- Pipeline Parallelism의 챌린지 (1): Weight Version Managing
5번 micro-batch 부터는 Forward & Backward
과정 중에 계속 파라미터 업데이트가 일어남.
(동그라미에서 계산미스가 발생하게 됨)
결과적으로 매 스텝마다 다른
파라미터를 가지고 Forward하게 됨.
=> 정확하지 못한 계산으로 이어짐.
1 2 3 4
Parallelism: Theory and Practice
202
Pipeline Parallelism
- PipeDream: MS의 파이프라인 병렬화 솔루션
- Pipeline Parallelism의 챌린지 (1): Weight Version Managing
- 이러한 문제를 막기 위해 PipeDream은 여러 버전의 Weight를 저장한다.
- 그러면 이미 변해버린 파라미터에 Forward & Backward 하는 문제를 막을 수 있다.
- 여러 버전을 저장하면 문제가 해결되긴 하지만 메모리 공간을 많이 차지하게 된다.
- 여기에서 Trade Off가 발생함:
- GPipe: 메모리 효율적, 프로세싱 비효율적
- PipeDream: 메모리 비효율적, 프로세싱 효율적
Parallelism: Theory and Practice
203
Pipeline Parallelism
- PipeDream: MS의 파이프라인 병렬화 솔루션
- Pipeline Parallelism의 챌린지 (2): Work Partitioning
- 두번째는 Neural Net을 어떻게 쪼개는 것이 현명한지에 대한 문제.
- 단순히 Layer 별로 쪼개는 것이 별로 현명하지 않을 수 있음.
- 일단 각 파티션의 Running Time이 비슷해야 Idle Time을 최소화 할 수 있을 것임.
- 그 이외에도 Parameter Size, Activation Memory 등 다양한 요소를 고려해야 함.
Parallelism: Theory and Practice
204
Pipeline Parallelism
- PipeDream: MS의 파이프라인 병렬화 솔루션
- Pipeline Parallelism의 챌린지 (2): Work Partitioning
- Profiling과 Optimizing을 통해 최적의 Partition을 찾아냄.
- Activation Size, Parameter Size, Compute Time 등을 고려.
Parallelism: Theory and Practice
205
Pipeline Parallelism
- PipeDream: MS의 파이프라인 병렬화 솔루션
- Experiments
- 단순 Data Parallelism에 비해 훨씬 빠르게 수렴하는 것을 볼 수 있음.
Parallelism: Theory and Practice
206
Pipeline Parallelism
- PipeDream 2BW (2-buffered weight update): Memory Efficient PipeDream
- PipeDream이 프로세싱 효율성이 좋지만, 메모리 효율성이 떨어졌음.
- PipeDream 2BW는 이전 PipeDream에 비해 메모리 효율성을 끌어올렸음.
- 핵심 아이디어는 파이프라이닝 중에 Gradient Accumulation을 수행하는 것임.
- 여러개의 Gradient들을 모아두다가 한번에 업데이트를 수행하는 방식으로 해결.
- 단 두개의 Weight Version만 유지해도 계산에 문제가 없으며 Flush도 필요 없음.
한번에 업데이트
Parallelism: Theory and Practice
207
Pipeline Parallelism
- PipeDream Flush: Memory Efficient PipeDream
- PipeDream Flush는 GPipe처럼 Pipeline Flush가 일어남.
- PipeDream의 1F1B (1-Forward, 1-Backward) 파이프라인과 Flush를 결함한 파이프라인.
- GPipe와 비교해서 Bubble Time은 비슷하나 Forward & Backward 중에 유지해야하는 activation 메모리가 줄어서 효율적.
- 단일 가중치만 유지하면 되기 때문에 PipeDream 2BW보다도 메모리 효율적임. (즉, 가장 메모리 효율적임)
Parallelism: Theory and Practice
208
Pipeline Parallelism
- PipeDream Flush: Memory Efficient PipeDream
- PipeDream Flush는 GPipe처럼 Pipeline Flush가 일어남.
activation memory = 4
activation memory = 2
Parallelism: Theory and Practice
209
Pipeline Parallelism
- Interleaved Scheduling:
- Bubble을 줄이기 위해서 각각의 device가 pipeline model parallel의 여러 stage에 해당 되도록 할당
- 이전에는 하나의 device가 연속된 레이어를 한번에 계산해서 결과 값을 뽑았었음.
- 예를 들면 1번 device가 1~4번 레이어, 2번 device가 5~8번 레이어를 맡는다고 가정.
- 그러면 1번 device는 1~4번 레이어에 대한 Forward & Backward 연산을 한번에 진행해서 출력했음.
- Interleaved Scheduling은 한개 device 안에서 파이프라인을 더 분할하는 작업
- 1번 device가 1~2번 레이어를 연산하는 것과 3~4번 레이어를 연산하는 것을 중첩시킴.
- 이렇게 되면 버블타임은 줄어드는대신 통신시간이 늘어나기 때문에 잘 조절해야함. (Trade Off 존재)
Parallelism: Theory and Practice
210
Pipeline Parallelism
- Interleaved Scheduling:
- Interleaved Scheduling은 한개 device 안에서 파이프라인을 더 분할하는 작업
- 1번 device가 1~2번 레이어를 연산하는 것과 3~4번 레이어를 연산하는 것을 중첩시킴.
- 이렇게 되면 버블타임은 줄어드는대신 통신시간이 늘어나기 때문에 잘 조절해야함. (Trade Off 존재)
Parallelism: Theory and Practice
211
Pipeline Parallelism
- Interleaved Scheduling:
- Interleaved Scheduling은 한개 device 안에서 파이프라인을 더 분할하는 작업
- 1번 device가 1~2번 레이어를 연산하는 것과 3~4번 레이어를 연산하는 것을 중첩시킴.
- 이렇게 되면 버블타임은 줄어드는대신 통신시간이 늘어나기 때문에 잘 조절해야함. (Trade Off 존재)
Parallelism: Theory and Practice
212
Pipeline Parallelism
- Interleaved Scheduling:
- Interleaved Scheduling은 한개 device 안에서 파이프라인을 더 분할하는 작업
- 1번 device가 1~2번 레이어를 연산하는 것과 3~4번 레이어를 연산하는 것을 중첩시킴.
- 이렇게 되면 버블타임은 줄어드는대신 통신시간이 늘어나기 때문에 잘 조절해야함. (Trade Off 존재)
Parallelism: Theory and Practice
213
Pipeline Parallelism
- 3D Parallelism:
- 초반에 언급했던 3D Parallelism은 다음과 같이 수행됨.
- Pipeline Parallelism: Inter-layer pipeline model parallelism (PipeDream Flush)
- Model Parallelism: Intra-layer model parallelism (Megatron-LM)
- Data Parallelism: Data Parallelism (DDP?)
Inter-layer pipeline model parallelism

(PipeDream Flush or Interleaved)
I
n
t
r
a
-
l
a
y
e
r
m
o
d
e
l
p
a
r
a
l
l
e
l
i
s
m


(
M
e
g
a
t
r
o
n
L
M
)
Parallelism: Theory and Practice
214
Pipeline Parallelism
- 3D Parallelism:
- 초반에 언급했던 3D Parallelism은 다음과 같이 수행됨.
- Pipeline Parallelism: Inter-layer pipeline model parallelism (PipeDream Flush)
- Model Parallelism: Intra-layer model parallelism (Megatron-LM)
- Data Parallelism: Data Parallelism ⇒ ZeRO Data Parallelism
Inter-layer pipeline model parallelism

(PipeDream Flush or Interleaved)
I
n
t
r
a
-
l
a
y
e
r
m
o
d
e
l
p
a
r
a
l
l
e
l
i
s
m


(
M
e
g
a
t
r
o
n
L
M
)
Deep Speed
(ZeRO, ZeRO-offload, ZeRO-infinity, 1Bit-Adam, Progressive Layer Dropping)
215
Parallelism: Theory and Practice
216
Deep Speed
- Mixed Precision: FP16 for F&Bward + FP32 for Update
- 요즘 대부분 모델을 학습하는데에는 FP16 (half)와 FP32 (single)을 함께 사용함.
- 최신 GPU들이 Lower Precision에 대한 계산을 지원하면서 속도 면에서 큰 이점이 생기게 되었음.
- V100 기준, FP32에서는 14 TFLOPS가 나오지만 FP16에서는 100TFLOPS가 나옴.
- 또한 FP16을 적용하면 모델 사이즈도 절반으로 줄기 때문에 배포시에도 장점이 있을 수 있음.
Parallelism: Theory and Practice
217
Deep Speed
- Mixed Precision: FP16 for F&Bward + FP32 for Update
- 그러나 FP16의 경우 미세한 Gradient 값들이 무시되기 때문에 정확도가 다소 감소할 우려가 있음.
- Mixed Precision (FP16 for F&Bward + FP32 for Update)를 사용하면 성능하락 없이 속도의 이점만 얻음
Parallelism: Theory and Practice
218
Deep Speed
- Mixed Precision: FP16 for F&Bward + FP32 for Update
- 그러나 FP16의 경우 미세한 Gradient 값들이 무시되기 때문에 정확도가 다소 감소할 우려가 있음.
- Mixed Precision (FP16 for F&Bward + FP32 for Update)를 사용하면 성능하락 없이 속도의 이점만 얻음
Loss
Scaling
Parallelism: Theory and Practice
219
Deep Speed
- Mixed Precision: Loss Scaling
- Loss에 일정한 상수를 곱해서 Loss 값을 키워줌. 이렇게 되면 FP16 이후의 가수부(fraction)들을 살릴 수 있음.
- e.g. Scale 500 times, 0.00000555 => 0.000277500, 이로 인해 0.000277에 해당하는 Gradient를 살려냈음.
Loss Scaling이 없으면
학습이 제대로 진행되지 않음.
FP32와 성능이 거의 비슷함.
Parallelism: Theory and Practice
220
Deep Speed
- Mixed Precision: Memory unefficient??
- Mixed Precision이 성능과 속도의 이점을 모두 취할 수 있다는 것은 사실.
- 그러나 빅 모델로 대두되는 이 시대에 memory unefficient 한 것은 매우 큰 문제이다.
- FP16과 FP32를 모두 사용하기 때문에 그들이 모두 GPU에 올라와 있어야 하기 때문.
FP32 Optimizer States
FP32 Parameters
FP16 Parameters
FP16 Gradients
Parallelism: Theory and Practice
221
Deep Speed
- ZeRO: Zero Redundancy Optimizer
- 메모리를 최적화하여 학습 속도를 크게 향상시키면서 효율적으로 학습 가능한 모델사이즈 확장.
- Data & Model Parallelism에서 Memory Redundancy를 제거하였음. (필요한 만큼만 메모리에 올리기)
- GPT3를 학습시킨 장본인, 추후에 1 Trillion 이상의 파라미터 모델을 학습시킬 수 있을 것으로 전망됨.
Parallelism: Theory and Practice
222
Deep Speed
- ZeRO: Zero Redundancy Optimizer
- 메모리 소비 스펙트럼을 분석: Model states & Residual states으로 나누어서 각각에 대한 솔루션 제안
- 메모리의 대부분을 Model States가 점유하고 있음. {Parameters, Gradients, Optimizer states}
- 나머지 Activation, Temporary Buffer, Fragmented Memory 등이 구성, 이 것을 Residual States (나머지)라고 부를 것임.
- ZeRO-DP: Model States 문제를 해결하기 위한 솔루션 (ZeRO-1에서 제안됨)
- ZeRO-R: Residual States 문제를 해결하기 위한 솔루션 (ZeRO-2에서 제안됨)
Parallelism: Theory and Practice
223
Deep Speed
- ZeRO: Zero Redundancy Optimizer 제품군
- ZeRO-1: ZeRO-DP에 대한 아이디어 공개 + ZeRO-DP Optimizer states partitioning 코드 공개
- ZeRO-2: ZeRO-R 공개 + ZeRO-DP Gradients state partitioning 코드 공개
- ZeRO-3: ZeRO-offload 공개 + ZeRO-DP Parameter states partitioning 코드 공개
- ZeRO-infinity: ZeRO-infinity 공개
Parallelism: Theory and Practice
224
Deep Speed
- ZeRO-DP: ZeRO powered Data Parallelism
- DP: Good Computation & Poor Memory efficiency (Parameter Duplication)
- MP: Poor Computation (Idle Time) & Good Memory efficiency
- 두 방식 모두, GPU에 학습에 항상 필요하지 않는 메모리를 올려놓는 비효율성이 있다. (특히 Optimizer States)
- ZeRO는 이러한 문제를 해결하여 Good Computation & Good Memory efficiency를 달성했다.
Parallelism: Theory and Practice
225
Deep Speed
- ZeRO-DP: ZeRO powered Data Parallelism (3 stages)
- Stage 1: Optimizer state partitioning: 메모리 4배 감소 (DP와 동일한 communication volume)
- Stage 2: Gradient state partitioning: 메모리 2배 더 감소 (총 8배 감소, DP와 동일한 Communication volume)
- Stage 3: Parameter state partitioning: DP_degree에 따라 선형적으로 감소 (대신 Communication 증가)
Parallelism: Theory and Practice
226
Deep Speed
- ZeRO-DP: ZeRO powered Data Parallelism (3 stages)
- Stage 1: Optimizer state partitioning: 메모리 4배 감소 (DP와 동일한 communication volume)
- Stage 2: Gradient state partitioning: 메모리 2배 더 감소 (총 8배 감소, DP와 동일한 Communication volume)
- Stage 3: Parameter state partitioning: DP_degree에 따라 선형적으로 감소 (대신 Communication 증가)
Large scale-lm-part1
Large scale-lm-part1
Large scale-lm-part1
Large scale-lm-part1
Large scale-lm-part1
Large scale-lm-part1
Large scale-lm-part1
Large scale-lm-part1
Large scale-lm-part1
Large scale-lm-part1
Large scale-lm-part1
Large scale-lm-part1
Large scale-lm-part1
Large scale-lm-part1
Large scale-lm-part1
Large scale-lm-part1
Large scale-lm-part1
Large scale-lm-part1
Large scale-lm-part1
Large scale-lm-part1
Large scale-lm-part1
Large scale-lm-part1
Large scale-lm-part1
Large scale-lm-part1
Large scale-lm-part1
Large scale-lm-part1
Large scale-lm-part1
Large scale-lm-part1
Large scale-lm-part1
Large scale-lm-part1
Large scale-lm-part1
Large scale-lm-part1
Large scale-lm-part1
Large scale-lm-part1
Large scale-lm-part1
Large scale-lm-part1

More Related Content

What's hot

Fine tune and deploy Hugging Face NLP models
Fine tune and deploy Hugging Face NLP modelsFine tune and deploy Hugging Face NLP models
Fine tune and deploy Hugging Face NLP modelsOVHcloud
 
GPT-2: Language Models are Unsupervised Multitask Learners
GPT-2: Language Models are Unsupervised Multitask LearnersGPT-2: Language Models are Unsupervised Multitask Learners
GPT-2: Language Models are Unsupervised Multitask LearnersYoung Seok Kim
 
DeBERTA : Decoding-Enhanced BERT with Disentangled Attention
DeBERTA : Decoding-Enhanced BERT with Disentangled AttentionDeBERTA : Decoding-Enhanced BERT with Disentangled Attention
DeBERTA : Decoding-Enhanced BERT with Disentangled Attentiontaeseon ryu
 
NLP State of the Art | BERT
NLP State of the Art | BERTNLP State of the Art | BERT
NLP State of the Art | BERTshaurya uppal
 
Transforming deep into transformers – a computer vision approach
Transforming deep into transformers – a computer vision approachTransforming deep into transformers – a computer vision approach
Transforming deep into transformers – a computer vision approachFerdin Joe John Joseph PhD
 
Machine translation survey - vol1
Machine translation survey  - vol1Machine translation survey  - vol1
Machine translation survey - vol1gohyunwoong
 
Attention mechanism 소개 자료
Attention mechanism 소개 자료Attention mechanism 소개 자료
Attention mechanism 소개 자료Whi Kwon
 
A Multi-Armed Bandit Framework For Recommendations at Netflix
A Multi-Armed Bandit Framework For Recommendations at NetflixA Multi-Armed Bandit Framework For Recommendations at Netflix
A Multi-Armed Bandit Framework For Recommendations at NetflixJaya Kawale
 
Switch transformers paper review
Switch transformers paper reviewSwitch transformers paper review
Switch transformers paper reviewSeonghoon Jung
 
Big Bird - Transformers for Longer Sequences
Big Bird - Transformers for Longer SequencesBig Bird - Transformers for Longer Sequences
Big Bird - Transformers for Longer Sequencestaeseon ryu
 
Deep learning for NLP and Transformer
 Deep learning for NLP  and Transformer Deep learning for NLP  and Transformer
Deep learning for NLP and TransformerArvind Devaraj
 
1909 BERT: why-and-how (CODE SEMINAR)
1909 BERT: why-and-how (CODE SEMINAR)1909 BERT: why-and-how (CODE SEMINAR)
1909 BERT: why-and-how (CODE SEMINAR)WarNik Chow
 
한국어 MRC 연구를 위한 표준 데이터셋(KorQuAD) 소개 및 B2B를 위한 MRC 연구 사례
한국어 MRC 연구를 위한 표준 데이터셋(KorQuAD) 소개 및 B2B를 위한 MRC 연구 사례한국어 MRC 연구를 위한 표준 데이터셋(KorQuAD) 소개 및 B2B를 위한 MRC 연구 사례
한국어 MRC 연구를 위한 표준 데이터셋(KorQuAD) 소개 및 B2B를 위한 MRC 연구 사례NAVER Engineering
 
Information retrieval 10 tf idf and bag of words
Information retrieval 10 tf idf and bag of wordsInformation retrieval 10 tf idf and bag of words
Information retrieval 10 tf idf and bag of wordsVaibhav Khanna
 
boosting 기법 이해 (bagging vs boosting)
boosting 기법 이해 (bagging vs boosting)boosting 기법 이해 (bagging vs boosting)
boosting 기법 이해 (bagging vs boosting)SANG WON PARK
 
The Factorization Machines algorithm for building recommendation system - Paw...
The Factorization Machines algorithm for building recommendation system - Paw...The Factorization Machines algorithm for building recommendation system - Paw...
The Factorization Machines algorithm for building recommendation system - Paw...Evention
 
Introduction to Few shot learning
Introduction to Few shot learningIntroduction to Few shot learning
Introduction to Few shot learningRidge-i, Inc.
 
Few shot learning/ one shot learning/ machine learning
Few shot learning/ one shot learning/ machine learningFew shot learning/ one shot learning/ machine learning
Few shot learning/ one shot learning/ machine learningﺁﺻﻒ ﻋﻠﯽ ﻣﯿﺮ
 

What's hot (20)

Fine tune and deploy Hugging Face NLP models
Fine tune and deploy Hugging Face NLP modelsFine tune and deploy Hugging Face NLP models
Fine tune and deploy Hugging Face NLP models
 
GPT-2: Language Models are Unsupervised Multitask Learners
GPT-2: Language Models are Unsupervised Multitask LearnersGPT-2: Language Models are Unsupervised Multitask Learners
GPT-2: Language Models are Unsupervised Multitask Learners
 
DeBERTA : Decoding-Enhanced BERT with Disentangled Attention
DeBERTA : Decoding-Enhanced BERT with Disentangled AttentionDeBERTA : Decoding-Enhanced BERT with Disentangled Attention
DeBERTA : Decoding-Enhanced BERT with Disentangled Attention
 
NLP State of the Art | BERT
NLP State of the Art | BERTNLP State of the Art | BERT
NLP State of the Art | BERT
 
Transforming deep into transformers – a computer vision approach
Transforming deep into transformers – a computer vision approachTransforming deep into transformers – a computer vision approach
Transforming deep into transformers – a computer vision approach
 
Parallelformers
ParallelformersParallelformers
Parallelformers
 
Machine translation survey - vol1
Machine translation survey  - vol1Machine translation survey  - vol1
Machine translation survey - vol1
 
Attention mechanism 소개 자료
Attention mechanism 소개 자료Attention mechanism 소개 자료
Attention mechanism 소개 자료
 
A Multi-Armed Bandit Framework For Recommendations at Netflix
A Multi-Armed Bandit Framework For Recommendations at NetflixA Multi-Armed Bandit Framework For Recommendations at Netflix
A Multi-Armed Bandit Framework For Recommendations at Netflix
 
Switch transformers paper review
Switch transformers paper reviewSwitch transformers paper review
Switch transformers paper review
 
Bert
BertBert
Bert
 
Big Bird - Transformers for Longer Sequences
Big Bird - Transformers for Longer SequencesBig Bird - Transformers for Longer Sequences
Big Bird - Transformers for Longer Sequences
 
Deep learning for NLP and Transformer
 Deep learning for NLP  and Transformer Deep learning for NLP  and Transformer
Deep learning for NLP and Transformer
 
1909 BERT: why-and-how (CODE SEMINAR)
1909 BERT: why-and-how (CODE SEMINAR)1909 BERT: why-and-how (CODE SEMINAR)
1909 BERT: why-and-how (CODE SEMINAR)
 
한국어 MRC 연구를 위한 표준 데이터셋(KorQuAD) 소개 및 B2B를 위한 MRC 연구 사례
한국어 MRC 연구를 위한 표준 데이터셋(KorQuAD) 소개 및 B2B를 위한 MRC 연구 사례한국어 MRC 연구를 위한 표준 데이터셋(KorQuAD) 소개 및 B2B를 위한 MRC 연구 사례
한국어 MRC 연구를 위한 표준 데이터셋(KorQuAD) 소개 및 B2B를 위한 MRC 연구 사례
 
Information retrieval 10 tf idf and bag of words
Information retrieval 10 tf idf and bag of wordsInformation retrieval 10 tf idf and bag of words
Information retrieval 10 tf idf and bag of words
 
boosting 기법 이해 (bagging vs boosting)
boosting 기법 이해 (bagging vs boosting)boosting 기법 이해 (bagging vs boosting)
boosting 기법 이해 (bagging vs boosting)
 
The Factorization Machines algorithm for building recommendation system - Paw...
The Factorization Machines algorithm for building recommendation system - Paw...The Factorization Machines algorithm for building recommendation system - Paw...
The Factorization Machines algorithm for building recommendation system - Paw...
 
Introduction to Few shot learning
Introduction to Few shot learningIntroduction to Few shot learning
Introduction to Few shot learning
 
Few shot learning/ one shot learning/ machine learning
Few shot learning/ one shot learning/ machine learningFew shot learning/ one shot learning/ machine learning
Few shot learning/ one shot learning/ machine learning
 

Similar to Large scale-lm-part1

Transformer Models_ BERT vs. GPT.pdf
Transformer Models_ BERT vs. GPT.pdfTransformer Models_ BERT vs. GPT.pdf
Transformer Models_ BERT vs. GPT.pdfhelloworld28847
 
GPT and other Text Transformers: Black Swans and Stochastic Parrots
GPT and other Text Transformers:  Black Swans and Stochastic ParrotsGPT and other Text Transformers:  Black Swans and Stochastic Parrots
GPT and other Text Transformers: Black Swans and Stochastic ParrotsKonstantin Savenkov
 
BloombergGPT.pdfA Large Language Model for Finance
BloombergGPT.pdfA Large Language Model for FinanceBloombergGPT.pdfA Large Language Model for Finance
BloombergGPT.pdfA Large Language Model for Finance957671457
 
Switch Transformers: Scaling to Trillion Parameter Models with Simple and Eff...
Switch Transformers: Scaling to Trillion Parameter Models with Simple and Eff...Switch Transformers: Scaling to Trillion Parameter Models with Simple and Eff...
Switch Transformers: Scaling to Trillion Parameter Models with Simple and Eff...taeseon ryu
 
How to build a GPT model.pdf
How to build a GPT model.pdfHow to build a GPT model.pdf
How to build a GPT model.pdfStephenAmell4
 
LLMs for the “GPU-Poor” - Franck Nijimbere.pdf
LLMs for the “GPU-Poor” - Franck Nijimbere.pdfLLMs for the “GPU-Poor” - Franck Nijimbere.pdf
LLMs for the “GPU-Poor” - Franck Nijimbere.pdfGDG Bujumbura
 
SCGPT : Few-shot Natural Language Generation for Task-Oriented Dialog
SCGPT : Few-shot Natural Language Generation for Task-Oriented DialogSCGPT : Few-shot Natural Language Generation for Task-Oriented Dialog
SCGPT : Few-shot Natural Language Generation for Task-Oriented Dialogtaeseon ryu
 
Zhongyuan Zhu - 2015 - Evaluating Neural Machine Translation in English-Japan...
Zhongyuan Zhu - 2015 - Evaluating Neural Machine Translation in English-Japan...Zhongyuan Zhu - 2015 - Evaluating Neural Machine Translation in English-Japan...
Zhongyuan Zhu - 2015 - Evaluating Neural Machine Translation in English-Japan...Association for Computational Linguistics
 
Recurrent Neural Networks for Text Analysis
Recurrent Neural Networks for Text AnalysisRecurrent Neural Networks for Text Analysis
Recurrent Neural Networks for Text Analysisodsc
 
Transformer Seq2Sqe Models: Concepts, Trends & Limitations (DLI)
Transformer Seq2Sqe Models: Concepts, Trends & Limitations (DLI)Transformer Seq2Sqe Models: Concepts, Trends & Limitations (DLI)
Transformer Seq2Sqe Models: Concepts, Trends & Limitations (DLI)Deep Learning Italia
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLionel Briand
 
VSSML17 Review. Summary Day 2 Sessions
VSSML17 Review. Summary Day 2 SessionsVSSML17 Review. Summary Day 2 Sessions
VSSML17 Review. Summary Day 2 SessionsBigML, Inc
 
Implications of GPT-3
Implications of GPT-3Implications of GPT-3
Implications of GPT-3Raven Jiang
 
BERT- Pre-training of Deep Bidirectional Transformers for Language Understand...
BERT- Pre-training of Deep Bidirectional Transformers for Language Understand...BERT- Pre-training of Deep Bidirectional Transformers for Language Understand...
BERT- Pre-training of Deep Bidirectional Transformers for Language Understand...Kyuri Kim
 
Weak Supervision.pdf
Weak Supervision.pdfWeak Supervision.pdf
Weak Supervision.pdfStephenLeo7
 
Dataworkz odsc london 2018
Dataworkz odsc london 2018Dataworkz odsc london 2018
Dataworkz odsc london 2018Olaf de Leeuw
 
Predicting Tweet Sentiment
Predicting Tweet SentimentPredicting Tweet Sentiment
Predicting Tweet SentimentLucinda Linde
 

Similar to Large scale-lm-part1 (20)

Transformer Models_ BERT vs. GPT.pdf
Transformer Models_ BERT vs. GPT.pdfTransformer Models_ BERT vs. GPT.pdf
Transformer Models_ BERT vs. GPT.pdf
 
GPT and other Text Transformers: Black Swans and Stochastic Parrots
GPT and other Text Transformers:  Black Swans and Stochastic ParrotsGPT and other Text Transformers:  Black Swans and Stochastic Parrots
GPT and other Text Transformers: Black Swans and Stochastic Parrots
 
BloombergGPT.pdfA Large Language Model for Finance
BloombergGPT.pdfA Large Language Model for FinanceBloombergGPT.pdfA Large Language Model for Finance
BloombergGPT.pdfA Large Language Model for Finance
 
Switch Transformers: Scaling to Trillion Parameter Models with Simple and Eff...
Switch Transformers: Scaling to Trillion Parameter Models with Simple and Eff...Switch Transformers: Scaling to Trillion Parameter Models with Simple and Eff...
Switch Transformers: Scaling to Trillion Parameter Models with Simple and Eff...
 
How to build a GPT model.pdf
How to build a GPT model.pdfHow to build a GPT model.pdf
How to build a GPT model.pdf
 
LLMs for the “GPU-Poor” - Franck Nijimbere.pdf
LLMs for the “GPU-Poor” - Franck Nijimbere.pdfLLMs for the “GPU-Poor” - Franck Nijimbere.pdf
LLMs for the “GPU-Poor” - Franck Nijimbere.pdf
 
Chatbot ppt
Chatbot pptChatbot ppt
Chatbot ppt
 
SCGPT : Few-shot Natural Language Generation for Task-Oriented Dialog
SCGPT : Few-shot Natural Language Generation for Task-Oriented DialogSCGPT : Few-shot Natural Language Generation for Task-Oriented Dialog
SCGPT : Few-shot Natural Language Generation for Task-Oriented Dialog
 
Zhongyuan Zhu - 2015 - Evaluating Neural Machine Translation in English-Japan...
Zhongyuan Zhu - 2015 - Evaluating Neural Machine Translation in English-Japan...Zhongyuan Zhu - 2015 - Evaluating Neural Machine Translation in English-Japan...
Zhongyuan Zhu - 2015 - Evaluating Neural Machine Translation in English-Japan...
 
Recurrent Neural Networks for Text Analysis
Recurrent Neural Networks for Text AnalysisRecurrent Neural Networks for Text Analysis
Recurrent Neural Networks for Text Analysis
 
Albert
AlbertAlbert
Albert
 
Transformer Seq2Sqe Models: Concepts, Trends & Limitations (DLI)
Transformer Seq2Sqe Models: Concepts, Trends & Limitations (DLI)Transformer Seq2Sqe Models: Concepts, Trends & Limitations (DLI)
Transformer Seq2Sqe Models: Concepts, Trends & Limitations (DLI)
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and Repair
 
VSSML17 Review. Summary Day 2 Sessions
VSSML17 Review. Summary Day 2 SessionsVSSML17 Review. Summary Day 2 Sessions
VSSML17 Review. Summary Day 2 Sessions
 
Implications of GPT-3
Implications of GPT-3Implications of GPT-3
Implications of GPT-3
 
NLP in 2020
NLP in 2020NLP in 2020
NLP in 2020
 
BERT- Pre-training of Deep Bidirectional Transformers for Language Understand...
BERT- Pre-training of Deep Bidirectional Transformers for Language Understand...BERT- Pre-training of Deep Bidirectional Transformers for Language Understand...
BERT- Pre-training of Deep Bidirectional Transformers for Language Understand...
 
Weak Supervision.pdf
Weak Supervision.pdfWeak Supervision.pdf
Weak Supervision.pdf
 
Dataworkz odsc london 2018
Dataworkz odsc london 2018Dataworkz odsc london 2018
Dataworkz odsc london 2018
 
Predicting Tweet Sentiment
Predicting Tweet SentimentPredicting Tweet Sentiment
Predicting Tweet Sentiment
 

Recently uploaded

IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024Mark Billinghurst
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...srsj9000
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2RajaP95
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx959SahilShah
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...VICTOR MAESTRE RAMIREZ
 
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxPoojaBan
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLDeelipZope
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130Suhani Kapoor
 
microprocessor 8085 and its interfacing
microprocessor 8085  and its interfacingmicroprocessor 8085  and its interfacing
microprocessor 8085 and its interfacingjaychoudhary37
 
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZTE
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escortsranjana rawat
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learningmisbanausheenparvam
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130Suhani Kapoor
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 

Recently uploaded (20)

IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024
 
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...
 
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptx
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCL
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
 
microprocessor 8085 and its interfacing
microprocessor 8085  and its interfacingmicroprocessor 8085  and its interfacing
microprocessor 8085 and its interfacing
 
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learning
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 

Large scale-lm-part1

  • 1. 집현전 최신반 1조 고현웅 김대웅 이윤재 Large-scale LM에 대한 얕고 넓은 지식들 (part 1) 1
  • 3. 요즘 우리(NLPer)들의 모습…... 솔직히 도저히 못 따라가겠습니다. …^^ 다른분야는 3년 전 논문이면 최신논문인데, 여기(AI)에서는 3년이면 강산이 바뀜 ㅋ LSTM이요? 그게 뭐죠? 기억이 안나는데…... 3
  • 4. 그래서 준비해봤습니다. 최신 이론과 기술들, 핵심만 말씀드릴게요! ps. 깊게 공부하고 싶으면 더 찾아보셔야 합니다. ps. 발표가 다소 길어요. 바쁘시면 유튜브로 챙겨보셔도 좋습니다. 4
  • 5. Index 1. 🤖 History of LM: Google vs OpenAI (Part1) 1. OpenAI: GPT-1 (110M) 2. Google: BERT (340M) 3. OpenAI: GPT-2 (1.5B) 2. 🔥 Parallelism: Theory and Practice (Part1) 1. Fundamentals 2. Data Parallelism 3. Model Parallelism 4. Pipeline Parallelism 5. Deep Speed 5 4. Google: T5 (11B) 5. OpenAI: GPT-3 (175B) 6. Google: Switch Transformers (1T)
  • 6. 3. 🤗 NEO & NEOX: Let's open it up! (Part 2) 1. GPT-NEO & NEOX 2. Sparsity 3. Positional Embeddings 4. Normalizations 4. 🌱 Beyond Fine-tuning: New methods (Part 2) 1. Prompt Programming Overview 2. Discrete Prompt Search 3. Continuous Prompt Search 4. Pattern Exploiting Training Index 6
  • 7. Chapter 1 🤖 History of LM: Google vs OpenAI (Background 연구 설명) 7
  • 9. GPT-1 (OpenAI 2018, size: 110M) - Transformer를 대량의 웹 데이터로 Pre-training해서 언어를 이해시켰다. - Supervised Dataset은 수가 적어 언어의 보편적인 특성을 배우기 어렵다. - 웹에 많은 데이터가 있으니 이를 활용해 모델의 성능을 높이기 위함. - 단어들이 주어지면 그 다음 단어를 예측하는 방식으로 Pre-training을 했음. - 이후에 NLU 태스크의 데이터셋으로 모델을 Fine-tuning 해서 사용한다. - 주어진 태스크의 데이터셋에 맞게 입력만 변경, Transformer는 고정한다. - Transformer Layer위에 새로운 Linear-layer를 붙여서 예측을 수행한다. History of LM: Google vs OpenAI 9
  • 10. GPT-1 (OpenAI 2018, size: 110M) - Transformer Decoder만 사용하여 만든 Causal LM. - Decoder에는 Masked Multi-head Attention만 존재. - Encoder가 없기 때문에, Cross-Attention도 제거됨. - 즉, GPT는 Uni-directional Attention만 참조할 수 있는 모델임. - 그 위에 2개의 Linear-layer가 탑재되어있다. - Text-classifier: Fine-tuning에 사용. - Text-prediction: Pre-training + Auxiliary Loss에 사용. - Auxiliary Loss는 GPT-2부터는 사라지게 되었음. History of LM: Google vs OpenAI 10
  • 12. BERT (Google 2018, size: 340M) - 마찬가지로 대량의 웹 데이터를 사용, 2가지 Objective로 Pre-training. - MLM: 단어를 [MASK]로 랜덤하게 (15%) 변경하고 원래 토큰 맞추기 - NSP: 두 문장을 [SEP]으로 연결해서 입력, 연결된 문장인지 아닌지 맞추기 - 이후에 원하는 태스크의 데이터셋으로 모델을 Fine-tuning 해서 사용. - Span prediction: size=2인 Linear-layer 붙여서 Start, End를 예측. - Pair prediction: 문장 두개 넣고 [CLS]토큰을 Linear-layer로 분류 - Single prediction: 문장 하나 넣고 [CLS] 토큰을 Linear-layer로 분류 - Sequence tagging: 각 토큰의 출력 Repr을 Linear-layer로 예측 - 도전한 모든 Task에서 당시 SoTA를 찍고 2010년대를 대표하는 LM이 됨. History of LM: Google vs OpenAI 12
  • 13. BERT (Google 2019, size: 340M) - BERT는 Transformer Encoder만 사용하여 만든 Encoder LM. - Activation 함수를 ReLU가 아닌 GeLU를 사용해서 성능을 개선. - 3개의 Embedding을 더해서 Token Representation으로 활용. - Token Embedding + Pos Embedding + Segment Embedding - Pos Embedding: Sinusoidal Encoding 보다 Embedding Matrix가 더 좋음. - Segment Embedding: 두개의 문장이 입력될 때, 각 문장에 다른 임베딩 부여. History of LM: Google vs OpenAI 13
  • 15. GPT-2 (Google 2019, size: 1.5B) - 요즘 NLP 모델들은 Specialist이다. 그러나 사람은 Generalist이다. - BERT와 같은 모델은 Fine-tuning 하여 특정 태스크만 풀 수 있는 Specialist이다. - 이들은 사람처럼 여러 작업을 수행하지 못하고 단 하나의 태스크만 풀 수 있다. - Generalist는 “Fr” = translation(“En”)이 아닌, “Fr” = general(“En”, “translation”) - Prompt Programming의 문을 열다. - GPT-2는 GPT-1과 동일한 구조이지만 더 많은 데이터와 파라미터를 사용했다. - 성능이 좋지는 않았지만 Fine-tuning 없이도 여러가지 태스크를 풀 수 있었다. - 가령 Text를 넣고, TLDR; 을 붙이면 요약이 되고, 몇개의 예제를 주면 번역을 해냈다. History of LM: Google vs OpenAI 15 VS
  • 16. GPT-2 (Google 2019, size: 1.5B) - Byte level BPE (BBPE) - 기존의 BPE는 Unicode level (Character level BPE, CBPE) OOV의 발생이 잦았다. - CBPE로 OOV가 없으려면 Vocab 사이즈가 13만 이상이여야 하는데 너무 큰 수치이다. - 그러나 토큰을 Byte-level (Byte-level BPE, BBPE)로 쪼개면 256개면 OOV를 없앨 수 있다. - Merging by category - BPE 학습시 특수기호가 캐릭터에 merge 되면 해당 단어의 Repr이 학습되는 것을 방해한다. - Dog! Dog? 같은 토큰들이 Transformer 모델이 Dog의 Repr을 학습하는 것을 방해한다. - 따라서 GPT2는 다른 카테고리의 토큰끼리는 병합되지 않도록 BPE 학습을 설계했다. History of LM: Google vs OpenAI 16
  • 17. GPT-2 (Google 2019, size: 1.5B) - Pre-Layer Normalization (Pre-LN) - Transformer는 Layer가 깊어지면 Gradient가 커지는데, Pre-LN은 Layer와 Gradient가 반비례함. - 따라서 Post LN은 Layer를 깊게 쌓으면 Gradient가 폭발하여 학습이 안되는 경우가 자주 발생함. - Pre-LN은 Gradient가 상쇄되어 Layer가 깊어도 기존보다 안정적으로 학습되는 경향이 있음. - Normalization Scaling - Post-LN의 경우 Residual Branch: x + f(x)에서 f(x) 부분의 종속성이 강함. - 그러면 학습이 진행되면서 학습 초기와 후반의 Output change가 커져서 학습이 불안정해짐. - 따라서 이 Residual Branch에 1/sqrt(n_layer)를 곱해줘서 학습을 안정하게 만듦. - https://github.com/kakaobrain/nlp-paper-reading/blob/master/notes/Admin.md 참고. History of LM: Google vs OpenAI 17
  • 19. T5 (Google 2019, size: 11B) - T5는 모든 태스크를 Seq2Seq 형태로 풀기위해 개발한 커다란 LM. - 분류, 태깅, 요약, 번역 등의 모든 태스크를 Seq2Seq으로 풀었음. - 파라미터의 수가 11B로 당시 최고 사이즈의 언어모델로 기록되었음. - 각종 Objective, Architecture를 비교, 최고의 LM을 만들고자 함. History of LM: Google vs OpenAI 19
  • 20. T5 (Google 2019, size: 11B) - 여러 아키텍처 중에서 Seq2Seq 아키텍처가 가장 좋다. - Seq2Seq, Uni-LM, CLM(GPT) 중에서 Seq2Seq이 가장 우수. - 다음 단어를 예측하는 GPT의 CLM보다 Denoising 하는게 더 좋다. History of LM: Google vs OpenAI 20
  • 21. T5 (Google 2019, size: 11B) - 여러 Objective 중에서 Span-level Denosing이 제일 좋다. - BERT나 MASS가 수행했던 Token-level Denoising 보다 SpanBERT 나 BART가 수행했던 Span-level Denosing의 성능이 더 좋음. - Span length는 3 ~ 5, corruption ratio는 15% 정도가 적당함. History of LM: Google vs OpenAI 21
  • 22. T5 (Google 2019, size: 11B) - 데이터의 양이 아주 많지 않다면, Unsupervised Pre-training이 좋다. - 번역을 제외하고는 Unsupervised PT+ FT가 가장 우수함. - mBART 논문에 따르면 Fine-tuning Training Dataset의 수가 너무 많으면 pre-training 때 배운 weight를 지워버림. - 따라서 이런 경우는 pre-training이 큰 힘을 쓰지 못하기 때문에 supervised multi-task learning이 좋은 성능을 보임. History of LM: Google vs OpenAI 22
  • 23. 23 갑자기 선을 넘어버리는 OpenAI... NLP 연구자들
  • 25. GPT-3 (OpenAI 2020, size: 175B) - OpenAI가 MS와 협업을 통해 1750억개의 파라미터를 가진 GPT-3를 발표. - 21년 현재까지도 역사상 최고의 Language Model이라는 찬사를 받고 있음. - Non-MoE Transformer 중에 현존하는 가장 큰 사이즈의 LM. - 진짜 Generalist의 출현을 알리다. - GPT-2때 가능성만 보여줬던, In-context learning (학습하지 않고 추론하는 것) 의 성능 을 웬만한 Supervised SoTA 모델 급의 성능까지 끌어올렸음 - 빅모델, 즉 Large-scale LM이라는 용어가 이 때 처음 유행하기 시작했으며 더 이상 특정 태스크를 위한 학습(파라미터 업데이트)이 필요 없게 되는 Paradigm Shift를 일으킴. History of LM: Google vs OpenAI 25
  • 26. GPT-3 (OpenAI 2020, size: 175B) - GPT-3는 같은 해, 본인들이 연구했던 Scaling Law에 기반하였다. - LM의 성능은 파라미터 수 N, 데이터 크기 D, 연산능력 C와 관계 있으며, 모델의 형태는 중요하지 않다. - 즉, 컴퓨팅 파워가 세질수록, N과 D의 크기에 따라 LM 성능이 좌우된다. - 모델의 오버피팅을 막기 위해서는 N이 10배 수준으로 커질 때, D도 5.5배 수준으로 커져야 한다. - N이 큰 모델은 더 적은 데이터와 스텝만으로 N이 작은 모델과 동일한 수준에 도달할 수 있다. - N이 고정되었을 때, 하이퍼 파라미터(n_layer, d_ff, n_head)는 Loss에 큰 영향은 주지 않는다. - 따라서 Optimal Compute Budget allocation을 위해서는 컴퓨팅의 대부분을 N을 늘리는데 써야한다. History of LM: Google vs OpenAI 26
  • 27. GPT-3 (OpenAI 2020, size: 175B) - GPT-3의 아키텍처는 GPT-2와 거의 유사하지만 사이즈에서 큰 차이가 있다. - Scaling Law에 따라 Hyperparamter를 설정하였음. - 최소 125M 부터 최대 175B에 해당하는 모델을 학습하였음. - 여기서 설정한 175B은 당시 개발된 ZeRO-2의 최고 학습 사이즈. - 하지만 이제 ZeRO-infinity가 나왔다고 하는데... (흠좀무) - 연산 효율성을 위해 Sparse한 Local Attention을 사용했다. - 이는 Sparse Transformer의 Attention과 유사함. - Full Attention은 O(n^2)의 복잡도를 가지기 때문에 큰 모델에 적합하지 않음. History of LM: Google vs OpenAI 27
  • 28. GPT-3 (OpenAI 2020, size: 175B) - 프롬프트에 Few-shot Examples의 수를 늘릴 수록 성능이 개선된다. - 프롬프트에 들어가는 Few-shot Examples의 수에 따라 성능을 비교했다. - Examples의 수가 늘어날 수록 성능이 일관되게 개선됨을 확인했다. - 프롬프트에 Natural Language Description이 추가되면 성능이 개선된다. - Natural Language Description은 T5에서 제안한 것과 유사하다. - 이러한 Description을 프롬프트에 추가하면 성능이 개선되었다. History of LM: Google vs OpenAI 28
  • 29. GPT-3 (OpenAI 2020, size: 175B) History of LM: Google vs OpenAI 29
  • 32. Switch Transformers (Google 2021, size: 1T) - 구글이 Trillion (1조) parameter를 가지는 Switch Transformers를 발표. - 이전에 발표된 MoE Transformer와 GShard를 개선한 논문. - MoE (Mixture of Experts) Transformer - FFN을 여러개로 쪼갠 후, 토큰별로 FFN을 선택해서 사용. - Mixture of Experts는 전문가의 연합이라는 뜻 (각각 FFN이 각 분야의 전문가) - 꽤 오래전에 제안된 개념으로 각각 Expert가 서로 다른 능력을 배울 것이라고 가정 - Gating Network를 통해 토큰들이 특정 FFN 레이어를 배정받는 메커니즘. - Gating Network 역시 Trainable Parameter로 다른부분들과 함께 학습됨. History of LM: Google vs OpenAI 32
  • 33. Switch Transformers (Google 2021, size: 1T) - MoE Transformers는 하나의 토큰을 2개 이상의 FFN에 게이팅 되도록 하였다. - 예를 들면 23번 토큰이 19번 FFN에도 할당되고 41번째 FFN에도 할당 되는 것. - 한 토큰이 여러 FFN들 중에서 어떤 것에 더 적합한지 비교하는 능력을 배울 것이라는 가설. - GShard: Scaling Giant Models with Conditional Computation and Automatic Sharding - GShard는 각각의 FFN들을 각각의 Device에 나눠담는 방식. - Attention, Norm등 파라미터는 모든 Device에 올리고, FFN만 각각 Device에 저장 - n번째 토큰이 k번째 FFN에 할당되면 k번째 FFN이 있는 Device로 포워딩되어 연산. History of LM: Google vs OpenAI 33
  • 34. Switch Transformers (Google 2021, size: 1T) - GShard의 문제1: Load Balancing Problem - 여러개의 FFN 중에서 일부의 FFN에만 토큰들이 엄청나게 몰리도록 학습 되었음. - 예를 들면 100개의 FFN 중에서 5번, 8번만 자주 쓰이고 나머지 98개는 잘 안쓰는것. - 특정 Device에만 부하가 걸리면 작업이 모두 끝날때까지 다른 Device는 기다려야함. - 이로 인해 전체적인 프로세싱 효율이 매우 떨어졌음. - GShard의 문제2: Gating Network의 Complexity - 하나의 토큰을 FFN 여러개에 포워딩 하기 때문에 Gating 과정이 매우 복잡하고 느렸음. History of LM: Google vs OpenAI 34
  • 35. Switch Transformers (Google 2021, size: 1T) - Switch Transformers: Scaling to Trillion Parameter Models with Simple and Efficient Sparsity - GShard가 가진 문제들을 해결하기 위해 여러가지 메커니즘을 도입한 모델. - Switch Routing (Top-1 Routing) - 한 토큰 당 하나의 FFN에 할당해도 기존 가설과 다르게 성능에 큰 문제가 없었음. - Routing Computation이 감소하고 Expert로 쏠리는 부하가 적어지며 구현도 심플해졌음. History of LM: Google vs OpenAI 35
  • 36. Switch Transformers (Google 2021, size: 1T) - Capacity Factor - 한개의 Expert가 입력받을 수 있는 최대 토큰의 수를 지정하고, 그 이상은 입력되지 않도록 함. - 예를 들어 배치에 20,000개의 토큰이 있고 Expert의 수가 1,000개라면 capacity factor가 1.0 일 때, 한개의 Expert는 최대 20개의 Token을 입력받고 2.0이면 최대 40개의 토큰을 입력받음. - 만약 특정 Expert에 최대치를 넘어서는 토큰이 할당되면 Logit 순서로 제외. - 아예 FFN에 입력이 안되는 토큰도 생기는데 성능은 큰 차이가 없었고 속도도 빨랐음. History of LM: Google vs OpenAI 36
  • 37. Switch Transformers (Google 2021, size: 1T) - Load Balancing Loss - 높은 확률을 갖는 Expert의 Logit을 줄이는 Loss를 추가하여 학습. - 이를 통해 토큰들이 특정 Expert에만 쏠리는 현상을 방지할 수 있었음. - Smaller Parameter Initialization & Expert Dropout - Initialization distribution의 scale을 작게 하니 성능이 많이 좋아짐. - Expert / Non-Expert의 Dropout을 각각 다르게 적용. History of LM: Google vs OpenAI 37
  • 38. History of LM: Google vs OpenAI 38 Switch Transformers (Google 2021, size: 1T) - Experiments - 큰 모델일 수록 더 성능이 좋으며 낮은 Loss에 빠르게 도달한다. - Sparse Model이기 때문에 파라미터가 많아도 FLOPS가 낮음. - 따라서 동일 FLOPS의 T5와 비교해서 성능이 우수하다고 함. (약간 억지 같기도?) - 재밌는건 T5-large (739M)의 성능이 Switch-Base (7.4B)보다 성능이 좋음.
  • 39. History of LM: Google vs OpenAI 39 Switch Transformers (Google 2021, size: 1T) - Distillation - T5 223M 모델을 0%, Switch-base 3.8B 모델을 100%라고 가정. - Switch-base를 T5 모델로 Distillation 했을 때, 30% 정도 성능을 개선시킬 수 있었음.
  • 40. Chapter 2 🔥 Parallelism: Theory and Practice (nn.DataParallel to ZeRO-infinity) 40
  • 42. Fundamentals - Parallelism (병렬화) - 병렬화는 여러개를 동시에 처리하는 기술을 의미함. - 머신러닝에서는 주로 여러개의 디바이스에서 연산을 병렬화 하여 속도나 메모리 효율성을 개선하기 위해 사용 - 머신러닝 영역에서는 주로 세가지 병렬화 기법이 존재함. Parallelism: Theory and Practice 42
  • 43. Fundamentals - Data Parallelism (데이터 병렬화) - 데이터가 많을 때, 데이터를 병렬처리 하여 학습속도를 끌어올리는 작업. - 모든 디바이스에 모델을 복사하고 서로 다른 데이터를 각 디바이스에 입력함. - 이로 인해 배치사이즈를 디바이스 수의 배수만큼 더 많이 입력할 수 있음. - 그러나 이러한 데이터 병렬화는 모델 하나가 디바이스 하나에 완전히 올라갈 때만 가능함. Parallelism: Theory and Practice 43
  • 44. Fundamentals - Data Parallelism (데이터 병렬화) - 데이터가 많을 때, 데이터를 병렬처리 하여 학습속도를 끌어올리는 작업. - 모든 디바이스에 모델을 복사하고 서로 다른 데이터를 각 디바이스에 입력함. - 이로 인해 배치사이즈를 디바이스 수의 배수만큼 더 많이 입력할 수 있음. - 그러나 이러한 데이터 병렬화는 모델 하나가 디바이스 하나에 완전히 올라갈 때만 가능함. Parallelism: Theory and Practice 44 배치 1~4 배치 5~8 배치 9~12 배치 12~16
  • 45. Fundamentals - Model Parallelism (모델 병렬화) - 만약 모델이 너무 커서 하나의 디바이스에 담을 수 없을 때 파라미터를 쪼개서 올리는 방법. - 각 디바이스에 모델의 파라미터 일부분들이 담겨있음. - 이로 인해 큰 모델도 작은 디바이스 여러개를 이용하면 디바이스에 올릴 수 있음. Parallelism: Theory and Practice 45
  • 46. Fundamentals - Model Parallelism (모델 병렬화) - 만약 모델이 너무 커서 하나의 디바이스에 담을 수 없을 때 파라미터를 쪼개서 올리는 방법. - 각 디바이스에 모델의 파라미터 일부분들이 담겨있음. - 이로 인해 큰 모델도 작은 디바이스 여러개를 이용하면 디바이스에 올릴 수 있음. Parallelism: Theory and Practice 46 레이어 1 레이어 3 레이어 2 레이어 4
  • 47. Fundamentals - Pipeline Parallelism (파이프라인 병렬화) - 만약 Layer 단위로 모델 병렬화를 수행했다면 반드시 레이어들을 순서대로 실행해야함. - 따라서 Layer 단위의 모델 병렬화를 수행하면 연산과정의 순서가 생길 수 밖에 없음. - 이 연산과정을 병렬적으로 파이프라이닝 하는 것이 파이프라인 병렬화임. (뒤에서 자세히 다시 설명할 예정) Parallelism: Theory and Practice 47
  • 48. Parallelism: Theory and Practice 48 동시에 2개 레이어 처리 동시에 3개 레이어 처리 동시에 4개 레이어 처리 동시에 1개 레이어 처리 동시에 1개 레이어 처리 동시에 1개 레이어 처리 파이프라인 모델 병렬화 기존 모델 병렬화 device들의 쉬는 시간이 많음 Fundamentals - Pipeline Parallelism (파이프라인 병렬화) - 만약 Layer 단위로 모델 병렬화를 수행했다면 반드시 레이어들을 순서대로 실행해야함. - 따라서 Layer 단위의 모델 병렬화를 수행하면 연산과정의 순서가 생길 수 밖에 없음. - 이 연산과정을 병렬적으로 파이프라이닝 하는 것이 파이프라인 병렬화임. (뒤에서 자세히 다시 설명할 예정)
  • 49. Fundamentals - Message Passing (메시지 패싱) - Message Passing은 동일한 주소 공간을 공유하지 않는 프로세스들이 데이터를 주고받을 수 있도록 메시지라는 간접 정보를 전달하고 주고 받는 것. - 예를 들면 Process1이 특정 태그가 달린 데이터를 메시지 큐에 Send 하도록, Process2는 해당 태그가 달린 데이터를 메시지에서 Receive 받도록 코딩 해놓으면 메모리 공유 없이도 두 프로세스가 데이터를 주고 받게 됨. Parallelism: Theory and Practice 49
  • 50. Fundamentals - MPI (Message Passing Interface) - Message Passing에 대한 표준 인터페이스를 의미 - 대표적으로 OpenMPI라는 오픈소스 Message Passing 라이브러리가 있음. - 프로세서간 Message Passing에 사용되는 여러가지 연산들이 정의되어 있음. Parallelism: Theory and Practice 50
  • 51. Fundamentals - MPI (Message Passing Interface) 기본 용어 - Node: 일반적으로 컴퓨터라고 생각하면 됨. 하나의 Node에 여러대의 Device가 존재 가능. - Global Rank: ML에서는 GPU의 ID라고 생각하면 됨 (원래는 프로세스의 우선순위) - Local Rank: ML에서는 Node 안에서의 GPU ID라고 생각하면 됨. (원래는 노드내 프로세스의 우선순위) - Size (World Size): ML에서는 전체 GPU의 수 (원래는 총 프로세스의 수) Parallelism: Theory and Practice 51 Node 0: GPU0, GPU1, GPU2, GPU3 Node 1: GPU0, GPU1, GPU2, GPU3 Node 2: GPU0, GPU1, GPU2, GPU3 Node 0의 GPU1: Global Rank=01, Local Rank=01 Node 1의 GPU0: Global Rank=04, Local Rank=00 Node 2의 GPU3: Global Rank=11, Local Rank=03 Size: 12
  • 52. Fundamentals - Collective Communication - MPI에서 제공하는 병렬처리 연산들. 더 많은 종류가 있는데 여기에서는 주요 4개 + 2개만 소개. - 여러 프로세스들이 협력해서 통신하는 것이기 때문에 Collective Communication임. - GPU에서 데이터나 Gradient 등을 전송할 때, 실제로 이러한 Collective Communication을 수행함. Parallelism: Theory and Practice 52
  • 53. Fundamentals - Collective Communication: Broadcast - 특정 Process에서 하나의 값을 복사해서 여러 Process들로 전송하는 연산. Parallelism: Theory and Practice 53
  • 54. Fundamentals - Collective Communication: Scatter - 특정 Process가 가진 배열의 값들을 다른 Process들로 쪼개서 전송하는 연산 Parallelism: Theory and Practice 54
  • 55. Fundamentals - Collective Communication: Gather - 각 Process가 가진 값들을 특정한 하나의 Process에게 모으는 연산. Parallelism: Theory and Practice 55
  • 56. Fundamentals - Collective Communication: Reduce - 각 Process가 가진 값들을 특정한 하나의 Process에게 연산해서 모으는 연산. - Gather와 비슷할 수도 있는데, 각 Process가 가진 연산을 하나의 값으로 만드는 것이 차이점. Parallelism: Theory and Practice 56
  • 57. Fundamentals - Collective Communication: 정리 Parallelism: Theory and Practice 57 복사하기 쪼개기 모으기 연산하기
  • 58. Fundamentals - Collective Communication: All + ??? - 기본적인 4개의 연산 이외에 All + ???와 같은 이름을 가진 연산들도 있음. - 이름 앞에 All이 붙으면 연산 결과를 참여한 모든프로세스가 동일하게 반환받는 연산임. Parallelism: Theory and Practice 58
  • 59. Fundamentals - Collective Communication: All-Gather - Gather 연산을 수행해서 모인 값들을 참여한 모든 Process가 반환받음. - 기존 Gather 연산에서 하나의 Process가 결과를 반환받는 것과 대조됨. Parallelism: Theory and Practice 59
  • 60. Fundamentals - Collective Communication: All-Reduce - 마찬가지로 Reduce 연산을 수행해서 계산된 결과를 참여한 모든 Process가 반환받음. - 기존 Reduce 연산에서 하나의 Process가 결과를 반환받는 것과 대조됨. Parallelism: Theory and Practice 60
  • 61. Fundamentals - Collective Communication: NCCL (Nvidia Collective Communication Library) - Nvidia에서 개발한 GPU 특화 Collective Communication Library (‘Nickel’이라고 읽음) - Nvidia GPU에서 사용시 다른 도구에 비해 월등히 탁월한 성능을 보이는 것으로 알려져 있음. - Nvlink (다중 GPU 연결 인터페이스)를 직접 활용하여 매우 높은 대역폭에서 전송 가능. Parallelism: Theory and Practice 61 Nvlink
  • 62. Data Parallelism (Pytorch, Horovod, Pytorch-distributed) 62
  • 63. Data Parallelism - nn.DataParallel( ) - Data Parallelism은 All-reduce 연산을 활용하기 전과 후로 나뉨. - 가장 먼저 우리에게 익숙한 torch의 nn.DataParallel(model)의 동작방식에 대해 알아봄. - nn.DataParallel( )은 single-node & multi-gpu에서 모델을 학습하기 위한 멀티 쓰레드 모듈. https://medium.com/daangn/pytorch-multi-gpu-학습-제대로-하기-27270617836b Parallelism: Theory and Practice 63
  • 64. Data Parallelism - nn.DataParallel( ): Forward Pass - 1) 입력된 mini-batch를 scatter하여 각 디바이스로 전송. - 2) GPU1에 저장된 모델의 파라미터를 GPU 2, 3, 4로 replicate하여 전송. - 3) 각 device로 복사된 모델로 Forward 하여 출력값을 구함. - 4) 출력값들을 gather하여 GPU1에 모음. https://medium.com/daangn/pytorch-multi-gpu-학습-제대로-하기-27270617836b Parallelism: Theory and Practice 64
  • 65. Data Parallelism - nn.DataParallel( ): Backward Pass - 1) GPU1의 Gather된 출력값과 Label을 이용하여 각각의 Loss를 계산. - 2) 계산된 각각의 Loss를 각각의 device에 scatter함. - 3) 전달받은 Loss를 이용해서 각 device에서 backward를 수행. - 4) 모든 gradient를 GPU1로 reduce하여 GPU1의 모델 파라미터를 업데이트. https://medium.com/daangn/pytorch-multi-gpu-학습-제대로-하기-27270617836b Parallelism: Theory and Practice 65
  • 66. Data Parallelism - nn.DataParallel( ): 혹시나 모르시는 분들을 위해…... - loss.backward( ): 기울기를 미분해서 Gradient만 계산 (parallel) - optimizer.step( ): Gradient를 이용해서 파라미터 업데이트 (sequential) - Computation Cost는 backward( ) > step( ) https://medium.com/daangn/pytorch-multi-gpu-학습-제대로-하기-27270617836b Parallelism: Theory and Practice 66 optimizer.step() loss.backward() + 모멘텀, Weight Decay 등
  • 67. Data Parallelism - nn.DataParallel( ): Codes - 사용할 땐, `nn.DataParallel(model)`만 호출해주면 됨. https://medium.com/daangn/pytorch-multi-gpu-학습-제대로-하기-27270617836b Parallelism: Theory and Practice 67 import torch import torch.nn as nn model = BERT(args) model = nn.DataParallel(model) model.cuda() ... for i, (inputs, labels) in enumerate(train_loader): outputs = model(inputs) loss = criterion(outputs, labels) optimizer.zero_grad() loss.backward() optimizer.step()
  • 68. Data Parallelism - nn.DataParallel( ): Codes - `nn.DataParallel(model)`의 forward를 코드로 나타내면 다음과 같음. https://medium.com/daangn/pytorch-multi-gpu-학습-제대로-하기-27270617836b Parallelism: Theory and Practice 68 def data_parallel(module, input, device_ids, output_device): inputs = nn.parallel.scatter(input, device_ids) # 입력 데이터를 device_ids들에 Scatter함 replicas = nn.parallel.replicate(module, device_ids) # 모델을 device_ids들에 복제함. outputs = nn.parallel.parallel_apply(replicas, inputs) # 각 device에 복제된 모델이 각 device의 데이터를 Forward함. return nn.parallel.gather(outputs, output_device) # 모델의 출력값을 output_device(하나의 device)로 모음
  • 69. Data Parallelism - nn.DataParallel( ): Codes - torch-lightning을 사용하면 매우 쉽게 사용 가능. https://medium.com/daangn/pytorch-multi-gpu-학습-제대로-하기-27270617836b Parallelism: Theory and Practice 69 from pytorch_lightining import Trainer lightning_model = ... trainer = Trainer( args, accelerator=‘dp’, # <—— 여기 한줄만 바꾸면 됨. ) Trainer.fit( lightning_model, train_loader, val_loader, )
  • 70. Data Parallelism - nn.DataParallel( ): Codes https://medium.com/daangn/pytorch-multi-gpu-학습-제대로-하기-27270617836b Parallelism: Theory and Practice 70 0번 디바이스에 Output들이 Gather되기 때문에 사용량이 많음. 근데 만약에 GPU 잘못 꽂아서 0번 Device가 8GB이고, 1번 Device가 32GB면? —> 아… 빼서 다시 꽂아야 하나…
  • 71. Data Parallelism - nn.DataParallel( ): Codes - `os.environ[‘CUDA_VISIBLE_DEVICE’]`를 이용해 사용할 GPU 선택 - `nn.DataParallel(model)`에 output_device를 설정하여 output을 gather 받을 device 선택 https://medium.com/daangn/pytorch-multi-gpu-학습-제대로-하기-27270617836b Parallelism: Theory and Practice 71 import os import torch.nn as nn os.environ["CUDA_VISIBLE_DEVICES"] = '0, 1, 2, 3’ # 4개의 device를 사용함 model = nn.DataParallel(model, output_device=1) # Gradient를 1번 device에 Gather함.
  • 72. Data Parallelism - nn.DataParallel( ): 문제점 - (1) 멀티쓰레드 모듈이기 때문에 python에서 비효율적임 (GIL 참고) - (2) GPU1에서 업데이트된 모델을 매 스텝마다 모든 device로 replicate 해야 함. - (3) 메모리 불균형이 일어나서 GPU를 100% 활용할 수 없음. https://medium.com/daangn/pytorch-multi-gpu-학습-제대로-하기-27270617836b Parallelism: Theory and Practice 72
  • 73. Data Parallelism - nn.DataParallel( ): 문제점 - (1) 멀티쓰레드 모듈이기 때문에 python에서 비효율적임 (GIL 참고) ——> 멀티 쓰레드의 문제 - (2) GPU1에서 업데이트된 모델을 매 스텝마다 모든 device로 replicate 해야 함. - (3) 메모리 불균형이 일어나서 GPU를 100% 활용할 수 없음. https://medium.com/daangn/pytorch-multi-gpu-학습-제대로-하기-27270617836b Parallelism: Theory and Practice 73
  • 74. Data Parallelism - nn.DataParallel( ): 문제점 - (1) 멀티쓰레드 모듈이기 때문에 python에서 비효율적임 (GIL 참고) ——> 멀티 쓰레드의 문제 - (2) GPU1에서 업데이트된 모델을 매 스텝마다 모든 device로 replicate 해야 함. - (3) 메모리 불균형이 일어나서 GPU를 100% 활용할 수 없음. https://medium.com/daangn/pytorch-multi-gpu-학습-제대로-하기-27270617836b Parallelism: Theory and Practice 74
  • 75. Data Parallelism - nn.DataParallel( ): Memory Imbalance - 메모리 불균형이 일어나는 이유는 Loss 함수가 Parallel 하지 않기 때문. - Loss 함수가 Parallel하지 않기 때문에 GPU 1개로 모든 Output을 모아서 Loss를 계산함 - => Parallel Loss 함수를 구현해서 Output을 모으지 않고 각 device에서 계산하면 됨. https://medium.com/daangn/pytorch-multi-gpu-학습-제대로-하기-27270617836b Parallelism: Theory and Practice 75
  • 76. Data Parallelism - nn.DataParallel( ): Memory Imbalance https://medium.com/daangn/pytorch-multi-gpu-학습-제대로-하기-27270617836b Parallelism: Theory and Practice 76 1. Scatter Labels 2. Parallel Loss Computation
  • 77. Data Parallelism - nn.DataParallel( ): Memory Imbalance https://medium.com/daangn/pytorch-multi-gpu-학습-제대로-하기-27270617836b Parallelism: Theory and Practice 77 from torch.nn.parallel.data_parallel import DataParallel class DataParallelCriterion(DataParallel): def forward(self, inputs, *targets, **kwargs): targets, kwargs = self.scatter(targets, kwargs, self.device_ids) # 라벨을 각 device들로 Scatter함. replicas = self.replicate(self.module, self.device_ids) # self.module(loss함수)을 device들에 복제함. outputs = _criterion_parallel_apply(replicas, inputs, targets, kwargs) # 병렬 criterion을 이용해 각 device의 loss를 계산 return Reduce.apply(*outputs) / len(outputs), targets # 계산한 outputs을 Reduce하여 Backward 연산을 할 수 있도록 함.
  • 78. Data Parallelism - nn.DataParallel( ): Memory Imbalance https://medium.com/daangn/pytorch-multi-gpu-학습-제대로-하기-27270617836b Parallelism: Theory and Practice 78 import torch import torch.nn as nn from parallel import DataParallelModel, DataParallelCriterion model = BERT(args) model = DataParallelModel(model) model.cuda() ... criterion = nn.NLLLoss() criterion = DataParallelCriterion(criterion) for i, (inputs, labels) in enumerate(trainloader): outputs = model(inputs) loss = criterion(outputs, labels) optimizer.zero_grad() loss.backward() optimizer.step() 커스텀 ParallelCriterion 사용 커스텀 ParallelCriterion을 사용하면 nn.DataParallel( )이 아니라 nn.DataParallelModel( )을 사용해야 함. nn.DataParallel( )은 기본적으로 Outputs을 Gather하게 구현 됨.
  • 79. Data Parallelism - nn.DataParallel( ): Memory Imbalance https://medium.com/daangn/pytorch-multi-gpu-학습-제대로-하기-27270617836b Parallelism: Theory and Practice 79 GPU 사용량이 감소했음.
  • 80. Data Parallelism - nn.DataParallel( ): 문제점 - (1) 멀티쓰레드 모듈이기 때문에 python에서 비효율적임 (GIL 참고) ——> 멀티 쓰레드의 문제 - (2) GPU1에서 업데이트된 모델을 매 스텝마다 모든 device로 replicate 해야 함. - (3) 메모리 불균형이 일어나서 GPU를 100% 활용할 수 없음. Parallelism: Theory and Practice 80
  • 81. Data Parallelism - nn.DataParallel( ): 문제점 - (1) 멀티쓰레드 모듈이기 때문에 python에서 비효율적임 (GIL 참고) ——> 멀티 쓰레드의 문제 - (2) GPU1에서 업데이트된 모델을 매 스텝마다 모든 device로 replicate 해야 함. - (3) 메모리 불균형이 일어나서 GPU를 100% 활용할 수 없음. Parallelism: Theory and Practice 81
  • 82. Data Parallelism - nn.DataParallel( ): All-reduce - 하나의 GPU에서 파라미터를 업데이트하고 업데이트된 파라미터를 매 스텝마다 replicate 해야함. - 만약 Gradient를 Reduce 하지 않고 평균을 계산해서 모든 device로 전송할 수 있다면? ——> All-reduce - Gradient의 평균으로 각 device에서 파라미터를 업데이트 한다면 모델을 매번 replicate 하지 않아도 됨. Parallelism: Theory and Practice 82
  • 83. Data Parallelism - nn.DataParallel( ): All-reduce - 따라서 기존의 nn.DataParallel( )을 개선하려면 All-reduce를 사용해서 Gradient의 평균을 모든 device로 전송하면 됨. - 그러나 All-reduce는 상당히 비용이 높은 연산임. - All-reduce의 구현: - (1) Reduce ——> Broadcast Parallelism: Theory and Practice 83 - (1) Gradient를 Reduce하여 평균을 GPU1에 저장 - (2) 평균값을 다른 디바이스로 Broadcast 마스터 프로세스(GPU1)의 부하가 심해지며, 프로세스(GPU) 수가 증가할 때마다 통신비용이 매우 커짐.
  • 84. Data Parallelism - nn.DataParallel( ): All-reduce - 따라서 기존의 nn.DataParallel( )을 개선하려면 All-reduce를 사용해서 Gradient의 평균을 모든 device로 전송하면 됨. - 그러나 All-reduce는 상당히 비용이 높은 연산임. - All-reduce의 구현: - (2) All-to-All (Collective Communication 연산 중 하나) Parallelism: Theory and Practice 84 - (1) 모든 디바이스가 개별 통신을 하여 값을 전송함. - (2) n개의 장비가 있을 때, 약 n^2의 통신이 발생함. 마찬가지로 프로세스 수가 증가할 때마다 통신비용이 심하게 커진다.
  • 85. Data Parallelism - nn.DataParallel( ): All-reduce - 그러나 Baidu에서 Ring All-reduce라는 알고리즘을 제안. - Ring All-reduce를 이용하면 All-reduce를 매우 효과적으로 수행 할 수 있음. - All-reduce의 구현: - (3) Ring All-reduce Parallelism: Theory and Practice 85 GPU: 0 GPU: 3 GPU: 1 GPU: 2 g0 g2 g1 g3
  • 86. Data Parallelism - nn.DataParallel( ): All-reduce - 그러나 Baidu에서 Ring All-reduce라는 알고리즘을 제안. - Ring All-reduce를 이용하면 All-reduce를 매우 효과적으로 수행 할 수 있음. - All-reduce의 구현: - (3) Ring All-reduce Parallelism: Theory and Practice 86 GPU: 0 GPU: 3 GPU: 1 GPU: 2 g0 g1 g2 g3 g = g0 + g1 + g2 + g3를 계산해서 모든 GPU로 전송해야 함.
  • 87. Parallelism: Theory and Practice 87 GPU: 0 GPU: 3 GPU: 1 GPU: 2 g0 g2 g1 g3 g0 Data Parallelism - nn.DataParallel( ): All-reduce - 그러나 Baidu에서 Ring All-reduce라는 알고리즘을 제안. - Ring All-reduce를 이용하면 All-reduce를 매우 효과적으로 수행 할 수 있음. - All-reduce의 구현: - (3) Ring All-reduce
  • 88. Parallelism: Theory and Practice 88 GPU: 0 GPU: 3 GPU: 1 GPU: 2 g0 g2 g0 + g1 g3 g0 Data Parallelism - nn.DataParallel( ): All-reduce - 그러나 Baidu에서 Ring All-reduce라는 알고리즘을 제안. - Ring All-reduce를 이용하면 All-reduce를 매우 효과적으로 수행 할 수 있음. - All-reduce의 구현: - (3) Ring All-reduce
  • 89. Parallelism: Theory and Practice 89 GPU: 0 GPU: 3 GPU: 1 GPU: 2 g0 g2 g0 + g1 g3 g0 + g1 Data Parallelism - nn.DataParallel( ): All-reduce - 그러나 Baidu에서 Ring All-reduce라는 알고리즘을 제안. - Ring All-reduce를 이용하면 All-reduce를 매우 효과적으로 수행 할 수 있음. - All-reduce의 구현: - (3) Ring All-reduce
  • 90. Parallelism: Theory and Practice 90 GPU: 0 GPU: 3 GPU: 1 GPU: 2 g0 g0 + g1 + g2 g0 + g1 g3 g0 + g1 Data Parallelism - nn.DataParallel( ): All-reduce - 그러나 Baidu에서 Ring All-reduce라는 알고리즘을 제안. - Ring All-reduce를 이용하면 All-reduce를 매우 효과적으로 수행 할 수 있음. - All-reduce의 구현: - (3) Ring All-reduce
  • 91. Parallelism: Theory and Practice 91 GPU: 0 GPU: 3 GPU: 1 GPU: 2 g0 g0 + g1 + g2 g0 + g1 g3 g0 + g1 + g2 Data Parallelism - nn.DataParallel( ): All-reduce - 그러나 Baidu에서 Ring All-reduce라는 알고리즘을 제안. - Ring All-reduce를 이용하면 All-reduce를 매우 효과적으로 수행 할 수 있음. - All-reduce의 구현: - (3) Ring All-reduce
  • 92. Parallelism: Theory and Practice 92 GPU: 0 GPU: 3 GPU: 1 GPU: 2 g0 g0 + g1 + g2 g0 + g1 g0 + g1 + g2 + g3 g0 + g1 + g2 Data Parallelism - nn.DataParallel( ): All-reduce - 그러나 Baidu에서 Ring All-reduce라는 알고리즘을 제안. - Ring All-reduce를 이용하면 All-reduce를 매우 효과적으로 수행 할 수 있음. - All-reduce의 구현: - (3) Ring All-reduce
  • 93. Parallelism: Theory and Practice 93 GPU: 0 GPU: 3 GPU: 1 GPU: 2 g0 g0 + g1 + g2 g0 + g1 g = g0 + g1 + g2 + g3 Data Parallelism - nn.DataParallel( ): All-reduce - 그러나 Baidu에서 Ring All-reduce라는 알고리즘을 제안. - Ring All-reduce를 이용하면 All-reduce를 매우 효과적으로 수행 할 수 있음. - All-reduce의 구현: - (3) Ring All-reduce
  • 94. Parallelism: Theory and Practice 94 GPU: 0 GPU: 3 GPU: 1 GPU: 2 g0 g0 + g1 + g2 g0 + g1 g Data Parallelism - nn.DataParallel( ): All-reduce - 그러나 Baidu에서 Ring All-reduce라는 알고리즘을 제안. - Ring All-reduce를 이용하면 All-reduce를 매우 효과적으로 수행 할 수 있음. - All-reduce의 구현: - (3) Ring All-reduce
  • 95. Parallelism: Theory and Practice 95 GPU: 0 GPU: 3 GPU: 1 GPU: 2 g0 g0 + g1 + g2 g0 + g1 g g Data Parallelism - nn.DataParallel( ): All-reduce - 그러나 Baidu에서 Ring All-reduce라는 알고리즘을 제안. - Ring All-reduce를 이용하면 All-reduce를 매우 효과적으로 수행 할 수 있음. - All-reduce의 구현: - (3) Ring All-reduce
  • 96. Parallelism: Theory and Practice 96 GPU: 0 GPU: 3 GPU: 1 GPU: 2 g g0 + g1 + g2 g0 + g1 g g Data Parallelism - nn.DataParallel( ): All-reduce - 그러나 Baidu에서 Ring All-reduce라는 알고리즘을 제안. - Ring All-reduce를 이용하면 All-reduce를 매우 효과적으로 수행 할 수 있음. - All-reduce의 구현: - (3) Ring All-reduce
  • 97. Parallelism: Theory and Practice 97 GPU: 0 GPU: 3 GPU: 1 GPU: 2 g g0 + g1 + g2 g0 + g1 g g Data Parallelism - nn.DataParallel( ): All-reduce - 그러나 Baidu에서 Ring All-reduce라는 알고리즘을 제안. - Ring All-reduce를 이용하면 All-reduce를 매우 효과적으로 수행 할 수 있음. - All-reduce의 구현: - (3) Ring All-reduce
  • 98. Parallelism: Theory and Practice 98 GPU: 0 GPU: 3 GPU: 1 GPU: 2 g g0 + g1 + g2 g g g Data Parallelism - nn.DataParallel( ): All-reduce - 그러나 Baidu에서 Ring All-reduce라는 알고리즘을 제안. - Ring All-reduce를 이용하면 All-reduce를 매우 효과적으로 수행 할 수 있음. - All-reduce의 구현: - (3) Ring All-reduce
  • 99. Parallelism: Theory and Practice 99 GPU: 0 GPU: 3 GPU: 1 GPU: 2 g g0 + g1 + g2 g g g Data Parallelism - nn.DataParallel( ): All-reduce - 그러나 Baidu에서 Ring All-reduce라는 알고리즘을 제안. - Ring All-reduce를 이용하면 All-reduce를 매우 효과적으로 수행 할 수 있음. - All-reduce의 구현: - (3) Ring All-reduce
  • 100. Parallelism: Theory and Practice 100 GPU: 0 GPU: 3 GPU: 1 GPU: 2 g g g g g Data Parallelism - nn.DataParallel( ): All-reduce - 그러나 Baidu에서 Ring All-reduce라는 알고리즘을 제안. - Ring All-reduce를 이용하면 All-reduce를 매우 효과적으로 수행 할 수 있음. - All-reduce의 구현: - (3) Ring All-reduce
  • 101. Parallelism: Theory and Practice 101 GPU: 0 GPU: 3 GPU: 1 GPU: 2 g g g g Weight Update Data Parallelism - nn.DataParallel( ): All-reduce - 그러나 Baidu에서 Ring All-reduce라는 알고리즘을 제안. - Ring All-reduce를 이용하면 All-reduce를 매우 효과적으로 수행 할 수 있음. - All-reduce의 구현: - (3) Ring All-reduce
  • 102. w ← w - α · g w ← w - α · g w ← w - α · g Parallelism: Theory and Practice 102 GPU: 0 GPU: 3 GPU: 1 GPU: 2 w ← w - α · g Weight Update Data Parallelism - nn.DataParallel( ): All-reduce - 그러나 Baidu에서 Ring All-reduce라는 알고리즘을 제안. - Ring All-reduce를 이용하면 All-reduce를 매우 효과적으로 수행 할 수 있음. - All-reduce의 구현: - (3) Ring All-reduce
  • 103. Parallelism: Theory and Practice 103 w ← w - α · g GPU: 0 GPU: 3 GPU: 1 GPU: 2 Weight Update w ← w - α · g w ← w - α · g w ← w - α · g - (1) 마스터 프로세스를 사용하지 않기 때문에 특정 device로 부하가 쏠리지 않음. - (2) All-to-All 처럼 비효율적인 연산을 수행하지 않음. - (3) 효율적인 방식으로 모든 device의 파라미터를 동시에 업데이트하기 때문에 파라 미터를 매번 replicate 하지 않아도 됨. Data Parallelism - nn.DataParallel( ): All-reduce - 그러나 Baidu에서 Ring All-reduce라는 알고리즘을 제안. - Ring All-reduce를 이용하면 All-reduce를 매우 효과적으로 수행 할 수 있음. - All-reduce의 구현: - (3) Ring All-reduce
  • 104. Data Parallelism - Horovod - Ring All-reduce를 사용, Uber에서 개발한 Distributed Deep Learning Library. - Tensorflow, Pytorch, MXNet, Keras 등 다양한 백엔드 지원. - single/multi-node & multi-gpu 모델을 학습하기 위한 멀티프로세싱 모듈. Parallelism: Theory and Practice 104
  • 105. Data Parallelism - Horovod - All-reduce를 사용하면 마스터 프로세스 개념이 없어지기 때문에 학습 과정이 매우 심플해짐. Parallelism: Theory and Practice 105 2. Forward 수행 3. Backward 수행 4. Gradient All-reduce 5. 파라미터 업데이트 1. 데이터 Scatter
  • 106. Data Parallelism - Horovod: Parameter Server - All-reduce가 도입되기 이전의 multi-node distributed training은 주로 Parameter Server를 통해 이루어졌음. - Parameter Server는 nn.DP에서 Gradient를 Reduce 받는 마스터 프로세스와 비슷한 역할을 하는 서버임. - 노드의 개수가 많아지면, Parameter Server 한대로는 감당이 안되기 때문에 여러대의 서버를 사용하기도 하였음. Parallelism: Theory and Practice 106
  • 107. Data Parallelism - Horovod: Parameter Server 문제점 - (1) 몇대의 워커 노드와 몇대의 파라미터 서버를 쓰는지에 따라 속도 차이가 생기는데 이것을 configure하기 어려움. Parallelism: Theory and Practice 107 워커 노드 파라미터 서버
  • 108. Data Parallelism - Horovod: Parameter Server 문제점 - (2) 또한 Communication이 느리고 Worker가 줄어들기 때문에 Ideal한 속도에 비해 한참 못 미치는 속도를 보여줌. Parallelism: Theory and Practice 108
  • 109. Data Parallelism - Horovod - Horovod는 Ring All-reduce를 사용해서 문제를 해결하였음. - Parameter Server 없이 모든 노드를 Worker로 사용하여 성능을 개선했음. Parallelism: Theory and Practice 109
  • 110. Data Parallelism - Horovod - Horovod는 Ring All-reduce를 사용해서 문제를 해결하였음. - Parameter Server 없이 모든 노드를 Worker로 사용하여 성능을 개선했음. Parallelism: Theory and Practice 110
  • 111. Data Parallelism - Horovod: Tensor Fusion - 또한 Horovod는 Tensor Fusion이라는 기술을 통해 성능을 더 개선했음. (65%↑) - 전송하는 데이터의 크기가 작은 경우, All-reduce 연산시에 오버헤드가 매우 많이 발생해서 성능이 떨어졌다고 함. - 그래서 일정한 사이즈의 버퍼를 만들어놓고 텐서를 저장하다가, 버퍼가 가능 차면 전송하는 방식을 채택함. - 이후에 말할 DDP의 Gradient Bucketing과 비슷한 메커니즘. 이후에 더 자세히 설명함. Parallelism: Theory and Practice 111
  • 112. Data Parallelism - Horovod: RDMA - RDMA는 Remote device의 memory에 직접 access하여 값을 쓰거나 읽는 방식. - TCP 통신에 비해 RDMA가 속도가 더 빨랐다고 함. Parallelism: Theory and Practice 112
  • 113. Data Parallelism - Horovod: Codes - (1) 먼저 Open MPI 설치 - https://www.open-mpi.org/software/ompi/v4.0/ 다운로드 후 압축 해제 - (2) 그리고나서 NCCL 설치 - https://docs.nvidia.com/deeplearning/sdk/nccl-install-guide/index.html - (3) 마지막으로 Horovod를 설치 Parallelism: Theory and Practice 113 $ cd openmpi-VERSION $ ./configure —-prefix=/usr/local $ make all install $ HOROVOD_GPU_ALLREDUCE=NCCL pip install horovod
  • 114. Data Parallelism - Horovod: Codes - Horovod 코드 작성 Parallelism: Theory and Practice 114 import torch import horovod.torch as hvd from torch.utils.data.distributed import DistributedSampler from torch.utils.data import DataLoader hvd.init() # horovod initialization 수행 torch.cuda.set_devices(hvd.local_rank()) # Local rank로서 사용할 GPU 고정 train_dataset = ... # 데이터셋 정의 train_sampler = DistributedSampler( train_dataset, num_replicas=hvd.size(), # replication할 device 개수 rank=hvd.rank(), ) # sampler 생성 train_loader = DataLoader( train_dataset, batch_size=..., sampler=train_sampler, ) # 데이터로더 생성
  • 115. Parallelism: Theory and Practice 115 model = BERT(args) model.cuda() # 모델 생성 optimizer = torch.optim.SGD(model.parameters()) optimizer = hvd.DistributedOptimizer( optimizer, named_parameters=model.named_parameters(), ) # 옵티마이저를 DistributedOptimizer로 만들어줘야 함. Data Parallelism - Horovod: Codes - Horovod 코드 작성 hvd.broadcast_parameters( model.state_dict(), root_rank=0 ) # all-reduce 기반의 프레임워크들은 최초 1회만 모델을 Broadcast. for epoch in range(100): for idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() output = model(data) loss = torch.nn.functional.nll_loss(output, target) loss.backward() optimizer.step() # 학습 수행
  • 116. Parallelism: Theory and Practice 116 Data Parallelism - Horovod: Codes - np: number of process (world size) - H: hosted servers + “:n_gpu” $ horovodrun —np=8 -H XXX.XXX.XXX.XXX:4, YYY.YYY.YYY.YYY:4 python train.py
  • 117. Parallelism: Theory and Practice 117 Data Parallelism - Horovod: Codes - torch-lightning을 사용하면 매우 쉽게 사용 가능. $ horovodrun -np=8 -H XXX.XXX.XXX.XXX:4, YYY.YYY.YYY.YYY:4 python train.py from pytorch_lightining import Trainer lightning_model = ... trainer = Trainer( args, accelerator=‘horovod’, # <—— 여기 한줄만 바꾸면 됨. ) Trainer.fit( lightning_model, train_loader, val_loader, )
  • 118. Parallelism: Theory and Practice 118 Data Parallelism - nn.parallel.DistributedDataParallel( ) - Pytorch로 구현된 All-reduce distributed training 모듈. - single/multi-node & multi-gpu에서 모델을 학습하기 위한 멀티 프로세싱 모듈.
  • 119. Parallelism: Theory and Practice 119 Data Parallelism - nn.parallel.DistributedDataParallel( ) - backward( )와 step( ) 중에서 언제 All-reduce를 실행하는게 좋은지 실험. 2. Forward 수행 3. Backward 수행 4. Gradient All-reduce 5. 파라미터 업데이트 1. 데이터 Scatter import torch import torch.nn as nn import torch.optim as optim net = nn.Linear(10, 10) opt = optim.SGD(net.parameters()) input, target = ... out = net(input) loss = nn.MSELoss(out, target) loss.backward() opt.step() Which one is better?
  • 120. Data Parallelism - nn.parallel.DistributedDataParallel( ) - 결과적으로 backward( )에서 수행하는 것이 훨씬 효율적임. - 분석 결과 backward( )가 훨씬 무거운 연산임. - 따라서 Computation과 Communication을 더 많이 Overlap 시킬 수 있어서 효율적. Parallelism: Theory and Practice 120 Backward의 Computation이 훨씬 큼 Backward( ) Step( )
  • 121. Data Parallelism - nn.parallel.DistributedDataParallel( ) - backward( ) 연산을 수행하면서 중간중간 나온 Gradient를 계속 All-reduce 하는 것임. - backward( ) 연산을 수행하는 동시에 All-reduce 하는 것이 기다렸다가 시작하는 것 보다 효율적. Parallelism: Theory and Practice 121 step( ) 때 실행 (Overlap을 하지 않은 경우) backward( ) 도중에 실행 (Overlap을 한 경우)
  • 122. Data Parallelism - nn.parallel.DistributedDataParallel( ) - Q1: backward( ) 연산 중에 Gradient가 다 계산되지 않았는데 어떻게 All-reduce를 수행합니까? - A1: backward( )는 뒤쪽 Layer부터 순차적으로 이루어지기 때문에 계산이 끝난 것을 먼저 전송하면 됩니다. - Q2: 그렇다면 언제마다 All-reduce가 수행되나요? 기준이 있나요? - A2: Gradient Bucketing을 수행합니다. Bucket이 가득차면 그 때 All-reduce를 수행합니다. Parallelism: Theory and Practice 122
  • 123. Data Parallelism - nn.parallel.DistributedDataParallel( ): Gradient Bucketing - Horovod의 Tensor Fusion과 유사한 방식, backward( ) 연산 도중에 뒤쪽 부터 계산된 Gradient를 버킷에 저장. - 버킷의 용량이 가득차게 되면 All-reduce를 수행해서 각 device에 Gradient의 평균을 전달함. - 그림 때문에 헷갈릴 수도 있는데, 버킷에 저장되는 것은 모델의 파라미터가 아닌, 해당 레이어에서 나온 Gradient임. - 모든 Bucket은 일정한 size를 가지고 있으며 `bucket_size_mb`라는 인자를 통해 버킷 사이즈를 변경 가능. (Mega byte level) Parallelism: Theory and Practice 123 Backward 가장 뒤쪽 레이어의 Gradient를 가장 먼저 All-reduce로 평균을 계산하여 교환함 2개 이상의 Layer에서 출력된 Gradient가 1개의 Bucket에 들어갈 수도 있음. Gradient와 버킷의 크기에 따라 다름. Bucket1에 해당하는 Layer가 Backward를 수행할 땐, Bucket2, 3은 All-reduce를 수행하고 있을 수 있음.
  • 124. Data Parallelism - nn.parallel.DistributedDataParallel( ): Codes - 프로세스 그룹 초기화 및 학습 코드 작성 Parallelism: Theory and Practice 124 def worker(rank, ngpus_per_node, args): torch.cuda.set_device(rank) # 현재 프로세스에서 사용중인 디바이스 등록 dist.init_process_group( backend='nccl', init_method='tcp://127.0.0.1:FREEPORT', world_size=args.world_size, rank=rank ) # 프로세스 그룹 초기화 model = Bert(args) model.cuda(rank) model = DistributedDataParallel(model, device_ids=[args.gpus]) # model = DistributedDataParallel(model, device_ids=[args.gpus], bucket_size_mb=???) # DistributedDataParallel으로 모델 wrapping for i in range(args.num_epochs): ... 학습 루프 ...
  • 125. Data Parallelism - nn.parallel.DistributedDataParallel( ): Codes - DDP 학습 실행코드 작성. Parallelism: Theory and Practice 125 import torch.distributed as dist import torch.multiprocessing as mp from torch.nn.parallel import DistributedDataParallel def main(): args = parser.parse_args() ngpus_per_node = torch.cuda.device_count() mp.spawn( worker, nprocs=ngpus_per_node, args=(ngpus_per_node, args), join=True ) # 멀티프로세싱 spawn 시작 if __name__ == “__main__”: main() python -m torch.distributed.launch —-nproc_per_node=4 main.py —-world_size 2 —-gpus 0 1 2 3 —-num_epochs 10 --batch_size 60 학습 시작
  • 126. Data Parallelism - nn.parallel.DistributedDataParallel( ): Codes - torch-lightning을 사용하면 매우 쉽게 사용 가능. Parallelism: Theory and Practice 126 from pytorch_lightining import Trainer lightning_model = ... trainer = Trainer( args, accelerator=‘ddp’, # <—— 여기 한줄만 바꾸면 됨. ) Trainer.fit( lightning_model, train_loader, val_loader, )
  • 128. Model Parallelism - Inter-layer model parallelism - 아까 그림에서 봤던 것 처럼 Layer-wise로 모델을 병렬화 하는 방식. - n번째 layer를 forward 하기 위해서는 반드시 n-1 번째 layer를 forward 해야 함. - 따라서 주로 GPipe나 Pipedream과 같은 Pipeline parallelism 도구를 함께 사용함. Parallelism: Theory and Practice 128
  • 129. Model Parallelism - Intra-layer model parallelism - 모델을 Layer-wise로 쪼개는 것이 아니라 Column 혹은 Row 방향으로 쪼개서 병렬화 하는 방식. - 대표적으로 Mesh-tensorflow나 Megatron-LM이 이러한 방식을 사용하고 있음. Parallelism: Theory and Practice 129 디바이스 1 디바이스 2
  • 130. Model Parallelism - Mesh-tensorflow - Google에서 개발한 오픈소스 모델/데이터 병렬처리 도구. - Tensorflow와 연동되며 TF Graph와 Operation을 만들어 줌. - All-reduce 기반의 Data Parallelism + Intra-layer model parallelism 지원 - Tensorflow 2.X 지원하지 않음. 1.X 인터페이스 사용 (ㅎㅎㅎ...) Parallelism: Theory and Practice 130
  • 131. Model Parallelism - Mesh-tensorflow - Mesh: 프로세서들이 포함될 수 있는 가상의 n-차원 배열 - Mesh-shape: Mesh 배열의 shape, 사용자가 원하는대로 병렬화 가능. - 예를 들면 32개의 TPU core가 있을 때, (4 x 4 x 2)와 같은 mesh-shape으로 병렬화 가능. - Mesh-shape은 가상의 shape임. 실제 device topology와는 상관 없음. - Layout Rules: 각각의 mesh-dimension에 원하는 대상을 부여하는 것. - 예를 들면 (4:batch, 4:hidden, 2:embd)와 같이 부여 할 수 있음. - 4:batch는 All-reduce 기반의 Data Parallelism 수행 - 4:hidden과 2:embd는 Intra-layer model parallelism 수행 Parallelism: Theory and Practice 131 Hidden Embd Batch
  • 132. Model Parallelism - Mesh-tensorflow - Example: (4:batch x 4:hidden x 2:embd) Parallelism: Theory and Practice 132 데이터 배치 데이터 배치 데이터 배치 데이터 배치 Batch Embd Hidden
  • 133. Model Parallelism - Mesh-tensorflow - Example: (4:batch x 4:hidden x 2:embd) Parallelism: Theory and Practice 133 Batch Embd Hidden
  • 134. Model Parallelism - Mesh-tensorflow - Example: (4:batch x 4:hidden x 2:embd) Parallelism: Theory and Practice 134 Hidden Embd Batch
  • 135. Model Parallelism - Mesh-tensorflow: Codes Parallelism: Theory and Practice 135 w1 = mtf.get_variable( mesh, “w1”, [rows_dim, cols_dim, hidden_dim] ) w2 = mtf.get_variable( mesh, “w2”, [hidden_dim, classes_dim] ) # 가중치 생성 hidden = mtf.einsum( images, w1, output_shape=[batch_dim, hidden_dim] ) hidden = mtf.relu(hidden) logits = mtf.einsum( hidden, W2, output_shape=[batch_dim, classes_dim] ) # forward 수행 import mesh_tensorflow as mtf graph = mtf.Graph() mesh = mtf.Mesh(graph, “my_mesh”) # graph와 mesh 생성 batch_dim = mtf.Dimension(“batch”, 100) rows_dim = mtf.Dimension(“rows”, 28) cols_dim = mtf.Dimension(“cols”, 28) # 인풋에 관련된 constants hidden_dim = mtf.Dimension(“hidden”, 1024) classes_dim = mtf.Dimension(“classes”, 10) # 모델에 관련된 constants images = mtf.import_tf_tensor( mesh, mnist_images, shape=[batch_dims, rows_dim, cols_dim] ) # 이미지 텐서 입력 Labels = mtf.import_tf_tensor( mesh, mnist_labels, shape=[batch_dim] ) # 라벨 텐서 입력
  • 136. Model Parallelism - Mesh-tensorflow: Codes Parallelism: Theory and Practice 136 output_label = mtf.one_hot( labels, classes_dim ) # one-hot label 생성 loss = mtf.layers.softmax_cross_entropy_with_logits( logits, onehot_labels, classes_dim ) loss = mtf.reduce_mean(loss) # loss 계산 w1_grad, w2_grad = mtf.gradients( [loss], [w1, w2], ) # gradient 계산 update_w1 = mtf.assign(w1, w1 - w1_grad * 0.001) update_w2 = mtf.assign(w2, w2 - w2_grad * 0.001) # 가중치 업데이트 연산 생성 devices = [“gpu:0”, “gpu:1”, “gpu:2”, “gpu:3”] # devices 정의 mesh_shape = [("all", 4)] layout_rules = [("batch", "all")] # mesh-shape, layout_rules 정의 mesh_impl = mtf.placement_mesh_impl.PlacementMeshImpl( mesh_shape, layout_rules, devices ) lowering = mtf.Lowering( graph, {mesh: mesh_impl} ) # mesh-tf -> tf Lowering 객체 생성 tf_update_ops = [ lowering.lowered_operation(update_w1), lowering.lowered_operation(update_w2) ] # tensorflow 연산객체 획득
  • 137. Model Parallelism - Mesh-tensorflow: Codes Parallelism: Theory and Practice 137 mesh_shape = [ ("x", 4), ("y", 4) ("z", 2) ] layout_rules = [ ("batch", "X"), ("hidden", "y"), ("embd", "y"), ] # user-defined rules layout_rules = mtf.auto_mtf.layout( graph, mesh_shape, outputs ) # auto-searched rules GPT-NEO 2.7B Configs
  • 138. Model Parallelism - Megatron-LM - Nvidia에서 개발한 Large-scale parallel transformer LM. - Pytorch로 작성, Intra-layer model parallelism 지원. - Transformer 각 부분에 대한 병렬화 전략에 대해서 이야기 함. Parallelism: Theory and Practice 138
  • 139. Model Parallelism - Megatron-LM: Row & Column Parallel Linear Layer - FFN Weight: [D, D] (e.g. 512 x 512)가 있을 때, 두가지 방식으로 병렬화 가능. - Row Parallel Linear: [D/2 x D] (e.g. 256 x 512) - 입력(T x D)이 들어오면 scatter 하고 내적 후에 reduce 수행 (addition) - X (T x D/2) ・ A (D/2 x D) = Y_list [(T x D), (T x D)]= Y_1 (T x D) + Y_2 (T x D) = Y (T x D) - Column Parallel Linear: [D x D/2] (e.g. 512 x 256) - 입력(T x D)이 들어오면 replicate 하고 내적 후에 gather 수행 (concatenation) - X (T x D) ・ A (D x D/2) = Y_list [(T x D/2), (T x D/2)] = Y_1 (T x D/2) ◎ Y_2 (T x D/2) = Y (T x D) Parallelism: Theory and Practice 139
  • 140. Row-wise Model Parallelism - Megatron-LM: Row & Column Parallel Linear Layer - FFN Weight: [D, D] (e.g. 512 x 512)가 있을 때, 두가지 방식으로 병렬화 가능. - Row Parallel Linear: [D/2 x D] (e.g. 256 x 512) - 입력(T x D)이 들어오면 scatter 하고 내적 후에 reduce 수행 (addition) - X (T x D/2) ・ A (D/2 x D) = Y_list [(T x D), (T x D)]= Y_1 (T x D) + Y_2 (T x D) = Y (T x D) Parallelism: Theory and Practice 140 Row-wise
  • 141. Column-wise Parallelism: Theory and Practice 141 Model Parallelism - Megatron-LM: Row & Column Parallel Linear Layer - FFN Weight: [D, D] (e.g. 512 x 512)가 있을 때, 두가지 방식으로 병렬화 가능. - Column Parallel Linear: [D x D/2] (e.g. 512 x 256) - 입력(T x D)이 들어오면 replicate 하고 내적 후에 gather 수행 (concatenation) - X (T x D) ・ A (D x D/2) = Y_list [(T x D/2), (T x D/2)] = Y_1 (T x D/2) ◎ Y_2 (T x D/2) = Y (T x D)
  • 142. Model Parallelism - Megatron-LM: Row & Column Parallel Linear Layer - FFN Weight: [D, D] (e.g. 512 x 512)가 있을 때, 두가지 방식으로 병렬화 가능. - Row Parallel Linear: [D/n x D] - 입력(T x D)이 들어오면 scatter 하고 내적 후에 reduce 수행 (addition) - X (T x D/2) ・ A (D/n x D) = Y_list [(T x D), ... , (T x D)]= Y_1 (T x D) + ... + Y_n (T x D) = Y (T x D) - Column Parallel Linear: [D x D/n] - 입력(T x D)이 들어오면 replicate 하고 내적 후에 gather 수행 (concatenation) - X (T x D) ・ A (D x D/n) = Y_list [(T x D/n), ..., (T x D/n)] = Y_1 (T x D/n) ◎ ... ◎ Y_n (T x D/n) = Y (T x D) Parallelism: Theory and Practice 142 n개로 병렬화 가능
  • 143. Model Parallelism - Megatron-LM: h ⇒ 4h로 가는 mlp layer는 column-wise로 병렬화 - GeLU 영역에서 Synchronization point를 만들지 않기 위함임. Parallelism: Theory and Practice 143
  • 144. Model Parallelism - Megatron-LM: h ⇒ 4h로 가는 mlp layer는 column-wise로 병렬화 - GeLU 영역에서 Synchronization point를 만들지 않기 위함임. - Row-wise로 연산하면 반드시 GeLU 영역에서 All-reduce를 해야 함. Parallelism: Theory and Practice 144 class RowParallelLinear(torch.nn.Module): def __init__(self): super(RowParallelLinear, self).__init__() chunked = torch.chunk(w, 2, dim=0) self.a1 = chunked[0] # [3, 6] self.a2 = chunked[1] # [3, 6] def forward(self, x): # Parallel O: GeLU(X1A1) + GeLU(X2A2) # 각 device에서 GeLU를 따로 연산 # Parallel X: GeLU(X1A1 + X2A2) # 값을 더해서 병렬화 안한 상태서 GeLU 연산 # 계산해보면 두 값이 다르기 때문에, # 두 device에 X1A1 + X2A2의 값이 있어야 함. x1, x2 = torch.chunk(x, 2, dim=1) y1 = gelu(x1 @ self.a1) + gelu(x2 @ self.a2) y2 = gelu(x1 @ self.a1 + x2 @ self.a2) return torch.all(y1 == y2) # False 병렬화: GeLU(XA1) + GeLU(XA2) 동기화: GeLU(XA1 + XA2) 연산 결과가 동일해야 Stability를 보장 가능. RowParallelLinear는 GeLU 영역을 병렬화, 동기화시의 값이 다름. 따라서 RowParallelLinear를 사용하려면 All-reduce 해서 두개의 device가 동일하게 X1A1 + X2A2의 값을 가져야 함. => Communication cost 발생!
  • 145. Model Parallelism - Megatron-LM: h ⇒ 4h로 가는 mlp layer는 column-wise로 병렬화 - GeLU 영역에서 Synchronization point를 만들지 않기 위함임. - Row-wise로 연산하면 반드시 GeLU 영역에서 All-reduce를 해야 함. Parallelism: Theory and Practice 145 All-reduce 연산 필요. Communication 발생 병렬화: GeLU(XA1) + GeLU(XA2) 동기화: GeLU(XA1 + XA2) 연산 결과가 동일해야 Stability를 보장 가능. RowParallelLinear는 GeLU 영역을 병렬화, 동기화시의 값이 다름. 따라서 RowParallelLinear를 사용하려면 All-reduce 해서 두개의 device가 동일하게 X1A1 + X2A2의 값을 가져야 함. => Communication cost 발생!
  • 146. Model Parallelism - Megatron-LM: h ⇒ 4h로 가는 mlp layer는 column-wise로 병렬화 - GeLU 영역에서 Synchronization point를 만들지 않기 위함임. - Column-wise로 연산하면 계산결과가 동일하여 통신없이 수행 가능. Parallelism: Theory and Practice 146 병렬화: GeLU(XA1) cat GeLU(XA2) 동기화: GeLU(XA1 cat XA2) 연산 결과가 동일해야 Stability를 보장 가능. ColumnParallelLinear는 GeLU 영역을 병렬화, 동기화시의 값이 동일함. 따라서 ColumnParallelLinear를 사용하면 Communication 없이 연산 수행이 가능함 class ColumnParallelLinear(torch.nn.Module): def __init__(self): super(ColumnParallelLinear, self).__init__() chunked = torch.chunk(w, 2, dim=1) self.a1 = chunked[0] # [6, 3] self.a2 = chunked[1] # [6, 3] def forward(self, x): # 어떻게 연산하던 값이 동일하기 때문에 Column-wise가 타당함. # GeLU(X1A1 cat X2A2) == GeLU(X1A1) cat GeLU(X2A2) y1 = torch.cat([gelu(x @ self.a1), gelu(x @ self.a2)], dim=1) y2 = gelu(torch.cat([(x @ self.a1), (x @ self.a2)], dim=1)) return torch.all(y1 == y2) # True
  • 147. Model Parallelism - Megatron-LM: 4h ⇒ h로 가는 mlp layer는 row-wise로 병렬화 - 이는 이전 Layer의 Output을 Concat 하는데에 들어가는 비용을 줄이기 위함임. - GeLU(XA1)과 GeLU(XA2)를 Concat 하려면 All-Gather 연산을 해야해서 비효율적임. Parallelism: Theory and Practice 147
  • 148. Column-wise Model Parallelism - Megatron-LM: 4h ⇒ h로 가는 mlp layer는 row-wise로 병렬화 - 이는 이전 Layer의 Output을 Concat 하는데에 들어가는 비용을 줄이기 위함임. - GeLU(XA1)과 GeLU(XA2)를 Concat 하려면 All-Gather 연산을 해야해서 비효율적임. Parallelism: Theory and Practice 148 Column-wise All-Gather 연산 필요. Communication 발생. 출력: D/2 병합: D 입력: D
  • 149. Model Parallelism - Megatron-LM: 4h ⇒ h로 가는 mlp layer는 row-wise로 병렬화 - 이는 이전 Layer의 Output을 Concat 하는데에 들어가는 비용을 줄이기 위함임. - GeLU(XA1)과 GeLU(XA2)를 Concat 하려면 All-Gather 연산을 해야해서 비효율적임. Parallelism: Theory and Practice 149 Row-wise Column-wise Row-wise 사용시 어차피 다시 Scatter를 해야 함. 출력: D/2 입력: D/2 (Scatter 필요) 병합: D All-Gather 연산 필요. Communication 발생.
  • 150. Model Parallelism - Megatron-LM: 4h ⇒ h로 가는 mlp layer는 row-wise로 병렬화 - 이는 이전 Layer의 Output을 Concat 하는데에 들어가는 비용을 줄이기 위함임. - GeLU(XA1)과 GeLU(XA2)를 Concat 하려면 All-Gather 연산을 해야해서 비효율적임. Parallelism: Theory and Practice 150 Row-wise Column-wise 그냥 안 합치고 바로 감. 이 방법이 제일 효율적임. All-Gather 필요 없음. Communication 없음. 출력: D/2 입력: D/2
  • 151. Row-wise Column-wise 다음 layer로 넘길 때 All-reduce 수행 Forward Pass Model Parallelism - Megatron-LM: 따라서 단 2번 (Forward, Backward)의 All-reduce만으로 FFN 구현 가능. - Forward, Backward 때 반드시 합쳐야 하는 부분에서만 All-reduce 연산이 일어남. Parallelism: Theory and Practice 151
  • 152. Parallelism: Theory and Practice 152 Row-wise Column-wise 이전 layer로 넘길 때 All-reduce 수행 Backward Pass Model Parallelism - Megatron-LM: 따라서 단 2번 (Forward, Backward)의 All-reduce만으로 FFN 구현 가능. - Forward, Backward 때 반드시 합쳐야 하는 부분에서만 All-reduce 연산이 일어남.
  • 153. Parallelism: Theory and Practice 153 Model Parallelism - Megatron-LM: 따라서 단 2번 (Forward, Backward)의 All-reduce만으로 FFN 구현 가능. - Forward, Backward 때 반드시 합쳐야 하는 부분에서만 All-reduce 연산이 일어남. Forward 때는 여기서 All-reduce. Backward 때는 여기서 All-reduce.
  • 154. Parallelism: Theory and Practice 154 Model Parallelism - Megatron-LM: Attention도 Column ⇒ Row로 병렬화해서 최소의 통신만 수행. - 마찬가지로 Column ⇒ Row로 병렬화하면 동기화 없이 수행할 수 있음. - 따라서 Forward, Backward 때 반드시 합쳐야 하는 부분에서만 All-reduce가 일어남. Column-wise 통신 (Gather) 없이 쭉 가려면 앞쪽에서는 Column-wise, 뒤쪽에서는 Row-wise를 써줘야 함. Row-wise
  • 155. Parallelism: Theory and Practice 155 Model Parallelism - Megatron-LM: Attention도 Column ⇒ Row로 병렬화해서 최소의 통신만 수행. - 마찬가지로 Column ⇒ Row로 병렬화하면 동기화 없이 수행할 수 있음. - 따라서 Forward, Backward 때 반드시 합쳐야 하는 부분에서만 All-reduce가 일어남. Forward 때는 여기서 All-reduce. Backward 때는 여기서 All-reduce.
  • 156. Parallelism: Theory and Practice 156 Model Parallelism - Megatron-LM: LayerNorm과 Dropout은 병렬화 하지 않음. - 이들의 연산 Cost나 파라미터의 크기는 별로 크지 않음. - 모든 Device에 별도의 Dropout과 LayerNorm Layer가 있음. ⇒ 여기에선 All-reduce가 일어나지 않음. No All-Reduce !
  • 157. Parallelism: Theory and Practice 157 Model Parallelism - Megatron-LM: Decoding을 위한 Embedding Layer와 CrossEntropy Layer를 Fuse 했음. - Representation을 Embedding Matrix에 곱한 뒤 나오는 Logit의 사이즈는 [bsz, seq_len, vocab_size] - vocab_size는 보통 수만개 단위이기 때문에 All-gather 후 Loss를 구하는 것은 비용이 큼. - 따라서 Logit을 All-gather 하지 않고 Loss까지 계산이 모두 끝나고나서 All-reduce 하여 Backprop 수행. 방법 1) All-gather 방식 - Vocab_size: 50000 - n개의 Device에 [bsz, seq_len, 50000 / n]의 Logit이 존재. - 모든 Logit을 All-gather 해서 concat ⇒ [bsz, seq_len, 50000] - 병합된 Logit으로 부터 Loss 계산 후 Backprop 수행. ⇒ Communication Cost가 매우 크다.
  • 158. 방법 2) Masking 방식 (채택) - Vocab_size: 50000 - n개의 Device에 [bsz, seq_len, 50000 / n]의 Logit이 존재. - Partitioning 된 Vocab의 범위에 해당이 안되면 Masking 처리. - Loss 계산 후 All-reduce로 Loss의 평균을 내서 Backprop 수행. ⇒ Communication Cost가 적긴한데, 이게 된다고...? (의문) Parallelism: Theory and Practice 158 Model Parallelism - Megatron-LM: Decoding을 위한 Embedding Layer와 CrossEntropy Layer를 Fuse 했음. - Representation을 Embedding Matrix에 곱한 뒤 나오는 Logit의 사이즈는 [bsz, seq_len, vocab_size] - vocab_size는 보통 수만개 단위이기 때문에 All-gather 후 Loss를 구하는 것은 비용이 큼. - 따라서 Logit을 All-gather 하지 않고 Loss까지 계산이 모두 끝나고나서 All-reduce 하여 Backprop 수행.
  • 159. Parallelism: Theory and Practice 159 Model Parallelism - Megatron-LM: (당시 기준) WikiText와 Lambada 태스크 등에서 SoTA를 달성. - 학습속도가 매우 빨랐으며 Intra-layer model parallelism을 해도 좋은 성능을 뽑을 수 있었음. - 추가적으로 Layer Normalization에 대한 분석을 진행. - Pre-LN 구조 사용시 Residual 이후에 Normalization을 해야 안정적인 학습이 가능했음. (원래 이렇게 하긴 했음)
  • 160. Parallelism: Theory and Practice 160 Model Parallelism - Examples: Inter-layer model parallelism on Pytorch - .to( ) - Pytorch로 Inter-layer 병렬화를 할 때는 아래와 같은 방법으로 수행할 수 있음. .to( ) 활용 (single-node) 제일 기본적인 방법이고 많이 쓸 수 있는 방법.
  • 161. Parallelism: Theory and Practice 161 Model Parallelism - Examples: Inter-layer model parallelism on Pytorch - RPC - Pytorch로 Inter-layer 병렬화를 할 때는 아래와 같은 방법으로 수행할 수 있음. RPC 활용 (multi-node) process간 P2P 통신 수행을 통해 다른 노드에게 값 전달
  • 162. Model Parallelism - Examples: Inter-layer model parallelism on Huggingface Transformers (standalone) - 앞선 방법들은 우리가 모델을 새로 짤 때, 가능한 기법들이다. 그럼 Pre-trained 모델은 어떨까? - Huggingface Transformers의 GPT2와 T5는 아래와 같이 병렬화 함수를 지원한다. - 그런데 유저 PR 이라 정식 업데이트에서 transformers standalone 병렬화를 기대하는 것은 어려울듯. - Standalone은 Transformers 자체만을 의미. (물론 Deepspeed 등을 붙이면 모델 병렬화 가능함) Parallelism: Theory and Practice 162 그럼 병렬화를 지원하지 않는 모델은?
  • 163. Parallelism: Theory and Practice 163 Model Parallelism - Examples: Inter-layer model parallelism on Huggingface Transformers (standalone) - 그만 알아보자... (텐서를 일일이 찾아다니면서 전부 다 .to( )를 찍어야 함)
  • 164. Parallelism: Theory and Practice 164 Model Parallelism - Examples: Inter-layer model parallelism on Huggingface Transformers (deepspeed) - 물론 플러그인 등을 사용하면 여러개 GPU를 활용할 수 있음. $ deepspeed --num_gpus 2 inference.py
  • 165. Parallelism: Theory and Practice 165 Model Parallelism - Examples: Inter-layer model parallelism on Fairseq (standalone) - Fairseq에는 ModelParallelTransformer라는 클래스가 있는데, 이는 Megatron LM을 기반으로 한다. - model_parallel_size > 1로 설정하면 기본 모델이 Megatron LM으로 변경된다. - Fairseq Standalone으로 더 이상의 모델 병렬화 기능은 보이지 않는다. (마찬가지로 Fairscale 등 붙일 수 있음)
  • 166. Parallelism: Theory and Practice 166 Model Parallelism - Examples: Inter-layer model parallelism on Parlai - Parlai는 내부적으로 모델 병렬화를 지원하고 있다. - `parlai.utils.torch.PipelineHelper`를 이용하면 모델 병렬화가 가능하다. - 학습할 땐, --model_parallel=True로 설정하면 된다. from parlai.utils.torch import PipelineHelper from parlai.core.agents import create_agent_from_model_file pf = PipelineHelper() model = create_agent_from_model_file(“zoo:blender/blender_3B/model”) model = pf.make_parallel(model) # 모델 병렬화 수행 model.observe({"text": "Hello !"}) model.act() # 대화 수행
  • 167. Pipeline Parallelism (GPipe, PipeDream, Interleaved Schedules, 3D Parallelism) 167
  • 168. Parallelism: Theory and Practice 168 Pipeline Parallelism - GPipe: 주로 Inter-layer model parallelism 속도를 개선하기 위해 사용. - Inter-layer model parallelism의 경우 레이어들의 연산을 순차적으로 수행함. - 때문에 동시에 한 layer의 연산이 수행 중일 때, 다른 layer가 저장되어 있는 device는 Idle 상태로 존재하게 됨.
  • 169. Parallelism: Theory and Practice 169 Pipeline Parallelism - GPipe: 주로 Inter-layer model parallelism 속도를 개선하기 위해 사용. - GPipe는 이러한 Idle 상태를 줄이기 위해 고안된 것. - mini-batch를 micro-batch로 쪼개서 학습과정을 파이프라이닝함. ⇒ Idle 상태 최소화
  • 170. https://kakaobrain.com/blog/66 Parallelism: Theory and Practice 170 Pipeline Parallelism - GPipe: 주로 Inter-layer model parallelism 속도를 개선하기 위해 사용. - GPipe는 이러한 Idle 상태를 줄이기 위해 고안된 것. - mini-batch를 micro-batch로 쪼개서 학습과정을 파이프라이닝함. ⇒ Idle 상태 최소화
  • 171. https://kakaobrain.com/blog/66 Parallelism: Theory and Practice 171 Pipeline Parallelism - GPipe: 주로 Inter-layer model parallelism 속도를 개선하기 위해 사용. - GPipe는 이러한 Idle 상태를 줄이기 위해 고안된 것. - mini-batch를 micro-batch로 쪼개서 학습과정을 파이프라이닝함. ⇒ Idle 상태 최소화
  • 172. https://kakaobrain.com/blog/66 Parallelism: Theory and Practice 172 Pipeline Parallelism - GPipe: 주로 Inter-layer model parallelism 속도를 개선하기 위해 사용. - GPipe는 이러한 Idle 상태를 줄이기 위해 고안된 것. - mini-batch를 micro-batch로 쪼개서 학습과정을 파이프라이닝함. ⇒ Idle 상태 최소화
  • 173. https://kakaobrain.com/blog/66 Parallelism: Theory and Practice 173 Pipeline Parallelism - GPipe: 주로 Inter-layer model parallelism 속도를 개선하기 위해 사용. - GPipe는 이러한 Idle 상태를 줄이기 위해 고안된 것. - mini-batch를 micro-batch로 쪼개서 학습과정을 파이프라이닝함. ⇒ Idle 상태 최소화
  • 174. Parallelism: Theory and Practice 174 Pipeline Parallelism - GPipe: 주로 Inter-layer model parallelism 속도를 개선하기 위해 사용. - 파이프라이닝을 해도, Bubble Time은 존재 할 수 밖에 없으며, Bubble Time은 M(micro-batch)와 K(partition)과 관계 있음. - 정량적 분석 결과 M >= K x 4 정도가 되면 Bubble Time을 거의 무시할 수 있다고 함.
  • 175. Parallelism: Theory and Practice 175 Pipeline Parallelism - GPipe: Remarterialization - GPU 메모리 절약 기술 - 대부분의 Layer는 내부에 Forward 입력을 가지고 있음. (Checkpointing) - 예를 들면 Max Pooling Layer의 미분계수는 오른쪽 Matrix와 같은데, Foward 입력이 있어야 이걸 계산할 수 있음. 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 미분 계수
  • 176. Parallelism: Theory and Practice 176 Pipeline Parallelism - GPipe: Remarterialization - GPU 메모리 절약 기술 - 대부분의 Layer는 내부에 Forward 입력을 가지고 있음. (Checkpointing) - 아래는 CNN numpy scratch 구현 예시임. `self.last_input`에 저장된 값을 `backward( )`시에 사용함.
  • 177. Parallelism: Theory and Practice 177 Pipeline Parallelism - GPipe: Remarterialization - GPU 메모리 절약 기술 - Remarterialization은 Layer 내부에 Input Checkpoint를 저장하지 않게 해서 메모리를 절약함. - Backward 할 때 Forward를 한번 다시해서 필요한 값만 얻어냄. - 대신 이렇게 하면 Forward를 2번 해야한다는 단점이 있는데 GPipe는 그것을 슬기롭게 극복함. Input Checkpoint
  • 178. Parallelism: Theory and Practice 178 Pipeline Parallelism - GPipe: Remarterialization - GPU 메모리 절약 기술 - Remarterialization은 Layer 내부에 Input Checkpoint를 저장하지 않게 해서 메모리를 절약함. - Backward 할 때 Forward를 한번 다시해서 필요한 값만 얻어냄. - 대신 이렇게 하면 Forward를 2번 해야한다는 단점이 있는데 GPipe는 그것을 슬기롭게 극복함. Input Checkpoint
  • 179. Parallelism: Theory and Practice 179 Pipeline Parallelism - GPipe: Remarterialization - GPU 메모리 절약 기술 - (1) 중간 Layer 들의 결과값은 가지고 있어서 맨 처음부터 Forward 하지는 않게 하였음. - (2) 자신의 Backward 타임이 오기 전에 (Bubble Time 동안) 미리 Forward를 연산해둠 중간 레이어들의 결과만 Checkpointing Forward를 한 스텝 먼저 진행해서 Rematerialization으로 발생하는 오버헤드 완화
  • 180. Parallelism: Theory and Practice 180 Pipeline Parallelism - Torch GPipe: 이제는 Pytorch에 내장된 기본 Pipelining 모듈 - Kakaobrain에서 개발한 torch GPipe가 torch 안에 내장되어서 이제 torch의 기본 모듈이 되었음. - 아래와 같이 사용 가능하며, 마찬가지 동일하게 torch.distributed.pipeline.sync.Pipe로 사용 가능함. from torchgpipe import GPipe import torch.nn as nn model = nn.Sequential(a, b, c, d) model = GPipe( model, balance=[2, 2], devices=[0, 1], chunks=8 )
  • 181. Parallelism: Theory and Practice 181 Pipeline Parallelism - Torch GPipe: 이제는 Pytorch에 내장된 기본 Pipelining 모듈 - Kakaobrain에서 개발한 torch GPipe가 torch 안에 내장되어서 이제 torch의 기본 모듈이 되었음. - 아래와 같이 사용 가능하며, 마찬가지 동일하게 torch.distributed.pipeline.sync.Pipe로 사용 가능함.
  • 182. import fairscale import torch.nn as nn model = nn.Sequential(a, b, c, d) model = fairscale.nn.Pipe( model, balance=[2, 2], devices=[0, 1], chunks=8 ) Parallelism: Theory and Practice 182 Pipeline Parallelism - Fairscale: Facebook에서 개발한 병렬처리 도구 (ZeRO, GPipe 등 다양한 기능 지원) - Fairscale의 nn.Pipe를 이용해도 동일하게 사용 가능함. (완전히 동일한 api를 제공함)
  • 183. Parallelism: Theory and Practice 183 Pipeline Parallelism - Pytorch-lightning: Fairscale Plugin을 이용해 학습에 쉽게 사용할 수 있도록 지원.
  • 184. Parallelism: Theory and Practice 184 Pipeline Parallelism - PipeDream: MS의 파이프라인 병렬화 솔루션 - Pipe Dream은 MS에서 개발한 파이프라인 병렬화 솔루션. - Google GPipe와 약간 다른 파이프라이닝 구조를 가지고 있음. - Pipeline Parallelism은 다음과 같은 챌린지들이 존재한다. - (1) Weight Version Managing - (2) Work Partitioning
  • 185. Parallelism: Theory and Practice 185 Pipeline Parallelism - PipeDream: MS의 파이프라인 병렬화 솔루션 - Pipeline Parallelism의 챌린지 (1): Weight Version Managing - GPipe의 경우 하나의 Weight 버전만 운용하지만 주기적으로 Pipeline Flush가 일어난다. - Pipeline Flush는 계산된 Gradients를 이용해 파라미터를 업데이트하는 과정 - 이러한 Flush 과정에서 Forward, Backward 연산도 하지 않기 때문에 처리효율이 떨어진다.
  • 186. Parallelism: Theory and Practice 186 Pipeline Parallelism - PipeDream: MS의 파이프라인 병렬화 솔루션 - Pipeline Parallelism의 챌린지 (1): Weight Version Managing - Pipe Dream은 이러한 Flush 과정 없이 파라미터 상태를 지속적으로 관리한다. - 만약 최신버전의 파라미터만 저장하면 이전 Layer의 출력이 다음 Layer로 전송될 때, 다음 Layer의 파라미터 부분이 이미 업데이트 되어버렸을 수도 있다.
  • 187. Parallelism: Theory and Practice 187 Pipeline Parallelism - PipeDream: MS의 파이프라인 병렬화 솔루션 - Pipeline Parallelism의 챌린지 (1): Weight Version Managing Forward
  • 188. Parallelism: Theory and Practice 188 Pipeline Parallelism - PipeDream: MS의 파이프라인 병렬화 솔루션 - Pipeline Parallelism의 챌린지 (1): Weight Version Managing Backward
  • 189. Parallelism: Theory and Practice 189 Pipeline Parallelism - PipeDream: MS의 파이프라인 병렬화 솔루션 - Pipeline Parallelism의 챌린지 (1): Weight Version Managing Update 1
  • 190. Parallelism: Theory and Practice 190 Pipeline Parallelism - PipeDream: MS의 파이프라인 병렬화 솔루션 - Pipeline Parallelism의 챌린지 (1): Weight Version Managing Forward
  • 191. Parallelism: Theory and Practice 191 Pipeline Parallelism - PipeDream: MS의 파이프라인 병렬화 솔루션 - Pipeline Parallelism의 챌린지 (1): Weight Version Managing Backward
  • 192. Parallelism: Theory and Practice 192 Pipeline Parallelism - PipeDream: MS의 파이프라인 병렬화 솔루션 - Pipeline Parallelism의 챌린지 (1): Weight Version Managing Update 2
  • 193. Parallelism: Theory and Practice 193 Pipeline Parallelism - PipeDream: MS의 파이프라인 병렬화 솔루션 - Pipeline Parallelism의 챌린지 (1): Weight Version Managing Forward
  • 194. Parallelism: Theory and Practice 194 Pipeline Parallelism - PipeDream: MS의 파이프라인 병렬화 솔루션 - Pipeline Parallelism의 챌린지 (1): Weight Version Managing Backward
  • 195. Parallelism: Theory and Practice 195 Pipeline Parallelism - PipeDream: MS의 파이프라인 병렬화 솔루션 - Pipeline Parallelism의 챌린지 (1): Weight Version Managing Update 3
  • 196. Parallelism: Theory and Practice 196 Pipeline Parallelism - PipeDream: MS의 파이프라인 병렬화 솔루션 - Pipeline Parallelism의 챌린지 (1): Weight Version Managing Forward
  • 197. Parallelism: Theory and Practice 197 Pipeline Parallelism - PipeDream: MS의 파이프라인 병렬화 솔루션 - Pipeline Parallelism의 챌린지 (1): Weight Version Managing Backward
  • 198. Parallelism: Theory and Practice 198 Pipeline Parallelism - PipeDream: MS의 파이프라인 병렬화 솔루션 - Pipeline Parallelism의 챌린지 (1): Weight Version Managing Update 4
  • 199. Parallelism: Theory and Practice 199 Pipeline Parallelism - PipeDream: MS의 파이프라인 병렬화 솔루션 - Pipeline Parallelism의 챌린지 (1): Weight Version Managing 빨간색 시점에서 Update가 일어남. 빨간색 숫자 n은 n번 데이터에 대한 업데이트임. 1 2 3 4
  • 200. Parallelism: Theory and Practice 200 Pipeline Parallelism - PipeDream: MS의 파이프라인 병렬화 솔루션 - Pipeline Parallelism의 챌린지 (1): Weight Version Managing 5번 micro-batch 부터는 Forward & Backward 과정 중에 계속 파라미터 업데이트가 일어남. 결과적으로 매 스텝마다 다른 파라미터를 가지고 Forward하게 됨. => 정확하지 못한 계산으로 이어짐. 1 2 3 4
  • 201. Parallelism: Theory and Practice 201 Pipeline Parallelism - PipeDream: MS의 파이프라인 병렬화 솔루션 - Pipeline Parallelism의 챌린지 (1): Weight Version Managing 5번 micro-batch 부터는 Forward & Backward 과정 중에 계속 파라미터 업데이트가 일어남. (동그라미에서 계산미스가 발생하게 됨) 결과적으로 매 스텝마다 다른 파라미터를 가지고 Forward하게 됨. => 정확하지 못한 계산으로 이어짐. 1 2 3 4
  • 202. Parallelism: Theory and Practice 202 Pipeline Parallelism - PipeDream: MS의 파이프라인 병렬화 솔루션 - Pipeline Parallelism의 챌린지 (1): Weight Version Managing - 이러한 문제를 막기 위해 PipeDream은 여러 버전의 Weight를 저장한다. - 그러면 이미 변해버린 파라미터에 Forward & Backward 하는 문제를 막을 수 있다. - 여러 버전을 저장하면 문제가 해결되긴 하지만 메모리 공간을 많이 차지하게 된다. - 여기에서 Trade Off가 발생함: - GPipe: 메모리 효율적, 프로세싱 비효율적 - PipeDream: 메모리 비효율적, 프로세싱 효율적
  • 203. Parallelism: Theory and Practice 203 Pipeline Parallelism - PipeDream: MS의 파이프라인 병렬화 솔루션 - Pipeline Parallelism의 챌린지 (2): Work Partitioning - 두번째는 Neural Net을 어떻게 쪼개는 것이 현명한지에 대한 문제. - 단순히 Layer 별로 쪼개는 것이 별로 현명하지 않을 수 있음. - 일단 각 파티션의 Running Time이 비슷해야 Idle Time을 최소화 할 수 있을 것임. - 그 이외에도 Parameter Size, Activation Memory 등 다양한 요소를 고려해야 함.
  • 204. Parallelism: Theory and Practice 204 Pipeline Parallelism - PipeDream: MS의 파이프라인 병렬화 솔루션 - Pipeline Parallelism의 챌린지 (2): Work Partitioning - Profiling과 Optimizing을 통해 최적의 Partition을 찾아냄. - Activation Size, Parameter Size, Compute Time 등을 고려.
  • 205. Parallelism: Theory and Practice 205 Pipeline Parallelism - PipeDream: MS의 파이프라인 병렬화 솔루션 - Experiments - 단순 Data Parallelism에 비해 훨씬 빠르게 수렴하는 것을 볼 수 있음.
  • 206. Parallelism: Theory and Practice 206 Pipeline Parallelism - PipeDream 2BW (2-buffered weight update): Memory Efficient PipeDream - PipeDream이 프로세싱 효율성이 좋지만, 메모리 효율성이 떨어졌음. - PipeDream 2BW는 이전 PipeDream에 비해 메모리 효율성을 끌어올렸음. - 핵심 아이디어는 파이프라이닝 중에 Gradient Accumulation을 수행하는 것임. - 여러개의 Gradient들을 모아두다가 한번에 업데이트를 수행하는 방식으로 해결. - 단 두개의 Weight Version만 유지해도 계산에 문제가 없으며 Flush도 필요 없음. 한번에 업데이트
  • 207. Parallelism: Theory and Practice 207 Pipeline Parallelism - PipeDream Flush: Memory Efficient PipeDream - PipeDream Flush는 GPipe처럼 Pipeline Flush가 일어남. - PipeDream의 1F1B (1-Forward, 1-Backward) 파이프라인과 Flush를 결함한 파이프라인. - GPipe와 비교해서 Bubble Time은 비슷하나 Forward & Backward 중에 유지해야하는 activation 메모리가 줄어서 효율적. - 단일 가중치만 유지하면 되기 때문에 PipeDream 2BW보다도 메모리 효율적임. (즉, 가장 메모리 효율적임)
  • 208. Parallelism: Theory and Practice 208 Pipeline Parallelism - PipeDream Flush: Memory Efficient PipeDream - PipeDream Flush는 GPipe처럼 Pipeline Flush가 일어남. activation memory = 4 activation memory = 2
  • 209. Parallelism: Theory and Practice 209 Pipeline Parallelism - Interleaved Scheduling: - Bubble을 줄이기 위해서 각각의 device가 pipeline model parallel의 여러 stage에 해당 되도록 할당 - 이전에는 하나의 device가 연속된 레이어를 한번에 계산해서 결과 값을 뽑았었음. - 예를 들면 1번 device가 1~4번 레이어, 2번 device가 5~8번 레이어를 맡는다고 가정. - 그러면 1번 device는 1~4번 레이어에 대한 Forward & Backward 연산을 한번에 진행해서 출력했음. - Interleaved Scheduling은 한개 device 안에서 파이프라인을 더 분할하는 작업 - 1번 device가 1~2번 레이어를 연산하는 것과 3~4번 레이어를 연산하는 것을 중첩시킴. - 이렇게 되면 버블타임은 줄어드는대신 통신시간이 늘어나기 때문에 잘 조절해야함. (Trade Off 존재)
  • 210. Parallelism: Theory and Practice 210 Pipeline Parallelism - Interleaved Scheduling: - Interleaved Scheduling은 한개 device 안에서 파이프라인을 더 분할하는 작업 - 1번 device가 1~2번 레이어를 연산하는 것과 3~4번 레이어를 연산하는 것을 중첩시킴. - 이렇게 되면 버블타임은 줄어드는대신 통신시간이 늘어나기 때문에 잘 조절해야함. (Trade Off 존재)
  • 211. Parallelism: Theory and Practice 211 Pipeline Parallelism - Interleaved Scheduling: - Interleaved Scheduling은 한개 device 안에서 파이프라인을 더 분할하는 작업 - 1번 device가 1~2번 레이어를 연산하는 것과 3~4번 레이어를 연산하는 것을 중첩시킴. - 이렇게 되면 버블타임은 줄어드는대신 통신시간이 늘어나기 때문에 잘 조절해야함. (Trade Off 존재)
  • 212. Parallelism: Theory and Practice 212 Pipeline Parallelism - Interleaved Scheduling: - Interleaved Scheduling은 한개 device 안에서 파이프라인을 더 분할하는 작업 - 1번 device가 1~2번 레이어를 연산하는 것과 3~4번 레이어를 연산하는 것을 중첩시킴. - 이렇게 되면 버블타임은 줄어드는대신 통신시간이 늘어나기 때문에 잘 조절해야함. (Trade Off 존재)
  • 213. Parallelism: Theory and Practice 213 Pipeline Parallelism - 3D Parallelism: - 초반에 언급했던 3D Parallelism은 다음과 같이 수행됨. - Pipeline Parallelism: Inter-layer pipeline model parallelism (PipeDream Flush) - Model Parallelism: Intra-layer model parallelism (Megatron-LM) - Data Parallelism: Data Parallelism (DDP?) Inter-layer pipeline model parallelism (PipeDream Flush or Interleaved) I n t r a - l a y e r m o d e l p a r a l l e l i s m ( M e g a t r o n L M )
  • 214. Parallelism: Theory and Practice 214 Pipeline Parallelism - 3D Parallelism: - 초반에 언급했던 3D Parallelism은 다음과 같이 수행됨. - Pipeline Parallelism: Inter-layer pipeline model parallelism (PipeDream Flush) - Model Parallelism: Intra-layer model parallelism (Megatron-LM) - Data Parallelism: Data Parallelism ⇒ ZeRO Data Parallelism Inter-layer pipeline model parallelism (PipeDream Flush or Interleaved) I n t r a - l a y e r m o d e l p a r a l l e l i s m ( M e g a t r o n L M )
  • 215. Deep Speed (ZeRO, ZeRO-offload, ZeRO-infinity, 1Bit-Adam, Progressive Layer Dropping) 215
  • 216. Parallelism: Theory and Practice 216 Deep Speed - Mixed Precision: FP16 for F&Bward + FP32 for Update - 요즘 대부분 모델을 학습하는데에는 FP16 (half)와 FP32 (single)을 함께 사용함. - 최신 GPU들이 Lower Precision에 대한 계산을 지원하면서 속도 면에서 큰 이점이 생기게 되었음. - V100 기준, FP32에서는 14 TFLOPS가 나오지만 FP16에서는 100TFLOPS가 나옴. - 또한 FP16을 적용하면 모델 사이즈도 절반으로 줄기 때문에 배포시에도 장점이 있을 수 있음.
  • 217. Parallelism: Theory and Practice 217 Deep Speed - Mixed Precision: FP16 for F&Bward + FP32 for Update - 그러나 FP16의 경우 미세한 Gradient 값들이 무시되기 때문에 정확도가 다소 감소할 우려가 있음. - Mixed Precision (FP16 for F&Bward + FP32 for Update)를 사용하면 성능하락 없이 속도의 이점만 얻음
  • 218. Parallelism: Theory and Practice 218 Deep Speed - Mixed Precision: FP16 for F&Bward + FP32 for Update - 그러나 FP16의 경우 미세한 Gradient 값들이 무시되기 때문에 정확도가 다소 감소할 우려가 있음. - Mixed Precision (FP16 for F&Bward + FP32 for Update)를 사용하면 성능하락 없이 속도의 이점만 얻음 Loss Scaling
  • 219. Parallelism: Theory and Practice 219 Deep Speed - Mixed Precision: Loss Scaling - Loss에 일정한 상수를 곱해서 Loss 값을 키워줌. 이렇게 되면 FP16 이후의 가수부(fraction)들을 살릴 수 있음. - e.g. Scale 500 times, 0.00000555 => 0.000277500, 이로 인해 0.000277에 해당하는 Gradient를 살려냈음. Loss Scaling이 없으면 학습이 제대로 진행되지 않음. FP32와 성능이 거의 비슷함.
  • 220. Parallelism: Theory and Practice 220 Deep Speed - Mixed Precision: Memory unefficient?? - Mixed Precision이 성능과 속도의 이점을 모두 취할 수 있다는 것은 사실. - 그러나 빅 모델로 대두되는 이 시대에 memory unefficient 한 것은 매우 큰 문제이다. - FP16과 FP32를 모두 사용하기 때문에 그들이 모두 GPU에 올라와 있어야 하기 때문. FP32 Optimizer States FP32 Parameters FP16 Parameters FP16 Gradients
  • 221. Parallelism: Theory and Practice 221 Deep Speed - ZeRO: Zero Redundancy Optimizer - 메모리를 최적화하여 학습 속도를 크게 향상시키면서 효율적으로 학습 가능한 모델사이즈 확장. - Data & Model Parallelism에서 Memory Redundancy를 제거하였음. (필요한 만큼만 메모리에 올리기) - GPT3를 학습시킨 장본인, 추후에 1 Trillion 이상의 파라미터 모델을 학습시킬 수 있을 것으로 전망됨.
  • 222. Parallelism: Theory and Practice 222 Deep Speed - ZeRO: Zero Redundancy Optimizer - 메모리 소비 스펙트럼을 분석: Model states & Residual states으로 나누어서 각각에 대한 솔루션 제안 - 메모리의 대부분을 Model States가 점유하고 있음. {Parameters, Gradients, Optimizer states} - 나머지 Activation, Temporary Buffer, Fragmented Memory 등이 구성, 이 것을 Residual States (나머지)라고 부를 것임. - ZeRO-DP: Model States 문제를 해결하기 위한 솔루션 (ZeRO-1에서 제안됨) - ZeRO-R: Residual States 문제를 해결하기 위한 솔루션 (ZeRO-2에서 제안됨)
  • 223. Parallelism: Theory and Practice 223 Deep Speed - ZeRO: Zero Redundancy Optimizer 제품군 - ZeRO-1: ZeRO-DP에 대한 아이디어 공개 + ZeRO-DP Optimizer states partitioning 코드 공개 - ZeRO-2: ZeRO-R 공개 + ZeRO-DP Gradients state partitioning 코드 공개 - ZeRO-3: ZeRO-offload 공개 + ZeRO-DP Parameter states partitioning 코드 공개 - ZeRO-infinity: ZeRO-infinity 공개
  • 224. Parallelism: Theory and Practice 224 Deep Speed - ZeRO-DP: ZeRO powered Data Parallelism - DP: Good Computation & Poor Memory efficiency (Parameter Duplication) - MP: Poor Computation (Idle Time) & Good Memory efficiency - 두 방식 모두, GPU에 학습에 항상 필요하지 않는 메모리를 올려놓는 비효율성이 있다. (특히 Optimizer States) - ZeRO는 이러한 문제를 해결하여 Good Computation & Good Memory efficiency를 달성했다.
  • 225. Parallelism: Theory and Practice 225 Deep Speed - ZeRO-DP: ZeRO powered Data Parallelism (3 stages) - Stage 1: Optimizer state partitioning: 메모리 4배 감소 (DP와 동일한 communication volume) - Stage 2: Gradient state partitioning: 메모리 2배 더 감소 (총 8배 감소, DP와 동일한 Communication volume) - Stage 3: Parameter state partitioning: DP_degree에 따라 선형적으로 감소 (대신 Communication 증가)
  • 226. Parallelism: Theory and Practice 226 Deep Speed - ZeRO-DP: ZeRO powered Data Parallelism (3 stages) - Stage 1: Optimizer state partitioning: 메모리 4배 감소 (DP와 동일한 communication volume) - Stage 2: Gradient state partitioning: 메모리 2배 더 감소 (총 8배 감소, DP와 동일한 Communication volume) - Stage 3: Parameter state partitioning: DP_degree에 따라 선형적으로 감소 (대신 Communication 증가)