프라이빗 환경에서 모델 배포하기

프라이빗 환경에서 모델 배포하기

라이선스를 사용해 Docker와 Kubernetes에서 Cohere의 컨테이너 이미지를 가져와 테스트하는 방법을 알아볼 거예요.

이 문서는 라이선스를 사용해 Cohere의 컨테이너 이미지를 가져오는 방법을 안내하고, Docker와 Kubernetes 이미지를 모두 테스트하는 단계를 제공해요.

시작하기 전에 Cohere가 제공한 라이선스와 이미지 태그가 있는지 확인하세요.

출처: 문서

라이선스로 컨테이너 이미지 가져오기

Cohere는 라이선스로 인증되는 레지스트리를 통해 컨테이너 이미지에 대한 접근을 제공해요. 사용자는 이 이미지를 가져와 필요에 따라 자신의 환경에 복제할 수 있어서, 클러스터 내부에서 런타임 네트워크 접근이 필요 없게 할 수 있어요.

이미지는 proxy.replicated.com 레지스트리를 통해 제공돼요. 이미지를 가져오려면 proxy.replicated.com과 proxy-auth.replicated.com에 대한 방화벽 접근이 열려 있어야 해요. 이 엔드포인트에 대한 자세한 내용은 Replicated 문서에서 확인할 수 있어요.

라이선스로 이미지 가져오기를 테스트하려면 레지스트리용 인증 세부 정보를 포함하도록 docker CLI 구성을 수정하세요. 참고: docker login은 동작하지 않아요.

docker CLI는 단지 예시일 뿐이에요. 자격 증명으로 이미지를 가져올 수 있는 어떤 도구든 라이선스 ID를 사용자 이름과 비밀번호로 모두 구성해 사용할 수 있어요. Skopeo도 레지스트리 간 이미지를 복사하는 데 널리 쓰이는 또 다른 도구로, 이 흐름과 함께 동작해요.

정보 (Info)

다음 명령은 기존 docker CLI 구성을 Cohere의 레지스트리용 인증 세부 정보로 덮어써요. 원한다면 기존 구성을 보존하도록 인증 세부 정보를 수동으로 추가할 수도 있어요.

LICENSE_ID="<YOUR LICENSE ID>"

cat <<EOF > ~/.docker/config.json 
{
    "auths": {
        "proxy.replicated.com": {
            "auth": "$(echo -n "${LICENSE_ID}:${LICENSE_ID}" | base64 | tr -d '\n')"
        }
    }
}
EOF

현재 터미널 세션에서만 docker CLI 구성을 업데이트하고 싶다면 대신 환경 변수를 내보낼 수도 있어요.

LICENSE_ID="<YOUR LICENSE ID>"

export DOCKER_CONFIG=$(mktemp -d)
cat <<EOF > "${DOCKER_CONFIG}/config.json"
{
    "auths": {
        "proxy.replicated.com": {
            "auth": "$(echo -n "${LICENSE_ID}:${LICENSE_ID}" | base64 | tr -d '\n')"
        }
    }
}
EOF

docker CLI를 사용해 인증된 이미지 가져오기가 제대로 동작하는지 검증하세요.

CUSTOMER_TAG=image_tag_from_cohere # provided by Cohere
docker pull $CUSTOMER_TAG

이제 이미지를 어디든 원하는 곳으로 다시 태그하고 복제할 수 있어요. 에어갭(air-gapped) 환경에 적합한 워크플로를 사용하면 돼요.

워크로드 인프라 검증하기

레지스트리에서 이미지를 가져올 수 있게 되면, 테스트 워크로드를 실행해 컨테이너 기능을 검증하세요.

Docker/Containerd

Docker로 컨테이너 이미지를 테스트하려면 다음이 설치된 머신이 있어야 해요.

예시 사용법 (Example Usage)

모델마다 입력이 달라요.

  • Embed 모델은 텍스트 배열을 입력으로 받고 출력으로 임베딩을 반환해요.
  • Rerank 모델은 문서 목록과 쿼리를 입력으로 받고 상위 n개 결과에 대한 관련성 점수를 반환해요 (n 매개변수는 구성 가능).
  • Command 모델은 프롬프트를 입력으로 받고 모델 응답을 반환해요.

이 섹션에서는 Docker 컨테이너에서 각 주요 Cohere 모델을 사용하는 간단한 예시를 제공해요. 시도하다가 curl: (7) Failed to connect to localhost port 8080: Connection refused 같은 오류가 나면 컨테이너가 아직 완전히 시작되지 않은 것이에요. 몇 초 더 기다렸다가 다시 시도하세요.

Docker로 Cohere 모델을 실행하기 위한 Bash 명령

여기 Docker를 통해 Embed v4, Embed Multilingual, Rerank English, Rerank Multilingual, Command 모델을 사용하기 위해 실행할 수 있는 bash 명령이 있어요.

Embed English

docker run -d --rm --name embed-v4 --gpus=1 --net=host $IMAGE_TAG

# wait 5-10 seconds for the container to start

# you can use `curl http://localhost:8080/ping` to check for readiness

curl --header "Content-Type: application/json" --request POST http://localhost:8080/embed --data-raw '{"input_type": "search_query", "texts":["Why are embeddings good"], "embedding_types": ["float"]}'

{"id":"6d54d453-f2c8-44da-aab8-39e3c11d29d5","texts":["Why are embeddings good"],"embeddings":{"float":[[0.033935547,0.06347656,0.020263672,-0.020507812,0.014160156,0.0038757324,-0.07421875,-0.05859375,...

docker stop embed-v4

Embed Multilingual

docker run -d --rm --name multilingual --gpus=1 --net=host $IMAGE_TAG

curl --header "Content-Type: application/json" --request POST http://localhost:8080/embed --data-raw '{"texts": ["testing multilingual embeddings"], "input_type": "classification"}'

{"id":"2eab88e7-5906-44e1-9644-01893a70f1e7","texts":["testing multilingual embeddings"],"embeddings":[[-0.022094727,-0.0121154785,0.037628174,-0.0026988983,-0.0129776,0.013305664,0.005458832,-0.03161621,-0.019744873,-0.026290894,0.017333984,-0.02444458,0.01953125...

docker stop multilingual

Rerank English

docker run -d --rm --name rerank-english --gpus=1 --net=host $IMAGE_TAG

curl --header "Content-Type: application/json" --request POST http://localhost:8080/rerank --data-raw '{"documents": [{"text": "orange"},{"text": "Ottawa"},{"text": "Toronto"},{"text": "Ontario"}],"query": "what is the capital of Canada","top_n": 2}'

{"id":"a547bcc5-a243-42dd-8617-d12a7944c164","results":[{"index":1,"relevance_score":0.9734939},{"index":2,"relevance_score":0.73772544}]}

docker stop rerank-english

Rerank Multilingual

docker run -d --rm --name rerank-multilingual --gpus=1 --net=host $IMAGE_TAG

curl --header "Content-Type: application/json" --request POST http://localhost:8080/rerank --data-raw '{"documents": [{"text": "orange"},{"text": "Ottawa"},{"text": "Toronto"},{"text": "Ontario"}],"query": "what is the capital of Canada","top_n": 2}'

{"id":"8abeacf2-e657-415c-bab3-ac593e67e8e5","results":[{"index":1,"relevance_score":0.6124835},{"index":2,"relevance_score":0.5305253}],"meta":{"api_version":{"version":"2022-12-06"},"billed_units":{"search_units":1}}}

docker stop rerank-multilingual

Command

docker run -d --rm --name command --gpus=2 --net=host $IMAGE_TAG # Number of GPUs may be different depending on the target model

curl --header "Content-Type: application/json" --request POST http://localhost:8080/chat --data-raw '{"query":"Docker is good because"}'

{
  "response_id": "dc182f8d-2db1-4b13-806c-e1bcea17f864",
  "text": "Docker is a powerful tool for developing,..."
  ...
}

curl --header "Content-Type: application/json" --request POST http://localhost:8080/chat --data-raw '{
    "chat_history": [
        {"role": "USER", "message": "Who discovered gravity?"},
        {"role": "CHATBOT", "message": "The man who is widely credited with discovering gravity is Sir Isaac Newton"}
    ],
    "message": "What year was he born?"
}'

{
  "response_id": "7938d788-f800-4f9b-a12c-72a96b76a6d6",
  "text": "Sir Isaac Newton was born in Woolsthorpe, England, on January 4, 1643. He was an English physicist, mathematician, astronomer, and natural philosopher who is widely recognized as one of the most...",
  ...
}

curl --header "Content-Type: application/json" --request POST http://localhost:8080/chat --data-raw '{
    "message": "tell me about penguins",
    "return_chatlog": true,
    "documents": [
      {
        "title": "Tall penguins",
        "snippet": "Emperor penguins are the tallest",
        "url": "http://example.com/foo"
      },
      {
        "title": "Tall penguins",
        "snippet": "Baby penguins are the tallest",
        "url": "https://example.com/foo"
      }
    ],
    "mode": "augmented_generation"
}'

{
  "response_id": "8a9f55f6-26aa-455e-bc4c-3e93d4b0d9e6",
  "text": "Penguins are a group of flightless birds that live in the Southern Hemisphere. There are many different types of penguins, including the Emperor penguin, which is the tallest of the penguin species. Baby penguins are also known to be the tallest species of penguin. \n\nWould you like to know more about the different types of penguins?",
  "generation_id": "65ef2270-46bb-427d-b54c-2e5f4d7daa90",
  "chatlog": "User: tell me about penguins\nChatbot: Penguins are a group of flightless birds that live in the Southern Hemisphere. There are many different types of penguins, including the Emperor penguin, which is the tallest of the penguin species. Baby penguins are also known to be the tallest species of penguin. \n\nWould you like to know more about the different types of penguins? ",
  "token_count": {
    "prompt_tokens": 435,
    "response_tokens": 68,
    "total_tokens": 503
  },
  "meta": {
    "api_version": {
      "version": "2022-12-06"
    },
    "billed_units": {
      "input_tokens": 4,
      "output_tokens": 68
    }
  },
  "citations": [
    {
      "start": 15,
      "end": 40,
      "text": "group of flightless birds",
      "document_ids": [
        "doc_1"
      ]
    },
    {
      "start": 58,
      "end": 78,
      "text": "Southern Hemisphere.",
      "document_ids": [
        "doc_1"
      ]
    },
    {
      "start": 137,
      "end": 152,
      "text": "Emperor penguin",
      "document_ids": [
        "doc_0"
      ]
    },
    {
      "start": 167,
      "end": 174,
      "text": "tallest",
      "document_ids": [
        "doc_0"
      ]
    },
    {
      "start": 238,
      "end": 265,
      "text": "tallest species of penguin.",
      "document_ids": [
        "doc_1"
      ]
    }
  ],
  "documents": [
    {
      "id": "doc_1",
      "snippet": "Baby penguins are the tallest",
      "title": "Tall penguins",
      "url": "https://example.com/foo"
    },
    {
      "id": "doc_0",
      "snippet": "Emperor penguins are the tallest",
      "title": "Tall penguins",
      "url": "http://example.com/foo"
    }
  ]
}

docker stop command

마지막 예시에는 Command 모델이 답변을 근거시키는 데 사용할 수 있는 문서들이 포함되어 있다는 점을 눈치채셨을 거예요. 이 기능은 검색 증강 생성에 속해요.

Kubernetes

Kubernetes에 배포하려면 다음이 설치된 노드가 필요해요.

동일한 이미지를 Kubernetes에 배포하려면 먼저 docker 구성을 이미지 풀 시크릿(image pull secret)으로 변환해야 해요 (자세한 내용은 Kubernetes 문서 참조).

YAML

kubectl create secret generic cohere-pull-secret \
    --from-file=.dockerconfigjson="~/.docker/config.json" \
    --type=kubernetes.io/dockerconfigjson

그렇게 한 다음 환경 변수를 채우고 애플리케이션 매니페스트를 생성하세요.

APP=cohere # or any other name you want to use
IMAGE= <IMAGE_TAG_FROM_COHERE> # replace with the image cohere provided
GPUS= <Number of GPUs for the target model> 

cat <<EOF > cohere.yaml
---
apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    app: ${APP}
  name: ${APP}
spec:
  replicas: 1
  selector:
    matchLabels:
      app: ${APP}
  strategy: {}
  template:
    metadata:
      labels:
        app: ${APP}
    spec:
      imagePullSecrets:
        - name: cohere-pull-secret
      containers:
      - image: ${IMAGE}
        name: ${APP}
        resources:
          limits:
            nvidia.com/gpu: ${GPUS}
---
apiVersion: v1
kind: Service
metadata:
  labels:
    app: ${APP}
  name: ${APP}
spec:
  ports:
  - name: http
    port: 8080
    protocol: TCP
    targetPort: 8080
  selector:
    app: ${APP}
  type: ClusterIP
---
EOF

위 매니페스트는 에어갭 환경을 고려하지 않았어요

에어갭 배포를 위해 이전에 가져온 이미지를 복제한 레지스트리로 이를 변경하세요. 또는 인터넷에 연결된 환경에서 테스트하려면, docker CLI에 대해 이전 단계에서 했던 것처럼 라이선스 ID를 사용자 이름/비밀번호로 사용해 이미지 풀 시크릿을 만드세요. 이미지 가져오기 단계에서 언급한 방화벽 규칙이 열려 있어야 한다는 점을 기억하세요.

다음을 사용해 컨테이너를 배포하고 추론 요청을 실행하세요.

kubectl apply -f cohere.yaml

이 이미지는 수 기가바이트 규모이므로 다운로드에 시간이 걸릴 수 있다는 점에 유의하세요.

파드가 실행되고 나면 대략 다음과 같은 출력이 보일 거예요.

# once the pod is running
kubectl port-forward svc/${APP} 8080:8080

# Forwarding from 127.0.0.1:8080 -> 8080
# Forwarding from [::1]:8080 -> 8080
# Handling connection for 8080

그것을 백그라운드에 계속 실행해 두고, 새 터미널 세션을 열어 테스트 요청을 실행하세요. 다음 몇 섹션에서는 주요 Cohere 모델에 적합한 요청 예시를 포함할 거예요.

예시 사용법 (Example Usage)

여기 Kubernetes를 통해 Embed English, Embed Multilingual, Rerank English, Rerank Multilingual, Command 모델을 사용하기 위해 실행할 수 있는 bash 명령이 있어요.

Embed English

curl --header "Content-Type: application/json" --request POST http://localhost:8080/embed --data-raw '{"texts": ["testing embeddings in english"], "input_type": "classification"}'

# {"id":"2ffe4bca-8664-4456-b858-1b3b15411f2c","embeddings":[[-0.5019531,-2.0917969,-1.6220703,-1.2919922,-0.80029297,1.3173828,1.4677734,-1.7763672,0.03869629,1.9033203...

Embed Multilingual

curl --header "Content-Type: application/json" --request POST http://localhost:8080/embed --data-raw '{"texts": ["testing multilingual embeddings"], "input_type": "classification"}'

# {"id":"2eab88e7-5906-44e1-9644-01893a70f1e7","texts":["testing multilingual embeddings"],"embeddings":[[-0.022094727,-0.0121154785,0.037628174,-0.0026988983,-0.0129776,0.013305664,0.005458832,-0.03161621,-0.019744873,-0.026290894,0.017333984,-0.02444458,0.01953125...

Rerank English

curl --header "Content-Type: application/json" --request POST http://localhost:8080/rerank --data-raw '{"documents": [{"text": "orange"},{"text": "Ottawa"},{"text": "Toronto"},{"text": "Ontario"}],"query": "what is the capital of Canada","top_n": 2}'

# {"id":"a547bcc5-a243-42dd-8617-d12a7944c164","results":[{"index":1,"relevance_score":0.9734939},{"index":2,"relevance_score":0.73772544}]}

Rerank Multilingual

curl --header "Content-Type: application/json" --request POST http://localhost:8080/rerank --data-raw '{"documents": [{"text": "orange"},{"text": "Ottawa"},{"text": "Toronto"},{"text": "Ontario"}],"query": "what is the capital of Canada","top_n": 2}'

# {"id":"8abeacf2-e657-415c-bab3-ac593e67e8e5","results":[{"index":1,"relevance_score":0.6124835},{"index":2,"relevance_score":0.5305253}],"meta":{"api_version":{"version":"2022-12-06"},"billed_units":{"search_units":1}}}

Command

curl --header "Content-Type: application/json" --request POST http://localhost:8080/chat --data-raw '{"query":"Docker is good because"}'

{
  "response_id": "dc182f8d-2db1-4b13-806c-e1bcea17f864",
  "text": "Docker is a powerful tool for developing,..."
  ...
}

curl --header "Content-Type: application/json" --request POST http://localhost:8080/chat --data-raw '{
    "chat_history": [
        {"role": "USER", "message": "Who discovered gravity?"},
        {"role": "CHATBOT", "message": "The man who is widely credited with discovering gravity is Sir Isaac Newton"}
    ],
    "message": "What year was he born?"
}'

{
  "response_id": "7938d788-f800-4f9b-a12c-72a96b76a6d6",
  "text": "Sir Isaac Newton was born in Woolsthorpe, England, on January 4, 1643. He was an English physicist, mathematician, astronomer, and natural philosopher who is widely recognized as one of the most...",
  ...
}

curl --header "Content-Type: application/json" --request POST http://localhost:8080/chat --data-raw '{
    "message": "tell me about penguins",
    "return_chatlog": true,
    "documents": [
      {
        "title": "Tall penguins",
        "snippet": "Emperor penguins are the tallest",
        "url": "http://example.com/foo"
      },
      {
        "title": "Tall penguins",
        "snippet": "Baby penguins are the tallest",
        "url": "https://example.com/foo"
      }
    ],
    "mode": "augmented_generation"
}'

{
  "response_id": "8a9f55f6-26aa-455e-bc4c-3e93d4b0d9e6",
  "text": "Penguins are a group of flightless birds that live in the Southern Hemisphere. There are many different types of penguins, including the Emperor penguin, which is the tallest of the penguin species. Baby penguins are also known to be the tallest species of penguin. \n\nWould you like to know more about the different types of penguins?",
  "generation_id": "65ef2270-46bb-427d-b54c-2e5f4d7daa90",
  "chatlog": "User: tell me about penguins\nChatbot: Penguins are a group of flightless birds that live in the Southern Hemisphere. There are many different types of penguins, including the Emperor penguin, which is the tallest of the penguin species. Baby penguins are also known to be the tallest species of penguin. \n\nWould you like to know more about the different types of penguins? ",
  "token_count": {
    "prompt_tokens": 435,
    "response_tokens": 68,
    "total_tokens": 503
  },
  "meta": {
    "api_version": {
      "version": "2022-12-06"
    },
    "billed_units": {
      "input_tokens": 4,
      "output_tokens": 68
    }
  },
  "citations": [
    {
      "start": 15,
      "end": 40,
      "text": "group of flightless birds",
      "document_ids": [
        "doc_1"
      ]
    },
    {
      "start": 58,
      "end": 78,
      "text": "Southern Hemisphere.",
      "document_ids": [
        "doc_1"
      ]
    },
    {
      "start": 137,
      "end": 152,
      "text": "Emperor penguin",
      "document_ids": [
        "doc_0"
      ]
    },
    {
      "start": 167,
      "end": 174,
      "text": "tallest",
      "document_ids": [
        "doc_0"
      ]
    },
    {
      "start": 238,
      "end": 265,
      "text": "tallest species of penguin.",
      "document_ids": [
        "doc_1"
      ]
    }
  ],
  "documents": [
    {
      "id": "doc_1",
      "snippet": "Baby penguins are the tallest",
      "title": "Tall penguins",
      "url": "https://example.com/foo"
    },
    {
      "id": "doc_0",
      "snippet": "Emperor penguins are the tallest",
      "title": "Tall penguins",
      "url": "http://example.com/foo"
    }
  ]
}

이것은 단지 예시적인 배포일 뿐이라는 점을 기억하세요. 필요에 따라 환경에 맞게 자유롭게 수정하세요.

에어갭 환경에 대한 참고 사항

proxy.replicated.com 레지스트리의 모든 이미지는 에어갭 환경으로 가져와 복사할 수 있어요. 라이선스 ID와 Cohere가 이전에 제공한 단계를 사용해 가져올 수 있어요.

더 알아보기 (Learn more)