大規模言語モデル(Llama2/Gemma/Calm2)を動かしてみる(使い方)
![](https://tech.aru-zakki.com/wp-content/uploads/2024/03/llama2-gemma-calm2.001.jpeg)
Llama2/Gemma/Calm2の3つの大規模言語モデル(LLM)を動かしてみました。今回は、3つのモデルとも7Bを動かしてみました(7BはGPUのメモリが16GBで動作する、70億のパラメーターでトレーニングされたモデル)。
![大規模言語モデル(LLM)関連の記事一覧](https://tech.aru-zakki.com/wp-content/uploads/2024/04/LLM-index.001-320x180.jpeg)
はじめに
3モデルともHuggingFaceに登録されていて、同じような感じで使うことが可能です。ちょっと、自前のコードに組み込むだけなら簡単です。
ただ、メモリとGPUのメモリは結構必要ですので、動作させるにはそれなりの環境が必要となります。
![](https://tech.aru-zakki.com/wp-content/uploads/2023/06/tabbycat.png)
Google Colabで動作させる場合は、GPU:T4以上+ハイメモリが良いと思います。ハイメモリでないとメモリクラッシュが発生しました。
前準備
ライブラリのインストール
動作させるには、ライブラリなどをインストールしておく必要があります。Google Colabの場合は以下のライブラリをインストールしておきます(必要ないものもあるかもしれません)。
!pip install -q accelerate==0.21.0 peft==0.4.0 bitsandbytes==0.40.2 transformers==4.31.0 trl==0.4.7
また、Gemmaに関しては最新のtransformersをインストールする必要がありました。
!pip install -q -U git+https://github.com/huggingface/transformers.git
HuggingFaceへのログイン
OpenCALM以外はHuggingFaceへのログインが必要です。
huggingface-cli login
を使って、ログインする必要があります。
!huggingface-cli login
ログインに必要なトークンは、ログインのメッセージにあるURLから入手することが可能です(HuggingFaceのアカウントが必要です)
![](https://tech.aru-zakki.com/wp-content/uploads/2024/03/image-1024x226.png)
Llama2(Meta)
Llama2とは
Llama2(Large Language Model Meta AI/ラマ)は、Meta社が開発した大規模言語モデル(LLM)です。現在、研究および商用利用に無料で提供されています
コード(Llama-2-7b-chat-hf)
今回はChat向けに学習した、Llama-2-7b-chat-hf
を利用しています。
以下は、tokenizer
とmodel
の定義です。
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained(
"meta-llama/Llama-2-7b-chat-hf",
)
model = AutoModelForCausalLM.from_pretrained(
"meta-llama/Llama-2-7b-chat-hf",
torch_dtype=torch.float16, device_map="auto", trust_remote_code=False,
)
以下は、model
/tokenizer
の使用例です。llama2では[INST]指示文[/INST]
という形で入力するようです。
# プロンプト(結構重い)
prompt = "[INST] 日本で一番高い建物は? [/INST]"
# 推論
input_ids = tokenizer(prompt, return_tensors='pt')
with torch.no_grad():
tokens = model.generate(
**input_ids.to(model.device),
max_new_tokens=64,
do_sample=True,
temperature=0.5,
top_p=0.9,
repetition_penalty=1.05,
)
output = tokenizer.decode(tokens[0], skip_special_tokens=True)
print(output)
出力結果
[INST] 日本で一番高い建物は? [/INST] Japan has several tall buildings, and the one that is considered to be the highest depends on the criteria used. Here are some of the tallest buildings in Japan:
1. Tokyo Skytree: At 634 meters (2,080 feet) tall, Tokyo Skytree is the tall
![](https://tech.aru-zakki.com/wp-content/uploads/2023/06/tabbycat.png)
トークナイザーについての記事はこちら
![Hugging FaceのTokenizerの動作まとめ](https://tech.aru-zakki.com/wp-content/uploads/2023/09/bert-tokenizer.001-320x180.jpeg)
チャットテンプレートを使ってプロンプトを生成する方法についてはこちら
![HuggingFace|大規模言語モデル(LLM)のチャットテンプレートを使う](https://tech.aru-zakki.com/wp-content/uploads/2024/03/huggingface-chatmodel.001-320x180.jpeg)
Gemma(Google)
Gemmaとは
Gemmaは、2024年2月21日に発表されたGoogleが開発した大規模言語モデル(LLM)です。AI開発者や研究者による商用利用や再配布が可能なオープンソースとして提供されています。
![](https://tech.aru-zakki.com/wp-content/uploads/2023/06/tabbycat.png)
利用するには、HuggingFaceのgemma-7bのページで利用規約に同意する必要があります。同意していない場合、ログインしていてもダウンロードできないので注意してください。
コード(gemma-7b)
今回はChat向けに学習した、google/gemma-7b
を利用しています。
以下は、tokenizer
とmodel
の定義です。
from transformers import AutoTokenizer, AutoModelForCausalLM
import torch
tokenizer = AutoTokenizer.from_pretrained("google/gemma-7b")
model = AutoModelForCausalLM.from_pretrained("google/gemma-7b", device_map="auto")
以下は、model
/tokenizer
の使用例です。日本語の質問はうまく動かなかったので、英語で質問しています。
input_text = "What is the tallest building in Japan?"
input_ids = tokenizer(input_text, return_tensors="pt").to(model.device)
with torch.no_grad():
tokens = model.generate(**input_ids)
output = tokenizer.decode(tokens[0], skip_special_tokens=True)
print(output)
出力結果
What is the tallest building in Japan?
The tallest building in Japan is the Tokyo Skytree
CALM2(CyberAgent)
CALM2とは
CALM2(CyberAgentLM2)はサイバーエージェントが開発した大規模言語モデル(LLM)です。日本語に特化した大規模言語モデルという部分が特徴です。32,000トークンまでの入力に対応していて日本語の文章として約50,000文字を一度に処理することができるそうです。
![](https://tech.aru-zakki.com/wp-content/uploads/2023/06/tabbycat.png)
50,000文字を32,000トークンなので、マルチリンガルモデルでありがちな日本語1文字につき1トークンに変換されているわけではなさそうです。
コード(calm2-7b-chat)
今回はChat向けに学習した、cyberagent/calm2-7b-chat
を利用しています。
以下は、tokenizer
とmodel
の定義です。
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
model = AutoModelForCausalLM.from_pretrained("cyberagent/calm2-7b-chat",
device_map="auto",
torch_dtype=torch.float16,
)
tokenizer = AutoTokenizer.from_pretrained("cyberagent/calm2-7b-chat")
以下は、model
/tokenizer
の使用例です。
会話する場合は、”USER: 文章 \nASSISTANT:
“という形式の入力が必要なようです。
公開されているチャットのテンプレート
USER: {user_message1}
ASSISTANT: {assistant_message1}<|endoftext|>
USER: {user_message2}
ASSISTANT: {assistant_message2}<|endoftext|>
USER: {user_message3}
ASSISTANT: {assistant_message3}<|endoftext|>
prompt = "USER: 日本で一番高い建物はなんですか?\nASSISTANT:"
# 推論
input_ids = tokenizer(prompt, return_tensors='pt')
with torch.no_grad():
tokens = model.generate(
**input_ids.to(model.device),
max_new_tokens=64,
do_sample=True,
temperature=0.5,
top_p=0.9,
repetition_penalty=1.05,
pad_token_id=tokenizer.pad_token_id,
)
output = tokenizer.decode(tokens[0], skip_special_tokens=True)
print(output)
出力結果
USER: 日本で一番高い建物はなんですか?
ASSISTANT: 日本で一番高い建物は、2019年8月時点において、東京都中央区晴海にある「あべのハルカス」です。高さは634メートルで、これは日本国内にある建造物で、最も高い建物となっています。
CLAM2については、他の記事も参考にしてください。
![CALM2のトークナイザーの出力調査&チャットボットの作り方](https://tech.aru-zakki.com/wp-content/uploads/2024/03/calm2-tokenizer.001-320x180.jpeg)
![LangChainでRAGを試す|CALM2 + FAISS + RetrievalQAの使用例](https://tech.aru-zakki.com/wp-content/uploads/2024/03/langchain.001-320x180.jpeg)
まとめ
以上、Llama2/Gemma/Calm2の3つを動かしてみました。Gemmaは日本語で聞くとうまく答えられませんでした。
とりあえず、環境さえあれば手軽に動かすことが可能です。
なお、チャットモデルにはチャットテンプレートで入力プロンプトを作成できるモデルもあります。これについては以下の記事を参考にしてください。
![HuggingFace|大規模言語モデル(LLM)のチャットテンプレートを使う](https://tech.aru-zakki.com/wp-content/uploads/2024/03/huggingface-chatmodel.001-320x180.jpeg)