メインコンテンツまでスキップ

Hugging Face モデルを 1 つの GPU 用に微調整

この記事では、1 つの GPU で Hugging Face transformers ライブラリを使用して Hugging Face モデルをファインチューンする方法について説明します。 また、レイクハウスからデータを読み込み、モデルを MLflow にログ記録するための Databricks 固有の推奨事項も含まれているため、Databricks でモデルを使用および管理できます。

Hugging Face transformers ライブラリには、 Transformers モデルの読み込みとファインチューニングを可能にする Trainer ユーティリティと Auto Model クラスが用意されています。

これらのツールは、簡単な変更を加えて次のタスクに使用できます。

  • ファインチューンするモデルの読み込み。
  • Hugging Face Transformersトレーナーユーティリティの構成を構築します。
  • 1 つの GPU でトレーニングを実行する。

「Hugging Faceトランスフォーマーとは」を参照してください。

必要条件

Hugging Face データセットのトークン化

Hugging Face Transformers モデルは、ダウンロードされたデータ内のテキストではなく、トークン化された入力を期待しています。 基本モデルとの互換性を確保するには、基本モデルから読み込まれた AutoTokenizer を使用します。 Hugging Face datasets を使用すると、トレーニングデータとテストデータの両方にトークナイザーを一貫して直接適用できます。

例えば:

Python
from transformers import AutoTokenizer

tokenizer = AutoTokenizer.from_pretrained(base_model)
def tokenize_function(examples):
return tokenizer(examples["text"], padding=False, truncation=True)

train_test_tokenized = train_test_dataset.map(tokenize_function, batched=True)

トレーニング設定のセットアップ

Hugging Face トレーニング設定ツールを使用して 、トレーナーを構成できます。 トレーナー クラスでは、ユーザーに次のものを提供する必要があります。

  • メトリクス
  • ベースモデル
  • トレーニング構成

コンピュートというデフォルトの loss メトリクスに加えて評価メトリクス Trainer 設定することができます。 次の例は、 accuracy をメトリクスとして追加する方法を示しています。

Python
import numpy as np
import evaluate
metric = evaluate.load("accuracy")
def compute_metrics(eval_pred):
logits, labels = eval_pred
predictions = np.argmax(logits, axis=-1)
return metric.compute(predictions=predictions, references=labels)

NLP の Auto Model クラスを使用して、タスクに適したモデルを読み込みます。

テキスト分類の場合は、 AutoModelForSequenceClassification を使用して、テキスト分類の基本モデルを読み込みます。 モデルを作成するときは、データセットの準備中に作成されたクラスの数とラベル マッピングを指定します。

Python
from transformers import AutoModelForSequenceClassification
model = AutoModelForSequenceClassification.from_pretrained(
base_model,
num_labels=len(label2id),
label2id=label2id,
id2label=id2label
)

次に、トレーニング設定を作成します。 TrainingArguments クラスでは、出力ディレクトリ、評価方法、学習率、およびその他のパラメーターを指定できます。

Python
from transformers import TrainingArguments, Trainer
training_args = TrainingArguments(output_dir=training_output_dir, evaluation_strategy="epoch")

データ コレーターを使用すると、トレーニング データセットと評価データセットの入力がバッチ処理されます。DataCollatorWithPadding は、テキスト分類のベースライン パフォーマンスを向上させます。

Python
from transformers import DataCollatorWithPadding
data_collator = DataCollatorWithPadding(tokenizer)

これらすべてのパラメーターが構築されたら、 Trainer.

Python
trainer = Trainer(
model=model,
args=training_args,
train_dataset=train_test_dataset["train"],
eval_dataset=train_test_dataset["test"],
compute_metrics=compute_metrics,
data_collator=data_collator,
)

MLflow へのトレーニングとログ記録

Hugging Face は MLflow と適切に連携し、 MLflowCallback を使用してモデル トレーニング中にメトリクスを自動的にログに記録します。 ただし、トレーニング済みのモデルは自分でログに記録する必要があります。

MLflow の実行でトレーニングをラップします。 これにより、トークナイザーとトレーニング済みモデルから Transformers パイプラインが構築され、ローカル ディスクに書き込まれます。 最後に、 mlflow.transformers.log_model を使用してモデルを MLflow にログ記録します。

Python
from transformers import pipeline

with mlflow.start_run() as run:
trainer.train()
trainer.save_model(model_output_dir)
pipe = pipeline("text-classification", model=AutoModelForSequenceClassification.from_pretrained(model_output_dir), batch_size=1, tokenizer=tokenizer)
model_info = mlflow.transformers.log_model(
transformers_model=pipe,
artifact_path="classification",
input_example="Hi there!",
)

パイプラインを作成する必要がない場合は、トレーニングで使用されるコンポーネントをディクショナリに送信できます。

Python
model_info = mlflow.transformers.log_model(
transformers_model={"model": trainer.model, "tokenizer": tokenizer},
task="text-classification",
artifact_path="text_classifier",
input_example=["MLflow is great!", "MLflow on Databricks is awesome!"],
)

推論のためにモデルを読み込む

モデルがログに記録され、準備ができている場合、推論のためにモデルを読み込むことは、MLflow でラップされた事前トレーニング済みモデルを読み込むことと同じです。

Python
logged_model = "runs:/{run_id}/{model_artifact_path}".format(run_id=run.info.run_id, model_artifact_path=model_artifact_path)

# Load model as a Spark UDF. Override result_type if the model does not return double values.
loaded_model_udf = mlflow.pyfunc.spark_udf(spark, model_uri=logged_model, result_type='string')

test = test.select(test.text, test.label, loaded_model_udf(test.text).alias("prediction"))
display(test)

詳細については、「Mosaic AI Model Servingを使用したモデルのデプロイ」を参照してください。

一般的な CUDA エラーのトラブルシューティング

このセクションでは、一般的な CUDA エラーと、その解決方法に関するガイダンスについて説明します。

OutOfMemoryError: CUDA がメモリ不足です

大規模なモデルをトレーニングする場合、CUDA のメモリ不足エラーがよく発生することがあります。

例:

Console
OutOfMemoryError: CUDA out of memory. Tried to allocate 20.00 MiB (GPU 0; 14.76 GiB total capacity; 666.34 MiB already allocated; 17.75 MiB free; 720.00 MiB reserved in total by PyTorch) If reserved memory is >> allocated memory try setting max_split_size_mb to avoid fragmentation.  See documentation for Memory Management and PYTORCH_CUDA_ALLOC_CONF.

このエラーを解決するには、次の推奨事項を試してください。

  • トレーニングのバッチ サイズを小さくします。 TrainingArgumentsper_device_train_batch_size値を減らすことができます。

  • 精度の低いトレーニングを使用します。 TrainingArgumentsfp16=True を設定できます。

  • TrainingArguments で gradient_accumulation_steps を使用して、全体的なバッチ サイズを効果的に増やします。

  • 8ビットのAdamオプティマイザーを使用してください

  • トレーニング前に GPU メモリをクリーンアップします。 場合によっては、GPUメモリが未使用のコードによって占有されている場合があります。

    Python
    from numba import cuda
    device = cuda.get_current_device()
    device.reset()

CUDA カーネル エラー

トレーニングを実行すると、CUDA カーネル エラーが発生する可能性があります。

例:

Console
CUDA kernel errors might be asynchronously reported at some other API call, so the stacktrace below might be incorrect.

For debugging, consider passing CUDA_LAUNCH_BLOCKING=1.

トラブルシューティングするには:

  • CPU でコードを実行してみて、エラーが再現可能かどうかを確認してください。

  • 別のオプションは、次のように設定して、より優れたトレースバックを取得することですCUDA_LAUNCH_BLOCKING=1

    Python
    import os
    os.environ["CUDA_LAUNCH_BLOCKING"] = "1"

ノートブック: 1 つの GPU でテキスト分類を微調整

コード例をすばやく使用するために、このサンプル ノートブックでは、テキスト分類用にモデルをファインチューンするためのエンドツーエンドの例を提供します。 この記事の以降のセクションでは、 DatabricksでHugging Face を使用してファインチューンする方法について詳しく説明します。

ファインチューニング Hugging Face text classification models ノートブック

Open notebook in new tab

追加のリソース

詳細については、Databricks の Hugging Face をご覧ください。