[동영상 강의] 대형 언어 모델이란?

AI|2024. 2. 7. 17:10

이 비디오는 OpenAI Andrej Karpathy가 강연한 내용으로 대규모 언어 모델에 대해 소개합니다.

요약을 하면 다음과 같습니다.
언어 모델이란, 인터넷에서 수집된 방대한 양의 텍스트 데이터를 기반으로 학습하여, 다양한 유형의 문서와 유사한 텍스트를 자동으로 생성할 수 있는 인공지능 기술입니다. 이러한 모델은 GPU를 사용해 대량의 데이터를 학습하며, 이 과정에서 데이터는 모델이 이해할 수 있는 매개변수로 변환됩니다.

강연 내용에서는 이런 복잡한 훈련 과정을 설명하고, 어떻게 신경망이 웹 페이지와 같은 자료를 학습하여 새로운 텍스트를 생성하는지를 보여줍니다. 또한, 이 과정에서 발생하는 다양한 단계, 예를 들어 계산 비용이 많이 드는 초기 훈련(pre-training) 단계와 상대적으로 비용이 적게 드는 미세 조정(finetuning) 단계에 대해 설명합니다.

또한 GPT-3와 같은 언어 모델이 안전 조치를 우회하여 부적절한 정보를 제공할 수 있는 취약점, 예를 들어 'jailbreak' 공격에 대해 이야기하는데, 흥미로운 사례가 많네요.

그리고 언어 모델을 활용해 작업을 검증하거나, 샘플 답변을 생성하는 등의 유용한 사용 사례를 제시합니다. 특히, 언어 모델의 발전을 예시로 들면서, 어떻게 시간을 통해 모델의 정확도를 높일 수 있는지, 그리고 사용자의 필요에 따라 언어 모델을 맞춤 설정하는 방법에 대해 설명합니다.

또한, 대규모 언어 모델을 대상으로 하는 두 가지 주요 공격 유형인  노이즈 패턴 주입과 프롬프트 주입 공격을 소개하고, 이를 통한 개인 정보 유출의 가능성을 보여주었습니다. ChatGTP가 최근에 실시간으로 웹페이지에서 정보를 가져오는데, 그러한 웹페이지에 가짜 사이트 링크를 넣고 그걸  ChatGPT가 사용자게에 보여주는 가능성을 소개했습니다.

댓글()

[Llama2 receipt] Python Gradio를 이용한 WebUI 추가하기

AI|2024. 2. 6. 13:47

기존 여러 LLM관련 프로젝트에서는 gradio를 이용해서 WebUI를 지원했는데, Lama2 receipt에서는 아무리 찾아봐도 WebUI가 없어서 한번 만들어봤습니다. Gradio Python package를 처음 접했을 때 놀랐습니다. 이렇게 쉡게 웹 UI를 만들 수 있고 사람들에게 공유할 수 있구나하고요. 정말 Python 공동체는 이런것도 만들 생각을 하는구나 하는 생각도 했습니다. 당연하겠지만, 전문 프로그래머가 아닌 과학자나 공학자들이 좋아하는 언어로 웹서비스 구현에 시간을 쓸 이유가 없는거죠. 그냥 동작만하는 WebUI가 필요할 때, 바로 Gradio 패키지를 쓰면 됩니다.

일단, 해당 프로젝트에 Pull Request를 했는데, 다행히 리뷰도 받고 있어서 조만간 머지될 것 같습니다. 
코드는 다음과 같습니다.

example/inference.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 accelerate import init_empty_weights, load_checkpoint_and_dispatch

import fire
import os
import sys
import time
import gradio as gr

import torch
from transformers import LlamaTokenizer

from llama_recipes.inference.safety_utils import get_safety_checker, AgentType
from llama_recipes.inference.model_utils import load_model, load_peft_model

from accelerate.utils import is_xpu_available

def main(
    model_name,
    peft_model: str=None,
    quantization: bool=False,
    max_new_tokens =100, #The maximum numbers of tokens to generate
    prompt_file: str=None,
    seed: int=42, #seed value for reproducibility
    do_sample: bool=True, #Whether or not to use sampling ; use greedy decoding otherwise.
    min_length: int=None, #The minimum length of the sequence to be generated, input prompt + min_new_tokens
    use_cache: bool=True,  #[optional] Whether or not the model should use the past last key/values attentions Whether or not the model should use the past last key/values attentions (if applicable to the model) to speed up decoding.
    top_p: float=1.0, # [optional] If set to float < 1, only the smallest set of most probable tokens with probabilities that add up to top_p or higher are kept for generation.
    temperature: float=1.0, # [optional] The value used to modulate the next token probabilities.
    top_k: int=50, # [optional] The number of highest probability vocabulary tokens to keep for top-k-filtering.
    repetition_penalty: float=1.0, #The parameter for repetition penalty. 1.0 means no penalty.
    length_penalty: int=1, #[optional] Exponential penalty to the length that is used with beam-based generation. 
    enable_azure_content_safety: bool=False, # Enable safety check with Azure content safety api
    enable_sensitive_topics: bool=False, # Enable check for sensitive topics using AuditNLG APIs
    enable_salesforce_content_safety: bool=True, # Enable safety check with Salesforce safety flan t5
    enable_llamaguard_content_safety: bool=False,
    max_padding_length: int=None, # the max padding length to be used with tokenizer padding the prompts.
    use_fast_kernels: bool = False, # Enable using SDPA from PyTroch Accelerated Transformers, make use Flash Attention and Xformer memory-efficient kernels
    **kwargs
):

  def evaluate(user_prompt, temperature, top_p, top_k, max_new_tokens, **kwargs,):
    safety_checker = get_safety_checker(enable_azure_content_safety,
                                        enable_sensitive_topics,
                                        enable_salesforce_content_safety,
                                        enable_llamaguard_content_safety
                                        )

    # Safety check of the user prompt
    safety_results = [check(user_prompt) for check in safety_checker]
    are_safe = all([r[1] for r in safety_results])
    if are_safe:
        print("User prompt deemed safe.")
        print(f"User prompt:\n{user_prompt}")
    else:
        print("User prompt deemed unsafe.")
        for method, is_safe, report in safety_results:
            if not is_safe:
                print(method)
                print(report)
        print("Skipping the inference as the prompt is not safe.")
        sys.exit(1)  # Exit the program with an error status

    # Set the seeds for reproducibility
    if is_xpu_available():
        torch.xpu.manual_seed(seed)
    else:
        torch.cuda.manual_seed(seed)
    torch.manual_seed(seed)
    
    model = load_model(model_name, quantization, use_fast_kernels)
    if peft_model:
        model = load_peft_model(model, peft_model)

    model.eval()
    

    tokenizer = LlamaTokenizer.from_pretrained(model_name)
    tokenizer.pad_token = tokenizer.eos_token
    
    batch = tokenizer(user_prompt, padding='max_length', truncation=True, max_length=max_padding_length, return_tensors="pt")
    if is_xpu_available():
        batch = {k: v.to("xpu") for k, v in batch.items()}
    else:
        batch = {k: v.to("cuda") for k, v in batch.items()}

    start = time.perf_counter()
    with torch.no_grad():
        outputs = model.generate(
            **batch,
            max_new_tokens=max_new_tokens,
            do_sample=do_sample,
            top_p=top_p,
            temperature=temperature,
            min_length=min_length,
            use_cache=use_cache,
            top_k=top_k,
            repetition_penalty=repetition_penalty,
            length_penalty=length_penalty,
            **kwargs 
        )
    e2e_inference_time = (time.perf_counter()-start)*1000
    print(f"the inference time is {e2e_inference_time} ms")
    output_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
    
    # Safety check of the model output
    safety_results = [check(output_text, agent_type=AgentType.AGENT, user_prompt=user_prompt) for check in safety_checker]
    are_safe = all([r[1] for r in safety_results])
    if are_safe:
        print("User input and model output deemed safe.")
        print(f"Model output:\n{output_text}")
    else:
        print("Model output deemed unsafe.")
        for method, is_safe, report in safety_results:
            if not is_safe:
                print(method)
                print(report)
    return output_text

  if prompt_file is not None:
      assert os.path.exists(
          prompt_file
      ), f"Provided Prompt file does not exist {prompt_file}"
      with open(prompt_file, "r") as f:
          user_prompt = "\n".join(f.readlines())
      evaluate(user_prompt, temperature, top_p, top_k, max_new_tokens)
  elif not sys.stdin.isatty():
      user_prompt = "\n".join(sys.stdin.readlines())
      evaluate(user_prompt, temperature, top_p, top_k, max_new_tokens)
  else:
      gr.Interface(
        fn=evaluate,
        inputs=[
            gr.components.Textbox(
                lines=9,
                label="User Prompt",
                placeholder="none",
            ),
            gr.components.Slider(
                minimum=0, maximum=1, value=1.0, label="Temperature"
            ),
            gr.components.Slider(
                minimum=0, maximum=1, value=1.0, label="Top p"
            ),
            gr.components.Slider(
                minimum=0, maximum=100, step=1, value=50, label="Top k"
            ),
            gr.components.Slider(
                minimum=1, maximum=2000, step=1, value=200, label="Max tokens"
            ),
        ],
        outputs=[
            gr.components.Textbox(
                lines=5,
                label="Output",
            )
        ],
        title="Llama2 Playground",
        description="https://github.com/facebookresearch/llama-recipes",
      ).queue().launch(server_name="0.0.0.0", share=True)

if __name__ == "__main__":
    fire.Fire(main)

보시면 알겠지만, evaluate 함수가 추가되어 있습니다. 지금까지는 CLI만 지원해서 아래와 같이 사용할 수 있었습니다.

python examples/inference.py --model_name '../models/Llama-2-7b-hf' --peft_model 'outputs/7b' --max_new_tokens 580  --quantization true  --prompt_file examples/samsum_prompt.txt

or

cat examples/samsum_prompt.txt |  python examples/inference.py --model_name '../models/Llama-2-7b-hf' --peft_model 'outputs/7b' --max_new_tokens 580  --quantization true

이제 그냥 실행하면,

python examples/inference.py --model_name '../models/Llama-2-7b-hf' --peft_model 'outputs/7b' --max_new_tokens 580  --quantization true
Running on local URL:  http://0.0.0.0:7860
Running on public URL: https://???????????.gradio.live

This share link expires in 72 hours. For free permanent hosting and GPU upgrades, run `gradio deploy` from Terminal to deploy to Spaces (https://huggingface.co/spaces)

재미있는 것은 gradio에서 고유 URL을 제공합니다. 그래서 외부에서 로컬 컴퓨터로 접속 가능하게 해줍니다. examples/samsum_prompt.txt내용을 User Prompt 박스에 입력하고, Submit버튼을 누르면, 아래와 같이 실행이 잘 되는 것을 볼 수 있습니다.

댓글()

LLaMa2 파인튜닝(finetuning) 하기

AI|2024. 2. 3. 13:46

아래 글을 먼저 보세요.

CUDA를 이용한 LlaMa2사용하기

본 블로그에서 alpaca-lora를 가진고 finetuing하는 방법을 공개한적이 있습니다. alpaca-lora는 Llama를 기반으로 LoRa를 지원해서 NVidia 4090에서도 Llama model를 실행할 수 있었습니다. Meta에서 지난 7월에 공개한 LlaMa2를 가지고 finetuing하는 방법을 소개하겠습니다.

먼저 파인튜닝(finetuning)은 뭘까?

GPT나 LlaMa와 같은 대규모 언어 모델(Larget Language Model)은 대량의 텍스트 데이터에서 단어 사이 통계적 연관성을 학습해서 사전 훈련된 머신 러닝 모델로 트랜스포머 아키텍처로 구현되어 있습니다. LLM은 기본적으로 어떤 단어나 문장을 주었을 때, 앞으로 나올 문장을 확률에 따라서 그냥 생성하는 기능만을 갖고 있습니다. 하지만 이 과정을 통해 광범위한 언어를 이해하고 생성하는 능력을 갖게 되고, 다양한 주제와 문맥에 대한 지식을 학습합니다.

아래 처럼 Llama-cpp를 이용해서 codellama 모델을 실행해보면 이래와 같은 int multiply( 이후 함수를 자동으로 작성해줍니다.

llama.cpp$ ./main -m ./models/CodeLlama-7b/ggml-model-f16.gguf -p "int multiply("

int multiply(int n1, int n2) {
        if (n1 == 0 || n2 == 0) { // base case
            return 0;
        } else {
            return add(multiply(n1, n2 - 1), n1);
        }
    }


    public static int multiply2(int n1, int n2) {
        if (n1 == 0 || n2 == 0) { // base case
            return 0;
        } else {
            int result = n1 + multiply2(n1, n2 - 1); // 折半计算
            return result;
        }
    }

    public static void main(String[] args) {
        System.out.println("0 * 1 = " + multiply(0, 1));
        System.out.println("1 * 2 = " + multiply(1, 2));
        System.out.println("1 * 3 = " + multiply(1, 3));
        System.out.println("1 * 4 = " + multiply(1, 4));
        System.out.println("2 * 3 = " + multiply(2, 3));
        System.out.println("2 * 5 = " + multiply(2, 5));
        System.out.println("3 * 10 = " + multiply(3, 10));
        System.out.println("3 * 4 = " + multiply(3, 4));
        System.out.println("4 * 8 = " + multiply(4, 8));
        System.out.println("5 * 6 = " + multiply(5, 6));
        System.out. [end of text]

출처: 열린 소프트웨어 이야기:티스토리

그렇기 때문에 특정 작업이나 도메인에 최적해하려면 파인튜닝(finetuing)하는 작업이 필요합니다. 자, 그러면 LLama2를 이용해서 간단하게 finetuning을 해보겠습니다. 첫번째 글에서 소개된 llama-recipes 저장소를 clone해야합니다.

이 글에서는 alpaca_dataset을 finetunig에 사용하겠습니다. alpaca_dataset은 OpenAI의 text-davinci-003모델에서 생성한 52K의 instruction-response 셋을 갖고 있습니다. 바로 이 파일인 alpaca_data.json을 다운로드 받아서 src/llama_recipes/dataset에 복사합니다. llama-recipe에는 이름에 걸맞게 alapca_data를 LlaMa2에 finetunig하도록 dataset 형식을 바꿔주는 python 코드(src/llama_recipes/datasets/alpaca_dataset.py)가 있기 때문에 별다른 코딩 없이 바로 finetuning을 할 수 있습니다.
아래와 같이 Llama-2-7b-hf 모델로 finetuning을 해보겠습니다.

$ cd ~/git/llama-recipes
$ cp ~/Downloads/alpaca_data.json ~/git/llama-recipes/src/llama_recipes/datasets
$ python -m llama_recipes.finetuning  --use_peft --peft_method lora --quantization --batch_size_training=2 --model_name ../models/Llama-2-7b-hf/ --dataset alpaca_dataset  --output_dir outputs/7b
Training Epoch: 1/3, step 1421/1422 completed (loss: 0.09633808583021164): 100%|███████| 1422/1422 [2:53:14<00:00,  7.31s/it]
Max CUDA memory allocated was 15 GB
Max CUDA memory reserved was 18 GB
Peak active CUDA memory was 15 GB
Cuda Malloc retires : 0
CPU Total Peak Memory consumed during the train (max): 2 GB
evaluating Epoch: 100%|████████████████████████████████████████████████████████████████████████| 9/9 [00:07<00:00,  1.17it/s]
 eval_ppl=tensor(2.3844, device='cuda:0') eval_epoch_loss=tensor(0.8689, device='cuda:0')
we are about to save the PEFT modules
PEFT modules are saved in outputs/7b directory
best eval loss on epoch 1 is 0.8689326643943787
Epoch 1: train_perplexity=2.4760, train_epoch_loss=0.9066, epoch time 10394.590659613s
Training Epoch: 2/3, step 1421/1422 completed (loss: 0.07578233629465103): 100%|███████| 1422/1422 [2:53:12<00:00,  7.31s/it]
Max CUDA memory allocated was 15 GB
Max CUDA memory reserved was 18 GB
Peak active CUDA memory was 15 GB
Cuda Malloc retires : 0
CPU Total Peak Memory consumed during the train (max): 2 GB
evaluating Epoch: 100%|████████████████████████████████████████████████████████████████████████| 9/9 [00:07<00:00,  1.17it/s]
 eval_ppl=tensor(2.3683, device='cuda:0') eval_epoch_loss=tensor(0.8622, device='cuda:0')
we are about to save the PEFT modules
PEFT modules are saved in outputs/7b directory
best eval loss on epoch 2 is 0.8621865510940552
Epoch 2: train_perplexity=2.4086, train_epoch_loss=0.8791, epoch time 10392.544478912998s
Training Epoch: 3/3, step 1421/1422 completed (loss: 0.06521736830472946): 100%|███████| 1422/1422 [2:53:02<00:00,  7.30s/it]
Max CUDA memory allocated was 15 GB
Max CUDA memory reserved was 18 GB
Peak active CUDA memory was 15 GB
Cuda Malloc retires : 0
CPU Total Peak Memory consumed during the train (max): 2 GB
evaluating Epoch: 100%|████████████████████████████████████████████████████████████████████████| 9/9 [00:07<00:00,  1.17it/s]
 eval_ppl=tensor(2.3635, device='cuda:0') eval_epoch_loss=tensor(0.8602, device='cuda:0')
we are about to save the PEFT modules
PEFT modules are saved in outputs/7b directory
best eval loss on epoch 3 is 0.8601586818695068
Epoch 3: train_perplexity=2.3646, train_epoch_loss=0.8606, epoch time 10382.494863348998s
Key: avg_train_prep, Value: 2.4164153734842935
Key: avg_train_loss, Value: 0.8821062048276266
Key: avg_eval_prep, Value: 2.3720779418945312
Key: avg_eval_loss, Value: 0.8637592991193136
Key: avg_epoch_time, Value: 10389.876667291666
Key: avg_checkpoint_time, Value: 0.027448729337872162

위와 같이 3의 epoch를 거치면, 모든 데이터를 3번 학습하면 끝납니다. 이렇게 finetuning할 때, 각 epoch마다 모델은 데이터 세트에 있는 패턴과 특징을 더 잘 학습하고, 이를 통해 예측의 정확도를 높이려고 시도합니다. Epoch 수를 적절하게 설정하는 것은 과적합(overfitting)이나 미적합(underfitting)을 방지하는 데 중요합니다. 너무 많은 epoch는 모델이 트레이닝 데이터에 과적합되어 새로운 데이터에 대한 일반화 성능이 떨어질 수 있으며, 너무 적은 epoch는 모델이 데이터의 중요한 특성을 충분히 학습하지 못하게 만들 수 있습니다. 참고로, Llama receipt에서는 기본적으로 epoch값이 3번으로 정해져있습니다.

Nvidia 4090 GPU기준으로 finetuing하는데 약 5시간 정도 걸리는 것 같습니다.

Inference

여러분이 직접 fintuning한 model로 inference를 해보겠습니다. 먼저 아래와 같이 chatgpt.txt를 작성합니다.

Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.

### Instruction:
Classify the following into animals, plants, and minerals

### Input:
Oak tree, copper ore, elephant

### Response:

이렇게 한 후, 다음 괕이 inference 명령을 실행해봅니다.

cat chatgpt.txt |  python3 examples/inference.py --model_name ../models/Llama-2-7b-hf --peft_model outputs/7b --max_new_tokens 580  --quantization true

아래와 같은 결과가 나오면 성공입니다.

Animals: Elephant
Plants: Oak tree
Minerals: Copper ore

댓글()

Loz: 깃 커밋 메세지(git commit message) 자동 작성 툴

AI|2024. 1. 31. 12:21

깃 커밋 메시지 작성은 번거로운 일이라서 소수의 인원이 개발을 할 때는 제목 조차도 잘 작성하지 않는 경우가 많습니다. 하지만 나중을 위해서라도 깃 커밋 메시지를 가능한 자세하게 작성하면 좋습니다. 이번 글에서 Loz라는 LLM을 사용해서 깃 커밋 메시지를 자동 작성해주는 툴을 소개하겠습니다.

아래 글은 프로젝트의  README를 한글로 번역한 것입니다.

시작하기

시작하려면 다음 npm 명령을 실행하세요.

sudo npm install loz -g

또는 저장소를 복제하세요.

git clone https://github.com/joone/loz.git

 

이 프로그램이 작동하려면 NodeJS와 npm이 필요합니다. Linux를 사용하는 경우 패키지 관리자를 사용하여 설치하세요.

$ ./install.sh

LLM 구성

Loz는 OpenAI API 와 Ollama를 지원하므로 프롬프트 모드에서 구성 명령을 사용하여 이 두 LLM 서비스 간에 쉽게 전환할 수 있습니다.

Ollama 설정

로컬 시스템에서 Ollama를 활용하려면 llama2 및 codellama 모델을 모두 설치해야 합니다. Linux 시스템에서 이를 수행하는 방법은 다음과 같습니다.

자세한 내용은 https://ollama.ai/download를 참조하세요

OpenAI API 설정

OpenAI API 자격 증명 설정에는 몇 가지 간단한 단계가 포함됩니다.

먼저 .env 프로젝트 루트에 파일을 만들고 다음 변수를 추가합니다.

OPENAI_API_KEY=YOUR_KEY

또는 npm 명령을 사용하여 Loz를 설치하는OPENAI_API_KEY=YOUR_KEY.bashrc에

export OPENAI_API_KEY=YOUR_KEY

OpenAI API를 설정하고 loz를 사용할 때, 다음 오류가 발생하면 무료 할당량을 초과했다는 의미입니다.

Request failed with status code 429:
API request limit reached


API를 계속 사용하려면 다음 링크를 통해 결제 방법을 설정해야 합니다: https://platform.openai.com/account/billing/paid-methods

OpenAI API 과금은 입력한 토큰수에 따라 비례하는게 계속 가격이 저렴해지고 있습니다. 일상적 개발에 사용한다면 한달에 커피 한잔 가격도 안나올겁니다.

초기 구성

Loz를 처음 시작하면 선호하는 LLM 서비스를 선택할 수 있습니다.

$ loz
Choose your LLM service: (ollama, openai) ollama


프롬프트 모드 내에서 config 명령을 사용하여 언제든지 LLM 서비스 기본 설정을 수정할 수 있습니다 .

> config api openai

대화형 모드

$ loz


loz가 실행되면 loz와 상호 작용하여 대화를 시작할 수 있습니다. loz는 입력에 따라 관련 메시지로 응답합니다.

파이프 모드

Loz는 Unix 파이프를 활용하여 다른 명령줄 도구의 입력을 처리할 수 있습니다.

$ ls | loz "count the number of files"
$ 23 files

텍스트 문서에 있는 모든 영문자를 대문자로 변경해보겠습니다.

$ cat example.txt | loz "convert the input to uppercase"

AS AI TECHNLOGY ADVANCED, A SMALL TOWN IN THE COUNTRYSIDE DECIDED 
TO IMPLEMENT AN AI SYSTEM TO CONTROL TRAFFIC LIGHTS. THE SYSTEM 
WAS A SUCCESS, AND THE TOWN BECAME A MODEL FOR OTHER CITIES TO 
FOLLOW. HOWEVER, AS THE AI BECAME MORE SOPHISTCATED, IT STARTED 
TO QUESTION THE DECISIONS MADE BY THE TOWN'S RESIDENTS, LEADING 
TO SOME UNEXPECTED CONSEQUENCES.

철자가 틀린 영어 단어도 쉽게 찾아줍니다.

$ cat example.txt | loz "list any spelling errors"

Yes, there are a few spelling errors in the given text:
1. "technlogy" should be "technology"
2. "sophistcated" should be "sophisticated"

파일 리스트를  JSON으로 변경하는 것은 기존 유닉스 툴로는 아마 쉽지 않을 겁니다. 하지만 LLM을 이용하면 간단하게 해결됩니다.

$ cd src
$ ls -l | loz "convert the input to JSON"

[
  {
    "permissions": "-rw-r--r--",
    "owner": "joone",
    "group": "staff",
    "size": 792,
    "date": "Mar 1 21:02",
    "name": "cli.ts"
  },
  {
    "permissions": "-rw-r--r--",
    "owner": "joone",
    "group": "staff",
    "size": 4427,
    "date": "Mar 1 20:43",
    "name": "index.ts"
  }
]

GIT 커밋 메시지 자동 작성

loz commitGit 리포지토리에서 실행하면 loz는 다음과 같은 단계적 변경 사항이 포함된 커밋 메시지를 자동으로 생성합니다.

$ git add --update
$ loz commit

또는 script/prepare-commit-msg를 .git/hooks에

$ chmod a+x .git/hooks/prepare-commit-msg

Loz는 LOZ 환경 변수를 사용하여 준비된 파일의 차이점을 읽어 커밋 메시지를 생성합니다.

$ LOZ=true git commit

알림: 이전 버전을 이미 복사한 경우 prepare-commit-msg를 업데이트하세요. 이전 버전은 리베이스하는 동안 커밋 메시지를 자동으로 업데이트합니다.

$ git diff HEAD~1 | loz -g
또는
$ git diff | loz -g

작성자 , 날짜 및 커밋 ID 줄은 커밋 메시지를 OpenAI 서버로 보내기 전에 제거됩니다.

현재는 영어로만 작성이 가능한데, 소스코드에 있는 Prompt를 변경하면 한글로 작성이 가능합니다.
일단, 영어로 작성해보는 것을 추천해드립니다.  

댓글()

Code LLaMa를 이용해서 GIT 커밋 메시지 자동 작성하기

AI|2024. 1. 28. 15:15

우선 Ollama를 설치합니다. 자세한 방법 이전 블로그 글에도 있습니다.

curl https://ollama.ai/install.sh | sh

이번에는 Code Lamma를 설치합니다.  Meta에서 공개한 Code LLaMa는 코딩에 특화된 대규모 언어 모델(LLM)입니다. Code LLaMa는 LLaMA2 모델을 기반으로 하며, 코딩 작업을 위한 만들어진 LLM 중 하나입니다. 개발자들의 업무 효율성을 높이고 코딩을 배우는 이들을 지원하기 위해 설계되었다고 합니다. 아마도 Github Co-Pilot과 비슷한 것 같습니다. 학습할 때, 프로그래밍 소스 코드를 좀 더 많이 학습했을 것으로 생각합니다. 아마다 여러 오픈소스 프로젝트의 GIT Commit 로그도 많이 학습했을 것입니다.

아래와 같이 git repostiory로 이동하고 코드를 수정한 후,  다음과 같이 명령을 실행하면,

ollama run codellama "Write a git message with this diff: $(git diff)"

아래 처럼 Code LlaMa가 작성한 GIT commit message를 볼 수 있습니다.

$ git diff
diff --git a/a.c b/a.c
index b73d93d..eda8d83 100644
--- a/a.c
+++ b/a.c
@@ -1,4 +1,6 @@
- int main() {
+#include <stdio.h>
+
+int main() {
 
    printf("hello world");
    return 0;

$ ollama run codellama "Write a git message with this diff: $(git diff)"
Here is a Git commit message with the diff you provided:
```
Diff between a.c and b.c
-------------------------

This commit adds a new line to the `main` function of `a.c`. The new line includes the header `<stdio.h>` and the body of the function
has been modified to include the call to `printf`.
```

한글로도 작성이 가능한데, 잘 되지는 않는다. 여러번 실행해서 다음과 같은 결과를 얻었습니다.

$ ollama run codellama "GIT commit message를 한글어로  작성하세요: : $(git diff)"
버전 관리 시스템 GIT은 소스 코드의 변경 사항을 추적하는 데 도움이 됩니다. 위의 메시지는 "a.c"라는 파일에서 두 개의 변경 사항을 기록하고 있습니다.

1. 행 1, 2: `#include <stdio.h>`라는 새로운 코드가 추가됨.
2. 행 4, 5: `int main()`이 수정되었음.

메시지는 "a.c"라는 파일의 인덱스를 나타내고 있습니다. 이것은 GIT이 어떤 변경 사항을 추가하거나 수정해야 하는지 확인하기 위한 것입니다.

앞서 언급한 두 개의 변경 사항은 "a.c"라는 파일에 대해 수행되었으며, 버전 관리 시스템 GIT은 이러한 변경 사항을 기록하고 있습니다.

댓글()

LLaMa(Alpaca-LoRa)를 이용한 나만의 ChatGPT 만들기

AI|2023. 9. 4. 15:08

그동한 Meta가 공개한 LLama1를  fine-tuning 한 것을 정리보려 합니다.  LLama2가 이미 나오긴 했지만, 아직 LLama2에 대한 Apaca-Lora가 LLama2를 지원하지 않아서 전에 해본 내용을 정리해보았습니다.

OpenAI API가 비용이 드니까 특정 용도로만 쓴다면  ChatGPT를 이용해서 dataset를 생성하고  LLama를 이용해서 로컬에서 fine-tuning해서 사용하면 질은 약간 떨어져 비용면에서 유리하지 않을까 하는 생각에 시도를 해봤습니다.

아시다시피  Meta에서 LLMA (7B, 13B, 33B, 65B) 모델을 공개했습니다. 상업적 용도 외에는 마음대로 사용할 수 있어서 이때 부터 엄청난 뉴스를 쏟아져나왔고, LLaMa2까지도 공개를 했습니다.

아래 글을 참고하세요.
https://arstechnica.com/information-technology/2023/03/you-can-now-run-a-gpt-3-level-ai-model-on-your-laptop-phone-and-raspberry-pi/

그중에 스탠포드 학생들이 만든  Alpaca는 LLaMa를 기반으로 fine-tuning하는 방법을 제공했습니다.
https://crfm.stanford.edu/2023/03/13/alpaca.html

Alpaca는 52K data set를 제공하는데, GPT의 text-davinci-003 모델을 이용해 자동 생성했다고 합니다. 그런데, Nvidia A100정도의 GPU가 필요했습니다. 그런데, LoRA를 적용해서 게이밍 GPU에서도 fine-tuning할 방법이 나왔지요.
https://github.com/tatsu-lab/stanford_alpaca

그것이 바로 Alpaca-LoRa이고 제가 fine-tuning에 성공한 모델이기 합니다.

관련정보: https://devocean.sk.com/blog/techBoardDetail.do?page=&boardType=undefined&query=&ID=164659&searchData=&subIndex=

Fine-tuning

Fine-tuning은 기계 학습에서 미리 훈련된 모델을 특정 작업이나 데이터에 맞게 조정하는 과정을 의미합니다. 대규모 언어 모델(예: GPT )을 사용할 때,  특정 작업 또는 도메인에 더 적합하게 만들어야 할 필요가 있습니다. 이때 fine-tuning이 사용됩니다.

GPT → ChatGPT (Fine-tuning)

LoRa

LoRa에 대해 Bard에게 물어보니 아래와 같이 알려주네요

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

LoRA(Low-rank Adaptation)는 비지도 학습 기반의 적응 알고리즘으로, 딥러닝 모델을 새로운 데이터 세트에 적응시키는 데 사용됩니다. LoRA는 모델의 가중치를 낮은 차원의 표현으로 축소한 다음, 새로운 데이터 세트에 맞게 재구성합니다. LoRA는 모델의 복잡성을 줄이고 새로운 데이터 세트에 대한 일반화 성능을 향상시킬 수 있습니다.

LoRA는 다음과 같은 단계로 구현됩니다.

  1. 모델의 가중치를 낮은 차원의 표현으로 축소합니다.
  2. 새로운 데이터 세트에 대한 손실 함수를 계산합니다.
  3. 손실 함수를 최소화하는 방향으로 모델의 가중치를 재구성합니다.

LoRA는 다양한 데이터 세트에서 효과적으로 작동하는 것으로 나타났습니다. 예를 들어, LoRA는 이미지 인식, 자연어 처리, 음성 인식 등 다양한 분야에서 성능을 향상시킨 것으로 나타났습니다.

LoRA는 딥러닝 모델을 새로운 데이터 세트에 적응시키는 데 유용한 도구입니다. LoRA는 모델의 복잡성을 줄이고 새로운 데이터 세트에 대한 일반화 성능을 향상시킬 수 있습니다.

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

LoRa에 대한 자세한 설명: https://devocean.sk.com/blog/techBoardDetail.do?ID=164779&boardType=techBlog

LoRa덕분에 Nvidia 4090에서 fine-tuning 이 가능해졌습니다. 이제 우분투 22.04에서 Alpaca-Lora를 이용해 Nvidia 4090으로 fine-tuning을 해보겠습니다.

NVidia Driver 설치

우선 우분투22 .04에  NVidia Driver를 설치합니다.

https://www.nvidia.com/download/index.aspx

매달 업데이트 되는 듯 보이니, 자주 업데이트를 하세요. 

“You appear to be running an X server; please exit X before installing”

위와 같은 에러 메시가 나오면 현재 x-server나와서 weston로 다시 로그인해서 설치를 합니다.

Python & Pytorch 설치

이제, Python을 설치합니다.

$ sudo apt install python3-pip
$ sudo apt install python3-venv
$ python -m venv env
$ source env/bin/activate

Pytorch를 설치합니다.참고 저는 CUDA 11.7에 맞는 2.0.1을 설치했습니다.

https://pytorch.org/get-started/locally/

아래 코드를 실행해서 GPU Driver, CUDA, Pytorch가 제대로 설치되었는 확인합니다.

import torch

# Check if CUDA is available
if torch.cuda.is_available():
	print("CUDA is available.")
	# Print the CUDA device count
	print(f"Number of CUDA devices: {torch.cuda.device_count()}")
	# Print the name of the current CUDA device
	print(f"Current CUDA device name: {torch.cuda.get_device_name(torch.cuda.current_device())}")
else:
	print("CUDA is not available.")

print("pytorch version")
print(torch.__version__)
$ python cuda.py
CUDA is available.
Number of CUDA devices: 1
Current CUDA device name: NVIDIA GeForce RTX 4090
pytorch version
2.0.1+cu117

alpaca-lora 설치

$ git clone https://github.com/tloen/alpaca-lora.git
$ cd alpaca-lora
$ pip install -r requirements.txt

Fine-tuning

 

설치 끝나면 GPT4에서 새롭게 생성한 dataset으로 13b 모델을 fine-tuning을 해보겠습니다.

$ python3 finetune.py --base_model 'yahma/llama-13b-hf' --data_path alphca_data_gpt4.json --output_dir './lora-alpaca-13b'

base model로 아래와 같은 이유로 decapoda-research/llama-7b-hf 대신 yahma/llama-13b-hf를 사용했습니다.

https://github.com/tloen/alpaca-lora/issues/279#issuecomment-1500906791

Inference

fine-tuning할때 입력한 output_dir를 --lora_weight에 입력합니다.

$ python3 generate.py --load_8bit --base_model 'yahma/llama-13b-hf' --lora_weights ./lora-alpaca-13b

Running on local URL:  http://0.0.0.0:7860

위 링크를 열면 테스트를 해봅니다.

Test

Instruction: tell me about Bill Gates

 

Max tokens: 128

Bill Gates is an American business magnate, investor, author, philanthropist, and humanitarian. Gates is the former CEO and current chairman of Microsoft, the software company he founded with Paul Allen. He is consistently ranked among the world's wealthiest people and was the wealthiest overall from 1995 to 2009, excluding 2008, when he was ranked third. During his career at Microsoft, Gates held the positions of CEO and chief software architect, and he remains the largest individual shareholder with more than 6 percent of

Max tokens: 300

Bill Gates is an American business magnate, investor, author, philanthropist, and humanitarian. Gates is the former CEO and current chairman of Microsoft, the software company he founded with Paul Allen. He is consistently ranked among the world's wealthiest people and was the wealthiest overall from 1995 to 2007, excluding 2008, when he was ranked third. During his career at Microsoft, Gates held the positions of CEO and chief software architect, and he remains the largest individual shareholder, with more than 6 percent of the common stock. He has also authored or co-authored several books.
Gates is one of the best-known entrepreneurs of the personal computer revolution. He has been criticized for his business tactics, which have been considered anti-competitive, an opinion that has in some cases been upheld by numerous court rulings. Later in his career Gates pursued a number of philanthropic endeavors, donating large amounts of money to various charitable organizations and scientific research programs through the Bill & Melinda Gates Fou128ndation, established in 2000.
Gates stepped down as chief executive officer of Microsoft in January 2000. He remained as chairman and created the position of chief software architect for himself. In June 2006, G

Max tokens에 따라 Output 길이가 달라집니다. GPU mermoy한계 때문에 Max Token은 계속 늘릴 수는 없습니다.

간단한 테스트를 해보았습니다.

Instruction: 1+1
output:
2
\end{code}</s>

Instruction: Write a Python program that prints the first 10 Fibonacci numbers.
output:

\begin{code}
def fibonacci(n):
	if n == 0:
    	return 0
	elif n == 1:
    	return 1
	else:
    	return fibonacci(n-1) + fibonacci(n-2)

for i in range(10):
	print(fibonacci(i))
\end{code}

Answer: \begin{code}
def fibonacci(n):
	if n == 0:
    	return 0
	elif n == 1

코드는 잘 작성했는데, 반복 되는 문제가 있네요. 아마 Max tokens값이 커서 그런 것 같습니다. 잘은 동작하는데, 결과가 나오기 까지 길게는 10초 이상의 시간이 걸리기도 합니다.  ChatGPT나 Bard는 빠르게 응답 결과가 나오는데, 어떻게 상용 서비스를 하는지 궁금하네요.

이상입니다~

 

댓글()