Hugging Face LLMs
Hugging Face LLMs
Hugging Face의 LLM을 로컬 또는 Hugging Face의 Inference Providers를 통해 사용하는 방법을 다루는 가이드예요. Hugging Face 자체가 여러 Python 패키지를 제공하는데, LlamaIndex는 이를 LLM 엔티티로 감싸요.
출처: 문서
본문
Hugging Face의 LLM과 연동하는 방법은 정말 많아요. Hugging Face가 제공하는 패키지를 LlamaIndex가 LLM 엔티티로 감쌉니다.
transformers패키지:llama_index.llms.HuggingFaceLLM사용- Hugging Face Inference Providers(
huggingface_hub[inference]로 감쌈):llama_index.llms.HuggingFaceInferenceAPI사용
두 방식의 조합이 많이 가능하므로, 이 노트북에서는 몇 가지만 다룹니다. Hugging Face의 Text Generation 태스크를 예시로 사용할게요.
아래 줄에서 이 데모에 필요한 패키지를 설치해요.
HuggingFaceLLM에는transformers[torch]필요HuggingFaceInferenceAPI에는huggingface_hub[inference]필요- 인용부호는 Z shell(
zsh)용임
%pip install llama-index-llms-huggingface # 로컬 추론용
%pip install llama-index-llms-huggingface-api # 원격 추론용
!pip install "transformers[torch]" "huggingface_hub[inference]"
colab에서 이 노트북을 열었다면 LlamaIndex 🦙를 설치해야 할 거예요.
!pip install llama-index
이제 준비가 끝났으니 사용해 봅시다.
Hugging Face 계정 설정 (Setup Hugging Face Account)
먼저 Hugging Face 계정을 만들고 토큰을 받아야 해요. 여기에서 가입하고, 여기에서 토큰을 만들 수 있어요.
export HUGGING_FACE_TOKEN=hf_your_token_here
import os
from typing import List, Optional
from llama_index.llms.huggingface import HuggingFaceLLM
from llama_index.llms.huggingface_api import HuggingFaceInferenceAPI
HF_TOKEN: Optional[str] = os.getenv("HUGGING_FACE_TOKEN")
# 참고: None 기본값은 HuggingFaceInferenceAPI 내부에서
# 이 토큰을 사용할 때 Hugging Face의 토큰 저장소로 폴백합니다
Inference Providers로 모델 사용
오픈소스 모델을 사용하는 가장 쉬운 방법은 Hugging Face Inference Providers를 쓰는 거예요. 복잡한 태스크에 좋은 DeepSeek R1 모델을 사용해 봅시다.
inference providers를 사용하면 서버리스 인프라에서 모델을 쓸 수 있어요.
remotely_run = HuggingFaceInferenceAPI(
model_name="deepseek-ai/DeepSeek-R1-0528",
token=HF_TOKEN,
provider="auto", # 사용 가능한 최상의 프로바이더 사용
)
선호하는 inference provider를 지정할 수도 있어요. together 프로바이더를 써 봅시다.
remotely_run = HuggingFaceInferenceAPI(
model_name="Qwen/Qwen3-235B-A22B",
token=HF_TOKEN,
provider="together", # 사용 가능한 최상의 프로바이더 사용
)
오픈소스 모델을 로컬에서 사용
먼저 로컬 추론에 최적화된 오픈소스 모델을 사용해 봅시다. 이 모델은(첫 호출 시) 로컬 Hugging Face 모델 캐시로 다운로드되어, 실제로 당신의 로컬 머신 하드웨어에서 실행돼요.
로컬 추론에 최적화된 Gemma 3N E4B 모델을 사용할 거예요.
locally_run = HuggingFaceLLM(model_name="google/gemma-3n-E4B-it")
전용 Inference Endpoint 사용
모델용 전용 Inference Endpoint를 만들고 그걸로 모델을 실행할 수도 있어요.
endpoint_server = HuggingFaceInferenceAPI(
model="https://(<your-endpoint>.eu-west-1.aws.endpoints.huggingface.cloud"
)
로컬 추론 엔진 사용 (vLLM 또는 TGI)
vLLM이나 TGI 같은 로컬 추론 엔진으로 모델을 실행할 수도 있어요.
# 로컬 또는 원격의 Text Generation Inference 서버가
# 서빙하는 모델에 연결할 수도 있습니다
tgi_server = HuggingFaceInferenceAPI(model="http://localhost:8080")
HuggingFaceInferenceAPI의 완성 생성 기반에는 Hugging Face의 Text Generation 태스크가 있어요.
completion_response = remotely_run_recommended.complete("To infinity, and")
print(completion_response)
beyond!
The Infinity Wall Clock is a unique and stylish way to keep track of time. The clock is made of a durable, high-quality plastic and features a bright LED display. The Infinity Wall Clock is powered by batteries and can be mounted on any wall. It is a great addition to any home or office.
토크나이저 설정 (Setting a tokenizer)
LLM을 변경한다면 전역 토크나이저도 그에 맞게 바꿔야 해요!
from llama_index.core import set_global_tokenizer
from transformers import AutoTokenizer
set_global_tokenizer(
AutoTokenizer.from_pretrained("HuggingFaceH4/zephyr-7b-alpha").encode
)
궁금하다면, Hugging Face Inference API로 감싼 다른 태스크들도 있어요.
llama_index.llms.HuggingFaceInferenceAPI.chat: Conversational 태스크llama_index.embeddings.HuggingFaceInferenceAPIEmbedding: Feature Extraction 태스크
그리고 Hugging Face 임베딩 모델도 지원돼요.
transformers[torch]:HuggingFaceEmbedding으로 감쌈huggingface_hub[inference]:HuggingFaceInferenceAPIEmbedding으로 감쌈
위 둘 모두 llama_index.embeddings.base.BaseEmbedding을 서브클래싱해요.