Transformers documentation

BROS

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v5.22.1).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

이 모델은 2021-08-10에 HF papers에 게시되었으며, 2023-09-15에 Hugging Face Transformers에 기여되었습니다.

BROS

개요

BROS 모델은 Teakgyu Hong, Donghyun Kim, Mingi Ji, Wonseok Hwang, Daehyun Nam, Sungrae Park가 BROS: A Pre-trained Language Model Focusing on Text and Layout for Better Key Information Extraction from Documents에서 제안했습니다.

BROS는 BERT Relying On Spatiality의 약자입니다. 이는 토큰 시퀀스와 해당 바운딩 박스를 입력으로 받아 숨겨진 상태(hidden states) 시퀀스를 출력하는 인코더 전용 Transformer 모델입니다. BROS는 절대 공간 정보 대신 상대 공간 정보를 인코딩합니다.

두 가지 목적 함수로 사전 학습됩니다: BERT에서 사용된 토큰 마스킹 언어 모델링 목적 함수(TMLM)와 새로운 영역 마스킹 언어 모델링 목적 함수(AMLM)입니다. TMLM에서는 토큰이 무작위로 마스킹되며, 모델은 공간 정보와 다른 마스킹되지 않은 토큰을 사용하여 마스킹된 토큰을 예측합니다. AMLM은 TMLM의 2D 버전입니다. 텍스트 토큰을 무작위로 마스킹하고 TMLM과 동일한 정보로 예측하지만, 텍스트 블록(영역)을 마스킹합니다.

BrosForTokenClassification은 BrosModel 위에 간단한 선형 레이어를 갖추고 있으며, 각 토큰의 라벨을 예측합니다. BrosSpadeEEForTokenClassification은 BrosModel 위에 initial_token_classifier와 subsequent_token_classifier를 갖추고 있습니다. initial_token_classifier는 각 엔티티의 첫 번째 토큰을 예측하는 데 사용되고, subsequent_token_classifier는 엔티티 내의 다음 토큰을 예측하는 데 사용됩니다. BrosSpadeELForTokenClassification는 BrosModel 위에 entity_linker를 갖추고 있습니다. entity_linker는 두 엔티티 간의 관계를 예측하는 데 사용됩니다.

BrosForTokenClassification와 BrosSpadeEEForTokenClassification는 기본적으로 동일한 작업을 수행합니다. 다만, BrosForTokenClassification는 입력 토큰이 완벽하게 직렬화되어 있다고 가정합니다(2D 공간에 존재하므로 매우 어려운 작업입니다). 반면 BrosSpadeEEForTokenClassification는 하나의 토큰에서 다음 연결 토큰을 예측하므로 직렬화 오류를 처리하는 데 더 유연합니다.

BrosSpadeELForTokenClassification은 엔티티 내 링크링 작업을 수행합니다. 두 엔티티가 어떤 관계를 공유하는 경우, 한 엔티티의 토큰에서 다른 엔티티의 토큰으로의 관계를 예측합니다.

BROS는 명시적인 시각적 특징에 의존하지 않으면서도 FUNSD, SROIE, CORD, SciTSR과 같은 주요 정보 추출(KIE) 벤치마크에서 동등하거나 더 나은 결과를 달성합니다.

해당 논문의 초록은 다음과 같습니다:

문서 이미지에서 주요 정보 추출(KIE)을 수행하려면 2차원(2D) 공간에서 텍스트의 문맥적 및 공간적 의미를 이해해야 합니다. 최근 많은 연구들은 문서 이미지의 시각적 특징과 텍스트 및 레이아웃을 결합하는 데 초점을 맞춘 사전 학습 언어 모델을 개발하여 이 문제를 해결하려고 시도하고 있습니다. 반면, 본 논문은 기본으로 돌아가 텍스트와 레이아웃의 효과적인 결합이라는 관점에서 문제를 다룹니다. 구체적으로, 2D 공간에서 텍스트의 상대적 위치를 인코딩하고 영역 마스킹 전략을 통해 라벨이 없는 문서에서 학습하는 사전 학습 언어 모델인 BROS(BERT Relying On Spatiality)를 제안합니다. 2D 공간의 텍스트 이해를 위한 최적화된 학습 방식을 통해, BROS는 시각적 특징에 의존하지 않으면서도 4개의 KIE 벤치마크(FUNSD, SROIE, CORD, SciTSR)에서 기존 방법들과 동등하거나 더 나은 성능을 보여줍니다. 본 논문은 또한 KIE 작업의 두 가지 현실적 과제, 즉 (1) 잘못된 텍스트 순서로 인한 오류 최소화 및 (2) 적은 수의 다운스트림 예제에서 효율적인 학습을 제시하고, BROS가 기존 방법들보다 우월함을 입증합니다.*

이 모델은 jinho8345님이 기여했습니다. 원본 코드는 여기에서 찾을 수 있습니다.

사용 팁 및 예제

  • forward()는 input_ids와 bbox(바운딩 박스)를 요구합니다. 각 바운딩 박스는 (x0, y0, x1, y1) 형식(좌상단 코너, 우하단 코너)이어야 합니다. 바운딩 박스를 얻는 방법은 외부 OCR 시스템에 따라 달라집니다. x 좌표는 문서 이미지의 너비로 정규화하고, y 좌표는 문서 이미지의 높이로 정규화해야 합니다.
def expand_and_normalize_bbox(bboxes, doc_width, doc_height):
    # here, bboxes are numpy array

    # Normalize bbox -> 0 ~ 1
    bboxes[:, [0, 2]] = bboxes[:, [0, 2]] / width
    bboxes[:, [1, 3]] = bboxes[:, [1, 3]] / height
  • [~transformers.BrosForTokenClassification.forward, ~transformers.BrosSpadeEEForTokenClassification.forward, ~transformers.BrosSpadeEEForTokenClassification.forward]은 손실 계산에 input_ids와 bbox뿐만 아니라 box_first_token_mask도 필요합니다. 이는 각 박스의 첫 번째 토큰이 아닌 토큰을 필터링하는 마스크입니다. input_ids를 단어에서 생성할 때 바운딩 박스의 시작 토큰 인덱스를 저장하여 이 마스크를 얻을 수 있습니다. 다음 코드로 box_first_token_mask를 만들 수 있습니다.
def make_box_first_token_mask(bboxes, words, tokenizer, max_seq_length=512):

    box_first_token_mask = np.zeros(max_seq_length, dtype=np.bool_)

    # encode(tokenize) each word from words (list[str])
    input_ids_list: list[list[int]] = [tokenizer.encode(e, add_special_tokens=False) for e in words]

    # get the length of each box
    tokens_length_list: list[int] = [len(l) for l in input_ids_list]

    box_end_token_indices = np.array(list(itertools.accumulate(tokens_length_list)))
    box_start_token_indices = box_end_token_indices - np.array(tokens_length_list)

    # filter out the indices that are out of max_seq_length
    box_end_token_indices = box_end_token_indices[box_end_token_indices < max_seq_length - 1]
    if len(box_start_token_indices) > len(box_end_token_indices):
        box_start_token_indices = box_start_token_indices[: len(box_end_token_indices)]

    # set box_start_token_indices to True
    box_first_token_mask[box_start_token_indices] = True

    return box_first_token_mask

리소스

  • 데모 스크립트는 여기에서 찾을 수 있습니다.

BrosConfig

클래스 transformers.BrosConfig

< >

( 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 = Nonevocab_size: int = 30522hidden_size: int = 768num_hidden_layers: int = 12num_attention_heads: int = 12intermediate_size: int = 3072hidden_act: str = 'gelu'hidden_dropout_prob: float | int = 0.1attention_probs_dropout_prob: float | int = 0.1max_position_embeddings: int = 512type_vocab_size: int = 2initializer_range: float = 0.02layer_norm_eps: float = 1e-12pad_token_id: int | None = 0dim_bbox: int = 8bbox_scale: float = 100.0n_relations: int = 1classifier_dropout_prob: float | int = 0.1is_decoder: bool = Falseadd_cross_attention: bool = False )

매개변수

  • vocab_size (int, 선택 사항, 기본값 30522) — 모델의 어휘 크기입니다. input_ids로 표현할 수 있는 서로 다른 토큰의 수를 정의합니다.
  • hidden_size (int, 선택 사항, 기본값 768) — 숨겨진 표현의 차원입니다.
  • num_hidden_layers (int, 선택 사항, 기본값 12) — Transformer 디코더의 숨겨진 레이어 수.
  • num_attention_heads (int, 선택 사항, 기본값 12) — Transformer decoder의 각 attention layer에 사용할 attention head의 수입니다.
  • intermediate_size (int, 선택 사항, 기본값 3072) — MLP 표현의 차원입니다.
  • hidden_act (str, 선택 사항, 기본값 gelu) — 디코더에서 사용되는 비선형 활성화 함수(함수 또는 문자열)입니다. 예를 들어, "gelu", "relu", "silu" 등이 있습니다.
  • hidden_dropout_prob (Union[float, int], 선택 사항, 기본값 0.1) — 임베딩, 인코더, 풀러의 모든 완전 연결 계층에 적용되는 드롭아웃 확률입니다.
  • attention_probs_dropout_prob (Union[float, int], 선택 사항, 기본값 0.1) — Attention 확률에 적용할 dropout 비율입니다.
  • max_position_embeddings (int, 선택 사항, 기본값 512) — 이 모델이 사용될 수 있는 최대 시퀀스 길이입니다.
  • type_vocab_size (int, 선택 사항, 기본값 2) — token_type_ids의 어휘 크기입니다.
  • initializer_range (float, 선택 사항, 기본값 0.02) — 모든 가중치 행렬을 초기화하는 truncated_normal_initializer의 표준 편차입니다.
  • layer_norm_eps (float, 선택 사항, 기본값 1e-12) — 레이어 정규화 레이어에서 사용되는 epsilon 값입니다.
  • pad_token_id (int, 선택 사항, 기본값 0) — 어휘에서 패딩에 사용되는 토큰 ID입니다.
  • dim_bbox (int, 선택 사항, 기본값 8) — 바운딩 박스 좌표의 차원입니다. (x0, y1, x1, y0, x1, y1, x0, y1)
  • bbox_scale (float, 선택 사항, 기본값 100.0) — 바운딩 박스 좌표의 스케일 팩터입니다.
  • n_relations (int, 선택 사항, 기본값 1) — SpadeEE(엔티티 추출), SpadeEL(엔티티 링크) 헤드의 관계 수입니다.
  • classifier_dropout_prob (Union[float, int], 선택 사항, 기본값 0.1) — classifier의 dropout 비율입니다.
  • is_decoder (bool, 선택 사항, 기본값 False) — 모델이 디코더로 사용되는지 여부입니다. False인 경우 모델은 인코더로 사용됩니다.
  • add_cross_attention (bool, 선택 사항, 기본값 False) — 모델에 cross-attention 레이어를 추가할지 여부.

이것은 BrosModel의 구성을 저장하기 위한 구성 클래스입니다. 지정된 인자에 따라 Bros 모델을 초기화하여 모델 아키텍처를 정의하는 데 사용됩니다. 기본값으로 구성을 초기화하면 jinho8345/bros-base-uncased와 유사한 구성이 생성됩니다.

Configuration 객체는 PreTrainedConfig를 상속하며 모델 출력을 제어하는 데 사용할 수 있습니다. 자세한 내용은 PreTrainedConfig의 문서를 참고하세요.

예:

>>> from transformers import BrosConfig, BrosModel

>>> # Initializing a BROS jinho8345/bros-base-uncased style configuration
>>> configuration = BrosConfig()

>>> # Initializing a model from the jinho8345/bros-base-uncased style configuration
>>> model = BrosModel(configuration)

>>> # Accessing the model configuration
>>> configuration = model.config

BrosProcessor

클래스 transformers.BrosProcessor

< >

( tokenizer = None**kwargs )

매개변수

  • tokenizer (BertTokenizer) — 토크나이저는 필수 입력값입니다.

토크나이저를 단일 프로세서로 래핑하는 BrosProcessor를 생성합니다.

BrosProcessor는 BertTokenizer의 모든 기능을 제공합니다. 자세한 내용은 ~BertTokenizer를 참고하세요.

__call__

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = Nonetext: str | list[str] | list[list[str]] | None = Nonevideos: typing.Union[list['PIL.Image.Image'], numpy.ndarray, ForwardRef('torch.Tensor'), list[numpy.ndarray], list['torch.Tensor'], list[list['PIL.Image.Image']], list[list[numpy.ndarray]], list[list['torch.Tensor']], transformers.video_utils.URL, list[transformers.video_utils.URL], list[list[transformers.video_utils.URL]], transformers.video_utils.Path, list[transformers.video_utils.Path], list[list[transformers.video_utils.Path]], NoneType] = Noneaudio: typing.Union[numpy.ndarray, ForwardRef('torch.Tensor'), collections.abc.Sequence[numpy.ndarray], collections.abc.Sequence['torch.Tensor'], NoneType] = None**kwargs: *<class 'transformers.processing_utils.ProcessingKwargs'> )

매개변수

  • images (Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]], 선택) — 전처리할 이미지입니다. 픽셀 값이 0에서 255 범위로 이루어진 단일 이미지 또는 배치 이미지를 기대합니다. 픽셀 값이 0에서 1 사이인 이미지를 전달하는 경우 do_rescale=False로 설정하세요.
  • text (Union[str, list[str], list[list[str]]], 선택 사항) — 인코딩할 시퀀스 또는 시퀀스 배치입니다. 각 시퀀스는 문자열 또는 문자열 목록(사전 토큰화된 문자열)일 수 있습니다. 사전 토큰화된 입력을 전달하는 경우, 배치 입력과의 혼동을 피하기 위해 is_split_into_words=True를 설정하세요.
  • videos (Union[list[PIL.Image.Image], numpy.ndarray, torch.Tensor, list[numpy.ndarray], list[torch.Tensor], list[list[PIL.Image.Image]], list[list[numpy.ndarray]], list[list[torch.Tensor]], ~video_utils.URL, list[~video_utils.URL], list[list[~video_utils.URL]], ~video_utils.Path, list[~video_utils.Path], list[list[~video_utils.Path]]], 선택) — 전처리할 비디오입니다. 픽셀 값이 0에서 255 범위를 가지는 단일 비디오 또는 비디오 배치(batch)를 기대합니다. 픽셀 값이 0에서 1 범위를 가지는 비디오를 전달하는 경우 do_rescale=False로 설정하십시오.
  • audio (Union[numpy.ndarray, torch.Tensor, collections.abc.Sequence[numpy.ndarray], collections.abc.Sequence[torch.Tensor]], 선택 사항) — 준비할 오디오 또는 오디오 배치입니다. 각 오디오는 NumPy 배열 또는 PyTorch 텐서일 수 있습니다. NumPy 배열/PyTorch 텐서의 경우, 각 오디오의 shape은 (C, T)여야 하며, 여기서 C는 채널 수, T는 오디오의 샘플 길이입니다.
  • return_tensors (str 또는 TensorType, 선택 사항) — 설정된 경우, 특정 프레임워크의 텐서를 반환합니다. 허용되는 값은 다음과 같습니다:
    • 'pt': PyTorch torch.Tensor 객체를 반환합니다.
    • 'np': NumPy np.ndarray 객체를 반환합니다.
  • **kwargs (ProcessingKwargs, 선택) — 각 모달리티(텍스트, 이미지, 비디오, 오디오)에 대한 추가 처리 옵션입니다. 모델별 매개변수는 위에 나열되어 있으며, 지원되는 인수의 전체 목록은 TypedDict 클래스를 참조하세요.

BrosModel

클래스 transformers.BrosModel

< >

( config: BrosConfigadd_pooling_layer = True )

매개변수

  • config (BrosConfig) — 모델의 모든 매개변수를 포함하는 모델 구성 클래스입니다. 구성 파일로 초기화하는 것은 모델과 연관된 가중치를 로드하지 않으며, 구성 정보만 로드합니다. 모델 가중치를 로드하려면 from_pretrained() 메서드를 확인하세요.
  • add_pooling_layer (bool, 선택 사항, 기본값 True) — pooling layer를 추가할지 여부

특정 헤드가 위에 없는 맨 Bros Model은 원시 hidden-states를 출력합니다.

이 모델은 PreTrainedModel에서 상속됩니다. 라이브러리가 모든 모델에 대해 구현하는 일반적 메서드(다운로드 또는 저장, 입력 임베딩 크기 조정, 헤드 프루닝 등)에 대한 세부 사항은 상위 클래스 문서를 확인하세요.

이 모델은 또한 PyTorch torch.nn.Module의 하위 클래스입니다. 일반적인 PyTorch Module처럼 사용하며, 일반적인 사용법 및 동작과 관련된 모든 사항은 PyTorch 문서를 참조하세요.

forward

< >

( input_ids: typing.Optional[torch.Tensor] = Nonebbox: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Nonetoken_type_ids: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.Tensor] = Noneinputs_embeds: typing.Optional[torch.Tensor] = Noneencoder_hidden_states: typing.Optional[torch.Tensor] = Noneencoder_attention_mask: typing.Optional[torch.Tensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutputWithPoolingAndCrossAttentions or tuple(torch.Tensor)

매개변수

  • input_ids (torch.Tensor 의 shape (batch_size, sequence_length), , 선택 사항) — 어휘(input vocabulary)에서 입력 시퀀스 토큰의 인덱스입니다. 기본적으로 패딩은 무시됩니다.

    AutoTokenizer를 사용하여 인덱스를 얻을 수 있습니다. 자세한 내용은 PreTrainedTokenizer.encode() 및 PreTrainedTokenizer.call()를 참조하세요.

    입력 ID란 무엇인가요?

  • bbox ('torch.Tensor', shape ‘(batch_size, num_boxes, 4)’) — 입력 시퀀스의 각 토큰에 대한 바운딩 박스 좌표. 각 바운딩 박스는 네 개의 값 (x1, y1, x2, y2)로 이루어진 리스트이며, (x1, y1)은 바운딩 박스의 왼쪽 위 모서리, (x2, y2)는 오른쪽 아래 모서리를 나타냅니다.
  • attention_mask (torch.Tensor 형상이 (batch_size, sequence_length), 선택 사항) — 패딩 토큰 인덱스에 대한 attention을 수행하지 않도록 방지하는 마스크. [0, 1]에서 선택된 마스크 값: 마스크되지 않은 토큰은 1, 마스크된 토큰은 0. attention mask란 무엇인가요? [0, 1]:
    • 마스크되지 않은 토큰에 대해 1
    • 마스크된 토큰에 대해 0

    어텐션 마스크란 무엇인가요?

  • token_type_ids (torch.Tensor 형상 (batch_size, sequence_length), 선택 사항) — 입력의 첫 번째 및 두 번째 부분을 나타내는 세그먼트 토큰 인덱스. 인덱스는 [0, 1]:
    • 0은 sentence A 토큰에 해당합니다.
    • 1은 sentence B 토큰에 해당합니다.

    토큰 타입 ID란 무엇인가요?

  • position_ids (torch.Tensor 의 shape (batch_size, sequence_length), , 선택 사항) — 입력 시퀀스 토큰의 위치 임베딩에서 각 토큰의 위치 인덱스. 범위는 [0, config.n_positions - 1].

    포지션 ID란 무엇인가요?

  • inputs_embeds (torch.Tensor, shape (batch_size, sequence_length, hidden_size), 선택) — input_ids를 전달하는 대신 임베딩 표현을 직접 전달할 수 있습니다. 이는 모델 내부의 임베딩 조회 행렬보다 input_ids 인덱스를 관련 벡터로 변환하는 방식에 대해 더 세밀한 제어가 필요한 경우에 유용합니다.
  • encoder_hidden_states (torch.Tensor, shape (batch_size, sequence_length, hidden_size), 선택 사항) — 인코더의 마지막 레이어 출력에서 생성된 hidden-states 시퀀스입니다. 모델이 decoder로 구성된 경우 cross-attention에 사용됩니다.
  • encoder_attention_mask (torch.Tensor 형상이 (batch_size, sequence_length), 선택 사항) — 인코더 입력의 패딩 토큰 인덱스에 대한 attention을 수행하지 않도록 하는 마스크입니다. 모델이 decoder로 구성된 경우 cross-attention에 이 마스크가 사용됩니다. [0, 1]:
    • 마스크되지 않은 토큰에 대해 1
    • 마스크된 토큰에 대해 0

반환값

BaseModelOutputWithPoolingAndCrossAttentions 또는 tuple(torch.Tensor)

torch.Tensor의 튜플 또는 BaseModelOutputWithPoolingAndCrossAttentions(return_dict=False가 전달되었거나 config.return_dict=False인 경우)로, 구성(BrosConfig)과 입력에 따라 다양한 요소를 포함합니다.

BrosModel의 forward 메서드는 __call__ 특수 메서드를 오버라이드합니다.

이 함수 내에서 forward pass의 레시피를 정의해야 하지만, 이후에는 이 함수 대신 Module 인스턴스를 호출해야 합니다. 전자는 전처리 및 후처리 단계를 실행하는 것을 처리하는 반면, 후자는 이를 조용히 무시하기 때문입니다.

  • last_hidden_state (torch.Tensor, shape (batch_size, sequence_length, hidden_size)) — 모델의 마지막 레이어 출력에서 생성된 hidden-state 시퀀스입니다.

  • pooler_output (torch.Tensor, shape (batch_size, hidden_size)) — 보조 사전 학습 작업을 위해 사용되는 레이어들을 통해 추가 처리된 시퀀스의 첫 번째 토큰(분류 토큰)의 마지막 레이어 hidden-state입니다. 예를 들어 BERT 계열 모델의 경우, 선형 레이어와 tanh 활성화 함수를 통해 처리된 후의 분류 토큰을 반환합니다. 선형 레이어의 가중치는 사전 학습 동안 다음 문장 예측(분류) 목적 함수를 통해 학습됩니다.

  • 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 가중치.

  • cross_attentions (tuple(torch.Tensor), 선택 사항, output_attentions=True와 config.add_cross_attention=True가 전달되었거나 config.output_attentions=True인 경우 반환됨) — 각 레이어마다 하나씩 포함된 torch.Tensor의 튜플로, 모양은 (batch_size, num_heads, sequence_length, sequence_length)입니다.

    decoder의 cross-attention 레이어에서 attention softmax를 적용한 후, cross-attention 헤드에서 가중 평균을 계산하는 데 사용되는 attention 가중치입니다.

  • past_key_values (Cache, 선택 사항, use_cache=True가 전달되었거나 config.use_cache=True인 경우 반환됨) — Cache 인스턴스입니다. 자세한 내용은 kv cache 가이드를 참고하세요.

    순차적 디코딩을 가속화하는 데 사용할 수 있는 사전 계산된 hidden-states(셀프 어텐션 블록의 key와 value, 그리고 config.is_encoder_decoder=True인 경우 크로스 어텐션 블록의 key와 value)를 포함합니다(입력 past_key_values 참조).

예:

>>> import torch
>>> from transformers import BrosProcessor, BrosModel

>>> processor = BrosProcessor.from_pretrained("jinho8345/bros-base-uncased")

>>> model = BrosModel.from_pretrained("jinho8345/bros-base-uncased")

>>> encoding = processor("Hello, my dog is cute", add_special_tokens=False, return_tensors="pt")
>>> bbox = torch.tensor([[[0, 0, 1, 1]]]).repeat(1, encoding["input_ids"].shape[-1], 1)
>>> encoding["bbox"] = bbox

>>> outputs = model(**encoding)
>>> last_hidden_states = outputs.last_hidden_state

BrosForTokenClassification

클래스 transformers.BrosForTokenClassification

< >

( config: BrosConfig )

매개변수

  • config (BrosConfig) — 모델의 모든 매개변수를 포함하는 모델 구성 클래스입니다. 구성 파일로 초기화하는 것은 모델과 연관된 가중치를 로드하지 않으며, 구성 정보만 로드합니다. 모델 가중치를 로드하려면 from_pretrained() 메서드를 확인하세요.

토큰 분류 헤드가 위에 있는 Bros transformer(예: Named-Entity-Recognition(NER) 작업)입니다. 이 헤드는 hidden-states 출력 위에 있는 선형 레이어입니다.

이 모델은 PreTrainedModel에서 상속됩니다. 라이브러리가 모든 모델에 대해 구현하는 일반적 메서드(다운로드 또는 저장, 입력 임베딩 크기 조정, 헤드 프루닝 등)에 대한 세부 사항은 상위 클래스 문서를 확인하세요.

이 모델은 또한 PyTorch torch.nn.Module의 하위 클래스입니다. 일반적인 PyTorch Module처럼 사용하며, 일반적인 사용법 및 동작과 관련된 모든 사항은 PyTorch 문서를 참조하세요.

forward

< >

( input_ids: typing.Optional[torch.Tensor] = Nonebbox: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Nonebbox_first_token_mask: typing.Optional[torch.Tensor] = Nonetoken_type_ids: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.Tensor] = Noneinputs_embeds: typing.Optional[torch.Tensor] = Nonelabels: typing.Optional[torch.Tensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → TokenClassifierOutput or tuple(torch.Tensor)

매개변수

  • input_ids (torch.Tensor 의 shape (batch_size, sequence_length), , 선택 사항) — 어휘(input vocabulary)에서 입력 시퀀스 토큰의 인덱스입니다. 기본적으로 패딩은 무시됩니다.

    AutoTokenizer를 사용하여 인덱스를 얻을 수 있습니다. 자세한 내용은 PreTrainedTokenizer.encode() 및 PreTrainedTokenizer.call()를 참조하세요.

    입력 ID란 무엇인가요?

  • bbox ('torch.Tensor', shape ‘(batch_size, num_boxes, 4)’) — 입력 시퀀스의 각 토큰에 대한 바운딩 박스 좌표. 각 바운딩 박스는 네 개의 값 (x1, y1, x2, y2)로 이루어진 리스트이며, (x1, y1)은 바운딩 박스의 왼쪽 위 모서리, (x2, y2)는 오른쪽 아래 모서리를 나타냅니다.
  • attention_mask (torch.Tensor 형상이 (batch_size, sequence_length), 선택 사항) — 패딩 토큰 인덱스에 대한 attention을 수행하지 않도록 방지하는 마스크. [0, 1]에서 선택된 마스크 값: 마스크되지 않은 토큰은 1, 마스크된 토큰은 0. attention mask란 무엇인가요? [0, 1]:
    • 마스크되지 않은 토큰에 대해 1
    • 마스크된 토큰에 대해 0

    어텐션 마스크란 무엇인가요?

  • bbox_first_token_mask (torch.Tensor shape (batch_size, sequence_length), 선택 사항) — 각 바운딩 박스의 첫 번째 토큰을 나타내는 마스크. [0, 1]:
    • 마스크되지 않은 토큰에 대해 1
    • 마스크된 토큰에 대해 0
  • token_type_ids (torch.Tensor 형상 (batch_size, sequence_length), 선택 사항) — 입력의 첫 번째 및 두 번째 부분을 나타내는 세그먼트 토큰 인덱스. 인덱스는 [0, 1]:
    • 0은 sentence A 토큰에 해당합니다.
    • 1은 sentence B 토큰에 해당합니다.

    토큰 타입 ID란 무엇인가요?

  • position_ids (torch.Tensor 의 shape (batch_size, sequence_length), , 선택 사항) — 입력 시퀀스 토큰의 위치 임베딩에서 각 토큰의 위치 인덱스. 범위는 [0, config.n_positions - 1].

    포지션 ID란 무엇인가요?

  • inputs_embeds (torch.Tensor, shape (batch_size, sequence_length, hidden_size), 선택) — input_ids를 전달하는 대신 임베딩 표현을 직접 전달할 수 있습니다. 이는 모델 내부의 임베딩 조회 행렬보다 input_ids 인덱스를 관련 벡터로 변환하는 방식에 대해 더 세밀한 제어가 필요한 경우에 유용합니다.
  • labels (torch.LongTensor, shape (batch_size, sequence_length), 선택 사항) — 토큰 분류 손실을 계산하는 데 사용되는 라벨입니다. 인덱스는 [0, ..., config.num_labels - 1] 범위에 있어야 합니다.

반환값

TokenClassifierOutput 또는 tuple(torch.Tensor)

torch.Tensor의 튜플 또는 TokenClassifierOutput입니다. 구성(BrosConfig)과 입력에 따라 다양한 요소를 포함하며, return_dict=False가 전달되거나 config.return_dict=False인 경우에도 동일합니다.

BrosForTokenClassification의 forward 메서드는 __call__ 특수 메서드를 오버라이드합니다.

이 함수 내에서 forward pass의 레시피를 정의해야 하지만, 이후에는 이 함수 대신 Module 인스턴스를 호출해야 합니다. 전자는 전처리 및 후처리 단계를 실행하는 것을 처리하는 반면, 후자는 이를 조용히 무시하기 때문입니다.

  • 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 가중치.

예:

>>> import torch
>>> from transformers import BrosProcessor, BrosForTokenClassification

>>> processor = BrosProcessor.from_pretrained("jinho8345/bros-base-uncased")

>>> model = BrosForTokenClassification.from_pretrained("jinho8345/bros-base-uncased")

>>> encoding = processor("Hello, my dog is cute", add_special_tokens=False, return_tensors="pt")
>>> bbox = torch.tensor([[[0, 0, 1, 1]]]).repeat(1, encoding["input_ids"].shape[-1], 1)
>>> encoding["bbox"] = bbox

>>> outputs = model(**encoding)

BrosSpadeEEForTokenClassification

class transformers.BrosSpadeEEForTokenClassification

< >

( config: BrosConfig )

매개변수

  • config (BrosConfig) — 모델의 모든 매개변수를 포함하는 모델 구성 클래스입니다. 구성 파일로 초기화하는 것은 모델과 연관된 가중치를 로드하지 않으며, 구성 정보만 로드합니다. 모델 가중치를 로드하려면 from_pretrained() 메서드를 확인하세요.

initial_token_layers와 subsequent_token_layer가 hidden-states 출력 위에 있는 토큰 분류 헤드를 가진 Bros 모델입니다. 예를 들어, Named-Entity-Recognition(NER) 작업에 사용됩니다. initial_token_classifier는 각 엔티티의 첫 번째 토큰을 예측하는 데 사용되고, subsequent_token_classifier는 엔티티 내의 후속 토큰을 예측하는 데 사용됩니다. BrosForTokenClassification와 비교할 때, 이 모델은 토큰 하나에서 다음 토큰을 예측하기 때문에 직렬화 오류에 대해 더 강건합니다.

이 모델은 PreTrainedModel에서 상속됩니다. 라이브러리가 모든 모델에 대해 구현하는 일반적 메서드(다운로드 또는 저장, 입력 임베딩 크기 조정, 헤드 프루닝 등)에 대한 세부 사항은 상위 클래스 문서를 확인하세요.

이 모델은 또한 PyTorch torch.nn.Module의 하위 클래스입니다. 일반적인 PyTorch Module처럼 사용하며, 일반적인 사용법 및 동작과 관련된 모든 사항은 PyTorch 문서를 참조하세요.

forward

< >

( input_ids: typing.Optional[torch.Tensor] = Nonebbox: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Nonebbox_first_token_mask: typing.Optional[torch.Tensor] = Nonetoken_type_ids: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.Tensor] = Noneinputs_embeds: typing.Optional[torch.Tensor] = Noneinitial_token_labels: typing.Optional[torch.Tensor] = Nonesubsequent_token_labels: typing.Optional[torch.Tensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BrosSpadeOutput or tuple(torch.Tensor)

매개변수

  • input_ids (torch.Tensor 의 shape (batch_size, sequence_length), , 선택 사항) — 어휘(input vocabulary)에서 입력 시퀀스 토큰의 인덱스입니다. 기본적으로 패딩은 무시됩니다.

    AutoTokenizer를 사용하여 인덱스를 얻을 수 있습니다. 자세한 내용은 PreTrainedTokenizer.encode() 및 PreTrainedTokenizer.call()를 참조하세요.

    입력 ID란 무엇인가요?

  • bbox ('torch.Tensor', shape ‘(batch_size, num_boxes, 4)’) — 입력 시퀀스의 각 토큰에 대한 바운딩 박스 좌표. 각 바운딩 박스는 네 개의 값 (x1, y1, x2, y2)로 이루어진 리스트이며, (x1, y1)은 바운딩 박스의 왼쪽 위 모서리, (x2, y2)는 오른쪽 아래 모서리를 나타냅니다.
  • attention_mask (torch.Tensor 형상이 (batch_size, sequence_length), 선택 사항) — 패딩 토큰 인덱스에 대한 attention을 수행하지 않도록 방지하는 마스크. [0, 1]에서 선택된 마스크 값: 마스크되지 않은 토큰은 1, 마스크된 토큰은 0. attention mask란 무엇인가요? [0, 1]:
    • 마스크되지 않은 토큰에 대해 1
    • 마스크된 토큰에 대해 0

    어텐션 마스크란 무엇인가요?

  • bbox_first_token_mask (torch.Tensor shape (batch_size, sequence_length), 선택 사항) — 각 바운딩 박스의 첫 번째 토큰을 나타내는 마스크. [0, 1]:
    • 마스크되지 않은 토큰에 대해 1
    • 마스크된 토큰에 대해 0
  • token_type_ids (torch.Tensor 형상 (batch_size, sequence_length), 선택 사항) — 입력의 첫 번째 및 두 번째 부분을 나타내는 세그먼트 토큰 인덱스. 인덱스는 [0, 1]:
    • 0은 sentence A 토큰에 해당합니다.
    • 1은 sentence B 토큰에 해당합니다.

    토큰 타입 ID란 무엇인가요?

  • position_ids (torch.Tensor 의 shape (batch_size, sequence_length), , 선택 사항) — 입력 시퀀스 토큰의 위치 임베딩에서 각 토큰의 위치 인덱스. 범위는 [0, config.n_positions - 1].

    포지션 ID란 무엇인가요?

  • inputs_embeds (torch.Tensor, shape (batch_size, sequence_length, hidden_size), 선택) — input_ids를 전달하는 대신 임베딩 표현을 직접 전달할 수 있습니다. 이는 모델 내부의 임베딩 조회 행렬보다 input_ids 인덱스를 관련 벡터로 변환하는 방식에 대해 더 세밀한 제어가 필요한 경우에 유용합니다.
  • initial_token_labels (torch.LongTensor, shape (batch_size, sequence_length), 선택 사항) — 초기 토큰 분류를 위한 라벨입니다.
  • subsequent_token_labels (torch.LongTensor, shape (batch_size, sequence_length), 선택 사항) — 다음 토큰 분류를 위한 라벨입니다.

반환값

BrosSpadeOutput 또는 tuple(torch.Tensor)

BrosSpadeOutput 또는 torch.Tensor의 튜플(return_dict=False가 전달되었거나 config.return_dict=False인 경우)로, 구성(BrosConfig)과 입력에 따라 다양한 요소를 포함합니다.

BrosSpadeEEForTokenClassification의 forward 메서드는 __call__ 특수 메서드를 오버라이드합니다.

이 함수 내에서 forward pass의 레시피를 정의해야 하지만, 이후에는 이 함수 대신 Module 인스턴스를 호출해야 합니다. 전자는 전처리 및 후처리 단계를 실행하는 것을 처리하는 반면, 후자는 이를 조용히 무시하기 때문입니다.

  • loss (torch.Tensor, shape (1,), 선택 사항, labels이 제공될 때 반환됨) — 분류 손실.

  • initial_token_logits (torch.Tensor, shape (batch_size, sequence_length, config.num_labels)) — 엔티티 초기 토큰에 대한 분류 점수(SoftMax 적용 전).

  • subsequent_token_logits (torch.Tensor, shape (batch_size, sequence_length, sequence_length+1)) — 엔티티 시퀀스 토큰에 대한 분류 점수(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 가중치.

예:

>>> import torch
>>> from transformers import BrosProcessor, BrosSpadeEEForTokenClassification

>>> processor = BrosProcessor.from_pretrained("jinho8345/bros-base-uncased")

>>> model = BrosSpadeEEForTokenClassification.from_pretrained("jinho8345/bros-base-uncased")

>>> encoding = processor("Hello, my dog is cute", add_special_tokens=False, return_tensors="pt")
>>> bbox = torch.tensor([[[0, 0, 1, 1]]]).repeat(1, encoding["input_ids"].shape[-1], 1)
>>> encoding["bbox"] = bbox

>>> outputs = model(**encoding)

BrosSpadeELForTokenClassification

class transformers.BrosSpadeELForTokenClassification

< >

( config: BrosConfig )

매개변수

  • config (BrosConfig) — 모델의 모든 매개변수를 포함하는 모델 구성 클래스입니다. 구성 파일로 초기화하는 것은 모델과 연관된 가중치를 로드하지 않으며, 구성 정보만 로드합니다. 모델 가중치를 로드하려면 from_pretrained() 메서드를 확인하세요.

토큰 분류 헤드가 위에 있는 Bros 모델(예: Entity-Linking을 위해 hidden-states 출력 위에 entity_linker 레이어를 배치한 경우). entity_linker는 엔티티 간 링크(하나의 엔티티에서 다른 엔티티로)를 예측하는 데 사용됩니다.

이 모델은 PreTrainedModel에서 상속됩니다. 라이브러리가 모든 모델에 대해 구현하는 일반적 메서드(다운로드 또는 저장, 입력 임베딩 크기 조정, 헤드 프루닝 등)에 대한 세부 사항은 상위 클래스 문서를 확인하세요.

이 모델은 또한 PyTorch torch.nn.Module의 하위 클래스입니다. 일반적인 PyTorch Module처럼 사용하며, 일반적인 사용법 및 동작과 관련된 모든 사항은 PyTorch 문서를 참조하세요.

forward

< >

( input_ids: typing.Optional[torch.Tensor] = Nonebbox: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Nonebbox_first_token_mask: typing.Optional[torch.Tensor] = Nonetoken_type_ids: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.Tensor] = Noneinputs_embeds: typing.Optional[torch.Tensor] = Nonelabels: typing.Optional[torch.Tensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → TokenClassifierOutput or tuple(torch.Tensor)

매개변수

  • input_ids (torch.Tensor 의 shape (batch_size, sequence_length), , 선택 사항) — 어휘(input vocabulary)에서 입력 시퀀스 토큰의 인덱스입니다. 기본적으로 패딩은 무시됩니다.

    AutoTokenizer를 사용하여 인덱스를 얻을 수 있습니다. 자세한 내용은 PreTrainedTokenizer.encode() 및 PreTrainedTokenizer.call()를 참조하세요.

    입력 ID란 무엇인가요?

  • bbox ('torch.Tensor', shape ‘(batch_size, num_boxes, 4)’) — 입력 시퀀스의 각 토큰에 대한 바운딩 박스 좌표. 각 바운딩 박스는 네 개의 값 (x1, y1, x2, y2)로 이루어진 리스트이며, (x1, y1)은 바운딩 박스의 왼쪽 위 모서리, (x2, y2)는 오른쪽 아래 모서리를 나타냅니다.
  • attention_mask (torch.Tensor 형상이 (batch_size, sequence_length), 선택 사항) — 패딩 토큰 인덱스에 대한 attention을 수행하지 않도록 방지하는 마스크. [0, 1]에서 선택된 마스크 값: 마스크되지 않은 토큰은 1, 마스크된 토큰은 0. attention mask란 무엇인가요? [0, 1]:
    • 마스크되지 않은 토큰에 대해 1
    • 마스크된 토큰에 대해 0

    어텐션 마스크란 무엇인가요?

  • bbox_first_token_mask (torch.Tensor shape (batch_size, sequence_length), 선택 사항) — 각 바운딩 박스의 첫 번째 토큰을 나타내는 마스크. [0, 1]:
    • 마스크되지 않은 토큰에 대해 1
    • 마스크된 토큰에 대해 0
  • token_type_ids (torch.Tensor 형상 (batch_size, sequence_length), 선택 사항) — 입력의 첫 번째 및 두 번째 부분을 나타내는 세그먼트 토큰 인덱스. 인덱스는 [0, 1]:
    • 0은 sentence A 토큰에 해당합니다.
    • 1은 sentence B 토큰에 해당합니다.

    토큰 타입 ID란 무엇인가요?

  • position_ids (torch.Tensor 의 shape (batch_size, sequence_length), , 선택 사항) — 입력 시퀀스 토큰의 위치 임베딩에서 각 토큰의 위치 인덱스. 범위는 [0, config.n_positions - 1].

    포지션 ID란 무엇인가요?

  • inputs_embeds (torch.Tensor, shape (batch_size, sequence_length, hidden_size), 선택) — input_ids를 전달하는 대신 임베딩 표현을 직접 전달할 수 있습니다. 이는 모델 내부의 임베딩 조회 행렬보다 input_ids 인덱스를 관련 벡터로 변환하는 방식에 대해 더 세밀한 제어가 필요한 경우에 유용합니다.
  • labels (torch.LongTensor, shape (batch_size, sequence_length), 선택 사항) — 토큰 분류 손실을 계산하는 데 사용되는 라벨입니다. 인덱스는 [0, ..., config.num_labels - 1] 범위에 있어야 합니다.

반환값

TokenClassifierOutput 또는 tuple(torch.Tensor)

torch.Tensor의 튜플 또는 TokenClassifierOutput입니다. 구성(BrosConfig)과 입력에 따라 다양한 요소를 포함하며, return_dict=False가 전달되거나 config.return_dict=False인 경우에도 동일합니다.

BrosSpadeELForTokenClassification의 forward 메서드는 __call__ 특수 메서드를 오버라이드합니다.

이 함수 내에서 forward pass의 레시피를 정의해야 하지만, 이후에는 이 함수 대신 Module 인스턴스를 호출해야 합니다. 전자는 전처리 및 후처리 단계를 실행하는 것을 처리하는 반면, 후자는 이를 조용히 무시하기 때문입니다.

  • 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 가중치.

예:

>>> import torch
>>> from transformers import BrosProcessor, BrosSpadeELForTokenClassification

>>> processor = BrosProcessor.from_pretrained("jinho8345/bros-base-uncased")

>>> model = BrosSpadeELForTokenClassification.from_pretrained("jinho8345/bros-base-uncased")

>>> encoding = processor("Hello, my dog is cute", add_special_tokens=False, return_tensors="pt")
>>> bbox = torch.tensor([[[0, 0, 1, 1]]]).repeat(1, encoding["input_ids"].shape[-1], 1)
>>> encoding["bbox"] = bbox

>>> outputs = model(**encoding)
Update on GitHub