Hugging Face 완벽 가이드 - Transformers, Datasets, Hub 활용법

Hugging Face란?

Hugging Face는 자연어 처리(NLP)와 머신러닝을 위한 오픈소스 플랫폼입니다. 2016년 설립된 이후 AI 커뮤니티의 중심이 되어, 사전 학습된 모델, 데이터셋, 도구를 공유하고 협업할 수 있는 생태계를 만들었습니다.

Hugging Face의 핵심 구성 요소

  • Transformers: 사전 학습된 모델을 쉽게 사용할 수 있는 라이브러리
  • Datasets: 다양한 데이터셋을 쉽게 로드하고 처리하는 라이브러리
  • Hub: 모델, 데이터셋, 데모를 공유하는 플랫폼
  • Tokenizers: 빠르고 효율적인 토크나이저 라이브러리
  • Accelerate: 분산 학습을 쉽게 만드는 라이브러리
  • Spaces: AI 데모를 호스팅하는 서비스
  • AutoTrain: 코드 없이 모델을 학습할 수 있는 도구

왜 Hugging Face인가?

  • 쉬운 사용: 몇 줄의 코드로 최신 AI 모델 사용 가능
  • 방대한 모델 허브: 100,000개 이상의 사전 학습된 모델
  • 활발한 커뮤니티: 전 세계 AI 연구자와 개발자들의 협업
  • 통합성: PyTorch, TensorFlow, JAX 모두 지원
  • 무료: 대부분의 기능을 무료로 사용 가능

1. 설치 및 환경 설정

필수 패키지 설치

# Transformers 라이브러리
pip install transformers

# PyTorch와 함께 설치 (권장)
pip install transformers torch

# TensorFlow와 함께 설치
pip install transformers tensorflow

# 모든 기능 설치
pip install transformers[torch]

# Datasets 라이브러리
pip install datasets

# 추가 유틸리티
pip install sentencepiece # 일부 모델에 필요
pip install accelerate # 분산 학습용
pip install bitsandbytes # 양자화용

Hugging Face Hub 계정 설정

# Hugging Face CLI 설치
pip install huggingface_hub

# 로그인 (토큰 필요)
huggingface-cli login

# 또는 Python에서
from huggingface_hub import login
login(token="your-token-here")

토큰은 Hugging Face Settings에서 생성할 수 있습니다.

2. Transformers 라이브러리 기본

2.1 파이프라인 - 가장 쉬운 방법

파이프라인은 전처리, 추론, 후처리를 자동으로 처리합니다.

from transformers import pipeline

# 감정 분석
classifier = pipeline("sentiment-analysis")
result = classifier("I love Hugging Face!")
print(result)
# [{'label': 'POSITIVE', 'score': 0.9998}]

# 여러 문장 처리
results = classifier([
"I love this!",
"I hate this!",
"This is okay."
])
for result in results:
print(result)

2.2 다양한 태스크

# 텍스트 생성
generator = pipeline("text-generation", model="gpt2")
result = generator("Once upon a time", max_length=50, num_return_sequences=2)
print(result)

# 질의응답
qa_pipeline = pipeline("question-answering")
context = "Hugging Face is a company based in New York and Paris."
question = "Where is Hugging Face based?"
result = qa_pipeline(question=question, context=context)
print(result)
# {'score': 0.98, 'start': 39, 'end': 58, 'answer': 'New York and Paris'}

# 요약
summarizer = pipeline("summarization")
text = """
The Hugging Face Hub is a platform with over 120,000 models,
20,000 datasets, and 50,000 demo apps (Spaces), all open source
and publicly available, in an online platform where people can
easily collaborate and build ML together.
"""
summary = summarizer(text, max_length=50, min_length=10)
print(summary)

# 번역
translator = pipeline("translation_en_to_fr")
result = translator("Hello, how are you?")
print(result)
# [{'translation_text': 'Bonjour, comment allez-vous?'}]

# 개체명 인식 (NER)
ner = pipeline("ner", grouped_entities=True)
result = ner("My name is John and I live in New York.")
print(result)

# 제로샷 분류
classifier = pipeline("zero-shot-classification")
result = classifier(
"This is a course about Python programming.",
candidate_labels=["education", "politics", "business"]
)
print(result)

# 이미지 분류
image_classifier = pipeline("image-classification")
result = image_classifier("path/to/image.jpg")
print(result)

# 음성 인식
transcriber = pipeline("automatic-speech-recognition")
result = transcriber("audio.mp3")
print(result)

2.3 특정 모델 지정

# 한국어 감정 분석
classifier = pipeline(
"sentiment-analysis",
model="matthewburke/korean_sentiment"
)

# GPT-3.5 스타일 모델
generator = pipeline(
"text-generation",
model="meta-llama/Llama-2-7b-chat-hf"
)

# BERT 기반 질의응답
qa = pipeline(
"question-answering",
model="deepset/roberta-base-squad2"
)

3. 모델과 토크나이저 사용

3.1 기본 사용법

from transformers import AutoTokenizer, AutoModel

# 모델과 토크나이저 로드
model_name = "bert-base-uncased"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModel.from_pretrained(model_name)

# 텍스트 토크나이징
text = "Hello, Hugging Face!"
inputs = tokenizer(text, return_tensors="pt")
print(inputs)
# {'input_ids': tensor([[...]]), 'attention_mask': tensor([[...]])}

# 모델 추론
outputs = model(**inputs)
print(outputs.last_hidden_state.shape)
# torch.Size([1, 6, 768])

3.2 토크나이저 상세 사용법

# 단일 문장
tokens = tokenizer.tokenize("Hello, world!")
print(tokens)
# ['hello', ',', 'world', '!']

# ID로 변환
ids = tokenizer.convert_tokens_to_ids(tokens)
print(ids)

# 디코딩
decoded = tokenizer.decode(ids)
print(decoded)
# "hello, world!"

# 배치 처리
texts = ["First sentence.", "Second sentence."]
batch = tokenizer(
texts,
padding=True, # 패딩 추가
truncation=True, # 최대 길이로 자르기
max_length=128,
return_tensors="pt" # PyTorch 텐서 반환
)

# 어텐션 마스크 확인
print(batch["attention_mask"])

3.3 다양한 모델 타입

from transformers import (
AutoModelForSequenceClassification,
AutoModelForQuestionAnswering,
AutoModelForTokenClassification,
AutoModelForCausalLM,
AutoModelForSeq2SeqLM
)

# 분류 모델
classification_model = AutoModelForSequenceClassification.from_pretrained(
"distilbert-base-uncased-finetuned-sst-2-english"
)

# 질의응답 모델
qa_model = AutoModelForQuestionAnswering.from_pretrained(
"deepset/roberta-base-squad2"
)

# 토큰 분류 (NER)
ner_model = AutoModelForTokenClassification.from_pretrained(
"dslim/bert-base-NER"
)

# 텍스트 생성 (GPT 스타일)
gpt_model = AutoModelForCausalLM.from_pretrained("gpt2")

# Seq2Seq (번역, 요약)
t5_model = AutoModelForSeq2SeqLM.from_pretrained("t5-small")

3.4 추론 예제

import torch

# 감정 분석 예제
text = "I love this product!"
inputs = tokenizer(text, return_tensors="pt")

with torch.no_grad():
outputs = classification_model(**inputs)

logits = outputs.logits
predictions = torch.argmax(logits, dim=-1)
print(f"Prediction: {predictions.item()}") # 0 or 1

# 확률 계산
probabilities = torch.softmax(logits, dim=-1)
print(f"Probabilities: {probabilities}")

4. 파인튜닝 (Fine-tuning)

4.1 데이터셋 준비

from datasets import load_dataset

# Hugging Face Hub에서 데이터셋 로드
dataset = load_dataset("glue", "mrpc")
print(dataset)

# 데이터셋 구조 확인
print(dataset["train"][0])
# {'sentence1': '...', 'sentence2': '...', 'label': 1}

# 커스텀 데이터셋
from datasets import Dataset

data = {
"text": ["I love this!", "I hate this!", "It's okay."],
"label": [1, 0, 2]
}
custom_dataset = Dataset.from_dict(data)

4.2 데이터 전처리

def preprocess_function(examples):
return tokenizer(
examples["sentence1"],
examples["sentence2"],
truncation=True,
padding="max_length",
max_length=128
)

# 전체 데이터셋에 적용
tokenized_dataset = dataset.map(preprocess_function, batched=True)

4.3 Trainer를 사용한 파인튜닝

from transformers import Trainer, TrainingArguments
from transformers import AutoModelForSequenceClassification
import numpy as np
from datasets import load_metric

# 모델 로드
model = AutoModelForSequenceClassification.from_pretrained(
"bert-base-uncased",
num_labels=2
)

# 평가 메트릭 정의
metric = load_metric("accuracy")

def compute_metrics(eval_pred):
logits, labels = eval_pred
predictions = np.argmax(logits, axis=-1)
return metric.compute(predictions=predictions, references=labels)

# 학습 설정
training_args = TrainingArguments(
output_dir="./results",
evaluation_strategy="epoch",
learning_rate=2e-5,
per_device_train_batch_size=16,
per_device_eval_batch_size=16,
num_train_epochs=3,
weight_decay=0.01,
logging_dir="./logs",
logging_steps=10,
save_strategy="epoch",
load_best_model_at_end=True,
)

# Trainer 초기화
trainer = Trainer(
model=model,
args=training_args,
train_dataset=tokenized_dataset["train"],
eval_dataset=tokenized_dataset["validation"],
compute_metrics=compute_metrics,
)

# 학습 시작
trainer.train()

# 평가
results = trainer.evaluate()
print(results)

# 모델 저장
trainer.save_model("./my-finetuned-model")

4.4 커스텀 학습 루프

from torch.utils.data import DataLoader
from transformers import AdamW, get_scheduler

# DataLoader 생성
train_dataloader = DataLoader(
tokenized_dataset["train"],
shuffle=True,
batch_size=8
)

# 옵티마이저
optimizer = AdamW(model.parameters(), lr=5e-5)

# 학습률 스케줄러
num_epochs = 3
num_training_steps = num_epochs * len(train_dataloader)
lr_scheduler = get_scheduler(
"linear",
optimizer=optimizer,
num_warmup_steps=0,
num_training_steps=num_training_steps
)

# 학습 루프
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)

for epoch in range(num_epochs):
model.train()
for batch in train_dataloader:
batch = {k: v.to(device) for k, v in batch.items()}

outputs = model(**batch)
loss = outputs.loss
loss.backward()

optimizer.step()
lr_scheduler.step()
optimizer.zero_grad()

print(f"Epoch {epoch + 1} completed")

5. Datasets 라이브러리

5.1 데이터셋 로드

from datasets import load_dataset

# Hub에서 로드
dataset = load_dataset("squad")
dataset = load_dataset("imdb")
dataset = load_dataset("wmt16", "de-en")

# 특정 설정 로드
dataset = load_dataset("glue", "mrpc")

# 스트리밍 모드 (큰 데이터셋)
dataset = load_dataset("wikipedia", "20220301.en", streaming=True)

# 로컬 파일에서 로드
dataset = load_dataset("csv", data_files="my_data.csv")
dataset = load_dataset("json", data_files="my_data.json")
dataset = load_dataset("parquet", data_files="my_data.parquet")

5.2 데이터셋 조작

# 데이터셋 정보
print(dataset)
print(dataset["train"].features)
print(len(dataset["train"]))

# 인덱싱
print(dataset["train"][0])
print(dataset["train"][:5])

# 필터링
filtered = dataset["train"].filter(lambda x: x["label"] == 1)

# 매핑
def uppercase_text(example):
return {"text": example["text"].upper()}

uppercase_dataset = dataset.map(uppercase_text)

# 셔플
shuffled = dataset["train"].shuffle(seed=42)

# 선택
small_dataset = dataset["train"].select(range(1000))

# 분할
train_test = dataset["train"].train_test_split(test_size=0.2)

# 컬럼 추가/제거
dataset = dataset.map(lambda x: {"length": len(x["text"])})
dataset = dataset.remove_columns(["length"])

# 정렬
sorted_dataset = dataset.sort("length")

5.3 데이터셋 저장 및 로드

# 디스크에 저장
dataset.save_to_disk("./my_dataset")

# 로드
from datasets import load_from_disk
dataset = load_from_disk("./my_dataset")

# CSV로 내보내기
dataset["train"].to_csv("train.csv")

# JSON으로 내보내기
dataset["train"].to_json("train.json")

# Pandas로 변환
df = dataset["train"].to_pandas()

5.4 커스텀 데이터셋 생성

from datasets import Dataset, DatasetDict

# 딕셔너리에서 생성
data = {
"text": ["First text", "Second text", "Third text"],
"label": [0, 1, 0]
}
dataset = Dataset.from_dict(data)

# Pandas에서 생성
import pandas as pd

df = pd.DataFrame({
"text": ["First", "Second"],
"label": [0, 1]
})
dataset = Dataset.from_pandas(df)

# 여러 분할 생성
dataset_dict = DatasetDict({
"train": Dataset.from_dict(train_data),
"test": Dataset.from_dict(test_data)
})

# Hub에 업로드
dataset.push_to_hub("username/my-dataset")

6. Hugging Face Hub 활용

6.1 모델 검색 및 다운로드

from huggingface_hub import HfApi, list_models

api = HfApi()

# 모델 검색
models = list(list_models(filter="text-classification", sort="downloads"))
for model in models[:5]:
print(f"{model.modelId}: {model.downloads} downloads")

# 모델 정보 가져오기
model_info = api.model_info("bert-base-uncased")
print(model_info.tags)
print(model_info.pipeline_tag)

# 모델 다운로드
from huggingface_hub import snapshot_download

model_path = snapshot_download(
repo_id="gpt2",
cache_dir="./models"
)

6.2 모델 업로드

from transformers import AutoModel, AutoTokenizer

# 모델 저장
model = AutoModel.from_pretrained("bert-base-uncased")
tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")

model.save_pretrained("./my-model")
tokenizer.save_pretrained("./my-model")

# Hub에 업로드
model.push_to_hub("username/my-awesome-model")
tokenizer.push_to_hub("username/my-awesome-model")

# 또는 huggingface-cli 사용
# huggingface-cli upload username/my-model ./my-model

6.3 모델 카드 작성

# README.md 생성
model_card = """
---
language: en
license: apache-2.0
tags:
- text-classification
- sentiment-analysis
datasets:
- imdb
metrics:
- accuracy
---

# My Awesome Model

This model is fine-tuned for sentiment analysis.

## Usage

```python
from transformers import pipeline

classifier = pipeline("sentiment-analysis", model="username/my-awesome-model")
result = classifier("I love this!")

Training

Trained on IMDB dataset with the following parameters:

  • Learning rate: 2e-5
  • Batch size: 16
  • Epochs: 3
    “””

with open(“./my-model/README.md”, “w”) as f:
f.write(model_card)


## 7. 고급 기능

### 7.1 양자화 (Quantization)

메모리 사용량을 줄이고 추론 속도를 높입니다.

```python
from transformers import AutoModelForCausalLM, BitsAndBytesConfig

# 8비트 양자화
quantization_config = BitsAndBytesConfig(load_in_8bit=True)

model = AutoModelForCausalLM.from_pretrained(
"meta-llama/Llama-2-7b-hf",
quantization_config=quantization_config,
device_map="auto"
)

# 4비트 양자화 (더 적은 메모리)
quantization_config = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_compute_dtype=torch.float16,
bnb_4bit_quant_type="nf4"
)

model = AutoModelForCausalLM.from_pretrained(
"meta-llama/Llama-2-7b-hf",
quantization_config=quantization_config,
device_map="auto"
)

7.2 LoRA (Low-Rank Adaptation)

파라미터 효율적인 파인튜닝 방법입니다.

pip install peft
from peft import LoraConfig, get_peft_model

# LoRA 설정
lora_config = LoraConfig(
r=8, # rank
lora_alpha=32,
target_modules=["q_proj", "v_proj"],
lora_dropout=0.05,
bias="none",
task_type="CAUSAL_LM"
)

# 모델에 LoRA 적용
model = AutoModelForCausalLM.from_pretrained("gpt2")
model = get_peft_model(model, lora_config)

# 학습 가능한 파라미터 확인
model.print_trainable_parameters()
# trainable params: 294,912 || all params: 124,734,720 || trainable%: 0.23%

# 학습 후 LoRA 가중치만 저장
model.save_pretrained("./my-lora-model")

# 로드
from peft import PeftModel

base_model = AutoModelForCausalLM.from_pretrained("gpt2")
model = PeftModel.from_pretrained(base_model, "./my-lora-model")

7.3 분산 학습 (Accelerate)

pip install accelerate
from accelerate import Accelerator

accelerator = Accelerator()

model, optimizer, train_dataloader = accelerator.prepare(
model, optimizer, train_dataloader
)

for batch in train_dataloader:
outputs = model(**batch)
loss = outputs.loss
accelerator.backward(loss)

optimizer.step()
optimizer.zero_grad()

명령줄에서 실행:

accelerate config  # 설정 생성
accelerate launch train.py # 학습 시작

7.4 그래디언트 체크포인팅

메모리를 절약하면서 큰 모델을 학습합니다.

model.gradient_checkpointing_enable()

# Trainer에서 사용
training_args = TrainingArguments(
gradient_checkpointing=True,
# ... 기타 설정
)

7.5 혼합 정밀도 학습

# Trainer에서 자동으로 처리
training_args = TrainingArguments(
fp16=True, # GPU 사용 시
# bf16=True, # A100/H100 GPU 사용 시
)

# 수동 설정
from torch.cuda.amp import autocast, GradScaler

scaler = GradScaler()

for batch in train_dataloader:
with autocast():
outputs = model(**batch)
loss = outputs.loss

scaler.scale(loss).backward()
scaler.step(optimizer)
scaler.update()
optimizer.zero_grad()

8. 실전 예제

8.1 감정 분석 시스템 구축

from transformers import pipeline, AutoModelForSequenceClassification, AutoTokenizer
import torch

class SentimentAnalyzer:
def __init__(self, model_name="distilbert-base-uncased-finetuned-sst-2-english"):
self.tokenizer = AutoTokenizer.from_pretrained(model_name)
self.model = AutoModelForSequenceClassification.from_pretrained(model_name)
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
self.model.to(self.device)

def analyze(self, text):
inputs = self.tokenizer(text, return_tensors="pt", truncation=True, max_length=512)
inputs = {k: v.to(self.device) for k, v in inputs.items()}

with torch.no_grad():
outputs = self.model(**inputs)

probs = torch.softmax(outputs.logits, dim=-1)
prediction = torch.argmax(probs, dim=-1).item()
confidence = probs[0][prediction].item()

label = "POSITIVE" if prediction == 1 else "NEGATIVE"

return {
"label": label,
"confidence": confidence,
"probabilities": {
"negative": probs[0][0].item(),
"positive": probs[0][1].item()
}
}

def batch_analyze(self, texts):
results = []
for text in texts:
results.append(self.analyze(text))
return results

# 사용
analyzer = SentimentAnalyzer()
result = analyzer.analyze("This product is amazing!")
print(result)

# 배치 처리
texts = [
"I love this!",
"This is terrible.",
"It's okay, nothing special."
]
results = analyzer.batch_analyze(texts)
for text, result in zip(texts, results):
print(f"{text}: {result['label']} ({result['confidence']:.2%})")

8.2 커스텀 챗봇

from transformers import AutoModelForCausalLM, AutoTokenizer
import torch

class ChatBot:
def __init__(self, model_name="microsoft/DialoGPT-medium"):
self.tokenizer = AutoTokenizer.from_pretrained(model_name)
self.model = AutoModelForCausalLM.from_pretrained(model_name)
self.chat_history_ids = None

def chat(self, user_input):
# 사용자 입력 인코딩
new_input_ids = self.tokenizer.encode(
user_input + self.tokenizer.eos_token,
return_tensors="pt"
)

# 대화 히스토리와 결합
if self.chat_history_ids is not None:
bot_input_ids = torch.cat([self.chat_history_ids, new_input_ids], dim=-1)
else:
bot_input_ids = new_input_ids

# 응답 생성
self.chat_history_ids = self.model.generate(
bot_input_ids,
max_length=1000,
pad_token_id=self.tokenizer.eos_token_id,
temperature=0.7,
top_p=0.9,
do_sample=True
)

# 디코딩
response = self.tokenizer.decode(
self.chat_history_ids[:, bot_input_ids.shape[-1]:][0],
skip_special_tokens=True
)

return response

def reset(self):
"""대화 히스토리 초기화"""
self.chat_history_ids = None

# 사용
bot = ChatBot()

print("Chatbot: Hello! How can I help you?")
while True:
user_input = input("You: ")
if user_input.lower() in ["quit", "exit", "bye"]:
print("Chatbot: Goodbye!")
break

response = bot.chat(user_input)
print(f"Chatbot: {response}")

8.3 문서 질의응답 시스템

from transformers import pipeline
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_community.vectorstores import FAISS
from langchain_community.embeddings import HuggingFaceEmbeddings

class DocumentQA:
def __init__(self):
# 임베딩 모델
self.embeddings = HuggingFaceEmbeddings(
model_name="sentence-transformers/all-MiniLM-L6-v2"
)

# QA 파이프라인
self.qa_pipeline = pipeline(
"question-answering",
model="deepset/roberta-base-squad2"
)

self.vectorstore = None

def load_documents(self, texts):
"""문서 로드 및 인덱싱"""
# 텍스트 분할
text_splitter = RecursiveCharacterTextSplitter(
chunk_size=500,
chunk_overlap=50
)

chunks = []
for text in texts:
chunks.extend(text_splitter.split_text(text))

# 벡터 스토어 생성
self.vectorstore = FAISS.from_texts(chunks, self.embeddings)

def answer(self, question, k=3):
"""질문에 답변"""
# 관련 문서 검색
docs = self.vectorstore.similarity_search(question, k=k)

# 각 문서에 대해 QA 수행
results = []
for doc in docs:
result = self.qa_pipeline(
question=question,
context=doc.page_content
)
results.append(result)

# 가장 높은 점수의 답변 반환
best_result = max(results, key=lambda x: x["score"])

return {
"answer": best_result["answer"],
"confidence": best_result["score"],
"context": docs[0].page_content
}

# 사용
qa_system = DocumentQA()

documents = [
"""
Hugging Face is a company that develops tools for building applications
using machine learning. It is most notable for its transformers library
built for natural language processing applications and its platform that
allows users to share machine learning models and datasets.
""",
"""
The Transformers library provides thousands of pretrained models to perform
tasks on different modalities such as text, vision, and audio. These models
can be applied on: Text, for tasks like text classification, information
extraction, question answering, summarization, translation, and text generation.
"""
]

qa_system.load_documents(documents)

question = "What is Hugging Face?"
result = qa_system.answer(question)

print(f"Question: {question}")
print(f"Answer: {result['answer']}")
print(f"Confidence: {result['confidence']:.2%}")

8.4 이미지 캡셔닝

pip install pillow
from transformers import VisionEncoderDecoderModel, ViTImageProcessor, AutoTokenizer
from PIL import Image

class ImageCaptioner:
def __init__(self):
self.model = VisionEncoderDecoderModel.from_pretrained(
"nlpconnect/vit-gpt2-image-captioning"
)
self.feature_extractor = ViTImageProcessor.from_pretrained(
"nlpconnect/vit-gpt2-image-captioning"
)
self.tokenizer = AutoTokenizer.from_pretrained(
"nlpconnect/vit-gpt2-image-captioning"
)

self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
self.model.to(self.device)

def generate_caption(self, image_path, num_captions=1):
# 이미지 로드
image = Image.open(image_path)
if image.mode != "RGB":
image = image.convert(mode="RGB")

# 전처리
pixel_values = self.feature_extractor(
images=image,
return_tensors="pt"
).pixel_values
pixel_values = pixel_values.to(self.device)

# 캡션 생성
output_ids = self.model.generate(
pixel_values,
max_length=16,
num_beams=4,
num_return_sequences=num_captions
)

# 디코딩
captions = self.tokenizer.batch_decode(output_ids, skip_special_tokens=True)
return [caption.strip() for caption in captions]

# 사용
captioner = ImageCaptioner()
captions = captioner.generate_caption("image.jpg", num_captions=3)

for i, caption in enumerate(captions, 1):
print(f"Caption {i}: {caption}")

9. Spaces - 모델 데모 호스팅

9.1 Gradio 앱 생성

pip install gradio
# app.py
import gradio as gr
from transformers import pipeline

# 파이프라인 로드
classifier = pipeline("sentiment-analysis")

def analyze_sentiment(text):
result = classifier(text)[0]
return f"{result['label']}: {result['score']:.2%}"

# Gradio 인터페이스
interface = gr.Interface(
fn=analyze_sentiment,
inputs=gr.Textbox(lines=5, placeholder="Enter text here..."),
outputs="text",
title="Sentiment Analysis",
description="Analyze the sentiment of any text!"
)

if __name__ == "__main__":
interface.launch()

9.2 Hugging Face Spaces에 배포

# 1. Space 생성 (웹에서)
# https://huggingface.co/new-space

# 2. 로컬에서 클론
git clone https://huggingface.co/spaces/username/my-space
cd my-space

# 3. 파일 추가
# - app.py (메인 코드)
# - requirements.txt
# - README.md

# requirements.txt
transformers
torch
gradio

# 4. 푸시
git add .
git commit -m "Initial commit"
git push

9.3 Streamlit 앱

pip install streamlit
# app.py
import streamlit as st
from transformers import pipeline

st.title("🤗 Sentiment Analysis")

# 사이드바
model_name = st.sidebar.selectbox(
"Select Model",
["distilbert-base-uncased-finetuned-sst-2-english", "cardiffnlp/twitter-roberta-base-sentiment"]
)

# 파이프라인 로드
@st.cache_resource
def load_model(name):
return pipeline("sentiment-analysis", model=name)

classifier = load_model(model_name)

# 입력
text = st.text_area("Enter text to analyze:", height=150)

# 분석 버튼
if st.button("Analyze"):
if text:
with st.spinner("Analyzing..."):
result = classifier(text)[0]

st.success("Analysis Complete!")

col1, col2 = st.columns(2)
with col1:
st.metric("Label", result["label"])
with col2:
st.metric("Confidence", f"{result['score']:.2%}")
else:
st.warning("Please enter some text!")

# 실행: streamlit run app.py

10. 베스트 프랙티스

10.1 메모리 최적화

# 1. 작은 배치 사이즈 사용
training_args = TrainingArguments(
per_device_train_batch_size=4,
gradient_accumulation_steps=4 # 효과적으로 배치 크기 16
)

# 2. 그래디언트 체크포인팅
model.gradient_checkpointing_enable()

# 3. 혼합 정밀도
training_args = TrainingArguments(
fp16=True
)

# 4. CPU 오프로딩
training_args = TrainingArguments(
optim="adamw_torch_fused",
gradient_checkpointing=True,
)

# 5. 모델 양자화
from transformers import BitsAndBytesConfig

bnb_config = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_use_double_quant=True,
bnb_4bit_quant_type="nf4",
bnb_4bit_compute_dtype=torch.bfloat16
)

model = AutoModelForCausalLM.from_pretrained(
"model-name",
quantization_config=bnb_config,
device_map="auto"
)

10.2 속도 최적화

# 1. 배치 처리
texts = ["text1", "text2", "text3"]
results = classifier(texts) # 한 번에 처리

# 2. 토큰 길이 최적화
inputs = tokenizer(
text,
truncation=True,
max_length=128, # 필요한 만큼만
padding="max_length"
)

# 3. 캐싱 활용
from transformers import pipeline

@lru_cache(maxsize=100)
def cached_inference(text):
return classifier(text)

# 4. ONNX 변환으로 추론 속도 향상
pip install optimum[onnxruntime]
from optimum.onnxruntime import ORTModelForSequenceClassification
from transformers import AutoTokenizer

model = ORTModelForSequenceClassification.from_pretrained(
"distilbert-base-uncased-finetuned-sst-2-english",
export=True
)
tokenizer = AutoTokenizer.from_pretrained(
"distilbert-base-uncased-finetuned-sst-2-english"
)

# 추론 속도 2-3배 향상

10.3 에러 핸들링

from transformers import pipeline
from requests.exceptions import HTTPError

def safe_inference(text, max_retries=3):
for attempt in range(max_retries):
try:
result = classifier(text)
return result
except HTTPError as e:
if attempt < max_retries - 1:
print(f"Retry {attempt + 1}/{max_retries}")
continue
else:
raise
except Exception as e:
print(f"Error: {e}")
return None

# 텍스트 길이 확인
def validate_input(text, max_length=512):
tokenized = tokenizer.tokenize(text)
if len(tokenized) > max_length:
print(f"Warning: Text too long ({len(tokenized)} tokens). Truncating...")
return True
return False

11. 유용한 리소스

공식 문서

커뮤니티

관련 도구

마무리

Hugging Face는 현대 AI 개발의 필수 도구가 되었습니다.

핵심 포인트:

  • Transformers: 사전 학습된 모델을 쉽게 사용
  • Datasets: 데이터 처리 및 관리 간소화
  • Hub: 모델과 데이터셋 공유 플랫폼
  • 파인튜닝: Trainer API로 쉬운 학습
  • 최적화: 양자화, LoRA로 효율적인 배포

다음 단계:

  1. Hugging Face Course 수강
  2. Hub에서 모델 탐색 및 실험
  3. 자신의 데이터로 모델 파인튜닝
  4. Spaces에 데모 배포
  5. 커뮤니티 참여 및 기여

Hugging Face를 활용하면 최신 AI 기술을 빠르게 프로덕션에 적용할 수 있습니다!

Share