Transformers documentation
DistilBERT
このモデルは2019年10月2日にHF papersで公開され、2020年11月16日にHugging Face Transformersに貢献されました。
DistilBERT
DistilBERTは、知識蒸留によって事前学習され、推論が速く、学習に必要な計算リソースが少ない小型モデルを構築します。事前学習中の3重損失目的関数(言語モデリング損失、蒸留損失、コサイン距離損失)を通じて、同等の性能を示します。
すべての元のDistilBERTチェックポイントは、DistilBERT組織の下で確認できます。
右側のサイドバーにあるDistilBERTモデルをクリックすると、DistilBERTをさまざまな言語タスクに適用する方法の例をさらに確認できます。
以下の例では、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}]import torch
from transformers import AutoModelForSequenceClassification, AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained(
"distilbert/distilbert-base-uncased-finetuned-sst-2-english",
)
model = AutoModelForSequenceClassification.from_pretrained(
"distilbert/distilbert-base-uncased-finetuned-sst-2-english",
device_map="auto",
attn_implementation="sdpa"
)
inputs = tokenizer("I love using Hugging Face Transformers!", return_tensors="pt").to(model.device)
with torch.no_grad():
outputs = model(**inputs)
predicted_class_id = torch.argmax(outputs.logits, dim=-1).item()
predicted_label = model.config.id2label[predicted_class_id]
print(f"Predicted label: {predicted_label}")注記
- DistilBERTには
token_type_idsがないため、どのトークンがどのセグメントに属するかを指定する必要はありません。セグメント間は、区切りトークンtokenizer.sep_token(または[SEP])で区切るだけです。 - DistilBERTには、入力位置(
position_ids入力)を選択するオプションはありません。必要に応じて追加することは可能ですが、このオプションが必要であればお知らせください。
DistilBertConfig
クラス transformers.DistilBertConfig
< source >( 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デコーダーの隠れ層の数。 - n_heads (
int、任意、デフォルトは12) — Transformer デコーダーの各アテンション層におけるアテンションヘッドの数。 - dim (
int、任意、デフォルトは 768) — エンコーダ層およびプーラ層の次元数。 - hidden_dim (
int、任意、デフォルトは3072) — 隠れ表現の次元数。 - dropout (
Union[float, int]、任意、デフォルト値は0.1) — すべての dropout レイヤーの比率です。 - attention_dropout (
Union[float, int]、任意、デフォルトは0.1) — アテンション確率のドロップアウト率です。 - 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 と同様の設定が得られます。
設定オブジェクトは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.configDistilBertTokenizer
DistilBertTokenizerFast
DistilBertModel
class transformers.DistilBertModel
< source >( config: DistilBertConfig )
パラメータ
- config (DistilBertConfig) — モデルのパラメータをすべて含むモデル設定クラスです。設定ファイルで初期化しても、モデルに関連する重みは読み込まれず、設定のみが読み込まれます。モデルの重みをロードするには、from_pretrained() メソッドを参照してください。
特定のヘッドを上に載せず、生のhidden-statesを出力する素のDistilbert Modelです。
このモデルは PreTrainedModel を継承しています。すべてのモデルに実装されている汎用的なメソッド(ダウンロードや保存、入力埋め込みのリサイズ、ヘッドのプルーニングなど)については、スーパークラスのドキュメントを参照してください。
このモデルは、PyTorchのtorch.nn.Moduleのサブクラスでもあります。 通常のPyTorch Moduleとして使用し、一般的な使用方法や動作に関する詳細については、PyTorchのドキュメントを参照してください。
forward
< source >( 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.Tensor)
パラメータ
- input_ids (
torch.LongTensorの形状(batch_size, num_choices)) — 語彙における入力シーケンスのトークンインデックス。インデックスはAutoTokenizerを使用して取得できます。詳細については、PreTrainedTokenizer.encode()およびPreTrainedTokenizer.call()を参照してください。
- attention_mask (
torch.Tensorの形状(batch_size, sequence_length), 、任意) — パディングトークンのインデックスに対するアテンションを回避するためのマスク。[0, 1]:- マスクされていないトークンに対して1
- マスクされたトークンに対しては 0 です。
- inputs_embeds (
torch.Tensor、形状(batch_size, num_choices, hidden_size)、任意) —input_idsを渡す代わりに、埋め込み表現を直接渡すこともできます。これは、モデル内部の埋め込み検索行列よりも、input_idsのインデックスを関連するベクトルに変換する方法をより細かく制御したい場合に有用です。 - position_ids (
torch.Tensorの形状(batch_size, sequence_length), 、省略可) — 位置埋め込みにおける各入力シーケンスのトークンの位置のインデックス。範囲[0, config.n_positions - 1].
戻り値
BaseModelOutput または tuple(torch.Tensor)
torch.Tensor のタプル、または BaseModelOutput(return_dict=False が渡された場合、または config.return_dict=False の場合)。設定(DistilBertConfig)と入力に応じて、さまざまな要素で構成されます。
DistilBertModelのforwardメソッドは、__call__特殊メソッドをオーバーライドします。
この関数内でフォワードパスの手順を定義する必要がありますが、その後、この関数ではなく
Moduleインスタンスを呼び出すべきです。前者は前処理と後処理の実行を適切に処理するのに対し、後者はそれらを黙って無視するためです。
last_hidden_state (
torch.Tensor、形状(batch_size, sequence_length, hidden_size)) — モデルの最終層の出力における隠れ状態のシーケンス。hidden_states (
tuple(torch.Tensor)、optional、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)、optional、output_attentions=Trueが渡された場合またはconfig.output_attentions=Trueの場合に返されます) —torch.Tensorのタプル(各レイヤーごとに1つ)、形状は(batch_size, num_heads, sequence_length, sequence_length)。アテンションのsoftmax後のアテンション重み。自己アテンションヘッド内で加重平均を計算するために使用されます。
DistilBertForMaskedLM
class transformers.DistilBertForMaskedLM
< source >( config: DistilBertConfig )
パラメータ
- config (DistilBertConfig) — モデルのパラメータをすべて含むモデル設定クラスです。設定ファイルで初期化しても、モデルに関連する重みは読み込まれず、設定のみが読み込まれます。モデルの重みをロードするには、from_pretrained() メソッドを参照してください。
masked language modelingヘッドを備えたDistilBertモデル。
このモデルは PreTrainedModel を継承しています。すべてのモデルに実装されている汎用的なメソッド(ダウンロードや保存、入力埋め込みのリサイズ、ヘッドのプルーニングなど)については、スーパークラスのドキュメントを参照してください。
このモデルは、PyTorchのtorch.nn.Moduleのサブクラスでもあります。 通常のPyTorch Moduleとして使用し、一般的な使用方法や動作に関する詳細については、PyTorchのドキュメントを参照してください。
forward
< source >( 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.Tensor)
パラメータ
- input_ids (
torch.LongTensorの形状(batch_size, num_choices)) — 語彙における入力シーケンスのトークンインデックス。インデックスはAutoTokenizerを使用して取得できます。詳細については、PreTrainedTokenizer.encode()およびPreTrainedTokenizer.call()を参照してください。
- attention_mask (
torch.Tensorの形状(batch_size, sequence_length), 、任意) — パディングトークンのインデックスに対するアテンションを回避するためのマスク。[0, 1]:- マスクされていないトークンに対して1
- マスクされたトークンに対しては 0 です。
- inputs_embeds (
torch.Tensor、形状(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のドキュメント文字列を参照)。インデックスが-100に設定されたトークンは無視(マスク)され、損失は[0, ..., config.vocab_size]の範囲のラベルを持つトークンに対してのみ計算されます。 - position_ids (
torch.Tensorの形状(batch_size, sequence_length), 、省略可) — 位置埋め込みにおける各入力シーケンスのトークンの位置のインデックス。範囲[0, config.n_positions - 1].
戻り値
MaskedLMOutput または tuple(torch.Tensor)
torch.Tensor のタプル、または MaskedLMOutput(return_dict=False が渡された場合、または config.return_dict=False の場合)。設定(DistilBertConfig)と入力に応じて、さまざまな要素で構成されます。
DistilBertForMaskedLM の forward メソッドは、__call__ という特殊メソッドをオーバーライドします。
この関数内でフォワードパスの手順を定義する必要がありますが、その後、この関数ではなく
Moduleインスタンスを呼び出すべきです。前者は前処理と後処理の実行を適切に処理するのに対し、後者はそれらを黙って無視するためです。
loss (
torch.Tensor、形状(1,)、任意、labelsが指定された場合に返されます) — マスクド言語モデリング (MLM) の損失。logits (
torch.Tensor、形状(batch_size, sequence_length, config.vocab_size)) — 言語モデリングヘッドの予測スコア(SoftMax 適用前の各語彙トークンのスコア)。hidden_states (
tuple(torch.Tensor)、optional、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)、optional、output_attentions=Trueが渡された場合またはconfig.output_attentions=Trueの場合に返されます) —torch.Tensorのタプル(各レイヤーごとに1つ)、形状は(batch_size, num_heads, sequence_length, sequence_length)。アテンションのsoftmax後のアテンション重み。自己アテンションヘッド内で加重平均を計算するために使用されます。
例:
>>> 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
クラス transformers.DistilBertForSequenceClassification
< source >( config: DistilBertConfig )
パラメータ
- config (DistilBertConfig) — モデルのパラメータをすべて含むモデル設定クラスです。設定ファイルで初期化しても、モデルに関連する重みは読み込まれず、設定のみが読み込まれます。モデルの重みをロードするには、from_pretrained() メソッドを参照してください。
DistilBert モデル。プーリングされた出力の上に線形層を配置したシーケンス分類/回帰ヘッドを備えた Transformer です。GLUE タスクなどに使用できます。
このモデルは PreTrainedModel を継承しています。すべてのモデルに実装されている汎用的なメソッド(ダウンロードや保存、入力埋め込みのリサイズ、ヘッドのプルーニングなど)については、スーパークラスのドキュメントを参照してください。
このモデルは、PyTorchのtorch.nn.Moduleのサブクラスでもあります。 通常のPyTorch Moduleとして使用し、一般的な使用方法や動作に関する詳細については、PyTorchのドキュメントを参照してください。
forward
< source >( 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.Tensor)
パラメータ
- input_ids (
torch.Tensorの形状(batch_size, sequence_length), 、任意) — 語彙における入力シーケンスのトークンインデックスです。デフォルトでは、パディングは無視されます。インデックスはAutoTokenizerを使用して取得できます。詳細については、PreTrainedTokenizer.encode()およびPreTrainedTokenizer.call()を参照してください。
- attention_mask (
torch.Tensorの形状(batch_size, sequence_length), 、任意) — パディングトークンのインデックスに対するアテンションを回避するためのマスク。[0, 1]:- マスクされていないトークンに対して1
- マスクされたトークンに対しては 0 です。
- inputs_embeds (
torch.Tensor、形状(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の場合は回帰損失(平均二乗誤差)が計算され、config.num_labels > 1の場合は分類損失(クロスエントロピー)が計算されます。 - position_ids (
torch.Tensorの形状(batch_size, sequence_length), 、省略可) — 位置埋め込みにおける各入力シーケンスのトークンの位置のインデックス。範囲[0, config.n_positions - 1].
戻り値
SequenceClassifierOutput または tuple(torch.Tensor)
torch.Tensor のタプル、または SequenceClassifierOutput(return_dict=False が渡された場合、または config.return_dict=False の場合)。設定(DistilBertConfig)と入力に応じて、さまざまな要素で構成されます。
DistilBertForSequenceClassification の forward メソッドは、__call__ という特殊メソッドをオーバーライドします。
この関数内でフォワードパスの手順を定義する必要がありますが、その後、この関数ではなく
Moduleインスタンスを呼び出すべきです。前者は前処理と後処理の実行を適切に処理するのに対し、後者はそれらを黙って無視するためです。
loss (
torch.Tensor、shape(1,)、optional、labelsが指定された場合に返されます) — 分類損失(config.num_labels==1 の場合は回帰損失)。logits (
torch.Tensor、形状(batch_size, config.num_labels)) — SoftMax 適用前の分類(または config.num_labels==1 の場合は回帰)スコア。hidden_states (
tuple(torch.Tensor)、optional、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)、optional、output_attentions=Trueが渡された場合またはconfig.output_attentions=Trueの場合に返されます) —torch.Tensorのタプル(各レイヤーごとに1つ)、形状は(batch_size, num_heads, sequence_length, sequence_length)。アテンションのsoftmax後のアテンション重み。自己アテンションヘッド内で加重平均を計算するために使用されます。
単一ラベル分類の例:
>>> 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).lossDistilBertForMultipleChoice
クラス transformers.DistilBertForMultipleChoice
< source >( config: DistilBertConfig )
パラメータ
- config (DistilBertConfig) — モデルのパラメータをすべて含むモデル設定クラスです。設定ファイルで初期化しても、モデルに関連する重みは読み込まれず、設定のみが読み込まれます。モデルの重みをロードするには、from_pretrained() メソッドを参照してください。
RocStories/SWAGタスクなど、プーリングされた出力の上に線形層とsoftmaxを積み重ねた多肢選択分類ヘッドを備えたDistilbertモデル。
このモデルは PreTrainedModel を継承しています。すべてのモデルに実装されている汎用的なメソッド(ダウンロードや保存、入力埋め込みのリサイズ、ヘッドのプルーニングなど)については、スーパークラスのドキュメントを参照してください。
このモデルは、PyTorchのtorch.nn.Moduleのサブクラスでもあります。 通常のPyTorch Moduleとして使用し、一般的な使用方法や動作に関する詳細については、PyTorchのドキュメントを参照してください。
forward
< source >( 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.Tensor)
パラメータ
- input_ids (
torch.LongTensorの形状(batch_size, num_choices, sequence_length)) — 語彙における入力シーケンスのトークンインデックス。インデックスはAutoTokenizerを使用して取得できます。詳細については、PreTrainedTokenizer.encode()およびPreTrainedTokenizer.call()を参照してください。
- attention_mask (
torch.Tensorの形状(batch_size, sequence_length), 、任意) — パディングトークンのインデックスに対するアテンションを回避するためのマスク。[0, 1]:- マスクされていないトークンに対して1
- マスクされたトークンに対しては 0 です。
- inputs_embeds (
torch.Tensor、形状(batch_size, num_choices, sequence_length, hidden_size)、任意) —input_idsを渡す代わりに、埋め込み表現を直接渡すこともできます。これは、モデル内部の埋め込み検索行列よりも、input_idsのインデックスを対応するベクトルに変換する方法をより細かく制御したい場合に有用です。 - labels (
torch.LongTensor、shape(batch_size,)、任意) — マルチクラス分類の損失を計算するためのラベル。インデックスは[0, ..., num_choices-1]の範囲である必要があります。ここでnum_choicesは入力テンソルの2次元目のサイズです。(上記のinput_idsを参照) - position_ids (
torch.Tensorの形状(batch_size, sequence_length), 、省略可) — 位置埋め込みにおける各入力シーケンスのトークンの位置のインデックス。範囲[0, config.n_positions - 1].
戻り値
MultipleChoiceModelOutput または tuple(torch.Tensor)
torch.Tensor のタプル、または MultipleChoiceModelOutput(return_dict=False が渡された場合、または config.return_dict=False の場合)。設定(DistilBertConfig)と入力に応じて、さまざまな要素で構成されます。
DistilBertForMultipleChoice の forward メソッドは、__call__ という特殊メソッドをオーバーライドします。
この関数内でフォワードパスの手順を定義する必要がありますが、その後、この関数ではなく
Moduleインスタンスを呼び出すべきです。前者は前処理と後処理の実行を適切に処理するのに対し、後者はそれらを黙って無視するためです。
loss (
torch.Tensor、形状 (1,)、オプション、labelsが指定された場合に返されます) — 分類損失。logits (
torch.Tensor、形状(batch_size, num_choices)) — num_choices は入力テンソルの2番目の次元です(input_ids を参照)。分類スコア(SoftMax 適用前)。
hidden_states (
tuple(torch.Tensor)、optional、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)、optional、output_attentions=Trueが渡された場合またはconfig.output_attentions=Trueの場合に返されます) —torch.Tensorのタプル(各レイヤーごとに1つ)、形状は(batch_size, num_heads, sequence_length, sequence_length)。アテンションのsoftmax後のアテンション重み。自己アテンションヘッド内で加重平均を計算するために使用されます。
例:
>>> 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.logitsDistilBertForTokenClassification
クラス transformers.DistilBertForTokenClassification
< source >( config: DistilBertConfig )
パラメータ
- config (DistilBertConfig) — モデルのパラメータをすべて含むモデル設定クラスです。設定ファイルで初期化しても、モデルに関連する重みは読み込まれず、設定のみが読み込まれます。モデルの重みをロードするには、from_pretrained() メソッドを参照してください。
トークン分類ヘッド(隠れ状態の出力上に配置された線形層)を備えたDistilbertトランスフォーマー。例として、固有名詞認識(NER)タスクに使用できます。
このモデルは PreTrainedModel を継承しています。すべてのモデルに実装されている汎用的なメソッド(ダウンロードや保存、入力埋め込みのリサイズ、ヘッドのプルーニングなど)については、スーパークラスのドキュメントを参照してください。
このモデルは、PyTorchのtorch.nn.Moduleのサブクラスでもあります。 通常のPyTorch Moduleとして使用し、一般的な使用方法や動作に関する詳細については、PyTorchのドキュメントを参照してください。
forward
< source >( 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.Tensor)
パラメータ
- input_ids (
torch.Tensorの形状(batch_size, sequence_length), 、任意) — 語彙における入力シーケンスのトークンインデックスです。デフォルトでは、パディングは無視されます。インデックスはAutoTokenizerを使用して取得できます。詳細については、PreTrainedTokenizer.encode()およびPreTrainedTokenizer.call()を参照してください。
- attention_mask (
torch.Tensorの形状(batch_size, sequence_length), 、任意) — パディングトークンのインデックスに対するアテンションを回避するためのマスク。[0, 1]:- マスクされていないトークンに対して1
- マスクされたトークンに対しては 0 です。
- inputs_embeds (
torch.Tensor、形状(batch_size, sequence_length, hidden_size)、任意) —input_idsを渡す代わりに、埋め込み表現を直接渡すこともできます。これは、モデル内部の埋め込み参照行列よりも、input_idsのインデックスを対応するベクトルに変換する方法をより細かく制御したい場合に有用です。 - labels (
torch.LongTensor、形状(batch_size, sequence_length)、任意) — トークン分類の損失を計算するためのラベル。インデックスは[0, ..., config.num_labels - 1]の範囲である必要があります。 - position_ids (
torch.Tensorの形状(batch_size, sequence_length), 、省略可) — 位置埋め込みにおける各入力シーケンスのトークンの位置のインデックス。範囲[0, config.n_positions - 1].
戻り値
TokenClassifierOutput または tuple(torch.Tensor)
torch.Tensor のタプル、または TokenClassifierOutput(return_dict=False が渡された場合、または config.return_dict=False の場合)。設定(DistilBertConfig)と入力に応じて、さまざまな要素で構成されます。
DistilBertForTokenClassificationのforwardメソッドは、__call__特殊メソッドをオーバーライドします。
この関数内でフォワードパスの手順を定義する必要がありますが、その後、この関数ではなく
Moduleインスタンスを呼び出すべきです。前者は前処理と後処理の実行を適切に処理するのに対し、後者はそれらを黙って無視するためです。
loss (
torch.Tensor、shape(1,)、optional、labelsが指定された場合に返されます)— 分類損失。logits (
torch.Tensor、形状(batch_size, sequence_length, config.num_labels)) — SoftMax 適用前の分類スコア。hidden_states (
tuple(torch.Tensor)、optional、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)、optional、output_attentions=Trueが渡された場合またはconfig.output_attentions=Trueの場合に返されます) —torch.Tensorのタプル(各レイヤーごとに1つ)、形状は(batch_size, num_heads, sequence_length, sequence_length)。アテンションのsoftmax後のアテンション重み。自己アテンションヘッド内で加重平均を計算するために使用されます。
例:
>>> 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
クラス transformers.DistilBertForQuestionAnswering
< source >( config: DistilBertConfig )
パラメータ
- config (DistilBertConfig) — モデルのパラメータをすべて含むモデル設定クラスです。設定ファイルで初期化しても、モデルに関連する重みは読み込まれず、設定のみが読み込まれます。モデルの重みをロードするには、from_pretrained() メソッドを参照してください。
SQuAD などの抽出型質問応答タスク向けに、スパン分類ヘッドを上部に備えた Distilbert トランスフォーマー(隠れ状態の出力の上に線形層を置き、span start logits と span end logits を計算する)。
このモデルは PreTrainedModel を継承しています。すべてのモデルに実装されている汎用的なメソッド(ダウンロードや保存、入力埋め込みのリサイズ、ヘッドのプルーニングなど)については、スーパークラスのドキュメントを参照してください。
このモデルは、PyTorchのtorch.nn.Moduleのサブクラスでもあります。 通常のPyTorch Moduleとして使用し、一般的な使用方法や動作に関する詳細については、PyTorchのドキュメントを参照してください。
forward
< source >( 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.Tensor)
パラメータ
- input_ids (
torch.LongTensorの形状(batch_size, num_choices)) — 語彙における入力シーケンスのトークンインデックス。インデックスはAutoTokenizerを使用して取得できます。詳細については、PreTrainedTokenizer.encode()およびPreTrainedTokenizer.call()を参照してください。
- attention_mask (
torch.Tensorの形状(batch_size, sequence_length), 、任意) — パディングトークンのインデックスに対するアテンションを回避するためのマスク。[0, 1]:- マスクされていないトークンに対して1
- マスクされたトークンに対しては 0 です。
- inputs_embeds (
torch.Tensor、形状(batch_size, num_choices, hidden_size)、任意) —input_idsを渡す代わりに、埋め込み表現を直接渡すこともできます。これは、モデル内部の埋め込み検索行列よりも、input_idsのインデックスを関連するベクトルに変換する方法をより細かく制御したい場合に有用です。 - start_positions (
torch.Tensor、形状(batch_size,)、任意) — トークン分類損失の計算に使用する、ラベル付きスパンの開始位置(インデックス)のラベルです。 位置はシーケンスの長さ(sequence_length)にクランプされます。シーケンス外の位置は、損失の計算には考慮されません。 - end_positions (
torch.Tensor、形状(batch_size,)、任意) — トークン分類損失の計算に使用する、ラベル付きスパンの終了位置(インデックス)のラベルです。 位置はシーケンスの長さ(sequence_length)にクランプされます。シーケンス外の位置は、損失の計算には考慮されません。 - position_ids (
torch.Tensorの形状(batch_size, sequence_length), 、省略可) — 位置埋め込みにおける各入力シーケンスのトークンの位置のインデックス。範囲[0, config.n_positions - 1].
戻り値
QuestionAnsweringModelOutput または tuple(torch.Tensor)
torch.Tensor のタプル(return_dict=False が渡された場合、または config.return_dict=False の場合)または QuestionAnsweringModelOutput。設定(DistilBertConfig)と入力に応じて、さまざまな要素で構成されます。
DistilBertForQuestionAnsweringのforwardメソッドは、__call__特殊メソッドをオーバーライドします。
この関数内でフォワードパスの手順を定義する必要がありますが、その後、この関数ではなく
Moduleインスタンスを呼び出すべきです。前者は前処理と後処理の実行を適切に処理するのに対し、後者はそれらを黙って無視するためです。
loss (
torch.Tensor、形状(1,)、任意、labelsが指定された場合に返されます) — 総スパン抽出損失は、開始位置と終了位置の Cross-Entropy の和です。start_logits (
torch.Tensor、形状(batch_size, sequence_length)) — スパン開始スコア(SoftMax 適用前)。end_logits (
torch.Tensor、形状(batch_size, sequence_length)) — スパンの終了スコア(SoftMax 適用前)。hidden_states (
tuple(torch.Tensor)、optional、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)、optional、output_attentions=Trueが渡された場合またはconfig.output_attentions=Trueの場合に返されます) —torch.Tensorのタプル(各レイヤーごとに1つ)、形状は(batch_size, num_heads, sequence_length, sequence_length)。アテンションのsoftmax後のアテンション重み。自己アテンションヘッド内で加重平均を計算するために使用されます。
例:
>>> 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)
...