<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>python - まったり勉強ノート</title>
	<atom:link href="https://www.mattari-benkyo-note.com/tag/python/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.mattari-benkyo-note.com</link>
	<description>shuの日々の勉強まとめ</description>
	<lastBuildDate>Mon, 17 Nov 2025 21:45:14 +0000</lastBuildDate>
	<language>ja</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.8.3</generator>
<site xmlns="com-wordpress:feed-additions:1">189243286</site>	<item>
		<title>PLaMo 3 の事前学習モデルを推論させてみる</title>
		<link>https://www.mattari-benkyo-note.com/2025/11/18/plamo-3-inference/</link>
					<comments>https://www.mattari-benkyo-note.com/2025/11/18/plamo-3-inference/#respond</comments>
		
		<dc:creator><![CDATA[Shuji Suzuki (shu)]]></dc:creator>
		<pubDate>Mon, 17 Nov 2025 21:45:13 +0000</pubDate>
				<category><![CDATA[プログラミング]]></category>
		<category><![CDATA[llm]]></category>
		<category><![CDATA[plamo]]></category>
		<category><![CDATA[python]]></category>
		<guid isPermaLink="false">https://www.mattari-benkyo-note.com/?p=3320</guid>

					<description><![CDATA[<p>先日PFNで開発しているPLaMo 3の事前学習モデルの小規模なモデルが公開されました。 https://huggingface.co/collections/pfnet/plamo-3 どのようなモデルなのかはPFNの [&#8230;]</p>
<p>The post <a href="https://www.mattari-benkyo-note.com/2025/11/18/plamo-3-inference/">PLaMo 3 の事前学習モデルを推論させてみる</a> first appeared on <a href="https://www.mattari-benkyo-note.com">まったり勉強ノート</a>.</p>]]></description>
										<content:encoded><![CDATA[<p>先日PFNで開発しているPLaMo 3の事前学習モデルの小規模なモデルが公開されました。</p>



<p><a href="https://huggingface.co/collections/pfnet/plamo-3">https://huggingface.co/collections/pfnet/plamo-3</a></p>



<p>どのようなモデルなのかはPFNのブログのほうに書かれています。</p>



<figure class="wp-block-embed is-type-wp-embed is-provider-preferred-networks-tech-blog wp-block-embed-preferred-networks-tech-blog"><div class="wp-block-embed__wrapper">
<blockquote class="wp-embedded-content" data-secret="MaWsT7D335"><a href="https://tech.preferred.jp/ja/blog/plamo_3_8b_31b/">大規模言語モデルの次期バージョン PLaMo 3 シリーズにおける8B, 31Bの小規模モデルによる事前学習の検証</a></blockquote><iframe class="wp-embedded-content" sandbox="allow-scripts" security="restricted"  title="&#8220;大規模言語モデルの次期バージョン PLaMo 3 シリーズにおける8B, 31Bの小規模モデルによる事前学習の検証&#8221; &#8212; Preferred Networks Tech Blog" src="https://tech.preferred.jp/ja/blog/plamo_3_8b_31b/embed/#?secret=MaWsT7D335" data-secret="MaWsT7D335" width="600" height="338" frameborder="0" marginwidth="0" marginheight="0" scrolling="no"></iframe>
</div></figure>



<p>簡単にPLaMo 3がどういうモデルか説明すると、PLaMo 2のときと同様、日本語のデータを大量にいれつつ、PLaMo 3では海外勢のLLMと差が大きかった学術的な部分の知識を増やすような取り組みをして、精度が上がったよというモデルになっています。</p>



<p>まだ、小規模モデルの検証段階のモデルが公開されているだけですが、最終的なモデルはもっとよくなる（はず）。</p>



<p>今回はPLaMo 2のとき少し面倒だった推論環境構築がPLaMo 3になったことで簡単になったので、2Bを使ってGoogle Colabで簡単に推論できる例を示そうと思います。</p>



<p>PLaMo 3は高速な推論が可能なvLLMでも簡単に動かせる仕組みが用意されているので、今回はhugging faceの仕組みを使った推論に加えて、vLLMによる推論の例も示します。</p>



<p>コードに関してはgithub上に置いてあります。コード全体を見たい方はこちらをご覧ください。</p>



<p><a href="https://github.com/shu65/plamo-3-inference/blob/main/plamo_3_hf_inference_example.ipynb">https://github.com/shu65/plamo-3-inference/blob/main/plamo_3_hf_inference_example.ipynb</a></p>



<p><a href="https://github.com/shu65/plamo-3-inference/blob/main/plamo_3_vllm_inference_example.ipynb">https://github.com/shu65/plamo-3-inference/blob/main/plamo_3_vllm_inference_example.ipynb</a></p>



<p>注意点としては、事前学習を触ろうと思っている人ならご存じだと思いますが、精度が高いモデルでも事前学習モデルは結構めちゃくちゃなことを言います。このため、めちゃくちゃな推論結果でも事前学習モデルならそうだよね、という感じで流してもらえればと思います。ある程度指示を聞くようにするSFTのやり方も後日公開予定です。指示をちゃんと聞かせたいという方はそちらもご覧ください。</p>



<h2 class="wp-block-heading">PLaMo 3を使うための事前準備</h2>



<p>PLaMo 3はダウンロードする前にライセンスに承認が必要になります。今回例で示す、PLaMo 3の2Bモデルである「PLaMo 3 NICT 2B Base」だと初めてアクセスする場合は以下のような画面になっています。</p>



<figure class="wp-block-image size-large"><img fetchpriority="high" decoding="async" width="1024" height="883" src="https://www.mattari-benkyo-note.com/wp-content/uploads/2025/11/image-1024x883.png" alt="" class="wp-image-3321" srcset="https://www.mattari-benkyo-note.com/wp-content/uploads/2025/11/image-1024x883.png 1024w, https://www.mattari-benkyo-note.com/wp-content/uploads/2025/11/image-300x259.png 300w, https://www.mattari-benkyo-note.com/wp-content/uploads/2025/11/image-768x662.png 768w, https://www.mattari-benkyo-note.com/wp-content/uploads/2025/11/image-1536x1324.png 1536w, https://www.mattari-benkyo-note.com/wp-content/uploads/2025/11/image.png 1807w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p>こちらHugging Faceにログインし、ライセンスを確認のうえ、acceptをおしてください。</p>



<p>次にGoogle Colabで使うランタイムを変更します。</p>



<p>Google Colabでnotebookを開いたあと、右上の下矢印をクリックすると以下のようなメニューがでてきます。</p>



<figure class="wp-block-image size-large"><img decoding="async" width="1024" height="687" src="https://www.mattari-benkyo-note.com/wp-content/uploads/2025/11/image-1-1024x687.png" alt="" class="wp-image-3322" srcset="https://www.mattari-benkyo-note.com/wp-content/uploads/2025/11/image-1-1024x687.png 1024w, https://www.mattari-benkyo-note.com/wp-content/uploads/2025/11/image-1-300x201.png 300w, https://www.mattari-benkyo-note.com/wp-content/uploads/2025/11/image-1-768x515.png 768w, https://www.mattari-benkyo-note.com/wp-content/uploads/2025/11/image-1.png 1032w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p>このうち、「ランタイムのタイプを変更」をクリックしてください。するとこのようなポップアップが出てきます。</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="812" src="https://www.mattari-benkyo-note.com/wp-content/uploads/2025/11/image-2-1024x812.png" alt="" class="wp-image-3323" srcset="https://www.mattari-benkyo-note.com/wp-content/uploads/2025/11/image-2-1024x812.png 1024w, https://www.mattari-benkyo-note.com/wp-content/uploads/2025/11/image-2-300x238.png 300w, https://www.mattari-benkyo-note.com/wp-content/uploads/2025/11/image-2-768x609.png 768w, https://www.mattari-benkyo-note.com/wp-content/uploads/2025/11/image-2.png 1096w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p>私の画面では有料のクレジットがある状態なので、T4以外にもL4が選択できるようになっていますが、無料の方は選択できないようになっていると思います。Hugging Faceのみの推論を試す場合は、無料で使えるT4で、vLLMを試したい方はL4にしてください。</p>



<p>ランタイムの設定が終わればここからはHugging FaceとvLLMで少し違うので個別に説明していきます。</p>



<h2 class="wp-block-heading">PLaMo 3の推論 Hugging Face編</h2>



<p>Hugging Faceの仕組みで実行するのはすごく簡単で、Google Colabで必要なパッケージはデフォルトで入っているので、基本的にpipインストールなどは必要ありません。ただ、Hugging Faceはすごい勢いで後方互換を壊していくので、最新のHugging Faceの<code>transformers</code>などのバージョンでは動かないということが発生する可能性があります。その時はnotebookにある<code>transformers==4.57.1</code> にしてみるなど試してみてください。</p>



<p>pipインストールが必要ないので、まずはHugging Faceにアクセスするためのトークンを設定します。やり方としては以下のコマンドをnotebook上でたたきます。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-plain"><code>!hf auth login</code></pre></div>



<p>これをたたくとtokenを生成するページのURLが表示されるので、サイトにアクセスして、tokenを作り、tokenを入力するということをしてください。</p>



<p>tokenを入力したら、Hugging Faceからモデルをダウンロードができるようになります。やり方は以下の通りです。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-python" data-lang="Python"><code>from transformers import AutoTokenizer, AutoModelForCausalLM
tokenizer = AutoTokenizer.from_pretrained(&quot;pfnet/plamo-3-nict-2b-base&quot;, trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained(&quot;pfnet/plamo-3-nict-2b-base&quot;, trust_remote_code=True)</code></pre></div>



<p>ここでエラーがでたらモデルの承認ができていない、Google Colab上でHagging Faceのtokenが指定できてないなどが考えられますので、戻って確認してください。</p>



<p>ダウンロードできれば以下のように推論することが可能です。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-python" data-lang="Python"><code>text = &quot;これからの人工知能技術は&quot;
input_ids = tokenizer(text, return_tensors=&quot;pt&quot;).input_ids
generated_tokens = model.generate(
    inputs=input_ids,
    max_new_tokens=32,
    do_sample=True,
    top_k=50,
    top_p=0.95,
    temperature=1.0,
)[0]
generated_text = tokenizer.decode(generated_tokens)
print(generated_text)</code></pre></div>



<p>出力としてはこのようなものが出てくると思います。</p>



<pre class="wp-block-preformatted">&lt;|plamo:bos|>これからの人工知能技術はAIの進化系であり、音声の文字起こしや翻訳といった従来の用途の枠を超えた、全く新しい可能性を切り拓いていくことでしょう。<br>10年以上、ディープラーニング</pre>



<p>これでHugging FaceのAPIを使ったPLaMo 3の推論ができました。</p>



<h2 class="wp-block-heading">PLaMo 3の推論 vLLM編</h2>



<p>次にPLaMo 3のvLLMを使った推論のやり方を示します。vLLMを使う場合はまずは以下のようにPLaMo 3用のvLLMのpluginをインストールします。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-plain"><code>!pip install --no-cache git+https://github.com/pfnet-research/vllm-plamo3-plugin.git</code></pre></div>



<p>ここで<code>--no-cache</code> を付けないと、Google Colabのイメージに変なキャッシュがあるのか、pipインストールでエラーがでるので注意してください。</p>



<p>インストールが終わったらHugging Face編と同じようにHugging Faceのtokenを設定するために以下のようにコマンドをたたきます。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-plain"><code>!hf auth login</code></pre></div>



<p>その後、出力されたtokenの生成サイトに行き、tokenを作ったあとできたtokenを入力するということをします。</p>



<p>次にvLLMでモデルをダウンロードしてロードします。コードとしては以下の通りです。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-plain"><code>import vllm
model = vllm.LLM(&quot;pfnet/plamo-3-nict-2b-base&quot;, trust_remote_code=True)</code></pre></div>



<p>ダウンロードできればあとは以下のように推論することができます。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-plain"><code>response = model.generate(
    prompts=[&quot;これからの人工知能技術は&quot;],
    sampling_params=vllm.SamplingParams(
        n=1,
        max_tokens=32,
        top_k=50,
        top_p=0.95,
        temperature=1.0,
    ),
)[0]
generated_text = response.outputs[0].text
print(generated_text)</code></pre></div>



<p>出力例としては以下の通り。</p>



<pre class="wp-block-preformatted">AIによる画像認識が主流になるといわれている。自動運転などはすでに実用化されている自動車が事故にあわない為の技術として人工知能が使われている。 例えば自動車が障害物を</pre>



<p>これでvLLMを使った推論もすることができました。</p>



<h2 class="wp-block-heading">終わりに</h2>



<p>今回はPLaMo 3の推論方法にのみ注目して紹介しました。ただ、最初に述べたように今回のモデルは事前学習モデルなので、そのままで使うことは難しいと思っています。このため、簡単にSFTする方法も後日紹介できればと思っています。</p><p>The post <a href="https://www.mattari-benkyo-note.com/2025/11/18/plamo-3-inference/">PLaMo 3 の事前学習モデルを推論させてみる</a> first appeared on <a href="https://www.mattari-benkyo-note.com">まったり勉強ノート</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://www.mattari-benkyo-note.com/2025/11/18/plamo-3-inference/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3320</post-id>	</item>
		<item>
		<title>[書評] 改訂独習Pythonバイオ情報解析 ー バイオのテーブルデータ解析することになったら読む一冊</title>
		<link>https://www.mattari-benkyo-note.com/2025/04/07/python_bioinfo_book_review/</link>
					<comments>https://www.mattari-benkyo-note.com/2025/04/07/python_bioinfo_book_review/#respond</comments>
		
		<dc:creator><![CDATA[Shuji Suzuki (shu)]]></dc:creator>
		<pubDate>Sun, 06 Apr 2025 23:30:00 +0000</pubDate>
				<category><![CDATA[書評]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[バイオインフォマティクス]]></category>
		<category><![CDATA[書籍]]></category>
		<category><![CDATA[機械学習]]></category>
		<guid isPermaLink="false">https://www.mattari-benkyo-note.com/?p=3273</guid>

					<description><![CDATA[<p>今回は「独習Pythonバイオ情報解析」の改訂版「改訂独習Pythonバイオ情報解析」が出たということで読んだので、その紹介になります。 どんな内容の本か？ 年度が変わり、新しい研究室に入ったり、就職した方で「このバイオ [&#8230;]</p>
<p>The post <a href="https://www.mattari-benkyo-note.com/2025/04/07/python_bioinfo_book_review/">[書評] 改訂独習Pythonバイオ情報解析 ー バイオのテーブルデータ解析することになったら読む一冊</a> first appeared on <a href="https://www.mattari-benkyo-note.com">まったり勉強ノート</a>.</p>]]></description>
										<content:encoded><![CDATA[<p>今回は「独習Pythonバイオ情報解析」の改訂版「<a href="https://amzn.to/42k4Ltm" title="改訂独習Pythonバイオ情報解析">改訂独習Pythonバイオ情報解析</a>」が出たということで読んだので、その紹介になります。</p>


		<div class="pochipp-box"
			data-id="3272"
			data-img="l"
			data-lyt-pc="dflt"
			data-lyt-mb="vrtcl"
			data-btn-style="dflt"
			data-btn-radius="on"
			data-sale-effect="none"
			 data-cvkey="8c0321e1"		>
							<div class="pochipp-box__image">
					<a href="https://www.amazon.co.jp/dp/B0DVKXYBB9?tag=shu65-22&#038;linkCode=ogi&#038;th=1&#038;psc=1" rel="nofollow noopener" target="_blank">
						<img loading="lazy" decoding="async" src="https://m.media-amazon.com/images/I/51silEjU90L._SL500_.jpg" alt="" width="120" height="120" />					</a>
				</div>
						<div class="pochipp-box__body">
				<div class="pochipp-box__title">
					<a href="https://www.amazon.co.jp/dp/B0DVKXYBB9?tag=shu65-22&#038;linkCode=ogi&#038;th=1&#038;psc=1" rel="nofollow noopener" target="_blank">
						改訂 独習Pythonバイオ情報解析　生成AI時代に活きるJupyter、NumPy、pandas、Matplotlib、Scanpyの基礎を身につけ、シングルセル、RNA-Seqデータ解析を自分の手で					</a>
				</div>

									<div class="pochipp-box__info">著:先進ゲノム解析研究推進プラットフォーム</div>
				
				
							</div>
				<div class="pochipp-box__btns"
		data-maxclmn-pc="fit"
		data-maxclmn-mb="1"
	>
					<div class="pochipp-box__btnwrap -amazon">
								<a href="https://www.amazon.co.jp/dp/B0DVKXYBB9?tag=shu65-22&#038;linkCode=ogi&#038;th=1&#038;psc=1" class="pochipp-box__btn" rel="nofollow noopener" target="_blank">
					<span>
						Amazon					</span>
									</a>
			</div>
							<div class="pochipp-box__btnwrap -rakuten">
								<a href="https://hb.afl.rakuten.co.jp/hgc/39c5c75e.b3799909.39c5c75f.e5fd5e7d/?pc=https%3A%2F%2Fsearch.rakuten.co.jp%2Fsearch%2Fmall%2F%25E6%2594%25B9%25E8%25A8%2582%25E7%258B%25AC%25E7%25BF%2592Python%25E3%2583%2590%25E3%2582%25A4%25E3%2582%25AA%25E6%2583%2585%25E5%25A0%25B1%25E8%25A7%25A3%25E6%259E%2590&#038;m=https%3A%2F%2Fsearch.rakuten.co.jp%2Fsearch%2Fmall%2F%25E6%2594%25B9%25E8%25A8%2582%25E7%258B%25AC%25E7%25BF%2592Python%25E3%2583%2590%25E3%2582%25A4%25E3%2582%25AA%25E6%2583%2585%25E5%25A0%25B1%25E8%25A7%25A3%25E6%259E%2590" class="pochipp-box__btn" rel="nofollow noopener" target="_blank">
					<span>
						楽天市場					</span>
									</a>
			</div>
											</div>
								<div class="pochipp-box__logo">
					<img loading="lazy" decoding="async" src="https://www.mattari-benkyo-note.com/wp-content/plugins/pochipp/assets/img/pochipp-logo-t1.png" alt="" width="32" height="32">
					<span>ポチップ</span>
				</div>
					</div>
	


<h2 class="wp-block-heading">どんな内容の本か？</h2>



<p>年度が変わり、新しい研究室に入ったり、就職した方で「このバイオのデータを解析して」って言われたらどうしますか？<br>私は今の会社に入った最初、いきなりヒトのとあるテーブルデータを渡されて解析の仕事をすることになり、「困ったぞ」となった記憶があります。<br>そんな私のような「困ったぞ」となったと思った人にお勧めなのが「独習Pythonバイオ情報解析」で、Pythonを使って特にテーブルデータを扱う人は共通して使える知識が詰まった本になっています。</p>



<p>特に改訂版になってLLMを使った解析の流れの説明や注意点などが増えていて、これから初めて解析をするぞという人は読んでおくとよさそうなことがいろいろ書いてあります。<br>一方、この本に向かない人はどんな人かというと、テーブルデータではない解析、例えば最近ありそうなのはタンパク質の立体構造系の話などはこの本はあまり参考にならないと思うので別の本を読んだほうが良いかと思います。<br>例えば最近私もこの辺では以下の本を読んで勉強しています。</p>



<figure class="wp-block-embed is-type-wp-embed"><div class="wp-block-embed__wrapper">
<blockquote class="wp-embedded-content" data-secret="QhGCA65O5t"><a href="https://www.mattari-benkyo-note.com/2025/01/14/structural_bioinformatics_book_review/">[書評] AlphaFold時代の構造バイオインフォマティクス実践ガイド ー 構造バイオインフォマティクスを勉強したい人におすすめな１冊</a></blockquote><iframe loading="lazy" class="wp-embedded-content" sandbox="allow-scripts" security="restricted"  title="&#8220;[書評] AlphaFold時代の構造バイオインフォマティクス実践ガイド ー 構造バイオインフォマティクスを勉強したい人におすすめな１冊&#8221; &#8212; まったり勉強ノート" src="https://www.mattari-benkyo-note.com/2025/01/14/structural_bioinformatics_book_review/embed/#?secret=FWVYHlybyh#?secret=QhGCA65O5t" data-secret="QhGCA65O5t" width="600" height="338" frameborder="0" marginwidth="0" marginheight="0" scrolling="no"></iframe>
</div></figure>



<h2 class="wp-block-heading">どんな人にお勧めか？</h2>



<p>今回は以下のような人にお勧めかと思います。</p>



<ol class="wp-block-list">
<li>Pythonがわからないというプログラム初心者</li>



<li>テーブルデータ解析の注意点がわからないという人</li>
</ol>



<p>この本ではPythonに関して、かなり初級者向けに詳しく紹介してくれています。このため、プログラムが初心者という人が最初に読むにはちょうどよさそうに感じます。また、後半ではsingle cellデータを対象にテーブルデータを解析する上で使いそうな検定の話やクラスタリングの話などが出てきます。このような技術はただ使うのであれば大した知識もなく使えるのですが、結果をちゃんと解釈するとなると、今回のケースで適切な検定方法なのかや、適切なパラメータが使われているのかなど、幅広いことを考える必要があります。<br>このようなことが今回の本ではちゃんと書いてある印象なので、この辺を詳しくないという人は一度読んでみることをお勧めします。</p>



<h2 class="wp-block-heading">個人的に良かった点</h2>



<p>個人的に良かった点としては以下の点です。</p>



<ol class="wp-block-list">
<li>改訂版になってLLMを使った例が最初に入っていて参考になった</li>



<li>忘れがちな解析の注意点を思い出せた</li>
</ol>



<p>特に良かったのが1が個人的には良かったです。第２章のLLMを使った章を書いた東君のXを時々見て、そんな使い方できるだーというのは飛び飛びで知ってたのですが、今回ちゃんと本にまとめてくれたおかげで、理解しやすかった印象です。<br>また、後半の検定やクラスタリングなど私自身最近使ってないので、忘れてたことが多かったのですが、そういえばこういう注意点があったということが思い出せたので良かったです。</p>



<h2 class="wp-block-heading">終わりに</h2>



<p>今回は「<a href="https://amzn.to/42k4Ltm" title="改訂独習Pythonバイオ情報解析">改訂独習Pythonバイオ情報解析</a>」が出たので紹介の記事を書きました。バイオインフォマティクス周りは変化が激しく、古い本では知識が古くて使い物にならないケースもあるのですが、今回のように改訂版がでて、ちゃんと新しい知識が増えた本がでて非常にうれしく思います。<br>定期的にこのように本の紹介記事を書いてます。もし興味があれば他の本の記事も見ていただければ幸いです。</p><p>The post <a href="https://www.mattari-benkyo-note.com/2025/04/07/python_bioinfo_book_review/">[書評] 改訂独習Pythonバイオ情報解析 ー バイオのテーブルデータ解析することになったら読む一冊</a> first appeared on <a href="https://www.mattari-benkyo-note.com">まったり勉強ノート</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://www.mattari-benkyo-note.com/2025/04/07/python_bioinfo_book_review/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3273</post-id>	</item>
		<item>
		<title>PFNの最新LLM PLaMo 2 8BをGoogle ColabでLoRAで学習してみる</title>
		<link>https://www.mattari-benkyo-note.com/2025/04/01/plamo-2-8b-lora/</link>
					<comments>https://www.mattari-benkyo-note.com/2025/04/01/plamo-2-8b-lora/#respond</comments>
		
		<dc:creator><![CDATA[Shuji Suzuki (shu)]]></dc:creator>
		<pubDate>Mon, 31 Mar 2025 23:30:00 +0000</pubDate>
				<category><![CDATA[プログラミング]]></category>
		<category><![CDATA[CUDA]]></category>
		<category><![CDATA[llm]]></category>
		<category><![CDATA[python]]></category>
		<guid isPermaLink="false">https://www.mattari-benkyo-note.com/?p=3255</guid>

					<description><![CDATA[<p>少し前になりますが、PFNが開発しているLLM、PLaMo 2の8Bモデル（事前学習モデル）が公開されました。こちら特殊なライセンスになっていますが、個人が使う分には商業利用も可能なライセンスで公開されています。 このモ [&#8230;]</p>
<p>The post <a href="https://www.mattari-benkyo-note.com/2025/04/01/plamo-2-8b-lora/">PFNの最新LLM PLaMo 2 8BをGoogle ColabでLoRAで学習してみる</a> first appeared on <a href="https://www.mattari-benkyo-note.com">まったり勉強ノート</a>.</p>]]></description>
										<content:encoded><![CDATA[<p>少し前になりますが、PFNが開発しているLLM、<a href="https://huggingface.co/pfnet/plamo-2-8b" target="_blank" rel="noopener" title="PLaMo 2の8Bモデル（事前学習モデル）">PLaMo 2の8Bモデル（事前学習モデル）</a>が公開されました。こちら特殊なライセンスになっていますが、個人が使う分には商業利用も可能なライセンスで公開されています。</p>



<p>このモデルは事前学習モデルなので、そのままではChataGPTなどの普通の人が良く使うLLMと違ってうまく指示を聞くようになっていませんがSFTなどの事後学習を行えばいろいろなタスクをこなせるようにすることが可能です。</p>



<p>この記事では、このような事後学習のやり方の一つとしてGoogle Colabで比較的安く使えるL4というGPUを使って、LoRAという方法で学習するやり方を紹介します。</p>



<p>今回紹介するコードは以下のところにありますので、参考にしてください。</p>



<p><a href="https://github.com/shu65/plamo-2-8b-lora-sft-example/blob/main/PLaMo_2_8B_LoRA_SFT.ipynb">https://github.com/shu65/plamo-2-8b-lora-sft-example/blob/main/PLaMo_2_8B_LoRA_SFT.ipynb</a></p>



<h2 class="wp-block-heading">LoRAとは</h2>



<p>LoRAとは「Low-Rank Adaptation」の略で、大規模言語モデルのような大きなモデルの学習を、メモリが小さいGPU１枚など小規模な計算機環境で学習するために提案された手法です。</p>



<p>具体的にはモデルの一部のLayerに対して低ランクの行列を導入し、低ランクの行列のみ学習することでモデル全体を学習するのと比べて非常に少ないメモリで学習できるようにしています。</p>



<p>このLoRAを使った学習はライブラリがそろっていることもあり、簡単なものはかなり短いコードで書くことができます。</p>



<h2 class="wp-block-heading">PLaMo 2 8B のLoRA</h2>



<p>ここからPLaMo 2 8BでLoRAを使って学習する方法を説明していきます。</p>



<h3 class="wp-block-heading">PLaMo 2 8B 利用規約への同意</h3>



<p>先ほども説明した通りPLaMo 2 8Bは特殊なライセンスということもあり、事前に同意しておく必要があります。</p>



<p>これにはまず、Hugging FaceのサイトのPLaMo 2 8Bのページに行きます。URLは以下の通りです。</p>



<p><a href="https://huggingface.co/pfnet/plamo-2-8b">https://huggingface.co/pfnet/plamo-2-8b</a></p>



<p>このページに行くとまだライセンスに同意していない場合は以下のようにライセンスの一部が表示されていると思います。</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img loading="lazy" decoding="async" width="1024" height="849" src="https://www.mattari-benkyo-note.com/wp-content/uploads/2025/03/スクリーンショット-2025-03-26-215250-1024x849.png" alt="" class="wp-image-3257" style="width:561px;height:auto" srcset="https://www.mattari-benkyo-note.com/wp-content/uploads/2025/03/スクリーンショット-2025-03-26-215250-1024x849.png 1024w, https://www.mattari-benkyo-note.com/wp-content/uploads/2025/03/スクリーンショット-2025-03-26-215250-300x249.png 300w, https://www.mattari-benkyo-note.com/wp-content/uploads/2025/03/スクリーンショット-2025-03-26-215250-768x637.png 768w, https://www.mattari-benkyo-note.com/wp-content/uploads/2025/03/スクリーンショット-2025-03-26-215250-1536x1273.png 1536w, https://www.mattari-benkyo-note.com/wp-content/uploads/2025/03/スクリーンショット-2025-03-26-215250.png 1567w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure></div>


<p>この場合はライセンスを確認の上、同意してください。同意すると以下のような表示になります。</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img loading="lazy" decoding="async" width="1024" height="209" src="https://www.mattari-benkyo-note.com/wp-content/uploads/2025/03/スクリーンショット-2025-03-26-220439-1024x209.png" alt="" class="wp-image-3259" style="width:588px;height:auto" srcset="https://www.mattari-benkyo-note.com/wp-content/uploads/2025/03/スクリーンショット-2025-03-26-220439-1024x209.png 1024w, https://www.mattari-benkyo-note.com/wp-content/uploads/2025/03/スクリーンショット-2025-03-26-220439-300x61.png 300w, https://www.mattari-benkyo-note.com/wp-content/uploads/2025/03/スクリーンショット-2025-03-26-220439-768x157.png 768w, https://www.mattari-benkyo-note.com/wp-content/uploads/2025/03/スクリーンショット-2025-03-26-220439-1536x313.png 1536w, https://www.mattari-benkyo-note.com/wp-content/uploads/2025/03/スクリーンショット-2025-03-26-220439.png 1550w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure></div>


<p>これでPLaMo 2 8Bを使う準備ができました。</p>



<h3 class="wp-block-heading">Google ColabのランタイムでL4を使うようにする</h3>



<p>次に、Google ColabでL4を使う準備をします。Google ColabでL4が使えるように課金が必要になりますので、まずは課金をします。</p>



<p>課金についてはこちらをご覧ください。</p>



<p><a href="https://colab.research.google.com/signup?hl=ja">https://colab.research.google.com/signup?hl=ja</a></p>



<p>今回のコードを動かすだけであれば「Pay As You Go」で100 コンピューティング ユニットを購入すれば十分です。この記事を執筆時点では1200円に満たない程度で購入できます。</p>



<p>課金が済んだら、メニューバーから「ランタイム」→「ランタイムのタイプを変更」をクリックします。すると無料枠では選択できないL4 GPUが選択できるようになっていると思うので、L4 GPUを選択します。</p>



<p>これでGPUを使う準備ができました。</p>



<h3 class="wp-block-heading">必要パッケージのインストール</h3>



<p>次に今回の学習で必要なパッケージをインストールします。コマンドとしては以下の通りです。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-plain"><code>!pip install torch==2.4.1 torchvision==0.19.1 torchaudio==2.4.1 --index-url https://download.pytorch.org/whl/cu124
!pip install trl numba&gt;=0.60.0 mamba-ssm&gt;=2.2.2 causal-conv1d&gt;=1.4.0 transformers&gt;=4.44.2</code></pre></div>



<p>最初にPytorchのバージョンを少し下げていますが、これはPLaMo 2の中で使われているライブラリの一部が最新のPyTorchに対応させるのが結構大変なため、簡単に実行できるようにするために少し古いPyTorchを入れています。</p>



<p>上記のコマンドを実行したあとは、以下のバージョンになっていました。</p>



<pre class="wp-block-preformatted">causal-conv1d                      1.5.0.post8<br>mamba-ssm                          2.2.4<br>numba                              0.60.0<br>numba-cuda                         0.2.0<br>sentence-transformers              3.4.1<br>torch                              2.4.1+cu124<br>torchaudio                         2.4.1+cu124<br>torchsummary                       1.5.1<br>torchvision                        0.19.1+cu124<br>transformers                       4.50.0<br></pre>



<h3 class="wp-block-heading">LoRAのコード</h3>



<p>パッケージをインストールしたら次は以下のようにHugging Faceにログインします。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-python" data-lang="Python"><code>from huggingface_hub import login

login()</code></pre></div>



<p>これを実行するとHugging Faceのtoken を聞かれますのでHugging Faceのtokeを入力してください。</p>



<p>次に各パッケージをimportしておきます。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-python" data-lang="Python"><code>from transformers import AutoModelForCausalLM
from transformers import AutoTokenizer
import datasets
import string
from trl import DataCollatorForCompletionOnlyLM
from trl import SFTConfig, SFTTrainer
from peft import LoraConfig
import torch</code></pre></div>



<p>そして、PLaMo 2 8Bのモデルとtokenizerを以下のようにロードします。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-python" data-lang="Python"><code>model_name = &quot;pfnet/plamo-2-8b&quot;
model = AutoModelForCausalLM.from_pretrained(model_name, trust_remote_code=True, torch_dtype=torch.bfloat16).to(&quot;cuda&quot;)
tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)</code></pre></div>



<p>「PLaMo 2 8B 利用規約への同意」の部分の手順ができていなかったり、Hugging Faceのログインがうまくできていないと、この部分でエラーがでると思われます。その場合は利用規約の同意ができているかや、正しくHugging Faceのログインができているかなどを確認してください。</p>



<p>次に今回使うinstructionデータをダウウンロードして、前処理します。今回は<code>kunishou/databricks-dolly-15k-ja</code> のinputがないデータだけを取り出して利用します。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-python" data-lang="Python"><code>dataset = datasets.load_dataset(&quot;kunishou/databricks-dolly-15k-ja&quot;)
train_dataset = dataset[&quot;train&quot;].filter(lambda data: &quot;instruction&quot; in data and &quot;output&quot; in data and data[&quot;input&quot;] == &quot;&quot;).select(range(2000))

data_collator = DataCollatorForCompletionOnlyLM(
    response_template=tokenizer.encode(&quot; Answer:\n&quot;, add_special_tokens=False),
    tokenizer=tokenizer
)</code></pre></div>



<p>次にLoRAとSFTの引数を指定します。PLaMo 2特有の部分として<code>LoraConfig</code> でLoRAを使って学習するレイヤーを指定する<code>target_modules</code> という引数があります。ここでLLaMa系のようなTransformerの場合、AttensionのQeury, Keyを作るLinearレイヤーをLoRAで学習することが多い印象なので、PLaMo 2でも同じようにAttensionのQueryとKeyを作るLinearレイヤーをLoRAで学習するようにします。PLaMo 2の場合は、Qeury, Key、Valueを作るLinearレイヤーをすべてまとめた<code>qkv_proj</code> というLinearレイヤーがありますので、この<code>qkv_proj</code> を<code>target_modules</code> に指定しています。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-python" data-lang="Python"><code>peft_config = LoraConfig(
    task_type=&quot;CAUSAL_LM&quot;,
    target_modules=[
        &quot;qkv_proj&quot;,
    ],
)

sft_args = SFTConfig(
    output_dir=&quot;./outputs&quot;,
    evaluation_strategy=&quot;no&quot;,
    per_device_train_batch_size=1,
    gradient_accumulation_steps=4,
    learning_rate=5e-5,
    num_train_epochs=1.0,
    lr_scheduler_type=&quot;cosine&quot;,
    warmup_ratio=0.3,
    logging_steps=10,
    save_strategy=&quot;epoch&quot;,
    report_to=&quot;tensorboard&quot;,
    bf16=True,
    max_seq_length=1024,
    gradient_checkpointing=True,
)</code></pre></div>



<p>あとはデータのサンプルに対してフォーマットに合わせて１つのテキストを生成する<code>formatting_func</code> を定義します。今回は以下のようなものを使います。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-plain"><code>INSTRUCTION_TEMPLATE = string.Template(
    &quot;&quot;&quot;### Question:
{input} ### Answer:
{response}&lt;|plamo:eos|&gt;
&quot;&quot;&quot;
)

def formatting_func(example):
  text = INSTRUCTION_TEMPLATE.substitute(input=example[&quot;instruction&quot;], response=example[&quot;output&quot;])
  return text</code></pre></div>



<p>最後に、ここまで用意したものを<code>SFTTrainer</code> に渡して学習を開始します。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-plain"><code>trainer = SFTTrainer(
    model=model,
    args=sft_args,
    peft_config=peft_config,
    data_collator=data_collator,
    train_dataset=train_dataset,
    formatting_func=formatting_func,
)

trainer.train()
trainer.save_model()
     </code></pre></div>



<p>今回の設定では500イテレーション回ることになるはずです。私が試した限りは15分程度で処理が完了しました。</p>



<p>できたモデルの出力が正しいかは以下のコードで確認できます。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-plain"><code>import torch

# プロンプトの準備
prompt = &quot;### Question:\n埼玉の県庁所在地は何市？\n\n### Answer:\n&quot;

# 推論の実行
inputs = tokenizer(prompt, return_tensors=&quot;pt&quot;).to(&quot;cuda&quot;)
generated_tokens = trainer.model.generate(
    **inputs,
    max_new_tokens=64,
    pad_token_id=tokenizer.pad_token_id,
)[0]
generated_text = tokenizer.decode(generated_tokens)
print(generated_text)</code></pre></div>



<p>おそらく以下のような出力がでるはずです</p>



<pre class="wp-block-code"><code>&lt;|plamo:bos|&gt;### Question:
埼玉の県庁所在地は何市？

### Answer:
さいたま市&lt;|plamo:eos|&gt;</code></pre>



<h2 class="wp-block-heading">終わりに</h2>



<p>いかがだったでしょうか？今回はPLaMo 2 8Bに対してLoRAによって学習する方法を紹介しました。LoRAを使えばメモリが少ないL4のようなGPUでも8Bモデル程度で学習することができます。今回のコードを使えば事後学習が簡単にできると思われますので、みなさんもいろいろ試していただければと思っています。無料枠で使えるGPUのT4でも量子化などを頑張れば8Bモデルも学習できる気がしますが、うまくできそうであればそちらも記事にしようと思います。</p>



<p>この他にもPLaMoを含めたLLMの技術も紹介できればと思っています。</p><p>The post <a href="https://www.mattari-benkyo-note.com/2025/04/01/plamo-2-8b-lora/">PFNの最新LLM PLaMo 2 8BをGoogle ColabでLoRAで学習してみる</a> first appeared on <a href="https://www.mattari-benkyo-note.com">まったり勉強ノート</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://www.mattari-benkyo-note.com/2025/04/01/plamo-2-8b-lora/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3255</post-id>	</item>
		<item>
		<title>小型LLM PLaMo 2 1BをGoogle ColabでSFTしてみる</title>
		<link>https://www.mattari-benkyo-note.com/2025/02/13/plamo-2-1b-sft/</link>
					<comments>https://www.mattari-benkyo-note.com/2025/02/13/plamo-2-1b-sft/#respond</comments>
		
		<dc:creator><![CDATA[Shuji Suzuki (shu)]]></dc:creator>
		<pubDate>Wed, 12 Feb 2025 23:30:00 +0000</pubDate>
				<category><![CDATA[プログラミング]]></category>
		<category><![CDATA[CUDA]]></category>
		<category><![CDATA[llm]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[pytorch]]></category>
		<category><![CDATA[機械学習]]></category>
		<guid isPermaLink="false">https://www.mattari-benkyo-note.com/?p=3210</guid>

					<description><![CDATA[<p>今回はPreferred Networksとその子会社のPreferred Elementsが共同で開発した1Bサイズの小型のLLM、PLaMo 2 1Bに対してSFTをするコードの紹介になります。 Google Col [&#8230;]</p>
<p>The post <a href="https://www.mattari-benkyo-note.com/2025/02/13/plamo-2-1b-sft/">小型LLM PLaMo 2 1BをGoogle ColabでSFTしてみる</a> first appeared on <a href="https://www.mattari-benkyo-note.com">まったり勉強ノート</a>.</p>]]></description>
										<content:encoded><![CDATA[<p>今回はPreferred Networksとその子会社のPreferred Elementsが共同で開発した1Bサイズの小型のLLM、<a href="https://huggingface.co/pfnet/plamo-2-1b" title="PLaMo 2 1B">PLaMo 2 1B</a>に対してSFTをするコードの紹介になります。</p>



<p>Google Colabの無料枠で推論を回す方法は前回記事にしましたので、そもそもPLaMo 2 1Bって何と思った方や推論を回してみたいという方はそちらをご覧ください。</p>



<figure class="wp-block-embed is-type-wp-embed"><div class="wp-block-embed__wrapper">
<blockquote class="wp-embedded-content" data-secret="ZZZgUkUP2R"><a href="https://www.mattari-benkyo-note.com/2025/02/12/plamo-2-1b-infernece/">小型LLM PLaMo 2 1BをGoogle Colabの無料枠の範囲で使ってみる</a></blockquote><iframe loading="lazy" class="wp-embedded-content" sandbox="allow-scripts" security="restricted"  title="&#8220;小型LLM PLaMo 2 1BをGoogle Colabの無料枠の範囲で使ってみる&#8221; &#8212; まったり勉強ノート" src="https://www.mattari-benkyo-note.com/2025/02/12/plamo-2-1b-infernece/embed/#?secret=V6iPyeE1qa#?secret=ZZZgUkUP2R" data-secret="ZZZgUkUP2R" width="600" height="338" frameborder="0" marginwidth="0" marginheight="0" scrolling="no"></iframe>
</div></figure>



<p>また、今回説明に使うコードはこちらに置いてありますので、適宜参照してください。</p>



<p><a href="https://github.com/shu65/plamo-2-1b-sft-example">https://github.com/shu65/plamo-2-1b-sft-example</a></p>



<p>Google Colabにおける一連の実行に関してはJupyter Notebookにまとめてありますので、細かい実行方法がわからないという方はこちらをご覧ください</p>



<p><a href="https://github.com/shu65/plamo-2-1b-sft-example/blob/main/run_sft_google_colab.ipynb">https://github.com/shu65/plamo-2-1b-sft-example/blob/main/run_sft_google_colab.ipynb</a></p>



<h2 class="wp-block-heading">Supervised Fine-Tuning(SFT)とは？</h2>



<p>SFTを知らない方に簡単に説明すると、SFTは指示と想定されている回答のペアを用意し、LLMに対して学習を行い、指示に従いやすいモデルを作る方法になります。</p>



<p>特にPLaMo 2 1Bのような事前学習モデルでは、特に指示に従うように学習されていないケースもあり、そのまま利用した際、余計なことをだらだらと出力し続けたり、頓珍漢な回答が返ってきたりという問題が発生することがあります。</p>



<p>このため指示に適切にこたえてもらうための技術がいろいろあるのですが、そのうちの一つにSFTというものがあります。</p>



<h2 class="wp-block-heading">Google ColabでPLaMo 2 1BをSFTする</h2>



<p>それでは本題のGoogle ColabでPLaMo 2 1BをSFTする方法について説明します。今回はGPUメモリの関係上、おそらく無料で使えるT4だと無改造では実行できない気がするのでL4を使った説明をします。</p>



<h3 class="wp-block-heading">L4 GPUの利用</h3>



<p>まず、Google ColabでL4が使えるように、課金が必要になります。</p>



<p>課金についてはこちらをご覧ください。</p>



<p><a href="https://colab.research.google.com/signup?hl=ja">https://colab.research.google.com/signup?hl=ja</a></p>



<p>今回のコードを動かすだけであれば「Pay As You Go」で100 コンピューティング ユニットを購入すれば十分です。この記事を執筆時点では1200円に満たない程度で購入できます。</p>



<p>課金が済んだら、メニューバーから「ランタイム」→「ランタイムのタイプを変更」をクリックします。すると無料枠では選択できないL4 GPUが選択できるようになっていると思うので、L4 GPUを選択します。</p>



<p>これでGPUを使う準備ができました。</p>



<h3 class="wp-block-heading">実行環境準備</h3>



<p>L4を利用するようにしたら、実行するコードのダウンロードやPythonパッケージのインストールを行います。</p>



<p>まずGithubよりコードをcloneしてきます</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-plain"><code>!git clone https://github.com/shu65/plamo-2-1b-sft-example.git</code></pre></div>



<p>次に、PyTorchのバージョンを現在の最新版よりも前の以下のものに変更します。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-plain"><code>!pip install torch==2.4.1 torchvision==0.19.1 torchaudio==2.4.1 --index-url https://download.pytorch.org/whl/cu124</code></pre></div>



<p>この後は以下のようにPyTorch以外のPLaMo 2 1Bの実行に必要なパッケージやSFTに必要なパッケージなどをインストールします。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-plain"><code>!pip install -r plamo-2-1b-sft-example/requirements.txt</code></pre></div>



<p>ここまで実行すると2025/02/12現在以下のようなバージョンがインストールされました。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-plain"><code>causal-conv1d                      1.5.0.post8
fastrlock                          0.8.3
mamba-ssm                          2.2.4
numba                              0.61.0
numba-cuda                         0.0.17.1
sentence-transformers              3.4.1
torch                              2.4.1+cu124
torchaudio                         2.4.1+cu124
torchsummary                       1.5.1
torchvision                        0.19.1+cu124
transformers                       4.48.2
trl                                0.14.0</code></pre></div>



<p>これであとはSFTのコードを実行すれば、SFTをすることができます。このSFTの中身に関しては次で紹介していきます。</p>



<h3 class="wp-block-heading">PLaMo 2 1BをSFTする</h3>



<p>SFTをする部分は<code>sft.py</code>　というスクリプトにまとめてあります。このスクリプトの重要な部分について簡単にですが説明していきます。</p>



<p>まず、今回はすぐに実行が終わるように少量の質問と回答のペアのデータを用います。</p>



<p>今回は日本語の指示学習でよく使われる<a href="https://huggingface.co/datasets/kunishou/databricks-dolly-15k-ja" target="_blank" rel="noopener" title="kunishou/databricks-dolly-15k-ja">kunishou/databricks-dolly-15k-ja</a>というデータセットのうち、<code>input</code> がなく<code>instruction</code> と<code>output</code> のペアになっているデータのみを取り出しその一部だけを利用します。一つ例を見せると以下のようなデータを利用します。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-python" data-lang="Python"><code>{
  &quot;output&quot;: &quot;イコクエイラクブカ&quot;,
  &quot;input&quot;: &quot;&quot;,
  &quot;index&quot;: &quot;1&quot;,
  &quot;category&quot;: &quot;classification&quot;,
  &quot;instruction&quot;: &quot;魚の種類はどっち？イコクエイラクブカとロープ&quot;
}</code></pre></div>



<p>一部だけ取り出すコードは以下の通りです。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-python" data-lang="Python"><code>    dataset = datasets.load_dataset(&quot;kunishou/databricks-dolly-15k-ja&quot;)
    train_dataset = dataset[&quot;train&quot;].filter(lambda data: data[&quot;input&quot;] == &quot;&quot;)</code></pre></div>



<p>次に<code>SFTConfig</code> というSFTの実行の設定のクラスのインスタンスを用意します。具体的には以下の通りです。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-python" data-lang="Python"><code>    sft_args = SFTConfig(
        output_dir=&quot;./outputs&quot;,
        evaluation_strategy=&quot;no&quot;,
        per_device_train_batch_size=1,
        gradient_accumulation_steps=4,
        learning_rate=5e-5,
        num_train_epochs=0.1,
        lr_scheduler_type=&quot;cosine&quot;,
        warmup_ratio=0.3,
        logging_steps=10,
        save_strategy=&quot;epoch&quot;,
        report_to=&quot;tensorboard&quot;,
        bf16=True,
        max_seq_length=1024,
        gradient_checkpointing=True,
        deepspeed=&#39;./deepspeed_config.json&#39;,
    )</code></pre></div>



<p>重要なこととして、今回はGPUのメモリが少ないため、DeepSpeedのStage 3という学習時に一部のデータをCPU側に置いておくモードを利用します。</p>



<p>これによりGPUメモリが少ない環境でもSFTを回すことができます。</p>



<p>DeepSpeed周りの設定は<code>deepspeed_config.json</code> に書いてありますので気になる方はご覧ください。</p>



<p>また、今回は学習データの10%だけを利用するようにしています。これはこの学習を早く終わらせるためであり、本来はもっと回す必要があると考えられますので、本気でSFTをする場合は注意してください。</p>



<p>次にデータをどのようなフォーマットでLLMに入力するかを指定する<code>formatting_func</code> という関数を用意します。今回は以下のようにしました。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-python" data-lang="Python"><code>INSTRUCTION_TEMPLATE = string.Template(
    &quot;&quot;&quot;### Question:
${input}

### Answer:
${response}&lt;|plamo:eos|&gt;
&quot;&quot;&quot;
)


def formatting_func(examples):
    output_texts = []
    for i in range(len(examples[&#39;instruction&#39;])):
        text = INSTRUCTION_TEMPLATE.substitute(input=examples[&#39;instruction&#39;][i], response=examples[&#39;output&#39;][i])
        output_texts.append(text)
    return output_texts</code></pre></div>



<p><code>INSTRUCTION_TEMPLATE</code> が今回のフォーマットで、<code>### Question:\n</code> の後に指示、<code>### Answer:\n</code> のあとに回答が続き、最後にend of sequenceである<code>&lt;|plamo:eos|&gt;</code> が来るようになっています。</p>



<p>また、学習時には回答部分だけを学習してほしいので、どこからが回答かがわかるように<code>‎DataCollatorForCompletionOnlyLM</code> のインスタンスも用意します。これは以下の通りです。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-python" data-lang="Python"><code>    data_collator = DataCollatorForCompletionOnlyLM(
        response_template=tokenizer.encode(&quot; Answer:\n&quot;, add_special_tokens=False),
        tokenizer=tokenizer
    )
</code></pre></div>



<p><code>response_template</code> のところで回答前の部分がどのようなtoken idになるかを指定する部分があるので、上記のように指定します。前後の文字の影響で指定したtoken idが出現しないケースがあるので、その時はいろいろ<code>response_template</code> に指定する文字列を調整してみてください。</p>



<p>最後にSFTを実行するためのクラスの<code>‎SFTTrainer</code> を以下のように用意します。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-python" data-lang="Python"><code>    trainer = SFTTrainer(
        model=model,
        args=sft_args,
        data_collator=data_collator,
        train_dataset=train_dataset,
        tokenizer=tokenizer,
        formatting_func=formatting_func,
    )</code></pre></div>



<p>そして、以下のように実行し、結果を保存します。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-python" data-lang="Python"><code>    trainer.train()
    trainer.save_model()</code></pre></div>



<p>これで学習が終わると<code>SFTConfig</code> の<code>output_dir</code> で指定した<code>./outputs</code> に結果が出力されます。試しに私がGoogle Colabで実行した際は13分程度で学習が終わりました。コンピューティングユニットとしてはパッケージなどのインストールも含めて4だけ消費しました。</p>



<h3 class="wp-block-heading">SFTされたモデルで推論してみる</h3>



<p>最後にSFTされたモデルで推論するというのを行います。</p>



<p>これはPLaMo 2 1Bのexampleとほぼ同じでpromptだけ少し変えたものを例として用います。コードとしては以下の通りです。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-plain"><code>from transformers import AutoTokenizer, AutoModelForCausalLM
import torch


model_name = &quot;./plamo-2-1b-sft-example/outputs&quot;

tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained(model_name, trust_remote_code=True)


# プロンプトの準備
prompt = &quot;### Question:\n埼玉の県庁所在地は何市？\n\n### Answer:\n&quot;

# 推論の実行
inputs = tokenizer(prompt, return_tensors=&quot;pt&quot;)
generated_tokens = model.generate(
    **inputs,
    max_new_tokens=64,
    pad_token_id=tokenizer.pad_token_id,
)[0]
generated_text = tokenizer.decode(generated_tokens)
print(generated_text)</code></pre></div>



<p>出力結果は以下のようになります。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-plain"><code>&lt;|plamo:bos|&gt;### Question:
埼玉の県庁所在地は何市？

### Answer:
埼玉県の県庁所在地はさいたま市です。&lt;|plamo:eos|&gt;</code></pre></div>



<p>ちゃんと学習で指定されたように<code>### Answer:\n</code> の後に質問に対する回答をし、その後<code>&lt;|plamo:eos|&gt;</code> を出力するということができています。</p>



<p>ちなみにSFTしていないモデルではどうなるかというと、以下のように余計なことを出力するうえ、出力が止まらないという状態になっています。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-plain"><code>&lt;|plamo:bos|&gt;### Question:
埼玉の県庁所在地は何市？

### Answer:
さいたま市

### 解説
「県庁所在地」とは、都道府県庁が置かれている都市のことです。
「さいたま市」は埼玉県の県庁所在地です。

### 関連記事
### 取り急ぎお知らせ
「埼玉の県庁所在地は何市？」の解説は以上です。
「埼玉の県庁所在地は何市？」の解説は以上です。</code></pre></div>



<p>このため、SFTでうまくフォーマットに従うよう学習できたと考えられます。</p>



<h2 class="wp-block-heading">終わりに</h2>



<p>今回はPLaMo 2 1Bを使ってSFTをする例を示しました。今回示したように簡単なSFTなら十分Google Colabで実行することができます。みなさんもぜひいろいろ試していただければと思います。</p><p>The post <a href="https://www.mattari-benkyo-note.com/2025/02/13/plamo-2-1b-sft/">小型LLM PLaMo 2 1BをGoogle ColabでSFTしてみる</a> first appeared on <a href="https://www.mattari-benkyo-note.com">まったり勉強ノート</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://www.mattari-benkyo-note.com/2025/02/13/plamo-2-1b-sft/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3210</post-id>	</item>
		<item>
		<title>小型LLM PLaMo 2 1BをGoogle Colabの無料枠の範囲で使ってみる</title>
		<link>https://www.mattari-benkyo-note.com/2025/02/12/plamo-2-1b-infernece/</link>
					<comments>https://www.mattari-benkyo-note.com/2025/02/12/plamo-2-1b-infernece/#respond</comments>
		
		<dc:creator><![CDATA[Shuji Suzuki (shu)]]></dc:creator>
		<pubDate>Tue, 11 Feb 2025 23:30:00 +0000</pubDate>
				<category><![CDATA[プログラミング]]></category>
		<category><![CDATA[GPU]]></category>
		<category><![CDATA[llm]]></category>
		<category><![CDATA[python]]></category>
		<guid isPermaLink="false">https://www.mattari-benkyo-note.com/?p=3195</guid>

					<description><![CDATA[<p>先日Preferred Networksとその子会社のPreferred Elementsが共同で開発した1Bサイズの小型のLLM、PLaMo 2 1Bがリリースされました。 私自身、開発にかかわっているメンバーの一人で [&#8230;]</p>
<p>The post <a href="https://www.mattari-benkyo-note.com/2025/02/12/plamo-2-1b-infernece/">小型LLM PLaMo 2 1BをGoogle Colabの無料枠の範囲で使ってみる</a> first appeared on <a href="https://www.mattari-benkyo-note.com">まったり勉強ノート</a>.</p>]]></description>
										<content:encoded><![CDATA[<p>先日Preferred Networksとその子会社のPreferred Elementsが共同で開発した1Bサイズの小型のLLM、<a href="https://huggingface.co/pfnet/plamo-2-1b" title="PLaMo 2 1B">PLaMo 2 1B</a>がリリースされました。</p>



<p>私自身、開発にかかわっているメンバーの一人です。このモデルは1Bという小さいサイズで手軽に動かすことができます。このため、今回はGoogle Colabの無料枠の範囲で簡単に使う方法を紹介します。</p>



<p>ちなみに今回紹介するGoogle Colabのコードはこちらにあげてあります。<br><a href="https://github.com/shu65/plamo-2-1b-examples/blob/main/plamo_2_1b_inference_example_google_colab_t4.ipynb" target="_blank" rel="noopener" title="">https://github.com/shu65/plamo-2-1b-examples/blob/main/plamo_2_1b_inference_example_google_colab_t4.ipynb</a></p>



<p><br>コードだけ見たいという方はこちらをご覧ください。動作に関しては2025/02/11現在のGoogle Colabで動くことは確認してありますが、時間がたつと動かなくなる可能性があるので注意してください。</p>



<h2 class="wp-block-heading">そもそもPLaMo 2 1Bとはどういうモデルか？</h2>



<p>まず、このモデルがどういうモデルか知っておくと、いろいろトラブルに対処する心構えができると思ったので、簡単にこのモデルについて説明します。</p>



<p>このLLMは、LLaMaなどに代表されるような、よくあるオープンな他のLLMとは違い、独自路線を突っ走っているモデルです。一番際立って違う点として、状態空間モデル（Sate Space Model, SSM）とSliding Window Attensionを組み合わせた<a href="https://arxiv.org/abs/2406.07522v1" title="Samba">Samba</a>で提案されたアーキテクチャベースのモデルになっています。知っている人からすると「マジで？」と思うかもしれませんが、マジです。詳しくはこちらをご覧ください。（アーキテクチャパートはこの辺いろいろ頑張ってくれてたPFEメンバーの力作の説明になっています）</p>



<figure class="wp-block-embed is-type-wp-embed is-provider-preferred-networks-research-amp-development wp-block-embed-preferred-networks-research-amp-development"><div class="wp-block-embed__wrapper">
<blockquote class="wp-embedded-content" data-secret="te92HKKFxD"><a href="https://tech.preferred.jp/ja/blog/plamo-2/">大規模言語モデルの次期バージョン PLaMo 2 の事前検証: SSMの採用と合成データによる性能改善の取り組み</a></blockquote><iframe loading="lazy" class="wp-embedded-content" sandbox="allow-scripts" security="restricted"  title="&#8220;大規模言語モデルの次期バージョン PLaMo 2 の事前検証: SSMの採用と合成データによる性能改善の取り組み&#8221; &#8212; Preferred Networks Research &amp; Development" src="https://tech.preferred.jp/ja/blog/plamo-2/embed/#?secret=te92HKKFxD" data-secret="te92HKKFxD" width="600" height="338" frameborder="0" marginwidth="0" marginheight="0" scrolling="no"></iframe>
</div></figure>



<p>これ以外にも際立って違う部分としてTokenizerがあります。こちらも特に既存のモデルと違う点として、トークン効率を上げるために英語でもスペース区切りをやめている点などがあります。私も最初「スペース区切りやめます！」って言われた時は「マジかよ」って思いましたが、マジで採用しました。これ以外の工夫も開発した方が熱い思いを記事にしていますので興味がある人はご覧ください。</p>



<figure class="wp-block-embed is-type-wp-embed is-provider-preferred-networks-research-amp-development wp-block-embed-preferred-networks-research-amp-development"><div class="wp-block-embed__wrapper">
<blockquote class="wp-embedded-content" data-secret="uDU82SGZDa"><a href="https://tech.preferred.jp/ja/blog/plamo-2-tokenizer/">大規模言語モデル PLaMo 2 のためのトークナイザ性能改善</a></blockquote><iframe loading="lazy" class="wp-embedded-content" sandbox="allow-scripts" security="restricted"  title="&#8220;大規模言語モデル PLaMo 2 のためのトークナイザ性能改善&#8221; &#8212; Preferred Networks Research &amp; Development" src="https://tech.preferred.jp/ja/blog/plamo-2-tokenizer/embed/#?secret=uDU82SGZDa" data-secret="uDU82SGZDa" width="600" height="338" frameborder="0" marginwidth="0" marginheight="0" scrolling="no"></iframe>
</div></figure>



<p>さて、ここでいろいろ既存のモデルと違うということが伝わったかと思いますが、このようにいろいろ独自な部分があり、面白いモデルになっていると思いますが、一方で他のLLMの感覚で使っているとハマる部分があるので、ここからはPLaMo 2 1Bの推論するやり方に焦点を絞って説明していきます。</p>



<h2 class="wp-block-heading">PLaMo 2 1BをGoogle Colabの無料枠で使う</h2>



<p>Google Colabでの使い方に関してはすでにあげてくれている方もいます。記事にしていただきありがとうございます。</p>



<p><a href="https://qiita.com/autotaker1984/items/32109944a6a058161eee">https://qiita.com/autotaker1984/items/32109944a6a058161eee</a></p>



<p>こちらを見ると、有料でしか使えないL4というGPUでのみ動作確認が取れたと報告をいただきました。私も同じように試したところ、L4での動作は確認できたのですが、いろいろな人に使ってもらうためにはやはり無料枠の範囲で試せるほうが良いだろうと思っています。</p>



<p>このため、ここからは無料で使えるT4というGPUでPLaMo 2 1Bを動かす手順を紹介します。</p>



<p>まず、Google ColabでT4が使えるようにメニューバーから「ランタイム」→「ランタイムのタイプを変更」をクリックして、T4 GPUを選択しておいてください。</p>



<p>そして、まずは最初にPyTorchのバージョンを以下のように2.4系に落とします。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-plain"><code>!pip install torch==2.4.1 torchvision==0.19.1 torchaudio==2.4.1 --index-url https://download.pytorch.org/whl/cu124</code></pre></div>



<p>T4でPLaMo 2 1Bを動かすにはこのPyTorchのバージョンを落とすということが重要でした。</p>



<p>この後は以下のように他に必要なパッケージをインストールするだけになります。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-plain"><code>!pip install transformers&gt;=4.44.2 numba&gt;=0.60.0 causal-conv1d==1.4.0 mamba-ssm==2.2.2</code></pre></div>



<p>2025/02/11現在Googel Colab上で上記のコマンドを叩くと以下のようなバージョンのパッケージが入りました。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-plain"><code>causal-conv1d                      1.4.0
mamba-ssm                          2.2.2
numba                              0.61.0
numba-cuda                         0.0.17.1
sentence-transformers              3.4.1
torch                              2.4.1+cu124
torchaudio                         2.4.1+cu124
torchsummary                       1.5.1
torchvision                        0.19.1+cu124
transformers                       4.48.2</code></pre></div>



<p>インストールが終わればあとは簡単で、PLaMo 2 1BのREADMEにある通りに実行するだけになります。実行コードの例としては以下の通りです。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-python" data-lang="Python"><code>from transformers import AutoTokenizer, AutoModelForCausalLM

tokenizer = AutoTokenizer.from_pretrained(&quot;pfnet/plamo-2-1b&quot;, trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained(&quot;pfnet/plamo-2-1b&quot;, trust_remote_code=True)

text = &quot;これからの人工知能技術は&quot;
input_ids = tokenizer(text, return_tensors=&quot;pt&quot;).input_ids
generated_tokens = model.generate(
    inputs=input_ids,
    max_new_tokens=32,
    do_sample=True,
    top_k=50,
    top_p=0.95,
    temperature=1.0,
)[0]
generated_text = tokenizer.decode(generated_tokens)
print(generated_text)</code></pre></div>



<p>私が実行した際は以下のように出力されました。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-plain"><code>&lt;|plamo:bos|&gt;これからの人工知能技術は人間の脳機能をコンピュータに取り入れ、私たちの生活に様々な影響を与えると言われています。人工知能技術の進化により、社会に混乱が生じる可能性があり、AIの規制に関して議論</code></pre></div>



<p>入力で与えた文章の続きとして問題ない文章がちゃんと出力できていると思われます。</p>



<p>このようにT4でも問題なくPLaMo 2 1Bを動かすことができました。</p>



<h2 class="wp-block-heading">終わりに</h2>



<p>この記事ではGoogle ColabのPLaMo 2 1BをGoogle Colabで動かす手順を紹介しました。おそらくGoogle Colabじゃなくても<code>causal-conv1d</code>と<code>mamba-ssm</code> がサポートされている環境であれば動作すると思われます。逆に言えばこの二つがサポートしてない環境では使うのにいろいろ魔改造が必要な可能性があります。</p>



<p>この辺りはハマる人が多いと思われるので、知見がたまったらまた記事にしようと思います。</p>



<p>この記事を参考にみなさんもPLaMo 2 1Bで遊んでもらえればと思います。</p>



<p>PLaMo 2 1BをSupervised Fine-Tuning（SFT）するコードに関しても準備中で、動作確認は済んだので今週中にあげようと思いますのでお楽しみに！</p><p>The post <a href="https://www.mattari-benkyo-note.com/2025/02/12/plamo-2-1b-infernece/">小型LLM PLaMo 2 1BをGoogle Colabの無料枠の範囲で使ってみる</a> first appeared on <a href="https://www.mattari-benkyo-note.com">まったり勉強ノート</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://www.mattari-benkyo-note.com/2025/02/12/plamo-2-1b-infernece/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3195</post-id>	</item>
		<item>
		<title>PFNが開発した国産LLM PLaMo Primeを使ってみる</title>
		<link>https://www.mattari-benkyo-note.com/2024/12/04/plamo_prime_api/</link>
					<comments>https://www.mattari-benkyo-note.com/2024/12/04/plamo_prime_api/#respond</comments>
		
		<dc:creator><![CDATA[Shuji Suzuki (shu)]]></dc:creator>
		<pubDate>Tue, 03 Dec 2024 21:49:49 +0000</pubDate>
				<category><![CDATA[プログラミング]]></category>
		<category><![CDATA[llm]]></category>
		<category><![CDATA[python]]></category>
		<guid isPermaLink="false">https://www.mattari-benkyo-note.com/?p=2999</guid>

					<description><![CDATA[<p>先日、Preferred Networksグループで開発されたPLaMo PrimeというLLMのAPI提供が開始されました。 このPLaMo PrimeはChatのWeb UIもありますが、APIを利用してプログラムか [&#8230;]</p>
<p>The post <a href="https://www.mattari-benkyo-note.com/2024/12/04/plamo_prime_api/">PFNが開発した国産LLM PLaMo Primeを使ってみる</a> first appeared on <a href="https://www.mattari-benkyo-note.com">まったり勉強ノート</a>.</p>]]></description>
										<content:encoded><![CDATA[<p>先日、Preferred Networksグループで開発されたPLaMo PrimeというLLMのAPI提供が開始されました。</p>



<figure class="wp-block-embed is-type-wp-embed is-provider-preferred-networks wp-block-embed-preferred-networks"><div class="wp-block-embed__wrapper">
<blockquote class="wp-embedded-content" data-secret="dQycjin9SR"><a href="https://www.preferred.jp/ja/news/pr20241202/">国産大規模言語モデルPLaMoのフラッグシップモデルPLaMo Primeを新開発</a></blockquote><iframe loading="lazy" class="wp-embedded-content" sandbox="allow-scripts" security="restricted"  title="&#8220;国産大規模言語モデルPLaMoのフラッグシップモデルPLaMo Primeを新開発&#8221; &#8212; Preferred Networks" src="https://www.preferred.jp/ja/news/pr20241202/embed/#?secret=dQycjin9SR" data-secret="dQycjin9SR" width="600" height="338" frameborder="0" marginwidth="0" marginheight="0" scrolling="no"></iframe>
</div></figure>



<p>このPLaMo PrimeはChatのWeb UIもありますが、APIを利用してプログラムから簡単に利用することができるようになっています。Pythonの場合はOpenAIのChatGPTと同じ`openai`というPythonパッケージをほぼ同じように使えば利用することができるので、ChatGPTをAPIで叩いたことがある人はすぐに使えると思っています。</p>



<p>そんなわけで、今回の記事では試しにAPI keyを取得して、PLaMoを使ってみたので、使い方を記事にまとめました。</p>



<p>ちなみに私自身はPFNでPLaMoの開発をしているメンバーなので、感想などについてはある程度バイアスが入った意見を書いているんだろうなーと思いつつ読んでいただければ幸いです。</p>



<h2 class="wp-block-heading">アカウント作成</h2>



<p>まず以下のサイトにアクセスしてアカウントを作ります</p>



<p><a href="https://plamo.preferredai.jp/api">https://plamo.preferredai.jp/api</a></p>



<p>アクセスしたら下で赤で示した「今すぐ登録」のボタンをクリックします。</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="564" src="https://www.mattari-benkyo-note.com/wp-content/uploads/2024/12/plamo_api_top-1-1024x564.png" alt="" class="wp-image-3001" srcset="https://www.mattari-benkyo-note.com/wp-content/uploads/2024/12/plamo_api_top-1-1024x564.png 1024w, https://www.mattari-benkyo-note.com/wp-content/uploads/2024/12/plamo_api_top-1-300x165.png 300w, https://www.mattari-benkyo-note.com/wp-content/uploads/2024/12/plamo_api_top-1-768x423.png 768w, https://www.mattari-benkyo-note.com/wp-content/uploads/2024/12/plamo_api_top-1-1536x846.png 1536w, https://www.mattari-benkyo-note.com/wp-content/uploads/2024/12/plamo_api_top-1-2048x1128.png 2048w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p>すると以下のように「同意事項確認」というページに移動します。ここで日本国内の居住者かどうかなどの確認事項にチェックや利用規約等に問題がないかなどをチェックします。利用規約とプライバシーポリシーはリンクを開かないとチェックできないしようになっています。</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="391" src="https://www.mattari-benkyo-note.com/wp-content/uploads/2024/12/plamo_api_同意-1-1024x391.png" alt="" class="wp-image-3003" srcset="https://www.mattari-benkyo-note.com/wp-content/uploads/2024/12/plamo_api_同意-1-1024x391.png 1024w, https://www.mattari-benkyo-note.com/wp-content/uploads/2024/12/plamo_api_同意-1-300x115.png 300w, https://www.mattari-benkyo-note.com/wp-content/uploads/2024/12/plamo_api_同意-1-768x293.png 768w, https://www.mattari-benkyo-note.com/wp-content/uploads/2024/12/plamo_api_同意-1-1536x587.png 1536w, https://www.mattari-benkyo-note.com/wp-content/uploads/2024/12/plamo_api_同意-1-2048x782.png 2048w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p>チェックが終わると次はクレジットカード登録になります。</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="491" src="https://www.mattari-benkyo-note.com/wp-content/uploads/2024/12/plamo_クレカ登録-1024x491.png" alt="" class="wp-image-3004" srcset="https://www.mattari-benkyo-note.com/wp-content/uploads/2024/12/plamo_クレカ登録-1024x491.png 1024w, https://www.mattari-benkyo-note.com/wp-content/uploads/2024/12/plamo_クレカ登録-300x144.png 300w, https://www.mattari-benkyo-note.com/wp-content/uploads/2024/12/plamo_クレカ登録-768x368.png 768w, https://www.mattari-benkyo-note.com/wp-content/uploads/2024/12/plamo_クレカ登録-1536x737.png 1536w, https://www.mattari-benkyo-note.com/wp-content/uploads/2024/12/plamo_クレカ登録-2048x983.png 2048w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p>クレジットカードの登録が終わればアカウントの作成完了です。アカウントができて、ログインすると以下のようなプロジェクト管理ページに飛びます。</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="299" src="https://www.mattari-benkyo-note.com/wp-content/uploads/2024/12/plamo_api_project_top-1024x299.png" alt="" class="wp-image-3005" srcset="https://www.mattari-benkyo-note.com/wp-content/uploads/2024/12/plamo_api_project_top-1024x299.png 1024w, https://www.mattari-benkyo-note.com/wp-content/uploads/2024/12/plamo_api_project_top-300x88.png 300w, https://www.mattari-benkyo-note.com/wp-content/uploads/2024/12/plamo_api_project_top-768x225.png 768w, https://www.mattari-benkyo-note.com/wp-content/uploads/2024/12/plamo_api_project_top-1536x449.png 1536w, https://www.mattari-benkyo-note.com/wp-content/uploads/2024/12/plamo_api_project_top-2048x599.png 2048w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<h2 class="wp-block-heading">利用上限設定</h2>



<p>この手のLLMのAPIは気を抜くとすごいリクエストを送りまくって、とんでもない額になるということが時々あります。これを防ぐためにPLaMo APIでも利用上限設定が設定できるようになっています。少なくとも個人で使う場合は意図せず高額請求が来ないように自分に合った額に設定しておくことがおすすめです。</p>



<p>設定する際は以下の①のところの「利用上限設定」をクリックして、②の「&#8230;」をクリックして「設定」をクリックします。自分の経験上、使うときは本当に一気に使われるのでアラームではなくハードリミットを1000円に設定しておくということをしておいています。この部分は使いながら調節して無理のない額に調整していく感じになるかと思います。</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="251" src="https://www.mattari-benkyo-note.com/wp-content/uploads/2024/12/plamo_api_limit-1024x251.png" alt="" class="wp-image-3006" srcset="https://www.mattari-benkyo-note.com/wp-content/uploads/2024/12/plamo_api_limit-1024x251.png 1024w, https://www.mattari-benkyo-note.com/wp-content/uploads/2024/12/plamo_api_limit-300x74.png 300w, https://www.mattari-benkyo-note.com/wp-content/uploads/2024/12/plamo_api_limit-768x188.png 768w, https://www.mattari-benkyo-note.com/wp-content/uploads/2024/12/plamo_api_limit-1536x377.png 1536w, https://www.mattari-benkyo-note.com/wp-content/uploads/2024/12/plamo_api_limit-2048x502.png 2048w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<h2 class="wp-block-heading">API key取得</h2>



<p>次にAPI Keyを取得します。API Keyを取得する際は以下のように①の「プロジェクト管理」をクリックし、デフォルトで設定されているプロジェクトの「Default」をクリックしてDefaultのAPI Keyを取得します。</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="680" src="https://www.mattari-benkyo-note.com/wp-content/uploads/2024/12/plamo_api_get_top-1024x680.png" alt="" class="wp-image-3009" srcset="https://www.mattari-benkyo-note.com/wp-content/uploads/2024/12/plamo_api_get_top-1024x680.png 1024w, https://www.mattari-benkyo-note.com/wp-content/uploads/2024/12/plamo_api_get_top-300x199.png 300w, https://www.mattari-benkyo-note.com/wp-content/uploads/2024/12/plamo_api_get_top-768x510.png 768w, https://www.mattari-benkyo-note.com/wp-content/uploads/2024/12/plamo_api_get_top.png 1281w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p>プロジェクトを開くと以下のような画面になります。今すでにAPI Keyが一つ入っていますが、最初は何もないと思います。新しくAPI Keyを追加する場合は右の赤枠の「API キーを追加する」をクリックし、APIキー名を適当につけて「作成」を押すと新しいAPI keyが作成されます。</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="245" src="https://www.mattari-benkyo-note.com/wp-content/uploads/2024/12/plamo_api_defalut-1024x245.png" alt="" class="wp-image-3010" srcset="https://www.mattari-benkyo-note.com/wp-content/uploads/2024/12/plamo_api_defalut-1024x245.png 1024w, https://www.mattari-benkyo-note.com/wp-content/uploads/2024/12/plamo_api_defalut-300x72.png 300w, https://www.mattari-benkyo-note.com/wp-content/uploads/2024/12/plamo_api_defalut-768x183.png 768w, https://www.mattari-benkyo-note.com/wp-content/uploads/2024/12/plamo_api_defalut-1536x367.png 1536w, https://www.mattari-benkyo-note.com/wp-content/uploads/2024/12/plamo_api_defalut-2048x489.png 2048w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p>API Keyが作成がされると以下のようにAPI Keyのシークレットが表示されるので、メモしておきます。</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="451" src="https://www.mattari-benkyo-note.com/wp-content/uploads/2024/12/plamo_api_key-1024x451.png" alt="" class="wp-image-3011" srcset="https://www.mattari-benkyo-note.com/wp-content/uploads/2024/12/plamo_api_key-1024x451.png 1024w, https://www.mattari-benkyo-note.com/wp-content/uploads/2024/12/plamo_api_key-300x132.png 300w, https://www.mattari-benkyo-note.com/wp-content/uploads/2024/12/plamo_api_key-768x338.png 768w, https://www.mattari-benkyo-note.com/wp-content/uploads/2024/12/plamo_api_key.png 1327w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p>これでAPI Keyの取得までできたので、次は実際にPLaMoの出力を取得する流れを説明します。</p>



<h2 class="wp-block-heading">PLaMo Primeの出力をPythonで取得する</h2>



<p>PLaMo Primeを使う方法はいくつかありますが、今回は <code>openai</code> というパッケージを使ってPLaMo Primeを使います。</p>



<p>他の利用方法も含め、使い方はこちらにまとまっています。</p>



<p><a href="https://docs.plamo.preferredai.jp/ja/getting-started">https://docs.plamo.preferredai.jp/ja/getting-started</a></p>



<p>また、今回紹介するコードは手軽に試せるようにGoogle Colabで動作させることを前提に説明していきます。コード全体はこちらにありますので参考にしてください。</p>



<p><a href="https://github.com/shu65/plamo_api_examples/blob/main/plamo_api_example.ipynb">https://github.com/shu65/plamo_api_examples/blob/main/plamo_api_example.ipynb</a></p>



<h3 class="wp-block-heading">環境セットアップ</h3>



<p>Google ColabでPLaMo Primeを使うにあたり、環境をセットアップします。必要なパッケージとしてはPLaMo Primeを使うのに必要な<code>openai</code> とAPI Keyの読み込みに<code>python-dotenv</code> を利用します。</p>



<p>インストールするには以下のようにします。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-plain"><code>!pip install openai python-dotenv</code></pre></div>



<p>次に<code>dotenv</code> を利用してAPI Keyを環境変数にセットします。<code>dotenv</code> で読み込むファイルは予めGoogle Driveに置いておきます。今回は<code>colab_env/plamo_api_env</code> に以下の内容のファイルを置いてある前提で説明します。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-plain"><code>OPENAI_API_KEY=&quot;取得したAPI Key&quot;</code></pre></div>



<p>上のファイルの「取得したAPI Key」の部分は先ほど取得したAPI Keyをコピペしてください。</p>



<p>Googel Driveにこのファイルを設置できたら、以下のコードをGoogle Colab上で実行します。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-python" data-lang="Python"><code>from google.colab import drive
from dotenv import load_dotenv

drive.mount(&#39;/content/drive&#39;)
load_dotenv(dotenv_path=&quot;/content/drive/MyDrive/colab_env/plamo_api_env&quot;)</code></pre></div>



<p><code>drive.mount()</code> を実行するとGoogle Driveに接続していいかの確認メッセージがでますので、許可してください。</p>



<p>許可されると<code>plamo_api_env</code> が読み込まれ、<code>OPENAI_API_KEY</code>という環境変数にAPI Keyがセットされます。</p>



<p>これであとは以下のようにリクエストを送るとPLaMo Primeから回答が返ってきます。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-python" data-lang="Python"><code>
import os
from openai import OpenAI

client = OpenAI(
    base_url=&quot;https://platform.preferredai.jp/api/completion/v1&quot;,
    # other params...,
)

completion = client.chat.completions.create(
    model=&quot;plamo-1.0-prime&quot;,
    messages=[
        {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: &quot;あなたは旅行アドバイザーです&quot;},
        {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;金沢で朝から夕方まで1日のおすすめの観光ルートを教えて下さい&quot;},
    ],
)
     </code></pre></div>



<p>OpenAIのモデルを使うときとPLaMo Primeを使うときで明確に違う点として<code>base_url</code> の指定があります。これが適切なものを指定されていないとPLaMo Primeにリクエストが飛ばないので注意してください。</p>



<p>今回はリファレンスのexampleにある「金沢で朝から夕方まで1日のおすすめの観光ルートを教えて下さい」というリクエストに対する回答をPLaMo Primeに返してもらうコードになっています。</p>



<p>回答結果は以下のように出力することができます。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-python" data-lang="Python"><code>print(completion.choices[0].message.content)</code></pre></div>



<p>私が実行したときは以下のように返ってきました。</p>



<pre class="wp-block-code"><code>金沢で朝から夕方までのおすすめの観光ルートを以下にご紹介いたします。


【午前】

金沢駅からスタートし、金沢の台所と呼ばれる近江町市場で朝食をとります。海鮮丼やお寿司などの金沢グルメをお楽しみください。

近江町市場（お食事）

↓（徒歩5分）

金沢の城下町を再現した長町武家屋敷跡を散策します。土塀の続く街並みを眺めながら、のんびりとお散歩をお楽しみください。

長町武家屋敷跡（散策）

↓（徒歩10分）

金沢市民の台所として親しまれている、金沢の三大市場のひとつ、「金沢市民の台所」として親しまれている、金沢の三大市場のひとつ、「金沢エムザ」でお土産を購入します。

金沢エムザ（お土産購入）


【午後】

兼六園周辺へ移動し、金沢で最も古い神社である石浦神社を参拝します。

石浦神社（参拝）

↓（徒歩5分）

日本三名園のひとつである兼六園を見学します。

兼六園（見学）

↓（徒歩5分）

金沢城公園を散策します。

金沢城公園（散策）

↓（徒歩10分）

尾山神社を参拝します。

尾山神社（参拝）


以上、朝から夕方までのおすすめの観光ルートをご紹介いたしました。

なお、各スポットの営業時間や、その他のご希望などございましたら、お知らせください。お客様のご希望に沿ったプランをご提案いたします。</code></pre>



<p>一応、提案されている場所が本当に金沢にあるかは調べて、確かにあることまでは確認しました。プランとしても一度金沢に行ったとき確か提案された場所を友達と回った記憶があるので、素人目からするとそこまで変なプランを提案されているわけではない印象を持っています。</p>



<h2 class="wp-block-heading">終わりに</h2>



<p>今回はPLaMo Primeがリリースされたということで使い方のまとめの記事を書きました。仕事ではPLaMoを結構叩いているので、他にもいつくか便利な使い方の記事は書いていこうかと思っています。</p>



<p>また、PLaMoに関して技術的な紹介の記事がいくつかすでに公開されているので、興味がある方はそちらもご覧ください。メインの3本は参考に下に示しておきます。</p>



<figure class="wp-block-embed is-type-wp-embed is-provider-preferred-networks-research-amp-development wp-block-embed-preferred-networks-research-amp-development"><div class="wp-block-embed__wrapper">
<blockquote class="wp-embedded-content" data-secret="beEj77Cj4s"><a href="https://tech.preferred.jp/ja/blog/plamo-100b/">1,000億パラメータ規模の独自LLM「PLaMo-100B」の事前学習</a></blockquote><iframe loading="lazy" class="wp-embedded-content" sandbox="allow-scripts" security="restricted"  title="&#8220;1,000億パラメータ規模の独自LLM「PLaMo-100B」の事前学習&#8221; &#8212; Preferred Networks Research &amp; Development" src="https://tech.preferred.jp/ja/blog/plamo-100b/embed/#?secret=beEj77Cj4s" data-secret="beEj77Cj4s" width="600" height="338" frameborder="0" marginwidth="0" marginheight="0" scrolling="no"></iframe>
</div></figure>



<figure class="wp-block-embed is-type-wp-embed is-provider-preferred-networks-research-amp-development wp-block-embed-preferred-networks-research-amp-development"><div class="wp-block-embed__wrapper">
<blockquote class="wp-embedded-content" data-secret="yYnttjguGh"><a href="https://tech.preferred.jp/ja/blog/plamo-100b-post-training/">1,000億パラメータの独自LLM「PLaMo-100B」の事後学習が完了</a></blockquote><iframe loading="lazy" class="wp-embedded-content" sandbox="allow-scripts" security="restricted"  title="&#8220;1,000億パラメータの独自LLM「PLaMo-100B」の事後学習が完了&#8221; &#8212; Preferred Networks Research &amp; Development" src="https://tech.preferred.jp/ja/blog/plamo-100b-post-training/embed/#?secret=yYnttjguGh" data-secret="yYnttjguGh" width="600" height="338" frameborder="0" marginwidth="0" marginheight="0" scrolling="no"></iframe>
</div></figure>



<figure class="wp-block-embed is-type-wp-embed is-provider-preferred-networks-research-amp-development wp-block-embed-preferred-networks-research-amp-development"><div class="wp-block-embed__wrapper">
<blockquote class="wp-embedded-content" data-secret="Zs5x7CIb2a"><a href="https://tech.preferred.jp/ja/blog/extending-plamo-context-length/">事後学習でPLaMoのコンテキスト長を4倍の16kにしました</a></blockquote><iframe loading="lazy" class="wp-embedded-content" sandbox="allow-scripts" security="restricted"  title="&#8220;事後学習でPLaMoのコンテキスト長を4倍の16kにしました&#8221; &#8212; Preferred Networks Research &amp; Development" src="https://tech.preferred.jp/ja/blog/extending-plamo-context-length/embed/#?secret=Zs5x7CIb2a" data-secret="Zs5x7CIb2a" width="600" height="338" frameborder="0" marginwidth="0" marginheight="0" scrolling="no"></iframe>
</div></figure><p>The post <a href="https://www.mattari-benkyo-note.com/2024/12/04/plamo_prime_api/">PFNが開発した国産LLM PLaMo Primeを使ってみる</a> first appeared on <a href="https://www.mattari-benkyo-note.com">まったり勉強ノート</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://www.mattari-benkyo-note.com/2024/12/04/plamo_prime_api/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2999</post-id>	</item>
		<item>
		<title>Hugging FaceのモデルをLangChainで使う方法を調べた</title>
		<link>https://www.mattari-benkyo-note.com/2023/05/19/langchain_hugging_face/</link>
					<comments>https://www.mattari-benkyo-note.com/2023/05/19/langchain_hugging_face/#respond</comments>
		
		<dc:creator><![CDATA[Shuji Suzuki (shu)]]></dc:creator>
		<pubDate>Thu, 18 May 2023 23:21:03 +0000</pubDate>
				<category><![CDATA[プログラミング]]></category>
		<category><![CDATA[langchain]]></category>
		<category><![CDATA[llm]]></category>
		<category><![CDATA[python]]></category>
		<guid isPermaLink="false">https://www.mattari-benkyo-note.com/?p=2813</guid>

					<description><![CDATA[<p>今回はLangChainの小ネタの記事でHugging FaceのモデルをLangChainで扱う方法について調べたので、その記事になります。 LangChainについてご存じないという方のために一言で説明するとLang [&#8230;]</p>
<p>The post <a href="https://www.mattari-benkyo-note.com/2023/05/19/langchain_hugging_face/">Hugging FaceのモデルをLangChainで使う方法を調べた</a> first appeared on <a href="https://www.mattari-benkyo-note.com">まったり勉強ノート</a>.</p>]]></description>
										<content:encoded><![CDATA[<p>今回はLangChainの小ネタの記事で<a href="https://huggingface.co/" target="_blank" rel="noreferrer noopener">Hugging Face</a>のモデルをLangChainで扱う方法について調べたので、その記事になります。</p>



<p>LangChainについてご存じないという方のために一言で説明するとLangChainはChatGPTの内部で使われているLLMを扱いやすい形でwarpしたライブラリになります。紹介記事を以前書きましたので、詳しく知りたい方はこちらをご覧ください。</p>



<figure class="wp-block-embed is-type-wp-embed is-provider-まったり勉強ノート wp-block-embed-まったり勉強ノート"><div class="wp-block-embed__wrapper">
<blockquote class="wp-embedded-content" data-secret="c4u4q0hVUK"><a href="https://www.mattari-benkyo-note.com/2023/03/28/langchain_example/">ChatGPTみたいなアプリが簡単に作れるLangChainがすごすぎ</a></blockquote><iframe loading="lazy" class="wp-embedded-content" sandbox="allow-scripts" security="restricted"  title="&#8220;ChatGPTみたいなアプリが簡単に作れるLangChainがすごすぎ&#8221; &#8212; まったり勉強ノート" src="https://www.mattari-benkyo-note.com/2023/03/28/langchain_example/embed/#?secret=LBSjXcLMLo#?secret=c4u4q0hVUK" data-secret="c4u4q0hVUK" width="600" height="338" frameborder="0" marginwidth="0" marginheight="0" scrolling="no"></iframe>
</div></figure>



<p>LangChainのexampleを見ると多くの場合OpenAIのAPIを使うことが多いように感じます。ただ、OpenAIのモデルは精度が良いのですが、一方で長文の生成をしようとするとかなりの額のお金が必要になります。このため、遊びで使うには勇気がいるケースがあります。</p>



<p>このため、懐に優しい形でLangChainを扱えないか？ということで、有名どころのモデルが大体おいてあるHugging Faceを利用してLangChainで使う方法を調べました。</p>



<p>調べるにあたって作ったコードはここに置いてあります。コード全体が見たいかたはこちらをご覧ください。</p>



<p><a href="https://github.com/shu65/langchain_examples/blob/main/langchain_hugging_face_example.ipynb">https://github.com/shu65/langchain_examples/blob/main/langchain_hugging_face_example.ipynb</a></p>



<h2 class="wp-block-heading">Hugging Faceとは？</h2>



<p>ここ最近、<a href="https://huggingface.co/" target="_blank" rel="noreferrer noopener">Hugging Face</a>は良く目にしますが、念のため説明しておきます。Hugging Faceは様々な機械学習のライブラリを開発している企業で、モデルやデータセットなどを共有するプラットフォームも提供しています。</p>



<p>たとえば、こちらの紹介記事を書いたTransformersはHugging Faceが作っているものになります。</p>



<figure class="wp-block-embed is-type-wp-embed is-provider-まったり勉強ノート wp-block-embed-まったり勉強ノート"><div class="wp-block-embed__wrapper">
<blockquote class="wp-embedded-content" data-secret="wV1K3KSKCs"><a href="https://www.mattari-benkyo-note.com/2023/05/08/transformers_book_review/">[書評] 機械学習エンジニアのためのTransformers ー 自然言語のTransformerについてより知りたい人向けな一冊</a></blockquote><iframe loading="lazy" class="wp-embedded-content" sandbox="allow-scripts" security="restricted"  title="&#8220;[書評] 機械学習エンジニアのためのTransformers ー 自然言語のTransformerについてより知りたい人向けな一冊&#8221; &#8212; まったり勉強ノート" src="https://www.mattari-benkyo-note.com/2023/05/08/transformers_book_review/embed/#?secret=QtlvaACq8c#?secret=wV1K3KSKCs" data-secret="wV1K3KSKCs" width="600" height="338" frameborder="0" marginwidth="0" marginheight="0" scrolling="no"></iframe>
</div></figure>



<p>ここ最近の公開されている有名どころのモデルは大体Hugging Faceからダウンロードできるようになっているので、既存のモデルを試したいというときは非常に便利です。</p>



<p>今回はHugging Faceが運営しているプラットフォームにおいてあるモデルをLangChainで使う方法について説明します。</p>



<h2 class="wp-block-heading">Hugging FaceにおいてあるモデルをLangChainで使う</h2>



<p>Hugging FaceのモデルをLangChainで使う方法としていくつか用意されています。今回はこの中の以下の二つについて紹介します。</p>



<ol class="wp-block-list">
<li>Hugging Face APIを利用する方法</li>



<li>Hugging Faceからモデルをダウンロードしてきて手元の計算機でLLMを動かす方法</li>
</ol>



<p>それぞれ順番に説明していきます。</p>



<h3 class="wp-block-heading">Hugging Face APIを利用する方法</h3>



<p>Hugging Face上においてあるモデルは制約はありますが、API経由で利用することができます。</p>



<p>APIのトークンの取得に関しては公式のチュートリアルを参考にしてください。</p>



<p><a href="https://huggingface.co/docs/api-inference/quicktour">https://huggingface.co/docs/api-inference/quicktour</a></p>



<p>LangChainで利用する場合は<code>HUGGINGFACEHUB_API_TOKEN</code>という環境変数に上で取得したトークンを入れておく必要があります。</p>



<p>今回のコードではnotebookを公開する都合上、トークンの中身がコードにでてこないように<code>dotenv</code> を利用して環境変数の設定をしています。手元で動かす際は以下のようにすれば十分です</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-bash" data-file="set_hugging_face_api.sh" data-lang="Bash"><code>export HUGGINGFACEHUB_API_TOKEN=XXXX</code></pre></div>



<p>あとは以下のようにHugging Face APIを利用したLLMのインスタンスを用意します。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-python" data-file="hugging_face_hub.py" data-lang="Python"><code>from langchain import HuggingFaceHub

repo_id = &quot;google/flan-t5-xl&quot; 

llm = HuggingFaceHub(repo_id=repo_id, model_kwargs={&quot;temperature&quot;:0, &quot;max_length&quot;:64})</code></pre></div>



<p>ここではモデルとして<a href="https://huggingface.co/google/flan-t5-xl" target="_blank" rel="noopener" title="GoogleのFlan-T5のXL">GoogleのFlan-T5のXL</a>というサイズのモデルを利用しています。<code>model_kwargs</code> はモデルごとに指定できるものが違うので注意してください。ここでは<code>temperature</code> と <code>max_length</code> を指定しています。</p>



<p>LLMが用意できればあとはOpenAIのモデルのときと同じ感覚で利用することができます。ここでは簡単にLangChainを使って以下のように質問して答えてもらいます</p>



<pre class="wp-block-preformatted"><code>Who won the FIFA World Cup in the year 1994? </code></pre>



<p>コードとしては以下の通りです。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-python" data-file="run_hugging_face_api_llm" data-lang="Python"><code>template = &quot;&quot;&quot;Question: {question}

Answer: Let&#39;s think step by step.&quot;&quot;&quot;
prompt = PromptTemplate(template=template, input_variables=[&quot;question&quot;])
llm_chain = LLMChain(prompt=prompt, llm=llm)

question = &quot;Who won the FIFA World Cup in the year 1994? &quot;

llm_chain.run(question)</code></pre></div>



<p>このコードは以下のように出力されました。</p>



<pre class="wp-block-preformatted">The FIFA World Cup is a football tournament that is played every 4 years. The year 1994 was the 44th FIFA World Cup. The final answer: Brazil.</pre>



<p>調べてみると1994年は確かにブラジルが優勝しているので正しい回答が得られているようです。</p>



<h3 class="wp-block-heading">Hugging Faceからモデルをダウンロードしてきて手元の計算機でLLMを動かす方法</h3>



<p>次にHugging Faceのモデルを手元にダウンロードしてきてLangChainで利用する方法を説明していきます。</p>



<p>まず、LLMの準備ですが以下のようにします。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-python" data-file="hugging_face_local" data-lang="Python"><code>from langchain.llms import HuggingFacePipeline
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline

model_id = &quot;gpt2&quot;
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(model_id)
pipe = pipeline(
    &quot;text-generation&quot;, model=model, tokenizer=tokenizer, max_new_tokens=64
)
llm = HuggingFacePipeline(pipeline=pipe)</code></pre></div>



<p>Google Colabで動かす都合上、小さめのモデルということでここでは<a href="https://huggingface.co/gpt2" target="_blank" rel="noopener" title="GPT-2">GPT-2</a>を利用しています。</p>



<p>基本的な使い方としては良くあるHugging Faceの使い方である <code>AutoTokenizer</code> と <code>AutoModelForCausalLM</code> を利用してtokenizerとmodelを用意します。その後LangChainが用意している <code>HuggingFacePipeline</code> を使ってLangChainで使えるLLMのインスタンスを作ります。</p>



<p>あとは先ほどと同様にすればLangChainでHugging Faceのモデルを利用することができます。コードはAPIのときと同じため省略します。またGPT-2ということもあり、結果はめちゃくちゃなので、出力結果も省略します。</p>



<h2 class="wp-block-heading">終わりに</h2>



<p>今回はLangChainでHugging Faceのモデルを利用する方法について調べたのでそのまとめを書きました。</p>



<p>LangChainのほうで思った以上に簡単に使えるように整備されている印象で、どの関数を使えばわかっていればすぐに使うことはできました。今回は紹介しませんでしたが他にもHugging Faceのモデルを動かす方法は用意されているようなので興味のある方は調べてみてください。</p>



<p>この記事が他の方の参考になれば幸いです。</p><p>The post <a href="https://www.mattari-benkyo-note.com/2023/05/19/langchain_hugging_face/">Hugging FaceのモデルをLangChainで使う方法を調べた</a> first appeared on <a href="https://www.mattari-benkyo-note.com">まったり勉強ノート</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://www.mattari-benkyo-note.com/2023/05/19/langchain_hugging_face/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2813</post-id>	</item>
		<item>
		<title>LangChainのContextual Compressionのいくつかの機能がどのように実現されているかを確認してみた</title>
		<link>https://www.mattari-benkyo-note.com/2023/05/12/langchain_contextual_compression/</link>
					<comments>https://www.mattari-benkyo-note.com/2023/05/12/langchain_contextual_compression/#respond</comments>
		
		<dc:creator><![CDATA[Shuji Suzuki (shu)]]></dc:creator>
		<pubDate>Thu, 11 May 2023 22:32:51 +0000</pubDate>
				<category><![CDATA[プログラミング]]></category>
		<category><![CDATA[langchain]]></category>
		<category><![CDATA[llm]]></category>
		<category><![CDATA[python]]></category>
		<guid isPermaLink="false">https://www.mattari-benkyo-note.com/?p=2797</guid>

					<description><![CDATA[<p>最近、LangChainの以下の公式blog記事で「Contextual Compression」という機能が紹介されていました。 https://blog.langchain.dev/improving-documen [&#8230;]</p>
<p>The post <a href="https://www.mattari-benkyo-note.com/2023/05/12/langchain_contextual_compression/">LangChainのContextual Compressionのいくつかの機能がどのように実現されているかを確認してみた</a> first appeared on <a href="https://www.mattari-benkyo-note.com">まったり勉強ノート</a>.</p>]]></description>
										<content:encoded><![CDATA[<p>最近、LangChainの以下の公式blog記事で「Contextual Compression」という機能が紹介されていました。</p>



<p><a href="https://blog.langchain.dev/improving-document-retrieval-with-contextual-compression/">https://blog.langchain.dev/improving-document-retrieval-with-contextual-compression/</a></p>



<p>ちょうどこういう機能があったらいいなぁと思っていたところだったので、この機能について調べてみました。今回はそのまとめ記事になります。</p>



<p>今回の記事を書くにあたり、動作チェックをした際のnotebookはここにあげておきました。コードを見たい方はこちらをご覧ください。</p>



<p><a href="https://github.com/shu65/langchain_examples/blob/main/LangChain_Contextual_Compression.ipynb">https://github.com/shu65/langchain_examples/blob/main/LangChain_Contextual_Compression.ipynb</a></p>



<p>また、LangChainがどういうものかご存じない方は以前LangChainの紹介記事を書きましたので、こちらをご覧ください。</p>



<figure class="wp-block-embed is-type-wp-embed is-provider-まったり勉強ノート wp-block-embed-まったり勉強ノート"><div class="wp-block-embed__wrapper">
<blockquote class="wp-embedded-content" data-secret="T0i4X7Rnjk"><a href="https://www.mattari-benkyo-note.com/2023/03/28/langchain_example/">ChatGPTみたいなアプリが簡単に作れるLangChainがすごすぎ</a></blockquote><iframe loading="lazy" class="wp-embedded-content" sandbox="allow-scripts" security="restricted"  title="&#8220;ChatGPTみたいなアプリが簡単に作れるLangChainがすごすぎ&#8221; &#8212; まったり勉強ノート" src="https://www.mattari-benkyo-note.com/2023/03/28/langchain_example/embed/#?secret=W0uyXVOi3m#?secret=T0i4X7Rnjk" data-secret="T0i4X7Rnjk" width="600" height="338" frameborder="0" marginwidth="0" marginheight="0" scrolling="no"></iframe>
</div></figure>



<h2 class="wp-block-heading">Contextual Compressionとは？</h2>



<p>LLMを使ったQAシステムでは関連するドキュメントを見つけてきて、質問と関連ドキュメントをLLMに入れて質問に答えるという形のものがあります。この際、以下のような問題点があります。</p>



<ol class="wp-block-list">
<li>質問と関連してないドキュメントが含まれるケースがある</li>



<li>関連ドキュメントの文字数が多いとLLMに入力できる文字数を圧迫する</li>
</ol>



<p>この問題を解決する方法の手段の一つとしてこの「Contextual Compression」があります。</p>



<p>このContextual Compressionでは関連ドキュメントを見つけたあと、質問により関連している情報だけを抽出します。この抽出された情報と質問をLLMに入れてより的確な質問に答えられるようにするというものです。</p>



<p>LangChainではContextual Compressionの機能としていくつか用意されています。その中でもぱっと見て動作が分かりずらいLLMを使ったものに関して今回はどういうpromptになっているのかを調べたので順番に紹介していきます。</p>



<h3 class="wp-block-heading">LLMChainExtractor</h3>



<p>まず一つ目が「LLMChainExtractor」です。これは関連するドキュメントを見つけたあとLLMによって質問に関連する部分だけを抽出するものになっています。</p>



<p>LLMChainExtractorを使う前の以下のコードは以下の通りです。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-python" data-file="baseline.py" data-lang="Python"><code>from langchain.text_splitter import CharacterTextSplitter
from langchain.embeddings import OpenAIEmbeddings
from langchain.document_loaders import TextLoader
from langchain.vectorstores import FAISS

documents = TextLoader(&#39;./state_of_the_union.txt&#39;).load()
text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
texts = text_splitter.split_documents(documents)
retriever = FAISS.from_documents(texts, OpenAIEmbeddings()).as_retriever()

docs = retriever.get_relevant_documents(&quot;What did the president say about Ketanji Brown Jackson&quot;)</code></pre></div>



<p>このコードの出力は以下のようになります。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-plain"><code>Document 1:

Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections. 

Tonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. 

One of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. 

And I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence.
----------------------------------------------------------------------------------------------------
Document 2:

A former top litigator in private practice. A former federal public defender. And from a family of public school educators and police officers. A consensus builder. Since she’s been nominated, she’s received a broad range of support—from the Fraternal Order of Police to former judges appointed by Democrats and Republicans. 

And if we are to advance liberty and justice, we need to secure the Border and fix the immigration system. 

We can do both. At our border, we’ve installed new technology like cutting-edge scanners to better detect drug smuggling.  

We’ve set up joint patrols with Mexico and Guatemala to catch more human traffickers.  

We’re putting in place dedicated immigration judges so families fleeing persecution and violence can have their cases heard faster. 

We’re securing commitments and supporting partners in South and Central America to host more refugees and secure their own borders.
----------------------------------------------------------------------------------------------------
Document 3:

And for our LGBTQ+ Americans, let’s finally get the bipartisan Equality Act to my desk. The onslaught of state laws targeting transgender Americans and their families is wrong. 

As I said last year, especially to our younger transgender Americans, I will always have your back as your President, so you can be yourself and reach your God-given potential. 

While it often appears that we never agree, that isn’t true. I signed 80 bipartisan bills into law last year. From preventing government shutdowns to protecting Asian-Americans from still-too-common hate crimes to reforming military justice. 

And soon, we’ll strengthen the Violence Against Women Act that I first wrote three decades ago. It is important for us to show the nation that we can come together and do big things. 

So tonight I’m offering a Unity Agenda for the Nation. Four big things we can do together.  

First, beat the opioid epidemic.
----------------------------------------------------------------------------------------------------
Document 4:

Tonight, I’m announcing a crackdown on these companies overcharging American businesses and consumers. 

And as Wall Street firms take over more nursing homes, quality in those homes has gone down and costs have gone up.  

That ends on my watch. 

Medicare is going to set higher standards for nursing homes and make sure your loved ones get the care they deserve and expect. 

We’ll also cut costs and keep the economy going strong by giving workers a fair shot, provide more training and apprenticeships, hire them based on their skills not degrees. 

Let’s pass the Paycheck Fairness Act and paid leave.  

Raise the minimum wage to $15 an hour and extend the Child Tax Credit, so no one has to raise a family in poverty. 

Let’s increase Pell Grants and increase our historic support of HBCUs, and invest in what Jill—our First Lady who teaches full-time—calls America’s best-kept secret: community colleges.</code></pre></div>



<p>それでは次にLLMChainExtractorを使った場合の結果を見てみます。コードとしては以下の通りです。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-python" data-file="LLMChainExtractor" data-lang="Python"><code>from langchain.llms import OpenAI
from langchain.retrievers import ContextualCompressionRetriever
from langchain.retrievers.document_compressors import LLMChainExtractor

llm = OpenAI(temperature=0)
compressor = LLMChainExtractor.from_llm(llm)
compression_retriever = ContextualCompressionRetriever(base_compressor=compressor, base_retriever=retriever)

compressed_docs = compression_retriever.get_relevant_documents(&quot;What did the president say about Ketanji Jackson Brown&quot;)</code></pre></div>



<p>compressed_docsの中身を見てみると以下の通りです。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-plain"><code>Document 1:

&quot;One of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. 

And I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence.&quot;
----------------------------------------------------------------------------------------------------
Document 2:

&quot;A former top litigator in private practice. A former federal public defender. And from a family of public school educators and police officers. A consensus builder. Since she’s been nominated, she’s received a broad range of support—from the Fraternal Order of Police to former judges appointed by Democrats and Republicans.&quot;</code></pre></div>



<p>先ほど変わってドキュメント数が減っているのと、Document 1のほうを見ると出力されている内容もたしかに関連したところだけ残っている感じがしています。この時、どのようなpromtpでLLMを実行されていたかというと、以下のようなテンプレートを使ってpromptを作ってLLMに入力していました。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-python" data-file="LLMChainExtractor_template" data-lang="Python"><code>&quot;&quot;&quot;Given the following question and context, extract any part of the context *AS IS* that is relevant to answer the question. If none of the context is relevant return {no_output_str}. 

Remember, *DO NOT* edit the extracted parts of the context.

&gt; Question: {{question}}
&gt; Context:
&gt;&gt;&gt;
{{context}}
&gt;&gt;&gt;
Extracted relevant parts:&quot;&quot;&quot;</code></pre></div>



<p>{{question}}と{{context}}がそれぞれ入力した質問と関連ドキュメントとして見つけたドキュメントの内容を入れる部分です。</p>



<p>templateを見ると、関連ドキュメントの中から質問に回答と関連すると思われるところを抜き出してくるというものになっています。また、関連していなければ{no_output_str}、実際にはNO_OUTPUTという文字列を返すようになっています。</p>



<p>これにより、見つけてきたドキュメントが関係ないものであればはじくということができるようになっています。</p>



<h3 class="wp-block-heading">LLMChainFilter</h3>



<p>次に「LLMChainFilter」です。これは先ほどの「LLMChainExtractor」と同じようにLLMを使うものになっていますが、見つけたドキュメントが質問に関連するものかどうかだけを判断し、関連しないものであればはじくということだけをするものになっています。つまり、「LLMChainExtractor」であった質問に関連する部分を抽出するという処理がなくなったバージョンという感じかと思います。</p>



<p>LLMChainFilterを利用するコードは以下のようになっています。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-python" data-file="LLMChainFilter" data-lang="Python"><code>from langchain.retrievers.document_compressors import LLMChainFilter

_filter = LLMChainFilter.from_llm(llm)
compression_retriever = ContextualCompressionRetriever(base_compressor=_filter, base_retriever=retriever)

compressed_docs = compression_retriever.get_relevant_documents(&quot;What did the president say about Ketanji Jackson Brown&quot;)</code></pre></div>



<p>このコードの出力結果は以下のようになります。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-plain"><code>Document 1:

Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections. 

Tonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. 

One of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. 

And I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence.</code></pre></div>



<p>オリジナルのコードでは4つ関連ドキュメントがでていましたが、今回は一つだけになっています。</p>



<p>これを実現するためにLLMChainFilterはLLMには以下のようなテンプレートのpromptをLLMに入力しています。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-plain"><code>&quot;&quot;&quot;Given the following question and context, return YES if the context is relevant to the question and NO if it isn&#39;t.

&gt; Question: {question}
&gt; Context:
&gt;&gt;&gt;
{context}
&gt;&gt;&gt;
&gt; Relevant (YES / NO):&quot;&quot;&quot;</code></pre></div>



<p>{question}と{context}がそれぞれ入力した質問と関連ドキュメントとして見つけたドキュメントの内容を入れる部分です。</p>



<p>テンプレートを見ればわかる通り、質問と関連するドキュメントかどうかを聞き、YESかNOを返すようにLLMにお願いするpromptになっていることがわかります。</p>



<h3 class="wp-block-heading">それ以外のContextual Compressionの機能</h3>



<p>今回はLLMを利用しているContextual Compressionのみに注目して紹介しましたが、これ以外にも以下のようなものがあります。</p>



<ol class="wp-block-list">
<li>EmbeddingsFilter: Embeddingによって質問と関連するドキュメントかどうかを判断してフィルタリングするもの。LLMを利用しないので、高速に動作する</li>



<li>DocumentCompressorPipeline: 複数の前処理との組み合わせることができるContextual Compressionの仕組み</li>
</ol>



<p>実際にこれらを使った例は公式のこちらのnotebookにありますので気になる方はご覧ください。</p>



<p><a href="https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/contextual-compression.html">https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/contextual-compression.html</a></p>



<h2 class="wp-block-heading">終わりに</h2>



<p>今回はContextual Compressionについて調べたのでまとめを書きました。LangChainを使った例としてQAシステムはよく見るのですが、自分でやってみると関連ドキュメントを見つけてくるドキュメントが微妙ということがよくあるので、このような仕組みがあったらいいな、と思っていました。このため、今回は個人的には非常に勉強になりました。</p>



<p>今後もまたLLMをどう扱えばいいのか？の勉強でいろいろ調べたらまとめようと思います。</p>



<p>この記事が皆様のお役に立てれば幸いです。</p><p>The post <a href="https://www.mattari-benkyo-note.com/2023/05/12/langchain_contextual_compression/">LangChainのContextual Compressionのいくつかの機能がどのように実現されているかを確認してみた</a> first appeared on <a href="https://www.mattari-benkyo-note.com">まったり勉強ノート</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://www.mattari-benkyo-note.com/2023/05/12/langchain_contextual_compression/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2797</post-id>	</item>
		<item>
		<title>LLMに表データの解析を手伝ってもらえるLangChainのPandas Dataframe Agentの中身がどうなっているのか調べた</title>
		<link>https://www.mattari-benkyo-note.com/2023/04/27/langchain_pandas/</link>
					<comments>https://www.mattari-benkyo-note.com/2023/04/27/langchain_pandas/#respond</comments>
		
		<dc:creator><![CDATA[Shuji Suzuki (shu)]]></dc:creator>
		<pubDate>Wed, 26 Apr 2023 22:33:14 +0000</pubDate>
				<category><![CDATA[プログラミング]]></category>
		<category><![CDATA[langchain]]></category>
		<category><![CDATA[llm]]></category>
		<category><![CDATA[pandas]]></category>
		<category><![CDATA[python]]></category>
		<guid isPermaLink="false">https://www.mattari-benkyo-note.com/?p=2775</guid>

					<description><![CDATA[<p>最近、LLMを使ったOSSの中身を調べてLLMとどう連携して目的を達成しているのかをいろいろ調べています。今回はLangChainのPandas Dataframe Agentの中身がどうなっているのか気になったので調べ [&#8230;]</p>
<p>The post <a href="https://www.mattari-benkyo-note.com/2023/04/27/langchain_pandas/">LLMに表データの解析を手伝ってもらえるLangChainのPandas Dataframe Agentの中身がどうなっているのか調べた</a> first appeared on <a href="https://www.mattari-benkyo-note.com">まったり勉強ノート</a>.</p>]]></description>
										<content:encoded><![CDATA[<p>最近、LLMを使ったOSSの中身を調べてLLMとどう連携して目的を達成しているのかをいろいろ調べています。今回はLangChainのPandas Dataframe Agentの中身がどうなっているのか気になったので調べたまとめになります。</p>



<p>今回のコードは以下のところにあるので、全体としてどうなっているのか見たい方はこちらをご覧ください。</p>



<p><a href="https://github.com/shu65/langchain_examples/blob/main/LangChain_Pandas_Dataframe_Agent.ipynb">https://github.com/shu65/langchain_examples/blob/main/LangChain_Pandas_Dataframe_Agent.ipynb</a></p>



<h2 class="wp-block-heading">LangChainのPandas Dataframe Agentとは</h2>



<p>LLMを使いやすくwrapしてくれるLangChainにはいくつかAgentというLLMとToolと呼ばれるものを組み合わせて実行する仕組みが用意されています。この中でもPandas Dataframe Agentは名前の通りpandasのDataframeに対する操作をLLMにやらせるための仕組みです。</p>



<p>どういうことができるかはこちらのnotebookをご覧ください。</p>



<p><a href="https://python.langchain.com/en/latest/modules/agents/toolkits/examples/pandas.html">https://python.langchain.com/en/latest/modules/agents/toolkits/examples/pandas.html</a></p>



<p>この記事では、上のnotebookの実行例の一つを取り上げてどのようにLLMなどと連携しているのかを説明していきたいと思います。</p>



<h2 class="wp-block-heading">実行例</h2>



<p>今回は機械学習でお馴染みのタイタニックのデータを使います。データはここから持ってきました。</p>



<p><a href="https://web.stanford.edu/class/archive/cs/cs109/cs109.1166/problem12.html">https://web.stanford.edu/class/archive/cs/cs109/cs109.1166/problem12.html</a></p>



<p>どういうデータか詳しく知りたい方は上のページの説明をご覧ください。</p>



<p>また、今回は以下のことをLLMに聞いたときのLLMなどを含めた一連の流れがどうなっているのかを説明していきます。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-python" data-lang="Python"><code>
from langchain.llms import OpenAI
from langchain.agents import create_pandas_dataframe_agent
import pandas as pd

df = pd.read_csv(&#39;titanic.csv&#39;)
agent = create_pandas_dataframe_agent(OpenAI(temperature=0), df, verbose=True)
agent.run(&quot;whats the square root of the average age?&quot;)</code></pre></div>



<p>最後の行がLLMでpandasのDataFrameを操作する部分になっています。やらせたいことは読んで分かる通り、年齢の平均を取って、それのルートを取るという計算をした結果を得るということです。</p>



<p>それではこの後これがどのように実行されるかを見ていきます。</p>



<h2 class="wp-block-heading">実行の流れ</h2>



<p>Pandas Dataframe Agentの大まかな実行の流れは以下の通りです。</p>



<ol class="wp-block-list">
<li><code>zero-shot-react-description</code> と同じAgentクラスに対し、promptを少し変えたAgentを作成</li>



<li>できたAgentがどのようなコードを実行するかを考える</li>



<li>考えに従ってコードを生成</li>



<li>生成されたコードを実行</li>



<li>実行した結果に基づいて再度考える。以降はこの繰り返して最終結果を得る</li>
</ol>



<p>このような「考える」と「行動」（LangChain的にはTool）を交互に繰り返すやり方はReActと呼ばれる方法で、以下の論文で提案されています。</p>



<p><span style="color: rgb(33, 37, 41); font-size: 16px; white-space: normal;">Yao, S., Zhao, J., Yu, D., Du, N., Shafran, I., Narasimhan, K., &amp; Cao, Y. (2022). ReAct: Synergizing Reasoning and Acting in Language Models.&nbsp;</span><em style="color: rgb(33, 37, 41); font-size: 16px; white-space: normal;">ArXiv, abs/2210.03629</em><span style="color: rgb(33, 37, 41); font-size: 16px; white-space: normal;">.</span></p>



<p><code>zero-shot-react-description</code> に関しては以前記事を書きましたので、動作について詳しく知りたい方はこちらも併せてご覧ください。</p>



<figure class="wp-block-embed is-type-wp-embed is-provider-まったり勉強ノート wp-block-embed-まったり勉強ノート"><div class="wp-block-embed__wrapper">
<blockquote class="wp-embedded-content" data-secret="dYRayzlMPQ"><a href="https://www.mattari-benkyo-note.com/2023/04/05/langchain_zero-shot-react-description/">LangChainのAgent「zero-shot-react-description」はLLMとどう連携しているのか？調べた</a></blockquote><iframe loading="lazy" class="wp-embedded-content" sandbox="allow-scripts" security="restricted"  title="&#8220;LangChainのAgent「zero-shot-react-description」はLLMとどう連携しているのか？調べた&#8221; &#8212; まったり勉強ノート" src="https://www.mattari-benkyo-note.com/2023/04/05/langchain_zero-shot-react-description/embed/#?secret=1tgUKm6Vhz#?secret=dYRayzlMPQ" data-secret="dYRayzlMPQ" width="600" height="338" frameborder="0" marginwidth="0" marginheight="0" scrolling="no"></iframe>
</div></figure>



<p>ここからはさきほどの例の場合、LLMと連携してどのような手順で処理をしていくかを見ていきます。</p>



<h3 class="wp-block-heading">一番最初のpromptに関して</h3>



<p>一番最初のpromptは以下のようになっています。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-plain"><code>You are working with a pandas dataframe in Python. The name of the dataframe is `df`.
You should use the tools below to answer the question posed of you:

python_repl_ast: A Python shell. Use this to execute python commands. Input should be a valid python command. When using this tool, sometimes output is abbreviated - make sure it does not look abbreviated before using it in your answer.

Use the following format:

Question: the input question you must answer
Thought: you should always think about what to do
Action: the action to take, should be one of [python_repl_ast]
Action Input: the input to the action
Observation: the result of the action
... (this Thought/Action/Action Input/Observation can repeat N times)
Thought: I now know the final answer
Final Answer: the final answer to the original input question


This is the result of `print(df.head())`:
   Survived  Pclass                                               Name  \
0         0       3                             Mr. Owen Harris Braund   
1         1       1  Mrs. John Bradley (Florence Briggs Thayer) Cum...   
2         1       3                              Miss. Laina Heikkinen   
3         1       1        Mrs. Jacques Heath (Lily May Peel) Futrelle   
4         0       3                            Mr. William Henry Allen   

      Sex   Age  Siblings/Spouses Aboard  Parents/Children Aboard     Fare  
0    male  22.0                        1                        0   7.2500  
1  female  38.0                        1                        0  71.2833  
2  female  26.0                        0                        0   7.9250  
3  female  35.0                        1                        0  53.1000  
4    male  35.0                        0                        0   8.0500  

Begin!
Question: whats the square root of the average age?</code></pre></div>



<p>一番最初のpromptが一番大事な部分なので、丁寧に説明していきます。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-plain"><code>You are working with a pandas dataframe in Python. The name of the dataframe is `df`.</code></pre></div>



<p>この部分は<code>zero-shot-react-description</code> とは違う部分の一つです。最初にpandasの<code>DataFrame</code>を使うことと、その変数名が<code>df</code>であることをLLMに伝えます。</p>



<p>次にこの部分についてです。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-plain"><code>You should use the tools below to answer the question posed of you:

python_repl_ast: A Python shell. Use this to execute python commands. Input should be a valid python command. When using this tool, sometimes output is abbreviated - make sure it does not look abbreviated before using it in your answer.
</code></pre></div>



<p>この部分はToolの説明です。Pandas Dataframe Agentの場合は<code>python_repl_ast</code>を使うため、このToolがどういうものかをLLMに伝えています。</p>



<p>次にこの部分です。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-plain"><code>Use the following format:

Question: the input question you must answer
Thought: you should always think about what to do
Action: the action to take, should be one of [python_repl_ast]
Action Input: the input to the action
Observation: the result of the action
... (this Thought/Action/Action Input/Observation can repeat N times)
Thought: I now know the final answer
Final Answer: the final answer to the original input question</code></pre></div>



<p>この部分は<code>zero-shot-react-description</code>と同じでLLMにReAct的な動きをしてもらうための説明のところです。</p>



<p>そして次はこの部分です。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-plain"><code>This is the result of `print(df.head())`:
   Survived  Pclass                                               Name  \
0         0       3                             Mr. Owen Harris Braund   
1         1       1  Mrs. John Bradley (Florence Briggs Thayer) Cum...   
2         1       3                              Miss. Laina Heikkinen   
3         1       1        Mrs. Jacques Heath (Lily May Peel) Futrelle   
4         0       3                            Mr. William Henry Allen   

      Sex   Age  Siblings/Spouses Aboard  Parents/Children Aboard     Fare  
0    male  22.0                        1                        0   7.2500  
1  female  38.0                        1                        0  71.2833  
2  female  26.0                        0                        0   7.9250  
3  female  35.0                        1                        0  53.1000  
4    male  35.0                        0                        0   8.0500  </code></pre></div>



<p>ここではDataFrameの一部を出力させてどういうデータであるかをLLMに伝えている部分です。</p>



<p>最後にこの部分です。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-plain"><code>Begin!
Question: whats the square root of the average age?
Thought: </code></pre></div>



<p>動作の開始の合図と、「Question:」から先が実際にAgentを使ってやりたいことをLLMに伝えます。そして、「Thought:」までLLMに入力させて、LLMに何をするべきか考えさせます。</p>



<p>ここから先はLLMの出力と出力されたPythonコードを実行して得られた結果を受け取ってさらにLLMに考えさせるという動作を繰り返していきます。これを順番に説明していきます。</p>



<h3 class="wp-block-heading">LLMが考えて、Pythonのコードを生成する部分(1回目)</h3>



<p>先ほどのpromptをLLMに入力すると以下のような出力が返ってきます。これを順番に見ていきます。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-plain"><code>I need to calculate the average age first
Action: python_repl_ast
Action Input: df[&#39;Age&#39;].mean()</code></pre></div>



<p>1行目が先ほどの「Thought:」の続きで、LLMがどのようなことをするべきか考えた部分です。最初は年齢の平均を計算しようと考えて、それを行うためのコードを「Action Input:」から先に出力しています。</p>



<p>このコードを今度は実際に実行します。</p>



<h3 class="wp-block-heading">Pythonコードの実行</h3>



<p>先ほどのPythonのコードをどのように実行するかを説明していきます。実際に実行している部分は、この記事を書いている現在のバージョンではLangChainのここになります。</p>



<p><a href="https://github.com/hwchase17/langchain/blob/72b7d76d79b0e187426787616d96257b64292119/langchain/tools/python/tool.py#L67-L92">https://github.com/hwchase17/langchain/blob/72b7d76d79b0e187426787616d96257b64292119/langchain/tools/python/tool.py#L67-L92</a></p>



<p>これは以下のような手順でPythonコードを実行しています。</p>



<ol class="wp-block-list">
<li>LLMの生成したPythonコードを受け取りきれいに整える</li>



<li>Pythonコードの抽象構文木を生成</li>



<li>Pythonコードの最後から一つ手前までのコードを実行</li>



<li>Pythonコードの最後の部分を実行して出力結果、もしくはエラーを得る</li>
</ol>



<p>3と4でなぜ分けて実行しているかというとToolの説明にある通り、途中の出力は省略して最後だけ得るためであると考えています。</p>



<p>このような流れでPythonコードを実行すると以下の結果が得られえます。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-plain"><code>Observation: 29.471443066516347</code></pre></div>



<p>ここから次に何をするべきかさらに考えて実行していきます。</p>



<h3 class="wp-block-heading">LLMが考えてPythonのコードを生成し、実行する部分(2回目)</h3>



<p>次にLLMの出力とPythonコードの実行は以下のようになります。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-plain"><code> I now need to calculate the square root of the average age
Action: python_repl_ast
Action Input: math.sqrt(df[&#39;Age&#39;].mean())
Observation: name &#39;math&#39; is not defined</code></pre></div>



<p>1行目は先ほどと同じように次に何をするべきかLLMに考えさせた結果の部分です。ここでは年齢の平均のルートを計算するということを考えてコードを生成しています。</p>



<p>このコードを実行すると以下のようなエラーが出力されます。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-plain"><code>name &#39;math&#39; is not defined</code></pre></div>



<p>まだ<code>math</code> がインポートされてないので、その部分でエラーがでています。たしかに現状のコードではどこも<code>math</code> をインポートしてないので、このエラーがでるのは当然です。</p>



<p>ここからさらにLLMに考えさせます。</p>



<h3 class="wp-block-heading">LLMが考えてPythonのコードを生成し、実行する部分(3回目)</h3>



<p>次にLLMの出力とPythonのコードを実行した結果は以下のようになります。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-plain"><code> I need to import the math library
Action: python_repl_ast
Action Input: import math
Observation: </code></pre></div>



<p>1行目は先ほどと同じように次に何をするべきかLLMに考えさせた結果の部分です。今度はちゃんと<code>math</code> をインポートするように考えて、その通りのコードを生成しています。</p>



<p>このコードはインポートだけなので出力はなしです。</p>



<h3 class="wp-block-heading">LLMが考えてPythonのコードを生成し、実行する部分(4回目)</h3>



<p>ここからさらにLLMに考えさせます。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-plain"><code> I now need to calculate the square root of the average age
Action: python_repl_ast
Action Input: math.sqrt(df[&#39;Age&#39;].mean())
Observation: 5.42876073026951</code></pre></div>



<p>LLMの考えていることは1行目にでていて、これは2回目のときと同じものになっています。コードも2回目と同じです。</p>



<p>一方、先ほど<code>math</code>をインポートしたので、今度はエラーが出ずに正しい計算ができています。</p>



<p>以上がPandas Dataframe Agentの中身になります。</p>



<h2 class="wp-block-heading">終わりに</h2>



<p>今回はLangChainのPandas Dataframe Agentの中身がどうなっているのかを調べたのでまとめを書きました。DataFrameの中の情報をどうやって教えているのか疑問だったのですが、その辺もわかってよかったです。</p>



<p>また、Pythonの<code>ast</code>まわりを知らなかったのでそれについてもいい勉強になりました。</p>



<p>この記事が少しでも他の方の役にたったら幸いです。</p><p>The post <a href="https://www.mattari-benkyo-note.com/2023/04/27/langchain_pandas/">LLMに表データの解析を手伝ってもらえるLangChainのPandas Dataframe Agentの中身がどうなっているのか調べた</a> first appeared on <a href="https://www.mattari-benkyo-note.com">まったり勉強ノート</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://www.mattari-benkyo-note.com/2023/04/27/langchain_pandas/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2775</post-id>	</item>
		<item>
		<title>LangChainのSummarizationについて調べたまとめ</title>
		<link>https://www.mattari-benkyo-note.com/2023/04/21/langchain_summarization/</link>
					<comments>https://www.mattari-benkyo-note.com/2023/04/21/langchain_summarization/#respond</comments>
		
		<dc:creator><![CDATA[Shuji Suzuki (shu)]]></dc:creator>
		<pubDate>Thu, 20 Apr 2023 23:24:00 +0000</pubDate>
				<category><![CDATA[プログラミング]]></category>
		<category><![CDATA[langchain]]></category>
		<category><![CDATA[llm]]></category>
		<category><![CDATA[python]]></category>
		<guid isPermaLink="false">https://www.mattari-benkyo-note.com/?p=2726</guid>

					<description><![CDATA[<p>LangChainの中身がどうなっているのか気になっている今日このごろ。 今回はLangChainのテキストをまとめるSummarizationまわりについて調べたのでそのまとめになります。 LangChainって何？っ [&#8230;]</p>
<p>The post <a href="https://www.mattari-benkyo-note.com/2023/04/21/langchain_summarization/">LangChainのSummarizationについて調べたまとめ</a> first appeared on <a href="https://www.mattari-benkyo-note.com">まったり勉強ノート</a>.</p>]]></description>
										<content:encoded><![CDATA[<p>LangChainの中身がどうなっているのか気になっている今日このごろ。</p>



<p>今回はLangChainのテキストをまとめるSummarizationまわりについて調べたのでそのまとめになります。</p>



<p>LangChainって何？ってなった方はこちらに紹介の記事がありますので、ご覧ください。</p>



<figure class="wp-block-embed is-type-wp-embed is-provider-まったり勉強ノート wp-block-embed-まったり勉強ノート"><div class="wp-block-embed__wrapper">
<blockquote class="wp-embedded-content" data-secret="LNqbkauJIX"><a href="https://www.mattari-benkyo-note.com/2023/03/28/langchain_example/">ChatGPTみたいなアプリが簡単に作れるLangChainがすごすぎ</a></blockquote><iframe loading="lazy" class="wp-embedded-content" sandbox="allow-scripts" security="restricted"  title="&#8220;ChatGPTみたいなアプリが簡単に作れるLangChainがすごすぎ&#8221; &#8212; まったり勉強ノート" src="https://www.mattari-benkyo-note.com/2023/03/28/langchain_example/embed/#?secret=nS1shevUZc#?secret=LNqbkauJIX" data-secret="LNqbkauJIX" width="600" height="338" frameborder="0" marginwidth="0" marginheight="0" scrolling="no"></iframe>
</div></figure>



<h2 class="wp-block-heading">LangChainのSummarizationとは？</h2>



<p>LangChainのSummarizationとは与えられたテキストデータから要約されたテキストを作る機能になります。</p>



<p>LangChainにはChatGPTのようなサンプル以外にも様々な例が紹介されています。その中の一つがSummarizationです。</p>



<p>Summarizationは他の機能よりも説明が少なく、また、少し長い論文の要約をさせようとすると動かないことがあるので、どのような処理をさせているのか？を理解したくて調査しました。</p>



<p>ちなみに参考にしたのはこのnotebookです。</p>



<p><a href="https://python.langchain.com/en/latest/modules/chains/index_examples/summarize.html">https://python.langchain.com/en/latest/modules/chains/index_examples/summarize.html</a></p>



<p>ここから基本的には要約したい<code>Document</code>のリストを引数にとる<code>load_summarize_chain()</code>を使って実行した場合の例について説明していきます。</p>



<h2 class="wp-block-heading">load_summarize_chainによるSummarizationの３つの方法</h2>



<p>load_summarize_chain()Summarizationとして以下の３つがあります。</p>



<ol class="wp-block-list">
<li><code>stuff</code> </li>



<li><code>map_reduce</code></li>



<li><code>refine</code>&nbsp;</li>
</ol>



<p>それぞれについて説明していきます。</p>



<h3 class="wp-block-heading">stuff</h3>



<p>おそらくSummarizationという機能から一番最初に想像するのがこれです。与えられた<code>Document</code>のリストを受け取って、すべてつなげた一つのテキストにします。それをLLMに投げて要約させます。defaultのPromptのテンプレートとしては以下のようなものになっています。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-python" data-file="stuff_prompt_template" data-lang="Python"><code>&quot;&quot;&quot;Write a concise summary of the following:


&quot;{text}&quot;


CONCISE SUMMARY:&quot;&quot;&quot;</code></pre></div>



<p>ここで、{text}のところに１つにつなげたテキストに置き換えてLLMに入力します。LLMはCONCISE SUMMARY:の続きを生成するので、{text}の部分に基づいて要約した文章を生成することになります。</p>



<p><code>CONCISE SUMMARY:</code> から先はLLMに生成させるようにすることで要約をえることができるようになっています。</p>



<p>ただ、これの問題点としては与えrる<code>Document</code>のリストの合計のテキストの長さが長すぎるとLLMのコンテキストサイズを超えて実行できないケースが発生するので注意してください。</p>



<h3 class="wp-block-heading">map_reduce</h3>



<p>次に<code>map_reduce</code> に関してです。名前の通りで、リストで与えられた<code>Document</code>を一度要約し、その要約されたものを組み合わせてさらに要約するというのを繰り返し行い、最終的な要約を得るものになります。</p>



<p>最初の要約の部分とその後の要約されたものからさらに要約をする部分の２種類のステップがありますが、どちらもデフォルトでは以下のpromptのテンプレートを使います。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-python" data-file="map_reduce_prompt_template" data-lang="Python"><code>&quot;&quot;&quot;Write a concise summary of the following:


&quot;{text}&quot;


CONCISE SUMMARY:&quot;&quot;&quot;</code></pre></div>



<p>いろいろ試しましたが、特に論文のような長い文章の場合はこれが一番まともな要約をしてくれる印象でした。</p>



<h3 class="wp-block-heading">refine</h3>



<p>最後に<code>refine</code> です。これも名前の通りですが、与えられた<code>Document</code>のリストの最初の要約を作り、そのごその要約と次の<code>Document</code>の要約を作ります。これを繰り返して最終的な要約を得ます。</p>



<p>これは二種類のプロンプトを使い分けて実行されます。まず最初の要約を作る部分は今までと同じように以下のプロンプトが使われます。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-python" data-file="refine_init_prompt_template" data-lang="Python"><code>&quot;&quot;&quot;Write a concise summary of the following:


&quot;{text}&quot;


CONCISE SUMMARY:&quot;&quot;&quot;</code></pre></div>



<p>そして、それまでの要約と新しい<code>Document</code>を組み合わせて新しい要約を作る部分のプロンプトは以下のようになります。</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-python" data-file="refine_prompt_template" data-lang="Python"><code>    &quot;Your job is to produce a final summary\n&quot;
    &quot;We have provided an existing summary up to a certain point: {existing_answer}\n&quot;
    &quot;We have the opportunity to refine the existing summary&quot;
    &quot;(only if needed) with some more context below.\n&quot;
    &quot;------------\n&quot;
    &quot;{text}\n&quot;
    &quot;------------\n&quot;
    &quot;Given the new context, refine the original summary&quot;
    &quot;If the context isn&#39;t useful, return the original summary.&quot;</code></pre></div>



<p><code>refine</code> を使ってみた感想としては最後のほうの<code>Document</code>に影響されて、それほど情報量のないにも関わらず、最後のほうの<code>Document</code>の内容が要約に含まれていました。このため、要約の品質としては<code>map_reduce</code> のほうがよいかもしれないと思っています。</p>



<h2 class="wp-block-heading">終わりに</h2>



<p>今回はLangChainのSummarizationについて調べたのでまとめを書きました。</p>



<p>長い文章の要約に使えないか？と思って調べたのですが、実際にやってみると期待したほどすごい要約がでてくるという感じではない印象です。</p>



<p>このため、個人的には使いどころが悩ましいなぁというと思っています。</p>



<p>ただ、いろいろ工夫すればいいものができそうな気もするので、少し文章の要約というかまとめは工夫できないかチャレンジしようと思います。</p><p>The post <a href="https://www.mattari-benkyo-note.com/2023/04/21/langchain_summarization/">LangChainのSummarizationについて調べたまとめ</a> first appeared on <a href="https://www.mattari-benkyo-note.com">まったり勉強ノート</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://www.mattari-benkyo-note.com/2023/04/21/langchain_summarization/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2726</post-id>	</item>
	</channel>
</rss>
