ホーム » 「HuggingFace Transformers 4.6」タグがついた投稿

タグアーカイブ: HuggingFace Transformers 4.6

HuggingFace Transformers 4.6 : ノートブック : パイプラインの利用

HuggingFace Transformers 4.6 : ノートブック : パイプラインの利用 (翻訳/解説)
翻訳 : (株)クラスキャット セールスインフォメーション
作成日時 : 06/14/2021 (4.6.1)

* 本ページは、HuggingFace Transformers の以下のドキュメントを翻訳した上で適宜、補足説明したものです:

* サンプルコードの動作確認はしておりますが、必要な場合には適宜、追加改変しています。
* ご自由にリンクを張って頂いてかまいませんが、sales-info@classcat.com までご一報いただけると嬉しいです。

 

無料 Web セミナー開催中 クラスキャット主催 人工知能 & ビジネス Web セミナー

人工知能とビジネスをテーマに WEB セミナーを定期的に開催しています。
スケジュールは弊社 公式 Web サイト でご確認頂けます。
  • お住まいの地域に関係なく Web ブラウザからご参加頂けます。事前登録 が必要ですのでご注意ください。
  • ウェビナー運用には弊社製品「ClassCat® Webinar」を利用しています。
クラスキャットは人工知能・テレワークに関する各種サービスを提供しております :

人工知能研究開発支援 人工知能研修サービス テレワーク & オンライン授業を支援
PoC(概念実証)を失敗させないための支援 (本支援はセミナーに参加しアンケートに回答した方を対象としています。)

お問合せ : 本件に関するお問い合わせ先は下記までお願いいたします。

株式会社クラスキャット セールス・マーケティング本部 セールス・インフォメーション
E-Mail:sales-info@classcat.com  ;  WebSite: https://www.classcat.com/  ;  Facebook

 

ノートブック : パイプラインの利用

transformers v2.3.0 で新たに導入された、パイプライン は以下を含む様々な下流タスクに渡る推論を行なうための高位の、使いやすい、API を提供します :

  • センテンス分類 (センチメント分析) : センテンス全体がポジティブかネガティブかを示します、つまり二値分類タスクかロジスティック回帰タスクです。

  • トークン分類 (固有表現認識品詞タギング) : 入力の各サブエンティティ (トークン) について、ラベルを割当てます、つまり分類タスクです。

  • 質問応答 : タプル (質問, コンテキスト) が提供されたとき、モデルは質問に答えるコンテンツのテキストの範囲を見つける必要があります。

  • マスク Filling : 提供されたコンテキストに関してマスクされた入力を埋める可能性のある単語を提示します。

  • 要約 : 入力記事をより短い記事に要約します。

  • 翻訳 : 入力をある言語から別の言語に翻訳します。

  • 特徴抽出 : 入力をデータから学習された、高位の多次元空間にマップします。

パイプラインは総ての NLP プロセスのプロセス全体をカプセル化します :

  1. トークン化 : 初期入力を … プロパティを持つ複数のサブエンティティに分割します (i.e. トークン)。

  2. 推論 : 総てのトークンをより意味のある表現にマップします。

  3. デコード : 基礎となるタスクのために最終的な出力を生成 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 の以下のドキュメントを翻訳した上で適宜、補足説明したものです:

* サンプルコードの動作確認はしておりますが、必要な場合には適宜、追加改変しています。
* ご自由にリンクを張って頂いてかまいませんが、sales-info@classcat.com までご一報いただけると嬉しいです。

 

無料 Web セミナー開催中 クラスキャット主催 人工知能 & ビジネス Web セミナー

人工知能とビジネスをテーマに WEB セミナーを定期的に開催しています。
スケジュールは弊社 公式 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 の以下のドキュメントを翻訳した上で適宜、補足説明したものです:

* サンプルコードの動作確認はしておりますが、必要な場合には適宜、追加改変しています。
* ご自由にリンクを張って頂いてかまいませんが、sales-info@classcat.com までご一報いただけると嬉しいです。

 

無料 Web セミナー開催中 クラスキャット主催 人工知能 & ビジネス Web セミナー

人工知能とビジネスをテーマに WEB セミナーを定期的に開催しています。
スケジュールは弊社 公式 Web サイト でご確認頂けます。
  • お住まいの地域に関係なく Web ブラウザからご参加頂けます。事前登録 が必要ですのでご注意ください。
  • ウェビナー運用には弊社製品「ClassCat® Webinar」を利用しています。
クラスキャットは人工知能・テレワークに関する各種サービスを提供しております :

人工知能研究開発支援 人工知能研修サービス テレワーク & オンライン授業を支援
PoC(概念実証)を失敗させないための支援 (本支援はセミナーに参加しアンケートに回答した方を対象としています。)

お問合せ : 本件に関するお問い合わせ先は下記までお願いいたします。

株式会社クラスキャット セールス・マーケティング本部 セールス・インフォメーション
E-Mail:sales-info@classcat.com  ;  WebSite: https://www.classcat.com/  ;  Facebook

 

 

ノートブック : Getting Started トークナイザー

Tokenization doesn’t have to be slow !

 

イントロダクション

機械学習や深層学習の自然言語処理モデルに深く潜る前に、総ての実践者は 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” のような単語のバリエーションはそれらの意味が非常に近い場合でさえも同じ識別子を共有しないでしょう。

 

サブトークンのトークン化

上で説明された問題を乗り越えるために、最近のワークは「サブトークン」トークン化を活用した、トークン化上で成されてきました。サブトークン は前の分割ストラテジーを単語を (データから学習された) 文法的にロジカルなサブコンポーネントに更に分解するように拡張します。

単語 catcats の前の例を取れば、単語 cats のサブトークン化は [cat, ##s] になります。ここで prefix “##” は初期入力のサブトークンを示します。そのような訓練アルゴリズムは英語コーパスに渡り “##ing”, “##ed” のようなサブトークンを抽出するかもしれません。

貴方が考えるかもしれないように、「ピース」全体の組合せを活用したこの種類のサブトークン構築は (機械学習モデルを訓練するために持ち運ばなければならない) 語彙のサイズを削減します。一方で、一つのトークンが複数のサブトークンに分解されるかもしれないので、モデルの入力が増加して入力シークエンスの長さにわたる非線形の複雑さを伴うモデルについて問題になるかもしれません。

総てのトークン化アルゴリズムの中で、Transformers ベースの SoTA モデルで利用された幾つかのサブトークン・アルゴリズムにハイライトを当てることができます :

それら総てを通り抜けることはこのノートブックの範囲外ですので、それをどのように利用できるかにだけハイライトします。

 

@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 の以下のドキュメントを翻訳した上で適宜、補足説明したものです:

* サンプルコードの動作確認はしておりますが、必要な場合には適宜、追加改変しています。
* ご自由にリンクを張って頂いてかまいませんが、sales-info@classcat.com までご一報いただけると嬉しいです。

 

無料 Web セミナー開催中 クラスキャット主催 人工知能 & ビジネス Web セミナー

人工知能とビジネスをテーマに WEB セミナーを定期的に開催しています。
スケジュールは弊社 公式 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 of  Transformers
- [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 の以下のドキュメントを翻訳した上で適宜、補足説明したものです:

* サンプルコードの動作確認はしておりますが、必要な場合には適宜、追加改変しています。
* ご自由にリンクを張って頂いてかまいませんが、sales-info@classcat.com までご一報いただけると嬉しいです。

 

無料 Web セミナー開催中 クラスキャット主催 人工知能 & ビジネス Web セミナー

人工知能とビジネスをテーマに WEB セミナーを定期的に開催しています。
スケジュールは弊社 公式 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 セミナー

人工知能とビジネスをテーマに WEB セミナーを定期的に開催しています。
スケジュールは弊社 公式 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 もまた供給します。

ここに幾つかサンプルがあります :

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.ModuleTensorFlow tf.keras.Model で (貴方のバックエンドに依存します)、これらは普通に利用できます。このチュートリアル は古典的な PyTorch or TensorFlow 訓練ループでそのようなモデルをどのように統合するか、あるいは新しいデータセット上で素早く再調整するために Trainer API をどのように利用するかを説明しています。

 

何故私は transformers を使用するべきでしょう?

  1. 使いやすい最先端のモデル :
    • NLU と NLG タスク上の高パフォーマンス。
    • 教育者と実践者のための入門への低い障壁。
    • 学習すべき 3 つのクラスだけを持つ、ユーザが直面する少ない抽象。
    • 事前訓練されたモデルの総てを使用するための統一 API。

  2. より低い計算コスト、より小さいカーボンフットプリント (二酸化炭素排出量) :
    • 研究者は常に再訓練する代わりに訓練モデルを共有できます。
    • 実践者は計算時間とプロダクション・コストを減じることができます。
    • 幾つかは100 言語以上の、2,000 超の事前訓練モデルを持つ数十のアーキテクチャ。

  3. モデルのライフタイムの総てのパートのために適切なフレームワークを選択する :
    • 3 行のコードで最先端のモデルを訓練します。
    • TF2.0/PyTorch フレームワーク間で単一モデルを自在に移動する。
    • 訓練、評価、プロダクションのための適切なフレームワークをシームレスに選択する。

  4. 貴方のニーズにモデルやサンプルを容易にカスタマイズする :
    • 言及されるアーキテクチャの公式著者による結果を再生成するための各アーキテクチャのためのサンプル。
    • できる限り一貫してモデル内部を公開する。
    • モデルファイルは素早い実験のためにライブラリから独立的に利用できる。

 

何故 transformers を利用するべきではないのでしょう?

  • このライブラリはニューラルネットのためのビルディングブロックのモジュール・ツールボックスではありません。研究者が追加の抽象/ファイルに深入りすることなくモデルの各々の上で素早く iterate できるようにように、モデルファイルのコードは意図的な追加の抽象によりリファクタリングされません。

  • 訓練 API は任意のモデル上で動作することを意図されていませんがライブラリにより提供されるモデルで動作するように最適化されています。一般的な機械学習ループのためには、他のライブラリを利用するべきです。

  • 私達は可能な限り多くのユースケースを提示する努力をする一方で、examples フォルダ のスクリプトは単なるサンプルです。それらは貴方の特定の問題上でそのままでは動作しないでしょうし、それらを貴方のニーズに適応させるためにコードの数行を変更する必要があることが想定されます。

 

モデル・アーキテクチャ

Transformers により提供される 総てのモデルチェックポイント は huggingface.co モデルハブ からシームレスに統合されていて、そこではそれらは ユーザ組織 により直接アップロードされています。

チェックポイントの現在の数 : モデル 11,588 (as of 5/15/2021)

Transformers は現在以下のアーキテクチャを提供しています (それらの各々の高位な要約については ここ を参照) :

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

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

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

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

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

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

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

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

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

  10. BORT (from Alexa) released with the paper Optimal Subarchitecture Extraction For BERT by Adrian de Wynter and Daniel J. Perry.

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

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

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

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

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

  16. DeBERTa (from Microsoft Research) released with the paper DeBERTa: Decoding-enhanced BERT with Disentangled Attention by Pengcheng He, Xiaodong Liu, Jianfeng Gao, Weizhu Chen.

  17. DeBERTa-v2 (from Microsoft) released with the paper DeBERTa: Decoding-enhanced BERT with Disentangled Attention by Pengcheng He, Xiaodong Liu, Jianfeng Gao, Weizhu Chen.

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

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

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

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

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

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

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

  25. GPT (from OpenAI) released with the paper Improving Language Understanding by Generative Pre-Training by Alec Radford, Karthik Narasimhan, Tim Salimans and Ilya Sutskever.

  26. 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**.

  27. GPT Neo (from EleutherAI) released in the repository EleutherAI/gpt-neo by Sid Black, Stella Biderman, Leo Gao, Phil Wang and Connor Leahy.

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

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

  30. LED (from AllenAI) released with the paper Longformer: The Long-Document Transformer by Iz Beltagy, Matthew E. Peters, Arman Cohan.

  31. Longformer (from AllenAI) released with the paper Longformer: The Long-Document Transformer by Iz Beltagy, Matthew E. Peters, Arman Cohan.

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

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

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

  35. MarianMT Machine translation models trained using OPUS data by Jörg Tiedemann. The Marian Framework is being developed by the Microsoft Translator Team.

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

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

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

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

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

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

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

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

  44. Reformer (from Google Research) released with the paper Reformer: The Efficient Transformer by Nikita Kitaev, Łukasz Kaiser, Anselm Levskaya.

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

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

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

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

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

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

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

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

  53. XLM (from Facebook) released together with the paper Cross-lingual Language Model Pretraining by Guillaume Lample and Alexis Conneau.

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

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

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

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

  58. 新しいモデルを寄贈することを望みますか?新しいモデルを追加するプロセスに導く詳細なガイドとテンプレートを追加しました。レポジトリの templates フォルダでそれらを見つけることができます。貴方の PR を始める前にフィードバックを集めるために contributing ガイドライン を確認してそしてメンテナーにコンタクトするか issue をオープンすることを確実にしてください。

各モデルが PyTorch/TensorFlow/Flax の実装を持つか、あるいは Tokenizer により支援された関連する tokenizer を持つかを確認するためには、このテーブル を参照してください。

これらの実装は幾つかのデータセット上でテストされ (examples スクリプト参照) そして元の実装のパフォーマンスに一致するはずです。ドキュメントの Examples セクションでパフォーマンス上の更なる詳細を見つけられます。

 

更に学習する

セクション 説明
ドキュメント Full API ドキュメントとチュートリアル
タスク要約 Transformers によりサポートされるタスク
前処理チュートリアル モデルのためにデータを準備するための Tokenizer クラスを使用する
訓練と再調整 PyTorch/TensorFlow 訓練ループと Trainer API で Transformers により提供されるモデルを使用する
クイックツアー: 再調整/使用方法スクリプト 広範囲なタスク上でモデルを再調整するためのサンプル・スクリプト
モデル共有とアップロード 貴方の再調整モデルをアップロードしてコミュニティで共有する
マイグレーション pytorch-transformers or pytorch-pretrained-bert から Transformers にマイグレートする

 

Citation

(訳注: 原文 を参照してください。)

 

以上



ClassCat® Chatbot

人工知能開発支援
クラスキャットは 人工知能研究開発支援 サービスを提供しています :
  • テクニカルコンサルティングサービス
  • 実証実験 (プロトタイプ構築)
  • アプリケーションへの実装
  • 人工知能研修サービス
◆ お問合せ先 ◆
(株)クラスキャット
セールス・インフォメーション
E-Mail:sales-info@classcat.com

カテゴリー