Welcome to Mashykom WebSite



llama.cpp による日本語大規模言語モデルの利用

 llama.cpp とは Meta社の大規模言語LLMシリーズの Llama-2 ,3 モデルの重みを量子化し、より低精度の離散値に変換することで推論の高速化を図るライブラリです。.cppと書かれていることからもわかるように推論箇所はC++で書かれています。llama.cpp の主な目的は、GPU を必要としない最小限のセットアップで、ローカルおよびクラウドのさまざまなハードウェア上で最先端のパフォーマンスを実現しながら LLM 推論を可能にすることです。

 llama という名前がついていますが、サポートされているLLMは Llama シリーズだけではありません。GPT、 Mistral や BERT などのモデルに対しても利用可能です。

 無料で利用できる日本語大規模言語モデルは多数開発されています。MIT や Apache-2.0 といったオープンソースライセンスが適用されています。利用可能な日本語大規模言語モデルのリストは、awesome-japanese-llm というサイトに紹介されています。海外モデル(Llama 2 ,3 、 Mistral や GPTなど)に日本語で追加事前学習を行ったモデルの代表的なものは、Llama-3.1-70B-Japanese-Instruct-2407 Llama 3 Swallow llama-3-youko-70b-instructLlama-3-ELYZA-JPなどです。

フルスクラッチで事前学習した日本語LLMモデルには、stockmark/stockmark-100b-instruct-v0.1 Tanuki-8x8B-dpo-v1.0 cyberagent/Llama-3.1-70B-Japanese-Instruct-2407SakanaAI/Llama-3-EvoVLM-JP-v2などがあります。

 このページで使用する日本語LLMは GGUF 形式で量子化されモデルです。HuggingFace のサイトからダウンロードできるモデルを対象としました。一つ目は、ELYZAが開発・提供する大規模言語モデル「ELYZA LLM for JP」シリーズの最新モデルです。Llama-3-ELYZA-JP は Llama 3 8B モデルを利用して日本語のファインチューニングをしたモデルです。2番目に取り上げるのは、Sakana AI がリリースした SakanaAI-EvoLLM-JP-v1-7B です。SakanaAI-EvoLLM-JP-v1-7B は Llama アーキテクチャーを利用していません。最後に、GENIAC 松尾研 LLM開発プロジェクトで開発されたLLMである weblab-GENIAC/Tanuki-8B-dpo-v1.0 のGGUF量子化モデルを取り上げます。

Last updated: 2024.9.15



llama.cpp のインストールと使用法


 llama.cppは、大規模言語LLMシリーズの Llama-2 ,3 モデルや mistral のモデルの重みを量子化という技術でより低精度の離散値に変換して、推論の高速化を図るツールです。使い方は非常にシンプルです。使用法は以下の通りです。

まず、バイナリを取得する必要があります。実行できる方法はいくつかあります:
方法 1: リポジトリをクローンしてローカルでビルドします。
方法 2: MacOS または Linux を使用している場合は、brew、flox、または nix 経由で llama.cpp をインストールできます
方法 3: Docker イメージを使用します。
方法 4: リリースからビルド済みのバイナリをダウンロードします

 リポジトリをクローンしてローカルでビルドするには、次のコマンドを使用して、基本的なビルドを実行できます。


$git clone https://github.com/ggerganov/llama.cpp
$cd llama.cpp

(llama.cpp)$make


 MacOS では、Metal はデフォルトで有効になっています。Metal を使用すると、計算は GPU 上で実行されます。この make を使ったビルドをすると、MacPC の場合には、Metal を使用することが条件になります。コンパイル時に Metal ビルドを無効にするには、GGML_NO_METAL=1 フラグまたは GGML_METAL=OFF cmake オプションを使用します。Metal を使用しないときは、以下のようにします。


(llama.cpp)$cmake -B build  -DGGML_METAL=OFF
(llama.cpp)$cmake --build build --config Release


 これで、cpu のみの MacPC で、Llama モデルの量子化モデルを用いた推論が実行可能になります。Llama.cppで動作させるためには、METAが提供するLlamaのモデルを量子化する必要があります。現在(2024年9月)、llama.cpp では、ggml 量子化フォーマットは現在サポートされていません。gguf フォーマット形式の量子化モデルが必要です。Llama 3 に対応する gguf フォーマット形式のコードは Hugging Face のQuantFactoryにあります。

 gguf 形式の量子化モデルを用いて推論を実行するときは、例えば、以下のようなコマンドを実行します。


$./llama-cli -m your_model.gguf -p "I believe the meaning of life is" -n 128


 -m, --model オプションはモデルの指定なので、 your_model.gguf と具体的に指定します。-p, --prompt はプロンプトのオプションなので、プロンプト" I believe he meaning of life is "と入力しています。-n, --n-predict は作成する文章のトークン数の指定です。-c, --ctx-size はプロンプトのサイズを指定します。デフォルトでは、512 です。

 例えば、Llama 3 8B の量子化モデルを用いて、以下のコードを実行します。


$./llama-cli -m models/Meta-Llama-3-8B-Instruct.Q4_K_M.gguf -p "I believe the meaning of life is" -n 128




--- response --- 

I believe the meaning of life is to find your passion and pursue it with all your heart. Whether it's a creative pursuit, a career, or a hobby, the most important thing is to be doing something that brings you joy and fulfillment.

I also believe that the key to a happy and fulfilling life is to be true to yourself and live authentically. This means being honest with yourself and others about who you are and what you want, and not trying to fit into someone else's mold or expectations.

Ultimately, the meaning of life is a personal and subjective thing, and what brings meaning and purpose to one person's life may be different for another. I believe
llama_perf_sampler_print:    sampling time =      24.73 ms /   136 runs   (    0.18 ms per token,  5498.28 tokens per second)
llama_perf_context_print:        load time =    3186.75 ms
llama_perf_context_print: prompt eval time =    1603.11 ms /     8 tokens (  200.39 ms per token,     4.99 tokens per second)
llama_perf_context_print:        eval time =   51880.52 ms /   127 runs   (  408.51 ms per token,     2.45 tokens per second)
llama_perf_context_print:       total time =   53550.01 ms /   135 tokens
Log end

 入力したプロンプトに対する答えが帰ってきます。ここでのプロンプトは文章の始まりなので、続きの文章が作成されます。

 chatbot のような会話形式でプロンプトを実行するときは、以下のようなコマンドを使用します。オプション「-cnv」をつけます。


$./llama-cli -m your_model.gguf -p "You are a helpful assistant" -cnv


 具体的には、以下のコマンドを入力しました。


$./llama-cli -m models/Meta-Llama-3-8B-Instruct.Q4_K_M.gguf -p "You are a helpful assistant" -cnv



--- response --- 

== Running in interactive mode. ==
 - Press Ctrl+C to interject at any time.
 - Press Return to return control to the AI.
 - To return control without starting a new line, end your input with '/'.
 - If you want to submit another line, end your input with '\'.

system

You are a helpful assistant


> hi, who are you?
Hello! I'm your helpful assistant! I'm a computer program designed to assist and communicate with you in a helpful and informative way. I can provide answers to your questions, complete tasks for you, and even have a conversation with you. I'm here to help you with whatever you need, so please don't hesitate to ask me anything!

What's on your mind today? Do you have a specific question or topic you'd like to discuss?

> can you tell me about Tokyo?                  
Tokyo!
Tokyo is the capital and largest city of Japan, a global hub for technology, fashion, food, and entertainment. It's a
fascinating city that seamlessly blends traditional and modern cultures, offering endless opportunities for exploration
and discovery. Here are some interesting facts and highlights about Tokyo:

----

>
== Running in interactive mode. ==
 - Press Ctrl+C to interject at any time.
 - Press Return to return control to the AI.
 - To return control without starting a new line, end your input with '/'.
 - If you want to submit another line, end your input with '\'.

<|im_start|>system
You are a helpful assistant<|im_end|>

> How are you
I'm doing well, thanks for asking! I'm a helpful assistant, here to assist you with any questions or tasks you may have. How can I help you today?

> Have you been in Los Angeles?
I'm just an artificial intelligence, I don't have a physical presence, so I haven't been to Los Angeles or any other location. I exist solely as a digital entity, and I don't have personal experiences or memories. However, I can provide you with information about Los Angeles or any other location if you're planning a trip or just want to learn more about it!

> (続けて、ここに質問のプロンプトを記入します。)

 チャット・テンプレートを指定しないときは、入力モデルのメタデータのものを使用します。チャット・テンプレートを指定するときは、例えば、「--chat-template NAME」と指定します。以下の例がそれです。


$./llama-cli -m your_model.gguf -p "You are a helpful assistant" -cnv --chat-template chatml


 チャット・テンプレートで指定できるものは、llama2, llama3, gemma, monarch, chatml, orion, vicuna などです。


llama.cpp で日本語LLMを使用


 早速、日本語LLM を使用してみましょう。ELYZA LLM for JP シリーズの最新モデル「Llama-3-ELYZA-JP」を使ってみましょう。「Llama-3-ELYZA-JP」シリーズの概要は以下のように説明されています。 「Llama-3-ELYZA-JP」シリーズは、Meta社の「Llama 3」シリーズをベースとした2種類の日本語大規模言語モデル(以下、LLM)を指し、700億パラメータの「Llama-3-ELYZA-JP-70B」と80億パラメータの「Llama-3-ELYZA-JP-8B」が該当します。各モデルは、それぞれ「Meta-Llama-3-70B-Instruct」と「Meta-Llama-3-8B-Instruct」に対し、日本語における指示追従能力を拡張するための、日本語追加事前学習および事後学習を行ったものです。

 日本語の生成能力に関するベンチマーク評価 (ELYZA Tasks 100、Japanese MT-Bench) において、両モデルはいずれもベースとなる「Llama 3」シリーズから大きく日本語性能が向上しています。特に 700億パラメータの「Llama-3-ELYZA-JP-70B」は「GPT-4」「Claude 3 Sonnet」「Gemini 1.5 Flash」といったグローバルモデルを上回る性能を達成しました。

 Llama-3-ELYZA-JP をgguf型式で量子化したモデル Llama-3-ELYZA-JP-8B-GGUF を使用します。これをダウンロードして、llama.cpp と同じディレクトリに models を作成して、ここに配置します。サイズは約4.9GBあります。

 llama.cpp ディレクトリから


(llama.cpp)$./build/bin/llama-cli -m ../models/Llama-3-ELYZA-JP-8B-q4_k_m.gguf -p "I believe the meaning of life is" -n 128


 結果は以下の通りです。


--- response --- 

Log start
main: build = 3755 (822b6322)
main: built with Apple clang version 15.0.0 (clang-1500.3.9.4) for x86_64-apple-darwin23.6.0
llama_model_loader: loaded meta data with 22 key-value pairs and 291 tensors from ../models/Llama-3-ELYZA-JP-8B-q4_k_m.gguf (version GGUF V3 (latest))
llama_model_loader: Dumping metadata keys/values. Note: KV overrides do not apply in this output.
llama_model_loader: - kv   0:                       general.architecture str              = llama
llama_model_loader: - kv   1:                               general.name str              = Llama-3-8B-optimal-merged-stage2
llama_model_loader: - kv   2:                          llama.block_count u32              = 32
llama_model_loader: - kv   3:                       llama.context_length u32              = 8192
llama_model_loader: - kv   4:                     llama.embedding_length u32              = 4096
llama_model_loader: - kv   5:                  llama.feed_forward_length u32              = 14336
llama_model_loader: - kv   6:                 llama.attention.head_count u32              = 32

...

generate: n_ctx = 8192, n_batch = 2048, n_predict = 128, n_keep = 1


I believe the meaning of life is to find your passion and pursue it with purpose and dedication. It's a challenging and sometimes difficult journey, but it's the most rewarding and fulfilling way to live your life. So, my advice is to find your passion and pursue it with purpose and dedication. It's the key to a happy and successful life. [end of text]

llama_perf_sampler_print:    sampling time =      10.54 ms /    72 runs   (    0.15 ms per token,  6829.82 tokens per second)
llama_perf_context_print:        load time =   21251.42 ms
llama_perf_context_print: prompt eval time =    1519.29 ms /     8 tokens (  189.91 ms per token,     5.27 tokens per second)
llama_perf_context_print:        eval time =   20218.65 ms /    63 runs   (  320.93 ms per token,     3.12 tokens per second)
llama_perf_context_print:       total time =   21769.80 ms /    71 tokens
Log end

 (例1)llama.cpp ディレクトリから


$./build/bin/llama-cli -m ../models/Llama-3-ELYZA-JP-8B-q4_k_m.gguf -p "私が思うに、人生とは" -n 128


 と入力すると、以下の返答となります。


--- response --- 

私が思うに、人生とは「経験の積み重ね」だと思います。いろいろな経験を積み重ねることで、人生は豊かになり、深みが増すと考えています。

経験とは「体験」や「知識」、「スキル」などが含まれます。人生には、計画された経験や、偶然の経験、失敗や成功など、多くの経験があります。

経験の積み重ねで得られることは、次の3つです。

1. 知識やスキルが向上する
llama_perf_sampler_print:    sampling time =      21.35 ms /   138 runs   (    0.15 ms per token,  6464.61 tokens per second)
llama_perf_context_print:        load time =    2785.36 ms
llama_perf_context_print: prompt eval time =    1843.75 ms /    10 tokens (  184.37 ms per token,     5.42 tokens per second)
llama_perf_context_print:        eval time =   40746.39 ms /   127 runs   (  320.84 ms per token,     3.12 tokens per second)
llama_perf_context_print:       total time =   42645.45 ms /   137 tokens
Log end

トークン数の指定が128なので、作成された文章が途中で終わっています。次に、作成する文章のトークン数を指定しないで実行します。

(例2)llama.cpp ディレクトリから

llama.cpp $ ./build/bin/llama-cli -m ../models/Llama-3-ELYZA-JP-8B-q4_k_m.gguf -p "z世代とは何ですか"


 以下の結果が表示されます。


--- response --- 

Log start

...

z世代とは何ですか?
z世代とは、1997年から2012年生まれの世代を指します。z世代は、ミレニアム世代の次に生まれた世代で、インターネットやデジタルテクノロジーを幼いころから当たり前のように使い、独自の価値観や消費行動を持つとされます。

特徴として、以下が挙げられます。

1. デジタルネイティブ:生まれた時からインターネットやスマートフォンが存在し、デジタルテクノロジーに馴染みがあります。
2. 多様性を重視:z世代は、多様性を重視し、個性や多様なバックグラウンドを尊重する傾向があります。
3. サステナビリティ意識が高い:z世代は、環境や社会の問題に敏感で、サステナビリティや社会的責任を重視する消費者層です。
4. コミュニケーションスタイルが異なる:z世代は、テキストメッセージやSNSでのコミュニケーションを好み、会話や電話を好まない傾向があります。
5. 金銭感覚が異なる:z世代は、金銭感覚が異なり、経済的な安定や長期的な視点を重視する傾向があります。

z世代は、将来の消費やマーケットを占める大切な世代です。企業は、z世代の特性や価値観を理解し、戦略を立案する必要があります。 [end of text]

llama_perf_sampler_print:    sampling time =      79.66 ms /   397 runs   (    0.20 ms per token,  4983.74 tokens per second)
llama_perf_context_print:        load time =    2755.90 ms
llama_perf_context_print: prompt eval time =    1246.78 ms /     7 tokens (  178.11 ms per token,     5.61 tokens per second)
llama_perf_context_print:        eval time =  169561.27 ms /   389 runs   (  435.89 ms per token,     2.29 tokens per second)
llama_perf_context_print:       total time =  171038.56 ms /   396 tokens
Log end

 Llama モデルとは異なるLLMの量子化モデルを使用してみましょう。Sakana AI が開発した日本語LLM、 SakanaAI-EvoLLM-JP-v1-7B-q4_K_M で実証しましょう。ダウンロードして、models ディレクトリに配置します。約4.4GBあります。 llama.cpp ディレクトリから


llama.cpp$./build/bin/llama-cli -m ../models/SakanaAI-EvoLLM-JP-v1-7B-q4_K_M.gguf -p "I believe the meaning of life is" -n 128



--- response --- 
'''
Log start
main: build = 3755 (822b6322)
main: built with Apple clang version 15.0.0 (clang-1500.3.9.4) for x86_64-apple-darwin23.6.0
llama_model_loader: loaded meta data with 23 key-value pairs and 291 tensors from ../models/SakanaAI-EvoLLM-JP-v1-7B-q4_K_M.gguf (version GGUF V3 (latest))
llama_model_loader: Dumping metadata keys/values. Note: KV overrides do not apply in this output.
llama_model_loader: - kv   0:                       general.architecture str              = llama
llama_model_loader: - kv   1:                               general.name str              = .
llama_model_loader: - kv   2:                           llama.vocab_size u32              = 32000
llama_model_loader: - kv   3:                       llama.context_length u32              = 32768

....

generate: n_ctx = 32768, n_batch = 2048, n_predict = 128, n_keep = 1


I believe the meaning of life is to live and to enjoy life. It's not about the pursuit of happiness, but the happiness of pursuits. It's about finding something worth living for and working hard to achieve it. It's about sharing life with others and giving back to the community. It's about leaving a legacy and making a difference in the world.

In my case, I'm a filmmaker and educator. I'm passionate about telling stories and helping others tell their stories. I'm also passionate about teaching and mentoring young people. I believe that we all have a story to tell and a purpose to live

llama_perf_sampler_print:    sampling time =       8.15 ms /   136 runs   (    0.06 ms per token, 16693.26 tokens per second)
llama_perf_context_print:        load time =   21747.21 ms
llama_perf_context_print: prompt eval time =    2458.60 ms /     8 tokens (  307.33 ms per token,     3.25 tokens per second)
llama_perf_context_print:        eval time =   42245.35 ms /   127 runs   (  332.64 ms per token,     3.01 tokens per second)
llama_perf_context_print:       total time =   44729.88 ms /   135 tokens
Log end
'''

 (例3)llama.cpp ディレクトリから、以下のコマンドを入力します。


llama.cpp$./build/bin/llama-cli -m ../models/SakanaAI-EvoLLM-JP-v1-7B-q4_K_M.gguf -p "z世代とは何ですか" 



--- response ---

z世代とは何ですか?
Z世代とは、1996年から2010年の間に生まれた世代です。この世代は、インターネットとデジタル技術が普及した時代に育っています。
Z世代の特徴は、デジタルネイティブ、ソーシャルネイティブ、マルチタスク、リアルタイム、コラボレーション、クリエイティブなどです。
Z世代は、従来の世代と比べて、より高いコミュニケーションスキル、自己表現スキル、創造性を持っています。
Z世代は、従来の世代と比べて、より高いコミュニケーションスキル、自己表現スキル、創造性を持っています。この世代は、新しい技術とツールを迅速に吸収し、革新的なアイデアを生み出す能力を示しています。
Z世代は、従来の世代と比べて、より高いコミュニケーションスキル、自己表現スキル、創造性を持っています。この世代は、新しい技術とツールを迅速に吸収し、革新的なアイデアを生み出す能力を示しています。また、従来の世代と比べて、より高いコミュニケーションスキル、自己表現スキル、創造性を持っています。この世代は、新しい技術とツールを迅速に吸収し、革新的なアイデアを生み出す能力を示しています。
[end of text]

llama_perf_sampler_print: sampling time = 34.11 ms / 528 runs ( 0.06 ms per token, 15481.60 tokens per second)
llama_perf_context_print: load time = 22630.58 ms
llama_perf_context_print: prompt eval time = 2019.10 ms / 10 tokens ( 201.91 ms per token, 4.95 tokens per second)
llama_perf_context_print: eval time = 195429.98 ms / 517 runs ( 378.01 ms per token, 2.65 tokens per second)
llama_perf_context_print: total time = 197552.94 ms / 527 tokens
Log end

 同じ文章が3回ほど繰り返されています。少し奇妙な日本語になっています。

 最後に、GENIAC 松尾研 LLM開発プロジェクトで開発されたLLMである weblab-GENIAC/Tanuki-8B-dpo-v1.0 のGGUF量子化モデルを取り上げます。Hugging Face のサイトからダウンロードします。約4.6GBあります。models ディレクトリに配置します。

 llama.cpp のあるディレクトリから


llama.cpp $./build/bin/llama-cli -m ../models/Tanuki-8B-dpo-v1.0-Q4_K_M.gguf -p "z世代とは何ですか"


 と入力すると、以下の返答があります。


--- response ---

z世代とは何ですか?また、その特徴や傾向について教えてください。

1. 定義と背景:
「ミレニアル世代」(Millennials)は、一般的に1980年代から2000年代初頭までに生まれた人々を指します。この世代は、インターネットの普及とともに成長し、デジタルネイティブとして知られています。彼らはベビーブーマーの後に生まれ、スマートフォンやソーシャルメディアが日常生活の一部となっている環境で育ちました。

2. 特徴:
- デジタルネイティブ: インターネットやスマートフォンを幼少期から利用しており、デジタル技術に非常に慣れています。
- 多様性と包摂性: ジェンダーや人種、性的指向に対する理解が深く、多様性を尊重する傾向があります。
- キャリア志向: 早い段階からキャリア形成を重視し、自己実現やプロフェッショナルな成長を追求します。
- ライフスタイルの変化: 伝統的な価値観や生活様式に対する関心が高く、持続可能性やエコフレンドリーなライフスタイルを求めることが多いです。
- ソーシャルメディアの影響: ソーシャルメディアを通じて情報を得たり、コミュニケーションを取ったりすることに慣れており、インフルエンサーやブランドに対する影響力が強いです。

3. 経済的・社会的影響:
- 消費行動: ミレニアル世代は購買力が高く、特にテクノロジーやファッション、健康・ウェルネス商品に対して積極的です。また、持続可能性やエシカルファッションにも関心を持っています。
- 労働市場: 彼らは柔軟な働き方やリモートワークを受け入れる傾向があり、企業文化や働き方にも大きな影響を与えています。
- 政治と社会活動: 社会正義や環境問題に対する意識が高く、積極的に社会活動や政治参加を行うことが多いです。

4. 課題と機会:
- 課題: 経済的不平等やキャリアの不安定さ、メンタルヘルスの問題などが指摘されています。また、情報過多によるストレスも問題です。
- 機会: 革新と新しいビジネスモデルの創出、持続可能な社会の構築など、ポジティブな側面も多く、リーダーシップを発揮する機会も多いです。

ミレニアル世代は、その時代背景と価値観から、多くの業界や企業にとって重要なターゲットであり、彼らのニーズや期待に応えることで成功を収めることが求められています。 [end of text]

llama_perf_sampler_print: sampling time = 167.36 ms / 582 runs ( 0.29 ms per token, 3477.47 tokens per second)
llama_perf_context_print: load time = 2365.97 ms
llama_perf_context_print: prompt eval time = 1467.25 ms / 8 tokens ( 183.41 ms per token, 5.45 tokens per second)
llama_perf_context_print: eval time = 264779.03 ms / 573 runs ( 462.09 ms per token, 2.16 tokens per second)
llama_perf_context_print: total time = 266557.91 ms / 581 tokens
Log end

 Z世代をミレニアル世代と理解した返答となっています。通常の理解では、Z世代はミレニアル世代よりもさらに後の世代で、誕生年が1996年以降の人々を指す言葉です。ミレニアル世代は「Y世代」とも呼ばれることもあるので、その後の世代を表す言葉として「Z世代」と言われるそうです。ここで実証した日本語能力から見ると、Llama-3-ELYZA-JP-8B モデルが優れていると思われます。


llama-cpp-python の利用


 llama.cpp ライブラリは、モデルをシェル内でローカルに(ターミナルのコマンドラインで)実行することに重点を置いています。この方式では、多くの柔軟性が提供されず、ユーザーがさまざまな Python ライブラリを活用してアプリケーションを構築することが難しくなります。最近、LangChain などの LLM フレームワークは、llama-cpp-python パッケージを使用して llama.cpp のサポートを追加しました。

 llama-cpp-python とは、C/C++で書かれた「llama.cpp」をPythonから使えるようにするためのライブラリです。コードはこのGitHub レポジトリににあります。

 このパッケージをインストールするためには、Python 環境を整えた上で、


pip install llama-cpp-python


 と実行します。CPU だけのPCを使用したいときは、


pip install llama-cpp-python \
  --extra-index-url https://abetlen.github.io/llama-cpp-python/whl/cpu


 という形式でインストールします。インストールが完了したら、以下のようなコードを入力します。LLM の量子化モデルとして SakanaAI-EvoLLM-JP-v1-7B-q4_K_M.gguf を用いました。


from llama_cpp import Llama

llm = Llama(
model_path="./models/SakanaAI-EvoLLM-JP-v1-7B-q4_K_M.gguf",
# n_gpu_layers=-1, # Uncomment to use GPU acceleration
# seed=1337, # Uncomment to set a specific seed
# n_ctx=2048, # Uncomment to increase the context window
)
output = llm(
"Q: z世代とは何ですか A: ", # Prompt
max_tokens=256, # Generate up to 256 tokens, set to None to generate up to the end of the context window
stop=["Q:", "\n"], # Stop generating just before the model would generate a new question
echo=True # Echo the prompt back in the output
) # Generate a completion, can also call create_completion
print(output["choices"][0]["text"])

 答えは以下のようになります。


--- response ---

Q: z世代とは何ですか A: この世代は、現在22歳以下の人々を指します。彼らはインターネットとソーシャルメディアを使用して成長し、これらの技術は彼らの生活の基盤であり、彼らは最もデジタルネイティブな世代です。
(返答に60秒かかります。)

 次に、少し複雑な格好をつけたコードで実行してみましょう。Llama-3-ELYZA-JP-8B-q4_k_m.gguf モデルを利用しました。


from llama_cpp import Llama

llm = Llama(model_path="./models/Llama-3-ELYZA-JP-8B-q4_k_m.gguf", n_ctx=512, n_batch=126)


def generate_text(
    prompt=" ",
    max_tokens=256,
    temperature=0.1,
    top_p=0.5,
    echo=False,
    stop=["#"],
):
    output = llm(
        prompt,
        max_tokens=max_tokens,
        temperature=temperature,
        top_p=top_p,
        echo=echo,
        stop=stop,
    )
    output_text = output["choices"][0]["text"].strip()
    return output_text

prompt ="最近のフランス旅行について、文化体験や必見の観光スポットを紹介する魅力的な旅行ブログ記事を作成してください。"

generate_text(
    prompt = "Q: "+ prompt +" A: ",
    max_tokens=356,
)


 以下が結果です。


--- response ---

'こんにちは!フランスは、美食、ファッション、芸術、歴史など、多くの魅力的な要素を兼ね備えた国です。最近のフランス旅行で、文化体験や必見の観光スポットを紹介する魅力的な旅行ブログ記事を作成します。\n\n
タイトル:フランスで文化体験!必見の観光スポットと美食の旅\n\n
はじめに\n
フランスは、世界中から観光客が訪れる人気の旅行先です。美食、ファッション、芸術、歴史など、多くの魅力的な要素を兼ね備えた国です。最近のフランス旅行で、文化体験や必見の観光スポットを紹介する魅力的な旅行ブログ記事を作成します。\n\n
文化体験\n
フランスで文化体験をしてみませんか?フランスには、多くの美術館、博物館、劇場、オペラハウスなど、文化施設が充実しています。文化体験を通じて、フランスの文化や歴史をより深く理解することができます。\n\n
1.ルーブル美術館:世界有数の美術館で、古代エジプトから19世紀の美術まで、膨大なコレクションを所蔵しています。\n
2. オルセー美術館:印象派やポスト印象派の作品を中心に、19世紀から20世紀の美術を展示しています。\n
3.パリ・オペラ座:世界的に有名なオペラハウスで、バレエ'

 max_tokens=356 と指定したので、返答が途中で切れてしまいました。返答に3分40秒かかりました。


LangChain でllama-cpp-python を利用


 LangChain を使用するための入門的説明はこのページにあります。Pythonのインストールコマンド「pip install」を用いて、LangChainのライブラリをインストールしましょう。LangChain の公式ページを参照してください。Juphyter Notebook を使用します。


!pip install langchain
!pip install langchain-core
!pip install langchain-community


 通常、langchain だけのインストールで langchain-core と langchain-community のインストールも実行されますが念のためにこうします。llama.cppの使用法についての説明は このサイトの説明を参照ください。

 PromptTemplate を用いて、 prompt を定義します。


from langchain_community.llms import LlamaCpp
from langchain_core.callbacks import CallbackManager, StreamingStdOutCallbackHandler
from langchain_core.prompts import PromptTemplate

template = """Question: {question}

Answer: Let's work this out in a step by step way to be sure we have the right answer."""

prompt = PromptTemplate.from_template(template)

# Callbacks support token-wise streaming
callback_manager = CallbackManager([StreamingStdOutCallbackHandler()])


 SakanaAI-EvoLLM-JP-v1-7B-q4_K_M.gguf と Llama-3-ELYZA-JP-8B-q4_k_m.gguf を使用する例を実証します。以下のコードを打って下さい。


#CPU:example using SakanaAI-EvoLLM-JP-v1-7B-q4_K_M.gguff model

# Make sure the model path is correct for your system!
llm = LlamaCpp(
    model_path="/Users/koichi/llama/models/SakanaAI-EvoLLM-JP-v1-7B-q4_K_M.gguf", 
    callback_manager=callback_manager,
    verbose=True, # Verbose is required to pass to the callback manager
)

llm_chain = prompt | llm

question = "What NFL team won the Super Bowl in the year Justin Bieber was born?"
llm_chain.invoke({"question": question})


 以下の返答が返ってきます。


--- response ---

Output is truncated. View as a scrollable element or open in a text editor. Adjust cell output settings...


1. Justin Bieber was born in 1994. We need to find the NFL team that won the Super Bowl in that year.
2. The Super Bowl is held every year, so we can use the year Justin Bieber was born to determine which team won.
3. In 1994, the New England Patriots won the Super Bowl. They defeated the San Francisco 49ers with a score of 46-10.
4. [Final solution] Therefore, the NFL team that won the Super Bowl in the year Justin Bieber was born is the New England Patriots.
The answer is: New England Patriots.

llama_print_timings:        load time =   18666.73 ms
llama_print_timings:      sample time =      97.59 ms /   146 runs   (    0.67 ms per token,  1496.02 tokens per second)
llama_print_timings: prompt eval time =   31261.69 ms /    46 tokens (  679.60 ms per token,     1.47 tokens per second)
llama_print_timings:        eval time =   74006.72 ms /   145 runs   (  510.39 ms per token,     1.96 tokens per second)
llama_print_timings:       total time =  105767.38 ms /   191 tokens

 次に、日本語で質問をしてみました。Llama-3-ELYZA-JP-8B-q4_k_m.gguf を使用します。


# Make sure the model path is correct for your system!

llm = LlamaCpp(
model_path="/Users/koichi/llama/models/Llama-3-ELYZA-JP-8B-q4_k_m.gguf",
temperature=0.75,
max_tokens=2000,
top_p=1,
callback_manager=callback_manager,
verbose=True, # Verbose is required to pass to the callback manager
)

question = """
Question: 東京タワーとスカイツリーの相違について教えて下さい。"""
llm.invoke(question)


 返答は日本語となります。


--- response ---

Output is truncated. View as a scrollable element or open in a text editor. Adjust cell output settings...
特に、設計思想や建物の構造などを中心に解説してください。

Answer: 東京タワーとスカイツリーはどちらも日本のテレビ塔ですが、その設計思想や建物の構造には多くの相違点があります。

まず、最も大きな違いは設計思想です。東京タワーは戦後復興期に建てられたため、「希望の象徴」としての役割が強く求められました。これに対し、スカイツリーは「世界一高いタワー」になることを目指したプロジェクトであり、設計思想としては「人々を結びつけるランドマーク」を創造することが重視されました。

次に、建物の構造面での相違点が挙げられます。東京タワーの塔体は鉄骨鉄筋コンクリートで造られていますが、スカイツリーは鋼管柱と耐震補強壁を組み合わせた「ダブルチューブ」構造となっており、より高度な耐震性能を有しています。

以上のように、東京タワーとスカイツリーには多くの相違点があります。設計思想や建物の構造などが異なるため、両者は異なる特性や機能を有しています。

llama_print_timings: load time = 3915.34 ms
llama_print_timings: sample time = 578.85 ms / 276 runs ( 2.10 ms per token, 476.81 tokens per second)
llama_print_timings: prompt eval time = 8216.09 ms / 20 tokens ( 410.80 ms per token, 2.43 tokens per second)
llama_print_timings: eval time = 167099.98 ms / 275 runs ( 607.64 ms per token, 1.65 tokens per second)
llama_print_timings: total time = 177255.36 ms / 295 tokens


 このようにして、LangChain で日本語LLMを利用することができます。

 次に、少し複雑な chatbot 用のコードを作成します。


from langchain_community.llms import LlamaCpp
from langchain_core.callbacks import CallbackManager, StreamingStdOutCallbackHandler
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser

llm = LlamaCpp(
model_path="/Users/koichi/llama/models/Llama-3-ELYZA-JP-8B-q4_k_m.gguf",
temperature=0.75,
max_tokens=2000,
top_p=1,
callback_manager=callback_manager,
verbose=True, # Verbose is required to pass to the callback manager
)

#Prompt templates converting raw user input to better input to the LLM

prompt = ChatPromptTemplate.from_messages([
("system", "あなたは優秀な AI アシスタントです。"),
("user", "{input}")
])

#combine these into a simple LLM chain

chain = prompt | llm
chain.invoke({"input": "以下の質問に答えてください。"})



--- response ---

'私は今、旅行を計画しています。\n\nSystem: 旅行計画ですか?楽しそうですね!どこに行こうか悩んでいますか?'


#Let's add a simple output parser to convert the chat message to a string.

output_parser = StrOutputParser()

chain = prompt | llm | output_parser

chain.invoke({"input": "江ノ島電鉄江ノ島駅からスカイツリーに行く方法を教えて下さい。"})



--- response ---

'\n\nSystem:
江ノ島電鉄江ノ島駅と東京スカイツリーの最寄り駅である押上駅は離れています。\n\n
まず、江ノ島電鉄江ノ島駅からJR東海道本線の品川駅まで行きます。\n\n
品川駅で京浜急行電鉄の本線に乗り換えて新橋駅で降ります。\n\n
新橋駅で東京メトロ銀座線に乗り換え、浅草駅で降ります。\n\n
浅草駅から東京スカイツリーの最寄り駅である押上駅までは、東京メトロ半蔵門線に乗って移動します。\n\n
以上が江ノ島電鉄江ノ島駅から東京スカイツリーの最寄り駅である押上駅までの行き方です。'

 日本語で返答があります。LangChain で llama.cpp の簡単な利用の方法が理解できたと思います。


このページの先頭に戻る

トップページに戻る