Hugging Face Hub: tìm và dùng model
1. Tổng quan
Hugging Face Hub là kho lưu trữ model, dataset và demo lớn nhất hiện nay cho machine learning. Bài này giúp bạn biết cách tìm đúng model cần dùng (thay vì đoán tên), đọc model card để tránh dùng nhầm license hay kiến trúc, rồi gọi model đó theo hai cách: chạy local bằng Python và gọi qua Inference API từ ứng dụng Spring Boot. Đọc xong, bạn tích hợp được một model NLP vào service Java mà không cần tự host GPU.
2. Hugging Face Hub là gì
Hub lưu ba loại tài nguyên chính:
- Models: weights đã train sẵn, kèm model card mô tả cách dùng.
- Datasets: dữ liệu để train/fine-tune hoặc benchmark.
- Spaces: demo chạy trực tiếp trên trình duyệt (Gradio, Streamlit).
Mỗi model có một model_id dạng tổ-chức/tên-model, ví dụ distilbert-base-uncased-finetuned-sst-2-english. model_id này là thứ bạn sẽ dùng trong code, không phải tên hiển thị trên UI.
3. Tìm model trên Hub
3.1. Qua giao diện web
Trang chủ Hub có bộ lọc theo task (text-classification, translation, image-segmentation…), library (transformers, sentence-transformers, timm…), license và language. Sắp xếp theo “Most downloads” hoặc “Trending” thường cho kết quả ổn định hơn là chọn model mới nhất — model mới chưa chắc đã có đủ người dùng kiểm chứng.
3.2. Qua huggingface_hub (Python)
Khi cần tìm model theo script (ví dụ để tự động chọn model nhỏ nhất đạt yêu cầu), dùng 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 lọc theo từ khóa trong tên/tag, sort="downloads" cùng direction=-1 xếp model phổ biến nhất lên đầu, limit=5 giới hạn kết quả. Output tương tự:
distilbert-base-uncased-finetuned-sst-2-english 5123456
cardiffnlp/twitter-roberta-base-sentiment-latest 2876543
nlptown/bert-base-multilingual-uncased-sentiment 1987654
...
Lưu ý: số lượt download không đồng nghĩa với chất lượng cao nhất cho bài toán của bạn — nó chỉ phản ánh mức độ phổ biến chung. Luôn test trên dữ liệu thật trước khi chốt.
4. Đọc model card trước khi dùng
Mỗi model có file README.md hiển thị dưới dạng model card, chứa:
- Task model được train cho (phân loại, dịch, sinh văn bản…).
- License:
apache-2.0,mit, haycc-by-nc(non-commercial — không dùng được cho sản phẩm thương mại). - Gated model: một số model yêu cầu bạn đăng nhập và được chủ sở hữu duyệt trước khi tải (thường là model lớn hoặc nhạy cảm).
Kiểm tra nhanh license và trạng thái gated bằng API:
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 nghĩa là bạn cần token cá nhân và đã được cấp quyền truy cập, nếu không request sẽ trả về lỗi 401/403.
5. Chạy model local bằng transformers
Với model nhỏ, cách nhanh nhất để thử nghiệm là 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 tự tải weights từ Hub về cache local (~/.cache/huggingface), load tokenizer tương ứng, và trả kết quả dạng list dict. Lần chạy đầu tiên sẽ chậm vì phải tải file model — kiểm tra kích thước model trên trang Hub trước khi tải nếu bạn đang ở môi trường giới hạn băng thông/disk.
6. Gọi model từ Spring Boot qua Inference API
Khi ứng dụng chính viết bằng Java, bạn không cần tự host model — Hugging Face cung cấp Inference API (HTTP) cho nhiều model phổ biến. Chỉ cần gọi REST với token cá nhân.
<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được Spring Boot tự cấu hình sẵn, chỉ cần setbaseUrlvà headerAuthorization.uri("/{model}", model)build URL dạng.../models/distilbert-base-uncased-finetuned-sst-2-english.- Response của Inference API cho task
text-classificationlà mảng lồng mảng ([[{...}]]), nên kiểu trả về làSentimentResult[][].
Gọi thử:
List<SentimentAnalysisService.SentimentResult> results =
sentimentAnalysisService.analyze("I love this library!");
[SentimentResult[label=POSITIVE, score=0.9997]]
Test parsing response
Vì response thực tế phụ thuộc network, bạn nên tách riêng phần parse JSON để test không cần gọi API thật:
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);
}
}
Test này đảm bảo record SentimentResult map đúng field label/score mà không phụ thuộc vào kết nối mạng hay token hợp lệ.
7. Lỗi hay gặp và khi nào không nên dùng Inference API
- 503 Service Unavailable khi gọi lần đầu: model chưa được “warm up” trên server free tier. Hugging Face trả kèm field
estimated_time— bạn nên retry sau vài giây thay vì coi đây là lỗi thật. - 429 Too Many Requests: free tier giới hạn rate khá chặt. Với traffic production ổn định, cân nhắc Inference Endpoints (dedicated, trả phí) thay vì free API.
- Model gated nhưng chưa được duyệt: lỗi 403 dù token hợp lệ — cần vào trang model, bấm “Request access” và chờ duyệt.
- License không phù hợp mục đích thương mại: nhiều model fine-tune từ Llama hoặc dataset non-commercial kèm điều khoản riêng, đọc kỹ phần license trên model card trước khi đưa vào sản phẩm.
Lưu ý: không dùng Inference API miễn phí cho hệ thống cần độ trễ thấp ổn định hoặc SLA — nó phù hợp để thử nghiệm, demo, hoặc traffic thấp. Với workload lớn, host model local bằng
transformers/text-generation-inferencehoặc dùng Inference Endpoints trả phí.
8. Kết luận
Hugging Face Hub cho bạn một quy trình rõ ràng: tìm model qua UI hoặc huggingface_hub, đọc model card để kiểm tra task/license/gated, rồi chọn cách dùng phù hợp — chạy local với pipeline khi cần kiểm soát toàn bộ, hoặc gọi Inference API từ Spring Boot khi muốn tích hợp nhanh vào hệ thống Java sẵn có. Điểm mấu chốt là luôn kiểm tra license và giới hạn rate trước khi đưa model vào production.