transformers
프레임워크huggingface/transformers
텍스트, 비전, 오디오 등을 지원하는 크로스모달 사전 학습 모델 추론 및 학습 프레임워크.
개요
Hugging Face Transformers는 모델 정의 프레임워크로, 텍스트, 비전, 오디오 및 멀티모달 태스크를 위한 수천 개의 사전 학습된 모델을 제공합니다. 추론과 학습을 지원하며 주요 학습 프레임워크 및 추론 엔진과 호환되고, AI 생태계 상호 운용성을 촉진하기 위해 모델 정의를 중앙에서 관리합니다.
README 미리보기
\n\n\n \n \n \n \n \n \n \n\n\n\n \n \n \n \n \n \n \n\n\n\n \n English |\n 简体中文 |\n 繁體中文 |\n 한국어 |\n Español |\n 日本語 |\n हिन्दी |\n Русский |\n Português |\n తెలుగు |\n Français |\n Deutsch |\n Italiano |\n Tiếng Việt |\n العربية |\n اردو |\n বাংলা |\n فارسی |\n Türkçe |\n \n\n\n\n State-of-the-art pretrained models for inference and training\n\n\n\n \n\n\nTransformers acts as the model-definition framework for state-of-the-art machine learning with text, computer\nvision, audio, video, and multimodal models, for both inference and training.\n\nIt centralizes the model definition so that this definition is agreed upon across the ecosystem. `transformers` is the\npivot across frameworks: if a model definition is supported, it will be compatible with the majority of training\nframeworks (Axolotl, Unsloth, DeepSpeed, FSDP, PyTorch-Lightning, ...), inference engines (vLLM, SGLang, TGI, ...),\nand adjacent modeling libraries (llama.cpp, mlx, ...) which leverage the model definition from `transformers`.\n\nWe pledge to help support new state-of-the-art models and democratize their usage by having their model definition be\nsimple, customizable, and efficient.\n\nThere are over 1M+ Transformers [model checkpoints](https://huggingface.co/models?library=transformers&sort=trending) on the [Hugging Face Hub](https://huggingface.co/models) you can use.\n\nExplore the [Hub](https://huggingface.co/) today to find a model and use Transformers to help you get started right away.\n\n## Installation\n\nTransformers works with Python 3.10+, and [PyTorch](https://pytorch.org/get-started/locally/) 2.5+.\n\nCreate and activate a virtual environment with [venv](https://docs.python.org/3/library/venv.html) or [uv](https://docs.astral.sh/uv/), a fast Rust-based Python package and project manager.\n\n```py\n# venv\
FAQ (5)
문제 해결MM Grounding DINO와 LLMDet이 transformers v5에서 잘못된(너무 작은) 바운딩 박스를 예측하는 이유는 무엇이며, 어떻게 해결할 수 있나요?
transformers 5.x(5.18.0+, main에서도 여전히 존재)의 알려진 버그: MMGroundingDinoForObjectDetection._tied_weights_keys가 모든 디코더 레이어의 box head와 class head를 레이어 0에 묶어버려(tie), 체크포인트 config의 decoder_bbox_embed_share: false / decoder_cls_embed_share: false를 무시합니다. 이로 인해 레이어 1-5가 레이어 0의 head를 재사용하게 되어 box가 잘못 출력됩니다(예: RefCOCO acc@0.5가 7/8에서 0/8로 하락). 영향을 받는 체크포인트에는 iSEE-Laboratory/llmdet_tiny/base/large와 openmmlab-community/mm_grounding_dino_tiny_* 및 mm_grounding_dino_large_all이 포함됩니다.
수정 방법 1 — 각 레이어가 자체 head를 유지하던 v4 동작으로 다운그레이드:pip install "transformers==4.57.1"
수정 방법 2 — 로딩 후 체크포인트에서 각 디코더 레이어의 고유 head를 복원:
from huggingface_hub import hf_hub_download
from safetensors.torch import load_file
weights = load_file(hf_hub_download(model_id, "model.safetensors"))
for i in range(1, model.config.decoder_layers):
model.bbox_embed[i] = type(model.bbox_embed[0])(model.config.d_model, model.config.d_model, 4, 3)
model.bbox_embed[i].load_state_dict({k.split(f"bbox_embed.{i}.")[1]: v for k, v in weights.items()
if k.startswith(f"model.decoder.bbox_embed.{i}.")})
model.class_embed[i] = type(model.class_embed[0])(model.config)
model.class_embed[i].bias.data = weights[f"model.decoder.class_embed.{i}.bias"].clone()
model.model.decoder.bbox_embed = model.bbox_embed
model.model.decoder.class_embed = model.class_embed버그는 먼저 다음으로 확인할 수 있습니다: config에서 head가 공유되지 않는다고 되어 있음에도
model.bbox_embed[1].layers[0].weight is model.bbox_embed[0].layers[0].weight가 True를 반환하는 경우입니다.문제 해결transformers 비디오 샘플링이 짧은 비디오를 낮은 FPS로 처리할 때 빈 프레임 인덱스를 반환하는 이유는 무엇인가요(read_video_pyav에서 IndexError)?
이것은 src/transformers/video_utils.py의 default_sample_indices_fn()에 있는 버그입니다. 이 함수는 num_frames = int(total_num_frames / video_fps * fps)를 계산하는데, 짧은 동영상의 경우 0으로 잘립니다(예: 10프레임, 30 FPS 동영상을 1 FPS로 샘플링하면 int(10/30*1) == 0이 됩니다). 그러면 다운스트림 디코더가 충돌합니다: read_video_pyav()는 indices[-1]에서 실패하고 read_video_opencv()는 np.stack(frames)에서 실패합니다. 해결 방법: 패치가 포함된 버전으로 transformers를 업그레이드하세요. 이 패치는 결과를 클램프하여 요청한 FPS가 양수인 비어 있지 않은 모든 동영상에 대해 최소 하나의 프레임 인덱스(예: [0])가 반환되도록 합니다. 이전 버전에서의 우회 방법: int(total_num_frames / video_fps * fps) >= 1이 되도록 더 높은 fps를 요청하거나, total_num_frames > 0이고 fps > 0일 때 num_frames = max(1, int(total_num_frames / video_fps * fps))로 함수를 몽키 패치하세요.
문제 해결Transformers image-text-to-text 파이프라인이 배치된 이미지에서 충돌하는 이유는 무엇이며, VLM 프로세서는 어떤 입력 형식을 지원하나요?
Hugging Face Transformers의 VLM 프로세서는 일관되지 않은 입력 형식을 받아들이므로, 한 모델에서는 작동하는 pipeline 호출이 다른 모델에서는 오류를 일으킬 수 있습니다. 주요 규칙과 우회 방법은 다음과 같습니다:
1. **URL**: Idefics, Idefics2, Idefics3 및 Pixtral만 이미지 URL을 직접 받아들입니다. 다른 모든 모델(LLaVA, BLIP, PaliGemma, Qwen2-VL 등)은 먼저 다운로드하여 PIL로 변환해야 합니다:
from PIL import Image
import requests
image = Image.open(requests.get(url, stream=True).raw)
2. **파일 경로**: 어떤 VLM 프로세서도 원시 파일 경로를 받아들이지 않습니다. 항상 Image.open(path)로 먼저 로드하세요.
3. **텍스트당 이미지 수가 다른 중첩 배치** (예: images=[[img1, img2], [img3]]): Qwen2-VL, Chameleon, PaliGemma, Llava-Next, LLaVA-OneVision, Mllama, InstructBLIP, Idefics2 및 Idefics3만 이를 지원합니다. LLaVA, BLIP2, VipLlava, Pixtral 같은 모델은 프로세서 수준에서 오류가 발생합니다. 우회 방법: 호환되는 모델로 전환하거나(예: llava-hf/llava-interleave-qwen-0.5b-hf 대신 llava-hf/llava-onevision-qwen2-0.5b-ov-hf), 각 텍스트/이미지 세트를 배치되지 않은 개별 호출로 처리하세요.
4. **패딩 특이 사항**: Qwen2-VL은 padding=True일 때 중첩되지 않은 배치 이미지에서 오류가 발생하며, Chameleon은 패딩을 수동으로 True로 설정해야만 작동합니다.
PIL은 유일하게 범용적으로 지원되는 형식이므로, 모델의 프로세서 문서를 확인하거나 먼저 단일 PIL 이미지로 테스트해 보세요.
방법Hugging Face Transformers를 사용하여 coreference resolution에 SpanBERT를 사용하는 방법은?
SpanBERT의 사전 학습 가중치는 Hugging Face Hub에 공개되어 있으며 표준 BERT 아키텍처로 로드할 수 있습니다:
from transformers import AutoTokenizer, AutoModel
tokenizer = AutoTokenizer.from_pretrained("SpanBERT/spanbert-base-cased")
model = AutoModel.from_pretrained("SpanBERT/spanbert-base-cased")
SpanBERT/spanbert-large-cased도 사용할 수 있습니다. 그러나 원 논문의 상호참조 헤드(TensorFlow 1.14 기반 mandarjoshi90/coref 구현)는 Transformers로 이식된 적이 없기 때문에, 내장된 SpanBERT 상호참조 파이프라인은 없습니다. 현재 상호참조 해결을 위한 우회 방법은 다음과 같습니다:
1. 바로 사용할 수 있는 상호참조 파이프라인을 제공하는 커뮤니티 모델 biu-nlp/f-coref(fastcoref)를 사용합니다.
2. 대안으로 neuralcoref(spaCy 기반)를 사용합니다.
3. 논문의 접근 방식을 재현해야 한다면, 로드된 SpanBERT AutoModel 위에 스팬 분류(span-classification) 헤드를 직접 파인튜닝합니다.
문제 해결Gemma4 오디오 모델이 eager attention에서 잘못되거나 균일한 attention 출력을 생성하는 이유는 무엇이며, eager와 sdpa 간의 불일치는 어떻게 해결해야 하나요?
근본 원인: Gemma4AudioAttention은 masked_fill(attention_mask.logical_not(), ...)를 통해 어텐션 마스크를 적용하는데, 이는 bool 마스크를 전제로 합니다. 그러나 create_bidirectional_mask는 eager 모드에서 가산형(additive) float 마스크를 반환하므로(0.0 = 허용, finfo.min = 불허), logical_not()가 의미를 뒤집습니다 — 허용된 위치가 마스킹되고, 전체가 허용된 마스크에서는 어텐션이 내용과 관계없이 거의 균일한 평균화로 퇴화합니다. 즉시 해결 방법: 올바른 bool 마스크를 사용하는 sdpa 어텐션을 강제로 사용합니다 — attn_implementation="sdpa"로 모델을 로드하거나 model.set_attn_implementation("sdpa")를 호출하세요. 영구 수정(transformers 패치): Gemma4AudioAttention에서 두 가지 마스크 규약을 모두 처리합니다 — bool 마스크 → masked_fill(mask.logical_not(), invalid_value); float 마스크 → 블록화된 5-D 변환 후 attn_weights = attn_weights + attention_mask로 가산 방식으로 적용합니다. 또한 _convert_4d_mask_to_blocked_5d를 dtype을 인식하도록 만드세요: float 마스크의 경우 value=False 대신(0.0으로 패딩되며, float 규약에서는 *허용*을 의미) F.pad(..., value=torch.finfo(dtype).min)을 사용하세요. 동일한 시드로 eager와 sdpa 출력을 비교하여 수정 사항을 검증하세요 — 최대 절대 차이가 ~0.12에서 ~1e-6으로 감소해야 합니다.