웹사이트 검색

LLM CLI를 사용하여 GPU 드롭릿에 GPT-4o 모델을 배포하는 방법


소개

LLM(대형 언어 모델)의 등장으로 클라우드 인프라에서 이러한 생성적 AI 모델을 실행하는 것이 더욱 실용적이 되고 있습니다. DigitalOcean은 최근 GPU Droplet을 출시했습니다. 이를 통해 개발자는 LLM 교육 및 배포와 같이 계산량이 많은 작업을 효율적으로 실행할 수 있습니다. 이 튜토리얼에서는 LLM CLI를 설정 및 사용하고 명령줄을 사용하여 DigitalOcean GPU Droplet에 OpenAI의 GPT-4o 모델을 배포하는 방법을 배웁니다.

LLM CLI는 원격 API와 사용자 컴퓨터에 설치하고 실행할 수 있는 모델을 통해 대규모 언어 모델과 상호 작용하기 위한 명령줄 유틸리티이자 Python 라이브러리입니다.

전제 조건

시작하기 전에 다음 사항을 확인하세요.

  • DigitalOcean 클라우드 계정.
  • GPU Droplet이 배포되어 실행 중입니다.
  • Linux 명령줄에 대한 지식. 자세히 알아보려면 Linux 명령줄 입문서에 대한 이 가이드를 참조하세요.
  • GPU Droplet에 설치된 LLM CLI 도구.
  • GPT-4o 모델에 액세스하기 위해 설정된 OpenAI API 키입니다.

1단계 - GPU 드롭릿 설정

1.새 프로젝트 만들기 - 클라우드 제어판에서 새 프로젝트를 만들고 GPU Droplet에 연결해야 합니다.

2.GPU 드롭렛 생성 - DigitalOcean 계정에 로그인하고 새 GPU 드롭렛을 생성한 후 OS로 AI/ML 지원을 선택합니다. 이 OS 이미지는 필요한 모든 NVIDIA GPU 드라이버를 설치합니다. GPU Droplet을 생성하는 방법에 대한 공식 문서를 참조할 수 있습니다.

3.인증을 위한 SSH 키 추가 - GPU Droplet으로 인증하려면 SSH 키가 필요하며, SSH 키를 추가하면 터미널에서 GPU Droplet에 로그인할 수 있습니다.

4.GPU 드롭릿 마무리 및 생성 - 위 단계가 모두 완료되면 새 GPU 드롭릿을 마무리하고 생성합니다.

2단계 - 종속성 설치

GPU Droplet이 준비되고 배포되면. 터미널에서 GPU Droplet에 SSH를 통해 연결할 수 있습니다.

ssh root@<your-droplet-ip>

LLM CLI를 사용하려면 GPU Droplet에 Python과 pip를 설치해야 합니다.

sudo apt install python3 python3-pip -y

Ubuntu 기반 GPU Droplet이 최신 상태인지 확인하세요.

sudo apt update && sudo apt upgrade -y

3단계 - LLM CLI 설치

pip를 사용하여 이 CLI 도구를 설치해 보겠습니다.

pip install llm

설치를 확인해 보겠습니다.

llm --version
llm, version 0.16

아래 명령을 사용하여 llm 명령 목록을 가져올 수 있습니다.

llm --help
Usage: llm [OPTIONS] COMMAND [ARGS]...

  Access large language models from the command-line

  Documentation: https://llm.datasette.io/

  To get started, obtain an OpenAI key and set it like this:

      $ llm keys set openai
      Enter key: ...

  Then execute a prompt like this:

      llm 'Five outrageous names for a pet pelican'

Options:
  --version  Show the version and exit.
  --help     Show this message and exit.

Commands:
  prompt*       Execute a prompt
  aliases       Manage model aliases
  chat          Hold an ongoing chat with a model.
  collections   View and manage collections of embeddings
  embed         Embed text and store or return the result
  embed-models  Manage available embedding models
  embed-multi   Store embeddings for multiple strings at once
  install       Install packages from PyPI into the same environment as LLM
  keys          Manage stored API keys for different models
  logs          Tools for exploring logged prompts and responses
  models        Manage available models
  openai        Commands for working directly with the OpenAI API
  plugins       List installed plugins
  replicate     Commands for working with models hosted on Replicate
  similar       Return top N similar IDs from a collection
  templates     Manage stored prompt templates
  uninstall     Uninstall Python packages from the LLM environment

4단계 - API 키 관리

많은 LLM 모델에는 API 키가 필요합니다. 이러한 API 키는 여러 가지 메커니즘을 사용하여 이 도구에 제공될 수 있습니다.

이 튜토리얼에서는 OpenAI의 GPT-4o 모델을 배포하므로 해당 사이트의 API 키 페이지에서 OpenAI의 언어 모델에 대한 API 키를 얻을 수 있습니다.

API 키가 준비되고 저장되면 아래 명령을 사용하여 APi 키를 저장하고 저장합니다.

llm keys set openai

다음과 같이 키를 입력하라는 메시지가 표시됩니다.

Enter key:<paste_your_api_key>

5단계 - LLM CLI를 사용하여 GPT-4o 모델 배포 및 실행

LLM CLI는 OpenAI의 API와 통신하기 위한 기본 플러그인과 함께 제공됩니다. gpt-3.5-turbo 모델을 기본 플러그인으로 사용합니다. 또한 LLM 플러그인을 설치하여 Claude, gpt4all, llama 등과 같은 다른 제공업체의 모델을 사용할 수 있으며, 여기에는 공개 라이선스 모델을 직접 실행할 수도 있습니다. 당신의 컴퓨터.

이 플러그인은 모두 자신의 컴퓨터에서 직접 LLM을 실행하는 데 도움이 됩니다.

사용 가능한 LLM 모델 플러그인 목록을 확인하려면 다음 명령을 사용할 수 있습니다.

llm models

그러면 현재 설치된 모델 목록이 제공됩니다.

OpenAI Chat: gpt-3.5-turbo (aliases: 3.5, chatgpt)
OpenAI Chat: gpt-3.5-turbo-16k (aliases: chatgpt-16k, 3.5-16k)
OpenAI Chat: gpt-4 (aliases: 4, gpt4)
OpenAI Chat: gpt-4-32k (aliases: 4-32k)
OpenAI Chat: gpt-4-1106-preview
OpenAI Chat: gpt-4-0125-preview
OpenAI Chat: gpt-4-turbo-2024-04-09
OpenAI Chat: gpt-4-turbo (aliases: gpt-4-turbo-preview, 4-turbo, 4t)
OpenAI Chat: gpt-4o (aliases: 4o)
OpenAI Chat: gpt-4o-mini (aliases: 4o-mini)
OpenAI Chat: o1-preview
OpenAI Chat: o1-mini
OpenAI Completion: gpt-3.5-turbo-instruct (aliases: 3.5-instruct, chatgpt-instruct)
Anthropic Messages: claude-3-opus-20240229 (aliases: claude-3-opus)
Anthropic Messages: claude-3-sonnet-20240229 (aliases: claude-3-sonnet)
Anthropic Messages: claude-3-haiku-20240307 (aliases: claude-3-haiku)
Anthropic Messages: claude-3-5-sonnet-20240620 (aliases: claude-3.5-sonnet)

llm install 명령(pip install 주변의 얇은 래퍼)을 사용하여 다른 플러그인을 설치할 수 있습니다.

CLI에서 프롬프트 실행

먼저 ChatGPT 3.5(기본값)에서 GPT-4o로 전환합니다. 명령줄에서 직접 쿼리하여 상호 작용을 시작할 수 있습니다. 예를 들어 모델에게 다음과 같은 질문을 해보세요.

llm -m gpt-4o "What is DigitalOcean GPU Droplet?"
DigitalOcean GPU Droplets are specialized cloud-based virtual machines designed to handle high-performance computing tasks that require GPU acceleration. These Droplets are equipped with powerful graphics processing units (GPUs) that excel at parallel processing tasks, making them ideal for applications such as machine learning, data analysis, scientific computing, and rendering tasks that require significant computational power.

With GPU Droplets, users can leverage the processing capability of GPUs to speed up tasks that would otherwise take a long time on standard CPU-based instances. DigitalOcean provides these GPU instances with various configurations, allowing users to select the number of GPUs and the specific type of GPU that suits their workload requirements.

The key features and benefits of DigitalOcean GPU Droplets include:

1. **High Performance**: Access to powerful GPUs which are optimized for intensive computational tasks.

2. **Flexible Pricing**: Pay-as-you-go pricing model allows users to scale resources up or down based on demand.

3. **Scalability**: Easily scale GPU-powered compute resources according to the needs of your application.

4. **Integration and Ease of Use**: Easy integration with other DigitalOcean products and services, providing a unified cloud infrastructure handling both compute and storage needs.

5. **Developer-Friendly**: DigitalOcean's intuitive dashboard and developer-friendly infrastructure make it simpler for developers to deploy and manage GPU-intensive applications.

참고: LLM CLI를 사용하여 프롬프트를 실행하는 기본 구문은 llm ""입니다. --model <모델 이름>을 전달하여 프롬프트와 함께 다른 모델을 사용할 수 있습니다.

예를 들어 표준 입력으로 프롬프트를 보낼 수도 있습니다. 텍스트를 표준 입력으로 보내고 인수를 제공하는 경우 결과 프롬프트는 파이프된 내용과 인수로 구성됩니다.

예를 들어, llm 명령을 파이프하여 Python 스크립트나 파일의 코드 조각을 설명하도록 요청할 수 있습니다.

cat factorial.py | llm "Explain this code and find any bugs"
The code provided is a Python implementation of a recursive function to calculate the factorial of a non-negative integer. Here's a breakdown of how the code works along with potential issues:

### Code Explanation:

1. **Function Definition**:
   - `def factorial(n):` defines a function named `factorial` that takes one argument `n`.

2. **Base Case**:
   - The first `if` statement `if n == 0 or n == 1:` checks whether `n` is either 0 or 1. The factorial of both 0 and 1 is 1, so if this condition is true, the function returns 1.

3. **Recursive Case**:
   - The `else:` clause is executed if `n` is greater than 1. The function calls itself recursively with the argument `n - 1` and multiplies the result by `n`. This recursive calling continues until it reaches the base case.

4. **Example Usage**:
   - The code asks the user to enter a number, converts that input into an integer using `int()`, and then prints the factorial of the given number by calling the `factorial` function.

### Bug and Issues:

1. **Input Validation**:
   - The code does not handle invalid inputs, such as negative numbers or non-integer values. Factorial is defined only for non-negative integers. If the user enters a negative integer or a non-integer (such as a string), the program will either return a stack overflow error (for negative numbers leading to infinite recursion) or crash with a `ValueError` for non-integer inputs.
   
   To fix this, you could add input validation to ensure `n` is a non-negative integer:
   while True:
       try:
           number = int(input("Enter a non-negative integer: "))
           if number < 0:
               print("Please enter a non-negative integer.")
           else:
               break
       except ValueError:
           print("Invalid input. Please enter a valid integer.")

기본적으로 도구는 실행할 때마다 새로운 대화를 시작합니다. 하지만 -c/--continue 옵션을 전달하여 이전 대화를 계속하도록 선택할 수 있습니다.

llm "Give me more ways to optimize the code" -c
Certainly! There are several ways to optimize the code for calculating the factorial. Here are some approaches, each with its own advantages:

### 1. Iterative Approach

The iterative approach is generally more efficient in terms of memory usage compared to the recursive approach:


def factorial(n):
    result = 1
    for i in range(2, n + 1):
        result *= i
    return result

### 2. Memoization

Using memoization can help store previously computed factorials to reduce redundant calculations. This is particularly useful if you're computing factorials of multiple numbers:


memo = {0: 1, 1: 1}  # Base case

def factorial(n):
    if n in memo:
        return memo[n]
    else:
        memo[n] = n * factorial(n - 1)
        return memo[n]


### 3. Using Python's Built-in Functions

Python has a built-in function for calculating factorials in the `math` module, which is highly optimized:

import math

number = int(input("Enter a non-negative integer: "))
print(f"The factorial of {number} is {math.factorial(number)}")

시스템에서 LLM CLI를 사용하여 Generative AI 애플리케이션을 상호 작용, 구축 및 배포하는 다양한 사용 사례가 있습니다. 여기에서 자세한 내용을 확인할 수 있습니다.

결론

이 가이드를 따르면 DigitalOcean GPU Droplet에서 LLM CLI를 사용하여 OpenAI GPT-4o 모델을 성공적으로 배포했습니다. 이제 콘텐츠 생성, 챗봇, 자연어 처리 등 고성능 언어 모델이 필요한 다양한 애플리케이션에 이 설정을 사용할 수 있습니다.

LLM CLI가 지원하는 다른 모델을 자유롭게 실험해 보거나 여러 모델을 실행하거나 GPU Droplet의 리소스를 늘려 배포를 확장해 보세요.

관련기사: