분류 모델

분류 모델 (Classification Models)

이 문서는 SGLang의 /v1/classify API 엔드포인트 구현을 설명해요. 이 API는 vLLM의 분류 API 형식과 호환되도록 설계됐어요. 텍스트 입력을 분류 모델로 분류하고, 각 클래스의 라벨과 확률을 반환받을 수 있어요.

출처: 문서

본문

개요 (Overview)

분류 API를 사용하면 분류 모델로 텍스트 입력을 분류할 수 있어요. 이 구현은 vLLM 0.7.0 분류 API와 동일한 형식을 따라요.

API 엔드포인트 (API Endpoint)

POST /v1/classify

요청 형식 (Request Format)

{
  "model": "model_name",
  "input": "text to classify"
}

파라미터 (Parameters)

  • model (string, required): 사용할 분류 모델의 이름
  • input (string, required): 분류할 텍스트
  • user (string, optional): 추적을 위한 사용자 식별자
  • rid (string, optional): 추적을 위한 요청 ID
  • priority (integer, optional): 요청 우선순위

응답 형식 (Response Format)

{
  "id": "classify-9bf17f2847b046c7b2d5495f4b4f9682",
  "object": "list",
  "created": 1745383213,
  "model": "jason9693/Qwen2.5-1.5B-apeach",
  "data": [
    {
      "index": 0,
      "label": "Default",
      "probs": [0.565970778465271, 0.4340292513370514],
      "num_classes": 2
    }
  ],
  "usage": {
    "prompt_tokens": 10,
    "total_tokens": 10,
    "completion_tokens": 0,
    "prompt_tokens_details": null
  }
}

응답 필드 (Response Fields)

  • id: 분류 요청의 고유 식별자
  • object: 항상 "list"
  • created: 요청이 생성된 Unix 타임스탬프
  • model: 분류에 사용된 모델
  • data: 분류 결과 배열
    • index: 결과의 인덱스
    • label: 예측된 클래스 라벨
    • probs: 각 클래스의 확률 배열
    • num_classes: 총 클래스 수
  • usage: 토큰 사용량 정보
    • prompt_tokens: 입력 토큰 수
    • total_tokens: 총 토큰 수
    • completion_tokens: 완성 토큰 수 (분류에서는 항상 0)
    • prompt_tokens_details: 추가 토큰 상세 정보 (선택)

사용 예시 (Example Usage)

curl 사용

curl -v "http://127.0.0.1:8000/v1/classify" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "jason9693/Qwen2.5-1.5B-apeach",
    "input": "Loved the new café—coffee was great."
  }'

Python 사용

import requests
import json

# Make classification request
response = requests.post(
    "http://127.0.0.1:8000/v1/classify",
    headers={"Content-Type": "application/json"},
    json={
        "model": "jason9693/Qwen2.5-1.5B-apeach",
        "input": "Loved the new café—coffee was great."
    }
)

# Parse response
result = response.json()
print(json.dumps(result, indent=2))

지원 모델 (Supported Models)

분류 API는 SGLang이 지원하는 모든 분류 모델과 함께 동작해요. 예를 들면:

분류 모델 (다중 클래스)

  • LlamaForSequenceClassification - 다중 클래스 분류
  • Qwen2ForSequenceClassification - 다중 클래스 분류
  • Qwen3ForSequenceClassification - 다중 클래스 분류
  • BertForSequenceClassification - 다중 클래스 분류
  • Gemma2ForSequenceClassification - 다중 클래스 분류

라벨 매핑 (Label Mapping): API는 모델의 config.json 파일에서 id2label 매핑을 자동으로 사용해 일반적인 클래스 이름 대신 의미 있는 라벨 이름을 제공해요. id2label이 없으면 LABEL_0, LABEL_1 등으로 폴백하고, 마지막 수단으로 Class_0, Class_1로 폴백해요.

보상 모델 (단일 점수)

  • InternLM2ForRewardModel - 단일 보상 점수
  • Qwen2ForRewardModel - 단일 보상 점수
  • LlamaForSequenceClassificationWithNormal_Weights - 특수 보상 모델

참고: SGLang의 /classify 엔드포인트는 원래 보상 모델용으로 설계됐지만, 이제 모든 비생성(non-generative) 모델을 지원해요. /v1/classify 엔드포인트는 분류 작업을 위한 표준화된 vLLM 호환 인터페이스를 제공해요.

오류 처리 (Error Handling)

API는 적절한 HTTP 상태 코드와 오류 메시지를 반환해요:

  • 400 Bad Request: 잘못된 요청 형식 또는 필수 필드 누락
  • 500 Internal Server Error: 서버 측 처리 오류

오류 응답 형식:

{
  "error": "Error message",
  "type": "error_type",
  "code": 400
}

구현 세부 사항 (Implementation Details)

분류 API는 다음으로 구현돼요:

  1. Rust Model Gateway: sgl-model-gateway/src/protocols/spec.rs에서 라우팅과 요청/응답 모델 처리
  2. Python HTTP Server: python/sglang/srt/entrypoints/http_server.py에서 실제 엔드포인트 구현
  3. 분류 서비스 (Classification Service): python/sglang/srt/entrypoints/openai/serving_classify.py에서 분류 로직 처리

테스트 (Testing)

제공된 테스트 스크립트로 구현을 검증할 수 있어요:

python test_classify_api.py

호환성 (Compatibility)

이 구현은 vLLM의 분류 API 형식과 호환되므로, 분류 작업에서 vLLM에서 SGLang으로 원활하게 전환할 수 있어요.

더 알아보기