LLM을 이용한 웹브라우징 자동화하는 솔루션

AI|2024. 2. 11. 05:55

LLM의 가장 큰 단점이 모델을 만들어진 이후 새로운 지식이나 뉴스에 대한 정보는 모르는 부분입니다. 그래서 최근 정보를 LlaMa2에 물어보면 다음과 같이 대답을 합니다.

> 2024년 1월에 일어나 주요 뉴스를 알려주세요
2024년 1월에 발생한 주요 뉴스는 아직 알려지지 않았습니다. 저는 인공지능 모델이며, 현재 시점에서 미래의 사건을 예측할 수 없습니다. 뉴스는 실제 사건이 발생한 후에 보도되므로, 2024년 1월에 발생한 주요 뉴스는 해당 시기에 가까워질 때까지 알 수 없습니다.

ChatGPT는 실시간 웹브라우징 기능을 지원하는데, 아직 제약적입니다. 우선  Bing으로 검색을 통해 인터넷을 검색하여 최신 정보를 통해 질문에 대한 답변을 제공하는 기능하지만, 유료 사용자만 사용 가능입니다. 브라우징은 하나의 통합된 모델로 통합되어 있으며, 모델 선택기에서 GPT-4를 선택하면 액세스할 수 있습니다

하지만, LLM으로 웹브라우징을 자동화하려는 회사가 있습니다. 바로 Adept AI입니다. 브라우저 뿐만 아니라 모든 응용 앱도 가능하게 하려고 하는 것이 이 회사의 목적인 것 같습니다.

https://www.adept.ai/

 

Adept: Useful General Intelligence

Adept is an ML research and product lab building general intelligence by enabling humans and computers to work together creatively.

www.adept.ai

우리가 일상적으로 사용하는 앱을 자동화해준다면 물건을 사거나 주문을 할 때 매우 편리할 것 같은데, 얼마나 잘 될지는 두고 봐야겠네요.

댓글()

구글 제미니(Gemini) 울트라 1.0 발표

AI|2024. 2. 9. 05:37

드디어 구글에서 ChatGPT4.0 대항마가 나왔습니다.  일단, Bard가 제미니(or 제미나이?)라고 이름이 변경되었고, 유료화 플랜이 나왔네요. 그리고 iOS와 Android로 앱스토어에 올라왔습니다.  다운로드해서 써보니, 아쉬운 부분은 음성 대화는 지원하지 않네요. ChatGPT 앱이 음성대화를 지원해서 영화  Her를 흉내 낼 수 있는데 이 부분은 빨리 개선되어야 할 것 같습니다. 기존 구글 서비스와 통합된 뭔가를 제공한다고 하는데, 기존에 되던 기능이 더 좋아지는 건지 기존 제공되는 것이 유료화되는건지는 알 수가 없네요.
이건 마치 MS 가 Office에  GTP를 통합하는 것과 비슷하네요. 여러  plan 가운데, 가장 비싼 AI Premium을 해야  울트라 1.0 모델을 쓸 수 있네요.  이게 정말 울트라 급인지 써봐야 할 것 같습니다.


https://blog.google/products/gemini/bard-gemini-advanced-app/

댓글()

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

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

댓글()

구글 픽셀 8 Pro 박스 개봉 및 간단 리뷰

기타|2024. 2. 3. 08:02

구글 픽셀 8 Pro를 뒤늦게 구입해서 이쁘게 사진을 찍어봤습니다. 하늘색 모델을 골랐는데, 나름 이쁘긴합니다. 이전 모델 보다 단단한 느낌이 있어서 내구성이 있어 보입니다. 일단한 케이스 없이 써보려고 하는데, 따로 케어 같은 것을 가입하지 않았기 때문에 조심스럽게 써야겠네요. 

 

지난 모델 부터 어댑터가 없었던 것으로 압니다. 이번에도 당연히 없네요. 대신 USB-C to USB 컨버터가 있습니다. 왜 들어있는지는 모르겠습니다.

특히하게 지문 인식이 화면에 위치하고 있는데, 이게 어떻게 동작하는지 참 궁금합니다. 분명 스캐너가 디스플레이에 달려있다는 의미인데, 신기합니다. 지난 모델은 인식이 잘 안되기도 했는데, 이번 모델을 좀 더 인식율을 높인 듯 보입니다.

뒷면에 G 마크는 뭔가 개발자 스러운데, 사실 픽셀폰의 구입 용도는 정확히 개발 용도이므로 저에게는 딱 좋은데, 일반인들에게는 어떤지 모르겠습니다.

기회가 되면 카메라 테스트 해보면 좋을 것 같은데, 잠깐 비교해 보니, 큰 차이는 없고 먼 배경이 좀 더 색감이 더 진하게 느껴져서 좋게는 느껴집니다. 물론 다양한 각도로 비교할 필요는 있습니다.

초기 부팅과 설정 과정을 영상으로 담아봤습니다.

구글 픽셀폰은 듀얼심을 지원해서는 한국심카드를 옆에 꼽고 Google Fi는 다운로드 받아 두 번호를 함께 쓰고 있습니다. 각종 인증 때문에 한국번호로 문자를 받아야 하므로 문자만 한국심카드에 연결해 놓고 데이터와 번호는 미국 번호로 연결해 놓았습니다.
물론 한국에 있으면 전부 한국 번호에 연결해 놓습니다. 이렇게 여러나라를 다닐때, Google Fi가 빛을 발휘하는 것 같습니다. 물론 가격은 다른 저가 통신사에 비해 좀 비싸기 합니다.
기회가 되면 카메라나 다른 소프트웨어 측면도 테스트해볼까 합니다.
자세한 리뷰는 아래 글을 참고하세요:
https://www.clien.net/service/board/use/18456647

구글 픽셀 8 프로 개봉기와 한달 사용 프리뷰 : 클리앙

구글 픽셀 8 프로 개봉기 *이 개봉기와 프리뷰의 모든 사진은 '직접 촬영'한 저작물입니다! (맨 아래 구글 키노트 세장 캡처 제외) 픽셀을 또다시 구매한 이유 과거 픽셀 2를 시작으로, 픽셀 4, 6 프

www.clien.net

 

댓글()

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은 이러한 변경 사항을 기록하고 있습니다.

댓글()