QEUR23_CHRLTM42 : (少量実験その2)Semantic Searchの意義を再度考える
~ Semantic Searchのありがたさ ~
D先生(設定年齢65歳): “今回も予備実験のつづきです。前回は、思ったようにFBQ(FACT_BASED_QUESTION)の答えが出てきませんでした。例えば・・・。”
(プロンプト)
You are an excellent AI assistant. Below is an instruction that describes a task, paired with an input that provides further information. The instruction and input are question provided by your user. Write a response appropriately your user's question. Because very useful texts have been provided in context field (texts after 'Context:'), you should write answer by using context information as much as possible. Your answer should be divided into two parts: the first part is a summary of the context, and the second part is your brief opinion based on the context. Your answer should be at least 800 words but no more than 1000 words.
あなたは優秀な AI アシスタントです。以下はタスクを説明する指示と、さらに詳しい情報を提供する入力を組み合わせたものです。指示と入力は、ユーザーから提供された質問です。ユーザーの質問に適切に応答してください。コンテキスト フィールド (「コンテキスト:」の後のテキスト) に非常に役立つテキストが提供されているため、できるだけコンテキスト情報を使用して回答を記述する必要があります。回答は 2 つの部分に分ける必要があります。最初の部分はコンテキストの要約で、2 番目の部分はコンテキストに基づいた簡単な意見です。回答は 800 語以上 1000 語以下にしてください。
D先生(設定年齢65歳): “このようなプロンプトに対して、前半は抽出したRAG文書のまとめ、後半はLLM自身の意見というように指定したのですが、うまく答えがでてきません。”
Instruction:
India's geopolitical stance is a good example of the emerging trend of countries seeking to diversify their trade relationships and maintain strategic autonomy. What are the key factors driving India's foreign policy approach, and how is it balancing its relationships with the G7, BRICS, and other global governance institutions?
インドの地政学的立場は、各国が貿易関係の多様化と戦略的自立の維持を目指す新たな傾向を示す好例です。インドの外交政策のアプローチを推進する主な要因は何ですか。また、インドは G7、BRICS、その他のグローバルガバナンス機関との関係をどのようにバランスさせているのでしょうか。
Response:
Summary:
India's geopolitical stance is a good example of the emerging trend of countries seeking to diversify their trade relationships and maintain strategic autonomy. The key factors driving India's foreign policy approach include its historical commitment to non-alignment movement, preference for stra-tegic independence, and the rise of emerging economies. India's approach to multilateral forums and alliances is measured and balanced, with a preference for maintaining strategic independence. The exclusion of significant economies from influential international bodies weakens the legitimacy of the G7 as a global forum. In the realm of global economic and geopolitical dynamics, multilateral coop-eration is increasingly playing an important role in shaping the future trajectory of world politics. The BRICS and G7 represent two different groups that hold conflicting views on the existing eco-nomic order and how it benefits certain nations. The intricate dynamics between these two groups encapsulate a complex interplay of cooperation, competition, and ideological divergence within the realm of global governance. The policy of "multi-alignment" gives India the opportunity to take on different foreign policy roles and thus pursue different strategies. Within the BRICS group, this is expressed in India's claim to represent a counterweight to Russia and China and consequently to bal-ance this power bloc politically and economically in order to contain its influence. This balancing act is reflected within BRICS in the confrontation with China, particularly in the "global South". Here, India and China are competing for the favour of various developing countries, whereby India's claim to be the leading power of the "global South" has not yet been fulfilled.
インドの地政学的立場は、貿易関係の多様化と戦略的自立の維持を目指す国々の新たな傾向を示す好例である。インドの外交政策アプローチを推進する主な要因には、非同盟運動への歴史的関与、戦略的独立の優先、新興経済国の台頭などがある。インドの多国間フォーラムや同盟へのアプローチは慎重かつバランスが取れており、戦略的独立の維持を優先している。影響力のある国際機関から主要経済国が排除されていることは、グローバルフォーラムとしての G7 の正当性を弱める。世界経済と地政学的ダイナミクスの領域では、多国間協力が世界政治の将来の軌道を形成する上でますます重要な役割を果たしている。BRICS と G7 は、既存の経済秩序とそれが特定の国にどのような利益をもたらすかについて相反する見解を持つ 2 つの異なるグループを表している。これら 2 つのグループ間の複雑なダイナミクスは、グローバル ガバナンスの領域における協力、競争、イデオロギーの相違の複雑な相互作用を要約している。 「多角的連携」政策は、インドにさまざまな外交政策の役割を担い、さまざまな戦略を追求する機会を与える。BRICS グループ内では、インドはロシアと中国に対するカウンターウェイトとなり、その結果、この勢力圏の政治的、経済的バランスを取り、その影響力を抑えるという主張に表れている。このバランスを取る行為は、特に「グローバル サウス」における中国との対立に BRICS 内で反映されている。ここでは、インドと中国はさまざまな発展途上国の支持を得るために競争しており、インドの「グローバル サウス」の主導的勢力であるという主張はまだ果たされていない。
Opinion:
India's geopolitical stance is a good example of the emerging trend of countries seeking to diversify their trade relationships and maintain strategic autonomy. The key factors driving India's foreign policy approach include its historical commitment to non-alignment movement, preference for stra-tegic independence, and the rise of emerging economies. India's approach to multilateral forums and alliances is measured and balanced, with a preference for maintaining strategic independence. The exclusion of significant economies from influential international bodies weakens the legitimacy of the G7 as a global forum. In the realm of global economic and geopolitical dynamics, multilateral coop-eration is increasingly playing an important role in shaping the future trajectory of world politics. The BRICS and G7 represent two different groups that hold conflicting views on the existing eco-nomic order and how it benefits certain nations. The intricate dynamics between these two groups encapsulate a complex interplay of cooperation, competition, and ideological divergence within the realm of global governance. The policy of "multi-alignment" gives India the opportunity to take on different foreign policy roles and thus pursue different strategies. Within the BRICS group, this is expressed in India's claim to represent a counterweight to Russia and China and consequently to bal-ance this power bloc politically and economically in order to contain its influence. This balancing act is reflected within BRICS in the confrontation with China, particularly in the "global South". Here, India and China are competing for the favour of various developing countries, whereby India's claim to be the leading power of the "global South" has not yet been fulfilled.
インドの地政学的立場は、貿易関係の多様化と戦略的自立の維持を目指す国々の新たな傾向を示す好例である。インドの外交政策アプローチを推進する主な要因には、非同盟運動への歴史的関与、戦略的独立の優先、新興経済国の台頭などがある。インドの多国間フォーラムや同盟へのアプローチは慎重かつバランスが取れており、戦略的独立の維持を優先している。影響力のある国際機関から主要経済国が排除されていることは、グローバルフォーラムとしての G7 の正当性を弱める。世界経済と地政学的ダイナミクスの領域では、多国間協力が世界政治の将来の軌道を形成する上でますます重要な役割を果たしている。BRICS と G7 は、既存の経済秩序とそれが特定の国にどのような利益をもたらすかについて相反する見解を持つ 2 つの異なるグループを表している。これら 2 つのグループ間の複雑なダイナミクスは、グローバル ガバナンスの領域における協力、競争、イデオロギーの相違の複雑な相互作用を要約している。 「多角的連携」政策は、インドにさまざまな外交政策の役割を担い、さまざまな戦略を追求する機会を与える。BRICS グループ内では、インドはロシアと中国に対するカウンターウェイトとなり、その結果、この勢力圏の政治的、経済的バランスを取り、その影響力を抑えるという主張に表れている。このバランスを取る行為は、特に「グローバル サウス」における中国との対立に BRICS 内で反映されている。ここでは、インドと中国はさまざまな発展途上国の支持を得るために競争しており、インドの「グローバル サウス」の主導的勢力であるという主張はまだ果たされていない。
QEU:FOUNDER(設定年齢65歳) : “そこで、LLMモデルのfinetuneのやり直しです。学習データのなかに、RAGデータ(CONTEXT)を入力した事例が必要です。このEXCELデータ(↓)を使います。”
D先生: “このデータの中で「RAG1~RAG5」がCONTEXTになるわけですね。”
QEU:FOUNDER : “今回は、Unsloth(Mistral_Nemo-12b)よりもさらに強力なLLM(Lllama3.1)で回答を出力させ、それを学習データとするためにEXCELファイルに出力するまでです。”
##############################
# RAGつきFinetuning用の推論
##############################
# 必要なライブラリのインポート
import pandas as pd
import numpy as np
import json
from groq import Groq
from jinja2 import Environment, FileSystemLoader
# Excelファイルからデータフレームを作成
df = pd.read_excel('finetune_rag_suppliment.xlsx')
df
# ---
# 情報の読み込み
num_df = len(df)
arr_instruction = df.loc[:,"instruction"].values
mx_rag = df.loc[:,"RAG1":"RAG5"].values
print(num_df)
#print(arr_concept)
# ---
# CONTEXTをまとめる
arr_ragsum = []
for i in range(num_df):
str_context = ""
for j in range(5):
temp_context = mx_rag[i,j]
temp_context.replace("\n\n","\n")
str_context = str_context + temp_context + "\n"
arr_ragsum.append(str_context)
# ---
arr_ragsum = np.array(arr_ragsum)
print(arr_ragsum)
##################################
# PROMPT ENGINEERING
##################################
# -----
# Jinja2テンプレートの読み込み
env = Environment(loader=FileSystemLoader('.'))
# INPUTがある
template = env.get_template('QA_finetune_rag_suppliment.j2')
#You are an excellent AI assistant. Below is an instruction ("INSTRUCTION") that describes a task. The instruction is question #provided by your user. Write a response appropriately your user's ques-tion. Because very useful texts have been provided in a #context ("CONTEXT") , you should write an answer by using context information as much as possible.
#INSTRUCTION```
#{{str_instruction}}
#```
#CONTEXT```
#{{str_context}}
#```
#Your answer should be divided into two sections: the first section is a summary of the context, and the second section is your #brief opinion based on the context. Your answer should be at least 600 words but no more than 800 words and the size of text #of opinion section should be less than 250 words.
# ---
# Jinja2テンプレートにデータを渡してクエリを生成する
str_instruction = template.render(
str_instruction = arr_instruction[0],
str_context = arr_ragsum[0],
)
print(str_instruction)
######################################
# RAG INFERENCE
######################################
# -----
# 連続推論
client = Groq()
arr_response = []
# ----
for i in range(num_df): # num_df
# INPUTがあるかないか
#if type(row['input']) == float:
# template = templateB
#else:
# template = templateA
# Jinja2テンプレートにデータを渡してクエリを生成
query = template.render(
str_instruction = arr_instruction[i],
str_context = arr_ragsum[i],
)
# クエリを送信してレスポンスを取得
chat_completion = client.chat.completions.create(
messages=[{"role": "user", "content": query}],
model="llama-3.1-70b-versatile",
)
response = chat_completion.choices[0].message.content
arr_response.append(response)
# ---
if i % 3 == 0:
print(f"--- i:{i}, <question> ---")
print(query)
print(f"--- i:{i}, <response> ---")
print(response)
# ----
df_out = df.copy()
df_out.loc[:, "CONTEXT"] = arr_ragsum
df_out.loc[:, "ANSWER"] = arr_response
df_out
# ----
df_out.to_excel("finetune_rag_suppliment_out.xlsx")
QEU:FOUNDER : “結果は以下の通り。CONTEXTとANSWERが追加されました。それをもとに、小生がレビューしたのが、この結果(↓)です。ドン!!”
D先生: “あれ?いくつかのレコード番号が抜けています。NO3は何処に言ったんですか?”
QEU:FOUNDER : “お話にならない回答なので、レコードごと消しました。”
D先生: “今回つかっているLLMモデルはLlama3.1-70bでしょ?GPT4レベルじゃないですか!?GPTはこんなにアクロバティック(↑)なことができるんですよ!”
QEU:FOUNDER : “実は、RAGの情報がダメダメだったんです。CONTEXTとしてリンク集を拾っていたようです。おそらく、前回のシステムでは、この部分(↓)が問題だったのだと思います。”
# ----
from langchain.embeddings import HuggingFaceBgeEmbeddings
embeddings = HuggingFaceBgeEmbeddings(
model_name="BAAI/bge-base-en",
model_kwargs={'device': 'cuda'},
encode_kwargs={'normalize_embeddings': True}
)
D先生: “これって、sentence-transformerのエンジンでしょ?いままで、何回も使ったことがあります。はっきり言って、一文だけの情報に対しては、そこそこの精度はあります。しかし、パラグラフ単位では精度がでません。”
QEU:FOUNDER : “だから、OpenAIとか、CohereのSemantic searchのサービスを使って、ChunkのRAG推論をしないといけないんです。もっと議論を発展させると、多くのRAGの教科書においてBAAIモデルを使っていますが、あれは厳密には実用には向いていないです。量産ケースでは使えないことも多々あるはずです。”
D先生: “多くのブログの事例ではうまく行っているように見えるのだが、それはなぜだろう・・・。”
QEU:FOUNDER : “これに対する答えは、BONSAI3のコンセプトの本質になります。ちょっと、いままでやってきたBONSAI2のスキームをみてみましょう。初期質問から、QQ(Question to Question)の流れは、以下のようになります。ここで、QQは「質問の深堀」という特性を持ちます。”
D先生: “この情報処理の流れは、いままでさんざんやってきたのでよくわかります。QQは深堀はできても、「質問の言い換え」みたいで面白くなかったですね。それで、今回アップグレードされてようとしているBONSAI3の情報の流れは・・・?”
QEU:FOUNDER : “BONSAI3のテーマは「質問の展開」です。より効率よく、質問を展開させるために、BONSAI3の初期質問においてRAG情報をインプットに使います。そして、アウトプットとしてRAG情報のまとめ(CONTEXT SUMMARY)と質問への答え(OPINION)を出力します。そうすれば、次のFACT抽出において、話題の幅が広がるようになります。”
D先生: “「CONTEXT SUMMAY」が出力になるのか・・・。そうすると、RAG情報の中にリンク集が混じると、回答の内容が無茶苦茶になりますね。じゃあ、この問題に対して、どのように対処するんですか?”
QEU:FOUNDER : “Semantic Searchのやり方を参考にして、2段階スクリーニングをすればいいとおもいます。結論として、BONSAI3の情報処理の流れは、「問題の深堀」と「問題の展開」が交互に現れます。つまり、STEP1が深堀だとすると、STEP2が展開になるということです。”
D先生: “なるほどね。これがBONSAI3のコンセプトなのか・・・。確かに、前回よりもディベートの幅が広がるでしょう。”
QEU:FOUNDER : “次は、このBONSAI3専用データを使ってUnslothのLLMモデルをFinetuningし、その「問題の展開」の効果を確かめてみましょう。”
~ まとめ ~
・・・ 前回のつづきです ・・・
QEU:FOUNDER : “ダウト!!wikipediaでは、「自称」となっているぞ!!”
QEU:FOUNDER : “なにはともあれ、今は情報過多の時代なので、いろいろな見方をしなければいけないことを勉強しました。ちなみに、我々は、別にオッサンの意見に賛成しているわけじゃないです。その場所で起きている「事実」が欲しい(真実じゃないよ?真実はウソが多いし・・・)です。これは、次回の動画にもつながります。”
D先生: “この件(↓)ですか?個人的には、オッサンの意見には?(はてな?)なのですが・・・。”
QEU:FOUNDER : “そう!ここあたりは、本当かどうか「わからんゾー」!!ここまでいくと、ジャーナリズムと陰謀論の境界線あたり・・・(笑)。ただし、この件の事実なんか絶対出てこないから、時間をかけて自分なりに判断するしかないんじゃないですか?それより、話題を変えようよ。この件よ、この件(↓)・・・。あそこって、「〇“カ」じゃない?”
D先生: “何考えてるの?あそこは?”
QEU:FOUNDER : “「何も考えていない・・・」というのは、結論として面白くないね(笑)。こういうのを「過剰適応」というのよ。ヒラメの連中が、「上の人」がやって欲しいと思うことを率先してやるのよ・・・。つまり、忖度・・・。”
D先生: “でも、「上の人」は指示をしてないんでしょ?もし、これが失敗したらどうなるの?この人たちが、さらに不利になったり、貧乏になったりしたらどうなるの?”
QEU:FOUNDER : “(上の人は)指示してません。それによる損失は、まわりまわって「自分党立憲支部」の自己責任でしょ?そのような過剰適応が美徳になるのが、「自分党」の所以なんですよ。”
QEU:FOUNDER : “好きなことをやっていない人たちの悪い面が出ているんだよね。非線形で複雑な時代なんだから、少しは視点を変えないと・・・。”