반응형
250x250
Notice
Recent Posts
Recent Comments
Link
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
Archives
Today
Total
관리 메뉴

가끔 보자, 하늘.

Fine-tuning LLMs with PEFT and LoRA (자막) 본문

개발 이야기/개발툴 및 기타 이야기

Fine-tuning LLMs with PEFT and LoRA (자막)

가온아 2023. 5. 4. 11:55

한국어가 아닌 개발에 도움이 될 만한 영상을 소개하고 이해를 돕기 위해 별도 자막을 남겨두려 합니다. 

영상 원본은 유튜브에서 직접 시청해 주시면 영상 올리신 분들에게도 많은 도움이 됩니다. 영상에 사용된 코드 링크 등은 유튜브 원본 영상에 가시면 확인하실 수 있습니다.

자막 생성에 사용한 툴도 같이 소개하니 많이 사용해 주세요.

유튜브 영상 텍스트 추출 용 크롬 확장 앱(제목 혹은 id로 쉽게 검색해서 설치 가능합니다.) : YouTube ChatGPT : 채팅GPT를 사용한 유튜브 동영상 요약 (ID : baecjmoceaobpnffgnlkloccenkoibbb)  (오탈자 혹은 LLM에서 전용하는 단어, 명칭들에 대한 오타 뿐 아니라 대소문자, 띄어쓰기 등등... 아직은 손봐야 할게 너무 많네요. 이 문제는 확장앱이 아닌 유튜브에서 생성한 영문 자막의 이슈입니다.)

번역 : Deepl (https://www.deepl.com/) + 일부 자체 수정

영상 주소 : https://www.youtube.com/watch?v=Us5ZFp16PaU 

 

(요약)

이 동영상에서는 메모리와 컴퓨팅 요구 사항, 결과물인 체크포인트 파일의 크기 등 대규모 언어 모델(LLM)을 훈련하고 미세 조정하는 데 따르는 어려움에 대해 설명합니다. 이 문제를 해결하기 위해 사전 학습된 네트워크의 원래 파라미터를 대부분 동결한 채 소수의 가중치만 추가로 학습하는 파라미터 효율적 미세 조정(PeFT) 기법이 소개됩니다. 이 동영상은 대규모 언어 모델에서 몇 개의 가중치만 미세 조정하는 PeFT에 사용되는 기술인 LoRa(낮은 순위 적응)에 중점을 둡니다. PeFT는 치명적인 망각을 방지하고 새로운 시나리오에 더 잘 일반화할 수 있도록 지원하며, 추가적으로 학습되는 가중치만으로 전체 모델을 미세 조정하는 것과 유사한 성능을 달성할 수 있습니다. 허깅페이스는 대규모 LLM을 쉽고 효율적으로 미세 조정할 수 있는 PeFT 기반 라이브러리를 출시했습니다. 이 비디오에서는 인과 관계 언어 모델링 작업에 LoRa와 함께 PeFT를 사용하는 코드 예시도 제공합니다.

(상세 내용)

00:00
대규모 언어 모델을 학습하고 미세 조정하는 데 있어 중요한 것은 가중치가 매우 커진다는 점입니다. 이로 인해 많은 문제가 발생합니다. 이러한 문제는 크게 두 가지입니다. 첫째, 훈련에 훨씬 더 많은 컴퓨팅이 필요합니다.
00:19
그리고 모델이 점점 더 커지고 있기 때문에 일부 모델을 미세 조정하기 위해 훨씬 더 큰 GPU, 즉 여러 개의 GPU가 필요하다는 것을 알게 됩니다. 두 번째 문제는 기본적으로 컴퓨팅이 필요하다는 것입니다. 파일 크기가 엄청나게 커진다는 것입니다. 그래서 flan-t5-xxl(https://huggingface.co/google/flan-t5-xxl)체크포인트의 크기는 약 40기가바이트 정도입니다. 현재 출시되는 200억 개의 매개변수 모델은 말할 것도 없고요.
00:46
점점 더 커지고 있습니다. 그래서 매개변수의 효율적인 미세 조정이라는 아이디어가 필요한 것입니다. 그래서 저는 앞으로 이것을 PeFT라고 부르겠습니다. PeFT는 다양한 기법을 사용합니다. 오늘 살펴볼 기술은 로우랭크 적응을 의미하는 LoRa입니다. 그리고 이것은 대규모 언어 모델에 대해 이 작업을 수행하는 것에 관한 논문에서 나온 것입니다.  
01:09
하지만 PEFT에는 접두사 튜닝, P 튜닝, 프롬프트 튜닝과 같은 다른 멋진 기술도 있습니다. 앞으로 이 기법들을 언제 사용해야 하는지, 어떻게 유용하게 사용할 수 있는지 살펴보겠습니다.   그리고 사람들이 클라우드에서 이러한 모델을 미세 조정할 수 있도록 하기 위해 Nvidia와 같은 회사에서 실제로 사용하고 있는 몇 가지 기술이 있습니다.
01:28
정말 흥미로운 부분입니다. 그래서 PeFT가 하는 일과 특히 LoRa의 특징은 바로 이것입니다. 모델에서 소수의 추가 가중치만 미세 조정할 수 있습니다. 사전 학습된 네트워크의 대부분의 파라미터를 고정하는 동안 말입니다. 따라서 실제로 원래의 가중치를 훈련하지 않는다는 것이 핵심입니다.
01:49
가중치를 추가하고 있습니다. 그리고 이를 미세 조정할 것입니다. 이것의 장점 중 하나는 원래의 웨이트를 그대로 사용한다는 것입니다. 따라서 치명적인 망각을 막는 데도 도움이 되는 경향이 있습니다. 미세 튜닝을 너무 많이 하면 모델이 원래 훈련받았던 것을 잊어버리는 경향이 있습니다. 결국 망각하게 되죠.
02:11
그러면 학습된 원본 데이터의 일부 내용을 잊어버리게 됩니다. 그러나 PeFT는 가중치를 추가하고 원래 가중치를 동결하면서 가중치를 조정하기 때문에 이러한 문제가 없습니다. 따라서 PeFT를 사용하면 소량의 데이터만 가지고 있어도 정말 훌륭한 미세 조정을 할 수 있습니다.
02:33
또한 이를 통해 다른 시나리오에도 더 잘 일반화할 수 있습니다.  따라서 대규모 언어 모델과 안정적인 확산과 같은 모델을 미세 조정하는 데 큰 도움이 됩니다. 현재 우리가 보고 있는 많은 AI 아트 모델에서도 이를 사용하기 시작했습니다. 가장 좋은 점 중 하나는 마지막에 작은 체크포인트만 남긴다는 점입니다. 최근 동영상 중 하나에서는 알파카 모델을 만들기 위해 라마 모델을 미세 조정하는 과정을 보여드렸습니다.
02:59
그리고 애드온 부분의 최종 체크포인트는 약 12메가바이트 정도였던 것 같습니다. 그래서 지금은 작아졌지만 여전히 원래의 무게가 필요합니다. 따라서 모든 것에서 완전히 벗어나는 것은 아니지만 훨씬 작은 무언가가 있습니다.
03:18
따라서 일반적으로 PeFT 접근 방식을 사용하면 기본적으로 전체 모델을 미세 조정하는 것과 비슷한 성능을 얻을 수 있습니다. 허깅 페이스는 이와 관련된 모든 종류의 라이브러리를 출시했으며, 이 PeFT는 여러 논문을 가져와 트랜스포머 라이브러리 및 가속 라이브러리와 함께 작동하도록 구현했습니다.
03:41
이를 통해 우리는 기본적으로 선반에 껴안고 있는 얼굴을 벗을 수 있습니다. Google에서 메타를 통해 다양한 회사에서 수행한 사전 학습된 모델입니다. 그리고 이 모델을 사용하여 정말 잘 조정할 수 있는 무언가에 넣을 수 있습니다. 이제 코드로 들어가서 기본적으로 PeFT를 사용하여 모델의 LoRa 미세 조정을 수행하는 방법을 살펴 보겠습니다.
04:06
이 노트북에서는 PEFT를 사용하여 모델을 훈련하거나 모델을 미세 조정하는 방법을 살펴보겠습니다. 비트와 바이트, 그리고 이를 위해 LoRa 체크포인트를 수행합니다. 이것이 바로 로라 미세 조정입니다. 로라에 대한 아이디어를 기억하신다면, 우리는 일종의 어댑터를 계속 훈련하고 있다는 것입니다. 실제 웨이트를 훈련하는 것이 아닙니다. 모델에 가중치를 추가하는 것입니다.
04:29
모델의 여러 지점에서 결과를 얻기 위해 미세 조정하고 있으므로 여기에 라이브러리를 설치하면 됩니다. 저는 항상 허깅 페이스 허브를 일찍 설정하는 것을 좋아합니다. 왜냐하면 이것을 실행 상태로 두었다가 훈련이 끝나면 기본적으로 모델과 가중치를 허깅 페이스 허브까지 최대한 빨리 저장하기를 원하기 때문입니다. 그래야 CoLab이 멈춰서 모든 작업을 잃지 않을 수 있습니다.
04:55
저는 이 부분을 전면에 배치하는 편입니다. 이것은 기본적으로 여기를 클릭하여 허깅을 클릭하고 허깅 프레스 토큰을 받는 것입니다.  이 작업을 수행하려면 당연히 쓰기 토큰이 필요합니다. 그래서 이 코랩은 A100으로 실행했습니다. 하지만 블룸 모델의 작은 버전으로 모델을 변경하면 T4로도 할 수 있을 것입니다. 그래서 제가 여기서 훈련하거나 미세 조정하고 있는 모델은 BLOOM 70억 파라미터 모델(https://bigscience.huggingface.co/blog/bloom, 이하 BLOOM 7B)입니다.
05:19
매개 변수가 있고 760 버전도 있습니다. 13 억 버전 등도 있다고 생각합니다. 그래서 우리는 모델에로드하고 있습니다. 보시다시피 방금 주문이 들어왔어요.  방금 트랜스포머에서 주문이 들어왔어요 8비트를 처리할 비트와 바이트를 가져오고 있습니다.
05:37
모델을 8비트로 전환하면 GPU 램을 많이 차지하지 않아서 더 빨라지고 나중에 더 쉽게 저장할 수 있습니다. 그리고 자동 토큰화 도구와 인과 관계 언어 모델링을 위한 자동 모델도 있습니다. 따라서 사전 학습된 데이터를 가져오기만 하면 BLOOM 7B에 전달할 수 있습니다. 여기서 우리가 해야 할 일은 전달하고 8비트 등호를 로드하는 것뿐입니다. 그리고 변환기는 이를 위해 비트 및 바이 라이브러리를 사용하여 8비트 변환을 처리합니다.
06:04
집에서 rtx 3090 또는 이와 유사한 GPU를 사용하고 있는데 거기에서 시도해보고 싶다면. 여러 대의 GPU가 있는 경우 디바이스 맵을 사용하여 기본적으로 모델의 일부를 매핑할 수 있습니다. 하지만 이 경우에는 자동을 사용하고 있으므로 처음부터 자동을 사용해 보시기 바랍니다.
06:21
이제 모델에 토큰화를 적용했습니다. 다음으로 할 일은 기본적으로 원래 가중치를 동결하는 것입니다. 여기서 몇 가지 예외를 제외하고는 기본적으로 가중치를 동결하는 것을 볼 수 있습니다. 레이어 표준 레이어를 유지하고 실제로 float32로 유지하려고 합니다.
06:41
또한 출력은 float 32로 유지하고자 합니다. 이것이 바로 이 작업을 수행하기 위한 표준 코드입니다. 다음은 실제 로라 어댑터를 설정하는 것입니다. 이 모든 것이 여기 설정으로 귀결됩니다. 따라서 기본적으로 구성을 가져올 것입니다. 여기에는 모델이 있고 이것이 전체 크기 모델입니다.
07:01
하지만 아직 LoRA가 추가되지 않았습니다. 여기서는 이 구성을 만들겠습니다. 그리고 기본적으로 우리가 가지고 있던 모델을 전달한 다음 원래 모델과 LoRA 어댑터가 있는 PEFT 모델을 가져올 것입니다. 따라서 여기서 구성이 핵심입니다. 기본적으로 알파 스케일링을 원하는 attention heads 수를 설정합니다.
07:20
모델에 특정 대상 모듈이 있다는 것을 알고 있는 경우. 현재 라이브러리에서 이에 대한 문서를 많이 찾지 못했습니다. 하지만 제 생각에는 앞으로 사람들이 큰 모듈에서 기본적으로 LoRa 어댑터가 드롭아웃을 설정하고 또 다른 핵심 모듈은 작업 유형을 설정하는 것이 가장 좋은 모듈이라는 것을 알아낼 것이라고 생각합니다.
07:43
그렇다면 인과적 언어 모델일까요? 즉, 디코더 전용 모델인 GPT 스타일 모델이라는 뜻입니다. 아니면 T5 모델, 플란 모델 등과 같은 추구 모델일까요?
07:57
  그리고 C2C 모델을 미세 조정하는 과정을 담은 또 다른 동영상을 제작할 예정입니다. 여기에서 차이점을 확인할 수 있습니다. 따라서 여기에서 이 두 가지 설정을 가지고 놀아보세요. 훈련 가능한 양의 크기가 상당히 많이 결정됩니다. 따라서 여기에서 몇 가지 다른 ID 아이디어를 시도해 볼 수 있습니다.
08:14
모든 파라미터에 대해 70억 개의 파라미터가 있습니다. 하지만 학습 가능한 파라미터는 아주 작습니다. 따라서 이것은 우리가 볼 수 있는 훈련 가능한 총 매개 변수를 제공합니다. 이 경우에는 데이터에 대해 아주 간단한 작업을 선택했습니다. 영어 따옴표로 이루어진 데이터 집합이 있습니다.
08:31
대부분의 사람들이 견적을 완성하는 데 사용하는 것보다는 누군가 견적을 시작하면 견적을 완성할 수 있도록 하는 데 사용하는 것 같습니다. 데이터 집합을 살펴보니 실제로 견적서에 대한 수많은 태그가 있다는 것을 알 수 있었습니다. 그래서 제가 생각한 것은 사용자가 직접 견적을 입력하면 해당 견적에 대한 태그가 생성되는 모델을 만들어 보자는 것이었습니다. 여기에서 제가 한 작업을 보시면 기본적으로 몇 개의 열을 병합하여 만든 것을 볼 수 있습니다.
08:57
여기에 한 인용문이 있습니다. 그리고 세 개의 문자가 있습니다. 이 세 문자가 선택된 이유는 사전 학습 등에서 순서대로 자주 나타나지 않을 것이기 때문입니다.   따라서 이 세 문자를 볼 때마다 그 전의 입력에 따라 조건을 지정하고 그 후에 태그를 생성하도록 모델을 가르치려고 합니다. 우리가 만든 데이터 세트를 보면 확인할 수 있습니다.
09:24
이건 당신 자신입니다. 다른 사람들은 모두 태그를 찍었습니다. 그래서 우리는 거기에 있습니다. 그리고 태그는 자신답게, 정직, 영감, 오스카 와일드에게 잘못 귀속된 이런 종류의 것들일 것입니다. 이제 그 중 일부는 인용문이 누군가의 메시지인지 예측할 수 있지만, 특히 인용문을 구성하는 경우 모델이 학습하기는 쉽지 않을 것입니다.
09:48
하지만 인용문의 키워드 종류에 대한 요소는 확실히 여기에 표시되어야 합니다. 여기에 표시되어야 합니다. 여기 보이시죠? 너무 많은 책, 너무 적은 시간 책, 유머 같은 것들, 그렇죠? 시도해 보기에 좋은 것 같아요. 일단 제가 가져가서 나중에 시도해 보겠습니다. 데이터가 있습니다. 기본적으로 입력 ID를 얻기 위해 실행하고 있습니다.
10:08
주의 집중은 이 모든 것을 해결해줍니다. 이제 훈련을 설정하겠습니다. 훈련은 여기 모델에 전달한 일종의 트랜스포머를 포옹 얼굴에 사용할 것입니다. 그런 다음 기차 데이터 세트를 전달합니다. 여기서 볼 수 있듯이 기차 데이터 세트가 있습니다. 그리고 인수를 전달해야 합니다. 이제 몇 가지 인수를 살펴봅시다.
10:27
첫 번째는 그라디언트 누적 단계, 즉 여러분이 변경할 수 있는 것들이 있습니다.  더 작은 GPU에서 실행하려는 경우. 여기에는 네 가지 예제가 있습니다.  네 번의 포워드 패스에 대해 그라디언트를 계산하기 전에 네 번을 수행하겠습니다.
10:48
따라서 일반적으로 배치라고 하면 많은 GPU로 훈련하는 경우 배치 크기를 128 또는 그 이상으로 할 것입니다. 라마 논문에서는 4백만 개의 배치 크기를 사용하고 있습니다. 정말 많은 GPU를 사용하고 있습니다. 안타깝게도 우리에게는 그만한 예산이 없습니다.
11:03
여기서 제가 보여드리고자 하는 것은 A100에서 이 기능을 제대로 활용하지 못하고 있다는 것입니다. 여기에서는 기본적으로 한 번에 네 가지 예제를 한 번에 네 개씩 수행하여 그라데이션으로 수집하고 4단계에 걸쳐 누적할 것이기 때문에 실제로 배치를 더 크게 만들 수 있습니다. 그런 다음 하나의 배치가 됩니다. 따라서 여기서는 16개의 배치를 수행하는 것과 같습니다.
11:23
다음으로 워밍업 단계를 설정하겠습니다. 따라서 학습률을 최대로 설정한 상태에서 시작하여 모든 것을 흔들고 싶지 않습니다. 학습률을 극도로 낮게 설정한 다음 설정한 학습률까지 끌어올려야 합니다. 그러려면 어느 정도 시간이 걸립니다.
11:41
그런 다음 여기에서 최대 걸음 수를 설정할 수 있습니다. 여기서 최대 걸음 수는 매우 작다고 말씀드렸습니다. 이것은 단지 무언가를 로드하는 것을 보여주기 위한 장난감 프로젝트에 불과합니다. 부동 소수점 16을 사용하고 있습니다. 여기에 이것을 설정하고 있습니다. 여기에는 우리가 확인할 출력이 있습니다.  그리고 훈련을 시작합니다.
11:58
여기에서 알 수 있듯이 이 경우 얼마나 오래 훈련할지 알려주면 매우 빠르게 훈련됩니다. 하지만 특정 사람에게는 훨씬 더 오래 훈련할 수 있습니다. 그리고 시간이 지나면 확실히 손실이 줄어들고 있다는 것을 알 수 있습니다.
12:12
모델이 무언가를 배우기 시작했으니 여기서 제가 한 것을 많이 훈련시키면서 이 실험을 진행할 수 있습니다. 다음 단계는 포옹하는 얼굴 허브에 이것을 공유하는 것입니다. 여기에는 기본적으로 허깅 페이스 허브 사용자 이름 슬래시와 모델 이름을 넣었습니다.
12:30
이 태그는 BLOOM 7B LaRA 태그입니다. 그리고 커밋 메시지에 몇 가지 정보를 입력할 수 있습니다. 저는 이것을 비공개로 설정하거나 공개로 설정할 수 있습니다. 나중에 이 체크포인트를 공개해서 여러분이 이걸 가지고 놀 수 있도록 할게요. 하지만 그러면 기본적으로 업로드됩니다.
12:46
그리고 LoRA 대기열도 업로드할 예정입니다. 전체 블룸 모델과 LoRA 웨이트를 업로드하는 것이 아닙니다. 따라서 행잉페이스에서 아주 작은 파일이 될 것입니다. 여기서는 몇 기가바이트가 아니라 메가바이트를 이야기하고 있습니다.
13:01
실제로 여기에서 완전히 업로드되면 31MB가 될 것임을 알 수 있습니다. 업로드했습니다. 다음은 추론만 하고 싶을 때입니다. 기본적으로 이렇게 가져올 수 있습니다. 따라서 기본적으로 이것을 로드할 수 있습니다.
13:17
그리고 이것은 기본적으로 훈련한 것을 조합하지만 실제 전체 모델도 가져옵니다.  따라서 이것은 기본적으로 가져오고 여기에서 작동한다는 것을 알 수 있습니다. 좋아요, 블룸 70억 모델이 필요해요. 가져올게요. 이를 위해 토큰화가 필요합니다. 그리고 그것들을 가져올 것입니다. 그리고 그것은 꺼지고 그것들을 다운로드 할 것입니다. 그러면 마지막으로 이것만 남습니다. 그래서 기본적으로 추론을 할 수 있습니다.
13:39
여기서는 기본적으로 인용문을 전달하고 세 개의 문자로 구성된 마법을 사용합니다. 우리가 입력하면 무언가를 예측할 수 있습니다. 이제 보실 수 있습니다. 좋아요. 그렇게 오래 훈련하지 않았어요.  그래서 루프에 들어가는 것 같습니다. 데이터에 문장 끝 태그 같은 것을 넣는 것도 고려할 수 있습니다.
13:58
하지만 "The world is your oyster."라는 문구를 볼 수 있습니다. 거기서 키워드를 찾았습니다. "world and oyster". 어디 보자 "o many books, so little time."을 넣은 것 같아요. 여기서도 분명히 변경할 수 있고 최대 토큰 등을 변경할 수 있습니다. 
14:15
"So many books, so little time" "books, reading-time, reading-writing, time, writing-books"이 또다시 반복되고 있습니다. 보시다시피요. 좋아요. 일종의 반복 모드로 들어갑니다. 이 작업을 훨씬 더 많이 수행하면 도움이 될 것입니다. 좋아, "Training models with PEFT and LoRA is cool." 어디 보자. 좋아요. 어떤 것을 골라낼까요? 그 중 일부를 찾을 수 있습니다.
14:39
물론 키워드를 골라낼 수도 있지만, 일부 키워드의 경우 다른 것도 골라낼 수 있습니다. 이제 흥미롭네요. 좋아요. 그래서 여기에는 교육과 교육이 제대로 이루어지지 않았고, PEFT와 LoRA는 예상대로입니다.
14:51
여기에서 이전 훈련의 일부가 아직 남아 있는 것을 볼 수 있으므로 모델 훈련과 관련된 몇 가지 항목이 있는 것처럼 보입니다. 그것은 튀는 것입니다. 이것을 정말로 모델로 사용하려면 더 오래 훈련하고 싶겠지만, 이것은 LoRA로 더 큰 인과 언어 모델을 튜닝하여 인과 언어 모델을 만드는 방법에 대한 좋은 예를 보여줍니다.


----------------------------------------------------------

So what's the problem with training large language models and fine tuning them, the key thing here is that we end up with really big weights. this raises a whole bunch of problems here. These  problems are two main things. One, you need a lot   more compute to train.
For this And as the models are getting larger and larger, you are finding that you need much bigger GPUs multiple GPUs just  to be able to fine tune some of these models. The second problem is that in addition to basically needing the compute. The file sizes become huge. So, t5-xxl check point is around about 40 gigabytes in size. Not to mention, the sort of 20 billion  parameter models that we've got coming out now.
Are getting bigger and bigger all the time. So,  this is where this idea of parameter efficient,   fine tuning comes in. So I'm just gonna talk  about this as PeFT going forward. So PeFT uses   a variety of different techniques. The one we're  gonna be looking at today is LoRa, which stands   for low rank adaption. And it comes from a paper  all about doing this for large language models.  
But PEFT also has some other cool techniques like prefix tuning, P tuning and prompt tuning. That we'll look at in the future and when to  use those and how they can be really useful.   And there are some of the techniques that are  actually being used by companies like Nvidia   to allow people to fine tune these models  in the cloud.
So that's something really   interesting to look at. So what PeFT does  and with LoRa particular is that it's just allowing you to fine tune only a small  number of extra weights in the model.   While you freeze most of the parameters of  the pre-trained network. So the idea here   is that we are not actually training the  original weights.
We're adding some extra   weights. And we're going to fine tune  those. One of the advantages of this. Is that we've still got the original weights . So  this also tends to help with stopping catastrophic forgetting. If you don't know, catastrophic forgetting is where models tend to forget what they were   originally trained on when you do a fine tuning, if you do the fine tuning too much. You end up.
Then causing it to forget, some of the things  from the original data that it was trained on. But PeFT doesn't have that  problem because it's just   adding extra weights and it's tuning  those as it freezes the original ones. So PeFT also allows you to get really good fine tuning when you've only got a small amount of data.
And also it allows this to generalize better to other scenarios as well.  So in all this sort of thing is a huge win for fine tuning large language models and even models like stable diffusion. A lot of the AI art models that we're seeing currently are starting to use this as well. One of the best things is that you end up at the end with just tiny checkpoints. In one of my recent videos, I showed fine tuning the llama model to create the alpaca model.
And  I think the final checkpoint for just the add-on part was something around 12  megabytes. So it's, tiny now you still need the original weights. So it's not like you are getting  away totally from everything, but you've got something that's much small on.
So in general, the  PeFT approaches allow you to basically get similar   performance to fine tuning a full model. Just  by fine tuning and tuning these add-on weights   that you're gonna put into. the hugging face has  released a whole sort of library around this and this is what where this PeFT comes in is  they've taken a number of papers and implemented   them to work with transformers library and the  accelerate library.
So this allows us to basically   take off the shelf, hugging face. Pre-trained  models that have been done by Google done by meta, done by a variety of different companies. And  put them into something where we can use them with this and fine tune them really well. So  we're gonna jump into the code and we're gonna   look at how to basically use PeFT to do a LoRa fine tuning of a model.
All right. In this notebook, we're gonna go through  and look at training up a model or fine tuning a model using PEFT. Bits and bytes and doing a  LoRa checkpoint for this. So this is a Laura   fine tuning. So if you remember the idea with  Laura is that we're training sort of adapters   that go on. We're not training the actual  weights. We're adding weights to the model.
At various points in the model and we're  fine-tuning those to get the results out that   So you just come up at you install your libraries  here. I always like to set up the hugging face   hub early because if you're gonna leave this  running and it gets to the end of the training you want it to basically save your model, your  weights up to hugging face hub as quickly as possible. So that your CoLab doesn't stop and then  you lose all your work in there.
I tend to put this up the front. This is  basically just get your hugging   click here get your hugging press token.  You'll need a write token obviously to do this. So this  CoLab, I've run on an A100. But you can certainly, you should  be able to do it with a T4 If you   change the model to be a smaller version  of the bloom model. So the model that I'm   training here or fine tuning here is the  bloom 7 billion parameter model.
And there's   also like a 760 version. I think there's  also a 1.3 billion version, et cetera that you could try out. So we are loading in the  model. So you'll see, we've just got an order.   We've just from transformers. We're bringing in  bits and bytes, which is gonna handle the eight   bit.
Turning our model into eight bit, which  means that it won't take up so much GPU ram that makes it easier makes it quicker,  makes it easier to store things later on, too. And we've got our auto tokenizer and we've  got this auto model for causal language modeling. So when we just bring in from pre-trained, we can pass in the name for the bloom 7 billion. And all we have to do here is pass in, load in  eight bit equals And, transformers will take  care of the eight bit conversion using the bits and bys library for doing this.
If you're using a GPU at home  where you've perhaps got a (rtx)3090, or something like that, and you want to  try it on there. If you've got multiple GPUs you can do a device map to basically  map parts of the model across. But in this case we're just using auto and I  suggest you try our auto at the start anyway
So we've got our model in, we've  got our tokenize in. The next thing we want to do is basically go through and freeze the  original weights. So you can see here that we're   basically just going through and freezing these  weights with a few exceptions. the layer norm layers we want to keep them and we want to actually keep them in float32.
And also the outputs we want to keep as  being float 32. So what this is just doing, this is some standard code for you for  doing that. Next up is setting up the actual lora adapters. So this all comes down to the config here. So we're gonna basically get the config. So we've remember up here we've got our model here and this is the full size model.
But there's no LoRA added to that yet. In here, we're gonna make this   config. And then we're gonna basically pass in  the model that we had and then get the PEFT model,   which is gonna have the original model and the  LoRA adapters on this. So the config here is key. You're basically setting the number  of attention heads that you want the alpha scaling.
If you know that your model's got certain target modules. I don't find a lot of documentation about  this in the library at the moment. But my guess is that going forward, people will work out are these are the best modules in the large module to basically have LoRa adapters on there setting your dropout for LoRA and another key one is just setting the task type.
So is it a causal language model? Meaning that it's a decoder only model a GPT style model. Or is it gonna be a c2c model more like the T5 models, the flan models, et cetera.
  And I'll perhaps make another video of going through train fine tuning a c2c model. So you can see the differences in here. So  by playing around with these two settings   up here. This will determine the size  of the trainable amount quite a lot. So you can try out some different ID ideas here, but you'll see that. 
We've got this 7 billion parameter for all the parameters. But the trainable parameters is just tiny, really tiny in here. So this gives us the total trainable  parameters that we can see that's going on there. All right. In this case for data. So I've just  picked a really simple little task in here. There's this data set of English quotes.
Rather  than what most people seem to do is use that to   finish a quote so that if someone starts a quote  and it can finish it. Looking at the data set,   I saw that there are actually a bunch of tags  about the quote. And what I thought would be   cool is let's try and make a model where you can  input your own quote and it will then generate tags for that quote. So you can see here what I've done is basically just merge some of the columns to make it.
So we've got this quote. And then we've got these three characters here. Now those three characters are chosen because they're probably not gonna appear in that order very often in the pre-training and stuff like that.   So we're trying to teach the model that  anytime you see these three characters we   are gonna condition on the input before  that, and we're gonna generate the tags   out after that. So you can see here by  looking at the data set that we've made.
We've got, this be yourself. Everyone else has  taken and then the tags. So we've got that there. And then the tags are gonna be this,  be yourself, honesty, inspirational, mis-attributed to Oscar Wild the these kinds of things. Now, some of them I probably being able to predict whether a quote was message  attributed to someone is probably not gonna be   easy for the model to learn to do especially  if you're making up the quotes.
But certainly,   elements about what the sort of keywords  in the quote. Should be appearing up here. As you see here? Things like, so many  books, so little time books, humor,   right? that's a good one to try out. let me just take that and we try that later on. So we've got the data there. We are just running  it through to basically to get the input IDs.
The attention masks all for that. Now we want to set  up our training. The training is just gonna use the HuggingFace the sort of transformers  we pass in the model here. We then pass in the train data set. so you can see here, we've got this train data set. And then we've gotta pass in the arguments. So let's  go through some of the arguments.
The first ones are This we're gonna have gradient  accumulation steps, meaning, and these are the things that you would change.  If you're trying to run on a smaller GPU. So here, we've got, we're gonna do four examples.  For four forward passes and then we're gonna do four of those before we calculate the  gradients.
So normally if you think of a batch, if you were training this with a lot of GPUs, you  would just do a batch size of 128 or a lot more. In the llama paper, they're using batch sizes  of 4 million. They're using so many GPUs. Unfortunately we don't have  that budget.
So here, what I'm trying to show you is that you could use, and this is probably underutilizing it for the A100. We could actually make the batches bigger here because see here, we are basically saying it, we're gonna do four,   examples at a time, we're gonna collect those in gradients we're gonna accumulate them for four steps. And then that will be one batch. So it's the equivalent of doing a batch of 16 here.
Next up, we wanna set up the warmup  steps. So we don't want to just go in   there and start with our learning rate t the full amount and shake everything around. We start with the learning rate  being extremely low and then building up to the learning rate that we've set. And  that will take, a certain amount of time.
And then we can set the max steps  here. So the max steps here,   I've said is very small. This is more just  a toy project to show you getting something   loading. We're using floating point 16. We're  setting this in here. We've got the outputs   where we're gonna be checking things.  And then we just kick off our training.
You can see here that it's. tell us okay, how long it's gonna train in this case,   it's trained very quickly. But you might find  for your particular one, it's gonna train, for a lot longer. And then we can see like over time  that yes, sure enough, our loss is going down.
So the model is starting to learn something.  you could go through an experiment doing this   with a lot training them what I've done  here. Then the next part is sharing this   onto the hugging face hub. So here you  can say, see, I've basically just put   my hugging face hub username slash then  the model name that I'm gonna call it.
So this is the BLOOM 7B LaRA tag is what I've called this here And I can put some info in for the commit message. I, can set this to be  private or to be public. I will come and make this   checkpoint public afterwards so that you can play  with this. but that will then basically upload it.
And it's just going to upload the LoRAwaits  too. It's not uploading the full BLOOM model plus the LoRA waits. So you'll find on the HangingFace this is gonna be a tiny, tiny file. We're talking about megabytes here, not multiple, multiple gigabytes. here.
In fact, you can see here that this is gonna be 31MB something when it's fully up. Uploaded. The next thing is, if you wanted to  just do inference. You can just, basically,   this is how you would bring it  in. So you can basically load this in.
And then this will basically put  together the one that you've trained, but also bring in the actual full model as well.  So you can see that this is basically bringing in, it's gonna work out from this. Okay. I need the bloom 7 billion model. I'll bring that in. I need the tokenize for  that. And I'll bring those in. And it will go off and download those. Then finally you're left  with this. So you can basically do some inference.
And  here we are basically passing in a quote and  we've got our sort of magic, three characters. That we're gonna put out and then it's gonna  predict there's something. Now you can see that. Okay. I haven't trained it that long.  So it does seem to go into a loop. We could  even look at putting a end of sentence tag or something like that in  there as well in the data
But we can see, "The world is your oyster." It's worked out the keywords there. "The world and oyster". Let's see. I think I put in this one "so many books, so little time.". And we could change this obviously here, we could change the max tokens,  et cetera. 
"So many books, so little time" It's generated "books, reading-time, reading-writing, time, writing-books" gone on again. You can see  that. Okay. It's going into sort of repeat mode. This would help probably help if we Did  this a lot more let's put in just something. Okay "Training models with PEFT and LoRA is cool." Let's see. Okay. What will it pick out for that. And you'll find that, some of them.
It will, obviously, it Could pick out keywords, but for  some of them too, it will pick out other things. Now it's interesting. Okay. So it's got training and teaching here hasn't really worked out, PEFT and LoRA, which is to be expected.
And you  can see here that it's got some of its previous   training still in there so you would probably  want to, it looks like that there's some things   related to training models in there. That is  bouncing off. You'd want train this for longer and if you really wanted to  use this as a model, but this gives you just   a good example of how to make a causal language model with find tuning a bigger causal language model with LoRA.
And then you  can use that for something that you particularly   want. It's very easy to play with your dataset put the whole thing together in here. As always, if there's any questions,   please put them in the comments.
If you  found this useful, please click like and   subscribe and feel free to let me know what  you would like to see videos going forward. Bye for now.

자동으로 쉽게 될 줄 알았는데, 결국은 영상 들으면서 오탈자나 오역된 내용들 하나씩 찾아내려니 힘들긴 하네요. 그래도 아예 없이 시작하는 것보다는 훨 좋네요. 좋은 세상!!

반응형