Transformers documentation
ModernVBert
이 모델은 2025-10-01에 HF papers에 게시되었으며, 2026-02-23에 Hugging Face Transformers에 기여되었습니다.
ModernVBert
개요
ModernVBert은 ModernBert과 SigLIP 비전 인코더를 결합한 Vision-Language 인코더입니다. 시각 문서 이해 및 검색 작업에 최적화되어 있습니다.
해당 모델은 ModernVBERT: Towards Smaller Visual Document Retrievers에서 소개되었습니다.
import torch
from huggingface_hub import hf_hub_download
from PIL import Image
from transformers import AutoModelForMaskedLM, AutoProcessor
processor = AutoProcessor.from_pretrained("./mvb")
model = AutoModelForMaskedLM.from_pretrained("./mvb", device_map="auto")
image = Image.open(hf_hub_download("HuggingFaceTB/SmolVLM", "example_images/rococo.jpg", repo_type="space"))
text = "This [MASK] is on the wall."
# Create input messages
messages = [
{
"role": "user",
"content": [
{"type": "image"},
{"type": "text", "text": text}
]
},
]
# Prepare inputs
prompt = processor.apply_chat_template(messages)
inputs = processor(text=prompt, images=[image], return_tensors="pt").to(model.device)
# Inference
with torch.no_grad():
outputs = model(**inputs)
# To get predictions for the mask:
masked_index = inputs["input_ids"][0].tolist().index(processor.tokenizer.mask_token_id)
predicted_token_id = outputs.logits[0, masked_index].argmax(axis=-1)
predicted_token = processor.tokenizer.decode(predicted_token_id)
print("Predicted token:", predicted_token) # Predicted token: paintingModernVBertConfig
class transformers.ModernVBertConfig
< source >( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonetext_config: transformers.configuration_utils.PreTrainedConfig | dict | None = Nonevision_config: transformers.configuration_utils.PreTrainedConfig | dict | None = Noneimage_token_id: int = 50407pixel_shuffle_factor: int = 4initializer_range: float = 0.02initializer_cutoff_factor: float = 2.0classifier_pooling: typing.Literal['cls', 'mean'] = 'cls'classifier_dropout: float | int = 0.0classifier_bias: bool = Falsetie_word_embeddings: bool = False )
매개변수
- text_config (
Union[~configuration_utils.PreTrainedConfig, dict], 선택) — 텍스트 백본의 config 객체 또는 사전입니다. - vision_config (
Union[~configuration_utils.PreTrainedConfig, dict], 선택) — 비전 백본의 config 객체 또는 사전입니다. - image_token_id (
int, 선택 사항, 기본값50407) — 입력 이미지용으로 플레이스홀더로 사용되는 이미지 토큰 인덱스입니다. - pixel_shuffle_factor (
int | None, 선택 사항, 기본값 4) — 비전 헤드에서 픽셀 셔플 / 업샘플링 연산에 사용되는 스케일 팩터입니다. - initializer_range (
float, 선택 사항, 기본값0.02) — 모든 가중치 행렬을 초기화하는 truncated_normal_initializer의 표준 편차입니다. - initializer_cutoff_factor (
float | None, 선택 사항, 기본값 2.0) — 모든 가중치 행렬을 초기화하는 truncated_normal_initializer에 사용되는 절단 계수입니다. - classifier_pooling (
Literal["cls", "mean"], 선택 사항, 기본값"cls") — 분류 작업에 사용할 풀링 전략입니다. - classifier_dropout (
Union[float, int], 선택 사항, 기본값0.0) — classifier의 dropout 비율입니다. - classifier_bias (
bool | None, 선택, 기본값False) — 분류 헤드에 bias 항을 추가할지 여부 - tie_word_embeddings (
bool, 선택, 기본값False) — 모델의tied_weights_keys매핑에 따라 가중치 임베딩을 묶을지 여부.
이것은 ModernVBertModel의 구성을 저장하기 위한 구성 클래스입니다. 지정된 인자에 따라 Modernvbert 모델을 인스턴스화하여 모델 아키텍처를 정의하는 데 사용됩니다. 기본값으로 구성을 인스턴스화하면 ModernVBERT/modernvbert와 유사한 구성이 생성됩니다.
Configuration 객체는 PreTrainedConfig를 상속하며 모델 출력을 제어하는 데 사용할 수 있습니다. 자세한 내용은 PreTrainedConfig의 문서를 참고하세요.
예:
>>> from transformers import ModernVBertConfig
>>> # Initializing configuration
>>> configuration = ModernVBertConfig()
>>> # Initializing a model from the configuration (model class is implemented in
>>> # `modernvbert.modeling_modernvbert`)
>>> from transformers import ModernVBertModel
>>> model = ModernVBertModel(configuration)
>>> # Accessing the model configuration
>>> cfg = model.configModernVBertModel
class transformers.ModernVBertModel
< source >( config: ModernVBertConfig )
매개변수
- config (ModernVBertConfig) — 모델의 모든 매개변수를 포함하는 모델 구성 클래스입니다. 구성 파일로 초기화하는 것은 모델과 관련된 가중치를 로드하지 않으며, 구성 정보만 로드합니다. 모델 가중치를 로드하려면 from_pretrained() 메서드를 확인하세요.
ModernVBertModel은 비전 인코더(SigLIP)와 텍스트 인코더(ModernBert)를 결합한 모델입니다.
ModernVBert은 시각 검색기 ColModernVBert의 기본 모델이며, 다음 논문에서 소개되었습니다: ModernVBERT: Towards Smaller Visual Document Retrievers.
이 모델은 PreTrainedModel에서 상속됩니다. 라이브러리가 모든 모델에 대해 구현하는 일반적 메서드(다운로드 또는 저장, 입력 임베딩 크기 조정, 헤드 프루닝 등)에 대한 세부 사항은 상위 클래스 문서를 확인하세요.
이 모델은 또한 PyTorch torch.nn.Module의 하위 클래스입니다. 일반적인 PyTorch Module처럼 사용하며, 일반적인 사용법 및 동작과 관련된 모든 사항은 PyTorch 문서를 참조하세요.
forward
< source >( input_ids: LongTensor = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Noneinputs_embeds: typing.Optional[torch.Tensor] = Nonepixel_values: typing.Optional[torch.Tensor] = Nonepixel_attention_mask: typing.Optional[torch.BoolTensor] = Noneimage_hidden_states: typing.Optional[torch.Tensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → ModernVBertBaseModelOutput or tuple(torch.Tensor)
매개변수
- input_ids (
torch.LongTensor형상이(batch_size, sequence_length), 선택 사항) — 어휘(input vocabulary)에서 입력 시퀀스 토큰의 인덱스입니다. 기본적으로 패딩은 무시됩니다.AutoTokenizer를 사용하여 인덱스를 얻을 수 있습니다. 자세한 내용은 PreTrainedTokenizer.encode() 및 PreTrainedTokenizer.call()를 참조하세요.
- attention_mask (
torch.Tensor형상이(batch_size, sequence_length), 선택 사항) — 패딩 토큰 인덱스에 대한 attention을 수행하지 않도록 방지하는 마스크. [0, 1]에서 선택된 마스크 값: 마스크되지 않은 토큰은 1, 마스크된 토큰은 0. attention mask란 무엇인가요?[0, 1]:- 마스크되지 않은 토큰에 대해 1
- 마스크된 토큰에 대해 0
- position_ids (
torch.LongTensor의 shape(batch_size, sequence_length), , 선택 사항) — 위치 임베딩에서 각 입력 시퀀스 토큰의 위치 인덱스. 범위[0, config.n_positions - 1]. - inputs_embeds (
torch.Tensor, shape(batch_size, sequence_length, hidden_size), 선택) —input_ids를 전달하는 대신 임베딩 표현을 직접 전달할 수 있습니다. 이는 모델 내부의 임베딩 조회 행렬보다input_ids인덱스를 관련 벡터로 변환하는 방식에 대해 더 세밀한 제어가 필요한 경우에 유용합니다. - pixel_values (
torch.Tensor, shape(batch_size, num_channels, image_size, image_size), 선택 사항) — 입력 이미지에 해당하는 텐서입니다. 픽셀 값은image_processor_class를 사용하여 얻을 수 있습니다. 자세한 내용은image_processor_class.__call__를 참조하세요 (Idefics3Processor는 이미지 처리에image_processor_class를 사용합니다). - pixel_attention_mask (
torch.Tensor, shape(batch_size, image_size, image_size), 선택 사항) — 패딩 픽셀 인덱스에 대한 attention을 수행하지 않도록 하는 마스크입니다. - image_hidden_states (
torch.Tensor, shape(batch_size, num_channels, image_size, image_size)) — 모달리티 투영 이후 이미지 인코더의 히든 스테이트입니다.
반환값
ModernVBertBaseModelOutput 또는 tuple(torch.Tensor)
ModernVBertBaseModelOutput 또는 torch.Tensor의 튜플(return_dict=False가 전달되었거나 config.return_dict=False인 경우)로, 구성(ModernVBertConfig)과 입력에 따라 다양한 요소를 포함합니다.
모델에 입력되는 데이터에는 임의의 개수의 이미지가 포함될 수 있습니다. 이를 처리하기 위해 모델에 전달되는 pixel_values에는 이미지 패딩이 적용되며, 형태는 (batch_size, max_num_images, 3, max_heights, max_widths)입니다. 여기서 max_num_images는 배치 내 batch_size개 샘플 중 가장 많은 이미지 개수입니다. 패딩 이미지는 모델 입구에서 pixel_values를 패딩하는 용도로만 필요하며, 그 이후에는 불필요합니다. 효율성을 위해 vision_model의 forward에 패딩 이미지를 제거한 실제 이미지, 즉 (image_batch_size, 3, height, width) 크기의 pixel_values만 전달합니다. 예를 들어 num_images_per_sample=[1, 3, 1, 2]이고 max_num_images가 3인 경우, image_batch_size는 7이 됩니다.
last_hidden_state (
torch.Tensor, shape(batch_size, sequence_length, hidden_size)) — 모델의 마지막 레이어 출력에서 생성된 hidden-state 시퀀스입니다.hidden_states (
tuple(torch.Tensor), 선택 사항,output_hidden_states=True가 전달되거나config.output_hidden_states=True인 경우 반환됨) —torch.Tensor의 튜플(모델에 임베딩 레이어가 있는 경우 임베딩 출력 1개 + 각 레이어의 출력 1개)로, 모양은(batch_size, sequence_length, hidden_size)입니다.각 레이어의 출력에서 모델의 Hidden-states와 선택적 초기 임베딩 출력을 포함합니다.
attentions (
tuple(torch.Tensor), 선택 사항,output_attentions=True가 전달되었거나config.output_attentions=True인 경우 반환됨) — 각 레이어마다 하나씩 포함된torch.Tensor의 튜플로, 모양은(batch_size, num_heads, sequence_length, sequence_length)입니다.self-attention 헤드에서 가중 평균을 계산하는 데 사용되는 attention softmax 이후의 attention 가중치.
image_hidden_states (
tuple(torch.FloatTensor), 선택) —torch.FloatTensor의 튜플(이미지 임베딩의 출력 하나,(batch_size, num_images, sequence_length, hidden_size)). 비전 인코더가 생성한 모델의 image_hidden_states
ModernVBertForMaskedLM
class transformers.ModernVBertForMaskedLM
< source >( config: ModernVBertConfig )
매개변수
- config (ModernVBertConfig) — 모델의 모든 매개변수를 포함하는 모델 구성 클래스입니다. 구성 파일로 초기화하는 것은 모델과 관련된 가중치를 로드하지 않으며, 구성 정보만 로드합니다. 모델 가중치를 로드하려면 from_pretrained() 메서드를 확인하세요.
language modeling 헤드가 위에 있는 Modernvbert 모델입니다.”
이 모델은 PreTrainedModel에서 상속됩니다. 라이브러리가 모든 모델에 대해 구현하는 일반적 메서드(다운로드 또는 저장, 입력 임베딩 크기 조정, 헤드 프루닝 등)에 대한 세부 사항은 상위 클래스 문서를 확인하세요.
이 모델은 또한 PyTorch torch.nn.Module의 하위 클래스입니다. 일반적인 PyTorch Module처럼 사용하며, 일반적인 사용법 및 동작과 관련된 모든 사항은 PyTorch 문서를 참조하세요.
forward
< source >( input_ids: LongTensor = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Noneinputs_embeds: typing.Optional[torch.Tensor] = Nonepixel_values: typing.Optional[torch.Tensor] = Nonepixel_attention_mask: typing.Optional[torch.BoolTensor] = Noneimage_hidden_states: typing.Optional[torch.Tensor] = Nonelabels: typing.Optional[torch.LongTensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → ModernVBertMaskedLMOutput or tuple(torch.Tensor)
매개변수
- input_ids (
torch.LongTensor형상이(batch_size, sequence_length), 선택 사항) — 어휘(input vocabulary)에서 입력 시퀀스 토큰의 인덱스입니다. 기본적으로 패딩은 무시됩니다.AutoTokenizer를 사용하여 인덱스를 얻을 수 있습니다. 자세한 내용은 PreTrainedTokenizer.encode() 및 PreTrainedTokenizer.call()를 참조하세요.
- attention_mask (
torch.Tensor형상이(batch_size, sequence_length), 선택 사항) — 패딩 토큰 인덱스에 대한 attention을 수행하지 않도록 방지하는 마스크. [0, 1]에서 선택된 마스크 값: 마스크되지 않은 토큰은 1, 마스크된 토큰은 0. attention mask란 무엇인가요?[0, 1]:- 마스크되지 않은 토큰에 대해 1
- 마스크된 토큰에 대해 0
- position_ids (
torch.LongTensor의 shape(batch_size, sequence_length), , 선택 사항) — 위치 임베딩에서 각 입력 시퀀스 토큰의 위치 인덱스. 범위[0, config.n_positions - 1]. - inputs_embeds (
torch.Tensor, shape(batch_size, sequence_length, hidden_size), 선택) —input_ids를 전달하는 대신 임베딩 표현을 직접 전달할 수 있습니다. 이는 모델 내부의 임베딩 조회 행렬보다input_ids인덱스를 관련 벡터로 변환하는 방식에 대해 더 세밀한 제어가 필요한 경우에 유용합니다. - pixel_values (
torch.Tensor, shape(batch_size, num_channels, image_size, image_size), 선택 사항) — 입력 이미지에 해당하는 텐서입니다. 픽셀 값은image_processor_class를 사용하여 얻을 수 있습니다. 자세한 내용은image_processor_class.__call__를 참조하세요 (Idefics3Processor는 이미지 처리에image_processor_class를 사용합니다). - pixel_attention_mask (
torch.Tensor, shape(batch_size, image_size, image_size), 선택 사항) — 패딩 픽셀 인덱스에 대한 attention을 수행하지 않도록 하는 마스크입니다. - image_hidden_states (
torch.Tensor, shape(batch_size, num_channels, image_size, image_size)) — 모달리티 투영 이후 이미지 인코더의 히든 스테이트입니다. - labels (
torch.LongTensor, shape(batch_size, sequence_length), 선택 사항) — 마스크 언어 모델링 손실을 계산하는 데 사용되는 라벨입니다. 인덱스는[0, ..., text_config.]또는model.image_token_id범위에 있어야 합니다. 인덱스가model.image_token_id로 설정된 토큰은 무시(마스크)되며, 손실은[0, ..., text_config.]범위의 라벨을 가진 토큰에 대해서만 계산됩니다.
반환값
ModernVBertMaskedLMOutput 또는 tuple(torch.Tensor)
ModernVBertMaskedLMOutput 또는 torch.Tensor의 튜플(return_dict=False이 전달되었거나 config.return_dict=False인 경우)로, 구성(ModernVBertConfig)과 입력에 따라 다양한 요소를 포함합니다.
모델에 입력되는 데이터에는 임의의 개수의 이미지가 포함될 수 있습니다. 이를 처리하기 위해 모델에 전달되는 pixel_values에는 이미지 패딩이 적용되며, 형태는 (batch_size, max_num_images, 3, max_heights, max_widths)입니다. 여기서 max_num_images는 배치 내 batch_size개 샘플 중 가장 많은 이미지 개수입니다. 패딩 이미지는 모델 입구에서 pixel_values를 패딩하는 용도로만 필요하며, 그 이후에는 불필요합니다. 효율성을 위해 vision_model의 forward에 패딩 이미지를 제거한 실제 이미지, 즉 (image_batch_size, 3, height, width) 크기의 pixel_values만 전달합니다. 예를 들어 num_images_per_sample=[1, 3, 1, 2]이고 max_num_images가 3인 경우, image_batch_size는 7이 됩니다.
loss (
torch.Tensor, shape(1,), 선택 사항,labels이 제공될 때 반환됨) — Masked language modeling (MLM) loss.logits (
torch.Tensor, shape(batch_size, sequence_length, config.vocab_size)) — 언어 모델링 헤드에서 생성된 예측 점수(SoftMax 적용 전 각 어휘 토큰에 대한 점수).hidden_states (
tuple(torch.Tensor), 선택 사항,output_hidden_states=True가 전달되거나config.output_hidden_states=True인 경우 반환됨) —torch.Tensor의 튜플(모델에 임베딩 레이어가 있는 경우 임베딩 출력 1개 + 각 레이어의 출력 1개)로, 모양은(batch_size, sequence_length, hidden_size)입니다.각 레이어의 출력에서 모델의 Hidden-states와 선택적 초기 임베딩 출력을 포함합니다.
attentions (
tuple(torch.Tensor), 선택 사항,output_attentions=True가 전달되었거나config.output_attentions=True인 경우 반환됨) — 각 레이어마다 하나씩 포함된torch.Tensor의 튜플로, 모양은(batch_size, num_heads, sequence_length, sequence_length)입니다.self-attention 헤드에서 가중 평균을 계산하는 데 사용되는 attention softmax 이후의 attention 가중치.
image_hidden_states (
tuple(torch.FloatTensor), 선택) —torch.FloatTensor의 튜플(이미지 임베딩의 출력 하나,(batch_size, num_images, sequence_length, hidden_size)). 비전 인코더가 생성한 모델의 image_hidden_states
예:
>>> from transformers import AutoTokenizer, ModernVBertForMaskedLM
>>> import torch
>>> tokenizer = AutoTokenizer.from_pretrained("ModernVBERT/modernvbert")
>>> model = ModernVBertForMaskedLM.from_pretrained("ModernVBERT/modernvbert")
>>> inputs = tokenizer("The capital of France is <mask>.", return_tensors="pt")
>>> with torch.no_grad():
... logits = model(**inputs).logits
>>> # retrieve index of <mask>
>>> mask_token_index = (inputs.input_ids == tokenizer.mask_token_id)[0].nonzero(as_tuple=True)[0]
>>> predicted_token_id = logits[0, mask_token_index].argmax(axis=-1)
>>> tokenizer.decode(predicted_token_id)
...
>>> labels = tokenizer("The capital of France is Paris.", return_tensors="pt")["input_ids"]
>>> # mask labels of non-<mask> tokens
>>> labels = torch.where(inputs.input_ids == tokenizer.mask_token_id, labels, -100)
>>> outputs = model(**inputs, labels=labels)
>>> round(outputs.loss.item(), 2)
...ModernVBertForSequenceClassification
class transformers.ModernVBertForSequenceClassification
< source >( config: ModernVBertConfig )
매개변수
- config (ModernVBertConfig) — 모델의 모든 매개변수를 포함하는 모델 구성 클래스입니다. 구성 파일로 초기화하는 것은 모델과 관련된 가중치를 로드하지 않으며, 구성 정보만 로드합니다. 모델 가중치를 로드하려면 from_pretrained() 메서드를 확인하세요.
pooling을 수행하는 sequence classification head가 위에 있는 ModernVBert Model입니다.
이 모델은 PreTrainedModel에서 상속됩니다. 라이브러리가 모든 모델에 대해 구현하는 일반적 메서드(다운로드 또는 저장, 입력 임베딩 크기 조정, 헤드 프루닝 등)에 대한 세부 사항은 상위 클래스 문서를 확인하세요.
이 모델은 또한 PyTorch torch.nn.Module의 하위 클래스입니다. 일반적인 PyTorch Module처럼 사용하며, 일반적인 사용법 및 동작과 관련된 모든 사항은 PyTorch 문서를 참조하세요.
forward
< source >( input_ids: LongTensor = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Noneinputs_embeds: typing.Optional[torch.Tensor] = Nonepixel_values: typing.Optional[torch.Tensor] = Nonepixel_attention_mask: typing.Optional[torch.BoolTensor] = Noneimage_hidden_states: typing.Optional[torch.Tensor] = Nonelabels: typing.Optional[torch.LongTensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → SequenceClassifierOutput or tuple(torch.Tensor)
매개변수
- input_ids (
torch.LongTensor형상이(batch_size, sequence_length), 선택 사항) — 어휘(input vocabulary)에서 입력 시퀀스 토큰의 인덱스입니다. 기본적으로 패딩은 무시됩니다.AutoTokenizer를 사용하여 인덱스를 얻을 수 있습니다. 자세한 내용은 PreTrainedTokenizer.encode() 및 PreTrainedTokenizer.call()를 참조하세요.
- attention_mask (
torch.Tensor형상이(batch_size, sequence_length), 선택 사항) — 패딩 토큰 인덱스에 대한 attention을 수행하지 않도록 방지하는 마스크. [0, 1]에서 선택된 마스크 값: 마스크되지 않은 토큰은 1, 마스크된 토큰은 0. attention mask란 무엇인가요?[0, 1]:- 마스크되지 않은 토큰에 대해 1
- 마스크된 토큰에 대해 0
- position_ids (
torch.LongTensor의 shape(batch_size, sequence_length), , 선택 사항) — 위치 임베딩에서 각 입력 시퀀스 토큰의 위치 인덱스. 범위[0, config.n_positions - 1]. - inputs_embeds (
torch.Tensor, shape(batch_size, sequence_length, hidden_size), 선택) —input_ids를 전달하는 대신 임베딩 표현을 직접 전달할 수 있습니다. 이는 모델 내부의 임베딩 조회 행렬보다input_ids인덱스를 관련 벡터로 변환하는 방식에 대해 더 세밀한 제어가 필요한 경우에 유용합니다. - pixel_values (
torch.Tensor, shape(batch_size, num_channels, image_size, image_size), 선택 사항) — 입력 이미지에 해당하는 텐서입니다. 픽셀 값은image_processor_class를 사용하여 얻을 수 있습니다. 자세한 내용은image_processor_class.__call__를 참조하세요 (Idefics3Processor는 이미지 처리에image_processor_class를 사용합니다). - pixel_attention_mask (
torch.Tensor, shape(batch_size, image_size, image_size), 선택 사항) — 패딩 픽셀 인덱스에 대한 attention을 수행하지 않도록 하는 마스크입니다. - image_hidden_states (
torch.Tensor, shape(batch_size, num_channels, image_size, image_size)) — 모달리티 투영 이후 이미지 인코더의 히든 스테이트입니다. - labels (
torch.LongTensor, shape(batch_size, sequence_length), 선택 사항) — 마스크 언어 모델링 손실을 계산하는 데 사용되는 라벨입니다. 인덱스는[0, ..., text_config.]또는model.image_token_id범위에 있어야 합니다. 인덱스가model.image_token_id로 설정된 토큰은 무시(마스크)되며, 손실은[0, ..., text_config.]범위의 라벨을 가진 토큰에 대해서만 계산됩니다.
반환값
SequenceClassifierOutput 또는 tuple(torch.Tensor)
torch.Tensor의 튜플 또는 SequenceClassifierOutput입니다. return_dict=False가 전달되거나 config.return_dict=False인 경우에도 동일합니다. 구성(ModernVBertConfig)과 입력에 따라 다양한 요소를 포함합니다.
모델에 입력되는 데이터에는 임의의 개수의 이미지가 포함될 수 있습니다. 이를 처리하기 위해 모델에 전달되는 pixel_values에는 이미지 패딩이 적용되며, 형태는 (batch_size, max_num_images, 3, max_heights, max_widths)입니다. 여기서 max_num_images는 배치 내 batch_size개 샘플 중 가장 많은 이미지 개수입니다. 패딩 이미지는 모델 입구에서 pixel_values를 패딩하는 용도로만 필요하며, 그 이후에는 불필요합니다. 효율성을 위해 vision_model의 forward에 패딩 이미지를 제거한 실제 이미지, 즉 (image_batch_size, 3, height, width) 크기의 pixel_values만 전달합니다. 예를 들어 num_images_per_sample=[1, 3, 1, 2]이고 max_num_images가 3인 경우, image_batch_size는 7이 됩니다.
loss (
torch.Tensor, shape(1,), 선택 사항,labels이 제공될 때 반환됨) — 분류 (또는 config.num_labels==1인 경우 회귀) 손실.logits (
torch.Tensor, shape(batch_size, config.num_labels)) — SoftMax 적용 전 분류(또는 config.num_labels==1인 경우 회귀) 점수.hidden_states (
tuple(torch.Tensor), 선택 사항,output_hidden_states=True가 전달되거나config.output_hidden_states=True인 경우 반환됨) —torch.Tensor의 튜플(모델에 임베딩 레이어가 있는 경우 임베딩 출력 1개 + 각 레이어의 출력 1개)로, 모양은(batch_size, sequence_length, hidden_size)입니다.각 레이어의 출력에서 모델의 Hidden-states와 선택적 초기 임베딩 출력을 포함합니다.
attentions (
tuple(torch.Tensor), 선택 사항,output_attentions=True가 전달되었거나config.output_attentions=True인 경우 반환됨) — 각 레이어마다 하나씩 포함된torch.Tensor의 튜플로, 모양은(batch_size, num_heads, sequence_length, sequence_length)입니다.self-attention 헤드에서 가중 평균을 계산하는 데 사용되는 attention softmax 이후의 attention 가중치.
단일 레이블 분류의 예시:
>>> import torch
>>> from transformers import AutoTokenizer, ModernVBertForSequenceClassification
>>> tokenizer = AutoTokenizer.from_pretrained("ModernVBERT/modernvbert")
>>> model = ModernVBertForSequenceClassification.from_pretrained("ModernVBERT/modernvbert")
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
>>> with torch.no_grad():
... logits = model(**inputs).logits
>>> predicted_class_id = logits.argmax().item()
>>> model.config.id2label[predicted_class_id]
...
>>> # To train a model on `num_labels` classes, you can pass `num_labels=num_labels` to `.from_pretrained(...)`
>>> num_labels = len(model.config.id2label)
>>> model = ModernVBertForSequenceClassification.from_pretrained("ModernVBERT/modernvbert", num_labels=num_labels)
>>> labels = torch.tensor([1])
>>> loss = model(**inputs, labels=labels).loss
>>> round(loss.item(), 2)
...다중 레이블 분류의 예시:
>>> import torch
>>> from transformers import AutoTokenizer, ModernVBertForSequenceClassification
>>> tokenizer = AutoTokenizer.from_pretrained("ModernVBERT/modernvbert")
>>> model = ModernVBertForSequenceClassification.from_pretrained("ModernVBERT/modernvbert", problem_type="multi_label_classification")
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
>>> with torch.no_grad():
... logits = model(**inputs).logits
>>> predicted_class_ids = torch.arange(0, logits.shape[-1])[torch.sigmoid(logits).squeeze(dim=0) > 0.5]
>>> # To train a model on `num_labels` classes, you can pass `num_labels=num_labels` to `.from_pretrained(...)`
>>> num_labels = len(model.config.id2label)
>>> model = ModernVBertForSequenceClassification.from_pretrained(
... "ModernVBERT/modernvbert", num_labels=num_labels, problem_type="multi_label_classification"
... )
>>> labels = torch.sum(
... torch.nn.functional.one_hot(predicted_class_ids[None, :].clone(), num_classes=num_labels), dim=1
... ).to(torch.float)
>>> loss = model(**inputs, labels=labels).lossModernVBertForTokenClassification
클래스 transformers.ModernVBertForTokenClassification
< source >( config: ModernVBertConfig )
매개변수
- config (ModernVBertConfig) — 모델의 모든 매개변수를 포함하는 모델 구성 클래스입니다. 구성 파일로 초기화하는 것은 모델과 관련된 가중치를 로드하지 않으며, 구성 정보만 로드합니다. 모델 가중치를 로드하려면 from_pretrained() 메서드를 확인하세요.
토큰 분류 헤드가 위에 있는 ModernVBert 모델로, 예를 들어 Named Entity Recognition (NER) 작업에 사용됩니다.
이 모델은 PreTrainedModel에서 상속됩니다. 라이브러리가 모든 모델에 대해 구현하는 일반적 메서드(다운로드 또는 저장, 입력 임베딩 크기 조정, 헤드 프루닝 등)에 대한 세부 사항은 상위 클래스 문서를 확인하세요.
이 모델은 또한 PyTorch torch.nn.Module의 하위 클래스입니다. 일반적인 PyTorch Module처럼 사용하며, 일반적인 사용법 및 동작과 관련된 모든 사항은 PyTorch 문서를 참조하세요.
forward
< source >( input_ids: LongTensor = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Noneinputs_embeds: typing.Optional[torch.Tensor] = Nonepixel_values: typing.Optional[torch.Tensor] = Nonepixel_attention_mask: typing.Optional[torch.BoolTensor] = Noneimage_hidden_states: typing.Optional[torch.Tensor] = Nonelabels: typing.Optional[torch.LongTensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → TokenClassifierOutput or tuple(torch.Tensor)
매개변수
- input_ids (
torch.LongTensor형상이(batch_size, sequence_length), 선택 사항) — 어휘(input vocabulary)에서 입력 시퀀스 토큰의 인덱스입니다. 기본적으로 패딩은 무시됩니다.AutoTokenizer를 사용하여 인덱스를 얻을 수 있습니다. 자세한 내용은 PreTrainedTokenizer.encode() 및 PreTrainedTokenizer.call()를 참조하세요.
- attention_mask (
torch.Tensor형상이(batch_size, sequence_length), 선택 사항) — 패딩 토큰 인덱스에 대한 attention을 수행하지 않도록 방지하는 마스크. [0, 1]에서 선택된 마스크 값: 마스크되지 않은 토큰은 1, 마스크된 토큰은 0. attention mask란 무엇인가요?[0, 1]:- 마스크되지 않은 토큰에 대해 1
- 마스크된 토큰에 대해 0
- position_ids (
torch.LongTensor의 shape(batch_size, sequence_length), , 선택 사항) — 위치 임베딩에서 각 입력 시퀀스 토큰의 위치 인덱스. 범위[0, config.n_positions - 1]. - inputs_embeds (
torch.Tensor, shape(batch_size, sequence_length, hidden_size), 선택) —input_ids를 전달하는 대신 임베딩 표현을 직접 전달할 수 있습니다. 이는 모델 내부의 임베딩 조회 행렬보다input_ids인덱스를 관련 벡터로 변환하는 방식에 대해 더 세밀한 제어가 필요한 경우에 유용합니다. - pixel_values (
torch.Tensor, shape(batch_size, num_channels, image_size, image_size), 선택 사항) — 입력 이미지에 해당하는 텐서입니다. 픽셀 값은image_processor_class를 사용하여 얻을 수 있습니다. 자세한 내용은image_processor_class.__call__를 참조하세요 (Idefics3Processor는 이미지 처리에image_processor_class를 사용합니다). - pixel_attention_mask (
torch.Tensor, shape(batch_size, image_size, image_size), 선택 사항) — 패딩 픽셀 인덱스에 대한 attention을 수행하지 않도록 하는 마스크입니다. - image_hidden_states (
torch.Tensor, shape(batch_size, num_channels, image_size, image_size)) — 모달리티 투영 이후 이미지 인코더의 히든 스테이트입니다. - labels (
torch.LongTensor, shape(batch_size, sequence_length), 선택 사항) — 마스크 언어 모델링 손실을 계산하는 데 사용되는 라벨입니다. 인덱스는[0, ..., text_config.]또는model.image_token_id범위에 있어야 합니다. 인덱스가model.image_token_id로 설정된 토큰은 무시(마스크)되며, 손실은[0, ..., text_config.]범위의 라벨을 가진 토큰에 대해서만 계산됩니다.
반환값
TokenClassifierOutput 또는 tuple(torch.Tensor)
torch.Tensor의 튜플 또는 TokenClassifierOutput입니다. return_dict=False가 전달되었거나 config.return_dict=False인 경우, 구성(ModernVBertConfig)과 입력에 따라 다양한 요소를 포함합니다.
모델에 입력되는 데이터에는 임의의 개수의 이미지가 포함될 수 있습니다. 이를 처리하기 위해 모델에 전달되는 pixel_values에는 이미지 패딩이 적용되며, 형태는 (batch_size, max_num_images, 3, max_heights, max_widths)입니다. 여기서 max_num_images는 배치 내 batch_size개 샘플 중 가장 많은 이미지 개수입니다. 패딩 이미지는 모델 입구에서 pixel_values를 패딩하는 용도로만 필요하며, 그 이후에는 불필요합니다. 효율성을 위해 vision_model의 forward에 패딩 이미지를 제거한 실제 이미지, 즉 (image_batch_size, 3, height, width) 크기의 pixel_values만 전달합니다. 예를 들어 num_images_per_sample=[1, 3, 1, 2]이고 max_num_images가 3인 경우, image_batch_size는 7이 됩니다.
loss (
torch.Tensor, shape(1,), 선택 사항,labels이 제공될 때 반환됨) — 분류 손실.logits (
torch.Tensor, shape(batch_size, sequence_length, config.num_labels)) — SoftMax 적용 전 분류 점수.hidden_states (
tuple(torch.Tensor), 선택 사항,output_hidden_states=True가 전달되거나config.output_hidden_states=True인 경우 반환됨) —torch.Tensor의 튜플(모델에 임베딩 레이어가 있는 경우 임베딩 출력 1개 + 각 레이어의 출력 1개)로, 모양은(batch_size, sequence_length, hidden_size)입니다.각 레이어의 출력에서 모델의 Hidden-states와 선택적 초기 임베딩 출력을 포함합니다.
attentions (
tuple(torch.Tensor), 선택 사항,output_attentions=True가 전달되었거나config.output_attentions=True인 경우 반환됨) — 각 레이어마다 하나씩 포함된torch.Tensor의 튜플로, 모양은(batch_size, num_heads, sequence_length, sequence_length)입니다.self-attention 헤드에서 가중 평균을 계산하는 데 사용되는 attention softmax 이후의 attention 가중치.
예:
>>> from transformers import AutoTokenizer, ModernVBertForTokenClassification
>>> import torch
>>> tokenizer = AutoTokenizer.from_pretrained("ModernVBERT/modernvbert")
>>> model = ModernVBertForTokenClassification.from_pretrained("ModernVBERT/modernvbert")
>>> inputs = tokenizer(
... "HuggingFace is a company based in Paris and New York", add_special_tokens=False, return_tensors="pt"
... )
>>> with torch.no_grad():
... logits = model(**inputs).logits
>>> predicted_token_class_ids = logits.argmax(-1)
>>> # Note that tokens are classified rather then input words which means that
>>> # there might be more predicted token classes than words.
>>> # Multiple token classes might account for the same word
>>> predicted_tokens_classes = [model.config.id2label[t.item()] for t in predicted_token_class_ids[0]]
>>> predicted_tokens_classes
...
>>> labels = predicted_token_class_ids
>>> loss = model(**inputs, labels=labels).loss
>>> round(loss.item(), 2)
...