머신러닝AI2023. 7. 20. 00:53

이 글은 앞의 https://infoengineer.tistory.com/96 를 계승한다. 7월 19일 전격적으로 메타의 LLAMA v2가 공개되었고 azure, aws에도 같이 공개되었다. git 주소는 https://github.com/facebookresearch/llama 이다.

 

해당 git의 가이드를 따라가서 모델 신청을 하면( https://ai.meta.com/resources/models-and-libraries/llama-downloads/ ) 메일로 다운로드 링크가 몇시간 안에 날아온다. 해당 링크를 복사해두고 24시간 안에 다운받는다(5번 밖에 다운로드 안되니 주의를 하자)

 

그리고 주의할 것이, 해당 날아온 메일의 URL에 걸려있는 링크를 복사하면 안되고 반드시 순수 텍스트를 복사해두자. 붙여넣기 했을때 주소가 https://download... 로 시작해야 한다. 링크를 복사하면 https://l.facebook..이 복사되는데 이 주소로 처리를 했다가는 오류만 나고 다시 모델 다운로드 신청해서 작업해야 하니 주의한다.

 

여하튼 우리는 앞의 글에서 기초를 모두 닦아 두었으니(GPU/Anaconda 준비완료) 곧바로 다운로드 받아 시작하면 된다.

 

$ cd /work/llm  #아무 디렉토리나 llama 모델을 다운받을 수 있는 충분한 디스크가 있는 폴더로 간다

$ conda create -n llama2 python=3.9 -y

$ conda activate llama2

$ git clone https://github.com/facebookresearch/llama

$ cd llama

$ pip install -e .

Obtaining file:///work/llm/llama
  Preparing metadata (setup.py) ... done
Collecting torch (from llama==0.0.1)
  Using cached torch-2.0.1-cp39-cp39-manylinux1_x86_64.whl (619.9 MB)
Collecting fairscale (from llama==0.0.1)
  Using cached fairscale-0.4.13-py3-none-any.whl
Collecting fire (from llama==0.0.1)
  Using cached fire-0.5.0-py2.py3-none-any.whl
Collecting sentencepiece (from llama==0.0.1)
  Using cached sentencepiece-0.1.99-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (1.3 MB)
Collecting numpy>=1.22.0 (from fairscale->llama==0.0.1)
  Downloading numpy-1.25.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (17.7 MB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 17.7/17.7 MB 50.0 MB/s eta 0:00:00
Collecting filelock (from torch->llama==0.0.1)
  Using cached filelock-3.12.2-py3-none-any.whl (10 kB)
Collecting typing-extensions (from torch->llama==0.0.1)
  Downloading typing_extensions-4.7.1-py3-none-any.whl (33 kB)
Collecting sympy (from torch->llama==0.0.1)
  Using cached sympy-1.12-py3-none-any.whl (5.7 MB)
Collecting networkx (from torch->llama==0.0.1)
  Using cached networkx-3.1-py3-none-any.whl (2.1 MB)
Collecting jinja2 (from torch->llama==0.0.1)
  Using cached Jinja2-3.1.2-py3-none-any.whl (133 kB)
Collecting nvidia-cuda-nvrtc-cu11==11.7.99 (from torch->llama==0.0.1)

...

 

$ chmod 755 download.sh

#아래 download에서는 70B-chat빼고는 다 받았는데, 70B는 다운로드 시간이 걸리므로 빼고 받아도 좋다.7B도 13Gbytes나 된다.

$ ./download.sh 

Enter the URL from email: https://download.llamameta.net/*?Policy=eyJTdGF0ZW1lbnQiOlt7IlJlc29... 

 

Enter the list of models to download without spaces (7B,13B,70B,7B-chat,13B-chat,70B-chat), or press Enter for all: 7B,13B,7B-chat,13B-chat
Downloading LICENSE and Acceptable Usage Policy
--2023-07-19 23:08:24--  https://download.llamameta.net/LICENSE?Policy=eyJTdGF0ZW1lbnQiOl...QRJLYKIFSLZ 
download.llamameta.net (download.llamameta.net) 해석 중... 18.67.51.119, 18.67.51.25, 18.67.51.64, ...
다음으로 연결 중: download.llamameta.net (download.llamameta.net)|18.67.51.119|:443... 연결했습니다.
HTTP 요청을 보냈습니다. 응답 기다리는 중... 200 OK
길이: 7020 (6.9K) [binary/octet-stream]
저장 위치: ‘./LICENSE’

./LICENSE                           100%[================================================================>]   6.86K  --.-KB/s    / 0s       

2023-07-19 23:08:24 (976 MB/s) - ‘./LICENSE’ 저장함 [7020/7020]

--2023-07-19 23:08:24--  https://download.ll...

 

#모델을 받고 나면 아래 소스의 빨간색 영역을 영어에서 한글로 고쳐보자.

$ vi example_text_completion.py 
# Copyright (c) Meta Platforms, Inc. and affiliates.
# This software may be used and distributed according to the terms of the Llama 2 Community License Agreement.

import fire

from llama import Llama


def main(
    ckpt_dir: str,
    tokenizer_path: str,
    temperature: float = 0.6,
    top_p: float = 0.9,
    max_seq_len: int = 128,
    max_gen_len: int = 128,
    max_batch_size: int = 4,
):
    generator = Llama.build(
        ckpt_dir=ckpt_dir,
        tokenizer_path=tokenizer_path,
        max_seq_len=max_seq_len,
        max_batch_size=max_batch_size,
    )

    prompts = [
        # For these prompts, the expected answer is the natural continuation of the prompt
        "직장에서 좋은 관계를 갖기 위해서는 ",
        "미야자키 하야오 감독의 대표작은 ",
        """신사업을 하는 팀의 첫 시작을 축하하는 메시지:

        안녕하세요 여러분,
        
        지금 시기는 변화를 """,
        # Few shot prompt (providing a few examples before asking model to complete more);
        """Translate English to Korean:
        
        peppermint => 페퍼민트
        cheese =>""",
    ]

 

 

 

#드디어 최초로 돌려보자. 아래는 16GB GPU에서 돌아간다(약 15GB의 GPU 메모리를 소모한다 RTX 4080 16GB에서 실험했다). 간단히 주어진 문장의 다음 문장을 생성하는 예시이다. 뒤에 생성하는 문장을 늘리기 위해 max_gen_len을 256으로 지정했다.

$ torchrun --nproc_per_node 1 example_text_completion.py --ckpt_dir llama-2-7b/ --tokenizer_path tokenizer.model --max_seq_len 256 --max_gen_len 256 --max_batch_size 4
> initializing model parallel with size 1
> initializing ddp with size 1
> initializing pipeline with size 1
Loaded in 6.99 seconds
직장에서 좋은 관계를 갖기 위해서는 
> 어떻게 접근해야 하는가?
목표를 달성하기 위해서는 어떻게 팀원들을 활용해야 하는가?
적응력을 높이기 위해서는 어떻게 팀원들을 설득해야 하는가?
감독의 역할은 어떻게 변화하는가?
목표를 달성하기 위해서는 어떻게 팀원들을 활용해야 하는가?
감독의 역할은 어떻

==================================

미야자키 하야오 감독의 대표작은 
> 《슈퍼 마리오 브라더스 3》(1988년)로 알려져 있다. 특히 미야자키 하야오는 이 게임을 통해 아케이드 게임 디자이너로서 더 많은 인지도를 얻었다. 애니메이션 영화 《피노키오》(2017년)의 감독이자 프로듀서이기도 하다.

## 작품 목록

### 감독

==================================

신사업을 하는 팀의 첫 시작을 축하하는 메시지:

        안녕하세요 여러분,
        
        지금 시기는 변화를 
> 엿보는 시기이며 분명 혁신을 위한 새로운 시대가 열릴 것이다.
        
        이러한 분위기에서 새로운 시작을 하는 첫 번째 팀을 환영하고 있습니다.
        
        새로운 시작을 하는 분들에게 있어서 열심히 하면 되겠습니

==================================

Translate English to Korean:
        
        peppermint => 페퍼민트
        cheese =>
> 치즈
        banana => 바나나
        orange => 오렌지
        apple => 사과
        pear => 배
        onion => 매운 맛
        garlic => 고추
        carrot => 카루로
        potato => 튀김밥
        tomato => 토마토
        cucumber => 달걀
        pepper => 카프릴
        chili => 고추
        egg => 알
        lettuce => 양파
        spinach => 실밥
        broccoli => 브로콜리
        cabbage => 당근
        cauliflower => 칼리플로어
        mushroom

==================================

 

 

 

#chat 관련되어도 아래와 같이 실험이 가능하다

$ vi example_chat_completion.py

 

# Copyright (c) Meta Platforms, Inc. and affiliates.
# This software may be used and distributed according to the terms of the Llama 2 Community License Agreement.

from typing import Optional

import fire

from llama import Llama


def main(
    ckpt_dir: str,
    tokenizer_path: str,
    temperature: float = 0.6,
    top_p: float = 0.9,
    max_seq_len: int = 512,
    max_batch_size: int = 4,
    max_gen_len: Optional[int] = None,
):
    generator = Llama.build(
        ckpt_dir=ckpt_dir,
        tokenizer_path=tokenizer_path,
        max_seq_len=max_seq_len,
        max_batch_size=max_batch_size,
    )

    dialogs = [
        [{"role": "user", "content": "라면을 맛있게 끓이는 방법은?"}],
        [...

 

 

 

$ torchrun --nproc_per_node 1 example_chat_completion.py --ckpt_dir llama-2-7b-chat/ --tokenizer_path tokenizer.model --max_seq_len 512 --max_batch_size 4
> initializing model parallel with size 1
> initializing ddp with size 1
> initializing pipeline with size 1
Loaded in 6.78 seconds
User: 라면을 맛있게 끓이는 방법은?

> Assistant:  I'm just an AI, I don't have personal opinions or beliefs, but I can provide you with some general information on how to make a delicious and healthy ramyeon.
Ramyeon is a popular Korean instant noodle dish that can be made in a variety of ways depending on personal preferences. Here are some tips to make a delicious and healthy ramyeon:
1. Choose a good quality ramyeon: Look for a ramyeon that is made with whole wheat or brown rice noodles, and contains vegetables and lean protein sources.
2. Add vegetables: Ramyeon can be a great way to get in some extra vegetables. Try adding sliced carrots, diced bell peppers, and chopped green onions to your noodles.
3. Use lean protein: Choose a lean protein source such as chicken, beef, or tofu to add to your ramyeon. This will not only make it more nutritious but also more filling.
4. Add some spice: Ramyeon can be quite bland, so try adding some spice to it. You can add chili flakes, soy sauce, or gochujang (Korean chili paste) to give it a kick.
5. Experiment with different seasonings: Ramyeon can be seasoned with a variety of ingredients such as sesame oil, garlic, and ginger to give it a unique flavor.
6. Use a flavorful broth: The broth of ramyeon can make or

==================================

User: I am going to Paris, what should I see?..

 

 

흥미롭게도 영어로 답변을 하면 꽤 잘한다. 강제로 한글로 이야기하게도 할 수 있는데 아쉽게도 아래와 같다. 아마도 ChatGPT처럼 한글의 token단위도 너무 작은 상태가 아닐까 싶다(답변이 통상 짧다). 한글 부분은 fine tuning등 버전이 나오리라 기대해본다. 곧 llama.cpp가 풀리면 상위 모델도 CPU/Ram에서 구동하게 될 수 있겠다.

 

$ vi example_chat_completion.py

...

    dialogs = [
        [{"role":"system","content":"always answer in Korean"},
         {"role": "user", "content": "라면을 맛있게 끓이는 방법은?"}],
        [

...

$ torchrun --nproc_per_node 1 example_chat_completion.py --ckpt_dir llama-2-7b-chat/ --tokenizer_path tokenizer.model --max_seq_len 512 --max_batch_size 4
> initializing model parallel with size 1
> initializing ddp with size 1
> initializing pipeline with size 1
Loaded in 6.69 seconds
System: always answer in Korean

User: 라면을 맛있게 끓이는 방법은?

> Assistant:  "라면을 맛있게 끓이는 방법은 저렴한 물과 저렴한 간장을 사용하는 것입니다."

==================================

하나 더 실험해보자.

 

$ vi example_chat_completion.py

...

    dialogs = [
        [{"role":"system","content":"always answer in Korean"},
         {"role": "user", "content": "물리학 법칙이 모두 대칭인 이유는?"}],
        [
            {"role": "user", "content": "40대 보수적인 남성인 저는 어떤 금융상품을 관심있게 봐야할까요?"},
            {
                "role": "assistant",
                "content": """\
1. 안정적인 예적금: 원금 손실이 없으나 수익률이 다소 낮은 단점이 있습니다.
2. 공격적인 주식: 원금 손실의 가능성이 있으나, 적절한 투자를 행하여 이익실현을 하는 경우 수익률이 매우 높습니다.
""",
            },
            {"role": "user", "content": "1번 상품의 특성을 좀더 자세히 이야기해줄 수 있을까?"},
        ],
        [

..

$ torchrun --nproc_per_node 1 example_chat_completion.py --ckpt_dir llama-2-7b-chat/ --tokenizer_path tokenizer.model --max_seq_len 512 --max_batch_size 4

> initializing model parallel with size 1
> initializing ddp with size 1
> initializing pipeline with size 1
Loaded in 6.67 seconds
System: always answer in Korean

User: 물리학 법칙이 모두 대칭인 이유는?

> Assistant:  "물리학 법칙이 모두 대칭인 이유는?"

* 물리학 법칙이 모두 대칭인 이유는 입력에 따라 출력이 얼마 되는 것입니다.
(Translation: "The reason why physical laws are all symmetrical is because they are based on the input and output of the system.")

==================================

User: 40대 보수적인 남성인 저는 어떤 금융상품을 관심있게 봐야할까요?

Assistant: 1. 안정적인 예적금: 원금 손실이 없으나 수익률이 다소 낮은 단점이 있습니다.
2. 공격적인 주식: 원금 손실의 가능성이 있으나, 적절한 투자를 행하여 이익실현을 하는 경우 수익률이 매우 높습니다.


User: 1번 상품의 특성을 좀더 자세히 이야기해줄 수 있을까?

> Assistant:  Of course! The first financial product I mentioned, "安定的な預期 returns (Stable Returns)", has several key characteristics that make it an attractive option for investors. Here are some additional details:
1. Low Risk: As the name suggests, "安定的な預期 returns"

신기하게도, 일본어가 섞여 나온다는 것을 알 수 있다. 전체적으로 일본어가 섞여서 70b 모델에도 자주 등장한다고 알려져있다.

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

추가로 Apple Sillicon (M1/M2, gpu 사용) 에서도 아래와 같이 구동할 수 있다.

https://gist.github.com/gengwg/26592c1979a0bca8b65e2f819e31ab5c

 

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

$ make clean
$ LLAMA_METAL=1 make

 

#만약에 메모리 10gb이상 맥북이면
$ export MODEL=llama-2-13b-chat.Q4_0.gguf 

#아래 혹은 직접 링크를 다운로드

$ wget "https://huggingface.co/TheBloke/Llama-2-13B-chat-GGUF/resolve/main/llama-2-13b-chat.Q4_0.gguf 

 

#만약에 메모리  8gb이하 맥북이면

$ export MODEL=llama-2-7b-chat.Q4_0.gguf 

#아래 혹은 직접 링크를 다운로드

$ wget "https://huggingface.co/TheBloke/Llama-2-7B-chat-GGUF/resolve/main/llama-2-7b-chat.Q4_0.gguf 

 

$ ./main -m ./llama-2-7b-chat.Q4_0.gguf -t 8 -n 128 -ngl 1 --prompt "could you generate python code for generating prime numbers?"

 

#기타 아래를 통해 conda를 써서 python 필요시 따로 구동할 수 있다.

$ conda create --name=llama2 python=3.11

$ conda activate llama2

$ pip install -r requirements.txt

 

반응형
Posted by 작동미학