Transformers documentation

DeBERTa-v2

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

and get access to the augmented documentation experience

to get started

이 모델은 2020-06-05에 HF papers에 게시되었으며, 2021-02-19에 Hugging Face Transformers에 기여되었습니다.

PyTorch

DeBERTa-v2

DeBERTa-v2는 SentencePiece 기반 토크나이저와 128K의 새로운 어휘 크기를 사용하여 원래 DeBERTa 아키텍처를 개선합니다. 또한 입력 토큰의 로컬 의존성을 더 잘 학습하기 위해 첫 번째 transformer 레이어 내에 추가적인 convolutional 레이어를 도입합니다. 마지막으로 attention 레이어에서 position projection과 content projection 행렬을 공유하여 매개변수 수를 줄입니다.

모든 원본 [DeBERTa-v2] 체크포인트는 Microsoft 조직에서 찾을 수 있습니다.

이 모델은 Pengcheng He님이 기여했습니다.

DeBERTa-v2 모델에 대한 추가 예제를 보려면 오른쪽 사이드바의 DeBERTa-v2 모델을 클릭하여 DeBERTa-v2를 다양한 언어 작업에 적용하는 방법을 확인하세요.

아래 예제는 Pipeline 또는 AutoModel 클래스를 사용하여 텍스트를 분류하는 방법을 보여줍니다.

Pipeline
AutoModel
from transformers import pipeline


pipeline = pipeline(
    task="text-classification",
    model="microsoft/deberta-v2-xlarge-mnli",
    device=0,
)
result = pipeline("DeBERTa-v2 is great at understanding context!")
print(result)

Quantization은 가중치를 더 낮은 정밀도로 표현하여 대규모 모델의 메모리 부담을 줄입니다. 사용 가능한 다른 양자화 백엔드에 대해서는 Quantization 개요를 참조하세요.

아래 예제는 bitsandbytes 양자화를 사용하여 가중치만 4비트로 양자화합니다.

from transformers import AutoModelForSequenceClassification, AutoTokenizer, BitsAndBytesConfig

model_id = "microsoft/deberta-v2-xlarge-mnli"
quantization_config = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_quant_type="nf4",
    bnb_4bit_compute_dtype="float16",
    bnb_4bit_use_double_quant=True,
)
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForSequenceClassification.from_pretrained(
    model_id,
    quantization_config=quantization_config,
    dtype="float16"
 device_map="auto")

inputs = tokenizer("DeBERTa-v2 is great at understanding context!", return_tensors="pt").to(model.device)
outputs = model(**inputs)
logits = outputs.logits
predicted_class_id = logits.argmax().item()
predicted_label = model.config.id2label[predicted_class_id]
print(f"Predicted label: {predicted_label}")

DebertaV2Config

class transformers.DebertaV2Config

< >

( 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 = 128100hidden_size: int = 1536num_hidden_layers: int = 24num_attention_heads: int = 24intermediate_size: int = 6144hidden_act: str = 'gelu'hidden_dropout_prob: float | int = 0.1attention_probs_dropout_prob: float | int = 0.1max_position_embeddings: int = 512type_vocab_size: int = 0initializer_range: float = 0.02layer_norm_eps: float = 1e-07relative_attention: bool = Falsemax_relative_positions: int = -1pad_token_id: int | None = 0bos_token_id: int | None = Noneeos_token_id: int | list[int] | None = Noneposition_biased_input: bool = Truepos_att_type: str | list[str] | None = Nonepooler_dropout: float | int = 0.0pooler_hidden_act: str = 'gelu'legacy: bool = Truetie_word_embeddings: bool = True )

매개변수

  • vocab_size (int, 선택 사항, 기본값 128100) — 모델의 어휘 크기입니다. input_ids로 표현할 수 있는 서로 다른 토큰의 수를 정의합니다.
  • hidden_size (int, 선택 사항, 기본값 1536) — 숨겨진 표현의 차원입니다.
  • num_hidden_layers (int, 선택 사항, 기본값 24) — Transformer decoder의 숨겨진 레이어 수.
  • num_attention_heads (int, 선택 사항, 기본값 24) — Transformer decoder의 각 attention layer에 사용할 attention head의 수입니다.
  • intermediate_size (int, 선택 사항, 기본값 6144) — 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, 선택 사항, 기본값 0) — token_type_ids의 어휘 크기입니다.
  • initializer_range (float, 선택 사항, 기본값 0.02) — 모든 가중치 행렬을 초기화하는 truncated_normal_initializer의 표준 편차입니다.
  • layer_norm_eps (float, 선택 사항, 기본값 1e-07) — 레이어 정규화 레이어에서 사용되는 epsilon 값입니다.
  • relative_attention (bool, 선택 사항, 기본값 True) — 상대 위치 인코딩을 사용할지 여부.
  • max_relative_positions (int, 선택 사항, 기본값 -1) — 상대 위치의 범위 [-max_position_embeddings, max_position_embeddings]입니다. max_position_embeddings와 동일한 값을 사용하세요.
  • pad_token_id (int, 선택 사항, 기본값 0) — 어휘에서 패딩에 사용되는 토큰 ID입니다.
  • bos_token_id (int, 선택 사항) — 어휘에서 스트림 시작에 사용되는 토큰 ID입니다.
  • eos_token_id (Union[int, list[int]], 선택) — 어휘에서 스트림 종료에 사용되는 토큰 ID입니다.
  • position_biased_input (bool, 선택 사항, 기본값 True) — 콘텐츠 임베딩에 절대 위치 임베딩을 추가할지 여부.
  • pos_att_type (list[str], 선택 사항) — 상대 위치 주의력(relative position attention)의 유형입니다. ["p2c", "c2p"]의 조합으로 구성될 수 있으며, 예를 들어 ["p2c"], ["p2c", "c2p"], ["p2c", "c2p"]와 같습니다.
  • pooler_dropout (float, 선택 사항, 기본값 0) — pooler 모듈의 dropout rate입니다.
  • pooler_hidden_act (str, 선택 사항, 기본값 "gelu") — dropout 모듈에서 사용되는 활성화 함수입니다.
  • legacy (bool, 선택 사항, 기본값 True) — 모델이 mask infilling 작업에서 제대로 작동하지 않는 레거시 LegacyDebertaOnlyMLMHead를 사용할지 여부입니다.
  • tie_word_embeddings (bool, 선택, 기본값 True) — 모델의 tied_weights_keys 매핑에 따라 가중치 임베딩을 묶을지 여부.

이것은 Deberta V2Model의 설정을 저장하기 위한 설정 클래스입니다. 지정된 인수를 기반으로 Deberta V2 모델을 인스턴스화하여 모델 아키텍처를 정의하는 데 사용됩니다. 기본값으로 설정을 인스턴스화하면 microsoft/deberta-v2-xlarge와 유사한 설정이 생성됩니다.

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

예:

>>> from transformers import DebertaV2Config, DebertaV2Model

>>> # Initializing a DeBERTa-v2 microsoft/deberta-v2-xlarge style configuration
>>> configuration = DebertaV2Config()

>>> # Initializing a model (with random weights) from the microsoft/deberta-v2-xlarge style configuration
>>> model = DebertaV2Model(configuration)

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

DebertaV2Tokenizer

클래스 transformers.DebertaV2Tokenizer

< >

( vocab: str | dict | list | None = Nonedo_lower_case = Falsesplit_by_punct = Falsebos_token = '[CLS]'eos_token = '[SEP]'unk_token = '[UNK]'sep_token = '[SEP]'pad_token = '[PAD]'cls_token = '[CLS]'mask_token = '[MASK]'add_prefix_space = Trueunk_id = 1**kwargs )

매개변수

  • vocab_file (str, 선택 사항) — 어휘 파일(SentencePiece 모델 파일)의 경로입니다. 직접 사용되지는 않지만 호환성을 위해 유지됩니다.
  • vocab (str, dict 또는 list, 선택 사항) — 어휘에 대한 (piece, score) 튜플 목록.
  • precompiled_charsmap (bytes, 선택 사항) — 정규화를 위한 사전 컴파일된 문자 매핑입니다.
  • do_lower_case (bool, 선택 사항, 기본값 False) — 토큰화할 때 입력을 소문자로 변환할지 여부.
  • split_by_punct (bool, 선택 사항, 기본값 False) — 구두점을 기준으로 분할할지 여부.
  • bos_token (str, 선택 사항, 기본값 "[CLS]") — 시퀀스 시작 토큰입니다.
  • eos_token (str, 선택 사항, 기본값 "[SEP]") — 시퀀스 종료 토큰입니다.
  • unk_token (str, 선택 사항, 기본값 "[UNK]") — 미지의 토큰입니다. 어휘에 없는 토큰은 ID로 변환할 수 없으므로, 대신 이 토큰으로 설정됩니다.
  • sep_token (str, 선택, 기본값 "[SEP]") — 여러 시퀀스로 시퀀스를 구성할 때 사용되는 구분 토큰입니다. 예를 들어 시퀀스 분류의 두 시퀀스나 질의응답의 텍스트와 질문 등에 사용됩니다. 특수 토큰으로 구성된 시퀀스의 마지막 토큰으로도 사용됩니다.
  • pad_token (str, 선택 사항, 기본값 "[PAD]") — 패딩에 사용되는 토큰입니다. 예를 들어, 길이가 다른 시퀀스를 배치(batching)할 때 사용됩니다.
  • cls_token (str, 선택 사항, 기본값 "[CLS]") — 시퀀스 분류(토큰별 분류가 아닌 전체 시퀀스에 대한 분류)를 수행할 때 사용되는 분류기 토큰입니다. 특수 토큰을 사용하여 시퀀스를 구성할 경우 시퀀스의 첫 번째 토큰입니다.
  • mask_token (str, 선택 사항, 기본값 "[MASK]") — 값을 마스킹하는 데 사용되는 토큰입니다. 이는 masked language modeling으로 이 모델을 학습시킬 때 사용되는 토큰이며, 모델이 예측을 시도하는 대상이 되는 토큰입니다.
  • add_prefix_space (bool, 선택 사항, 기본값 True) — 입력 앞에 공백을 추가할지 여부입니다. 이를 통해 첫 번째 단어를 다른 단어와 동일하게 처리할 수 있습니다.
  • unk_id (int, 선택 사항, 기본값은 vocab에서 unk_token의 인덱스) — 어휘에서 unknown token의 ID입니다.

HuggingFace의 tokenizers 라이브러리를 기반으로 DeBERTa-v2 토크나이저를 구성합니다. Unigram 토크나이제이션을 기반으로 합니다.

이 토크나이저는 대부분의 주요 메서드를 포함하고 있는 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 )

DebertaV2Model

class transformers.DebertaV2Model

< >

( config: DebertaV2Config )

매개변수

  • config (DebertaV2Config) — 모델의 모든 매개변수를 포함하는 모델 구성 클래스입니다. 구성 파일로 초기화하면 모델에 연결된 가중치는 로드되지 않으며 구성만 로드됩니다. 모델 가중치를 로드하려면 from_pretrained() 메서드를 확인하세요.

특정 헤드가 위에 없는 상태에서 원시 hidden-states를 출력하는 기본 Deberta V2 Model입니다.

이 모델은 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] = Noneoutput_attentions: bool | None = Noneoutput_hidden_states: bool | None = Nonereturn_dict: bool | None = None**kwargs ) → 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.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 인덱스를 관련 벡터로 변환하는 방식에 대해 더 세밀한 제어가 필요한 경우에 유용합니다.
  • 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인 경우)로, 구성(DebertaV2Config)과 입력에 따라 다양한 요소를 포함합니다.

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

DebertaV2PreTrainedModel

클래스 transformers.DebertaV2PreTrainedModel

< >

( config: PreTrainedConfig*inputs**kwargs )

매개변수

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

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

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

forward

( *args**kwargs )

점으로 구분된 경로(예: torch.float32)에 대한 mock 값: 속성 접근 체인, 호출은 pass-through 데코레이터처럼 동작하며, repr은 해당 점으로 구분된 경로입니다. 이를 베이스 클래스로 사용하면 plain-type 베이스로 대체됩니다(PEP 560 __mro_entries__). 따라서 실제 서브클래스는 일반적인 메타클래스를 유지하고, inspect.signature는 mock의 __init__가 아닌 실제 __init__를 읽습니다.

DebertaV2ForMaskedLM

class transformers.DebertaV2ForMaskedLM

< >

( config: DebertaV2Config )

매개변수

  • config (DebertaV2Config) — 모델의 모든 매개변수를 포함하는 모델 구성 클래스입니다. 구성 파일로 초기화하면 모델에 연결된 가중치는 로드되지 않으며 구성만 로드됩니다. 모델 가중치를 로드하려면 from_pretrained() 메서드를 확인하세요.

language modeling 헤드가 위에 있는 Deberta V2 모델입니다.”

이 모델은 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] = Nonelabels: typing.Optional[torch.Tensor] = Noneoutput_attentions: bool | None = Noneoutput_hidden_states: bool | None = Nonereturn_dict: bool | None = None**kwargs ) → MaskedLMOutput 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.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), 선택 사항) — 마스크 언어 모델링 손실을 계산하는 데 사용되는 라벨입니다. 인덱스는 [-100, 0, ..., config.vocab_size] 범위여야 합니다(input_ids docstring 참조). 인덱스가 -100으로 설정된 토큰은 무시(마스크)되며, 손실은 라벨이 [0, ..., config.vocab_size] 범위에 있는 토큰에 대해서만 계산됩니다.
  • output_attentions (bool, 선택 사항) — 모든 attention 레이어의 attentions 텐서를 반환할지 여부. 자세한 내용은 반환 텐서 섹션의 attentions 항목을 참조하세요.
  • output_hidden_states (bool, 선택 사항) — 모든 레이어의 hidden states를 반환할지 여부입니다. 자세한 내용은 반환되는 텐서 중 hidden_states 항목을 참고하세요.
  • return_dict (bool, 선택) — 일반 튜플 대신 ModelOutput를 반환할지 여부.

반환값

MaskedLMOutput 또는 tuple(torch.Tensor)

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

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

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

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

예:

>>> from transformers import AutoTokenizer, DebertaV2ForMaskedLM
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("microsoft/deberta-v2-xlarge")
>>> model = DebertaV2ForMaskedLM.from_pretrained("microsoft/deberta-v2-xlarge")

>>> 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)
...

DebertaV2ForSequenceClassification

class transformers.DebertaV2ForSequenceClassification

< >

( config: DebertaV2Config )

매개변수

  • config (DebertaV2Config) — 모델의 모든 매개변수를 포함하는 모델 구성 클래스입니다. 구성 파일로 초기화하면 모델에 연결된 가중치는 로드되지 않으며 구성만 로드됩니다. 모델 가중치를 로드하려면 from_pretrained() 메서드를 확인하세요.

DeBERTa 모델은 풀링된 출력 위에 선형 레이어를 배치한 시퀀스 분류/회귀 헤드를 갖춘 transformer로, GLUE 작업 등에 사용됩니다.

이 모델은 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] = Nonelabels: typing.Optional[torch.Tensor] = Noneoutput_attentions: bool | None = Noneoutput_hidden_states: bool | None = Nonereturn_dict: bool | None = None**kwargs ) → SequenceClassifierOutput 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.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,), 선택 사항) — 시퀀스 분류/회귀 손실을 계산하는 데 사용되는 라벨입니다. 인덱스는 [0, ..., config.num_labels - 1] 범위에 있어야 합니다. config.num_labels == 1인 경우 회귀 손실(Mean-Square loss)이 계산되고, config.num_labels > 1인 경우 분류 손실(Cross-Entropy)이 계산됩니다.
  • output_attentions (bool, 선택 사항) — 모든 attention 레이어의 attentions 텐서를 반환할지 여부. 자세한 내용은 반환 텐서 섹션의 attentions 항목을 참조하세요.
  • output_hidden_states (bool, 선택 사항) — 모든 레이어의 hidden states를 반환할지 여부입니다. 자세한 내용은 반환되는 텐서 중 hidden_states 항목을 참고하세요.
  • return_dict (bool, 선택) — 일반 튜플 대신 ModelOutput를 반환할지 여부.

반환값

SequenceClassifierOutput 또는 tuple(torch.Tensor)

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

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

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

  • 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, DebertaV2ForSequenceClassification

>>> tokenizer = AutoTokenizer.from_pretrained("microsoft/deberta-v2-xlarge")
>>> model = DebertaV2ForSequenceClassification.from_pretrained("microsoft/deberta-v2-xlarge")

>>> 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 = DebertaV2ForSequenceClassification.from_pretrained("microsoft/deberta-v2-xlarge", num_labels=num_labels)

>>> labels = torch.tensor([1])
>>> loss = model(**inputs, labels=labels).loss
>>> round(loss.item(), 2)
...

다중 레이블 분류의 예시:

>>> import torch
>>> from transformers import AutoTokenizer, DebertaV2ForSequenceClassification

>>> tokenizer = AutoTokenizer.from_pretrained("microsoft/deberta-v2-xlarge")
>>> model = DebertaV2ForSequenceClassification.from_pretrained("microsoft/deberta-v2-xlarge", 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 = DebertaV2ForSequenceClassification.from_pretrained(
...     "microsoft/deberta-v2-xlarge", 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).loss

DebertaV2ForTokenClassification

class transformers.DebertaV2ForTokenClassification

< >

( config: DebertaV2Config )

매개변수

  • config (DebertaV2Config) — 모델의 모든 매개변수를 포함하는 모델 구성 클래스입니다. 구성 파일로 초기화하면 모델에 연결된 가중치는 로드되지 않으며 구성만 로드됩니다. 모델 가중치를 로드하려면 from_pretrained() 메서드를 확인하세요.

토큰 분류 헤드가 위에 있는 Deberta V2 transformer입니다(숨겨진 상태(hidden-states) 출력 위에 선형 레이어가 있는 구조)로, 예를 들어 Named-Entity-Recognition(NER) 작업에 사용됩니다.

이 모델은 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] = Nonelabels: typing.Optional[torch.Tensor] = Noneoutput_attentions: bool | None = Noneoutput_hidden_states: bool | None = Nonereturn_dict: bool | None = None**kwargs ) → TokenClassifierOutput 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.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] 범위에 있어야 합니다.
  • output_attentions (bool, 선택 사항) — 모든 attention 레이어의 attentions 텐서를 반환할지 여부. 자세한 내용은 반환 텐서 섹션의 attentions 항목을 참조하세요.
  • output_hidden_states (bool, 선택 사항) — 모든 레이어의 hidden states를 반환할지 여부입니다. 자세한 내용은 반환되는 텐서 중 hidden_states 항목을 참고하세요.
  • return_dict (bool, 선택) — 일반 튜플 대신 ModelOutput를 반환할지 여부.

반환값

TokenClassifierOutput 또는 tuple(torch.Tensor)

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

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

예:

>>> from transformers import AutoTokenizer, DebertaV2ForTokenClassification
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("microsoft/deberta-v2-xlarge")
>>> model = DebertaV2ForTokenClassification.from_pretrained("microsoft/deberta-v2-xlarge")

>>> 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)
...

DebertaV2ForQuestionAnswering

클래스 transformers.DebertaV2ForQuestionAnswering

< >

( config: DebertaV2Config )

매개변수

  • config (DebertaV2Config) — 모델의 모든 매개변수를 포함하는 모델 구성 클래스입니다. 구성 파일로 초기화하면 모델에 연결된 가중치는 로드되지 않으며 구성만 로드됩니다. 모델 가중치를 로드하려면 from_pretrained() 메서드를 확인하세요.

SQuAD와 같은 추출형 질의응답 작업을 위해 Deberta V2 transformer 위에 span classification head를 적용한 모델입니다. hidden-states 출력 위에 linear layer를 올려 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.Tensor] = Noneend_positions: typing.Optional[torch.Tensor] = Noneoutput_attentions: bool | None = Noneoutput_hidden_states: bool | None = Nonereturn_dict: bool | None = None**kwargs ) → 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.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 인덱스를 관련 벡터로 변환하는 방식에 대해 더 세밀한 제어가 필요한 경우에 유용합니다.
  • start_positions (torch.Tensor, shape (batch_size,), 선택 사항) — 토큰 분류 손실을 계산하기 위해 라벨이 지정된 스팬의 시작 위치(인덱스)에 대한 라벨입니다. 위치는 시퀀스 길이(sequence_length)로 클램프됩니다. 시퀀스 범위를 벗어난 위치는 손실 계산에 반영되지 않습니다.
  • end_positions (torch.Tensor, shape (batch_size,), 선택 사항) — 토큰 분류 손실을 계산하기 위해 라벨이 지정된 스팬의 끝 위치(인덱스)에 대한 라벨입니다. 위치는 시퀀스 길이(sequence_length)로 클램프됩니다. 시퀀스 범위를 벗어난 위치는 손실 계산에 반영되지 않습니다.
  • output_attentions (bool, 선택 사항) — 모든 attention 레이어의 attentions 텐서를 반환할지 여부. 자세한 내용은 반환 텐서 섹션의 attentions 항목을 참조하세요.
  • output_hidden_states (bool, 선택 사항) — 모든 레이어의 hidden states를 반환할지 여부입니다. 자세한 내용은 반환되는 텐서 중 hidden_states 항목을 참고하세요.
  • return_dict (bool, 선택) — 일반 튜플 대신 ModelOutput를 반환할지 여부.

반환값

QuestionAnsweringModelOutput 또는 tuple(torch.Tensor)

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

DebertaV2ForQuestionAnswering의 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, DebertaV2ForQuestionAnswering
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("microsoft/deberta-v2-xlarge")
>>> model = DebertaV2ForQuestionAnswering.from_pretrained("microsoft/deberta-v2-xlarge")

>>> 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)
...

DebertaV2ForMultipleChoice

class transformers.DebertaV2ForMultipleChoice

< >

( config: DebertaV2Config )

매개변수

  • config (DebertaV2Config) — 모델의 모든 매개변수를 포함하는 모델 구성 클래스입니다. 구성 파일로 초기화하면 모델에 연결된 가중치는 로드되지 않으며 구성만 로드됩니다. 모델 가중치를 로드하려면 from_pretrained() 메서드를 확인하세요.

RocStories/SWAG 작업과 같이, 풀링된 출력 위에 선형 레이어와 softmax를 적용한 다중 선택 분류 헤드가 있는 Deberta V2 모델.

이 모델은 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] = Nonelabels: typing.Optional[torch.Tensor] = Noneoutput_attentions: bool | None = Noneoutput_hidden_states: bool | None = Nonereturn_dict: bool | None = None**kwargs ) → MultipleChoiceModelOutput 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.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,), 선택 사항) — 다중 선택 분류 손실을 계산하는 데 사용되는 라벨입니다. 인덱스는 [0, ..., num_choices-1] 범위에 있어야 하며, num_choices는 입력 텐서의 두 번째 차원의 크기입니다. (위 input_ids 참조)
  • output_attentions (bool, 선택 사항) — 모든 attention 레이어의 attentions 텐서를 반환할지 여부. 자세한 내용은 반환 텐서 섹션의 attentions 항목을 참조하세요.
  • output_hidden_states (bool, 선택 사항) — 모든 레이어의 hidden states를 반환할지 여부입니다. 자세한 내용은 반환되는 텐서 중 hidden_states 항목을 참고하세요.
  • return_dict (bool, 선택) — 일반 튜플 대신 ModelOutput를 반환할지 여부.

반환값

MultipleChoiceModelOutput 또는 tuple(torch.Tensor)

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

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

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

  • loss (torch.Tensor, shape (1,), optional, labels가 제공될 때 반환됨) — 분류 손실.

  • logits (torch.Tensor, shape (batch_size, num_choices)) — num_choices는 입력 텐서의 두 번째 차원입니다. (위 input_ids 참조).

    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, DebertaV2ForMultipleChoice
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("microsoft/deberta-v2-xlarge")
>>> model = DebertaV2ForMultipleChoice.from_pretrained("microsoft/deberta-v2-xlarge")

>>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced."
>>> choice0 = "It is eaten with a fork and a knife."
>>> choice1 = "It is eaten while held in the hand."
>>> labels = torch.tensor(0).unsqueeze(0)  # choice0 is correct (according to Wikipedia ;)), batch size 1

>>> encoding = tokenizer([prompt, prompt], [choice0, choice1], return_tensors="pt", padding=True)
>>> outputs = model(**{k: v.unsqueeze(0) for k, v in encoding.items()}, labels=labels)  # batch size is 1

>>> # the linear classifier still needs to be trained
>>> loss = outputs.loss
>>> logits = outputs.logits
Update on GitHub