Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
huggingface
GitHub Repository: huggingface/notebooks
Path: blob/main/transformers_doc/ja/tensorflow/language_modeling.ipynb
4535 views
Kernel: Unknown Kernel

Causal language modeling

言語モデリングには、因果的モデリングとマスクされた言語モデリングの 2 つのタイプがあります。このガイドでは、因果関係のある言語モデリングについて説明します。 因果言語モデルはテキスト生成によく使用されます。これらのモデルは、次のようなクリエイティブなアプリケーションに使用できます。 独自のテキスト アドベンチャーを選択するか、Copilot や CodeParrot などのインテリジェントなコーディング アシスタントを選択します。

#@title from IPython.display import HTML HTML('<iframe width="560" height="315" src="https://www.youtube.com/embed/Vpjb1lu0MDk?rel=0&amp;controls=0&amp;showinfo=0" frameborder="0" allowfullscreen></iframe>')

因果言語モデリングは、一連のトークン内の次のトークンを予測します。モデルは、次のトークンにのみ対応できます。 左。これは、モデルが将来のトークンを認識できないことを意味します。 GPT-2 は因果的言語モデルの一例です。

このガイドでは、次の方法を説明します。

  1. ELI5r/askscience サブセットで DistilGPT2 を微調整します。 /huggingface.co/datasets/eli5) データセット。

  2. 微調整したモデルを推論に使用します。

[removed]

このタスクと互換性のあるすべてのアーキテクチャとチェックポイントを確認するには、タスクページ を確認することをお勧めします。u

始める前に、必要なライブラリがすべてインストールされていることを確認してください。

pip install transformers datasets evaluate

モデルをアップロードしてコミュニティと共有できるように、Hugging Face アカウントにログインすることをお勧めします。プロンプトが表示されたら、トークンを入力してログインします。

from huggingface_hub import notebook_login notebook_login()

Load ELI5 dataset

まず、ELI5 データセットの r/askscience サブセットの小さいサブセットを 🤗 データセット ライブラリからロードします。 これにより、完全なデータセットのトレーニングにさらに時間を費やす前に、実験してすべてが機能することを確認する機会が得られます。

from datasets import load_dataset eli5 = load_dataset("eli5", split="train_asks[:5000]")

train_test_split メソッドを使用して、データセットの train_asks をトレイン セットとテスト セットに分割します。

eli5 = eli5.train_test_split(test_size=0.2)

次に、例を見てみましょう。

eli5["train"][0]
{'answers': {'a_id': ['c3d1aib', 'c3d4lya'], 'score': [6, 3], 'text': ["The velocity needed to remain in orbit is equal to the square root of Newton's constant times the mass of earth divided by the distance from the center of the earth. I don't know the altitude of that specific mission, but they're usually around 300 km. That means he's going 7-8 km/s.\n\nIn space there are no other forces acting on either the shuttle or the guy, so they stay in the same position relative to each other. If he were to become unable to return to the ship, he would presumably run out of oxygen, or slowly fall into the atmosphere and burn up.", "Hope you don't mind me asking another question, but why aren't there any stars visible in this photo?"]}, 'answers_urls': {'url': []}, 'document': '', 'q_id': 'nyxfp', 'selftext': '_URL_0_\n\nThis was on the front page earlier and I have a few questions about it. Is it possible to calculate how fast the astronaut would be orbiting the earth? Also how does he stay close to the shuttle so that he can return safely, i.e is he orbiting at the same speed and can therefore stay next to it? And finally if his propulsion system failed, would he eventually re-enter the atmosphere and presumably die?', 'selftext_urls': {'url': ['http://apod.nasa.gov/apod/image/1201/freeflyer_nasa_3000.jpg']}, 'subreddit': 'askscience', 'title': 'Few questions about this space walk photograph.', 'title_urls': {'url': []}}

これは多くのことのように見えるかもしれませんが、実際に関心があるのはtextフィールドだけです。言語モデリングの優れている点 タスクでは、次の単語がラベル * であるため、ラベル (教師なしタスクとも呼ばれます) は必要ありません。

Preprocess

#@title from IPython.display import HTML HTML('<iframe width="560" height="315" src="https://www.youtube.com/embed/ma1TrR7gE7I?rel=0&amp;controls=0&amp;showinfo=0" frameborder="0" allowfullscreen></iframe>')

次のステップは、textサブフィールドを処理するために DistilGPT2 トークナイザーをロードすることです。

from transformers import AutoTokenizer tokenizer = AutoTokenizer.from_pretrained("distilbert/distilgpt2")

上の例からわかるように、textフィールドは実際にはanswers内にネストされています。つまり、次のことが必要になります。 flatten メソッドを使用して、ネストされた構造から text サブフィールドを抽出します。

eli5 = eli5.flatten() eli5["train"][0]
{'answers.a_id': ['c3d1aib', 'c3d4lya'], 'answers.score': [6, 3], 'answers.text': ["The velocity needed to remain in orbit is equal to the square root of Newton's constant times the mass of earth divided by the distance from the center of the earth. I don't know the altitude of that specific mission, but they're usually around 300 km. That means he's going 7-8 km/s.\n\nIn space there are no other forces acting on either the shuttle or the guy, so they stay in the same position relative to each other. If he were to become unable to return to the ship, he would presumably run out of oxygen, or slowly fall into the atmosphere and burn up.", "Hope you don't mind me asking another question, but why aren't there any stars visible in this photo?"], 'answers_urls.url': [], 'document': '', 'q_id': 'nyxfp', 'selftext': '_URL_0_\n\nThis was on the front page earlier and I have a few questions about it. Is it possible to calculate how fast the astronaut would be orbiting the earth? Also how does he stay close to the shuttle so that he can return safely, i.e is he orbiting at the same speed and can therefore stay next to it? And finally if his propulsion system failed, would he eventually re-enter the atmosphere and presumably die?', 'selftext_urls.url': ['http://apod.nasa.gov/apod/image/1201/freeflyer_nasa_3000.jpg'], 'subreddit': 'askscience', 'title': 'Few questions about this space walk photograph.', 'title_urls.url': []}

answers接頭辞で示されるように、各サブフィールドは個別の列になり、textフィールドはリストになりました。その代わり 各文を個別にトークン化する場合は、リストを文字列に変換して、それらをまとめてトークン化できるようにします。

以下は、各例の文字列のリストを結合し、結果をトークン化する最初の前処理関数です。

def preprocess_function(examples): return tokenizer([" ".join(x) for x in examples["answers.text"]])

この前処理関数をデータセット全体に適用するには、🤗 Datasets map メソッドを使用します。 map 関数を高速化するには、batched=True を設定してデータセットの複数の要素を一度に処理し、num_proc でプロセスの数を増やします。不要な列を削除します。

tokenized_eli5 = eli5.map( preprocess_function, batched=True, num_proc=4, remove_columns=eli5["train"].column_names, )

このデータセットにはトークン シーケンスが含まれていますが、その一部はモデルの最大入力長よりも長くなります。

2 番目の前処理関数を使用して、

  • すべてのシーケンスを連結します

  • 連結されたシーケンスをblock_sizeで定義された短いチャンクに分割します。これは、最大入力長より短く、GPU RAM に十分な長さである必要があります。

block_size = 128 def group_texts(examples): # Concatenate all texts. concatenated_examples = {k: sum(examples[k], []) for k in examples.keys()} total_length = len(concatenated_examples[list(examples.keys())[0]]) # We drop the small remainder, we could add padding if the model supported it instead of this drop, you can # customize this part to your needs. if total_length >= block_size: total_length = (total_length // block_size) * block_size # Split by chunks of block_size. result = { k: [t[i : i + block_size] for i in range(0, total_length, block_size)] for k, t in concatenated_examples.items() } result["labels"] = result["input_ids"].copy() return result

Apply the group_texts function over the entire dataset:

lm_dataset = tokenized_eli5.map(group_texts, batched=True, num_proc=4)

次に、DataCollat​​orForLanguageModeling を使用してサンプルのバッチを作成します。 動的にパディングする方が効率的です。 データセット全体を最大長までパディングするのではなく、照合中にバッチ内の文を最長の長さにします。

シーケンス終了トークンをパディング トークンとして使用し、mlm=False を設定します。これは、入力を 1 要素分右にシフトしたラベルとして使用します。

from transformers import DataCollatorForLanguageModeling data_collator = DataCollatorForLanguageModeling(tokenizer=tokenizer, mlm=False, return_tensors="tf")

Train

[removed]

Keras を使用したモデルの微調整に慣れていない場合は、基本チュートリアル をご覧ください。

TensorFlow でモデルを微調整するには、オプティマイザー関数、学習率スケジュール、およびいくつかのトレーニング ハイパーパラメーターをセットアップすることから始めます。
from transformers import create_optimizer, AdamWeightDecay optimizer = AdamWeightDecay(learning_rate=2e-5, weight_decay_rate=0.01)

次に、TFAutoModelForCausalLM を使用して DistilGPT2 をロードできます。

from transformers import TFAutoModelForCausalLM model = TFAutoModelForCausalLM.from_pretrained("distilbert/distilgpt2")

prepare_tf_dataset() を使用して、データセットを tf.data.Dataset 形式に変換します。

tf_train_set = model.prepare_tf_dataset( lm_dataset["train"], shuffle=True, batch_size=16, collate_fn=data_collator, ) tf_test_set = model.prepare_tf_dataset( lm_dataset["test"], shuffle=False, batch_size=16, collate_fn=data_collator, )

compile を使用してトレーニング用のモデルを設定します。 Transformers モデルにはすべてデフォルトのタスク関連の損失関数があるため、次の場合を除き、損失関数を指定する必要はないことに注意してください。

import tensorflow as tf model.compile(optimizer=optimizer) # No loss argument!

これは、モデルとトークナイザーを PushToHubCallback でプッシュする場所を指定することで実行できます。

from transformers.keras_callbacks import PushToHubCallback callback = PushToHubCallback( output_dir="my_awesome_eli5_clm-model", tokenizer=tokenizer, )

ついに、モデルのトレーニングを開始する準備が整いました。トレーニングおよび検証データセット、エポック数、コールバックを指定して fit を呼び出し、モデルを微調整します。

model.fit(x=tf_train_set, validation_data=tf_test_set, epochs=3, callbacks=[callback])

トレーニングが完了すると、モデルは自動的にハブにアップロードされ、誰でも使用できるようになります。

[removed]

因果言語モデリング用にモデルを微調整する方法のより詳細な例については、対応するドキュメントを参照してください。 PyTorch ノートブック または TensorFlow ノートブック

Inference

モデルを微調整したので、それを推論に使用できるようになりました。

テキストを生成するプロンプトを考え出します。

prompt = "Somatic hypermutation allows the immune system to"

推論用に微調整されたモデルを試す最も簡単な方法は、それを pipeline() で使用することです。モデルを使用してテキスト生成用のpipelineをインスタンス化し、それにテキストを渡します。

from transformers import pipeline generator = pipeline("text-generation", model="my_awesome_eli5_clm-model") generator(prompt)
[{'generated_text': "Somatic hypermutation allows the immune system to be able to effectively reverse the damage caused by an infection.\n\n\nThe damage caused by an infection is caused by the immune system's ability to perform its own self-correcting tasks."}]

テキストをトークン化し、input_idsを TensorFlow テンソルとして返します。

from transformers import AutoTokenizer tokenizer = AutoTokenizer.from_pretrained("my_awesome_eli5_clm-model") inputs = tokenizer(prompt, return_tensors="tf").input_ids

~transformers.generation_tf_utils.TFGenerationMixin.generate メソッドを使用して要約を作成します。さまざまなテキスト生成戦略と生成を制御するためのパラメーターの詳細については、テキスト生成戦略 ページを参照してください。

from transformers import TFAutoModelForCausalLM model = TFAutoModelForCausalLM.from_pretrained("my_awesome_eli5_clm-model") outputs = model.generate(input_ids=inputs, max_new_tokens=100, do_sample=True, top_k=50, top_p=0.95)

生成されたトークン ID をデコードしてテキストに戻します。

tokenizer.batch_decode(outputs, skip_special_tokens=True)
['Somatic hypermutation allows the immune system to detect the presence of other viruses as they become more prevalent. Therefore, researchers have identified a high proportion of human viruses. The proportion of virus-associated viruses in our study increases with age. Therefore, we propose a simple algorithm to detect the presence of these new viruses in our samples as a sign of improved immunity. A first study based on this algorithm, which will be published in Science on Friday, aims to show that this finding could translate into the development of a better vaccine that is more effective for']