Transformers documentation

DistilBERT

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

이 모델은 2019-10-02에 HF papers에 게시되었으며, 2020-11-16에 Hugging Face Transformers에 기여되었습니다.

SDPA FlashAttention

DistilBERT

DistilBERT는 지식 증류(knowledge distillation)를 통해 사전 학습되어, 추론 속도가 더 빠르고 학습에 필요한 컴퓨트 자원이 적은 더 작은 모델을 생성합니다. 사전 학습 과정에서 언어 모델링 손실, 증류 손실, 코사인 거리 손실이라는 3중 손실 함수를 사용하여, 더 큰 transformer 언어 모델과 유사한 성능을 보여줍니다.

모든 원본 DistilBERT 체크포인트는 DistilBERT 조직에서 찾을 수 있습니다.

DistilBERT 모델을 적용하여 다양한 언어 작업을 수행하는 방법에 대한 추가 예제는 오른쪽 사이드바의 DistilBERT 모델에서 확인하세요.

아래 예제는 Pipeline, AutoModel 및 명령줄을 사용하여 텍스트를 분류하는 방법을 보여줍니다.

Pipeline
AutoModel
from transformers import pipeline


classifier = pipeline(
    task="text-classification",
    model="distilbert-base-uncased-finetuned-sst-2-english",
    device=0
)

result = classifier("I love using Hugging Face Transformers!")
print(result)
# Output: [{'label': 'POSITIVE', 'score': 0.9998}]

The input is a single word "Notes". 참고

  • DistilBERT에는 token_type_ids가 없으므로, 어떤 토큰이 어떤 세그먼트에 속하는지 지정할 필요가 없습니다. 세그먼트를 구분 토큰 tokenizer.sep_token(또는 [SEP])으로 분리하기만 하면 됩니다.
  • DistilBERT에는 입력 위치를 선택하는 옵션(position_ids 입력)이 없습니다. 필요에 따라 추가할 수 있으니, 해당 옵션이 필요하시면 알려 주세요.

DistilBertConfig

클래스 transformers.DistilBertConfig

< >

( 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 = 30522max_position_embeddings: int = 512sinusoidal_pos_embds: bool = Falsen_layers: int = 6n_heads: int = 12dim: int = 768hidden_dim: int = 3072dropout: float | int = 0.1attention_dropout: float | int = 0.1activation: str = 'gelu'initializer_range: float = 0.02qa_dropout: float | int = 0.1seq_classif_dropout: float | int = 0.2pad_token_id: int | None = 0eos_token_id: int | list[int] | None = Nonebos_token_id: int | None = Nonetie_word_embeddings: bool = True )

매개변수

  • vocab_size (int, 선택 사항, 기본값 30522) — 모델의 어휘 크기입니다. input_ids로 표현할 수 있는 서로 다른 토큰의 수를 정의합니다.
  • max_position_embeddings (int, 선택 사항, 기본값 512) — 이 모델이 사용될 수 있는 최대 시퀀스 길이입니다.
  • sinusoidal_pos_embds (boolean, 선택 사항, 기본값 False) — 사인 위치 임베딩을 사용할지 여부입니다.
  • n_layers (int, 선택 사항, 기본값 6) — Transformer decoder의 숨겨진 레이어 수입니다.
  • n_heads (int, 선택 사항, 기본값 12) — Transformer decoder의 각 attention layer에 사용할 attention head의 수입니다.
  • dim (int, 선택 사항, 기본값 768) — 인코더 레이어와 풀러 레이어의 차원.
  • hidden_dim (int, 선택 사항, 기본값 3072) — 숨겨진 표현의 차원입니다.
  • dropout (Union[float, int], 선택 사항, 기본값 0.1) — 모든 dropout 레이어에 적용할 비율입니다.
  • attention_dropout (Union[float, int], 선택 사항, 기본값 0.1) — Attention 확률에 적용할 dropout 비율입니다.
  • activation (str, 선택 사항, 기본값 gelu) — 디코더에서 사용되는 비선형 활성화 함수(함수 또는 문자열)입니다. 예를 들어, "gelu", "relu", "silu" 등이 있습니다.
  • initializer_range (float, 선택 사항, 기본값 0.02) — 모든 가중치 행렬을 초기화하는 truncated_normal_initializer의 표준 편차입니다.
  • qa_dropout (float, 선택, 기본값 0.1) — 질문 답변 모델 DistilBertForQuestionAnswering에서 사용되는 dropout 확률입니다.
  • seq_classif_dropout (float, 선택, 기본값 0.2) — 시퀀스 분류 및 다중 선택 모델 DistilBertForSequenceClassification에서 사용되는 dropout 확률입니다.
  • pad_token_id (int, 선택 사항, 기본값 0) — 어휘에서 패딩에 사용되는 토큰 ID입니다.
  • eos_token_id (Union[int, list[int]], 선택) — 어휘에서 스트림 종료에 사용되는 토큰 ID입니다.
  • bos_token_id (int, 선택 사항) — 어휘에서 스트림 시작에 사용되는 토큰 ID입니다.
  • tie_word_embeddings (bool, 선택, 기본값 True) — 모델의 tied_weights_keys 매핑에 따라 가중치 임베딩을 묶을지 여부.

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

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

예:

>>> from transformers import DistilBertConfig, DistilBertModel

>>> # Initializing a DistilBERT configuration
>>> configuration = DistilBertConfig()

>>> # Initializing a model (with random weights) from the configuration
>>> model = DistilBertModel(configuration)

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

DistilBertTokenizer

클래스 transformers.DistilBertTokenizer

< >

( *argsdo_lower_case: bool = True**kwargs )

DistilBertTokenizerFast

class transformers.DistilBertTokenizer

< >

( *argsdo_lower_case: bool = True**kwargs )

DistilBertModel

클래스 transformers.DistilBertModel

< >

( config: DistilBertConfig )

매개변수

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

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

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

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

forward

< >

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

매개변수

  • input_ids (torch.LongTensor 형상 (batch_size, num_choices)) — 어휘 사전에서 입력 시퀀스 토큰의 인덱스입니다. 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

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

  • inputs_embeds (torch.FloatTensor, shape (batch_size, num_choices, hidden_size), 선택) — input_ids를 전달하는 대신 임베딩 표현을 직접 전달할 수 있습니다. 이는 모델 내부의 임베딩 조회 행렬보다 input_ids 인덱스를 관련 벡터로 변환하는 방식을 더 세밀하게 제어하려는 경우에 유용합니다.
  • position_ids (torch.Tensor 의 shape (batch_size, sequence_length), , 선택 사항) — 입력 시퀀스 토큰의 위치 임베딩에서 각 토큰의 위치 인덱스. 범위는 [0, config.n_positions - 1].

    포지션 ID란 무엇인가요?

반환값

BaseModelOutput 또는 tuple(torch.FloatTensor)

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

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

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

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

  • hidden_states (tuple(torch.FloatTensor), 선택 사항, output_hidden_states=True가 전달되었거나 config.output_hidden_states=True인 경우 반환됨) — torch.FloatTensor의 튜플(모델에 임베딩 레이어가 있는 경우 임베딩 출력 1개 + 각 레이어의 출력 1개)로, 모양은 (batch_size, sequence_length, hidden_size)입니다.

    각 레이어의 출력에서 모델의 Hidden-states와 선택적 초기 임베딩 출력을 포함합니다.

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

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

DistilBertForMaskedLM

class transformers.DistilBertForMaskedLM

< >

( config: DistilBertConfig )

매개변수

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

masked language modeling 헤드가 위에 있는 DistilBert 모델.

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

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

forward

< >

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

매개변수

  • input_ids (torch.LongTensor 형상 (batch_size, num_choices)) — 어휘 사전에서 입력 시퀀스 토큰의 인덱스입니다. 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

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

  • inputs_embeds (torch.FloatTensor, shape (batch_size, num_choices, 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] 범위에 있는 토큰에 대해서만 계산됩니다.
  • position_ids (torch.Tensor 의 shape (batch_size, sequence_length), , 선택 사항) — 입력 시퀀스 토큰의 위치 임베딩에서 각 토큰의 위치 인덱스. 범위는 [0, config.n_positions - 1].

    포지션 ID란 무엇인가요?

반환값

MaskedLMOutput 또는 tuple(torch.FloatTensor)

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

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

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

  • loss (torch.FloatTensor, shape (1,), 선택, labels가 제공될 때 반환됨) — Masked language modeling(MLM) loss.

  • logits (torch.FloatTensor, shape (batch_size, sequence_length, config.vocab_size)) — 언어 모델링 헤드에서 생성된 예측 점수(SoftMax 적용 전 각 어휘 토큰에 대한 점수).

  • hidden_states (tuple(torch.FloatTensor), 선택 사항, output_hidden_states=True가 전달되었거나 config.output_hidden_states=True인 경우 반환됨) — torch.FloatTensor의 튜플(모델에 임베딩 레이어가 있는 경우 임베딩 출력 1개 + 각 레이어의 출력 1개)로, 모양은 (batch_size, sequence_length, hidden_size)입니다.

    각 레이어의 출력에서 모델의 Hidden-states와 선택적 초기 임베딩 출력을 포함합니다.

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

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

예:

>>> from transformers import AutoTokenizer, DistilBertForMaskedLM
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("google/distilbert-base-uncased")
>>> model = DistilBertForMaskedLM.from_pretrained("google/distilbert-base-uncased")

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

DistilBertForSequenceClassification

class transformers.DistilBertForSequenceClassification

< >

( config: DistilBertConfig )

매개변수

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

시퀀스 분류/회귀 헤드가 위에 있는 DistilBert 모델 변환기(풀링된 출력 위에 선형 레이어가 있는 형태)로, 예를 들어 GLUE 작업에 사용됩니다.

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

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

forward

< >

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

매개변수

  • 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

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

  • 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)이 계산됩니다.
  • position_ids (torch.Tensor 의 shape (batch_size, sequence_length), , 선택 사항) — 입력 시퀀스 토큰의 위치 임베딩에서 각 토큰의 위치 인덱스. 범위는 [0, config.n_positions - 1].

    포지션 ID란 무엇인가요?

반환값

SequenceClassifierOutput 또는 tuple(torch.FloatTensor)

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

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

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

  • loss (torch.FloatTensor, shape (1,), 선택 사항, labels가 제공될 때 반환됨) — 분류(또는 config.num_labels==1인 경우 회귀) 손실.

  • logits (torch.FloatTensor, shape (batch_size, config.num_labels)) — SoftMax 적용 전 분류(또는 config.num_labels==1인 경우 회귀) 점수.

  • hidden_states (tuple(torch.FloatTensor), 선택 사항, output_hidden_states=True가 전달되었거나 config.output_hidden_states=True인 경우 반환됨) — torch.FloatTensor의 튜플(모델에 임베딩 레이어가 있는 경우 임베딩 출력 1개 + 각 레이어의 출력 1개)로, 모양은 (batch_size, sequence_length, hidden_size)입니다.

    각 레이어의 출력에서 모델의 Hidden-states와 선택적 초기 임베딩 출력을 포함합니다.

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

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

단일 레이블 분류의 예시:

>>> import torch
>>> from transformers import AutoTokenizer, DistilBertForSequenceClassification

>>> tokenizer = AutoTokenizer.from_pretrained("google/distilbert-base-uncased")
>>> model = DistilBertForSequenceClassification.from_pretrained("google/distilbert-base-uncased")

>>> 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 = DistilBertForSequenceClassification.from_pretrained("google/distilbert-base-uncased", num_labels=num_labels)

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

다중 레이블 분류의 예시:

>>> import torch
>>> from transformers import AutoTokenizer, DistilBertForSequenceClassification

>>> tokenizer = AutoTokenizer.from_pretrained("google/distilbert-base-uncased")
>>> model = DistilBertForSequenceClassification.from_pretrained("google/distilbert-base-uncased", 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 = DistilBertForSequenceClassification.from_pretrained(
...     "google/distilbert-base-uncased", 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

DistilBertForMultipleChoice

class transformers.DistilBertForMultipleChoice

< >

( config: DistilBertConfig )

매개변수

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

Distilbert 모델은 풀링된 출력 위에 선형 레이어와 softmax를 적용한 다중 선택 분류 헤드를 포함하며, RocStories/SWAG와 같은 작업에 사용됩니다.

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

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

forward

< >

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

매개변수

  • input_ids (torch.LongTensor 형태 (batch_size, num_choices, 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

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

  • inputs_embeds (torch.FloatTensor, shape (batch_size, num_choices, sequence_length, hidden_size), 선택) — input_ids를 전달하는 대신 임베딩 표현을 직접 전달할 수 있습니다. 이는 모델 내부의 임베딩 조회 행렬보다 input_ids 인덱스를 관련 벡터로 변환하는 방식을 더 세밀하게 제어하려는 경우에 유용합니다.
  • labels (torch.LongTensor, shape (batch_size,), 선택 사항) — 다중 선택 분류 손실을 계산하는 데 사용되는 라벨입니다. 인덱스는 [0, ..., num_choices-1] 범위에 있어야 하며, num_choices는 입력 텐서의 두 번째 차원의 크기입니다. (위 input_ids 참조)
  • position_ids (torch.Tensor 의 shape (batch_size, sequence_length), , 선택 사항) — 입력 시퀀스 토큰의 위치 임베딩에서 각 토큰의 위치 인덱스. 범위는 [0, config.n_positions - 1].

    포지션 ID란 무엇인가요?

반환값

MultipleChoiceModelOutput 또는 tuple(torch.FloatTensor)

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

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

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

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

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

    SoftMax 적용 전 분류 점수.

  • hidden_states (tuple(torch.FloatTensor), 선택 사항, output_hidden_states=True가 전달되었거나 config.output_hidden_states=True인 경우 반환됨) — torch.FloatTensor의 튜플(모델에 임베딩 레이어가 있는 경우 임베딩 출력 1개 + 각 레이어의 출력 1개)로, 모양은 (batch_size, sequence_length, hidden_size)입니다.

    각 레이어의 출력에서 모델의 Hidden-states와 선택적 초기 임베딩 출력을 포함합니다.

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

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

예:

>>> from transformers import AutoTokenizer, DistilBertForMultipleChoice
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("distilbert-base-cased")
>>> model = DistilBertForMultipleChoice.from_pretrained("distilbert-base-cased")

>>> 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, choice0], [prompt, 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

DistilBertForTokenClassification

class transformers.DistilBertForTokenClassification

< >

( config: DistilBertConfig )

매개변수

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

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

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

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

forward

< >

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

매개변수

  • 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

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

  • 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] 범위에 있어야 합니다.
  • position_ids (torch.Tensor 의 shape (batch_size, sequence_length), , 선택 사항) — 입력 시퀀스 토큰의 위치 임베딩에서 각 토큰의 위치 인덱스. 범위는 [0, config.n_positions - 1].

    포지션 ID란 무엇인가요?

반환값

TokenClassifierOutput 또는 tuple(torch.FloatTensor)

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

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

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

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

  • logits (torch.FloatTensor, shape (batch_size, sequence_length, config.num_labels)) — SoftMax 적용 전 분류 점수.

  • hidden_states (tuple(torch.FloatTensor), 선택 사항, output_hidden_states=True가 전달되었거나 config.output_hidden_states=True인 경우 반환됨) — torch.FloatTensor의 튜플(모델에 임베딩 레이어가 있는 경우 임베딩 출력 1개 + 각 레이어의 출력 1개)로, 모양은 (batch_size, sequence_length, hidden_size)입니다.

    각 레이어의 출력에서 모델의 Hidden-states와 선택적 초기 임베딩 출력을 포함합니다.

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

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

예:

>>> from transformers import AutoTokenizer, DistilBertForTokenClassification
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("google/distilbert-base-uncased")
>>> model = DistilBertForTokenClassification.from_pretrained("google/distilbert-base-uncased")

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

DistilBertForQuestionAnswering

class transformers.DistilBertForQuestionAnswering

< >

( config: DistilBertConfig )

매개변수

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

SQuAD와 같은 추출형 질의응답 작업을 위해 상단에 스팬 분류 헤드가 있는 Distilbert 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] = Noneinputs_embeds: typing.Optional[torch.Tensor] = Nonestart_positions: typing.Optional[torch.Tensor] = Noneend_positions: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.Tensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → QuestionAnsweringModelOutput or tuple(torch.FloatTensor)

매개변수

  • input_ids (torch.LongTensor 형상 (batch_size, num_choices)) — 어휘 사전에서 입력 시퀀스 토큰의 인덱스입니다. 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

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

  • inputs_embeds (torch.FloatTensor, shape (batch_size, num_choices, hidden_size), 선택) — input_ids를 전달하는 대신 임베딩 표현을 직접 전달할 수 있습니다. 이는 모델의 내부 임베딩 조회 행렬보다 input_ids 인덱스를 관련 벡터로 변환하는 방식을 더 세밀하게 제어하려는 경우에 유용합니다.
  • start_positions (torch.Tensor, shape (batch_size,), 선택 사항) — 토큰 분류 손실을 계산하기 위해 라벨이 지정된 스팬의 시작 위치(인덱스)에 대한 라벨입니다. 위치는 시퀀스 길이(sequence_length)로 클램프됩니다. 시퀀스 범위를 벗어난 위치는 손실 계산에 반영되지 않습니다.
  • end_positions (torch.Tensor, shape (batch_size,), 선택 사항) — 토큰 분류 손실을 계산하기 위해 라벨이 지정된 스팬의 끝 위치(인덱스)에 대한 라벨입니다. 위치는 시퀀스 길이(sequence_length)로 클램프됩니다. 시퀀스 범위를 벗어난 위치는 손실 계산에 반영되지 않습니다.
  • position_ids (torch.Tensor 의 shape (batch_size, sequence_length), , 선택 사항) — 입력 시퀀스 토큰의 위치 임베딩에서 각 토큰의 위치 인덱스. 범위는 [0, config.n_positions - 1].

    포지션 ID란 무엇인가요?

반환값

QuestionAnsweringModelOutput 또는 tuple(torch.FloatTensor)

torch.FloatTensor의 튜플 또는 QuestionAnsweringModelOutput입니다. return_dict=False가 전달되었거나 config.return_dict=False인 경우, DistilBertConfig와 입력에 따라 다양한 요소를 포함합니다.

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

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

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

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

  • end_logits (torch.FloatTensor, shape (batch_size, sequence_length)) — SoftMax 적용 전 스팬 끝 점수.

  • hidden_states (tuple(torch.FloatTensor), 선택 사항, output_hidden_states=True가 전달되었거나 config.output_hidden_states=True인 경우 반환됨) — torch.FloatTensor의 튜플(모델에 임베딩 레이어가 있는 경우 임베딩 출력 1개 + 각 레이어의 출력 1개)로, 모양은 (batch_size, sequence_length, hidden_size)입니다.

    각 레이어의 출력에서 모델의 Hidden-states와 선택적 초기 임베딩 출력을 포함합니다.

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

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

예:

>>> from transformers import AutoTokenizer, DistilBertForQuestionAnswering
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("google/distilbert-base-uncased")
>>> model = DistilBertForQuestionAnswering.from_pretrained("google/distilbert-base-uncased")

>>> 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)
...
Update on GitHub