Transformers documentation

Splinter

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-01-02에 HF papers에 게시되었으며, 2021-08-17에 Hugging Face Transformers에 기여되었습니다.

Splinter

개요

Splinter 모델은 Ori Ram, Yuval Kirstain, Jonathan Berant, Amir Globerson, Omer Levy가 발표한 Few-Shot Question Answering by Pretraining Span Selection에서 제안되었습니다. Splinter는 Wikipedia와 Toronto Book Corpus로 구성된 대규모 코퍼스에서 반복 스팬 선택 작업을 사용하여 사전 학습된 인코더 전용 transformer(BERT와 유사)입니다.

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

여러 질의응답 벤치마크에서 사전 학습 모델은 약 100,000개의 주석된 질문과 답변으로 fine-tuning을 수행하여 인간 수준의 성능에 도달했습니다. 우리는 훈련 예제가 몇백 개만 제공되는, 보다 현실적인 few-shot 설정을 탐구했으며, 표준 모델이 낮은 성능을 보임으로써 현재 사전 학습 목표와 질의응답 간의 불일치를 강조했습니다. 우리는 질의응답에 맞게 설계된 새로운 사전 학습 방식인 recurring span selection을 제안합니다. 여러 세트의 recurring spans가 포함된 패사지가 주어지면, 각 세트에서 하나의 recurring span을 제외한 모든 recurring spans을 mask하고, 모델이 패사지 내에서 각 mask된 span에 해당하는 올바른 span을 선택하도록 합니다. Mask된 span은 special token으로 대체되며, 이 token은 질문 표현으로 간주되어 이후 fine-tuning 단계에서 답변 span을 선택하는 데 사용됩니다. 결과적으로 생성된 모델은 여러 벤치마크에서 놀라울 정도로 좋은 결과를 얻습니다(예: 훈련 예제 128개만 사용하여 SQuAD에서 F1 72.7 달성) 동시에 고자원 설정에서도 경쟁력 있는 성능을 유지합니다.

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

사용 팁

  • Splinter은 특수한 [QUESTION] 토큰에 조건부화된 답변 스팬을 예측하도록 학습되었습니다. 이러한 토큰은 질문 표현으로 컨텍스트화되며, 이 표현은 답변 예측에 사용됩니다. 이 레이어는 QASS라고 불리며, SplinterForQuestionAnswering 클래스의 기본 동작입니다. 따라서:
  • 이 특수 토큰이 이미 포함되어 있으므로 BertTokenizer 대신 SplinterTokenizer를 사용하세요. 또한 두 개의 시퀀스가 주어지면 기본적으로 이 토큰을 사용하도록 설정되어 있습니다.
  • 질문 토큰을 기억해 두세요. 특히 few-shot 설정에서는 모델의 성공에 중요한 역할을 할 수 있습니다.
  • 각 크기의 Splinter에는 서로 다른 두 개의 체크포인트가 있습니다. 둘은 기본적으로 동일하며, 차이점은 QASS 레이어의 사전 학습된 가중치를 포함하는지 여부입니다(tau/splinter-base-qass 및 tau/splinter-large-qass는 포함하고, tau/splinter-base 및 tau/splinter-large는 포함하지 않음). 이는 해당 레이어를 미세 조정 시점에 무작위로 초기화하는 방식을 지원하기 위함이며, 논문에서는 일부 경우에 이 방식이 더 나은 결과를 산출한다고 보고하고 있습니다.

리소스

SplinterConfig

클래스 transformers.SplinterConfig

< >

( 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 = 0bos_token_id: int | None = Noneeos_token_id: int | list[int] | None = Nonequestion_token_id: int = 104 )

매개변수

  • 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입니다.
  • bos_token_id (int, 선택 사항) — 어휘에서 스트림 시작에 사용되는 토큰 ID입니다.
  • eos_token_id (Union[int, list[int]], 선택) — 어휘에서 스트림 종료에 사용되는 토큰 ID입니다.
  • question_token_id (int, 선택 사항, 기본값 104) — [QUESTION] 토큰의 id입니다.

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

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

예:

>>> from transformers import SplinterModel, SplinterConfig

>>> # Initializing a Splinter tau/splinter-base style configuration
>>> configuration = SplinterConfig()

>>> # Initializing a model from the tau/splinter-base style configuration
>>> model = SplinterModel(configuration)

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

SplinterTokenizer

클래스 transformers.SplinterTokenizer

< >

( vocab: str | dict[str, int] | None = Nonedo_lower_case: bool = Trueunk_token: str = '[UNK]'sep_token: str = '[SEP]'pad_token: str = '[PAD]'cls_token: str = '[CLS]'mask_token: str = '[MASK]'question_token: str = '[QUESTION]'tokenize_chinese_chars: bool = Truestrip_accents: bool | None = None**kwargs )

매개변수

  • vocab_file (str, 선택 사항) — 어휘 파일의 경로입니다.
  • tokenizer_file (str, 선택 사항) — 토크나이저의 직렬화를 포함하는 tokenizers JSON 파일의 경로입니다.
  • do_lower_case (bool, 선택 사항, 기본값 True) — 토큰화할 때 입력을 소문자로 변환할지 여부.
  • unk_token (str, 선택 사항, 기본값 "[UNK]") — 미지의 토큰입니다. 어휘에 없는 토큰은 ID로 변환할 수 없으므로, 대신 이 토큰으로 설정됩니다.
  • sep_token (str, 선택 사항, 기본값 "[SEP]") — 여러 시퀀스로 시퀀스를 구성할 때 사용되는 구분자 토큰입니다.
  • pad_token (str, 선택 사항, 기본값 "[PAD]") — 패딩에 사용되는 토큰입니다. 예를 들어, 길이가 다른 시퀀스를 배치(batching)할 때 사용됩니다.
  • cls_token (str, 선택 사항, 기본값 "[CLS]") — 시퀀스 분류를 수행할 때 사용되는 분류기 토큰입니다.
  • mask_token (str, 선택 사항, 기본값 "[MASK]") — 값을 마스킹하는 데 사용되는 토큰입니다.
  • question_token (str, 선택 사항, 기본값 "[QUESTION]") — 질문 표현을 구성하는 데 사용되는 토큰입니다.
  • tokenize_chinese_chars (bool, 선택, 기본값 True) — 한자 문자를 토큰화할지 여부입니다.
  • strip_accents (bool, 선택) — 모든 발음 기호를 제거할지 여부입니다. 이 옵션이 지정되지 않으면 lowercase의 값에 따라 결정됩니다.
  • vocab (str, dict 또는 list, 선택 사항) — 사용자 정의 어휘 사전입니다. 제공되지 않으면 최소한의 어휘가 생성됩니다.

HuggingFace의 tokenizers 라이브러리를 기반으로 하는 Splinter 토크나이저를 생성합니다. WordPiece 기반입니다.

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

get_special_tokens_mask

< >

( token_ids_0: list[int]token_ids_1: list[int] | None = Nonealready_has_special_tokens: bool = False ) → A list of integers in the range [0, 1]

매개변수

  • token_ids_0 — (이미 포맷된) 시퀀스의 ID 목록.
  • token_ids_1 — already_has_special_tokens=True인 경우 사용되지 않습니다. 이 경우 None이어야 합니다.
  • already_has_special_tokens — 시퀀스가 이미 특수 토큰으로 포맷되어 있는지 여부.

반환값

범위 [0, 1]의 정수 목록

특수 토큰은 1, 시퀀스 토큰은 0입니다.

…

빠른 토크나이저의 경우, 데이터 콜레이터는 이미 포맷된 시퀀스에 대한 마스크를 생성하기 위해 already_has_special_tokens=True를 전달하여 이 함수를 호출합니다. 이 경우 all_special_ids에 대한 멤버십을 확인하여 마스크를 계산합니다.

save_vocabulary

< >

( save_directory: strfilename_prefix: str | None = None )

SplinterModel

class transformers.SplinterModel

< >

( config: SplinterConfig )

매개변수

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

특정 헤드가 위에 없는 상태의 Splinter Model은 원시 hidden-states를 출력합니다.

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

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

forward

< >

( input_ids: 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] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutput or tuple(torch.Tensor)

매개변수

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

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

    입력 ID란 무엇인가요?

  • attention_mask (torch.Tensor 형상이 (batch_size, sequence_length), 선택 사항) — 패딩 토큰 인덱스에 대한 attention을 수행하지 않도록 방지하는 마스크. [0, 1]에서 선택된 마스크 값: 마스크되지 않은 토큰은 1, 마스크된 토큰은 0. attention mask란 무엇인가요? [0, 1]:
    • 마스크되지 않은 토큰에 대해 1
    • 마스크된 토큰에 대해 0

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

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

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

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

    포지션 ID란 무엇인가요?

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

반환값

BaseModelOutput 또는 tuple(torch.Tensor)

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

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

SplinterForQuestionAnswering

class transformers.SplinterForQuestionAnswering

< >

( config: SplinterConfig )

매개변수

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

SQuAD와 같은 추출형 질의응답 작업을 위해 span classification head를 최상단에 배치한 Splinter transformer (hidden-states 출력 위에 선형 레이어를 올려 span start logits과 span end logits을 계산).

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

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

forward

< >

( input_ids: 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] = Nonestart_positions: typing.Optional[torch.LongTensor] = Noneend_positions: typing.Optional[torch.LongTensor] = Nonequestion_positions: typing.Optional[torch.LongTensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → QuestionAnsweringModelOutput or tuple(torch.Tensor)

매개변수

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

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

    입력 ID란 무엇인가요?

  • attention_mask (torch.Tensor 형상이 (batch_size, sequence_length), 선택 사항) — 패딩 토큰 인덱스에 대한 attention을 수행하지 않도록 방지하는 마스크. [0, 1]에서 선택된 마스크 값: 마스크되지 않은 토큰은 1, 마스크된 토큰은 0. attention mask란 무엇인가요? [0, 1]:
    • 마스크되지 않은 토큰에 대해 1
    • 마스크된 토큰에 대해 0

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

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

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

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

    포지션 ID란 무엇인가요?

  • inputs_embeds (torch.Tensor, shape (batch_size, sequence_length, hidden_size), 선택) — input_ids를 전달하는 대신 임베딩 표현을 직접 전달할 수 있습니다. 이는 모델 내부의 임베딩 조회 행렬보다 input_ids 인덱스를 관련 벡터로 변환하는 방식에 대해 더 세밀한 제어가 필요한 경우에 유용합니다.
  • start_positions (torch.LongTensor, shape (batch_size,), 선택 사항) — 토큰 분류 손실을 계산하기 위해 라벨이 지정된 스팬의 시작 위치(인덱스)에 대한 라벨입니다. 위치는 시퀀스 길이(sequence_length)로 클램프됩니다. 시퀀스 범위를 벗어난 위치는 손실 계산에 반영되지 않습니다.
  • end_positions (torch.LongTensor, shape (batch_size,), 선택 사항) — 토큰 분류 손실을 계산하기 위해 라벨이 지정된 스팬의 끝 위치(인덱스)에 대한 라벨입니다. 위치는 시퀀스 길이(sequence_length)로 클램프됩니다. 시퀀스 범위를 벗어난 위치는 손실 계산에 반영되지 않습니다.
  • question_positions (torch.LongTensor, shape (batch_size, num_questions), 선택 사항) — 모든 question 토큰의 위치입니다. 값이 주어지면 start_logits와 end_logits의 shape은 (batch_size, num_questions, sequence_length)가 됩니다. None인 경우, 배치 내 각 시퀀스의 첫 번째 question 토큰에 대해서만 start_logits와 end_logits가 계산되며, shape은 (batch_size, sequence_length)가 됩니다.

반환값

QuestionAnsweringModelOutput 또는 tuple(torch.Tensor)

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

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

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

  • loss (torch.Tensor, shape (1,), 선택 사항, labels이 제공될 때 반환됨) — 전체 span 추출 손실은 시작 및 끝 위치의 Cross-Entropy 합입니다.

  • start_logits (torch.Tensor, shape (batch_size, sequence_length)) — SoftMax 적용 전 스팬 시작 점수.

  • end_logits (torch.Tensor, shape (batch_size, sequence_length)) — 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, SplinterForQuestionAnswering
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("tau/splinter-base")
>>> model = SplinterForQuestionAnswering.from_pretrained("tau/splinter-base")

>>> question, text = "Who was Jim Henson?", "Jim Henson was a nice puppet"

>>> inputs = tokenizer(question, text, return_tensors="pt")
>>> with torch.no_grad():
...     outputs = model(**inputs)

>>> answer_start_index = outputs.start_logits.argmax()
>>> answer_end_index = outputs.end_logits.argmax()

>>> predict_answer_tokens = inputs.input_ids[0, answer_start_index : answer_end_index + 1]
>>> tokenizer.decode(predict_answer_tokens, skip_special_tokens=True)
...

>>> # target is "nice puppet"
>>> target_start_index = torch.tensor([14])
>>> target_end_index = torch.tensor([15])

>>> outputs = model(**inputs, start_positions=target_start_index, end_positions=target_end_index)
>>> loss = outputs.loss
>>> round(loss.item(), 2)
...

SplinterForPreTraining

클래스 transformers.SplinterForPreTraining

< >

( config: SplinterConfig )

매개변수

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

에서 수행한 반복 스팬 선택 작업을 위한 Splinter Model입니다. QA 작업과의 차이점은 질문이 없으며, 대신 반복 스팬의 출현 위치를 대체하는 여러 개의 질문 토큰이 있다는 점입니다.

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

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

forward

< >

( input_ids: 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] = Nonestart_positions: typing.Optional[torch.LongTensor] = Noneend_positions: typing.Optional[torch.LongTensor] = Nonequestion_positions: typing.Optional[torch.LongTensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → SplinterForPreTrainingOutput or tuple(torch.Tensor)

매개변수

  • input_ids (torch.LongTensor 다음 형식의 (batch_size, num_questions, sequence_length)) — 어휘 사전에서 입력 시퀀스 토큰의 인덱스입니다. 인덱스는 AutoTokenizer를 사용하여 얻을 수 있습니다. 자세한 내용은 PreTrainedTokenizer.encode() 및 PreTrainedTokenizer.call()을 참조하세요. input ID란 무엇인가요?

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

    입력 ID란 무엇인가요?

  • attention_mask (torch.Tensor 형상이 (batch_size, sequence_length), 선택 사항) — 패딩 토큰 인덱스에 대한 attention을 수행하지 않도록 방지하는 마스크. [0, 1]에서 선택된 마스크 값: 마스크되지 않은 토큰은 1, 마스크된 토큰은 0. attention mask란 무엇인가요? [0, 1]:
    • 마스크되지 않은 토큰에 대해 1
    • 마스크된 토큰에 대해 0

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

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

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

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

    포지션 ID란 무엇인가요?

  • inputs_embeds (torch.Tensor, shape (batch_size, num_questions, sequence_length, hidden_size), 선택) — input_ids를 전달하는 대신 임베딩 표현을 직접 전달할 수 있습니다. 이는 모델의 내부 임베딩 조회 행렬보다 input_ids 인덱스를 관련 벡터로 변환하는 방식을 더 세밀하게 제어하려는 경우에 유용합니다.
  • start_positions (torch.LongTensor, shape (batch_size, num_questions), 선택 사항) — 토큰 분류 손실을 계산하기 위해 라벨이 지정된 스팬의 시작 위치(인덱스)에 대한 라벨입니다. 위치는 시퀀스 길이(sequence_length)로 클램프됩니다. 시퀀스 범위를 벗어난 위치는 손실 계산에 반영되지 않습니다.
  • end_positions (torch.LongTensor, shape (batch_size, num_questions), 선택 사항) — 토큰 분류 손실을 계산하기 위해 라벨이 지정된 스팬의 끝 위치(인덱스)에 대한 라벨입니다. 위치는 시퀀스 길이(sequence_length)로 클램프됩니다. 시퀀스 범위를 벗어난 위치는 손실 계산에 반영되지 않습니다.
  • question_positions (torch.LongTensor, shape (batch_size, num_questions), 선택 사항) — 모든 question 토큰의 위치입니다. 값이 주어지면 start_logits와 end_logits의 shape은 (batch_size, num_questions, sequence_length)가 됩니다. None인 경우, 배치 내 각 시퀀스의 첫 번째 question 토큰에 대해서만 start_logits와 end_logits가 계산되며, shape은 (batch_size, sequence_length)가 됩니다.

반환값

SplinterForPreTrainingOutput 또는 tuple(torch.Tensor)

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

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

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

  • loss (torch.Tensor, shape (1,), optional, start와 end 위치가 제공될 때 반환됨) — 전체 span 추출 손실은 start와 end 위치의 Cross-Entropy 합입니다.

  • start_logits (torch.Tensor, shape (batch_size, num_questions, sequence_length)) — SoftMax 적용 전 스팬 시작 점수.

  • end_logits (torch.Tensor, shape (batch_size, num_questions, sequence_length)) — 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 가중치.

예:

Update on GitHub