Transformers documentation

MGP-STR

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

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

MGP-STR

개요

MGP-STR 모델은 Peng Wang, Cheng Da, Cong Yao가 Multi-Granularity Prediction for Scene Text Recognition에서 제안했습니다. MGP-STR은 Vision Transformer (ViT)를 기반으로 구축된 개념적으로 단순하면서도 강력한 비전 Scene Text Recognition(STR) 모델입니다. 언어적 지식을 통합하기 위해, Multi-Granularity Prediction(MGP) 전략을 제안하여 언어 모달리티의 정보를 모델에 암시적으로 주입합니다.

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

장면 텍스트 인식(STR)은 수년간 컴퓨터 비전 분야에서 활발한 연구 주제였습니다. 이 어려운 문제를 해결하기 위해 수많은 혁신적인 방법이 제안되었으며, 최근에는 언어 지식을 STR 모델에 통합하는 것이 두드러진 트렌드가 되었습니다. 본 연구에서는 최근 Vision Transformer(ViT)의 발전에서 영감을 받아 개념적으로 단순하면서도 강력한 비전 STR 모델을 구성했습니다. 이 모델은 ViT를 기반으로 구축되어 장면 텍스트 인식의 기존 최첨단 모델, 즉 순수 비전 모델과 언어 증강 방법 모두를 능가합니다. 언어 지식을 통합하기 위해, 우리는 Multi-Granularity Prediction 전략을 추가로 제안하여 언어 모달리티의 정보를 모델에 암묵적으로 주입합니다. 즉, 독립적인 언어 모델(LM)을 사용하지 않으면서도, NLP에서 널리 사용되는 서브워드 표현(BPE 및 WordPiece)을 기존 문자 수준 표현 외에도 출력 공간에 도입합니다. 그 결과 나온 알고리즘(MGP-STR로 명명됨)은 STR의 성능 한계를 더 높은 수준으로 끌어올릴 수 있습니다. 구체적으로, 표준 벤치마크에서 93.35%의 평균 인식 정확도를 달성합니다.

drawing MGP-STR architecture. Taken from the original paper.

MGP-STR는 MJSynth(MJ)와 SynthText(ST)라는 두 개의 합성 데이터셋으로 학습되며, 다른 데이터셋으로의 fine-tuning은 수행하지 않습니다. 이 모델은 3개의 정규 텍스트 데이터셋(IC13, SVT, IIIT)과 3개의 비정규 데이터셋(IC15, SVTP, CUTE)을 포함한 6개의 표준 라틴 문자 장면 텍스트 벤치마크에서 최첨단(state-of-the-art) 결과를 달성합니다. 이 모델은 yuekun에 의해 기여되었습니다. 원본 코드는 여기에서 확인할 수 있습니다.

추론 예시

MgpstrModel은 이미지를 입력으로 받아 서로 다른 세밀도 수준에서 텍스트 정보를 나타내는 세 가지 유형의 예측을 생성합니다. 세 가지 유형의 예측은 결합되어 최종 예측 결과를 제공합니다.

ViTImageProcessor 클래스는 입력 이미지의 전처리를 담당하고, MgpstrTokenizer는 생성된 문자 토큰을 대상 문자열로 디코딩합니다. MgpstrProcessor는 ViTImageProcessor와 MgpstrTokenizer를 단일 인스턴스로 묶어 입력 특징 추출과 예측된 토큰 ID 디코딩을 모두 수행합니다.

  • Step-by-step Optical Character Recognition (OCR)
import requests
from PIL import Image

from transformers import MgpstrForSceneTextRecognition, MgpstrProcessor


processor = MgpstrProcessor.from_pretrained('alibaba-damo/mgp-str-base')
model = MgpstrForSceneTextRecognition.from_pretrained('alibaba-damo/mgp-str-base', device_map="auto")

# load a synthetic scene-text image
url = "https://huggingface.co/datasets/hf-internal-testing/transformers-synthetic-assets/resolve/main/images/mgp_str_ticket.png"
image = Image.open(requests.get(url, stream=True).raw).convert("RGB")

pixel_values = processor(images=image, return_tensors="pt").to(model.device).pixel_values
outputs = model(pixel_values)

generated_text = processor.batch_decode(outputs.logits)['generated_text']

MgpstrConfig

클래스 transformers.MgpstrConfig

< >

( 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 = Noneimage_size: list[int] | tuple[int, ...] = (32, 128)patch_size: int | list[int] | tuple[int, int] = 4num_channels: int = 3max_token_length: int = 27num_character_labels: int = 38num_bpe_labels: int = 50257num_wordpiece_labels: int = 30522hidden_size: int = 768num_hidden_layers: int = 12num_attention_heads: int = 12mlp_ratio: float | int = 4.0qkv_bias: bool = Truedistilled: bool = Falselayer_norm_eps: float = 1e-05drop_rate: float | int = 0.0attn_drop_rate: float | int = 0.0drop_path_rate: float | int = 0.0output_a3_attentions: bool = Falseinitializer_range: float = 0.02 )

매개변수

  • image_size (Union[list[int], tuple[int, ...]], 선택 사항, 기본값 (32, 128)) — 각 이미지의 크기(해상도).
  • patch_size (Union[int, list[int], tuple[int, int]], 선택 사항, 기본값 4) — 각 패치의 크기(해상도)입니다.
  • num_channels (int, 선택 사항, 기본값 3) — 입력 채널의 수입니다.
  • max_token_length (int, 선택 사항, 기본값 27) — 출력 토큰의 최대 개수입니다.
  • num_character_labels (int, 선택 사항, 기본값 38) — character head의 클래스 수입니다.
  • num_bpe_labels (int, 선택 사항, 기본값 50257) — bpe head의 클래스 수입니다.
  • num_wordpiece_labels (int, 선택 사항, 기본값 30522) — wordpiece head의 클래스 수입니다.
  • hidden_size (int, 선택 사항, 기본값 768) — 숨겨진 표현의 차원입니다.
  • num_hidden_layers (int, 선택 사항, 기본값 12) — Transformer 디코더의 숨겨진 레이어 수.
  • num_attention_heads (int, 선택 사항, 기본값 12) — Transformer decoder의 각 attention layer에 사용할 attention head의 수입니다.
  • mlp_ratio (Union[float, int], 선택 사항, 기본값 4.0) — MLP 은닉 차원과 임베딩 차원의 비율입니다.
  • qkv_bias (bool, 선택 사항, 기본값 True) — 쿼리, 키, 값에 bias를 추가할지 여부.
  • distilled (bool, 선택 사항, 기본값 False) — DeiT 모델과 마찬가지로 모델에 증류 토큰과 헤드가 포함됩니다.
  • layer_norm_eps (float, 선택 사항, 기본값 1e-05) — 레이어 정규화 레이어에서 사용되는 epsilon 값입니다.
  • drop_rate (float, 선택 사항, 기본값 0.0) — 임베딩 및 인코더의 모든 완전 연결 계층에 적용되는 dropout 확률입니다.
  • attn_drop_rate (float, 선택 사항, 기본값 0.0) — Attention 확률에 적용할 dropout 비율입니다.
  • drop_path_rate (Union[float, int], 선택 사항, 기본값 0.0) — 패치 융합에 사용할 드롭 패스 비율입니다.
  • output_a3_attentions (bool, 선택 사항, 기본값 False) — 모델이 A^3 모듈의 attentions을 반환할지 여부.
  • initializer_range (float, 선택 사항, 기본값 0.02) — 모든 가중치 행렬을 초기화하는 truncated_normal_initializer의 표준 편차입니다.

이것은 Mgp StrModel의 구성을 저장하기 위한 구성 클래스입니다. 지정된 인자에 따라 Mgp Str 모델을 인스턴스화하여 모델 아키텍처를 정의하는 데 사용됩니다. 기본값으로 구성을 인스턴스화하면 alibaba-damo/mgp-str-base와 유사한 구성이 생성됩니다.

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

예:

>>> from transformers import MgpstrConfig, MgpstrForSceneTextRecognition

>>> # Initializing a Mgpstr mgp-str-base style configuration
>>> configuration = MgpstrConfig()

>>> # Initializing a model (with random weights) from the mgp-str-base style configuration
>>> model = MgpstrForSceneTextRecognition(configuration)

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

MgpstrTokenizer

클래스 transformers.MgpstrTokenizer

< >

( vocab_fileunk_token = '[GO]'bos_token = '[GO]'eos_token = '[s]'pad_token = '[GO]'**kwargs )

매개변수

  • vocab_file (str) — 어휘 파일의 경로입니다.
  • unk_token (str, 선택 사항, 기본값 "[GO]") — 미지의 토큰입니다. 어휘에 없는 토큰은 ID로 변환할 수 없으므로 대신 이 토큰으로 설정됩니다.
  • bos_token (str, 선택 사항, 기본값 "[GO]") — 시퀀스 시작 토큰입니다.
  • eos_token (str, 선택 사항, 기본값 "[s]") — 시퀀스 종료 토큰입니다.
  • pad_token (str 또는 tokenizers.AddedToken, 선택 사항, 기본값 "[GO]") — 배치 처리를 위해 토큰 배열의 크기를 동일하게 만드는 데 사용되는 특수 토큰입니다. 이후 attention 메커니즘이나 손실 계산에서는 무시됩니다.

MGP-STR 문자 토크나이저를 구성합니다.

이 토크나이저는 대부분의 주요 메서드를 포함하는 PreTrainedTokenizer를 상속합니다. 해당 메서드에 대한 자세한 내용은 이 상위 클래스를 참고하세요.

save_vocabulary

< >

( save_directory: strfilename_prefix: str | None = None )

MgpstrProcessor

클래스 transformers.MgpstrProcessor

< >

( image_processor = Nonetokenizer = None**kwargs )

매개변수

  • image_processor (ViTImageProcessor) — 이미지 프로세서가 필수 입력입니다.
  • tokenizer (MgpstrTokenizer) — 토크나이저는 필수 입력값입니다.

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

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

__call__

< >

( text = Noneimages = None**kwargs )

매개변수

  • text (`) -- The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings (pretokenized string). If you pass a pretokenized input, set is_split_into_words=True` to avoid ambiguity with batched inputs.
  • images (`) -- Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If passing in images with pixel values between 0 and 1, set do_rescale=False`.
  • return_tensors (str 또는 TensorType, 선택 사항) — 설정된 경우, 특정 프레임워크의 텐서를 반환합니다. 허용되는 값은 다음과 같습니다:
    • 'pt': PyTorch torch.Tensor 객체를 반환합니다.
    • 'np': NumPy np.ndarray 객체를 반환합니다.

batch_decode

< >

( sequences ) → dict[str, any]

매개변수

  • sequences (torch.Tensor) — 토큰화된 입력 id 목록.

반환값

dict[str, any]

디코딩된 결과의 모든 출력을 담은 사전입니다. generated_text (list[str]): char, bpe, wp의 점수를 융합한 최종 결과 scores (list[float]): char, bpe, wp의 점수를 융합한 최종 점수 char_preds (list[str]): 문자 디코딩 문장 목록 bpe_preds (list[str]): bpe 디코딩 문장 목록 wp_preds (list[str]): wp 디코딩 문장 목록

decode를 호출하여 토큰 ID의 리스트로 된 리스트를 문자열의 리스트로 변환합니다.

이 메서드는 모든 인수를 PreTrainedTokenizer의 batch_decode()로 전달합니다. 자세한 내용은 해당 메서드의 docstring을 참고하세요.

MgpstrModel

class transformers.MgpstrModel

< >

( config: MgpstrConfig )

매개변수

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

특정 헤드가 위에 없는 상태에서 원시 hidden-states를 출력하는 순수 Mgp Str Model입니다.

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

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

forward

< >

( pixel_values: Tensoroutput_attentions: bool | None = Noneoutput_hidden_states: bool | None = Nonereturn_dict: bool | None = None**kwargs ) → BaseModelOutput or tuple(torch.Tensor)

매개변수

  • pixel_values (torch.Tensor, shape (batch_size, num_channels, image_size, image_size)) — 입력 이미지에 해당하는 텐서입니다. 픽셀 값은 ViTImageProcessor를 사용하여 얻을 수 있습니다. 자세한 내용은 ViTImageProcessor.call()를 참조하세요 (MgpstrProcessor는 이미지 처리에 ViTImageProcessor를 사용합니다).
  • output_attentions (bool, 선택 사항) — 모든 attention 레이어의 attentions 텐서를 반환할지 여부. 자세한 내용은 반환 텐서 섹션의 attentions 항목을 참조하세요.
  • output_hidden_states (bool, 선택 사항) — 모든 레이어의 hidden states를 반환할지 여부입니다. 자세한 내용은 반환되는 텐서 중 hidden_states 항목을 참고하세요.
  • return_dict (bool, 선택) — 일반 튜플 대신 ModelOutput를 반환할지 여부.

반환값

BaseModelOutput 또는 tuple(torch.Tensor)

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

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

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

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

MgpstrForSceneTextRecognition

class transformers.MgpstrForSceneTextRecognition

< >

( config: MgpstrConfig )

매개변수

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

MGP-STR 모델은 transformer 위에 세 개의 분류 헤드를 배치한 구조로(세 개의 A^3 모듈과 transformer 인코더 출력 위에 세 개의 선형 레이어) 장면 텍스트 인식(STR)에 사용됩니다.

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

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

forward

< >

( pixel_values: Tensoroutput_attentions: bool | None = Noneoutput_a3_attentions: bool | None = Noneoutput_hidden_states: bool | None = Nonereturn_dict: bool | None = None**kwargs ) → MgpstrModelOutput or tuple(torch.Tensor)

매개변수

  • pixel_values (torch.Tensor, shape (batch_size, num_channels, image_size, image_size)) — 입력 이미지에 해당하는 텐서입니다. 픽셀 값은 ViTImageProcessor를 사용하여 얻을 수 있습니다. 자세한 내용은 ViTImageProcessor.call()를 참조하세요 (MgpstrProcessor는 이미지 처리에 ViTImageProcessor를 사용합니다).
  • output_attentions (bool, 선택 사항) — 모든 attention 레이어의 attentions 텐서를 반환할지 여부. 자세한 내용은 반환 텐서 섹션의 attentions 항목을 참조하세요.
  • output_a3_attentions (bool, 선택 사항) — a3 모듈의 attentions 텐서를 반환할지 여부. 자세한 내용은 반환 텐서 섹션의 a3_attentions 항목을 참조하세요.
  • output_hidden_states (bool, 선택 사항) — 모든 레이어의 hidden states를 반환할지 여부입니다. 자세한 내용은 반환되는 텐서 중 hidden_states 항목을 참고하세요.
  • return_dict (bool, 선택) — 일반 튜플 대신 ModelOutput를 반환할지 여부.

반환값

MgpstrModelOutput 또는 tuple(torch.Tensor)

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

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

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

  • logits (tuple(torch.Tensor), shape (batch_size, config.num_character_labels)) — torch.Tensor의 튜플 (shape (batch_size, config.max_token_length, config.num_character_labels)인 character 출력 하나, + shape (batch_size, config.max_token_length, config.num_bpe_labels)인 bpe 출력 하나, + shape (batch_size, config.max_token_length, config.num_wordpiece_labels)인 wordpiece 출력 하나) .

    character, bpe, wordpiece의 분류 점수(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 가중치.

  • a3_attentions (tuple(torch.Tensor), optional, returned when output_a3_attentions=True is passed or when config.output_a3_attentions=True) — Tuple of torch.Tensor (one for the attention of character, + one for the attention of bpe, + one for the attention of wordpiece) of shape(batch_size, config.max_token_length, sequence_length)`.

    self-attention 헤드에서 가중 평균을 계산하는 데 사용되는 attention softmax 이후의 attention 가중치.

예:

>>> from transformers import (
...     MgpstrProcessor,
...     MgpstrForSceneTextRecognition,
... )
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO
>>> from PIL import Image

>>> # load a synthetic scene-text image
>>> url = "https://huggingface.co/datasets/hf-internal-testing/transformers-synthetic-assets/resolve/main/images/mgp_str_ticket.png"
>>> with httpx.stream("GET", url) as response:
...     image = Image.open(BytesIO(response.read())).convert("RGB")

>>> processor = MgpstrProcessor.from_pretrained("alibaba-damo/mgp-str-base")
>>> pixel_values = processor(images=image, return_tensors="pt").pixel_values

>>> model = MgpstrForSceneTextRecognition.from_pretrained("alibaba-damo/mgp-str-base")

>>> # inference
>>> outputs = model(pixel_values)
>>> out_strs = processor.batch_decode(outputs.logits)
>>> out_strs["generated_text"]
'["ticket"]'
Update on GitHub