Hugging Face Hub: 모델 찾기 및 사용하기
1. 개요
Hugging Face Hub는 현재 머신러닝을 위한 가장 큰 모델, 데이터셋 및 데모 저장소입니다. 이 글은 필요한 모델을 올바르게 찾는 방법을 배우는 데 도움이 됩니다 (이름을 추측하는 대신), 모델 카드를 읽어 라이선스나 아키텍처를 잘못 사용하는 것을 피하고, 그 다음 두 가지 방법으로 모델을 호출합니다: Python으로 로컬에서 실행하거나 Spring Boot 애플리케이션에서 Inference API를 통해 호출합니다. 이 글을 읽은 후, GPU를 직접 호스팅할 필요 없이 NLP 모델을 Java 서비스에 통합할 수 있습니다.
2. Hugging Face Hub란 무엇인가
Hub는 세 가지 주요 리소스 유형을 저장합니다:
- Models: 미리 학습된 가중치와 사용 방법을 설명하는 모델 카드 포함.
- Datasets: 학습/미세 조정 또는 벤치마크를 위한 데이터.
- Spaces: 브라우저에서 직접 실행되는 데모 (Gradio, Streamlit).
각 모델에는 model_id 형식의 조직/모델-이름이 있습니다. 예: distilbert-base-uncased-finetuned-sst-2-english. model_id는 UI의 표시 이름이 아니라 코드에서 사용할 항목입니다.
3. Hub에서 모델 찾기
3.1. 웹 인터페이스를 통해
Hub 홈페이지에는 task (text-classification, translation, image-segmentation…), library (transformers, sentence-transformers, timm…), license 및 language에 따른 필터가 있습니다. “Most downloads” 또는 “Trending”으로 정렬하면 최신 모델을 선택하는 것보다 더 안정적인 결과를 얻을 수 있습니다. 새로운 모델이 반드시 충분한 사용자 검증을 받았다고 보장할 수 없기 때문입니다.
3.2. huggingface_hub (Python)을 통해
스크립트로 모델을 찾아야 할 때 (예: 요구 사항을 충족하는 가장 작은 모델을 자동으로 선택), HfApi를 사용합니다:
pip install huggingface_hub
from huggingface_hub import HfApi
api = HfApi()
models = api.list_models(
search="sentiment",
library="transformers",
sort="downloads",
direction=-1,
limit=5,
)
for m in models:
print(m.id, m.downloads)
search는 이름/태그의 키워드로 필터링하고, sort="downloads"와 direction=-1은 가장 인기 있는 모델을 맨 위에 정렬하며, limit=5는 결과를 제한합니다. 출력은 다음과 유사합니다:
distilbert-base-uncased-finetuned-sst-2-english 5123456
cardiffnlp/twitter-roberta-base-sentiment-latest 2876543
nlptown/bert-base-multilingual-uncased-sentiment 1987654
...
주의: 다운로드 수가 당신의 문제에 대한 최고의 품질을 의미하지는 않습니다. 그것은 단지 전반적인 인기도를 반영할 뿐입니다. 결정하기 전에 항상 실제 데이터로 테스트하세요.
4. 사용하기 전에 모델 카드 읽기
각 모델에는 모델 카드로 표시되는 README.md 파일이 있으며, 다음을 포함합니다:
- Task 모델이 학습된 작업 (분류, 번역, 텍스트 생성…).
- License:
apache-2.0,mit, 또는cc-by-nc(non-commercial — 상용 제품에 사용할 수 없음). - Gated model: 일부 모델은 로그인이 필요하며 소유자 승인 후에만 로드할 수 있습니다 (일반적으로 큰 또는 민감한 모델).
API를 사용하여 라이선스 및 gated 상태를 빠르게 확인합니다:
from huggingface_hub import model_info
info = model_info("meta-llama/Llama-3.1-8B")
print(info.gated, info.tags)
True ['text-generation', 'license:llama3.1']
gated=True는 개인 토큰이 필요하고 액세스 권한이 부여되었음을 의미합니다. 그렇지 않으면 요청이 401/403 오류를 반환합니다.
5. transformers로 로컬에서 모델 실행
작은 모델의 경우 테스트하는 가장 빠른 방법은 pipeline입니다:
pip install transformers torch
from transformers import pipeline
classifier = pipeline(
"sentiment-analysis",
model="distilbert-base-uncased-finetuned-sst-2-english",
)
result = classifier("Hugging Face Hub makes finding models easy!")
print(result)
[{'label': 'POSITIVE', 'score': 0.9998}]
pipeline은 자동으로 Hub에서 가중치를 로컬 캐시(~/.cache/huggingface)에 로드하고, 해당 토크나이저를 로드하며, list dict 형식으로 결과를 반환합니다. 첫 번째 실행은 모델 파일을 로드해야 하므로 느립니다. 대역폭/디스크가 제한된 환경에 있는 경우 로드하기 전에 Hub 페이지에서 모델 크기를 확인하세요.
6. Spring Boot에서 Inference API를 통해 모델 호출
주 애플리케이션이 Java로 작성된 경우 모델을 직접 호스팅할 필요가 없습니다. Hugging Face는 많은 인기 있는 모델에 대해 Inference API (HTTP)를 제공합니다. 개인 토큰으로 REST를 호출하기만 하면 됩니다.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
huggingface.api-token=${HF_API_TOKEN}
huggingface.model=distilbert-base-uncased-finetuned-sst-2-english
@Service
public class SentimentAnalysisService {
private final RestClient restClient;
private final String model;
public SentimentAnalysisService(RestClient.Builder builder,
@Value("${huggingface.api-token}") String token,
@Value("${huggingface.model}") String model) {
this.model = model;
this.restClient = builder
.baseUrl("https://api-inference.huggingface.co/models")
.defaultHeader("Authorization", "Bearer " + token)
.build();
}
public List<SentimentResult> analyze(String text) {
SentimentResult[][] response = restClient.post()
.uri("/{model}", model)
.body(Map.of("inputs", text))
.retrieve()
.body(SentimentResult[][].class);
return response == null ? List.of() : List.of(response[0]);
}
public record SentimentResult(String label, double score) {}
}
RestClient.Builder는 Spring Boot에서 자동으로 구성되며,baseUrl과Authorization헤더만 설정하면 됩니다.uri("/{model}", model)은.../models/distilbert-base-uncased-finetuned-sst-2-english형식의 URL을 구성합니다.text-classificationtask의 Inference API 응답은 중첩 배열([[{...}]])이므로 반환 유형은SentimentResult[][]입니다.
시도해 봅니다:
List<SentimentAnalysisService.SentimentResult> results =
sentimentAnalysisService.analyze("I love this library!");
[SentimentResult[label=POSITIVE, score=0.9997]]
응답 파싱 테스트
실제 응답이 네트워크에 따라 달라지므로, 실제 API를 호출할 필요 없이 테스트하기 위해 JSON 파싱 부분을 분리해야 합니다:
import com.fasterxml.jackson.databind.ObjectMapper;
import static org.assertj.core.api.Assertions.assertThat;
class SentimentResultParsingTest {
@Test
void shouldParseInferenceApiResponse() throws Exception {
String json = """
[[{"label":"POSITIVE","score":0.9998}]]
""";
ObjectMapper mapper = new ObjectMapper();
SentimentAnalysisService.SentimentResult[][] result =
mapper.readValue(json, SentimentAnalysisService.SentimentResult[][].class);
assertThat(result[0][0].label()).isEqualTo("POSITIVE");
assertThat(result[0][0].score()).isGreaterThan(0.99);
}
}
이 테스트는 SentimentResult 레코드가 네트워크 연결이나 유효한 토큰에 의존하지 않고 label/score 필드를 올바르게 매핑하도록 합니다.
7. 일반적인 오류 및 Inference API를 사용하면 안 되는 경우
- 첫 호출 시 503 Service Unavailable: 모델이 무료 계층 서버에서 아직 “warm up”되지 않았습니다. Hugging Face는
estimated_time필드를 제공합니다. 이를 실제 오류로 취급하는 대신 몇 초 후 재시도하세요. - 429 Too Many Requests: 무료 계층의 레이트 제한이 상당히 엄격합니다. 안정적인 프로덕션 트래픽의 경우 무료 API 대신 Inference Endpoints (전용, 유료)를 고려하세요.
- Gated 모델이지만 아직 승인되지 않음: 토큰이 유효함에도 불구하고 403 오류 발생 — 모델 페이지로 이동하여 “Request access”를 클릭하고 승인을 기다려야 합니다.
- 상업적 목적에 적합하지 않은 라이선스: Llama에서 미세 조정된 많은 모델이나 non-commercial 데이터셋에는 별도의 약관이 있습니다. 제품에 포함하기 전에 모델 카드의 라이선스 부분을 꼼꼼히 읽으세요.
주의: 안정적인 낮은 지연 시간이나 SLA가 필요한 시스템에는 무료 Inference API를 사용하지 마세요. 이는 테스트, 데모 또는 낮은 트래픽에 적합합니다. 대규모 워크로드의 경우,
transformers/text-generation-inference로 로컬 모델을 호스팅하거나 유료 Inference Endpoints를 사용하세요.
8. 결론
Hugging Face Hub는 명확한 프로세스를 제공합니다: UI 또는 huggingface_hub를 통해 모델을 찾고, task/license/gated를 확인하기 위해 모델 카드를 읽은 후, 적절한 사용 방법을 선택합니다. 완전한 제어가 필요할 때는 pipeline으로 로컬에서 실행하고, 기존 Java 시스템에 빠르게 통합하려면 Spring Boot에서 Inference API를 호출합니다. 핵심은 모델을 프로덕션에 배포하기 전에 항상 라이선스와 레이트 제한을 확인하는 것입니다.