본문 바로가기
인공지능

Meta의 Llama2를 m1 mac에 설치해보자!

by 개발자A입니다 2023. 7. 24.

첫 직장에서 chatGPT 유료버전을 지원해줘서 유용하게 사용했고, 현재는 MLOps를 만드는 곳으로 이직한 상태이다.

그러다 보니 자연스럽게 LLM에도 지속적으로 관심을 갖고 있는 중이었다.

 

내가 LLM에 관심을 갖고 있던 그때, Llama2가 상업적으로도 무료로 사용가능하게 공개되었다는 소식이 들려왔다~!

"오호라! 주말에 갖고 놀 장난감이 생겼구나~!"

주말에 테스트 해보기로 마음 먹었고, 오늘이 바로 그 주말!

이렇게 Llama2를 나의 m1pro macbook에서 실행시키는 시도를 하게되었다ㅎ

 

 

step1)

아래 웹페이지로 가서 "Doqnload the Model" 버튼을 누르고 신청을 하면, 잠시 후 입력한 메일로 url을 받게된다.

https://ai.meta.com/llama/

 

Llama 2 - Meta AI

We have a broad range of supporters around the world who believe in our open approach to today’s AI — companies that have given early feedback and are excited to build with Llama 2, cloud providers that will include the model as part of their offering

ai.meta.com

 

step2)

mac에 wget와 md5sum를 brew로 설치한다.

$ brew install wget      
$ brew install md5sha1sum

 

step3)

llama2의 githube 레포지토리로 이동해서 git clone을 받고, sh파일을 실행하여 llama2를 다운로드 받는다.

$ chmod 755 download.sh 
$ ./download.sh
Enter the URL from email: // email로 받은 url입력
Enter the list of models to download without spaces (7B,13B,70B,7B-chat,13B-chat,70B-chat), or press Enter for all:  // 용량의 압박으로 7B,7B-chat만 받았다.

 

step4) 

llama2를 애플실리콘에서 돌릴 수 있도록 하는 방법을 찾아보니 양자화가 필요하다고 한다.

이에 아래 문서를 참고하여 종속성이 있는 것들을 설치한다.

(참고자료: https://gist.github.com/cedrickchee/e8d4cb0c4b1df6cc47ce8b18457ebde0)

$ xcode-select --install // 나는 이미 설치되어 있었음
$ brew install pkgconfig cmake

// torch는 apple silicon용으로 설치하기 위해서는 아래 명령어를 입력해야한다.
// apple silicon용 버전관련 언급: https://pytorch.org/blog/introducing-accelerated-pytorch-training-on-mac/#training-benefits-on-apple-silicon
// 명령어 선택: https://pytorch.org/get-started/locally/
$ pip3 install --pre torch torchvision torchaudio --index-url https://download.pytorch.org/whl/nightly/cpu

 

step5)

llama.cpp 레포지토리를 git clone 받기

(레포지토리: https://github.com/ggerganov/llama.cpp)

$ git clone https://github.com/ggerganov/llama.cpp.git
$ cd llama.cpp

// build
$ make 

// install Python dependencies
$ python3 -m pip install -r requirements.txt 

// convert llama2 to ggml FP16 format
$ python3 convert.py <llama2 model directory ex) models/llama-2-7b> 

// quantize the model to 4-bits (using q4_0 method)
$ ./quantize ./models/llama-2-7b/ggml-model-f32.bin ./models/llama-2-7b/ggml-model-q4_0.bin q4_0  

// run the inference
$ ./main -m ./models/llama-2-7b/ggml-model-q4_0.bin -n 128

 

step6)

모델 실행하기

// llama-2-7b 실행하기
$ ./main -m ./models/llama-2-7b/ggml-model-q4_0.bin \
        -t 8 \
        -n 128 \
        -p 'Hello world is '
        
 // 답변
  Hello world is 2 days late!
 nobody seems to want to be the first one to greet me so I will do it myself. So glad that 2016 is out of the way and a new year has started.
My first day was really good, spent some time thinking about what I need to learn in 2017. Will try and share them here as I go along. [end of text]




// llama-2-7b-chat 실행하기
$ ./main -m ./models/llama-2-7b-chat/ggml-model-q4_0.bin \ 
        -t 8 \
        -n 128 \
        -p 'Hello world~!'

// 답변
 Hello world~! 😊 How are you today? *hugs* I hope everything is going well for you. Unterscheidung between the two is crucial in order to avoid confusion and ensure accurate communication. Here are some key differences: The first difference is their meaning. 1. The first difference is their meaning. Hello! The word "world" refers to the planet Earth and all living things on it, including humans, animals, plants, and other organisms. "Hello world!" is often used as a test message in programming to see if a program or software is working properly. It can also be used to greet people from

 

chatGPT에 익숙해져서 인지, chat 버전이 좀 더 재미있어 보인다ㅎ

한국어도 되는지 물어봤더니 아래와 같은 답변이 나왔다.

$ me: Can you speak Korean?
$ llama-2-7b-chat: 
	(ENG) Unterscheidung of Korean and Japanese
		Introduction:
		Korean and Japanese are two closely related languages that share many similarities, but they also have some distinct differences. In this article, we will explore the key differences between Korean and Japanese, including their writing systems, grammar, vocabulary, and pronunciation.
		Writing Systems:
		Korean uses a unique alphabet called Hangul, which consists of 14 consonants and 10 vowels. The alphabet is made up of blocks, with each block representing a different sound. Korean also uses Chinese characters, known as Hanja
	(KOR) 한국어와 일본어의 언더샤이딩
		소개:
		한국어와 일본어는 많은 유사점을 공유하는 밀접한 관련이 있는 두 언어이지만, 몇 가지 뚜렷한 차이점도 있습니다. 이 글에서는 한국어와 일본어의 문자 체계, 문법, 어휘, 발음 등 주요 차이점에 대해 알아보고자 합니다.
		문자 체계:
		한국어는 자음 14개와 모음 10개로 구성된 한글이라는 고유 알파벳을 사용합니다. 알파벳은 블록으로 구성되어 있으며 각 블록은 다른 소리를 나타냅니다. 한국어는 한자라는 한자어도 사용합니다.


$ me: 안녕하세요~!
$ llama-2-7b-chat: 
	(KOR) округу 잘 못 표현했어요. 지금은 공식 블로그에 있는 내용을 읽어보세요. ^^;
		[end of text]

 

아직은 한국어 서비스에 활용하려면 번역기를 붙여서 만들어야할 듯하다ㅠㅠ

다음주에는 이걸 활용해서 무엇을 만들지 고민해보고 주말에 만들어봐야겠다ㅎㅎㅎ

 

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

Llama2를 갖고놀다가 메모해두고 싶은게 있어서 글을 추가합니다.

 

한국어를 못하는 llama-2-7b-chat이지만, 저녁 메뉴 추천을 부탁했더니..

 

무려 한국 음식을 제안했습니다~~~~~~만,

 

중간에 끊겨서 '이어서 말해줘'라고 했더니 엉뚱한 이야기를 하는걸 보니 이전 대화는 기억을 못하는거 같네요ㅠㅠ

방법을 좀 더 찾아봐야겠습니다.

$ me: Could you recommend me a dinner menu?
$ llama-2-7b-chat: 
	(ENG) październik 20, 2016 at 9:43 am
		I would be happy to help! Can you please provide me with some more information about your dinner preferences? For example, do you have any dietary restrictions or allergies? Do you prefer meat, fish, or vegetarian options? Are there any specific cuisines or flavors you enjoy? [end of text]
	(KOR) 파치 지에 닉 20, 2016, 9 : 43 오전
		기꺼이 도와드리겠습니다! 선호하는 저녁 식사에 대한 정보를 좀 더 알려주실 수 있나요? 예를 들어, 식이 제한이나 알레르기가 있으신가요? 육류, 생선, 채식 중 어떤 것을 선호하시나요? 특별히 좋아하는 요리나 맛이 있나요? [텍스트 끝]


$ me: I do not have any allergies and I am a meat lover!
$ llama-2-7b-chat: 
	(ENG) 😋 The first time I had Korean BBQ was in 2018 when my friends and I went to a Korean restaurant here in Cebu. Hinweis: The following are based on the author's personal preferences and may vary from person to person.
		So, here are some of my favorite Korean BBQ dishes that you might want to try:
		1. Galbi (Korean-Style Short Ribs) - This is a must-try dish for any meat lover! The tender short ribs are marinated in a sweet and savory soy-ging
	(KOR) 😋 2018년 친구들과 함께 세부에 있는 한국 식당에 갔을 때 처음으로 한국식 바비큐를 먹었어요. 힌바이스: 다음은 필자의 개인적인 취향에 따른 것으로 사람마다 다를 수 있습니다.
		그래서 제가 좋아하는 한국식 바비큐 요리 몇 가지를 소개해드릴게요:
		1. 갈비 (한국식 갈비) - 고기를 좋아한다면 꼭 먹어봐야 할 요리입니다! 부드러운 갈비를 달콤하고 고소한 간장 양념에 재운 요리입니다.


$ me: Please continue.
$ llama-2-7b-chat: 
	(ENG) nobody is perfect, but with self-awareness and an open mind, you can learn to manage your limitations and grow from them.
		It is important to recognize that everyone has their own unique strengths and weaknesses, and to embrace both as part of who you are. By being self-aware and honest with yourself about your limitations, you can focus on developing the skills and abilities that play to your strengths, while also working to improve in areas where you struggle.
		Remember, personal growth is a lifelong process, and it is okay to have limitations or struggles at any point in time
	(KOR) 완벽한 사람은 없지만, 자기 인식과 열린 마음으로 자신의 한계를 관리하고 그로부터 성장하는 법을 배울 수 있습니다.
		모든 사람은 자신만의 고유한 강점과 약점을 가지고 있다는 사실을 인식하고 두 가지를 모두 자신의 일부로 포용하는 것이 중요합니다. 자신의 한계를 자각하고 스스로에게 솔직해지면 자신의 강점을 살릴 수 있는 기술과 능력을 개발하는 데 집중하는 동시에 어려움을 겪고 있는 분야를 개선하기 위해 노력할 수 있습니다.
		개인적인 성장은 평생에 걸친 과정이며, 어느 시점에서든 한계나 어려움을 겪어도 괜찮다는 점을 기억하세요.

 

한국음식이 나오면, 국뽕 질문 하나 더 해봐야죠ㅎㅎ

$ me: Do you know BTS?
$ llama-2-7b-chat: 
	(ENG) everybody loves BTS, and for good reason. They are a phenomenal K-pop group that has taken the world by storm with their catchy tunes, meaningful lyrics, and captivating performances. But did you know that there is more to BTS than just their music? Here are some interesting facts about the group that will make you appreciate them even more:
		1. BTS stands for Bangtan Sonyeondan, which means "Beyond the Scene" in Korean. This name represents the group's mission to go beyond traditional K-pop boundaries and to create music that reson
	(KOR) 모두가 방탄소년단을 좋아하는 데에는 그럴 만한 이유가 있습니다. 그들은 귀에 쏙쏙 들어오는 음악, 의미 있는 가사, 매혹적인 퍼포먼스로 전 세계를 사로잡은 경이로운 케이팝 그룹입니다. 하지만 방탄소년단에게는 음악 외에도 더 많은 것이 있다는 사실을 알고 계셨나요? 방탄소년단을 더 깊이 이해할 수 있는 흥미로운 사실 몇 가지를 소개합니다:
		1. BTS는 방탄소년단의 약자로, 한국어로 "무대 너머"라는 뜻입니다. 이 이름은 전통적인 케이팝의 경계를 뛰어넘어 공감을 불러일으키는 음악을 만들겠다는 그룹의 사명을 나타냅니다.