catch-img

【Llama2】GPUSOROBANでの使い方(Ubuntu)

この記事では、GPUSOROBANの環境を使ってLlama2によるテキストを生成(推論)する方法について紹介しています。


目次[非表示]

  1. 1.Llama2とは
  2. 2.Metaへのモデル利用申請とHuggingFaceの設定
  3. 3.実行環境
  4. 4.Jupyter Labを起動
  5. 5.ライブラリのインストール
  6. 6.モデルの設定
  7. 7.生成タスク1
    1. 7.1.プロンプトの実行
    2. 7.2.生成結果
    3. 7.3.日本語翻訳
  8. 8.生成タスク2
    1. 8.1.プロンプトの実行
    2. 8.2.生成結果
    3. 8.3.日本語翻訳
  9. 9.生成タスク3
    1. 9.1.プロンプトの実行
    2. 9.2.生成結果
    3. 9.3.日本語翻訳
  10. 10.LLMならGPUクラウド
  11. 11.まとめ


Llama2とは

Llama2(Large Language Model Meta AI 2/ラマツー)とは、Facebookを運営するMeta社が開発した言語生成AI(LLM)で、OpenAI社のChatGPTに匹敵するの性能を持っています。


Llama2の特徴としては、軽量モデルで高性能、そして無料で使えるオープンソースであるため、開発者にとって扱いやすいモデルになっています。

llama2


Llama2の詳細については、以下の記事で解説しています。


  Llama2とは?使い方・日本語性能・商用利用について解説 | 初心者ガイド この記事では、Llama2について幅広く解説しています。Llama2の性能や安全性、商用利用、日本語対応、様々な環境での使い方などに触れています。 業界最安級GPUクラウド | GPUSOROBAN



Metaへのモデル利用申請とHuggingFaceの設定

Llama2を利用する前に、Meta社へのモデル利用の申請とHuggingFaceの設定の準備を行います。
設定が完了したら、HuggingFaceのアクセストークンを後で使いますので、メモしておきます。

Metaへのモデル利用申請・HuggingFaceの設定方法について、以下の記事で詳しく解説しています。


  【Llama2】Meta・HuggingFaceへの利用申請 この記事では、Llama2を使用するためのMeta・HuggingFaceへの利用申請について解説しています。 業界最安級GPUクラウド | GPUSOROBAN


実行環境

この記事ではGPUクラウドサービス(GPUSOROBAN)を使用しました。

  • インスタンス名:t80-1-a-exlarge-ubs22-i
  • GPU:NVIDIA A100 80GB x 1
  • OS :Ubuntu 22.04
  • CUDA:11.7
  • Jupyter Labプリインストール


GPUSOROBANはメガクラウドの50%以上安いGPUクラウドサービスです。

GPUSOROBANの使い方は以下の記事で解説しています。

  会員登録~インスタンス接続手順 | GPUSOROBAN GPUSOROBANの会員登録からインスタンス作成・接続までの手順を詳しく解説する記事です。会員登録、電話番号認証、SSHキー作成、インスタンスの作成、キーの設置、ターミナルからのインスタンス接続までの流れを説明しています。 業界最安級GPUクラウド | GPUSOROBAN


Jupyter Labを起動

GPUSOROBANのインスタンスに接続したら、次のコマンドを実行し、Jupyter Labを起動します。

jupyter lab --ip='*' --port=8888 --NotebookApp.token='' --NotebookApp.password='' --no-browser

llama-gpusoroban


ブラウザの検索窓に"localhost:8888"を入力すると、Jupyter Labをブラウザで表示できます。

localhost:8888


Jupyter Labのホーム画面で[Python3 ipykernel]を選択し、Notebookを開きます。

llama-gpusoroban


Jupyter Labの使い方が分からない方は、以下の記事が参考になります。


プリインストールされたJupyter Labを使用する場合

  プリインストールの利用方法(Docker、PyTorch、TensorFlow、JupyterLab)| GPUSOROBAN GPUSOROBAN高速コンピューティングのプリインストールの利用方法を説明しています。PyTorchやTensosrFlow、JupyterLabがプリインストールされたインスタンスを使うことで環境構築にかかる時間を削減できます。 業界最安級GPUクラウド | GPUSOROBAN


Jupyter Labを新しくインストールして使う場合


  Jupyter Labのインストール(Ubuntu)| GPUSOROBAN GPUSOROBANのUbuntuインスタンスにJupyter Labをインストールする方法を紹介しています。高性能なGPUインスタンスを利用したクラウドサービスGPUSOROBANでJupyter Labを動作させることが可能です。 業界最安級GPUクラウド | GPUSOROBAN


ライブラリのインストール

JupyterLabのNotebookのコードセルで次のコマンドを実行し、必要なパッケージをインストールします。

pip install transformers sentencepiece accelerate bitsandbytes scipy

llama-gpusoroban


必要なライブラリをインポートします。

import torch
from torch import cuda,bfloat16
from transformers import AutoTokenizer,AutoModelForCausalLM
import transformers


モデルの設定

HuggingFaceのtransformersというライブラリを使用してモデルの準備をします。

HuggingFaceで利用申請したLlamaのモデルを読み込みます。

この段階でモデルがGPUメモリにロードされますので、しばらく時間がかかります。

model_id = "meta-llama/Llama-2-70b-chat-hf"


この記事ではLlama-2-70b-chat-hfのパラメータ70bのチャットモデルを使用していますが、他のモデルを使いたい場合は表を参考に適宜model_idを変更してください。

model_id

GPUメモリ(VRAM)使用量
※モデルには4bit量子化を使用

ストレージ使用

使用したGPU

meta-llama/Llama-2-7b-hf

6.7GB

13GB

NVIDIA A4000 16GB x 1

meta-llama/Llama-2-13b-hf

10.3GB

25GB

NVIDIA A4000 16GB x 1

meta-llama/Llama-2-70b-hf

37.9GB

129GB

NVIDIA A100 80GB x 1

meta-llama/Llama-2-7b-chat-hf

6.7GB

13GB

NVIDIA A4000 16GB x 1

meta-llama/Llama-2-13b-chat-hf

10.1GB

25GB

NVIDIA A4000 16GB x 1

meta-llama/Llama-2-70b-chat-hf

37.9GB

129GB

NVIDIA A100 80GB x 1


HuggingFaceにアクセスするためのトークンを設定します。

token = 'hf_****************************'


HuggignFaceでのアクセストークンの発行方法は以下の記事で解説しています。


  【Llama2】Meta・HuggingFaceへの利用申請 この記事では、Llama2を使用するためのMeta・HuggingFaceへの利用申請について解説しています。 業界最安級GPUクラウド | GPUSOROBAN


モデルの量子化の設定を行います。

量子化は、モデルのパラメータや活性化関数などを低bitに変換する技術で、モデルサイズを軽量化することができます。

quant_config = transformers.BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_quant_type='nf4',
    bnb_4bit_use_double_quant=True,
    bnb_4bit_compute_dtype=bfloat16
)


この記事では、モデルのパラメータを4bitでロードするように設定し、4bitの計算に使用されるデータ型をBFloat16に設定しています。

モデルを読み込みます。初回はモデルをダウンロードするため時間がかかりますが、2回目以降はモデルの読み込みだけになりますので、時間はかかりません。

model = transformers.AutoModelForCausalLM.from_pretrained(
    model_id,
    trust_remote_code=True,
    token=token,
    quantization_config=quant_config,
    device_map="auto"
)



トークナイザーを読み込みます。

tokenizer = AutoTokenizer.from_pretrained(
    model_id,
    token=token
)


transformersライブラリの pipeline 関数を使用して、テキスト生成のためのパイプラインを構築します。

pipeline = transformers.pipeline(
    model=model,
    tokenizer=tokenizer,
    task="text-generation",
    repetition_penalty=1.1
)


生成タスク1

プロンプトの実行

Tokenizerのeos_token_idメソッドについて質問をしてみます。

prompt = """USER:Please tell me about tokenizer.eos_token_id.
SYSTEM:"""
sequences = pipeline(
    prompt,
    do_sample=True,
    temperature=0.8,
    top_p=0.9,
    top_k=40,
    num_return_sequences=1,
    eos_token_id=tokenizer.eos_token_id,
    max_length=300,
)
print(sequences[0]["generated_text"])


生成結果

Tokenizerのeos_token_idメソッドに関する適切な回答が得られました。

便宜上max_length=300のトークン数で生成していますが、生成するトークン数の上限を増やすこともできます。

USER:Please tell me about tokenizer.eos_token_id.
SYSTEM:The `tokenizer.eos_token_id` property is a token ID that represents the end-of-stream (EOS) token in a given tokenizer. The EOS token is typically the last token in a sequence of tokens generated by the tokenizer, and it indicates the end of the input sequence.

For example, if you are using the `google/text-to-sequence` tokenizer to generate tokens for a sentence, the EOS token will be the last token in the sequence. You can use the `tokenizer.eos_token_id` property to identify this token and indicate that the input sequence has been fully processed.

Here's an example code snippet that demonstrates how to use the `tokenizer.eos_token_id` property:
```
from transformers import AutoTokenizer, AutoModelForSequenceClassification

# Load the tokenizer
tokenizer = AutoTokenizer.from_pretrained('google/text-to-sequence')

# Generate tokens for a sentence
tokens = tokenizer.encode("This is a sample sentence", return_tensors='pt')

# Get the EOS token ID
eos_token_id = tokenizer.eos_token_id

print(f"E


日本語翻訳

USER: tokenizer.eos_token_idについて教えてください。

SYSTEM: tokenizer.eos_token_idプロパティは、与えられたトークナイザー内で終了トークン(EOS)を表すトークンIDです。EOSトークンは通常、トークナイザーによって生成されたトークンのシーケンスの最後のトークンであり、入力シーケンスの終了を示します。

例えば、google/text-to-sequenceトークナイザーを使用して文のトークンを生成する場合、EOSトークンはシーケンス内の最後のトークンになります。tokenizer.eos_token_idプロパティを使用してこのトークンを識別し、入力シーケンスが完全に処理されたことを示すことができます。

以下は、tokenizer.eos_token_idプロパティの使用方法を示すコードスニペットの例です:

python
from transformers import AutoTokenizer, AutoModelForSequenceClassification

# トークナイザーの読み込み
tokenizer = AutoTokenizer.from_pretrained('google/text-to-sequence')

# 文のトークンを生成
tokens = tokenizer.encode("This is a sample sentence", return_tensors='pt')

# EOSトークンのIDを取得
eos_token_id = tokenizer.eos_token_id

print(f"E


生成タスク2

プロンプトの実行

AutoTokenizer.from_pretrainedメソッドについて質問をしてみます。

prompt = """USER:Please tell me about AutoTokenizer.from_pretrained.
SYSTEM:"""
sequences = pipeline(
    prompt,
    do_sample=True,
    temperature=0.8,
    top_p=0.9,
    top_k=40,
    num_return_sequences=1,
    eos_token_id=tokenizer.eos_token_id,
    max_length=300,
)
print(sequences[0]["generated_text"])


生成結果

 AutoTokenizer.from_pretrainedメソッドに関する適切な回答が得られました。

USER:Please tell me about AutoTokenizer.from_pretrained.
SYSTEM:Certainly! AutoTokenizer is a convenient class in the transformers library that allows you to easily tokenize text data using pre-trained models. Here's how it works:

1. **Pre-trained models**: AutoTokenizer relies on pre-trained models that have been trained on large amounts of text data. These models are available for various languages and can be downloaded from the Hugging Face model hub.
2. **Tokenization**: When you call `AutoTokenizer.from_pretrained`, you pass in the path to a pre-trained model file, such as `bert-base-uncased`. The tokenizer will then load the model and use it to tokenize input text.
3. **Customization**: While AutoTokenizer provides a simple way to tokenize text, you may need to customize the output for your specific use case. For example, you might want to modify the tokenizer to exclude certain special characters or add custom tokens. In these cases, you can use the ` AutoTokenizer` class to create custom tokenizers with additional functionality.
4. **Efficiency**: AutoTokenizer is designed to be efficient and fast, making it suitable for large-scale text processing tasks. It uses a streaming approach to tokenization, which reduces memory


日本語翻訳

USER:AutoTokenizer.from_pretrained について教えてください。
システム:確かに! AutoTokenizer は、事前トレーニングされたモデルを使用してテキスト データを簡単にトークン化できるトランスフォーマー ライブラリの便利なクラスです。 仕組みは次のとおりです。

1. **事前トレーニングされたモデル**: AutoTokenizer は、大量のテキスト データでトレーニングされた事前トレーニング モデルに依存します。 これらのモデルはさまざまな言語で利用でき、Hugging Face モデル ハブからダウンロードできます。
2. **トークン化**: `AutoTokenizer.from_pretrained` を呼び出すときは、`bert-base-uncased` などの事前トレーニングされたモデル ファイルへのパスを渡します。 トークナイザーはモデルをロードし、それを使用して入力テキストをトークン化します。
3. **カスタマイズ**: AutoTokenizer はテキストをトークン化する簡単な方法を提供しますが、特定の使用例に合わせて出力をカスタマイズする必要がある場合があります。 たとえば、トークナイザーを変更して、特定の特殊文字を除外したり、カスタム トークンを追加したりすることができます。このような場合、`AutoTokenizer` クラスを使用して、追加機能を備えたカスタム トークナイザーを作成できます。
4. **効率**: AutoTokenizer は効率的かつ高速に実行できるように設計されており、大規模なテキスト処理タスクに適しています。 トークン化にはストリーミング アプローチを使用します。


生成タスク3

プロンプトの実行

Transformers.pipelineの引数のdo_sampleについて質問をしています。

prompt = """USER:Please tell me the role of do_sample=True used in the Transformers.pipeline at inference.
SYSTEM:"""
sequences = pipeline(
    prompt,
    do_sample=True,
    temperature=0.8,
    top_p=0.9,
    top_k=40,
    num_return_sequences=1,
    eos_token_id=tokenizer.eos_token_id,
    max_length=300,
)
print(sequences[0]["generated_text"])


生成結果

Transformers.pipelineの引数のdo_sampleに関する適切な回答が得られました。

USER:Please tell me the role of do_sample=True used in the Transformers.pipeline at inference.
SYSTEM:The `do_sample=True` parameter is used in the Transformers.pipeline to sample the input data during inference. This is done to reduce the computational cost of the pipeline by only processing a subset of the input data, rather than the entire dataset.

When `do_sample=True`, the pipeline will randomly sample a subset of the input data and use that subset to perform the inference. The size of the sampled subset is determined by the `sample_size` parameter, which can be set to a value between 0 and the total number of input samples.

By default, `do_sample=False`, meaning that the pipeline will process the entire input dataset during inference. However, in some cases, it may be desirable to reduce the computational cost of the pipeline by sampling the input data. For example, if you are working with very large datasets or if you want to speed up the inference process for a specific model, setting `do_sample=True` can be useful.

It's worth noting that using `do_sample=True` can result in a slight loss of accuracy compared to processing the entire input dataset. However, this loss should be relatively small, especially when the sample size is reasonably large.


日本語翻訳

USER: 推論時のTransformers.pipelineで使用されるdo_sample=Trueの役割を教えてください。
SYSTEM: do_sample=True パラメータは、Transformers.pipeline内で推論時に入力データをサンプリングするために使用されます。これにより、パイプラインの計算コストを削減し、入力データのサブセットのみを処理することが可能になります。

do_sample=True の場合、パイプラインは入力データのサブセットをランダムにサンプリングし、そのサブセットを使用して推論を実行します。サンプリングされるサブセットのサイズは、sample_size パラメータによって決定され、0から入力サンプルの総数までの値に設定できます。

デフォルトでは、do_sample=False であり、これはパイプラインが推論時に入力データセット全体を処理することを意味します。ただし、非常に大きなデータセットで作業している場合や特定のモデルの推論プロセスを高速化したい場合など、入力データをサンプリングしてパイプラインの計算コストを削減することが望ましい場合があります。do_sample=True を設定することで、このような場面で役立つことがあります。

do_sample=True を使用することは、入力データセット全体を処理する場合と比較してわずかな精度の損失を引き起こす可能性があります。ただし、特にサンプルサイズが十分に大きい場合、この損失は比較的小さくなるはずです。


LLMならGPUクラウド

Llama2やその他のLLMを使用する際には、モデルサイズやタスクに応じて必要なスペックが異なります。

LLMで使用されるGPUは高価なため、買い切りのオンプレミスよりも、コストパフォーマンスが高く柔軟な使い方ができるGPUクラウドをおすすめしています。


GPUクラウドのメリットは以下の通りです。

  • 必要なときだけ利用して、コストを最小限に抑えられる
  • タスクに応じてGPUサーバーを変更できる
  • 需要に応じてGPUサーバーを増減できる
  • 簡単に環境構築ができ、すぐに開発をスタートできる
  • 新しいGPUを利用できるため、陳腐化による買い替えが不要
  • GPUサーバーの高電力・熱管理が不要


コスパをお求めなら、メガクラウドと比較して50%以上安いGPUクラウドサービス「GPUSOROBAN」がおすすめです。


  生成AIに最適なGPUクラウド「高速コンピューティング」|GPUSOROBAN GPUSOROBANの高速コンピューティングは、NVIDIAの高速GPUが業界最安級で使えるクラウドサービスです。NVIDIA A100を始めする高速GPUにより、画像生成AI、大規模言語モデルLLM、機械学習、シミュレーションを高速化します。 業界最安級GPUクラウド | GPUSOROBAN


大規模なLLMを計算する場合は、NVIDIA H100のクラスタが使える「GPUSOROBAN AIスパコンクラウド」がおすすめです。


  LLMに最適なH100が業界最安級「AIスパコンクラウド」| GPUSOROBAN AIスパコンクラウドはNVIDIA H100を搭載したGPUインスタンスが業界最安級で使えるクラウドサービスです。HGX H100(H100 x8枚)を複数連結したクラスタ構成により、LLMやマルチモーダルAIの計算時間を短縮します。料金はAWSのH100インスタンスと比較して75%安く設定しており、大幅なコストダウンが可能です。 業界最安級GPUクラウド | GPUSOROBAN


まとめ

この記事では、GPUSOROBANの環境でLlama2を用いて推論をする方法を紹介しました。

Llama2は無料で使えて商用利用可能な利便性の高いモデルでありながら、ChatGPTと同等以上の性能があります。

Llama2に関する詳細な情報は、以下の記事でまとめて紹介していますので、あわせてご覧ください。


  Llama2とは?使い方・日本語性能・商用利用について解説 | 初心者ガイド この記事では、Llama2について幅広く解説しています。Llama2の性能や安全性、商用利用、日本語対応、様々な環境での使い方などに触れています。 業界最安級GPUクラウド | GPUSOROBAN



MORE INFORMATION

GPUでお困りの方はGPUSOROBANで解決!
お気軽にご相談ください

10日間無料トライアル
詳しい資料はこちら
質問・相談はこちら