大規模言語モデル (LLM) は、自然言語を理解して生成するように設計された (AI) のサブセットです。これらのモデルは、膨大な量のテキスト データでトレーニングされ、複雑なアルゴリズムを使用して言語のパターンを学習します。 LLM は、チャットボットから言語翻訳サービスに至るまで、さまざまなアプリケーションの開発に使用されてきました。この記事では、単一のコンピュータ上で LLM を作成する方法について説明し、ソース コードの例を示します。 人工知能 前提条件 始める前に、お使いのコンピューターが次の要件を満たしていることを確認することが重要です。 少なくとも 16 GB の RAM と 1 TB の無料ストレージを備えた強力なコンピューター 少なくとも 8GB のビデオ メモリを備えた、NVIDIA GeForce や AMD Radeon などの最新の GPU Ubuntu や CentOS などの Linux オペレーティング システム コマンド ライン インターフェイス (CLI) および Python プログラミング言語に関する基本的な知識 ステップ 1: Anaconda をインストールする Anaconda は、データ サイエンスと機械学習用の人気のあるオープンソース プラットフォームです。これには、LLM の作成に使用するさまざまなツールとライブラリが含まれています。 Anaconda をインストールするには、次の手順に従います。 公式 Web サイトから Anaconda インストーラーをダウンロードします: https://www.anaconda.com/products/individual ターミナルを開き、インストーラーがダウンロードされたディレクトリに移動します 次のコマンドを入力してインストーラーを実行します: bash Anaconda3–2021.11-Linux-x86_ 64.sh 画面の指示に従ってインストールを完了します ステップ 2: Python 環境を作成する LLM に必要なライブラリと依存関係をインストールするための Python 環境を作成します。環境を作成するには、次の手順に従います。 ターミナルを開き、次のコマンドを入力します: conda create — name lm python=3.8 「conda activate lm」と入力して環境をアクティブ化します。 ステップ 3: TensorFlow をインストールする TensorFlow は、機械学習モデルを構築およびトレーニングするためのオープンソース プラットフォームです。 TensorFlow を使用して LLM を作成します。 TensorFlow をインストールするには、次の手順に従います。 ターミナルに次のコマンドを入力します: pip install tensorflow TensorFlow を Python にインポートして、TensorFlow がインストールされていることを確認します。 import tensorflow as tf ステップ 4: 事前トレーニングされた LLM をダウンロードする LLM をゼロからトレーニングするには、膨大な計算能力と時間が必要です。幸いなことに、特定のユースケースに合わせて微調整できる事前トレーニング済みモデルが利用可能です。最も人気のある事前トレーニング済み LLM の 1 つは GPT-2 (Generative Pre-trained Transformer 2) です。事前トレーニングされた GPT-2 モデルをダウンロードするには、次の手順に従います。 ターミナルを開き、次のコマンドを入力します: git clone https://github.com/openai/gpt-2.git cd gpt-2 と入力して、gpt-2 ディレクトリに移動します。 「python 117M」と入力して、事前トレーニング済みモデルをダウンロードします。 download_model.py ステップ 5: 事前トレーニングされた LLM を微調整する 事前トレーニングされた LLM の微調整には、特定のタスク用に特定のデータセットでモデルをトレーニングすることが含まれます。この例では、テキスト生成タスクで事前トレーニングされた GPT-2 モデルを微調整します。モデルを微調整するには、次の手順に従います。 mkdir my_model と入力して、微調整モデル用の新しいディレクトリを作成します。 cd my_model と入力して、my_model ディレクトリに移動します。 「touch と入力して、新しい Python ファイルを作成します。 train.py」 テキスト エディタで ファイルを開き、次のコードを貼り付けます。 train.py import tensorflow as tf import numpy as np import os import json import random import time import argparse #Define the command-line arguments parser = argparse.ArgumentParser() parser.add_argument("--dataset_path", type=str, required=True, help="Path to the dataset") parser.add_argument("--model_path", type=str, required=True, help="Path to the pre-trained model") parser.add_argument("--output_path", type=str, required=True, help="Path to save the fine-tuned model") parser.add_argument("--batch_size", type=int, default=16, help="Batch size for training") parser.add_argument("--epochs", type=int, default=1, help="Number of epochs to train for") args = parser.parse_args() #Load the pre-trained GPT-2 model with open(os.path.join(args.model_path, "hparams.json"), "r") as f: hparams = json.load(f) model = tf.compat.v1.estimator.Estimator( model_fn=model_fn, model_dir=args.output_path, params=hparams, config=tf.compat.v1.estimator.RunConfig( save_checkpoints_steps=5000, keep_checkpoint_max=10, save_summary_steps=5000 )) #Define the input function for the dataset def input_fn(mode): dataset = tf.data.TextLineDataset(args.dataset_path) dataset = dataset.repeat() dataset = dataset.shuffle(buffer_size=10000) dataset = dataset.batch(args.batch_size) dataset = dataset.map(lambda x: tf.strings.substr(x, 0, hparams["n_ctx"])) iterator = dataset.make_one_shot_iterator() return iterator.get_next() #Define the training function def train(): for epoch in range(args.epochs): model.train(input_fn=lambda: input_fn(tf.estimator.ModeKeys.TRAIN)) print(f"Epoch {epoch+1} completed.") #Start the training train() 上記のコードでは、データセット パス、事前トレーニングされたモデル パス、出力パス、バッチ サイズ、トレーニング対象のエポック数のコマンド ライン引数を定義します。次に、事前トレーニングされた GPT-2 モデルを読み込み、データセットの入力関数を定義します。最後に、トレーニング関数を定義し、トレーニングを開始します。 ステップ 6: 微調整された LLM を使用してテキストを生成する LLM が微調整されたら、それを使用してテキストを生成できます。テキストを生成するには、次の手順に従います。 ターミナルを開き、「cd my_model」と入力して my_model ディレクトリに移動します。 「 と入力して、新しい Python ファイルを作成します。 touchgenerate.py」 テキスト エディタで ファイルを開き、次のコードを貼り付けます。 generate.py import tensorflow as tf import numpy as np import os import json import random import time import argparse #Define the command-line arguments parser = argparse.ArgumentParser() parser.add_argument("--model_path", type=str, required=True, help="Path to the fine-tuned model") parser.add_argument("--length", type=int, default=100, help="Length of the generated text") parser.add_argument("--temperature", type=float, default=0.7, help="Temperature for text generation") args = parser.parse_args() #Load the fine-tuned model with open(os.path.join(args.model_path, "hparams.json"), "r") as f: hparams = json.load(f) model_fn = model_fn(hparams, tf.estimator.ModeKeys.PREDICT) model = tf.compat.v1.estimator.Estimator( model_fn=model_fn, model_dir=args.model_path, params=hparams ) #Define the generation function def generate_text(length, temperature): start_token = "<|startoftext|>" tokens = tokenizer.convert_tokens_to_ids([start_token]) token_length = len(tokens) while token_length < length: prediction_input = np.array(tokens[-hparams["n_ctx"]:]) output = list(model.predict(input_fn=lambda: [[prediction_input]]))[0]["logits"] logits = output[-1] / temperature logits = logits - np.max(logits) probs = np.exp(logits) / np.sum(np.exp(logits)) token = np.random.choice(range(hparams["n_vocab"]), p=probs) tokens.append(token) token_length += 1 output_text = tokenizer.convert_ids_to_tokens(tokens) output_text = "".join(output_text).replace("▁", " ") output_text = output_text.replace(start_token, "") return output_text #Generate text text = generate_text(args.length, args.temperature) print(text) 上記のコードでは、微調整されたモデル パス、生成されるテキストの長さ、およびテキスト生成の温度のコマンド ライン引数を定義します。次に、微調整されたモデルをロードし、生成関数を定義します。最後に、generate_text 関数を使用してテキストを生成し、出力を印刷すれば完了です。 結論 この記事では、TensorFlow と GPT-2 アーキテクチャを使用して 1 台のコンピューター上で大規模言語モデル (LLM) を作成する方法を学びました。まず、TensorFlow をインストールし、OpenAI GitHub リポジトリから GPT-2 コードをダウンロードしました。次に、データセットで GPT-2 モデルをトレーニングし、同じデータセットを使用して事前トレーニングされた GPT-2 モデルを微調整しました。最後に、微調整された LLM を使用してテキストを生成しました。 この記事の手順に従うことで、独自の LLM を作成し、言語翻訳、チャットボット、コンテンツ生成などのさまざまなタスク用のテキストを生成できます。 参考文献 Radford, A.、Wu, J.、Child, R.、Luan, D.、Amodei, D.、Sutskever, I. (2019)。言語モデルは教師なしのマルチタスク学習者です。 OpenAI ブログ、1(8)、9. オープンAI。 (2019年)。 GPT-2: 言語モデルは教師なしのマルチタスク学習者です。ギットハブ。 から取得。 https://github.com/openai/gpt-2 テンソルフロー。 (2021年)。 TensorFlow: 誰でも使えるオープンソースの機械学習フレームワーク。 から取得。 https://www.tensorflow.org/ ブラウン、TB、マン、B.、ライダー、N.、サブビア、M.、カプラン、J.、ダリワル、P.、… & アモデイ、D. (2020)。言語モデルは少数回の学習です。 arXiv プレプリント arXiv:2005.14165。 こちらでも公開しております。