ホーム » sales-info の投稿 (ページ 3)
作者アーカイブ: sales-info
HuggingFace Transformers 4.17 : Get Started : 用語集
HuggingFace Transformers 4.17 : Get Started : 用語集 (翻訳/解説)
翻訳 : (株)クラスキャット セールスインフォメーション
作成日時 : 04/10/2022 (v4.17.0)
* 本ページは、HuggingFace Transformers の以下のドキュメントを翻訳した上で適宜、補足説明したものです:
* サンプルコードの動作確認はしておりますが、必要な場合には適宜、追加改変しています。
* ご自由にリンクを張って頂いてかまいませんが、sales-info@classcat.com までご一報いただけると嬉しいです。
- 人工知能研究開発支援
- 人工知能研修サービス(経営者層向けオンサイト研修)
- テクニカルコンサルティングサービス
- 実証実験(プロトタイプ構築)
- アプリケーションへの実装
- 人工知能研修サービス
- PoC(概念実証)を失敗させないための支援
- お住まいの地域に関係なく Web ブラウザからご参加頂けます。事前登録 が必要ですのでご注意ください。
◆ お問合せ : 本件に関するお問い合わせ先は下記までお願いいたします。
- 株式会社クラスキャット セールス・マーケティング本部 セールス・インフォメーション
- sales-info@classcat.com ; Web: www.classcat.com ; ClassCatJP
HuggingFace Transformers : Get Started : 用語集
一般用語
- autoencoding モデル : MLM 参照
- autoregressive モデル : CLM 参照
- CLM : 因果 (= causal) 言語モデリング、モデルがテキストを順番に読みそして次の単語を予測しなければならない、事前訓練済みタスクです。それは通常はセンテンス全体を読むことにより成されますが、特定の時間ステップで未来のトークンを隠すためにモデル内のマスクを使用します。
- 深層学習 : 幾つかの層を持つニューラルネットワークを使用する機械学習アルゴリズム
- MLM : masked 言語モデリング、モデルは (通常は幾つかのトークンをランダムにマスクすることにより成される) テキストの破損した (= corrupted) バージョンを見て、元のテキストを予測しなければならない事前訓練済みタスクです。
- multimodal (多様性) : テキストと別の種類の入力 (例えば画像) を結合するタスク。
- NLG: 自然言語生成 (= generation)、テキスト生成に関連する総てのタスク (例えば transformer と話す、翻訳)。
- NLP : 自然言語処理、「テキストを処理する」と言うための一般的な方法です。
- NLU : 自然言語理解 (= understanding)、テキスト内にあるものの理解に関連する総てのタスク (例えばテキスト全体、個々の単語の分類)。
- 事前訓練済みモデル : あるデータ (例えば総ての Wikipedia) 上で事前訓練されたモデル。事前訓練方法は自己教師あり目的を含みます、これはテキストを読んで次の単語を予測しようとする (CLM 参照) か、幾つかの単語をマスクしてそれらを予測しようとすることであり得ます (MLM 参照)。
- RNN : リカレント・ニューラルネットワーク、テキストを処理するために層に渡るループを使用するタイプのモデル。
- self-attention : 入力の各要素は入力のどの別の要素に注意を払うべきか を明らかにします。
- seq2seq or sequence-to-sequence : (Bart や T5 のような) 翻訳モデルや要約モデルのような、入力から新しいシークエンスを生成するモデル。
- トークン : センテンスの一部、通常は単語ですが、部分単語 (非一般的単語はしばしば部分単語に分割されます) や句読点シンボルでもあり得ます。
- transformer : self-attention ベースの深層学習モデル・アーキテクチャ。
モデル入力
総てのモデルは異なりますが他のものとの類似性を有します。従って殆どのモデルは同じ入力を用います、それはここで使用サンプルとともに詳述されます。
入力 ID
入力 id はしばしば入力としてモデルに渡される唯一の必須パラメータです。それらはトークン・インデックスで、モデルにより入力として使用されるシークエンスを構築するトークンの数値表現です。
各 tokenizer は異なって動作しますが基礎的なメカニズムは同じままです。ここに BERT tokenzier を使用するサンプルがあります、これは WordPiece tokenizer です :
from transformers import BertTokenizer
tokenizer = BertTokenizer.from_pretrained("bert-base-cased")
sequence = "A Titan RTX has 24GB of VRAM"
tokenizer はシークエンスを tokenzier 語彙で利用可能なトークンに分割する処理をします。
tokenized_sequence = tokenizer.tokenize(sequence)
トークンは単語か部分単語のいずれかです。ここでは例えば、”VRAM” はモデル語彙にないので、それは “V”, “RA” と “M” に分割されます。それらのトークンが別々の単語ではなく同じ単語の一部であることを示すために、“RA” と “M” のために double-hash プレフィックスが追加されます。
print(tokenized_sequence)
['A', 'Titan', 'R', '##T', '##X', 'has', '24', '##GB', 'of', 'V', '##RA', '##M']
そしてこれらのトークンはモデルにより理解可能な ID に変換できます。これはセンテンスを直接 tokenizer に供給することにより成されます、これは最高のパフォーマンスのために Tokenizers の Rust 実装を活用しています。
inputs = tokenizer(sequence)
tokenizer は対応するモデルが正しく動作するために必要な総ての引数を持つ辞書を返します。トークンインデックスはキー “inputs_ids” のもとにあります :
encoded_sequence = inputs["input_ids"]
print(encoded_sequence)
[101, 138, 18696, 155, 1942, 3190, 1144, 1572, 13745, 1104, 159, 9664, 2107, 102]
tokenizer は (関連モデルがそれらに依存する場合)「特殊トークン」を自動的に追加することに注意してください、これはモデルが時に使用する特殊な ID です。
前の id のシークエンスをデコードする場合、
decoded_sequence = tokenizer.decode(encoded_sequence)
次を見ます :
print(decoded_sequence)
[CLS] A Titan RTX has 24GB of VRAM [SEP]
これは BertModel がその入力に想定する方法であるからです。
Attention マスク
attention マスクはシークエンスをまとめてバッチ処理するときに使用されるオプションの引数です。
この引数はどのトークンが注意を払われるべきか、そしてどれがそうでないかをモデルに示します。
例えば、これらの 2 つのセンテンスを考えます :
from transformers import BertTokenizer
tokenizer = BertTokenizer.from_pretrained("bert-base-cased")
sequence_a = "This is a short sequence."
sequence_b = "This is a rather long sequence. It is at least longer than the sequence A."
encoded_sequence_a = tokenizer(sequence_a)["input_ids"]
encoded_sequence_b = tokenizer(sequence_b)["input_ids"]
エンコードされたバージョンは異なる長さを持ちます :
len(encoded_sequence_a), len(encoded_sequence_b)
(8, 19)
従って、それらをそのままで同じテンソル内に一緒に配置することはできません。最初のシークエンスは 2 番目のものの長さにまでパディングされる必要があるか、あるいは 2 番目のものが最初のものの長さにまで切り詰められる必要があります。
最初のケースでは、ID のリストは padding インデックスにより拡張されます。リストを tokenizer に渡してこのようにパディングすることを要求することができます :
padded_sequences = tokenizer([sequence_a, sequence_b], padding=True)
最初のセンテンスの右側にそれを 2 番目のものと同じ長さにするために 0 が追加されたことが分かります。
padded_sequences["input_ids"]
[[101, 1188, 1110, 170, 1603, 4954, 119, 102, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [101, 1188, 1110, 170, 1897, 1263, 4954, 119, 1135, 1110, 1120, 1655, 2039, 1190, 1103, 4954, 138, 119, 102]]
そしてこれは PyTorch や TensorFlow のテンソルに変換できます。attention マスクはパディングされたインデックスの位置を示す二値テンソルで、その結果モデルはそれらに注意を払いません。BertTokenizer については、1 は注意されるべき値を示し、その一方で 0 はパディングされた値を示します。この attention マスクはキー “attention_mask” のもとで tokenizer により返される辞書内にあります。
padded_sequences["attention_mask"]
[[1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]
トークン型 ID
幾つかのモデルの目的はセンテンスのペアの分類や質問応答を行なうことです。
これらは 2 つの異なるシークエンスが単一の “input_ids” エントリ内に結合されることを必要とします、これは通常は classifier ([CLS]) と separator ([SEP]) トークンのような特殊トークンの助けにより遂行されます。例えば、BERT モデルはその 2 つのシークエンス入力を次のように構築します :
# [CLS] SEQUENCE_A [SEP] SEQUENCE_B [SEP]
そのようなセンテンスを自動的に生成するために、このように 2 つのセンテンスを tokenizer に (前のように、リストではなく、) 2 つの引数として渡すことにより、tokenizer を利用できます :
from transformers import BertTokenizer
tokenizer = BertTokenizer.from_pretrained("bert-base-cased")
sequence_a = "HuggingFace is based in NYC"
sequence_b = "Where is HuggingFace based?"
encoded_dict = tokenizer(sequence_a, sequence_b)
decoded = tokenizer.decode(encoded_dict["input_ids"])
これは次を返します :
print(decoded)
[CLS] HuggingFace is based in NYC [SEP] Where is HuggingFace based? [SEP]
幾つかのモデルについては、1 つのシークエンスがどこで終わりそしてもう 1 つがどこから始まるかを理解するためにこれで十分です。けれども、BERT のような他のモデルはまたトークン型 ID も配備します (セグメント ID とも呼ばれます)。それらはモデルの 2 つのタイプのシークエンスを識別する二値マスクとして表されます。
tokenizer はこのマスクを “token_type_ids” エントリとして返します :
encoded_dict["token_type_ids"]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1]
最初のシークエンス、質問のために使用される「コンテキスト」は 0 で表される総てのトークンを持ち、その一方で「質問」に相当する 2 番目のシークエンスは 1 で表される総てのトークンを持ちます。
XLNetModel のような幾つかのモデルは 2 で表される追加のトークンを使用します。
位置 ID
(RNN に) 埋め込まれた各トークンの位置を持つ RNN とは違い、transformer は各トークンの位置を知りません。そのため、トークンのリスト内の各トークンの位置を識別するために位置 ID (position_ids) がモデルにより使用されます。
これらはオプションのパラメータです。position_ids がモデルに渡されない場合、ID は絶対的位置の埋め込みとして自動的に作成されます。
絶対的な位置埋め込みは範囲 [0, config.max_position_embeddings – 1] 内で選択されます。幾つかのモデルは sinusoidal (正弦波) 位置埋め込み or 相対的位置埋め込みのような他のタイプの位置埋め込みを利用します。
ラベル
ラベルはオプション引数で、モデルが損失自体を計算するために渡すことができます。これらのラベルはモデルの期待される予測であるべきです : それは予測と期待値 (ラベル) の間の損失を計算するために標準的な損失を利用します。
これらのラベルはモデルヘッドに従って異なります、例えば :
- シークエンス分類モデル (e.g., BertForSequenceClassification) については、モデルはシークエンス全体の期待されるラベルに対応するバッチの各値を持つ次元 (batch_size) のテンソルを想定します。
- トークン分類モデル (e.g., BertForTokenClassification) については、モデルは各個々のトークンの期待されるラベルに対応する各値を持つ次元 (batch_size, seq_length) のテンソルを想定します。
- masked 言語モデリング (e.g., BertForMaskedLM) については、モデルは各個々のトークンの期待されるラベルに対応する各値を持つ次元 (batch_size, seq_length) のテンソルを想定します : masked トークンのためのトークン ID であるラベルの場合、値は残りのためには無視されます (通常は -100)。
- sequence to sequence タスク (e.g., BartForConditionalGeneration, MBartForConditionalGeneration) については、モデルは各入力シークエンスに関連するターゲット・シークエンスに対応する各値を持つ次元 (batch_size, tgt_seq_length) のテンソルを想定します。訓練の間、BART と T5 の両者は適切な decoder_input_ids と decoder attention マスクを内部的に作成します。それらは通常は供給される必要はありません。これは Encoder-Decoder フレームワークを利用するモデルには当てはまりません。各特定のモデルのラベル上の詳細については各モデルのドキュメントを見てください。
ベースモデル (e.g. BertModel) はラベルを受け取りません、何故ならばこれらはベース transformer モデルで、単純に特徴を出力するだけだからです。
Decoder 入力 ID
この入力はエンコーダ・デコーダモデル特有で、デコーダに供給される入力 ID を含みます。これらの入力は翻訳や要約のような、sequence to sequence タスクのために使用されるべきで、通常は各モデルに固有の方法で構築されます。
殆どのエンコーダ・デコーダモデル (BART, T5) はラベルから独自に decoder_input_ids を作成します。そのようなモデルでは、ラベルを渡すことは訓練を扱うために好まれる方法です。
sequence to sequence 訓練のためにそれらがこれらの入力 ID をどのように処理するかを見るには各モデルの docs を確認してください。
順伝播 Chunking
transformer の各残差 attention ブロックでは self-attention 層には通常は 2 つの順伝播層が続きます。順伝播層の中間の埋め込みサイズはしばしばモデルの隠れサイズよりも大きいです (e.g., bert-base-uncased に対して)。
サイズ [batch_size, sequence_length] の入力について、中間の順伝播埋め込み [batch_size, sequence_length, config.intermediate_size] をストアするために必要なメモリはメモリ使用量の大きな割合を占める可能性があります。
以上
HuggingFace Transformers 4.17 : Get Started : 哲学
HuggingFace Transformers 4.17 : Get Started : 哲学 (翻訳/解説)
翻訳 : (株)クラスキャット セールスインフォメーション
作成日時 : 04/09/2022 (v4.17.0)
* 本ページは、HuggingFace Transformers の以下のドキュメントを翻訳した上で適宜、補足説明したものです:
* サンプルコードの動作確認はしておりますが、必要な場合には適宜、追加改変しています。
* ご自由にリンクを張って頂いてかまいませんが、sales-info@classcat.com までご一報いただけると嬉しいです。
- 人工知能研究開発支援
- 人工知能研修サービス(経営者層向けオンサイト研修)
- テクニカルコンサルティングサービス
- 実証実験(プロトタイプ構築)
- アプリケーションへの実装
- 人工知能研修サービス
- PoC(概念実証)を失敗させないための支援
- お住まいの地域に関係なく Web ブラウザからご参加頂けます。事前登録 が必要ですのでご注意ください。
◆ お問合せ : 本件に関するお問い合わせ先は下記までお願いいたします。
- 株式会社クラスキャット セールス・マーケティング本部 セールス・インフォメーション
- sales-info@classcat.com ; Web: www.classcat.com ; ClassCatJP
HuggingFace Transformers : Gettiing Started : 哲学
Transformers は以下のために構築された自説を曲げない (= opnionated) ライブラリです :
- 大規模な transformer モデルを利用/研究/拡張することを追求する NLP 研究者と教育者
- それらのモデルを再調整して and/or それらをプロダクションでサービス提供することを望むハンズオン実践者
- 事前訓練モデルをダウンロードして与えられた NLP タスクを解くためにそれを使用することを単に望む技術者
ライブラリは 2 つの強力な目標を念頭において設計されました :
- できる限り容易に高速に利用できるものとして :
- 学習しなければならないユーザ向け抽象化の数を強く制限しました、実際に、殆ど抽象化はなく、各モデルを利用するために必要な単に 3 つの標準的なクラス : configuration, models と tokenizer があるだけです。
- これらのクラス総ては共通の from_pretrained() インスタンス化メソッドを使用することで単純で統一された方法で事前訓練済みインスタンスから初期化できます、これは Hugging Face ハブ や貴方自身のセーブされたチェックポイントで提供される事前訓練されたチェックポイントから、 (必要であれば) ダウンロードを処理し、関連するクラス・インスタンスと関連データ (configurations のハイパーパラメータ, tokenizers の語彙とモデルの重み) をキャッシュしてロードします。
- それら 3 つの基底クラスの上に、ライブラリは 2 つの API を提供します : 与えられたタスク上でモデル (加えて関連する tokenizer と configuration) を素早く使用するための pipeline() そして与えられたモデルを素早く訓練または再調整するための Trainer() / Keras.fit です。
- その結果、このライブラリはニューラルネットのためのビルディング・ブロックのモジュール・ツールボックスでは ありません。ライブラリを拡張 / (その上で) 構築することを望むのであれば、通常の Python/PyTorch/TensorFlow/Keras モジュールを単に使用してそしてモデルロード/セーブのような機能を再利用するためにはライブラリの基底クラスから継承してください。
- 学習しなければならないユーザ向け抽象化の数を強く制限しました、実際に、殆ど抽象化はなく、各モデルを利用するために必要な単に 3 つの標準的なクラス : configuration, models と tokenizer があるだけです。
- 元のモデルにできる限り近いパフォーマンスを持つ最先端技術のモデルを提供する :
- 各アーキテクチャに対して少なくとも一つのサンプルを提供します、これはそのアーキテクチャの公式著者により提供された結果を再現します。
- コードは通常は元のコードベースに出来る限り近いです、これはある PyTorch コードは pytorchic ではないかもしれないことを意味します、何故ならばそれは変換された TensorFlow コードの結果そしてその逆である可能性があるからです。
- 各アーキテクチャに対して少なくとも一つのサンプルを提供します、これはそのアーキテクチャの公式著者により提供された結果を再現します。
幾つかの他のゴール :
- モデルの内部をできる限り一貫性を持って公開する :
- 単一の API を使用して、full 隠れ状態と attention 重みへのアクセスを与えます。
- tokenizer と基底モデルの API はモデル間で容易に切り替えられるように標準化されています。
- これらのモデルを再調整/調査するために見込みのあるツールの主観的な選択を組み入れます :
- 再調整のため語彙と埋め込みに新しいトークンを追加するための単純で/一貫した方法。
- transformer ヘッドをマスクして刈り取る (= prune) 単純な方法。
- PyTorch と TensorFlow 2.0 間を容易に切り替え、一つのフレームワークを使用して訓練して別のものを使用して推論することを可能にします。
主要コンセプト
ライブラリは各モデルに対して 3 つのタイプのクラスを中心に構築されます :
- BertModel のような Model クラス、これは 30+ PyTorch モデル (torch.nn.Module) や Keras モデル (tf.keras.Model) で、ライブラリで提供される事前訓練済み重みで動作します。
- BertConfig のような Configuration クラス、これはモデルを構築するために必要なパラメータ総てをストアします。これらを貴方自身でインスタンス化する必要は必ずしもありません。特に、どのような変更もなしに事前訓練済みモデルを使用している場合、モデルの作成は configuration のインスタンス化を自動的に処理します (これはモデルの一部です)。
- BertTokenizer のような Tokenizer クラス、これは各モデルのための語彙をストアして、モデルに供給されるトークン埋め込みインデックスのリスト内のエンコード/デコード文字列のためのメソッドを提供します。
これらのクラス総ては 2 つのメソッドを使用して事前訓練済みインスタンスからインスタンス化してローカルにセーブできます :
- from_pretrained() は、ライブラリ自身から提供される (サポートされるモデルは モデルハブ で見つけられます) かユーザによりローカルに (or サーバ上に) ストアされた事前訓練済みバージョンから model/configuration/tokenizer をインスタンス化させます。
- save_pretrained() は model/configuration/tokenizer をローカルにセーブさせます、その結果それは from_pretrained() を使用して再ロードできます。
以上
HuggingFace Transformers 4.17 : Get Started : クイック・ツアー
HuggingFace Transformers 4.17 : Get Started : クイック・ツアー (翻訳/解説)
翻訳 : (株)クラスキャット セールスインフォメーション
作成日時 : 04/09/2022 (v4.17.0)
* 本ページは、HuggingFace Transformers の以下のドキュメントを翻訳した上で適宜、補足説明したものです:
* サンプルコードの動作確認はしておりますが、必要な場合には適宜、追加改変しています。
* ご自由にリンクを張って頂いてかまいませんが、sales-info@classcat.com までご一報いただけると嬉しいです。
- 人工知能研究開発支援
- 人工知能研修サービス(経営者層向けオンサイト研修)
- テクニカルコンサルティングサービス
- 実証実験(プロトタイプ構築)
- アプリケーションへの実装
- 人工知能研修サービス
- PoC(概念実証)を失敗させないための支援
- お住まいの地域に関係なく Web ブラウザからご参加頂けます。事前登録 が必要ですのでご注意ください。
◆ お問合せ : 本件に関するお問い合わせ先は下記までお願いいたします。
- 株式会社クラスキャット セールス・マーケティング本部 セールス・インフォメーション
- sales-info@classcat.com ; Web: www.classcat.com ; ClassCatJP
HuggingFace Transformers 4.17 : Get Started : クイック・ツアー
Get up and running with Transformers! 素早い推論のために pipeline() を利用して始めましょう、そしてテキスト, ビジョン, or 音声タスクを解決するために AutoClass で事前訓練済みモデルと tokenizer を素早くロードしましょう。
Pipeline
与えられたタスクに対して事前訓練済みモデルを使用するためには pipeline() が最も簡単な方法です。
pipeline() は多くの一般的なタスクを out of the box にサポートします :
テキスト :
- センチメント分析 : 与えられたテキストの両極性 (= polarity) を分類する。
- テキスト生成 (in English) : 与えられた入力からテキストを生成する。
- 固有表現認識 (NER) : 各単語をそれが表すエンティティ (person, date, location 等) でラベル付けします
- 質問応答 : あるコンテキストと質問が与えられたとき、コンテキストから答えを抽出します。
- マスクされたテキストを埋める (Fill-mask) : マスクされた単語を含むテキストが与えられたとき、ブランクを埋めます。
- 要約 : テキストか文書の長いシークエンスの要約を生成します。
- 翻訳 : テキストを別の言語に翻訳します。
- 特徴抽出 : テキストのテンソル表現を作成します。
画像 :
- 画像分類 : 画像を分類する。
- 画像セグメンテーション : 画像の総てのピクセルを分類する。
- 物体検出 : 画像内の物体を検出する。
音声 :
- 音声分類 : 与えられた音声のセグメントにラベルを割り当てる。
- 自動発話認識 (ASR) : 音声データをテキストに文字起こしする。
pipeline() と関連タスクの詳細は、ここ でドキュメントを参照してください。
パイプラインの使用方法
以下のサンプルでは、センチメント分析のために pipeline() を利用ます。
まだインストールしていない場合には、以下の依存性をインストールしてください :
pip install torch
pip install torch
pipeline() をインポートして完了させたいタスクを指定します :
from transformers import pipeline
classifier = pipeline("sentiment-analysis")
pipeline はセンチメント分析のためのデフォルトの事前訓練済みモデルと tokenzier をダウンロードしてキャッシュします。そしてターゲットテキストで分類器を使用できます :
classifier("We are very happy to show you the 🤗 Transformers library.")
[{'label': 'POSITIVE', 'score': 0.9998}]
複数のセンテンスについては、センテンスのリストを pipeline() に渡します、これは辞書のリストを返します :
results = classifier(["We are very happy to show you the 🤗 Transformers library.", "We hope you don't hate it."])
for result in results:
print(f"label: {result['label']}, with score: {round(result['score'], 4)}")
label: POSITIVE, with score: 0.9998 label: NEGATIVE, with score: 0.5309
pipeline() はまたデータセット全体に対してイテレートすることもできます。🤗 データセット・ライブラリをインストールすることから始めます :
pip install datasets
解決したいタスクと使用したいモデルで pipeline() を作成します。テンソルを CUDA デバイスに置くためにデバイスパラメータを 0 に設定します :
from transformers import pipeline
speech_recognizer = pipeline("automatic-speech-recognition", model="facebook/wav2vec2-base-960h", device=0)
次に、イテレートしたいデータセット (詳細は 🤗 Datasets クイックスタート 参照) をロードします。例えば、SUPERB データセットをロードしましょう :
import datasets
dataset = datasets.load_dataset("superb", name="asr", split="test")
データセット全体をパイプラインに渡すことができます :
files = dataset["file"]
speech_recognizer(files[:4])
[{'text': 'HE HOPED THERE WOULD BE STEW FOR DINNER TURNIPS AND CARROTS AND BRUISED POTATOES AND FAT MUTTON PIECES TO BE LADLED OUT IN THICK PEPPERED FLOWER FAT AND SAUCE'}, {'text': 'STUFFERED INTO YOU HIS BELLY COUNSELLED HIM'}, {'text': 'AFTER EARLY NIGHTFALL THE YELLOW LAMPS WOULD LIGHT UP HERE AND THERE THE SQUALID QUARTER OF THE BROTHELS'}, {'text': 'HO BERTIE ANY GOOD IN YOUR MIND'}]
(音声やビジョンでのような) 入力が大きい大規模なデータセットについては、総ての入力をメモリにロードするリストの代わりに generator を渡すことを望むでしょう。詳細は パイプライン・ドキュメント を見てください。
パイプラインで別のモデルと tokenizer を使用する
pipeline() は モデルハブ から任意のモデルを提供できるので、他のユースケースに pipeline() を適応させることは容易です。例えば、フランス語テキストを扱えるモデルを望む場合、適切なモデルのためにフィルタリングするためにモデルハブでタグを使用します。フィルタリングされたトップの結果はセンチメント分析のために再調整されたマルチリンガル BERT モデル を返します。Great, let’s use this model!
model_name = "nlptown/bert-base-multilingual-uncased-sentiment"
事前訓練済みモデルと関連するトークナイザーをロードするために AutoModelForSequenceClassification と AutoTokenizer を使用します (AutoClass については後述) :
from transformers import AutoTokenizer, AutoModelForSequenceClassification
model = AutoModelForSequenceClassification.from_pretrained(model_name)
tokenizer = AutoTokenizer.from_pretrained(model_name)
from transformers import AutoTokenizer, TFAutoModelForSequenceClassification
model = TFAutoModelForSequenceClassification.from_pretrained(model_name)
tokenizer = AutoTokenizer.from_pretrained(model_name)
そして pipeline() でモデルとトークナイザーを指定して、ターゲットテキストに分類器を適用できます :
classifier = pipeline("sentiment-analysis", model=model, tokenizer=tokenizer)
classifier("Nous sommes très heureux de vous présenter la bibliothèque 🤗 Transformers.")
[{'label': '5 stars', 'score': 0.7273}]
貴方のユースケースのためのモデルを見つけられない場合、貴方のデータで事前訓練済みモデルを再調整する必要があります。その方法を学習するには 再調整チュートリアル を見てください。最後に、事前訓練済みモデルを再調整した後には、NLP を皆のために民主化するためにそれをモデルハブでコミュニティと共有する (ここ のチュートリアル参照) ことを考えてください!🤗
AutoClass
内部的には、AutoModelForSequenceClassification と AutoTokenizer クラスは pipeline() を駆動するために一緒に動作しています。AutoClass は事前訓練済みモデルのアーキテクチャををその名前かパスから自動的に取得するショートカットです。タスクのための適切な AutoClass と関連するトークナイザーを AutoTokenizer で選択する必要があるだけです。
サンプルに戻り pipeline() の結果を複製するために AutoClass をどのように使用できるかを見ましょう。
AutoTokenizer
トークナイザーはテキストをモデルが理解可能な形式に前処理する役割を負います。最初に、トークナイザーはテキストをトークンと呼ばれる単語に分割します。単語を分割する方法やレベルを含む、トークン化プロセスを規定する複数のルールがあります (トークン化については ここ で更に学習してください)。覚えておくべき最も重要なことは、モデルがそれで事前訓練されたトークン化ルールを使用していることを確実にするために同じモデル名でトークナイザーをインスタンス化する必要があることです。
AutoTokenizer でトークナイザーをロードします :
from transformers import AutoTokenizer
model_name = "nlptown/bert-base-multilingual-uncased-sentiment"
tokenizer = AutoTokenizer.from_pretrained(model_name)
次に、トークナイザーはモデルへの入力としてテンソルを構築するためにトークンを数値に変換します。これはモデルの語彙として知られています。
テキストをトークナイザーに渡します :
encoding = tokenizer("We are very happy to show you the 🤗 Transformers library.")
print(encoding)
{'input_ids': [101, 11312, 10320, 12495, 19308, 10114, 11391, 10855, 10103, 100, 58263, 13299, 119, 102], 'token_type_ids': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'attention_mask': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]}
トークナイザーは以下を含む辞書を返します :
- input_ids : トークンの数値表現。
- atttention_mask : どのトークンが注目されるべきかを示す。
丁度 pipeline() のように、トークナイザーは入力のリストを受け取ります。更に、トークナイザーはまた均一な長さのバッチを返すためにテキストをパディングして切り詰めます :
pt_batch = tokenizer(
["We are very happy to show you the 🤗 Transformers library.", "We hope you don't hate it."],
padding=True,
truncation=True,
max_length=512,
return_tensors="pt",
)
tf_batch = tokenizer(
["We are very happy to show you the 🤗 Transformers library.", "We hope you don't hate it."],
padding=True,
truncation=True,
max_length=512,
return_tensors="tf",
)
トークン化の詳細は 前処理 チュートリアルを読んでください。
AutoModel
🤗 Transformers は事前訓練済みインスタンスをロードする単純で統一された方法を提供します。これは、AutoTokenizer をロードするように AutoModel をロードできることを意味します。唯一の違いはタスクに対して正しい AutoModel を選択することです。テキスト – or シークエンス – 分類を行なっていますので、AutoModelForSequenceClassification をロードします。TensorFlow の同値は単純に TFAutoModelForSequenceClassification です :
from transformers import AutoModelForSequenceClassification
model_name = "nlptown/bert-base-multilingual-uncased-sentiment"
pt_model = AutoModelForSequenceClassification.from_pretrained(model_name)
from transformers import TFAutoModelForSequenceClassification
model_name = "nlptown/bert-base-multilingual-uncased-sentiment"
tf_model = TFAutoModelForSequenceClassification.from_pretrained(model_name)
これで前処理した入力のバッチをモデルに直接渡すことができます。PyTorch モデルを使用している場合には、** を追加することで辞書をアンパックしてください。TensorFlow については、辞書キーを直接テンソルに渡してください。
pt_outputs = pt_model(**pt_batch)
tf_outputs = tf_model(tf_batch)
モデルは logits 属性内で最後の活性を出力します。確率を取得するためには softmax 関数を logits に適用します :
from torch import nn
pt_predictions = nn.functional.softmax(pt_outputs.logits, dim=-1)
print(pt_predictions)
tensor([[0.0021, 0.0018, 0.0115, 0.2121, 0.7725], [0.2084, 0.1826, 0.1969, 0.1755, 0.2365]], grad_fn=)
import tensorflow as tf
tf_predictions = tf.nn.softmax(tf_outputs.logits, axis=-1)
print(tf_predictions)
tf.Tensor( [[0.00206 0.00177 0.01155 0.21209 0.77253] [0.20842 0.18262 0.19693 0.1755 0.23652]], shape=(2, 5), dtype=float32)
総ての 🤗 Transformers モデルは (PyTorch or TensorFlow) は (softmax のような) 最終的な活性化関数の前にテンソルを出力します、最後の活性化関数は損失と融合されることが多いからです。
モデルは標準的な torch.nn.Module or a tf.keras.Model ですので、通常の訓練ループでそれらを使用できます。けれども、より簡単にするため、 🤗 Transformers は PyTorch のために Trainer クラスを提供しています、これは分散訓練, 混合精度, 等のための機能を追加します。TensorFlow については、Keras からの fit メソッドを利用できます。詳細は 訓練チュートリアル を参照してください。
🤗 Transformers モデル出力は特殊なデータクラスなので、それらの属性は IDE で自動補完されます。モデル出力はまたタプルか辞書のようにも動作します (e.g. 整数, スライス, 文字列でインデックスできます)、その場合には None の属性は無視されます。
モデルのセーブ
モデルが再調整されたら、PreTrainedModel.save_pretrained() を使用してそれをそのトークナイザーと共にセーブできます :
pt_save_directory = "./pt_save_pretrained"
tokenizer.save_pretrained(pt_save_directory)
pt_model.save_pretrained(pt_save_directory)
tf_save_directory = "./tf_save_pretrained"
tokenizer.save_pretrained(tf_save_directory)
tf_model.save_pretrained(tf_save_directory)
モデルを再度利用する準備ができたときには、それを PreTrainedModel.from_pretrained() で再ロードします :
pt_model = AutoModelForSequenceClassification.from_pretrained("./pt_save_pretrained")
tf_model = TFAutoModelForSequenceClassification.from_pretrained("./tf_save_pretrained")
一つの特にクールな 🤗 Transformers の機能はモデルをセーブしてそれを PyTorch か TensorFlow モデルのいずれかとして再ロードする機能です。from_pt or from_tf パラメータはモデルを一つのフレームワークから他方に変換できます :
from transformers import AutoModel
tokenizer = AutoTokenizer.from_pretrained(tf_save_directory)
pt_model = AutoModelForSequenceClassification.from_pretrained(tf_save_directory, from_tf=True)
from transformers import TFAutoModel
tokenizer = AutoTokenizer.from_pretrained(pt_save_directory)
tf_model = TFAutoModelForSequenceClassification.from_pretrained(pt_save_directory, from_pt=True)
以上
HuggingFace Transformers 4.17 : 概要
HuggingFace Transformers 4.17 : 概要 (翻訳/解説)
翻訳 : (株)クラスキャット セールスインフォメーション
作成日時 : 04/04/2022 (v4.17.0)
* 本ページは、HuggingFace Transformers の以下のドキュメントを翻訳した上で適宜、補足説明したものです:
* サンプルコードの動作確認はしておりますが、必要な場合には適宜、追加改変しています。
* ご自由にリンクを張って頂いてかまいませんが、sales-info@classcat.com までご一報いただけると嬉しいです。
- 人工知能研究開発支援
- 人工知能研修サービス(経営者層向けオンサイト研修)
- テクニカルコンサルティングサービス
- 実証実験(プロトタイプ構築)
- アプリケーションへの実装
- 人工知能研修サービス
- PoC(概念実証)を失敗させないための支援
- お住まいの地域に関係なく Web ブラウザからご参加頂けます。事前登録 が必要ですのでご注意ください。
◆ お問合せ : 本件に関するお問い合わせ先は下記までお願いいたします。
- 株式会社クラスキャット セールス・マーケティング本部 セールス・インフォメーション
- sales-info@classcat.com ; Web: www.classcat.com ; ClassCatJP
HuggingFace Transformers 4.17 : 概要
JAX, PyTorch と TensorFlow のための最先端の機械学習
Transformers は、テキスト、ビジョンと音声のような様々な様相のタスクを遂行する数千の事前訓練済みモデルを提供しています。
これらのモデルを以下で適用できます :
- テキスト – 100 言語以上で、テキスト分類, 情報抽出, 質問応答, 要約, 翻訳, テキスト生成のようなタスクのために。
- 画像 – 画像分類、物体検出 と セグメンテーションのようなタスクのために。
- 音声 – 発話認識と音声分類のようなタスクのために。
Transformer モデルはまた テーブル質問応答, 光学文字認識, スキャンされた文書からの情報抽出, 動画分類, そして視覚的質問応答 のような、組み合わされた様々な様相 上のタスクも遂行します。
Transformers はそれらの事前訓練済みモデルを素早くダウンロードして与えられたテキスト上で利用し、それらを貴方自身のデータセット上で再調整し、それからそれらを私達の モデル・ハブ 上でコミュニティと共有するための API を提供します。同時に、アーキテクチャを定義する各 python モジュールは完全にスタンドアロンで、素早い研究実験を可能にするために変更できます。
Transformers は 3 つの最もポピュラーな深層学習ライブラリ – Jax, PyTorch と TensorFlow により、それらの間のシームレスな統合によって支援されます。他のものでそれらを推論のためにロードする前にその一つでモデルを訓練することは簡単です。
オンライン・デモ
私達のモデルの殆どを モデルハブ からのそれらのページで直接テストすることができます。public と private モデルのために プライベートモデル・ホスティング、バージョニング & 推論 API もまた供給します。
ここに幾つかサンプルがあります :
自然言語処理 :
- BERT によるマスクされた単語補完
- Electra による固有表現抽出
- GPT-2 によるテキスト生成
- RoBERTa による自然言語推論
- BART による要約
- DistilBERT による質問応答
- T5 による翻訳
コンピュータビジョン
音声 :
Hugging Face チームにより構築された Write With Transformer はこのレポジトリのテキスト生成機能の公式デモです。
クイック・ツアー
与えられた入力 (テキスト, 画像, 音声, …) 上でモデルを直ちに利用するため、パイプライン API を提供しています。パイプラインは事前訓練済みモデルをそのモデル訓練の間に使用された前処理と一緒にグループ化します。ここにポジティブ vs ネガティブ・テキストを分類するためのパイプラインを素早く利用する方法があります :
>>> from transformers import pipeline
# Allocate a pipeline for sentiment-analysis
>>> classifier = pipeline('sentiment-analysis')
>>> classifier('We are very happy to introduce pipeline to the transformers repository.')
[{'label': 'POSITIVE', 'score': 0.9996980428695679}]
コードの 2 番目の行はパイプラインで使用された事前訓練済みモデルをダウンロードしてキャッシュします、一方で 3 番目の行はそれを与えられたテキスト上で評価します。ここでは答えは 99.97% の信頼度で「ポジティブ」です。
多くの NLP タスクは (使用準備ができている) 事前訓練済みのパイプラインを持ちます。例えば、コンテキストが与えられたとき質問への回答を容易に抽出できます :
>>> from transformers import pipeline
# Allocate a pipeline for question-answering
>>> question_answerer = pipeline('question-answering')
>>> question_answerer({
... 'question': 'What is the name of the repository ?',
... 'context': 'Pipeline has been included in the huggingface/transformers repository'
... })
{'score': 0.30970096588134766, 'start': 34, 'end': 58, 'answer': 'huggingface/transformers'}
答えに加えて、ここで使用される事前訓練済みモデルは (トークン化されたセンテンスにおける答えの開始位置と終了位置とともに) その信頼度スコアを返しました。このチュートリアル でパイプライン API によりサポートされるタスクについて更に学習できます。
与えられたタスク上で任意の事前訓練済みモデルをダウンロードして利用するには、3 行のコードを必要とするだけです。ここに PyToch バージョンがあります :
>>> from transformers import AutoTokenizer, AutoModel
>>> tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
>>> model = AutoModel.from_pretrained("bert-base-uncased")
>>> inputs = tokenizer("Hello world!", return_tensors="pt")
>>> outputs = model(**inputs)
そしてここに TensorFlow のための同値なコードがあります :
>>> from transformers import AutoTokenizer, TFAutoModel
>>> tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
>>> model = TFAutoModel.from_pretrained("bert-base-uncased")
>>> inputs = tokenizer("Hello world!", return_tensors="tf")
>>> outputs = model(**inputs)
トークナイザーは事前訓練済みのモデルが想定する前処理の総ての責任を負い、そして (上のサンプルでのように) 単一の文字列かリスト上で直接呼び出せます。それは辞書を出力します、これは下流コードで利用するか、あるいは ** 引数 unpacking 演算子を使用して単純にモデルに渡すことができます。
モデル自身は通常の Pytorch nn.Module や TensorFlow tf.keras.Model で (貴方のバックエンドに依存します)、これらは普通に利用できます。このチュートリアル は古典的な PyTorch or TensorFlow 訓練ループにそのようなモデルをどのように統合するか、あるいは新しいデータセット上で素早く再調整するために Trainer API をどのように使用するかを説明しています。
何故私は transformers を使用するべきでしょう?
- 使いやすい最先端のモデル :
- 自然言語理解 & 生成、コンピュータビジョン、そして音声タスク上の高パフォーマンス。
- 教育者と実践者のための入門への低い障壁。
- 学習すべき 3 つのクラスだけを持つ、ユーザが直面する少ない抽象化。
- 事前訓練済みモデルの総てを使用するための統一 API。
- より低い計算コスト、より小さいカーボンフットプリント (二酸化炭素排出量) :
- 研究者は常に再訓練する代わりに訓練済みモデルを共有できます。
- 実践者は計算時間とプロダクション・コストを削減することができます。
- 幾つかは100 言語以上の、20,000 超の事前訓練済みモデルを持つ数十のアーキテクチャ。
- モデルのライフタイムの総てのパートのために適切なフレームワークを選択する :
- 3 行のコードで最先端のモデルを訓練します。
- TF2.0/PyTorch/JAX フレームワーク間で単一モデルを自在に移動する。
- 訓練、評価、プロダクションのための適切なフレームワークをシームレスに選択する。
- 貴方のニーズに合わせてモデルやサンプルを容易にカスタマイズする :
- 元の著者により公開された結果を再現するための各アーキテクチャのためのサンプル。
- できる限り一貫してモデル内部を公開する。
- モデルファイルは素早い実験のためにライブラリから独立的に利用できる。
何故 transformers を利用するべきではないのでしょう?
- このライブラリはニューラルネットのためのビルディングブロックのモジュール・ツールボックスではありません。研究者が追加の抽象化/ファイルに深入りすることなくモデルの各々の上で素早く iterate できるようにように、モデルファイルのコードは意図的な追加の抽象によりリファクタリングされません。
- 訓練 API は任意のモデル上で動作することを意図されていませんがライブラリにより提供されるモデルで動作するように最適化されています。一般的な機械学習ループのためには、他のライブラリを利用するべきです。
- 私達は可能な限り多くのユースケースを提示する努力をする一方で、examples フォルダ のスクリプトは単なるそれ : サンプルです。それらは貴方の特定の問題上でそのままでは動作しないでしょうし、それらを貴方のニーズに適応させるためにコードの数行を変更する必要があることが想定されます。
モデル・アーキテクチャ
Transformers により提供される 総てのモデルチェックポイント は huggingface.co モデルハブ からシームレスに統合されていて、そこではそれらは ユーザ と 組織 により直接アップロードされています。
チェックポイントの現在の数 : モデル 35,704 (as of 4/08/2022)
Transformers は現在以下のアーキテクチャを提供しています (それらの各々の高位な要約については ここ を参照) :
- ALBERT (from Google Research and the Toyota Technological Institute at Chicago) released with the paper ALBERT: A Lite BERT for Self-supervised Learning of Language Representations, by Zhenzhong Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut.
- BART (from Facebook) released with the paper BART: Denoising Sequence-to-Sequence Pre-training for Natural Language Generation, Translation, and Comprehension by Mike Lewis, Yinhan Liu, Naman Goyal, Marjan Ghazvininejad, Abdelrahman Mohamed, Omer Levy, Ves Stoyanov and Luke Zettlemoyer.
- BARThez (from École polytechnique) released with the paper BARThez: a Skilled Pretrained French Sequence-to-Sequence Model by Moussa Kamal Eddine, Antoine J.-P. Tixier, Michalis Vazirgiannis.
- BARTpho (from VinAI Research) released with the paper BARTpho: Pre-trained Sequence-to-Sequence Models for Vietnamese by Nguyen Luong Tran, Duong Minh Le and Dat Quoc Nguyen.
- BEiT (from Microsoft) released with the paper BEiT: BERT Pre-Training of Image Transformers by Hangbo Bao, Li Dong, Furu Wei.
- BERT (from Google) released with the paper BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding by Jacob Devlin, Ming-Wei Chang, Kenton Lee and Kristina Toutanova.
- BERTweet (from VinAI Research) released with the paper BERTweet: A pre-trained language model for English Tweets by Dat Quoc Nguyen, Thanh Vu and Anh Tuan Nguyen.
- BERT For Sequence Generation (from Google) released with the paper Leveraging Pre-trained Checkpoints for Sequence Generation Tasks by Sascha Rothe, Shashi Narayan, Aliaksei Severyn.
- BigBird-RoBERTa (from Google Research) released with the paper Big Bird: Transformers for Longer Sequences by Manzil Zaheer, Guru Guruganesh, Avinava Dubey, Joshua Ainslie, Chris Alberti, Santiago Ontanon, Philip Pham, Anirudh Ravula, Qifan Wang, Li Yang, Amr Ahmed.
- BigBird-Pegasus (from Google Research) released with the paper Big Bird: Transformers for Longer Sequences by Manzil Zaheer, Guru Guruganesh, Avinava Dubey, Joshua Ainslie, Chris Alberti, Santiago Ontanon, Philip Pham, Anirudh Ravula, Qifan Wang, Li Yang, Amr Ahmed.
- Blenderbot (from Facebook) released with the paper Recipes for building an open-domain chatbot by Stephen Roller, Emily Dinan, Naman Goyal, Da Ju, Mary Williamson, Yinhan Liu, Jing Xu, Myle Ott, Kurt Shuster, Eric M. Smith, Y-Lan Boureau, Jason Weston.
- BlenderbotSmall (from Facebook) released with the paper Recipes for building an open-domain chatbot by Stephen Roller, Emily Dinan, Naman Goyal, Da Ju, Mary Williamson, Yinhan Liu, Jing Xu, Myle Ott, Kurt Shuster, Eric M. Smith, Y-Lan Boureau, Jason Weston.
- BORT (from Alexa) released with the paper Optimal Subarchitecture Extraction For BERT by Adrian de Wynter and Daniel J. Perry.
- ByT5 (from Google Research) released with the paper ByT5: Towards a token-free future with pre-trained byte-to-byte models by Linting Xue, Aditya Barua, Noah Constant, Rami Al-Rfou, Sharan Narang, Mihir Kale, Adam Roberts, Colin Raffel.
- CamemBERT (from Inria/Facebook/Sorbonne) released with the paper CamemBERT: a Tasty French Language Model by Louis Martin*, Benjamin Muller*, Pedro Javier Ortiz Suárez*, Yoann Dupont, Laurent Romary, Éric Villemonte de la Clergerie, Djamé Seddah and Benoît Sagot.
- CANINE (from Google Research) released with the paper CANINE: Pre-training an Efficient Tokenization-Free Encoder for Language Representation by Jonathan H. Clark, Dan Garrette, Iulia Turc, John Wieting.
- ConvNeXT (from Facebook AI) released with the paper A ConvNet for the 2020s by Zhuang Liu, Hanzi Mao, Chao-Yuan Wu, Christoph Feichtenhofer, Trevor Darrell, Saining Xie.
- CLIP (from OpenAI) released with the paper Learning Transferable Visual Models From Natural Language Supervision by Alec Radford, Jong Wook Kim, Chris Hallacy, Aditya Ramesh, Gabriel Goh, Sandhini Agarwal, Girish Sastry, Amanda Askell, Pamela Mishkin, Jack Clark, Gretchen Krueger, Ilya Sutskever.
- ConvBERT (from YituTech) released with the paper ConvBERT: Improving BERT with Span-based Dynamic Convolution by Zihang Jiang, Weihao Yu, Daquan Zhou, Yunpeng Chen, Jiashi Feng, Shuicheng Yan.
- CPM (from Tsinghua University) released with the paper CPM: A Large-scale Generative Chinese Pre-trained Language Model by Zhengyan Zhang, Xu Han, Hao Zhou, Pei Ke, Yuxian Gu, Deming Ye, Yujia Qin, Yusheng Su, Haozhe Ji, Jian Guan, Fanchao Qi, Xiaozhi Wang, Yanan Zheng, Guoyang Zeng, Huanqi Cao, Shengqi Chen, Daixuan Li, Zhenbo Sun, Zhiyuan Liu, Minlie Huang, Wentao Han, Jie Tang, Juanzi Li, Xiaoyan Zhu, Maosong Sun.
- CTRL (from Salesforce) released with the paper CTRL: A Conditional Transformer Language Model for Controllable Generation by Nitish Shirish Keskar*, Bryan McCann*, Lav R. Varshney, Caiming Xiong and Richard Socher.
- Data2Vec (from Facebook) released with the paper Data2Vec: A General Framework for Self-supervised Learning in Speech, Vision and Language by Alexei Baevski, Wei-Ning Hsu, Qiantong Xu, Arun Babu, Jiatao Gu, Michael Auli.
- DeBERTa (from Microsoft) released with the paper DeBERTa: Decoding-enhanced BERT with Disentangled Attention by Pengcheng He, Xiaodong Liu, Jianfeng Gao, Weizhu Chen.
- DeBERTa-v2 (from Microsoft) released with the paper DeBERTa: Decoding-enhanced BERT with Disentangled Attention by Pengcheng He, Xiaodong Liu, Jianfeng Gao, Weizhu Chen.
- Decision Transformer (from Berkeley/Facebook/Google) released with the paper Decision Transformer: Reinforcement Learning via Sequence Modeling by Lili Chen, Kevin Lu, Aravind Rajeswaran, Kimin Lee, Aditya Grover, Michael Laskin, Pieter Abbeel, Aravind Srinivas, Igor Mordatch.
- DiT (from Microsoft Research) released with the paper DiT: Self-supervised Pre-training for Document Image Transformer by Junlong Li, Yiheng Xu, Tengchao Lv, Lei Cui, Cha Zhang, Furu Wei.
- DeiT (from Facebook) released with the paper Training data-efficient image transformers & distillation through attention by Hugo Touvron, Matthieu Cord, Matthijs Douze, Francisco Massa, Alexandre Sablayrolles, Hervé Jégou.
- DETR (from Facebook) released with the paper End-to-End Object Detection with Transformers by Nicolas Carion, Francisco Massa, Gabriel Synnaeve, Nicolas Usunier, Alexander Kirillov, Sergey Zagoruyko.
- DialoGPT (from Microsoft Research) released with the paper DialoGPT: Large-Scale Generative Pre-training for Conversational Response Generation by Yizhe Zhang, Siqi Sun, Michel Galley, Yen-Chun Chen, Chris Brockett, Xiang Gao, Jianfeng Gao, Jingjing Liu, Bill Dolan.
- DistilBERT (from HuggingFace), released together with the paper DistilBERT, a distilled version of BERT: smaller, faster, cheaper and lighter by Victor Sanh, Lysandre Debut and Thomas Wolf. The same method has been applied to compress GPT2 into DistilGPT2, RoBERTa into DistilRoBERTa, Multilingual BERT into DistilmBERT and a German version of DistilBERT.
- DPR (from Facebook) released with the paper Dense Passage Retrieval for Open-Domain Question Answering by Vladimir Karpukhin, Barlas Oğuz, Sewon Min, Patrick Lewis, Ledell Wu, Sergey Edunov, Danqi Chen, and Wen-tau Yih.
- DPT (from Intel Labs) released with the paper Vision Transformers for Dense Prediction by René Ranftl, Alexey Bochkovskiy, Vladlen Koltun.
- EncoderDecoder (from Google Research) released with the paper Leveraging Pre-trained Checkpoints for Sequence Generation Tasks by Sascha Rothe, Shashi Narayan, Aliaksei Severyn.
- ELECTRA (from Google Research/Stanford University) released with the paper ELECTRA: Pre-training text encoders as discriminators rather than generators by Kevin Clark, Minh-Thang Luong, Quoc V. Le, Christopher D. Manning.
- FlauBERT (from CNRS) released with the paper FlauBERT: Unsupervised Language Model Pre-training for French by Hang Le, Loïc Vial, Jibril Frej, Vincent Segonne, Maximin Coavoux, Benjamin Lecouteux, Alexandre Allauzen, Benoît Crabbé, Laurent Besacier, Didier Schwab.
- FNet (from Google Research) released with the paper FNet: Mixing Tokens with Fourier Transforms by James Lee-Thorp, Joshua Ainslie, Ilya Eckstein, Santiago Ontanon.
- Funnel Transformer (from CMU/Google Brain) released with the paper Funnel-Transformer: Filtering out Sequential Redundancy for Efficient Language Processing by Zihang Dai, Guokun Lai, Yiming Yang, Quoc V. Le.
- GLPN (from KAIST) released with the paper Global-Local Path Networks for Monocular Depth Estimation with Vertical CutDepth by Doyeon Kim, Woonghyun Ga, Pyungwhan Ahn, Donggyu Joo, Sehwan Chun, Junmo Kim.
- GPT (from OpenAI) released with the paper Improving Language Understanding by Generative Pre-Training by Alec Radford, Karthik Narasimhan, Tim Salimans and Ilya Sutskever.
- GPT-2 (from OpenAI) released with the paper Language Models are Unsupervised Multitask Learners by Alec Radford*, Jeffrey Wu*, Rewon Child, David Luan, Dario Amodei** and Ilya Sutskever**.
- GPT-J (from EleutherAI) released in the repository kingoflolz/mesh-transformer-jax by Ben Wang and Aran Komatsuzaki.
- GPT Neo (from EleutherAI) released in the repository EleutherAI/gpt-neo by Sid Black, Stella Biderman, Leo Gao, Phil Wang and Connor Leahy.
- Hubert (from Facebook) released with the paper HuBERT: Self-Supervised Speech Representation Learning by Masked Prediction of Hidden Units by Wei-Ning Hsu, Benjamin Bolte, Yao-Hung Hubert Tsai, Kushal Lakhotia, Ruslan Salakhutdinov, Abdelrahman Mohamed.
- I-BERT (from Berkeley) released with the paper I-BERT: Integer-only BERT Quantization by Sehoon Kim, Amir Gholami, Zhewei Yao, Michael W. Mahoney, Kurt Keutzer.
- ImageGPT (from OpenAI) released with the paper Generative Pretraining from Pixels by Mark Chen, Alec Radford, Rewon Child, Jeffrey Wu, Heewoo Jun, David Luan, Ilya Sutskever.
- LayoutLM (from Microsoft Research Asia) released with the paper LayoutLM: Pre-training of Text and Layout for Document Image Understanding by Yiheng Xu, Minghao Li, Lei Cui, Shaohan Huang, Furu Wei, Ming Zhou.
- LayoutLMv2 (from Microsoft Research Asia) released with the paper LayoutLMv2: Multi-modal Pre-training for Visually-Rich Document Understanding by Yang Xu, Yiheng Xu, Tengchao Lv, Lei Cui, Furu Wei, Guoxin Wang, Yijuan Lu, Dinei Florencio, Cha Zhang, Wanxiang Che, Min Zhang, Lidong Zhou.
- LayoutXLM (from Microsoft Research Asia) released with the paper LayoutXLM: Multimodal Pre-training for Multilingual Visually-rich Document Understanding by Yiheng Xu, Tengchao Lv, Lei Cui, Guoxin Wang, Yijuan Lu, Dinei Florencio, Cha Zhang, Furu Wei.
- LED (from AllenAI) released with the paper Longformer: The Long-Document Transformer by Iz Beltagy, Matthew E. Peters, Arman Cohan.
- Longformer (from AllenAI) released with the paper Longformer: The Long-Document Transformer by Iz Beltagy, Matthew E. Peters, Arman Cohan.
- LUKE (from Studio Ousia) released with the paper LUKE: Deep Contextualized Entity Representations with Entity-aware Self-attention by Ikuya Yamada, Akari Asai, Hiroyuki Shindo, Hideaki Takeda, Yuji Matsumoto.
- mLUKE (from Studio Ousia) released with the paper mLUKE: The Power of Entity Representations in Multilingual Pretrained Language Models by Ryokan Ri, Ikuya Yamada, and Yoshimasa Tsuruoka.
- LXMERT (from UNC Chapel Hill) released with the paper LXMERT: Learning Cross-Modality Encoder Representations from Transformers for Open-Domain Question Answering by Hao Tan and Mohit Bansal.
- M2M100 (from Facebook) released with the paper Beyond English-Centric Multilingual Machine Translation by Angela Fan, Shruti Bhosale, Holger Schwenk, Zhiyi Ma, Ahmed El-Kishky, Siddharth Goyal, Mandeep Baines, Onur Celebi, Guillaume Wenzek, Vishrav Chaudhary, Naman Goyal, Tom Birch, Vitaliy Liptchinsky, Sergey Edunov, Edouard Grave, Michael Auli, Armand Joulin.
- MarianMT Machine translation models trained using OPUS data by Jörg Tiedemann. The Marian Framework is being developed by the Microsoft Translator Team.
- MaskFormer (from Meta and UIUC) released with the paper Per-Pixel Classification is Not All You Need for Semantic Segmentation by Bowen Cheng, Alexander G. Schwing, Alexander Kirillov.
- MBart (from Facebook) released with the paper Multilingual Denoising Pre-training for Neural Machine Translation by Yinhan Liu, Jiatao Gu, Naman Goyal, Xian Li, Sergey Edunov, Marjan Ghazvininejad, Mike Lewis, Luke Zettlemoyer.
- MBart-50 (from Facebook) released with the paper Multilingual Translation with Extensible Multilingual Pretraining and Finetuning by Yuqing Tang, Chau Tran, Xian Li, Peng-Jen Chen, Naman Goyal, Vishrav Chaudhary, Jiatao Gu, Angela Fan.
- Megatron-BERT (from NVIDIA) released with the paper Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism by Mohammad Shoeybi, Mostofa Patwary, Raul Puri, Patrick LeGresley, Jared Casper and Bryan Catanzaro.
- Megatron-GPT2 (from NVIDIA) released with the paper Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism by Mohammad Shoeybi, Mostofa Patwary, Raul Puri, Patrick LeGresley, Jared Casper and Bryan Catanzaro.
- MPNet (from Microsoft Research) released with the paper MPNet: Masked and Permuted Pre-training for Language Understanding by Kaitao Song, Xu Tan, Tao Qin, Jianfeng Lu, Tie-Yan Liu.
- MT5 (from Google AI) released with the paper mT5: A massively multilingual pre-trained text-to-text transformer by Linting Xue, Noah Constant, Adam Roberts, Mihir Kale, Rami Al-Rfou, Aditya Siddhant, Aditya Barua, Colin Raffel.
- Nyströmformer (from the University of Wisconsin – Madison) released with the paper Nyströmformer: A Nyström-Based Algorithm for Approximating Self-Attention by Yunyang Xiong, Zhanpeng Zeng, Rudrasis Chakraborty, Mingxing Tan, Glenn Fung, Yin Li, Vikas Singh.
- Pegasus (from Google) released with the paper PEGASUS: Pre-training with Extracted Gap-sentences for Abstractive Summarization by Jingqing Zhang, Yao Zhao, Mohammad Saleh and Peter J. Liu.
- Perceiver IO (from Deepmind) released with the paper Perceiver IO: A General Architecture for Structured Inputs & Outputs> by Andrew Jaegle, Sebastian Borgeaud, Jean-Baptiste Alayrac, Carl Doersch, Catalin Ionescu, David Ding, Skanda Koppula, Daniel Zoran, Andrew Brock, Evan Shelhamer, Olivier Hénaff, Matthew M. Botvinick, Andrew Zisserman, Oriol Vinyals, João Carreira.
- PhoBERT (from VinAI Research) released with the paper PhoBERT: Pre-trained language models for Vietnamese by Dat Quoc Nguyen and Anh Tuan Nguyen.
- PLBart (from UCLA NLP) released with the paper Unified Pre-training for Program Understanding and Generation by Wasi Uddin Ahmad, Saikat Chakraborty, Baishakhi Ray, Kai-Wei Chang.
- PoolFormer (from Sea AI Labs) released with the paper MetaFormer is Actually What You Need for Vision by Yu, Weihao and Luo, Mi and Zhou, Pan and Si, Chenyang and Zhou, Yichen and Wang, Xinchao and Feng, Jiashi and Yan, Shuicheng.
- ProphetNet (from Microsoft Research) released with the paper ProphetNet: Predicting Future N-gram for Sequence-to-Sequence Pre-training by Yu Yan, Weizhen Qi, Yeyun Gong, Dayiheng Liu, Nan Duan, Jiusheng Chen, Ruofei Zhang and Ming Zhou.
- QDQBert (from NVIDIA) released with the paper Integer Quantization for Deep Learning Inference: Principles and Empirical Evaluation by Hao Wu, Patrick Judd, Xiaojie Zhang, Mikhail Isaev and Paulius Micikevicius.
- REALM (from Google Research) released with the paper REALM: Retrieval-Augmented Language Model Pre-Training by Kelvin Guu, Kenton Lee, Zora Tung, Panupong Pasupat and Ming-Wei Chang.
- Reformer (from Google Research) released with the paper Reformer: The Efficient Transformer by Nikita Kitaev, Łukasz Kaiser, Anselm Levskaya.
- RemBERT (from Google Research) released with the paper Rethinking embedding coupling in pre-trained language models by Hyung Won Chung, Thibault Févry, Henry Tsai, M. Johnson, Sebastian Ruder.
- RegNet (from META Platforms) released with the paper Designing Network Design Space by Ilija Radosavovic, Raj Prateek Kosaraju, Ross Girshick, Kaiming He, Piotr Dollár.
- ResNet (from Microsoft Research) released with the paper Deep Residual Learning for Image Recognition by Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun.
- RoBERTa (from Facebook), released together with the paper RoBERTa: A Robustly Optimized BERT Pretraining Approach by Yinhan Liu, Myle Ott, Naman Goyal, Jingfei Du, Mandar Joshi, Danqi Chen, Omer Levy, Mike Lewis, Luke Zettlemoyer, Veselin Stoyanov.
- RoFormer (from ZhuiyiTechnology), released together with the paper RoFormer: Enhanced Transformer with Rotary Position Embedding by Jianlin Su and Yu Lu and Shengfeng Pan and Bo Wen and Yunfeng Liu.
- SegFormer (from NVIDIA) released with the paper SegFormer: Simple and Efficient Design for Semantic Segmentation with Transformers by Enze Xie, Wenhai Wang, Zhiding Yu, Anima Anandkumar, Jose M. Alvarez, Ping Luo.
- SEW (from ASAPP) released with the paper Performance-Efficiency Trade-offs in Unsupervised Pre-training for Speech Recognition by Felix Wu, Kwangyoun Kim, Jing Pan, Kyu Han, Kilian Q. Weinberger, Yoav Artzi.
- SEW-D (from ASAPP) released with the paper Performance-Efficiency Trade-offs in Unsupervised Pre-training for Speech Recognition by Felix Wu, Kwangyoun Kim, Jing Pan, Kyu Han, Kilian Q. Weinberger, Yoav Artzi.
- SpeechToTextTransformer (from Facebook), released together with the paper fairseq S2T: Fast Speech-to-Text Modeling with fairseq by Changhan Wang, Yun Tang, Xutai Ma, Anne Wu, Dmytro Okhonko, Juan Pino.
- SpeechToTextTransformer2 (from Facebook), released together with the paper Large-Scale Self- and Semi-Supervised Learning for Speech Translation by Changhan Wang, Anne Wu, Juan Pino, Alexei Baevski, Michael Auli, Alexis Conneau.
- Splinter (from Tel Aviv University), released together with the paper Few-Shot Question Answering by Pretraining Span Selection by Ori Ram, Yuval Kirstain, Jonathan Berant, Amir Globerson, Omer Levy.
- SqueezeBert (from Berkeley) released with the paper SqueezeBERT: What can computer vision teach NLP about efficient neural networks? by Forrest N. Iandola, Albert E. Shaw, Ravi Krishna, and Kurt W. Keutzer.
- Swin Transformer (from Microsoft) released with the paper Swin Transformer: Hierarchical Vision Transformer using Shifted Windows by Ze Liu, Yutong Lin, Yue Cao, Han Hu, Yixuan Wei, Zheng Zhang, Stephen Lin, Baining Guo.
- T5 (from Google AI) released with the paper Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer by Colin Raffel and Noam Shazeer and Adam Roberts and Katherine Lee and Sharan Narang and Michael Matena and Yanqi Zhou and Wei Li and Peter J. Liu.
- T5v1.1 (from Google AI) released in the repository google-research/text-to-text-transfer-transformer by Colin Raffel and Noam Shazeer and Adam Roberts and Katherine Lee and Sharan Narang and Michael Matena and Yanqi Zhou and Wei Li and Peter J. Liu.
- TAPAS (from Google AI) released with the paper TAPAS: Weakly Supervised Table Parsing via Pre-training by Jonathan Herzig, Paweł Krzysztof Nowak, Thomas Müller, Francesco Piccinno and Julian Martin Eisenschlos.
- Transformer-XL (from Google/CMU) released with the paper Transformer-XL: Attentive Language Models Beyond a Fixed-Length Context by Zihang Dai*, Zhilin Yang*, Yiming Yang, Jaime Carbonell, Quoc V. Le, Ruslan Salakhutdinov.
- TrOCR (from Microsoft), released together with the paper TrOCR: Transformer-based Optical Character Recognition with Pre-trained Models by Minghao Li, Tengchao Lv, Lei Cui, Yijuan Lu, Dinei Florencio, Cha Zhang, Zhoujun Li, Furu Wei.
- UniSpeech (from Microsoft Research) released with the paper UniSpeech: Unified Speech Representation Learning with Labeled and Unlabeled Data by Chengyi Wang, Yu Wu, Yao Qian, Kenichi Kumatani, Shujie Liu, Furu Wei, Michael Zeng, Xuedong Huang.
- UniSpeechSat (from Microsoft Research) released with the paper UNISPEECH-SAT: UNIVERSAL SPEECH REPRESENTATION LEARNING WITH SPEAKER AWARE PRE-TRAINING by Sanyuan Chen, Yu Wu, Chengyi Wang, Zhengyang Chen, Zhuo Chen, Shujie Liu, Jian Wu, Yao Qian, Furu Wei, Jinyu Li, Xiangzhan Yu.
- VAN (from Tsinghua University and Nankai University) released with the paper Visual Attention Network by Meng-Hao Guo, Cheng-Ze Lu, Zheng-Ning Liu, Ming-Ming Cheng, Shi-Min Hu.
- ViLT (from NAVER AI Lab/Kakao Enterprise/Kakao Brain) released with the paper ViLT: Vision-and-Language Transformer Without Convolution or Region Supervision by Wonjae Kim, Bokyung Son, Ildoo Kim.
- Vision Transformer (ViT) (from Google AI) released with the paper An Image is Worth 16×16 Words: Transformers for Image Recognition at Scale by Alexey Dosovitskiy, Lucas Beyer, Alexander Kolesnikov, Dirk Weissenborn, Xiaohua Zhai, Thomas Unterthiner, Mostafa Dehghani, Matthias Minderer, Georg Heigold, Sylvain Gelly, Jakob Uszkoreit, Neil Houlsby.
- ViTMAE (from Meta AI) released with the paper Masked Autoencoders Are Scalable Vision Learners by Kaiming He, Xinlei Chen, Saining Xie, Yanghao Li, Piotr Dollár, Ross Girshick.
- VisualBERT (from UCLA NLP) released with the paper VisualBERT: A Simple and Performant Baseline for Vision and Language by Liunian Harold Li, Mark Yatskar, Da Yin, Cho-Jui Hsieh, Kai-Wei Chang.
- WavLM (from Microsoft Research) released with the paper WavLM: Large-Scale Self-Supervised Pre-Training for Full Stack Speech Processing by Sanyuan Chen, Chengyi Wang, Zhengyang Chen, Yu Wu, Shujie Liu, Zhuo Chen, Jinyu Li, Naoyuki Kanda, Takuya Yoshioka, Xiong Xiao, Jian Wu, Long Zhou, Shuo Ren, Yanmin Qian, Yao Qian, Jian Wu, Michael Zeng, Furu Wei.
- Wav2Vec2 (from Facebook AI) released with the paper wav2vec 2.0: A Framework for Self-Supervised Learning of Speech Representations by Alexei Baevski, Henry Zhou, Abdelrahman Mohamed, Michael Auli.
- Wav2Vec2Phoneme (from Facebook AI) released with the paper Simple and Effective Zero-shot Cross-lingual Phoneme Recognition by Qiantong Xu, Alexei Baevski, Michael Auli.
- XGLM (From Facebook AI) released with the paper Few-shot Learning with Multilingual Language Models by Xi Victoria Lin, Todor Mihaylov, Mikel Artetxe, Tianlu Wang, Shuohui Chen, Daniel Simig, Myle Ott, Naman Goyal, Shruti Bhosale, Jingfei Du, Ramakanth Pasunuru, Sam Shleifer, Punit Singh Koura, Vishrav Chaudhary, Brian O’Horo, Jeff Wang, Luke Zettlemoyer, Zornitsa Kozareva, Mona Diab, Veselin Stoyanov, Xian Li.
- XLM (from Facebook) released together with the paper Cross-lingual Language Model Pretraining by Guillaume Lample and Alexis Conneau.
- XLM-ProphetNet (from Microsoft Research) released with the paper ProphetNet: Predicting Future N-gram for Sequence-to-Sequence Pre-training by Yu Yan, Weizhen Qi, Yeyun Gong, Dayiheng Liu, Nan Duan, Jiusheng Chen, Ruofei Zhang and Ming Zhou.
- XLM-RoBERTa (from Facebook AI), released together with the paper Unsupervised Cross-lingual Representation Learning at Scale by Alexis Conneau*, Kartikay Khandelwal*, Naman Goyal, Vishrav Chaudhary, Guillaume Wenzek, Francisco Guzmán, Edouard Grave, Myle Ott, Luke Zettlemoyer and Veselin Stoyanov.
- XLM-RoBERTa-XL (from Facebook AI), released together with the paper Larger-Scale Transformers for Multilingual Masked Language Modeling by Naman Goyal, Jingfei Du, Myle Ott, Giri Anantharaman, Alexis Conneau.
- XLNet (from Google/CMU) released with the paper XLNet: Generalized Autoregressive Pretraining for Language Understanding by Zhilin Yang*, Zihang Dai*, Yiming Yang, Jaime Carbonell, Ruslan Salakhutdinov, Quoc V. Le.
- XLSR-Wav2Vec2 (from Facebook AI) released with the paper Unsupervised Cross-Lingual Representation Learning For Speech Recognition by Alexis Conneau, Alexei Baevski, Ronan Collobert, Abdelrahman Mohamed, Michael Auli.
- XLS-R (from Facebook AI) released with the paper XLS-R: Self-supervised Cross-lingual Speech Representation Learning at Scale by Arun Babu, Changhan Wang, Andros Tjandra, Kushal Lakhotia, Qiantong Xu, Naman Goyal, Kritika Singh, Patrick von Platen, Yatharth Saraf, Juan Pino, Alexei Baevski, Alexis Conneau, Michael Auli.
- YOSO (from the University of Wisconsin – Madison) released with the paper You Only Sample (Almost) Once: Linear Cost Self-Attention Via Bernoulli Sampling by Zhanpeng Zeng, Yunyang Xiong, Sathya N. Ravi, Shailesh Acharya, Glenn Fung, Vikas Singh.
- 新しいモデルを寄贈することを望みますか?新しいモデルを追加するプロセスに導く 詳細なガイドとテンプレート を追加しました。レポジトリの templates フォルダでそれらを見つけることができます。貴方の PR を始める前にフィードバックを集めるために contributing ガイドライン を確認してそしてメンテナーにコンタクトするか issue をオープンすることを確実にしてください。
各モデルが Flax, PyTorch or TensorFlow の実装を持つか、あるいは Tokenizer により支援された関連する tokenizer を持つかを確認するためには、このテーブル を参照してください。
これらの実装は幾つかのデータセット上でテストされ (examples スクリプト参照) そして元の実装のパフォーマンスに一致するはずです。ドキュメントの Examples セクションでパフォーマンス上の更なる詳細を見つけられます。
更に学習する
セクション | 説明 |
ドキュメント | Full API ドキュメントとチュートリアル |
タスク概要 | ![]() |
前処理チュートリアル | モデルのためのデータを準備する Tokenizer クラスを使用する |
訓練と再調整 | PyTorch/TensorFlow 訓練ループと Trainer API で ![]() |
クイックツアー: 再調整/使用方法スクリプト | 広範囲なタスク上でモデルを再調整するためのサンプル・スクリプト |
モデル共有とアップロード | 貴方の再調整済みモデルをアップロードしてコミュニティで共有する |
マイグレーション | pytorch-transformers or pytorch-pretrained-bert から ![]() |
Citation
(訳注: 原文 を参照してください。)
以上
HuggingFace Transformers 4.6 : ノートブック : パイプラインの利用
HuggingFace Transformers 4.6 : ノートブック : パイプラインの利用 (翻訳/解説)
翻訳 : (株)クラスキャット セールスインフォメーション
作成日時 : 06/14/2021 (4.6.1)
* 本ページは、HuggingFace Transformers の以下のドキュメントを翻訳した上で適宜、補足説明したものです:
- Notebooks : How to use Pipelines
* サンプルコードの動作確認はしておりますが、必要な場合には適宜、追加改変しています。
* ご自由にリンクを張って頂いてかまいませんが、sales-info@classcat.com までご一報いただけると嬉しいです。
スケジュールは弊社 公式 Web サイト でご確認頂けます。
- お住まいの地域に関係なく Web ブラウザからご参加頂けます。事前登録 が必要ですのでご注意ください。
- ウェビナー運用には弊社製品「ClassCat® Webinar」を利用しています。
人工知能研究開発支援 | 人工知能研修サービス | テレワーク & オンライン授業を支援 |
PoC(概念実証)を失敗させないための支援 (本支援はセミナーに参加しアンケートに回答した方を対象としています。) |
◆ お問合せ : 本件に関するお問い合わせ先は下記までお願いいたします。
株式会社クラスキャット セールス・マーケティング本部 セールス・インフォメーション |
E-Mail:sales-info@classcat.com ; WebSite: https://www.classcat.com/ ; Facebook |
ノートブック : パイプラインの利用
transformers v2.3.0 で新たに導入された、パイプライン は以下を含む様々な下流タスクに渡る推論を行なうための高位の、使いやすい、API を提供します :
- センテンス分類 (センチメント分析) : センテンス全体がポジティブかネガティブかを示します、つまり二値分類タスクかロジスティック回帰タスクです。
- トークン分類 (固有表現認識、品詞タギング) : 入力の各サブエンティティ (トークン) について、ラベルを割当てます、つまり分類タスクです。
- 質問応答 : タプル (質問, コンテキスト) が提供されたとき、モデルは質問に答えるコンテンツのテキストの範囲を見つける必要があります。
- マスク Filling : 提供されたコンテキストに関してマスクされた入力を埋める可能性のある単語を提示します。
- 要約 : 入力記事をより短い記事に要約します。
- 翻訳 : 入力をある言語から別の言語に翻訳します。
- 特徴抽出 : 入力をデータから学習された、高位の多次元空間にマップします。
パイプラインは総ての NLP プロセスのプロセス全体をカプセル化します :
- トークン化 : 初期入力を … プロパティを持つ複数のサブエンティティに分割します (i.e. トークン)。
- 推論 : 総てのトークンをより意味のある表現にマップします。
- デコード : 基礎となるタスクのために最終的な出力を生成 and/or 抽出するために上の表現を使用します。
API 全体が以下の構造を持つ pipeline() メソッドを通してエンドユーザに公開されます :
from transformers import pipeline
# Using default model and tokenizer for the task
pipeline("<task-name>")
# Using a user-specified model
pipeline("<task-name>", model="<model_name>")
# Using custom model/tokenizer as str
pipeline('<task-name>', model='<model name>', tokenizer='<tokenizer_name>')
!pip install -q transformers
from __future__ import print_function
import ipywidgets as widgets
from transformers import pipeline
1. センテンス分類 – センチメント分析
nlp_sentence_classif = pipeline('sentiment-analysis')
nlp_sentence_classif('Such a nice weather outside !')
[{'label': 'POSITIVE', 'score': 0.9997656}]
2. トークン分類 – 固有表現認識
nlp_token_class = pipeline('ner')
nlp_token_class('Hugging Face is a French company based in New-York.')
[{'entity': 'I-ORG', 'score': 0.9970937967300415, 'word': 'Hu'}, {'entity': 'I-ORG', 'score': 0.9345749020576477, 'word': '##gging'}, {'entity': 'I-ORG', 'score': 0.9787060022354126, 'word': 'Face'}, {'entity': 'I-MISC', 'score': 0.9981995820999146, 'word': 'French'}, {'entity': 'I-LOC', 'score': 0.9983047246932983, 'word': 'New'}, {'entity': 'I-LOC', 'score': 0.8913459181785583, 'word': '-'}, {'entity': 'I-LOC', 'score': 0.9979523420333862, 'word': 'York'}]
3. 質問応答
nlp_qa = pipeline('question-answering')
nlp_qa(context='Hugging Face is a French company based in New-York.', question='Where is based Hugging Face ?')
{'answer': 'New-York.', 'end': 50, 'score': 0.9632969241603995, 'start': 42}
4. テキスト生成 – マスク Filling
nlp_fill = pipeline('fill-mask')
nlp_fill('Hugging Face is a French company based in ' + nlp_fill.tokenizer.mask_token)
[{'score': 0.23106741905212402, 'sequence': '<s> Hugging Face is a French company based in Paris', 'token': 2201}, {'score': 0.08198167383670807, 'sequence': '<s> Hugging Face is a French company based in Lyon', 'token': 12790}, {'score': 0.04769487306475639, 'sequence': '<s> Hugging Face is a French company based in Geneva', 'token': 11559}, {'score': 0.04762246832251549, 'sequence': '<s> Hugging Face is a French company based in Brussels', 'token': 6497}, {'score': 0.041305847465991974, 'sequence': '<s> Hugging Face is a French company based in France', 'token': 1470}]
5. 要約
要約は現在 Bart と T5 でサポートされます。
TEXT_TO_SUMMARIZE = """
New York (CNN)When Liana Barrientos was 23 years old, she got married in Westchester County, New York.
A year later, she got married again in Westchester County, but to a different man and without divorcing her first husband.
Only 18 days after that marriage, she got hitched yet again. Then, Barrientos declared "I do" five more times, sometimes only within two weeks of each other.
In 2010, she married once more, this time in the Bronx. In an application for a marriage license, she stated it was her "first and only" marriage.
Barrientos, now 39, is facing two criminal counts of "offering a false instrument for filing in the first degree," referring to her false statements on the
2010 marriage license application, according to court documents.
Prosecutors said the marriages were part of an immigration scam.
On Friday, she pleaded not guilty at State Supreme Court in the Bronx, according to her attorney, Christopher Wright, who declined to comment further.
After leaving court, Barrientos was arrested and charged with theft of service and criminal trespass for allegedly sneaking into the New York subway through an emergency exit, said Detective
Annette Markowski, a police spokeswoman. In total, Barrientos has been married 10 times, with nine of her marriages occurring between 1999 and 2002.
All occurred either in Westchester County, Long Island, New Jersey or the Bronx. She is believed to still be married to four men, and at one time, she was married to eight men at once, prosecutors say.
Prosecutors said the immigration scam involved some of her husbands, who filed for permanent residence status shortly after the marriages.
Any divorces happened only after such filings were approved. It was unclear whether any of the men will be prosecuted.
The case was referred to the Bronx District Attorney\'s Office by Immigration and Customs Enforcement and the Department of Homeland Security\'s
Investigation Division. Seven of the men are from so-called "red-flagged" countries, including Egypt, Turkey, Georgia, Pakistan and Mali.
Her eighth husband, Rashid Rajput, was deported in 2006 to his native Pakistan after an investigation by the Joint Terrorism Task Force.
If convicted, Barrientos faces up to four years in prison. Her next court appearance is scheduled for May 18.
"""
summarizer = pipeline('summarization')
summarizer(TEXT_TO_SUMMARIZE)
{'summary_text': 'Liana Barrientos has been married 10 times, sometimes within two weeks of each other. Prosecutors say the marriages were part of an immigration scam. She is believed to still be married to four men, and at one time, she was married to eight men at once. Her eighth husband was deported in 2006 to his native Pakistan.'}]
6. 翻訳
翻訳は言語マッピング – 英語-to-フランス語 (translation_en_to_fr)、英語-to-ドイツ語 (translation_en_to_de) そして英語-to-ルーマニア語 (translation_en_to_ro) のために T5 により現在サポートされています。
# English to French
translator = pipeline('translation_en_to_fr')
translator("HuggingFace is a French company that is based in New York City. HuggingFace's mission is to solve NLP one commit at a time")
[{'translation_text': 'HuggingFace est une entreprise française basée à New York et dont la mission est de résoudre les problèmes de NLP, un engagement à la fois.'}]
# English to German
translator = pipeline('translation_en_to_de')
translator("The history of natural language processing (NLP) generally started in the 1950s, although work can be found from earlier periods.")
[{'translation_text': 'Die Geschichte der natürlichen Sprachenverarbeitung (NLP) begann im Allgemeinen in den 1950er Jahren, obwohl die Arbeit aus früheren Zeiten zu finden ist.'}]
7. テキスト生成
テキスト生成は現在 GPT-2, OpenAi-GPT, TransfoXL, XLNet, CTRL と Reformer によりサポートされています。
text_generator = pipeline("text-generation")
text_generator("Today is a beautiful day and I will")
[{'generated_text': 'Today is a beautiful day and I will celebrate my birthday!"\n\nThe mother told CNN the two had planned their meal together. After dinner, she added that she and I walked down the street and stopped at a diner near her home. "He'}]
8. 射影 – 特徴抽出
import numpy as np
nlp_features = pipeline('feature-extraction')
output = nlp_features('Hugging Face is a French company based in Paris')
np.array(output).shape # (Samples, Tokens, Vector Size)
(1, 12, 768)
◆ Alright ! 今では transformers のパイプラインを通して何が可能かの良いイメージを持ち、そして今後のリリースでは更に多くのものが装備されます。
その間、貴方自身の入力で様々なパイプラインを試すことができます。
task = widgets.Dropdown(
options=['sentiment-analysis', 'ner', 'fill_mask'],
value='ner',
description='Task:',
disabled=False
)
input = widgets.Text(
value='',
placeholder='Enter something',
description='Your input:',
disabled=False
)
def forward(_):
if len(input.value) > 0:
if task.value == 'ner':
output = nlp_token_class(input.value)
elif task.value == 'sentiment-analysis':
output = nlp_sentence_classif(input.value)
else:
if input.value.find('') == -1:
output = nlp_fill(input.value + ' ')
else:
output = nlp_fill(input.value)
print(output)
input.on_submit(forward)
display(task, input)
Dropdown(description='Task:', index=1, options=('sentiment-analysis', 'ner', 'fill_mask'), value='ner') Text(value='', description='Your input:', placeholder='Enter something') [{'word': 'Peter', 'score': 0.9935821294784546, 'entity': 'I-PER'}, {'word': 'Pan', 'score': 0.9901397228240967, 'entity': 'I-PER'}, {'word': 'Marseille', 'score': 0.9984904527664185, 'entity': 'I-LOC'}, {'word': 'France', 'score': 0.9998687505722046, 'entity': 'I-LOC'}]
context = widgets.Textarea(
value='Einstein is famous for the general theory of relativity',
placeholder='Enter something',
description='Context:',
disabled=False
)
query = widgets.Text(
value='Why is Einstein famous for ?',
placeholder='Enter something',
description='Question:',
disabled=False
)
def forward(_):
if len(context.value) > 0 and len(query.value) > 0:
output = nlp_qa(question=query.value, context=context.value)
print(output)
query.on_submit(forward)
display(context, query)
Textarea(value='Einstein is famous for the general theory of relativity', description='Context:', placeholder=… Text(value='Why is Einstein famous for ?', description='Question:', placeholder='Enter something') {'score': 0.40340594113729367, 'start': 27, 'end': 54, 'answer': 'general theory of relativity'}
以上
HuggingFace Transformers 4.6 : ノートブック : Getting Started Transformers
HuggingFace Transformers 4.6 : ノートブック : Getting Started Transformers (翻訳/解説)
翻訳 : (株)クラスキャット セールスインフォメーション
作成日時 : 06/12/2021 (4.6.1)
* 本ページは、HuggingFace Transformers の以下のドキュメントを翻訳した上で適宜、補足説明したものです:
- Notebooks : Getting Started Transformers
* サンプルコードの動作確認はしておりますが、必要な場合には適宜、追加改変しています。
* ご自由にリンクを張って頂いてかまいませんが、sales-info@classcat.com までご一報いただけると嬉しいです。
スケジュールは弊社 公式 Web サイト でご確認頂けます。
- お住まいの地域に関係なく Web ブラウザからご参加頂けます。事前登録 が必要ですのでご注意ください。
- ウェビナー運用には弊社製品「ClassCat® Webinar」を利用しています。
人工知能研究開発支援 | 人工知能研修サービス | テレワーク & オンライン授業を支援 |
PoC(概念実証)を失敗させないための支援 (本支援はセミナーに参加しアンケートに回答した方を対象としています。) |
◆ お問合せ : 本件に関するお問い合わせ先は下記までお願いいたします。
株式会社クラスキャット セールス・マーケティング本部 セールス・インフォメーション |
E-Mail:sales-info@classcat.com ; WebSite: https://www.classcat.com/ ; Facebook |
ノートブック : Getting Started Transformers
イントロダクション
transformers ライブラリは、Bert (Devlin & al., 2018), Roberta (Liu & al., 2019), GPT2 (Radford & al., 2019), XLNet (Yang & al., 2019) 等のような Transformer アーキテクチャ (Vaswani & al., 2017) に基づくモデルを訓練し、利用して共有するためのオープンソース、コミュニティ・ベースのレポジトリです。
これらのモデルとともに、ライブラリは 固有表現認識 (NER)、センチメント分析、言語モデリング、質問応答 等のような多種多様な下流タスクのためにそれらの各々の複数のバリエーションを含みます。
Transformer 以前
2017 に戻ると、ニューラルネットワークを使用する人々の殆どは自然言語処理で作業するとき リカレント・ニューラルネットワーク (RNN) を通した入力のシーケンシャルな処理に依存していました。
RNN は入力シークエンスに渡るシーケンシャルな依存性を含む様々なタスク上で上手く遂行しました。けれども、シーケンシャルな依存プロセスは非常に長い範囲の依存性をモデル化する問題を持っていて、悪い並列化機能ゆえに現在活用している種類のハードウェアのためには上手く適合しませんでした。
双方向 RNN ( Schuster & Paliwal., 1997, Graves & al., 2005 ) のような、幾つかの拡張が学術的なコミュニティから提供されました、これは 2 つのシーケンシャルなプロセスの結合として見ることができて、シークエンス入力に対して一つは順方向に進み、他方は逆方向に進みます。
そしてまた、Attention メカニズムは、シークエンスの各要素に学習された、重み付けされた重要性を与えることにより “raw” RNN を越える良い改良を導入し、モデルが重要な要素にフォーカスすることを可能にしました。
そして Transformer の登場
Transformer の時代は元々は翻訳タスク上で リカレント・ニューラルネットワーク (RNN) を越える優位性を実演した ( Vaswani & al., 2017 ) のワークから始まりましたが、それは迅速に当時 RNN が最先端であった殆ど総てのタスクに拡張されました。
RNN のカウンターパートを越える Transformer の一つの優位点は非シーケンシャルな attention モデルでした。忘れないでください、RNN は入力シークエンスの各要素に渡り一つ一つ反復して各跳躍 (= hop) 間で「更新可能な状態」を持ち運ばなければなりませんでした。Transformer では、モデルはシークエンスの総ての位置を同時に、一つの演算で見ることができます。
Transformer アーキテクチャの詳細については、The Annotated Transformer が論文の総ての詳細に沿って貴方を導きます。
Getting started with transformers
このノートブックの残りについては、BERT (Devlin & al., 2018) アーキテクチャを使用します、それは最も単純でインターネット上にそれについて多くのコンテンツがあるので、貴方が望めばこのアーキテクチャについて更に掘り下げることは容易です。
transformers ライブラリは巨大でコストのかかる計算インフラを必要とすることなく、大規模な、事前訓練された言語モデルから恩恵を受けることを可能にします。殆どの最先端モデルがその author から直接提供され、透過的で交換可能な方法で PyTorch と TensorFlow のライブラリで利用可能です。
このノートブックを Colab で実行する場合、transformers ライブラリをインストールする必要があります。このコマンドでそれを行なうことができます :
# !pip install transformers
import torch
from transformers import AutoModel, AutoTokenizer, BertTokenizer
torch.set_grad_enabled(False)
<torch.autograd.grad_mode.set_grad_enabled at 0x7ff0cc2a2c50>
# Store the model we want to use
MODEL_NAME = "bert-base-cased"
# We need to create the model and tokenizer
model = AutoModel.from_pretrained(MODEL_NAME)
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
上のコードの 2 行だけで、BERT 事前訓練モデルを利用する準備ができました。トークナイザーは raw テキスト入力を (モデルが操作できる方法でテキスト入力を表す) 整数のシークエンスにマップすることを可能にします。PyTorch モデルを使用しますので、トークナイザーに PyTorch tensor を返すように求めます。
tokens_pt = tokenizer("This is an input example", return_tensors="pt")
for key, value in tokens_pt.items():
print("{}:\n\t{}".format(key, value))
input_ids: tensor([[ 101, 1188, 1110, 1126, 7758, 1859, 102]]) token_type_ids: tensor([[0, 0, 0, 0, 0, 0, 0]]) attention_mask: tensor([[1, 1, 1, 1, 1, 1, 1]])
トークナイザーは入力をモデルにより想定される総ての入力に自動的に変換しました。それは幾つかの追加の tensor を ID の上に生成しました。
- token_type_ids : この tensor は総てのトークンを対応するセグメントにマップします (下参照)。
- attention_mask: この tensor は異なる長さを持つシークエンスのバッチでパッドされた値を「マスク」するために使用されます (下参照)。
それらのキーの各々についてのより多くの情報のためには 用語集 を確認できます。
これをモデルに単に直接供給できます。
outputs = model(**tokens_pt)
last_hidden_state = outputs.last_hidden_state
pooler_output = outputs.pooler_output
print("Token wise output: {}, Pooled output: {}".format(last_hidden_state.shape, pooler_output.shape))
Token wise output: torch.Size([1, 7, 768]), Pooled output: torch.Size([1, 768])
ご覧のように、BERT は 2 つの tensor を出力します :
- 一つは入力の総てのトークンのための生成された表現です (1, NB_TOKENS, REPRESENTATION_SIZE)。
- 一つは入力全体のための集約表現です (1, REPRESENTATION_SIZE)。
タスクがシークエンス表現を保持することを必要としトークンレベルで操作することを望む場合、最初のトークンベースの表現が活用できます。これは固有表現認識と質問応答のために特に有用です。
シークエンスのコンテキスト全体を抽出する必要があり極め細かいトークンレベルを必要としない場合、2 番目の集約表現が特別に有用です。これはシークエンスのセンチメント分析や情報検索に当てはまります。
# Single segment input
single_seg_input = tokenizer("This is a sample input")
# Multiple segment input
multi_seg_input = tokenizer("This is segment A", "This is segment B")
print("Single segment token (str): {}".format(tokenizer.convert_ids_to_tokens(single_seg_input['input_ids'])))
print("Single segment token (int): {}".format(single_seg_input['input_ids']))
print("Single segment type : {}".format(single_seg_input['token_type_ids']))
# Segments are concatened in the input to the model, with
print()
print("Multi segment token (str): {}".format(tokenizer.convert_ids_to_tokens(multi_seg_input['input_ids'])))
print("Multi segment token (int): {}".format(multi_seg_input['input_ids']))
print("Multi segment type : {}".format(multi_seg_input['token_type_ids']))
Single segment token (str): ['[CLS]', 'This', 'is', 'a', 'sample', 'input', '[SEP]'] Single segment token (int): [101, 1188, 1110, 170, 6876, 7758, 102] Single segment type : [0, 0, 0, 0, 0, 0, 0] Multi segment token (str): ['[CLS]', 'This', 'is', 'segment', 'A', '[SEP]', 'This', 'is', 'segment', 'B', '[SEP]'] Multi segment token (int): [101, 1188, 1110, 6441, 138, 102, 1188, 1110, 6441, 139, 102] Multi segment type : [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1]
# Padding highlight
tokens = tokenizer(
["This is a sample", "This is another longer sample text"],
padding=True # First sentence will have some PADDED tokens to match second sequence length
)
for i in range(2):
print("Tokens (int) : {}".format(tokens['input_ids'][i]))
print("Tokens (str) : {}".format([tokenizer.convert_ids_to_tokens(s) for s in tokens['input_ids'][i]]))
print("Tokens (attn_mask): {}".format(tokens['attention_mask'][i]))
print()
Tokens (int) : [101, 1188, 1110, 170, 6876, 102, 0, 0] Tokens (str) : ['[CLS]', 'This', 'is', 'a', 'sample', '[SEP]', '[PAD]', '[PAD]'] Tokens (attn_mask): [1, 1, 1, 1, 1, 1, 0, 0] Tokens (int) : [101, 1188, 1110, 1330, 2039, 6876, 3087, 102] Tokens (str) : ['[CLS]', 'This', 'is', 'another', 'longer', 'sample', 'text', '[SEP]'] Tokens (attn_mask): [1, 1, 1, 1, 1, 1, 1, 1]
フレームワーク相互運用性
transformers の最もパワフルな特徴の一つはユーザの痛みなく PyTorch から TensorFlow にシームレスに移動できる能力です。
PyTorch モデル内に TensorFlow 事前訓練重みをロードする (そしてその反対の) ための幾つかの便利なメソッドを提供しています。
from transformers import TFBertModel, BertModel
# Let's load a BERT model for TensorFlow and PyTorch
model_tf = TFBertModel.from_pretrained('bert-base-cased')
model_pt = BertModel.from_pretrained('bert-base-cased')
# transformers generates a ready to use dictionary with all the required parameters for the specific framework.
input_tf = tokenizer("This is a sample input", return_tensors="tf")
input_pt = tokenizer("This is a sample input", return_tensors="pt")
# Let's compare the outputs
output_tf, output_pt = model_tf(input_tf), model_pt(**input_pt)
# Models outputs 2 values (The value for each tokens, the pooled representation of the input sentence)
# Here we compare the output differences between PyTorch and TensorFlow.
for name in ["last_hidden_state", "pooler_output"]:
print("{} differences: {:.5}".format(name, (output_tf[name].numpy() - output_pt[name].numpy()).sum()))
last_hidden_state differences: 1.2933e-05 pooler_output differences: 2.9691e-06
より軽量であることを望みますか?より高速であることを?distillation について話しましょう!
これらの Transformer ベースのモデルを使用するときの主要な懸念の一つはそれらが必要とする計算パワーです。このノートブック全体に渡り BERT モデルを使用しています、それは一般的なマシン上で実行できるからですが、モデルの総てのために当てはまりません。
例えば、Google は数ヶ月前に Transformer ベースのエンコーダ/デコーダ・アーキテクチャ T5 をリリースしました、そして 110 億に過ぎないパラメータを持つ transformers で利用可能です。マイクロソフトはまた最近 170 億パラメータを使用して Turing-NLG によりゲームに参加しました。この種類のモデルは重みをストアするために数十 GB を必要としそして一般的な人のためには実行不可能とする、そのようなモデルを実行するために非常に膨大な計算インフラを必要とします。
Transformer ベースの NLP を総ての人にアクセス可能にする目標により、@huggingface は Distillation と呼ばれる訓練プロセスを活用するモデルを開発しました、これはパフォーマンスを殆ど落とすことなくそのようなモデルを実行するために必要なリソースを劇的に削減することを可能にします。
Distillation プロセス全体を調べることはこのノートブックの範囲外ですが、主題についてより多くの情報を望む場合には、DistilBERT 論文の著者である、私の同僚 Victor SANH により書かれたこの Medium の記事 を参照することができます、論文 ( Sanh & al., 2019 ) を直接見ることもまた望むかもしれません。
もちろん、transformers では幾つかのモデルを蒸留してライブラリで直接利用可能にしました!
from transformers import DistilBertModel
bert_distil = DistilBertModel.from_pretrained('distilbert-base-cased')
input_pt = tokenizer(
'This is a sample input to demonstrate performance of distiled models especially inference time',
return_tensors="pt"
)
%time _ = bert_distil(input_pt['input_ids'])
%time _ = model_pt(input_pt['input_ids'])
HBox(children=(FloatProgress(value=0.0, description='Downloading', max=411.0, style=ProgressStyle(description_… HBox(children=(FloatProgress(value=0.0, description='Downloading', max=263273408.0, style=ProgressStyle(descri… CPU times: user 64.4 ms, sys: 0 ns, total: 64.4 ms Wall time: 72.9 ms CPU times: user 130 ms, sys: 124 µs, total: 130 ms Wall time: 131 ms
コミュニティ提供モデル
最後になりましたが、このノートブックの前の方で Hugging Face transformers を NLP コミュニティが事前訓練モデルを交換するためのレポジトリとして紹介しました。この機能とそれがエンドユーザに供給する総ての可能性を強調することを望みました。
コミュニティの事前訓練モデルを活用するためには、組織名とモデルの名前を from_pretrained に単に提供するだけでそしてそれは総てのマジックを貴方のために行ないます!
現在コミュニティにより提供された 50 モデル以上を持ちそして更に多くが毎日追加されています、試すことを躊躇しないでください!
# Let's load German BERT from the Bavarian State Library
de_bert = BertModel.from_pretrained("dbmdz/bert-base-german-cased")
de_tokenizer = BertTokenizer.from_pretrained("dbmdz/bert-base-german-cased")
de_input = de_tokenizer(
"Hugging Face ist eine französische Firma mit Sitz in New-York.",
return_tensors="pt"
)
print("Tokens (int) : {}".format(de_input['input_ids'].tolist()[0]))
print("Tokens (str) : {}".format([de_tokenizer.convert_ids_to_tokens(s) for s in de_input['input_ids'].tolist()[0]]))
print("Tokens (attn_mask): {}".format(de_input['attention_mask'].tolist()[0]))
print()
outputs_de = de_bert(**de_input)
last_hidden_state_de = outputs_de.last_hidden_state
pooler_output_de = outputs_de.pooler_output
print("Token wise output: {}, Pooled output: {}".format(last_hidden_state_de.shape, pooler_output_de.shape))
Tokens (int) : [102, 12272, 9355, 5746, 30881, 215, 261, 5945, 4118, 212, 2414, 153, 1942, 232, 3532, 566, 103] Tokens (str) : ['[CLS]', 'Hug', '##ging', 'Fac', '##e', 'ist', 'eine', 'französische', 'Firma', 'mit', 'Sitz', 'in', 'New', '-', 'York', '.', '[SEP]'] Tokens (attn_mask): [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] Token wise output: torch.Size([1, 17, 768]), Pooled output: torch.Size([1, 768])
以上
HuggingFace Transformers 4.6 : ノートブック : Getting Started トークナイザー
HuggingFace Transformers 4.6 : ノートブック : Getting Started トークナイザー (翻訳/解説)
翻訳 : (株)クラスキャット セールスインフォメーション
作成日時 : 06/11/2021 (4.6.1)
* 本ページは、HuggingFace Transformers の以下のドキュメントを翻訳した上で適宜、補足説明したものです:
Transformers Notebooks : Getting Started Tokenizers
* サンプルコードの動作確認はしておりますが、必要な場合には適宜、追加改変しています。
* ご自由にリンクを張って頂いてかまいませんが、sales-info@classcat.com までご一報いただけると嬉しいです。
スケジュールは弊社 公式 Web サイト でご確認頂けます。
- お住まいの地域に関係なく Web ブラウザからご参加頂けます。事前登録 が必要ですのでご注意ください。
- ウェビナー運用には弊社製品「ClassCat® Webinar」を利用しています。
人工知能研究開発支援 | 人工知能研修サービス | テレワーク & オンライン授業を支援 |
PoC(概念実証)を失敗させないための支援 (本支援はセミナーに参加しアンケートに回答した方を対象としています。) |
◆ お問合せ : 本件に関するお問い合わせ先は下記までお願いいたします。
株式会社クラスキャット セールス・マーケティング本部 セールス・インフォメーション |
E-Mail:sales-info@classcat.com ; WebSite: https://www.classcat.com/ ; Facebook |
ノートブック : Getting Started トークナイザー
イントロダクション
機械学習や深層学習の自然言語処理モデルに深く潜る前に、総ての実践者は raw 入力文字列を訓練可能なモデルにより理解可能な表現にマップする方法を見つけるべきです。
一つの非常に単純なアプローチは総ての空白に渡り入力を分割して各単語に識別子を割り当てることです。このアプローチは Python の下のコードに類似して見えます。
s = "very long corpus..."
words = s.split(" ") # Split over space
vocabulary = dict(enumerate(set(words))) # Map storing the word to it's corresponding id
このアプローチは貴方の語彙が少ないままなら上手く動作するかもしれません、というのはそれは元の入力に存在する総ての単語 (or トークン) をストアするからです。更に、”cat” と “cats” のような単語のバリエーションはそれらの意味が非常に近い場合でさえも同じ識別子を共有しないでしょう。
サブトークンのトークン化
上で説明された問題を乗り越えるために、最近のワークは「サブトークン」トークン化を活用した、トークン化上で成されてきました。サブトークン は前の分割ストラテジーを単語を (データから学習された) 文法的にロジカルなサブコンポーネントに更に分解するように拡張します。
単語 cat と cats の前の例を取れば、単語 cats のサブトークン化は [cat, ##s] になります。ここで prefix “##” は初期入力のサブトークンを示します。そのような訓練アルゴリズムは英語コーパスに渡り “##ing”, “##ed” のようなサブトークンを抽出するかもしれません。
貴方が考えるかもしれないように、「ピース」全体の組合せを活用したこの種類のサブトークン構築は (機械学習モデルを訓練するために持ち運ばなければならない) 語彙のサイズを削減します。一方で、一つのトークンが複数のサブトークンに分解されるかもしれないので、モデルの入力が増加して入力シークエンスの長さにわたる非線形の複雑さを伴うモデルについて問題になるかもしれません。
総てのトークン化アルゴリズムの中で、Transformers ベースの SoTA モデルで利用された幾つかのサブトークン・アルゴリズムにハイライトを当てることができます :
- Byte Pair Encoding (BPE) – Neural Machine Translation of Rare Words with Subword Units (Sennrich et al., 2015)
サブワード・ユニットによる稀な単語のニューラル機械翻訳
- Word Piece – Japanese and Korean voice search (Schuster, M., and Nakajima, K., 2015)
Word Piece – 日本語と韓国語の音声検索
- Unigram Language Model – Subword Regularization: Improving Neural Network Translation Models with Multiple Subword Candidates (Kudo, T., 2018)
Unigram 言語モデル – サブワード正則化 : 複数のサブワード候補によるニューラルネットワーク翻訳モデルの改良
- Sentence Piece – A simple and language independent subword tokenizer and detokenizer for Neural Text Processing (Taku Kudo and John Richardson, 2018)
Sentence Piece – ニューラルテキスト処理のための単純で言語独立なサブワード・トークナイザーと detokenizer
それら総てを通り抜けることはこのノートブックの範囲外ですので、それをどのように利用できるかにだけハイライトします。
@huggingface/tokenizers ライブラリ
transformers ライブラリとともに、@huggingface は一般的なマルチコアマシン上で数十 Gb/s でテキストを訓練、トークン化そしてデコードできる非常に高速なトークン化ライブラリを提供しています。
ネイティブなメモリ-aware な方法でマルチコア並列計算を活用することを可能にするためにライブラリは Rust で書かれていて、その上に Python と NodeJS のためのバインディングを提供しています (より多くのバインディングが将来追加される可能性があります)。
ライブラリが取り替え可能な end-to-end なトークナイザーを作成するために必要な総てのブロックを提供するように設計しました。その意味で、これらの様々なコンポーネントを提供します :
- Normalizer : 初期入力文字列に渡り初期変換の総てを実行します。例えばあるテキストを小文字化し、多分それを strip し、あるいは一般的な unicode 正規化プロセスの一つを適用することさえ必要である場合、Normalizer を追加します。
- PreTokenizer : 初期入力文字列の分割を担当します。元の文字列をどこでどのように事前にセグメント化するかを決定するコンポーネントです。最も単純な例は前に見たように空白で単純に分割することです。
- モデル : 総てのサブトークンの発見 (= discovery) と生成を処理します、この部分は訓練可能で実際には入力データに依存しています。
- Post-Processor : Transformers ベースの SoTA モデルの幾つかと互換な進んだ構築機能を提供します。例えば、BERT についてそれはトークン化されたセンテンスを [CLS] と [SEP] トークンでラップします。
- Decoder : トークン化された入力を元の文字列にマップし戻すことを担当します。デコーダは通常は前に使用した PreTokenizer に従って選択されます。
- Trainer : 各モデルに訓練機能を提供します。
上のコンポーネントの各々のために複数の実装を提供します :
- Normalizer : Lowercase, Unicode (NFD, NFKD, NFC, NFKC), Bert, Strip, …
- PreTokenizer : ByteLevel, WhitespaceSplit, CharDelimiterSplit, Metaspace, …
- Model : WordLevel, BPE, WordPiece
- Post-Processor : BertProcessor, …
- Decoder : WordLevel, BPE, WordPiece, …
動作するトークン化パイプラインを作成するためにこれらのビルディング・ブロックの総てを組み合わせることができます。次のセクションで最初のパイプラインを調べます。
Alright, 今では tokenizers を通して最初のトークン化パイプラインを実装する準備ができました。
このため、このノートブックの目的で Byte-Pair エンコーディング (BPE) トークナイザーを非常に小さい入力上で訓練します。Peter Norving からのファイル で作業します。このファイルはおよそ 130,000 行の raw テキストを含みます、これは動作するトークナイザーを生成するためにライブラリにより処理されます。
!pip install tokenizers
BIG_FILE_URL = 'https://raw.githubusercontent.com/dscape/spell/master/test/resources/big.txt'
# Let's download the file and save it somewhere
from requests import get
with open('big.txt', 'wb') as big_f:
response = get(BIG_FILE_URL, )
if response.status_code == 200:
big_f.write(response.content)
else:
print("Unable to get the file: {}".format(response.reason))
訓練データを持った今、トークナイザーのためのパイプライン全体を作成する必要があります。
# For the user's convenience `tokenizers` provides some very high-level classes encapsulating
# the overall pipeline for various well-known tokenization algorithm.
# Everything described below can be replaced by the ByteLevelBPETokenizer class.
from tokenizers import Tokenizer
from tokenizers.decoders import ByteLevel as ByteLevelDecoder
from tokenizers.models import BPE
from tokenizers.normalizers import Lowercase, NFKC, Sequence
from tokenizers.pre_tokenizers import ByteLevel
# First we create an empty Byte-Pair Encoding model (i.e. not trained model)
tokenizer = Tokenizer(BPE())
# Then we enable lower-casing and unicode-normalization
# The Sequence normalizer allows us to combine multiple Normalizer that will be
# executed in order.
tokenizer.normalizer = Sequence([
NFKC(),
Lowercase()
])
# Our tokenizer also needs a pre-tokenizer responsible for converting the input to a ByteLevel representation.
tokenizer.pre_tokenizer = ByteLevel()
# And finally, let's plug a decoder so we can recover from a tokenized input to the original one
tokenizer.decoder = ByteLevelDecoder()
このノートブックで先にダウンロードしたコーパス上でパイプライン全体が訓練される準備が今は整いました。
from tokenizers.trainers import BpeTrainer
# We initialize our trainer, giving him the details about the vocabulary we want to generate
trainer = BpeTrainer(vocab_size=25000, show_progress=True, initial_alphabet=ByteLevel.alphabet())
tokenizer.train(files=["big.txt"], trainer=trainer)
print("Trained vocab size: {}".format(tokenizer.get_vocab_size()))
Trained vocab size: 25000
Et voilà ! tokenizers を使用して貴方の本当に最初のトークナイザーをスクラッチから訓練しました。もちろん、これは基本だけをカバーしており、そして貴方は Trainer クラスの add_special_tokens や special_tokens パラメータを見ることを望むかもしれませんが、プロセス全体は非常に類似しているはずです。
モデルの内容をそれを後で再利用するためにセーブできます。
# You will see the generated files in the output.
tokenizer.model.save('.')
['./vocab.json', './merges.txt']
今は、訓練モデルをロードして新たに訓練されたトークナイザーを利用し始めましょう。
# Let's tokenizer a simple input
tokenizer.model = BPE('vocab.json', 'merges.txt')
encoding = tokenizer.encode("This is a simple input to be tokenized")
print("Encoded string: {}".format(encoding.tokens))
decoded = tokenizer.decode(encoding.ids)
print("Decoded string: {}".format(decoded))
Encoded string: ['Ġthis', 'Ġis', 'Ġa', 'Ġsimple', 'Ġin', 'put', 'Ġto', 'Ġbe', 'Ġtoken', 'ized'] Decoded string: this is a simple input to be tokenized
エンコーディング構造は複数のプロパティを公開しています、それらは transformers モデルで作業するときに有用です。
- normalized_str: 正規化 (小文字化、unicode、stripping 等) 後の入力文字列
- original_str: それが提供されたときの入力文字列
- tokens: 文字列表現による生成されたトークン
- input_ids: 整数表現による生成されたトークン
- attention_mask: 入力がトークナイザーによりパディングされている場合、これは任意のパディングされていないトークンのために 1、パディングされているもののためには 0 のベクトルです。
- special_token_mask: 入力が [CLS], [SEP], [MASK], [PAD] のような特殊トークンを含む場合、これは特殊トークンが追加された場所で 1 を持つベクトルになります。
- type_ids: 入力が (質問、コンテキスト) のような複数の「パート」から成る場合、これは各トークンについてそれが属するセグメントのベクトルになります。
- overflowing: 入力が長さ制限のために複数のサブパートに切り捨てられた場合 (例えば BERT についてはシークエンス長は 512 に制限されています)、これは総ての残りのオーバーフローしたパートを含みます。
以上
HuggingFace Transformers 4.6 : 上級ガイド : Examples
HuggingFace Transformers 4.6 : 上級ガイド : Examples (翻訳/解説)
翻訳 : (株)クラスキャット セールスインフォメーション
作成日時 : 05/15/2021 (4.6.0)
* 本ページは、HuggingFace Transformers の以下のドキュメントを翻訳した上で適宜、補足説明したものです:
- Advanced Guides : Examples
* サンプルコードの動作確認はしておりますが、必要な場合には適宜、追加改変しています。
* ご自由にリンクを張って頂いてかまいませんが、sales-info@classcat.com までご一報いただけると嬉しいです。
スケジュールは弊社 公式 Web サイト でご確認頂けます。
- お住まいの地域に関係なく Web ブラウザからご参加頂けます。事前登録 が必要ですのでご注意ください。
- ウェビナー運用には弊社製品「ClassCat® Webinar」を利用しています。
人工知能研究開発支援 | 人工知能研修サービス | テレワーク & オンライン授業を支援 |
PoC(概念実証)を失敗させないための支援 (本支援はセミナーに参加しアンケートに回答した方を対象としています。) |
◆ お問合せ : 本件に関するお問い合わせ先は下記までお願いいたします。
株式会社クラスキャット セールス・マーケティング本部 セールス・インフォメーション |
E-Mail:sales-info@classcat.com ; WebSite: https://www.classcat.com/ ; Facebook |
HuggingFace Transformers : 上級ガイド : Examples
このフォルダは NLP タスクに沿って体系化された Transformers の使用方法のアクティブにメンテナンスされたサンプルを含みます。このフォルダーにかつてあったサンプルを探している場合には、対応するフレームワークのサブフォルダ (pytorch, tensorflow or flax)、研究プロジェクト のサブフォルダ (それは研究プロジェクトの凍結されたスナップショットを含みます)、あるいはレガシー・サブフォルダに移動したかもしれません、
できる限り多くのユースケースを提示しようと努力する一方で、このフォルダのスクリプトは単なるサンプルです。それらは貴方の特定の問題にそのままでは動作しませんし、要求に適応させるためには数行のコードの変更が必要とされることが想定されます。それを助けるために、殆どのサンプルはデータの前処理を完全に公開しています。このようにして、貴方はそれらを容易に調整できます。
貴方がスクリプトに現在使用しているものとは異なる別のメトリックをレポートすることを望む場合も、同様です : スクリプト内の compute_metrics 関数を見てください。それは予測とラベルの完全な配列を取り文字列キーと float 値の辞書を返す必要があります。既にレポートされているものに貴方自身のメトリックを追加するためにそれを単に変更するか置き換えてください。
サンプルで実装して欲しい機能は PR を提出する前に フォーラム か issue で議論してください : バグ修正は歓迎しますがサンプルをできる限り単純に保持したいので、可読性を犠牲にしてより多くの機能を追加するためにプルリクエストをマージすることは殆どないでしょう。
重要な注意点
サンプルスクリプトの最新バージョンを成功的に実行できることを確実にするには、ライブラリをソースからインストールして幾つかのサンプル固有の requirements をインストールする必要があります。これを行なうには、新しい仮想環境で以下のステップを実行します :
git clone https://github.com/huggingface/transformers
cd transformers
pip install .
そして選択した example フォルダに cd して次を実行します :
pip install -r requirements.txt
Transformers のリリースされたバージョンに対応する examples をブラウザするには、下の行をクリックしてからライブラリの望まれるバージョンの上でクリックします :
Examples for older versions ofTransformers - [v4.5.1](https://github.com/huggingface/transformers/tree/v4.5.1/examples) - [v4.4.2](https://github.com/huggingface/transformers/tree/v4.4.2/examples) - [v4.3.3](https://github.com/huggingface/transformers/tree/v4.3.3/examples) - [v4.2.2](https://github.com/huggingface/transformers/tree/v4.2.2/examples) - [v4.1.1](https://github.com/huggingface/transformers/tree/v4.1.1/examples) - [v4.0.1](https://github.com/huggingface/transformers/tree/v4.0.1/examples) - [v3.5.1](https://github.com/huggingface/transformers/tree/v3.5.1/examples) - [v3.4.0](https://github.com/huggingface/transformers/tree/v3.4.0/examples) - [v3.3.1](https://github.com/huggingface/transformers/tree/v3.3.1/examples) - [v3.2.0](https://github.com/huggingface/transformers/tree/v3.2.0/examples) - [v3.1.0](https://github.com/huggingface/transformers/tree/v3.1.0/examples) - [v3.0.2](https://github.com/huggingface/transformers/tree/v3.0.2/examples) - [v2.11.0](https://github.com/huggingface/transformers/tree/v2.11.0/examples) - [v2.10.0](https://github.com/huggingface/transformers/tree/v2.10.0/examples) - [v2.9.1](https://github.com/huggingface/transformers/tree/v2.9.1/examples) - [v2.8.0](https://github.com/huggingface/transformers/tree/v2.8.0/examples) - [v2.7.0](https://github.com/huggingface/transformers/tree/v2.7.0/examples) - [v2.6.0](https://github.com/huggingface/transformers/tree/v2.6.0/examples) - [v2.5.1](https://github.com/huggingface/transformers/tree/v2.5.1/examples) - [v2.4.0](https://github.com/huggingface/transformers/tree/v2.4.0/examples) - [v2.3.0](https://github.com/huggingface/transformers/tree/v2.3.0/examples) - [v2.2.0](https://github.com/huggingface/transformers/tree/v2.2.0/examples) - [v2.1.1](https://github.com/huggingface/transformers/tree/v2.1.0/examples) - [v2.0.0](https://github.com/huggingface/transformers/tree/v2.0.0/examples) - [v1.2.0](https://github.com/huggingface/transformers/tree/v1.2.0/examples) - [v1.1.0](https://github.com/huggingface/transformers/tree/v1.1.0/examples) - [v1.0.0](https://github.com/huggingface/transformers/tree/v1.0.0/examples)
代わりに、クローンされた Transformers を次で特定のバージョン (例えば v3.5.1) に切り替えた後で :
git checkout tags/v3.5.1
通常のようにサンプルコマンドを実行できます。
以上
HuggingFace Transformers 4.6 : 上級ガイド : 事前訓練モデル
HuggingFace Transformers 4.6 : 上級ガイド : 事前訓練モデル (翻訳/解説)
翻訳 : (株)クラスキャット セールスインフォメーション
作成日時 : 05/16/2021 (4.6.0)
* 本ページは、HuggingFace Transformers の以下のドキュメントを翻訳した上で適宜、補足説明したものです:
- Advanced Guides : Pretrained models
* サンプルコードの動作確認はしておりますが、必要な場合には適宜、追加改変しています。
* ご自由にリンクを張って頂いてかまいませんが、sales-info@classcat.com までご一報いただけると嬉しいです。
スケジュールは弊社 公式 Web サイト でご確認頂けます。
- お住まいの地域に関係なく Web ブラウザからご参加頂けます。事前登録 が必要ですのでご注意ください。
- ウェビナー運用には弊社製品「ClassCat® Webinar」を利用しています。
人工知能研究開発支援 | 人工知能研修サービス | テレワーク & オンライン授業を支援 |
PoC(概念実証)を失敗させないための支援 (本支援はセミナーに参加しアンケートに回答した方を対象としています。) |
◆ お問合せ : 本件に関するお問い合わせ先は下記までお願いいたします。
株式会社クラスキャット セールス・マーケティング本部 セールス・インフォメーション |
E-Mail:sales-info@classcat.com ; WebSite: https://www.classcat.com/ ; Facebook |
HuggingFace Transformers : 上級ガイド : 事前訓練モデル
ここに各モデルの短い説明とともに利用可能な事前訓練モデルの部分的なリストがあります。
完全なリストについては、https://huggingface.co/models を参照してください。
アーキテクチャ | モデル id | モデルの詳細 |
BERT | bert-base-uncased | 12-層、768-隠れ次元、12-ヘッド、110M パラメータ lower-cased 英語テキスト上で訓練 |
bert-large-uncased | 24-層、1024-隠れ次元、16-ヘッド、336M パラメータlower-cased 英語テキスト上で訓練 | |
bert-base-cased | 12-層、768-隠れ次元、12-ヘッド、109M パラメータcased 英語テキスト上で訓練 | |
bert-large-cased | 24-層、1024-隠れ次元、16-ヘッド、335M パラメータcased 英語テキスト上で訓練 | |
bert-base-multilingual-uncased | (オリジナル、非推奨) 12-層、768-隠れ次元、12-ヘッド、168M パラメータ the largest Wikipedias 内でトップ 102 言語内の lower-cased テキスト上で訓練 (詳細 参照) |
|
bert-base-multilingual-cased | (新規、推奨) 12-層、768-隠れ次元、12-ヘッド、179M パラメータ the largest Wikipedias 内でトップ 104 言語内の cased テキスト上で訓練 (詳細 参照) |
|
bert-base-chinese | 12-層、768-隠れ次元、12-ヘッド、103M パラメータcased 中国語 (簡体字と繁体字) テキスト上で訓練 | |
bert-base-german-cased | 12-層、768-隠れ次元、12-ヘッド、110M パラメータDeepset.ai による cased ドイツ語テキスト上で訓練 (deepset.ai website 上の詳細 参照) |
|
bert-large-uncased-whole-word-masking | 24-層、1024-隠れ次元、16-ヘッド、336M パラメータWhole-Word-Masking を使用して lower-cased 英語テキスト上で訓練 (詳細 参照) |
|
bert-large-cased-whole-word-masking | 24-層、1024-隠れ次元、16-ヘッド、335M パラメータWhole-Word-Masking を使用して cased 英語テキスト上で訓練 (詳細 参照) |
|
bert-large-uncased-whole-word-masking-finetuned-squad | 24-層、1024-隠れ次元、16-ヘッド、336M パラメータSQuAD 上で再調整された bert-large-uncased-whole-word-masking モデル (example セクション の再調整の詳細参照) |
|
bert-large-cased-whole-word-masking-finetuned-squad | 24-層、1024-隠れ次元、16-ヘッド、335M パラメータSQuAD 上で再調整された bert-large-cased-whole-word-masking モデル (example セクション の再調整の詳細参照) |
|
bert-base-cased-finetuned-mrpc | 12-層、768-隠れ次元、12-ヘッド、110M パラメータMRPC 上で再調整された bert-base-cased モデル (example セクション の再調整の詳細参照) |
|
bert-base-german-dbmdz-cased | 12-層、768-隠れ次元、12-ヘッド、110M パラメータDBMDZ による cased ドイツ語テキスト上で訓練 (dbmdz レポジトリ上の詳細 参照) |
|
bert-base-german-dbmdz-uncased | 12-層、768-隠れ次元、12-ヘッド、110M パラメータDBMDZ による uncased ドイツ語テキスト上で訓練 (dbmdz レポジトリ上の詳細 参照) |
|
cl-tohoku/bert-base-japanese | 12-層、768-隠れ次元、12-ヘッド、111M パラメータ日本語テキスト上で訓練。テキストは MeCab と WordPiece でトークン化され、これは幾つかの追加の依存性を必要とします、fugashi これは MeCab のラッパーです。 それらをインストールするには pip install transformers[“ja”] (or ソースからインストールする場合は pip install -e .[“ja”]) を使用します。 (cl-tohoku レポジトリ 上の詳細参照) |
|
cl-tohoku/bert-base-japanese-whole-word-masking | 12-層、768-隠れ次元、12-ヘッド、111M パラメータ日本語テキスト上で訓練。テキストは MeCab と WordPiece でトークン化され、これは幾つかの追加の依存性を必要とします、fugashi これは MeCab のラッパーです。 それらをインストールするには pip install transformers[“ja”] (or ソースからインストールする場合は pip install -e .[“ja”]) を使用します。 (cl-tohoku レポジトリ 上の詳細参照) |
|
cl-tohoku/bert-base-japanese-char | 12-層、768-隠れ次元、12-ヘッド、90M パラメータ日本語テキスト上で訓練。テキストは文字にトークン化されます。 (cl-tohoku レポジトリ 上の詳細参照) |
|
cl-tohoku/bert-base-japanese-char-whole-word-masking | 12-層、768-隠れ次元、12-ヘッド、90M パラメータWhole-Word-Masking を使用して日本語テキスト上で訓練。テキストは文字にトークン化されます。 (cl-tohoku レポジトリ 上の詳細参照) |
|
TurkuNLP/bert-base-finnish-cased-v1 | 12-層、768-隠れ次元、12-ヘッド、125M パラメータcased フィンランド語テキスト上で訓練。 (turkunlp.org 上の詳細 参照。) |
TurkuNLP/bert-base-finnish-uncased-v1 | 12-層、768-隠れ次元、12-ヘッド、110M パラメータuncased フィンランド語テキスト上で訓練。 (turkunlp.org 上の詳細 参照。) |
wietsedv/bert-base-dutch-cased | 12-層、768-隠れ次元、12-ヘッド、110M パラメータcased オランダ語テキスト上で訓練。 (wietsedv レポジトリ上の詳細 参照。) |
GPT | openai-gpt | 12-層、768-隠れ次元、12-ヘッド、110M パラメータOpenAI GPT 英語モデル |
GPT-2 | gpt2 | 12-層、768-隠れ次元、12-ヘッド、117M パラメータOpenAI GPT-2 英語モデル |
gpt2-medium | 24-層、1024-隠れ次元、16-ヘッド、345M パラメータOpenAI のミディアムサイズ GPT-2 英語モデル | |
gpt2-large | 36-層、1280-隠れ次元、20-ヘッド、774M パラメータOpenAI のラージサイズ GPT-2 英語モデル | |
gpt2-xl | 48-層、1600-隠れ次元、25-ヘッド、1558M パラメータOpenAI の XL サイズ GPT-2 英語モデル | |
GPTNeo | EleutherAI/gpt-neo-1.3B | 24-層、2048-隠れ次元、16-ヘッド、1.3B パラメータEleutherAI の GPT-3 ライク言語モデル |
EleutherAI/gpt-neo-2.7B | 32-層、2560-隠れ次元、20-ヘッド、2.7B パラメータEleutherAI の GPT-3 ライク言語モデル | |
Transformer-XL | transfo-xl-wt103 | 18-層、1024-隠れ次元、16-ヘッド、257M パラメータwikitext-103 上で訓練された英語モデル |
XLNet | xlnet-base-cased | 12-層、768-隠れ次元、12-ヘッド、110M パラメータXLNet 英語モデル |
xlnet-large-cased | 24-層、1024-隠れ次元、16-ヘッド、340M パラメータXLNet ラージ英語モデル | |
XLM | xlm-mlm-en-2048 | 12-層、2048-隠れ次元、16-ヘッドXLM 英語モデル |
xlm-mlm-ende-1024 | 6-層、1024-隠れ次元、8-ヘッド英語とドイツ語 wikipedia の結合上で訓練された XLM 英独モデル | |
xlm-mlm-enfr-1024 | 6-層、1024-隠れ次元、8-ヘッド英語とフランス語 wikipedia の結合上で訓練された XLM 英仏モデル | |
xlm-mlm-enro-1024 | 6-層、1024-隠れ次元、8-ヘッドXLM 英語ルーマニア語多言語モデル | |
xlm-mlm-xnli15-1024 | 12-層、1024-隠れ次元、8-ヘッド15 XNLI 言語 上 MLM で事前訓練された XLM モデル | |
xlm-mlm-tlm-xnli15-1024 | 12-層、1024-隠れ次元、8-ヘッド15 XNLI 言語 上 MLM + TLM で事前訓練された XLM モデル | |
xlm-clm-enfr-1024 | 6-層、1024-隠れ次元、8-ヘッド英語とフランス語 wikipedia の結合上で CLM で訓練された XLM 英仏モデル | |
xlm-clm-ende-1024 | 6-層、1024-隠れ次元、8-ヘッド英語とドイツ語 wikipedia の結合上で CLM で訓練された XLM 英独モデル | |
xlm-mlm-17-1280 | 16-層、1280-隠れ次元、16-ヘッド17 言語上で MLM で訓練された XLM モデル | |
xlm-mlm-100-1280 | 16-層、1280-隠れ次元、16-ヘッド100 言語上で MLM で訓練された XLM モデル | |
RoBERTa | roberta-base | 12-層、768-隠れ次元、16-ヘッド、125M パラメータBERT ベースのアーキテクチャを使用する RoBERTa (詳細 参照) |
roberta-large | 24-層、1024-隠れ次元、16-ヘッド、355M パラメータBERT-large アーキテクチャを使用する RoBERTa (詳細 参照) |
|
roberta-large-mnli | 24-層、1024-隠れ次元、16-ヘッド、355M パラメータMNLI 上で再調整された roberta-large (詳細 参照) |
|
distilroberta-base | 6-層、768-隠れ次元、12-ヘッド、82M パラメータRoBERTa モデル roberta-base チェックポイント から蒸留された DistilRoBERTa モデル (詳細 参照) |
|
roberta-base-openai-detector | 12-層、768-隠れ次元、12-ヘッド、125M パラメータ1.5B-パラメータ GPT-2 モデルの出力上で OpenAI により再調整された roberta-base (詳細 参照) |
|
roberta-large-openai-detector | 24-層、1024-隠れ次元、16-ヘッド、355M パラメータ1.5B-パラメータ GPT-2 モデルの出力上で OpenAI により再調整された roberta-large (詳細 参照) |
|
DistilBERT | distilbert-base-uncased | 6-層、768-隠れ次元、12-ヘッド、66M パラメータBERT モデル bert-base-uncased チェックポイントから蒸留された DistilBERT モデル (詳細 参照) |
distilbert-base-uncased-distilled-squad | 6-層、768-隠れ次元、12-ヘッド、66M パラメータ追加の線形層を持ち、BERT モデル bert-base-uncased チェックポイントから蒸留された DistilBERT モデル (詳細 参照) |
|
distilbert-base-cased | 6-層、768-隠れ次元、12-ヘッド、65M パラメータBERT モデル bert-base-cased チェックポイントから蒸留された DistilBERT モデル (詳細 参照) |
|
distilbert-base-cased-distilled-squad | 6-層、768-隠れ次元、12-ヘッド、65M パラメータ追加の質問応答層を持ち、BERT モデル bert-base-cased チェックポイントから蒸留された DistilBERT モデル (詳細 参照) |
|
distilgpt2 | 6-層、768-隠れ次元、12-ヘッド、82M パラメータGPT2 モデル gpt2 チェックポイントから蒸留された DistilGPT2 モデル (詳細 参照) |
|
distilbert-base-german-cased | 6-層、768-隠れ次元、12-ヘッド、66M パラメータドイツ語 DBMDZ BERT モデル bert-base-german-dbmdz-cased チェックポイントから蒸留されたドイツ語 DistilBERT モデル (詳細 参照) |
|
distilbert-base-multilingual-cased | 6-層、768-隠れ次元、12-ヘッド、134M パラメータ多言語 BERT モデル bert-base-multilingual-cased チェックポイントから蒸留された多言語 DistilBERT モデル (詳細 参照) |
|
CTRL | ctrl | 48-層、1280-隠れ次元、16-ヘッド、1.6B パラメータSalesforce のラージサイズ CTRL 英語モデル |
CamemBERT | camembert-base | 12-層、768-隠れ次元、12-ヘッド、110M パラメータBERT-base アーキテクチャを使用する CamemBERT (詳細 参照) |
ALBERT | albert-base-v1 | 12-反復 (= repeating) 層、128 埋め込み、768-隠れ次元、12-ヘッド、11M パラメータALBERT ベースモデル (詳細 参照) |
albert-large-v1 | 24-反復 (= repeating) 層、128 埋め込み、1024-隠れ次元、16-ヘッド、17M パラメータALBERT ラージモデル (詳細 参照) |
|
albert-xlarge-v1 | 24-反復 (= repeating) 層、128 埋め込み、2048-隠れ次元、16-ヘッド、58M パラメータALBERT xlarge モデル (詳細 参照) |
|
albert-xxlarge-v1 | 12-反復 (= repeating) 層、128 埋め込み、4096-隠れ次元、64-ヘッド、223M パラメータALBERT xxlarge モデル (詳細 参照) |
|
albert-base-v2 | 12-反復 (= repeating) 層、128 埋め込み、768-隠れ次元、12-ヘッド、11M パラメータdropout なし、追加の訓練データとより長い訓練を伴う、ALBERT ベースモデル (詳細 参照) |
|
albert-large-v2 | 24-反復 (= repeating) 層、128 埋め込み、1024-隠れ次元、16-ヘッド、17M パラメータdropout なし、追加の訓練データとより長い訓練を伴う、ALBERT ラージモデル (詳細 参照) |
|
albert-xlarge-v2 | 24-反復 (= repeating) 層、128 埋め込み、2048-隠れ次元、16-ヘッド、58M パラメータdropout なし、追加の訓練データとより長い訓練を伴う、ALBERT xlarge モデル (詳細 参照) |
|
albert-xxlarge-v2 | 12-反復 (= repeating) 層、128 埋め込み、4096-隠れ次元、64-ヘッド、223M パラメータdropout なし、追加の訓練データとより長い訓練を伴う、ALBERT xxlarge モデル (詳細 参照) |
|
T5 | t5-small | 6-層、512-隠れ状態、2048 順伝播隠れ状態、8-ヘッド を持つ ~60M パラメータ英語テキスト: Colossal Clean Crawled コーパス (C4) 上で訓練 |
t5-base | 12-層、768-隠れ状態、3072 順伝播隠れ状態、12-ヘッド を持つ ~220M パラメータ英語テキスト: Colossal Clean Crawled コーパス (C4) 上で訓練 | |
t5-large | 24-層、1024-隠れ状態、4096 順伝播隠れ状態、16-ヘッド を持つ ~770M パラメータ英語テキスト: Colossal Clean Crawled コーパス (C4) 上で訓練 | |
t5-3B | 24-層、1024-隠れ状態、16384 順伝播隠れ状態、32-ヘッド を持つ ~2.8B パラメータ英語テキスト: Colossal Clean Crawled コーパス (C4) 上で訓練 | |
t5-11B | 24-層、1024-隠れ状態、65536 順伝播隠れ状態、128-ヘッド を持つ ~11B パラメータ英語テキスト: Colossal Clean Crawled コーパス (C4) 上で訓練 | |
XLM-RoBERTa | xlm-roberta-base | 12-層、768-隠れ状態、3072 順伝播隠れ状態、8-ヘッド を持つ ~270M パラメータ100 言語の新たに作成された clean CommonCrawl データの 2.5 TB 上で訓練 |
xlm-roberta-large | 24-層、1024-隠れ状態、4096 順伝播隠れ状態、16-ヘッド を持つ ~550M パラメータ100 言語の新たに作成された clean CommonCrawl データの 2.5 TB 上で訓練 | |
FlauBERT | flaubert/flaubert_small_cased | 6-層、512-隠れ状態、8-ヘッド、54M パラメータFlauBERT small アーキテクチャ (詳細 参照) |
flaubert/flaubert_base_uncased | 12-層、768-隠れ状態、12-ヘッド、137M パラメータuncased 語彙による FlauBERT ベースアーキテクチャ (詳細 参照) |
|
flaubert/flaubert_base_cased | 12-層、768-隠れ状態、12-ヘッド、138M パラメータcased 語彙による FlauBERT ベースアーキテクチャ (詳細 参照) |
|
flaubert/flaubert_large_cased | 24-層、1024-隠れ状態、16-ヘッド、373M パラメータFlauBERT large アーキテクチャ (詳細 参照) |
|
Bart | facebook/bart-large | 24-層、1024-隠れ状態、16-ヘッド、406M パラメータ(詳細 参照) |
facebook/bart-base | 12-層、768-隠れ状態、16-ヘッド、139M パラメータ | |
facebook/bart-large-mnli | 1M パラメータを持つ 2 層分類ヘッドを追加 MNLI 上で再調整された、分類ヘッドを持つ bart-large ベースアーキテクチャ |
|
facebook/bart-large-cnn | 24-層、1024-隠れ状態、16-ヘッド、406M パラメータ (large と同じ) cnn 要約タスク上で再調整された bart-large ベースアーキテクチャ |
|
BARThez | moussaKam/barthez | 12-層、768-隠れ状態、12-ヘッド、216M パラメータ (詳細 参照) |
moussaKam/mbarthez | 24-層、1024-隠れ状態、16-ヘッド、516M パラメータ | |
DialoGPT | DialoGPT-small | 12-層、768-隠れ状態、12-ヘッド、124M パラメータ 英語テキスト: Reddit から抽出された 147M の会話 like なやり取り – 上で訓練 |
DialoGPT-medium | 24-層、1024-隠れ状態、16-ヘッド、355M パラメータ 英語テキスト: Reddit から抽出された 147M の会話 like なやり取り – 上で訓練 |
|
DialoGPT-large | 36-層、1280-隠れ状態、20-ヘッド、774M パラメータ 英語テキスト: Reddit から抽出された 147M の会話 like なやり取り – 上で訓練 |
|
Reformer | reformer-enwik8 | 12-層、1024-隠れ状態、8-ヘッド、149M パラメータ 英語 Wikipedia データ – enwiki8 上で訓練 |
reformer-crime-and-punishment | 6-層、256-隠れ状態、2-ヘッド、3M パラメータ 英語テキスト: 罪と罰 小説 by フョードル・ドストエフスキー – 上で訓練 |
|
M2M100 | facebook/m2m100_418M | 24-層、1024-隠れ状態、16-ヘッド、418M パラメータ 100言語のための多言語機械翻訳モデル |
facebook/m2m100_1.2B | 48-層、1024-隠れ状態、16-ヘッド、1.2B パラメータ 100言語のための多言語機械翻訳モデル |
|
MarianMT | Helsinki-NLP/opus-mt-{src}-{tgt} | 12-層、512-隠れ状態、8-ヘッド、~74M パラメータ機械翻訳モデル。パラメータ数は語彙サイズに依存して様々です。 (モデルリスト 参照) |
Pegasus | google/pegasus-{dataset} | 16-層、1024-隠れ状態、16-ヘッド、~568M パラメータ、要約のためには 2.2 GB。モデルリスト |
Longformer | allenai/longformer-base-4096 | 12-層、768-隠れ状態、12-ヘッド、~149M パラメータ RoBERTa-base チェックポイントから始めて、最大長 4,096 のドキュメント上で訓練 |
allenai/longformer-large-4096 | 24-層、1024-隠れ状態、16-ヘッド、~435M パラメータ RoBERTa-large チェックポイントから始めて、最大長 4,096 のドキュメント上で訓練 |
|
MBart | facebook/mbart-large-cc25 | 24-層、1024-隠れ状態、16-ヘッド、610M パラメータ 25 言語の monolingual コーパス上で訓練された mBART (bart-large アーキテクチャ) モデル |
facebook/mbart-large-en-ro | 24-層、1024-隠れ状態、16-ヘッド、610M パラメータ WMT 英語ルーマニア翻訳上で再調整された mbart-large-cc25 モデル |
|
facebook/mbart-large-50 | 24-層、1024-隠れ状態、16-ヘッド 50 言語の monolingual コーパス上で訓練された mBART モデル |
|
facebook/mbart-large-50-one-to-many-mmt | 24-層、1024-隠れ状態、16-ヘッド 一つ (英語) を 50 言語をカバーする多くの多言語機械翻訳のために再調整された mbart-50-large モデル |
|
facebook/mbart-large-50-many-to-many-mmt | 24-層、1024-隠れ状態、16-ヘッド 多数 (の言語) を 50 言語をカバーする多くの多言語機械翻訳のために再調整された mbart-50-large モデル |
|
Lxmert | lxmert-base-uncased | 9-言語層、9-関係 (= relationship) 層と 12-交差モーダリティ層、768-隠れ状態、12-ヘッド (各層について) ~ 228M パラメータ lxmert-base チェックポイントから始めて、COCO, VisualGenome, GQA, VQA からの 9 百万を越える画像-テキストのカプレット (= couplet) 上で訓練 |
Funnel Transformer | funnel-transformer/small | 14 層: 4 層の 3 ブロックから 2 層デコーダ、768-隠れ状態、12-ヘッド、130M パラメータ (詳細 参照) |
funnel-transformer/small-base | 12 層: 4 層の 3 ブロック (no デコーダ)、768-隠れ状態、12-ヘッド、115M パラメータ (詳細 参照) |
|
funnel-transformer/medium | 14 層: 3 ブロック 6, 3×2, 3×2 層から 2 層デコーダ、768-隠れ状態、12-ヘッド、130M パラメータ (詳細 参照) |
|
funnel-transformer/medium-base | 12 層: 3 ブロック 6, 3×2, 3×2 層 (no デコーダ)、768-隠れ状態、12-ヘッド、115M パラメータ (詳細 参照) |
|
funnel-transformer/intermediate | 20 層: 6 層の 3 ブロックから 2 層デコーダ、768-隠れ状態、12-ヘッド、177M パラメータ (詳細 参照) |
|
funnel-transformer/intermediate-base | 18 層: 6 層の 3 ブロック (no デコーダ)、768-隠れ状態、12-ヘッド、161M パラメータ (詳細 参照) |
|
funnel-transformer/large | 26 層: 8 層の 3 ブロックから 2 層デコーダ、1024-隠れ状態、12-ヘッド、386M パラメータ (詳細 参照) |
|
funnel-transformer/large-base | 24 層: 8 層の 3 ブロック (no デコーダ)、1024-隠れ状態、12-ヘッド、358M パラメータ (詳細 参照) |
|
funnel-transformer/xlarge | 32 層: 10 層の 3 ブロックから 2 層デコーダ、1024-隠れ状態、12-ヘッド、468M パラメータ (詳細 参照) |
|
funnel-transformer/xlarge-base | 30 層: 10 層の 3 ブロック (no デコーダ)、1024-隠れ状態、12-ヘッド、440M パラメータ (詳細 参照) |
|
LayoutLM | microsoft/layoutlm-base-uncased | 12-層、768-隠れ状態、12-ヘッド、113M パラメータ (詳細 参照) |
microsoft/layoutlm-large-uncased | 24-層、1024-隠れ状態、16-ヘッド、343M パラメータ (詳細 参照) |
|
DeBERTa | microsoft/deberta-base | 12-層、768-隠れ状態、12-ヘッド、~140M パラメータ BERT ベース・アーキテクチャを使用する DeBERTa (詳細 参照) |
microsoft/deberta-large | 24-層、1024-隠れ状態、16-ヘッド、~400M パラメータ BERT large アーキテクチャを使用する DeBERTa (詳細 参照) |
|
microsoft/deberta-xlarge | 48-層、1024-隠れ状態、16-ヘッド、~750M パラメータ 類似した BERT アーキテクチャによる DeBERTa XLarge (詳細 参照) |
|
microsoft/deberta-xlarge-v2 | 24-層、1536-隠れ状態、24-ヘッド、~900M パラメータ 類似した BERT アーキテクチャによる DeBERTa XLarge V2 (詳細 参照) |
|
microsoft/deberta-xxlarge-v2 | 48-層、1536-隠れ状態、24-ヘッド、~1.5B パラメータ 類似した BERT アーキテクチャによる DeBERTa XXLarge V2 (詳細 参照) |
|
SqueezeBERT | squeezebert/squeezebert-uncased | 12-層、768-隠れ状態、12-ヘッド、51M パラメータ、スマートフォン上で bert-base-uncased より 4.3x 高速。 MLM とセンテンス順序予測 (SOP) タスク上でスクラッチから事前訓練された SqueezeBERT アーキテクチャ。 |
squeezebert/squeezebert-mnli | 12-層、768-隠れ状態、12-ヘッド、51M パラメータ、スマートフォン上で bert-base-uncased より 4.3x 高速。 これは electra-base からの蒸留による MNLI センテンス・ペア分類タスク上で再調整された squeezebert-uncased モデル。 |
|
squeezebert/squeezebert-mnli-headless | 12-層、768-隠れ状態、12-ヘッド、51M パラメータ、スマートフォン上で bert-base-uncased より 4.3x 高速。 これは electra-base からの蒸留による MNLI センテンス・ペア分類タスク上で再調整された squeezebert-uncased モデル。 最後の分類層は除去されていますので、貴方が再調整するとき、最終層は最初期化されます。 |
以上
HuggingFace Transformers 4.6 : 概要
HuggingFace Transformers 4.6 : 概要 (翻訳/解説)
翻訳 : (株)クラスキャット セールスインフォメーション
作成日時 : 05/15/2021 (4.6.0)
* 本ページは、HuggingFace Transformers の以下のドキュメントを翻訳した上で適宜、補足説明したものです:
* サンプルコードの動作確認はしておりますが、必要な場合には適宜、追加改変しています。
* ご自由にリンクを張って頂いてかまいませんが、sales-info@classcat.com までご一報いただけると嬉しいです。
スケジュールは弊社 公式 Web サイト でご確認頂けます。
- お住まいの地域に関係なく Web ブラウザからご参加頂けます。事前登録 が必要ですのでご注意ください。
- ウェビナー運用には弊社製品「ClassCat® Webinar」を利用しています。
人工知能研究開発支援 | 人工知能研修サービス | テレワーク & オンライン授業を支援 |
PoC(概念実証)を失敗させないための支援 (本支援はセミナーに参加しアンケートに回答した方を対象としています。) |
◆ お問合せ : 本件に関するお問い合わせ先は下記までお願いいたします。
株式会社クラスキャット セールス・マーケティング本部 セールス・インフォメーション |
E-Mail:sales-info@classcat.com ; WebSite: https://www.classcat.com/ ; Facebook |
HuggingFace Transformers : 概要
PyTorch と TensorFlow 2.0 のための最先端の自然言語処理
Transformers は 100+ 言語の分類、情報抽出、質問応答、要約、翻訳、テキスト生成等のテキスト上のタスクを遂行するために数千の事前訓練モデルを提供します。その目的は最先端の NLP を誰でも容易に利用できるようにすることです。
Transformers はそれらの事前訓練モデルを素早くダウンロードして与えられたテキスト上で利用し、それらを貴方自身のデータセット上で再調整し、それからそれらを私達の モデル・ハブ 上でコミュニティと共有するための API を提供します。同時に、アーキテクチャを定義する各 python モジュールは素早い研究実験を可能にするためスタンドアロンとして利用できて変更できます。
Transformers は 2 つの最もポピュラーな深層学習ライブラリ PyTorch と TensorFlow により、それらの間のシームレスな統合によって支援され、その一つでモデルを訓練してから推論のために他方でそれをロードすることを可能にします。
オンライン・デモ
私達のモデルの殆どを モデルハブ のそれらのページから直接テストすることができます。それらのモデルを利用するための プライベートモデル・ホスティング、バージョニング & 推論 API もまた供給します。
ここに幾つかサンプルがあります :
- BERT による Masked 単語補完
- Electra による固有表現認識
- GPT-2 によるテキスト生成
- RoBERTa による自然言語推論
- BART による要約
- DistilBERT による質問応答
- T5 による翻訳
Hugging Face チームにより構築された Write With Transformer はこのレポジトリのテキスト生成機能の公式デモです。
クイック・ツアー
与えられたテキスト上でモデルを直ちに利用するため、パイプライン API を提供します。パイプラインは事前訓練されたモデルをそのモデル訓練の間に使用された前処理と一緒にグループ化します。ここにポジティブ vs ネガティブ・テキストを分類するためのパイプラインをどのように素早く利用するかがあります :
>>> from transformers import pipeline
# Allocate a pipeline for sentiment-analysis
>>> classifier = pipeline('sentiment-analysis')
>>> classifier('We are very happy to introduce pipeline to the transformers repository.')
[{'label': 'POSITIVE', 'score': 0.9996980428695679}]
コードの 2 番目の行はパイプラインで使用された事前訓練モデルをダウンロードしてキャッシュします、一方で 3 番目の行はそれを与えられたテキスト上で評価します。ここでは答えは 99.97% の信頼度で「ポジティブ」です。
多くの NLP タスクは事前訓練されたパイプラインを持ちます。例えば、コンテキストが与えられたとき質問への回答を容易に抽出できます :
>>> from transformers import pipeline
# Allocate a pipeline for question-answering
>>> question_answerer = pipeline('question-answering')
>>> question_answerer({
... 'question': 'What is the name of the repository ?',
... 'context': 'Pipeline has been included in the huggingface/transformers repository'
... })
{'score': 0.30970096588134766, 'start': 34, 'end': 58, 'answer': 'huggingface/transformers'
答えに加えて、ここで使用される事前訓練モデルは (トークン化されたセンテンスの開始位置と終了位置とともに) その信頼度スコアを返しました。このチュートリアル でパイプライン API によりサポートされるタスクについて更に学習できます。
与えられたタスク上で任意の事前訓練されたモデルをダウンロードして利用するには、3 行のコードを必要とするだけです。ここに PyToch バージョンがあります :
>>> from transformers import AutoTokenizer, AutoModel
>>> tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
>>> model = AutoModel.from_pretrained("bert-base-uncased")
>>> inputs = tokenizer("Hello world!", return_tensors="pt")
>>> outputs = model(**inputs)
そしてここに TensorFlow のための同値なコードがあります :
>>> from transformers import AutoTokenizer, TFAutoModel
>>> tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
>>> model = TFAutoModel.from_pretrained("bert-base-uncased")
>>> inputs = tokenizer("Hello world!", return_tensors="tf")
>>> outputs = model(**inputs)
tokenizer は事前訓練されたモデルが想定する前処理の総ての責任を負い、そして (上のサンプルでのように) 単一の文字列かリスト上で直接呼び出せます。それは辞書を出力します、これは下流コードで利用するか、あるいは ** 引数 unpacking 演算子を使用して単純にモデルに渡すことができます。
モデル自身は通常の Pytorch nn.Module や TensorFlow tf.keras.Model で (貴方のバックエンドに依存します)、これらは普通に利用できます。このチュートリアル は古典的な PyTorch or TensorFlow 訓練ループでそのようなモデルをどのように統合するか、あるいは新しいデータセット上で素早く再調整するために Trainer API をどのように利用するかを説明しています。
何故私は transformers を使用するべきでしょう?
- 使いやすい最先端のモデル :
- NLU と NLG タスク上の高パフォーマンス。
- 教育者と実践者のための入門への低い障壁。
- 学習すべき 3 つのクラスだけを持つ、ユーザが直面する少ない抽象。
- 事前訓練されたモデルの総てを使用するための統一 API。
- より低い計算コスト、より小さいカーボンフットプリント (二酸化炭素排出量) :
- 研究者は常に再訓練する代わりに訓練モデルを共有できます。
- 実践者は計算時間とプロダクション・コストを減じることができます。
- 幾つかは100 言語以上の、2,000 超の事前訓練モデルを持つ数十のアーキテクチャ。
- モデルのライフタイムの総てのパートのために適切なフレームワークを選択する :
- 3 行のコードで最先端のモデルを訓練します。
- TF2.0/PyTorch フレームワーク間で単一モデルを自在に移動する。
- 訓練、評価、プロダクションのための適切なフレームワークをシームレスに選択する。
- 貴方のニーズにモデルやサンプルを容易にカスタマイズする :
- 言及されるアーキテクチャの公式著者による結果を再生成するための各アーキテクチャのためのサンプル。
- できる限り一貫してモデル内部を公開する。
- モデルファイルは素早い実験のためにライブラリから独立的に利用できる。
何故 transformers を利用するべきではないのでしょう?
- このライブラリはニューラルネットのためのビルディングブロックのモジュール・ツールボックスではありません。研究者が追加の抽象/ファイルに深入りすることなくモデルの各々の上で素早く iterate できるようにように、モデルファイルのコードは意図的な追加の抽象によりリファクタリングされません。
- 訓練 API は任意のモデル上で動作することを意図されていませんがライブラリにより提供されるモデルで動作するように最適化されています。一般的な機械学習ループのためには、他のライブラリを利用するべきです。
- 私達は可能な限り多くのユースケースを提示する努力をする一方で、examples フォルダ のスクリプトは単なるサンプルです。それらは貴方の特定の問題上でそのままでは動作しないでしょうし、それらを貴方のニーズに適応させるためにコードの数行を変更する必要があることが想定されます。
モデル・アーキテクチャ
Transformers により提供される 総てのモデルチェックポイント は huggingface.co モデルハブ からシームレスに統合されていて、そこではそれらは ユーザ と 組織 により直接アップロードされています。
チェックポイントの現在の数 : モデル 11,588 (as of 5/15/2021)
Transformers は現在以下のアーキテクチャを提供しています (それらの各々の高位な要約については ここ を参照) :
- ALBERT (from Google Research and the Toyota Technological Institute at Chicago) released with the paper ALBERT: A Lite BERT for Self-supervised Learning of Language Representations, by Zhenzhong Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut.
- BART (from Facebook) released with the paper BART: Denoising Sequence-to-Sequence Pre-training for Natural Language Generation, Translation, and Comprehension by Mike Lewis, Yinhan Liu, Naman Goyal, Marjan Ghazvininejad, Abdelrahman Mohamed, Omer Levy, Ves Stoyanov and Luke Zettlemoyer.
- BARThez (from École polytechnique) released with the paper BARThez: a Skilled Pretrained French Sequence-to-Sequence Model by Moussa Kamal Eddine, Antoine J.-P. Tixier, Michalis Vazirgiannis.
- BERT (from Google) released with the paper BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding by Jacob Devlin, Ming-Wei Chang, Kenton Lee and Kristina Toutanova.
- BERT For Sequence Generation (from Google) released with the paper Leveraging Pre-trained Checkpoints for Sequence Generation Tasks by Sascha Rothe, Shashi Narayan, Aliaksei Severyn.
- BigBird-RoBERTa (from Google Research) released with the paper Big Bird: Transformers for Longer Sequences by Manzil Zaheer, Guru Guruganesh, Avinava Dubey, Joshua Ainslie, Chris Alberti, Santiago Ontanon, Philip Pham, Anirudh Ravula, Qifan Wang, Li Yang, Amr Ahmed.
- New ! BigBird-Pegasus (from Google Research) released with the paper Big Bird: Transformers for Longer Sequences by Manzil Zaheer, Guru Guruganesh, Avinava Dubey, Joshua Ainslie, Chris Alberti, Santiago Ontanon, Philip Pham, Anirudh Ravula, Qifan Wang, Li Yang, Amr Ahmed.
- Blenderbot (from Facebook) released with the paper Recipes for building an open-domain chatbot by Stephen Roller, Emily Dinan, Naman Goyal, Da Ju, Mary Williamson, Yinhan Liu, Jing Xu, Myle Ott, Kurt Shuster, Eric M. Smith, Y-Lan Boureau, Jason Weston.
- BlenderbotSmall (from Facebook) released with the paper Recipes for building an open-domain chatbot by Stephen Roller, Emily Dinan, Naman Goyal, Da Ju, Mary Williamson, Yinhan Liu, Jing Xu, Myle Ott, Kurt Shuster, Eric M. Smith, Y-Lan Boureau, Jason Weston.
- BORT (from Alexa) released with the paper Optimal Subarchitecture Extraction For BERT by Adrian de Wynter and Daniel J. Perry.
- CamemBERT (from Inria/Facebook/Sorbonne) released with the paper CamemBERT: a Tasty French Language Model by Louis Martin*, Benjamin Muller*, Pedro Javier Ortiz Suárez*, Yoann Dupont, Laurent Romary, Éric Villemonte de la Clergerie, Djamé Seddah and Benoît Sagot.
- New ! CLIP from (OpenAI) released with the paper Learning Transferable Visual Models From Natural Language Supervision by Alec Radford, Jong Wook Kim, Chris Hallacy, Aditya Ramesh, Gabriel Goh, Sandhini Agarwal, Girish Sastry, Amanda Askell, Pamela Mishkin, Jack Clark, Gretchen Krueger, Ilya Sutskever.
- ConvBERT (from YituTech) released with the paper ConvBERT: Improving BERT with Span-based Dynamic Convolution by Zihang Jiang, Weihao Yu, Daquan Zhou, Yunpeng Chen, Jiashi Feng, Shuicheng Yan.
- CPM (from Tsinghua University) released with the paper CPM: A Large-scale Generative Chinese Pre-trained Language Model by Zhengyan Zhang, Xu Han, Hao Zhou, Pei Ke, Yuxian Gu, Deming Ye, Yujia Qin, Yusheng Su, Haozhe Ji, Jian Guan, Fanchao Qi, Xiaozhi Wang, Yanan Zheng, Guoyang Zeng, Huanqi Cao, Shengqi Chen, Daixuan Li, Zhenbo Sun, Zhiyuan Liu, Minlie Huang, Wentao Han, Jie Tang, Juanzi Li, Xiaoyan Zhu, Maosong Sun.
- CTRL (from Salesforce) released with the paper CTRL: A Conditional Transformer Language Model for Controllable Generation by Nitish Shirish Keskar*, Bryan McCann*, Lav R. Varshney, Caiming Xiong and Richard Socher.
- DeBERTa (from Microsoft Research) released with the paper DeBERTa: Decoding-enhanced BERT with Disentangled Attention by Pengcheng He, Xiaodong Liu, Jianfeng Gao, Weizhu Chen.
- DeBERTa-v2 (from Microsoft) released with the paper DeBERTa: Decoding-enhanced BERT with Disentangled Attention by Pengcheng He, Xiaodong Liu, Jianfeng Gao, Weizhu Chen.
- DeiT (from Facebook) released with the paper Training data-efficient image transformers & distillation through attention by Hugo Touvron, Matthieu Cord, Matthijs Douze, Francisco Massa, Alexandre Sablayrolles, Hervé Jégou.
- DialoGPT (from Microsoft Research) released with the paper DialoGPT: Large-Scale Generative Pre-training for Conversational Response Generation by Yizhe Zhang, Siqi Sun, Michel Galley, Yen-Chun Chen, Chris Brockett, Xiang Gao, Jianfeng Gao, Jingjing Liu, Bill Dolan.
- DistilBERT (from HuggingFace), released together with the paper DistilBERT, a distilled version of BERT: smaller, faster, cheaper and lighter by Victor Sanh, Lysandre Debut and Thomas Wolf. The same method has been applied to compress GPT2 into DistilGPT2, RoBERTa into DistilRoBERTa, Multilingual BERT into DistilmBERT and a German version of DistilBERT.
- DPR (from Facebook) released with the paper Dense Passage Retrieval for Open-Domain Question Answering by Vladimir Karpukhin, Barlas Oğuz, Sewon Min, Patrick Lewis, Ledell Wu, Sergey Edunov, Danqi Chen, and Wen-tau Yih.
- ELECTRA (from Google Research/Stanford University) released with the paper ELECTRA: Pre-training text encoders as discriminators rather than generators by Kevin Clark, Minh-Thang Luong, Quoc V. Le, Christopher D. Manning.
- FlauBERT (from CNRS) released with the paper FlauBERT: Unsupervised Language Model Pre-training for French by Hang Le, Loïc Vial, Jibril Frej, Vincent Segonne, Maximin Coavoux, Benjamin Lecouteux, Alexandre Allauzen, Benoît Crabbé, Laurent Besacier, Didier Schwab.
- Funnel Transformer (from CMU/Google Brain) released with the paper Funnel-Transformer: Filtering out Sequential Redundancy for Efficient Language Processing by Zihang Dai, Guokun Lai, Yiming Yang, Quoc V. Le.
- GPT (from OpenAI) released with the paper Improving Language Understanding by Generative Pre-Training by Alec Radford, Karthik Narasimhan, Tim Salimans and Ilya Sutskever.
- GPT-2 (from OpenAI) released with the paper Language Models are Unsupervised Multitask Learners by Alec Radford*, Jeffrey Wu*, Rewon Child, David Luan, Dario Amodei** and Ilya Sutskever**.
- GPT Neo (from EleutherAI) released in the repository EleutherAI/gpt-neo by Sid Black, Stella Biderman, Leo Gao, Phil Wang and Connor Leahy.
- I-BERT (from Berkeley) released with the paper I-BERT: Integer-only BERT Quantization by Sehoon Kim, Amir Gholami, Zhewei Yao, Michael W. Mahoney, Kurt Keutzer
- LayoutLM (from Microsoft Research Asia) released with the paper LayoutLM: Pre-training of Text and Layout for Document Image Understanding by Yiheng Xu, Minghao Li, Lei Cui, Shaohan Huang, Furu Wei, Ming Zhou.
- LED (from AllenAI) released with the paper Longformer: The Long-Document Transformer by Iz Beltagy, Matthew E. Peters, Arman Cohan.
- Longformer (from AllenAI) released with the paper Longformer: The Long-Document Transformer by Iz Beltagy, Matthew E. Peters, Arman Cohan.
- New ! LUKE (from Studio Ousia) released with the paper LUKE: Deep Contextualized Entity Representations with Entity-aware Self-attention by Ikuya Yamada, Akari Asai, Hiroyuki Shindo, Hideaki Takeda, Yuji Matsumoto.
- LXMERT (from UNC Chapel Hill) released with the paper LXMERT: Learning Cross-Modality Encoder Representations from Transformers for Open-Domain Question Answering by Hao Tan and Mohit Bansal.
- M2M100 (from Facebook) released with the paper Beyond English-Centric Multilingual Machine Translation by by Angela Fan, Shruti Bhosale, Holger Schwenk, Zhiyi Ma, Ahmed El-Kishky, Siddharth Goyal, Mandeep Baines, Onur Celebi, Guillaume Wenzek, Vishrav Chaudhary, Naman Goyal, Tom Birch, Vitaliy Liptchinsky, Sergey Edunov, Edouard Grave, Michael Auli, Armand Joulin.
- MarianMT Machine translation models trained using OPUS data by Jörg Tiedemann. The Marian Framework is being developed by the Microsoft Translator Team.
- MBart (from Facebook) released with the paper Multilingual Denoising Pre-training for Neural Machine Translation by Yinhan Liu, Jiatao Gu, Naman Goyal, Xian Li, Sergey Edunov, Marjan Ghazvininejad, Mike Lewis, Luke Zettlemoyer.
- MBart-50 (from Facebook) released with the paper Multilingual Translation with Extensible Multilingual Pretraining and Finetuning by Yuqing Tang, Chau Tran, Xian Li, Peng-Jen Chen, Naman Goyal, Vishrav Chaudhary, Jiatao Gu, Angela Fan.
- Megatron-BERT (from NVIDIA) released with the paper Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism by Mohammad Shoeybi, Mostofa Patwary, Raul Puri, Patrick LeGresley, Jared Casper and Bryan Catanzaro.
- Megatron-GPT2 (from NVIDIA) released with the paper Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism by Mohammad Shoeybi, Mostofa Patwary, Raul Puri, Patrick LeGresley, Jared Casper and Bryan Catanzaro.
- MPNet (from Microsoft Research) released with the paper MPNet: Masked and Permuted Pre-training for Language Understanding by Kaitao Song, Xu Tan, Tao Qin, Jianfeng Lu, Tie-Yan Liu.
- MT5 (from Google AI) released with the paper mT5: A massively multilingual pre-trained text-to-text transformer by Linting Xue, Noah Constant, Adam Roberts, Mihir Kale, Rami Al-Rfou, Aditya Siddhant, Aditya Barua, Colin Raffel.
- Pegasus (from Google) released with the paper PEGASUS: Pre-training with Extracted Gap-sentences for Abstractive Summarization by Jingqing Zhang, Yao Zhao, Mohammad Saleh and Peter J. Liu.
- ProphetNet (from Microsoft Research) released with the paper ProphetNet: Predicting Future N-gram for Sequence-to-Sequence Pre-training by Yu Yan, Weizhen Qi, Yeyun Gong, Dayiheng Liu, Nan Duan, Jiusheng Chen, Ruofei Zhang and Ming Zhou.
- Reformer (from Google Research) released with the paper Reformer: The Efficient Transformer by Nikita Kitaev, Łukasz Kaiser, Anselm Levskaya.
- RoBERTa (from Facebook), released together with the paper a Robustly Optimized BERT Pretraining Approach by Yinhan Liu, Myle Ott, Naman Goyal, Jingfei Du, Mandar Joshi, Danqi Chen, Omer Levy, Mike Lewis, Luke Zettlemoyer, Veselin Stoyanov. ultilingual BERT into DistilmBERT and a German version of DistilBERT.
- SpeechToTextTransformer (from Facebook), released together with the paper fairseq S2T: Fast Speech-to-Text Modeling with fairseq by Changhan Wang, Yun Tang, Xutai Ma, Anne Wu, Dmytro Okhonko, Juan Pino.
- SqueezeBert released with the paper SqueezeBERT: What can computer vision teach NLP about efficient neural networks? by Forrest N. Iandola, Albert E. Shaw, Ravi Krishna, and Kurt W. Keutzer.
- T5 (from Google AI) released with the paper Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer by Colin Raffel and Noam Shazeer and Adam Roberts and Katherine Lee and Sharan Narang and Michael Matena and Yanqi Zhou and Wei Li and Peter J. Liu.
- TAPAS (from Google AI) released with the paper TAPAS: Weakly Supervised Table Parsing via Pre-training by Jonathan Herzig, Paweł Krzysztof Nowak, Thomas Müller, Francesco Piccinno and Julian Martin Eisenschlos.
- Transformer-XL (from Google/CMU) released with the paper Transformer-XL: Attentive Language Models Beyond a Fixed-Length Context by Zihang Dai*, Zhilin Yang*, Yiming Yang, Jaime Carbonell, Quoc V. Le, Ruslan Salakhutdinov.
- Vision Transformer (ViT) (from Google AI) released with the paper An Image is Worth 16×16 Words: Transformers for Image Recognition at Scale by Alexey Dosovitskiy, Lucas Beyer, Alexander Kolesnikov, Dirk Weissenborn, Xiaohua Zhai, Thomas Unterthiner, Mostafa Dehghani, Matthias Minderer, Georg Heigold, Sylvain Gelly, Jakob Uszkoreit, Neil Houlsby.
- Wav2Vec2 (from Facebook AI) released with the paper wav2vec 2.0: A Framework for Self-Supervised Learning of Speech Representations by Alexei Baevski, Henry Zhou, Abdelrahman Mohamed, Michael Auli.
- XLM (from Facebook) released together with the paper Cross-lingual Language Model Pretraining by Guillaume Lample and Alexis Conneau.
- XLM-ProphetNet (from Microsoft Research) released with the paper ProphetNet: Predicting Future N-gram for Sequence-to-Sequence Pre-training by Yu Yan, Weizhen Qi, Yeyun Gong, Dayiheng Liu, Nan Duan, Jiusheng Chen, Ruofei Zhang and Ming Zhou.
- XLM-RoBERTa (from Facebook AI), released together with the paper Unsupervised Cross-lingual Representation Learning at Scale by Alexis Conneau*, Kartikay Khandelwal*, Naman Goyal, Vishrav Chaudhary, Guillaume Wenzek, Francisco Guzmán, Edouard Grave, Myle Ott, Luke Zettlemoyer and Veselin Stoyanov.
- XLNet (from Google/CMU) released with the paper XLNet: Generalized Autoregressive Pretraining for Language Understanding by Zhilin Yang*, Zihang Dai*, Yiming Yang, Jaime Carbonell, Ruslan Salakhutdinov, Quoc V. Le.
- XLSR-Wav2Vec2 (from Facebook AI) released with the paper Unsupervised Cross-Lingual Representation Learning For Speech Recognition by Alexis Conneau, Alexei Baevski, Ronan Collobert, Abdelrahman Mohamed, Michael Auli.
- 新しいモデルを寄贈することを望みますか?新しいモデルを追加するプロセスに導く詳細なガイドとテンプレートを追加しました。レポジトリの templates フォルダでそれらを見つけることができます。貴方の PR を始める前にフィードバックを集めるために contributing ガイドライン を確認してそしてメンテナーにコンタクトするか issue をオープンすることを確実にしてください。
各モデルが PyTorch/TensorFlow/Flax の実装を持つか、あるいは Tokenizer により支援された関連する tokenizer を持つかを確認するためには、このテーブル を参照してください。
これらの実装は幾つかのデータセット上でテストされ (examples スクリプト参照) そして元の実装のパフォーマンスに一致するはずです。ドキュメントの Examples セクションでパフォーマンス上の更なる詳細を見つけられます。
更に学習する
セクション | 説明 |
ドキュメント | Full API ドキュメントとチュートリアル |
タスク要約 | ![]() |
前処理チュートリアル | モデルのためにデータを準備するための Tokenizer クラスを使用する |
訓練と再調整 | PyTorch/TensorFlow 訓練ループと Trainer API で![]() |
クイックツアー: 再調整/使用方法スクリプト | 広範囲なタスク上でモデルを再調整するためのサンプル・スクリプト |
モデル共有とアップロード | 貴方の再調整モデルをアップロードしてコミュニティで共有する |
マイグレーション | pytorch-transformers or pytorch-pretrained-bert から ![]() |
Citation
(訳注: 原文 を参照してください。)
以上