
WSL2でLlama-3.1-8Bを試してみる
コンテキスト長が128kとなったLlama 3.1-8Bモデル群を試してみます。
使用するPCはドスパラさんの「GALLERIA UL9C-R49」。スペックは
・CPU: Intel® Core™ i9-13900HX Processor
・Mem: 64 GB
・GPU: NVIDIA® GeForce RTX™ 4090 Laptop GPU(16GB)・GPU: NVIDIA® GeForce RTX™ 4090 (24GB)
・OS: Ubuntu22.04 on WSL2(Windows 11)
です。
1. 準備
同意
meta-llama/Meta-Llama-3.1-8Bまたはmeta-llama/Meta-Llama-3.1-8B-Instruct にアクセスし、必要事項記入の上、同意してくださいませ。
同意して、暫くすると「アクセス権を与えよう」というメールが届きます。
環境構築
python3 -m vevn llama3.1
cd $_
source bin/activateパッケージのインストールです。
pip install torch transformers accelerate2. モデルの設定ファイルのなかみ
コンテキスト長が128kとのことなので、以下のファイルを覗いてみましょう。
コンテキスト長を見てみましょう。
"max_position_embeddings": 131072,131,072 = 128 k のようです。
ロープスケーリングの設定を確認します。
"rope_scaling": {
"factor": 8.0,
"low_freq_factor": 1.0,
"high_freq_factor": 4.0,
"original_max_position_embeddings": 8192,
"rope_type": "llama3"
},扱えるコンテキスト長が拡張されていることが分かります。もともとのコンテキスト長は original_max_position_embeddingsの値である8,192、すなわち8kでした。が、ロープスケーリングを用いることで 16倍の128kまで拡張している、ということですね。
ロープスケーリング、すごーい。
3. 流し込むコード
では、いつものコードです。query.pyという名前で保存した想定で以下進めます。
import sys
import argparse
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, TextStreamer
from typing import List, Dict
import time
# argv
parser = argparse.ArgumentParser()
parser.add_argument("--model-path", type=str, default=None)
parser.add_argument("--no-chat", action='store_true')
parser.add_argument("--no-use-system-prompt", action='store_true')
parser.add_argument("--max-tokens", type=int, default=256)
args = parser.parse_args(sys.argv[1:])
model_id = args.model_path
if model_id == None:
exit
is_chat = not args.no_chat
use_system_prompt = not args.no_use_system_prompt
max_new_tokens = args.max_tokens
# トークナイザーとモデルの準備
tokenizer = AutoTokenizer.from_pretrained(
model_id,
trust_remote_code=True
)
model = AutoModelForCausalLM.from_pretrained(
model_id,
#torch_dtype="auto",
torch_dtype=torch.bfloat16,
device_map="auto",
#device_map="cuda",
low_cpu_mem_usage=True,
trust_remote_code=True
)
#if torch.cuda.is_available():
# model = model.to("cuda")
streamer = TextStreamer(
tokenizer,
skip_prompt=True,
skip_special_tokens=True
)
DEFAULT_SYSTEM_PROMPT = "あなたは誠実で優秀な日本人のアシスタントです。"
# generation params
generation_params = {
"do_sample": True,
"temperature": 0.8,
"top_p": 0.95,
"top_k": 40,
"max_new_tokens": max_new_tokens,
"repetition_penalty": 1.1,
}
def q(
user_query: str,
history: List[Dict[str, str]]=None
) -> List[Dict[str, str]]:
start = time.process_time()
# messages
messages = ""
if is_chat:
messages = []
if use_system_prompt:
messages = [
{"role": "system", "content": DEFAULT_SYSTEM_PROMPT},
]
user_messages = [
{"role": "user", "content": user_query}
]
else:
user_messages = user_query
if history:
user_messages = history + user_messages
messages += user_messages
# generation prompts
if is_chat:
prompt = tokenizer.apply_chat_template(
conversation=messages,
add_generation_prompt=True,
tokenize=False
)
else:
prompt = messages
input_ids = tokenizer.encode(
prompt,
add_special_tokens=True,
return_tensors="pt"
)
print("--- prompt")
print(prompt)
print("--- output")
# 推論
output_ids = model.generate(
input_ids.to(model.device),
streamer=streamer,
**generation_params
)
output = tokenizer.decode(
output_ids[0][input_ids.size(1) :],
skip_special_tokens=True
)
if is_chat:
user_messages.append(
{"role": "assistant", "content": output}
)
else:
user_messages += output
end = time.process_time()
##
input_tokens = len(input_ids[0])
output_tokens = len(output_ids[0][input_ids.size(1) :])
total_time = end - start
tps = output_tokens / total_time
print(f"prompt tokens = {input_tokens:.7g}")
print(f"output tokens = {output_tokens:.7g} ({tps:f} [tps])")
print(f" total time = {total_time:f} [s]")
return user_messages
print('history = ""')
print('history = q("ドラえもんとはなにか")')
print('history = q("続きを教えてください", history)')
4. 試してみる
ベースモデルとインストラクションモデルの両方を試します。
(1) Meta-Llama-3.1-8B
Hugging Faceのパスを指定して起動です。ベースモデルなので --no-chat オプションを付けておきます。
python -i /path/to/query.py --model-path meta-llama/Meta-Llama-3.1-8B --no-chat聞いてみる
とりあえず聞いてみましょう。
>>> history = q("ドラえもんは")
--- prompt
ドラえもんは
--- output
The attention mask and the pad token id were not set. As a consequence, you may observe unexpected behavior. Please pass your input's `attention_mask` to obtain reliable results.
Setting `pad_token_id` to `eos_token_id`:128001 for open-end generation.
すごいぞ! その5
1 : 名無しさん@お腹いっぱい。 :2016/05/11(水) 22:00:06 ID:gq3sD7r20
3 : 名無しさん@お腹いっぱい。 :2016/05/11(水) 23:03:25 ID:JzPQ8uYs0
5 : 名無しさん@お腹いっぱい。 :2016/05/12(木) 18:55:16 ID:i0cXxW2p0
6 : 名無しさん@お腹いっぱい。 :2016/05/13(金) 21:09:24 ID:XhJi4eO.0
prompt tokens = 6
output tokens = 149 (26.764732 [tps])
total time = 5.567028 [s]すごいぞ! その5
1 : 名無しさん@お腹いっぱい。 :2016/05/11(水) 22:00:06 ID:gq3sD7r20
3 : 名無しさん@お腹いっぱい。 :2016/05/11(水) 23:03:25 ID:JzPQ8uYs0
5 : 名無しさん@お腹いっぱい。 :2016/05/12(木) 18:55:16 ID:i0cXxW2p0
6 : 名無しさん@お腹いっぱい。 :2016/05/13(金) 21:09:24 ID:XhJi4eO.0
すごいぞ!というか、まさかの2チャンネル。
VRAM使用量は 8Bモデルですから、15.7GBと想定通りですね。

(2) Meta-Llama-3.1-8B-Instruct
Hugging Faceのパスを指定して起動です。
python -i /path/to/query.py --model-path meta-llama/Meta-Llama-3.1-8B-Instruct聞いてみる
とりあえず聞いてみましょう。
>>> history = q("ドラえもんとはなにか")
--- prompt
<|begin_of_text|><|start_header_id|>system<|end_header_id|>
あなたは誠実で優秀な日本人のアシスタントです。<|eot_id|><|start_header_id|>user<|end_header_id|>
ドラえもんとはなにか<|eot_id|><|start_header_id|>assistant<|end_header_id|>
--- output
The attention mask and the pad token id were not set. As a consequence, you may observe unexpected behavior. Please pass your input's `attention_mask` to obtain reliable results.
Setting `pad_token_id` to `eos_token_id`:128001 for open-end generation.
The attention mask is not set and cannot be inferred from input because pad token is same as eos token.As a consequence, you may observe unexpected behavior. Please pass your input's `attention_mask` to obtain reliable results.
大人気の漫画、映画、アニメ、テレビ番組「ドラえもん」です。
主に小学館の漫画雑誌に連載されている「クイズ面白パズル ドラえもん」から派生して、富野由悠季監督がアニメ化した作品です。
この「ドラえもん」は、1969年(昭和44年)4月15日に第1話を放送し、現在も長続きしています。
その名高い「ドタバタコミック」と評される、明るく活躍する少年・ノボタロボタンと、そのペットの猫であるドラえもんと、学級委員 長のしっぽんだいお兄さんと共に日常生活の中で起こる様々な出来事や物語を描いています。
ドラえもんというのは、科学的な知識を応用して未来から送られた時計型のポケットウサギです。
かっこいい名前で通じますね?
prompt tokens = 40
output tokens = 218 (26.106983 [tps])
total time = 8.350256 [s]
>>>大人気の漫画、映画、アニメ、テレビ番組「ドラえもん」です。
主に小学館の漫画雑誌に連載されている「クイズ面白パズル ドラえもん」から派生して、富野由悠季監督がアニメ化した作品です。
この「ドラえもん」は、1969年(昭和44年)4月15日に第1話を放送し、現在も長続きしています。
その名高い「ドタバタコミック」と評される、明るく活躍する少年・ノボタロボタンと、そのペットの猫であるドラえもんと、学級委員 長のしっぽんだいお兄さんと共に日常生活の中で起こる様々な出来事や物語を描いています。
ドラえもんというのは、科学的な知識を応用して未来から送られた時計型のポケットウサギです。
かっこいい名前で通じますね?
VRAM使用量も(とうぜん)ベースモデルとほぼ変わらず。
