QEUR23_ CHRLTM10 : [GROUP_B]ディベートの結果をRAGに反映させる
~ 当たり前だが、今回はさらに「良くなった・・・」 ~
D先生(設定年齢65歳) : “前回は、なぜか成り行きの故で、「数理言語政治学」という変な「お遊び」をする羽目になりました。それに気を取り直しての今回ですが・・・。で?何をしましょうか?”
QEU:FOUNDER(設定年齢65歳) : “ディベートに関しては、まだ次の方針を決めていません。ただし、せっかくここまで「討論(ディベート)」をやってみたのだから、ここまでのデータを我々の成果物であるLLMに入れるところまでは行きたいんです。”
QEU:FOUNDER : “小生の言っている意味は、汎用技術構造(↑)における縦軸のことです。それでは、RAG推論を行いましょう。あくまで「多様なMODEL」を作るための学習用のデータです。”
(RAG_JED_step1A(1))
D先生(設定年齢65歳) : “このデータ(↑)は、Cohere 独特のWeb-searchによるRAG機能で得たものですね。このデータは、GOAL_Bのものですか?”
QEU:FOUNDER : “いや、これはGOAL_Aのものです。ただし、GOAL_Bで生成したデータでもほとんど同じになります。LLMは、GOAL_Bの「信念」が気に入らないらしく、GOAL_Aのような風味の回答を作成しますから・・・(笑)。”
(GOAL_B)
日本の長期の経済停滞の理由は、若者の怠慢である。おそらくバブル化以降の文化的な堕落の結果ではないだろうか。若者は、いかなる手段を以てしても就職して、家を買い、結婚をして子供を作るものである。仕事を選ばなければいくらでもある。もし給料が半分であったら、他人の2倍働けば良いのではないだろうか。規制緩和で競争が増えるのは良いことであり、ものが安くなり、結果としてイノベーションが生まれる。生産性を高めるには、人件費を安くさえすればよい。人件費が高いから生産性が低く、その結果として経済がわるいのだ。現状の自民党と大企業の癒着は、単に「よい協力関係」であるにすぎない。彼らが、世界の大企業と戦っているので、日本の競争力を保つことができる。逆に言うと、振興企業にはリスクが高く、あまり期待すべきものではない。社会のダイバーシティは現在のレベルで十分である。優秀な海外学生を招聘し、移民を推進すべきでない。自国の若者の機会を減らすだけである。
D先生: “それでは、RAG推論に入りましょう。確か、今回から質問はFACT_BASED_QUESTIONにしたいと言っていましたね。“
QEU:FOUNDER : “FBQは「質問の深み」が段違いだからね。それでは、プログラムをドン!”
# -----
import re, math, time
# ----
import pandas as pd
import numpy as np
import json
# ----
# 選択してね(今回はCohere)
import cohere
import matplotlib.pyplot as plt
# -----
# [FACT_BASED_ANSWER]Excelファイルからデータフレームを作成する(3)
# -----
df_qq = pd.read_excel('qq_JED_step1A(4).xlsx')
# Step1の質問数
num_df = len(df_qq)
#df_qq
# -----
# EXCELシートから、文字列を抽出する
# -----
# Question(Initial)
arr_QInitial = df_qq.loc[:,'QInitial'].values
#print(arr_QInitial)
# -----
# Answer(Initial)
arr_AInitial = df_qq.loc[:,'AInitial'].values
#print("--- Answer(Initial) ---")
#print(arr_AInitial[0])
# -----
# (matrix) Fact Based Question
mx_FBQ = df_qq.loc[:,'FBQ1':'FBQ5'].values
print("--- (matrix) Fact Based Question ---")
print(mx_FBQ[0,:])
# -----
# (array) Fact Based Question
arr_FBQ = mx_FBQ.flatten()
print("--- (array) Fact Based Question ---")
print(arr_FBQ[0:10])
# ---
# Set up the base vector store retriever
from langchain_community.document_loaders import TextLoader, DirectoryLoader
from langchain_cohere import CohereEmbeddings
from langchain_community.vectorstores import FAISS
from langchain_text_splitters import RecursiveCharacterTextSplitter
# ---
# paths
TXTs_path = './data'
Embeddings_path = '/data/faiss-ml-papers-st'
Output_folder = './ml-papers-vectordb'
# ---
# [TXT]Load data
text_loader_kwargs = {'autodetect_encoding': True}
loader = DirectoryLoader(
TXTs_path,
glob = "./*.txt",
loader_cls = TextLoader,
show_progress = True,
use_multithreading = True,
loader_kwargs=text_loader_kwargs
)
documents = loader.load()
# ---
print(f'We have {len(documents)} pages in total')
# ---
# Helper function for printing docs
def pretty_print_docs(docs):
print(
f"\n{'-' * 100}\n".join(
[f"Document {i+1}:\n\n" + d.page_content for i, d in enumerate(docs)]
)
)
# ---
# 質問への回答
text_splitter = RecursiveCharacterTextSplitter(chunk_size=512, chunk_overlap=128)
texts = text_splitter.split_documents(documents)
retriever = FAISS.from_documents(texts, CohereEmbeddings()).as_retriever(
search_kwargs={"k": 20}
)
query = "Who is Shinzo Abe?"
docs = retriever.invoke(query)
pretty_print_docs(docs)
# -------
# Doing reranking with CohereRerank
from langchain.retrievers.contextual_compression import ContextualCompressionRetriever
from langchain_cohere import CohereRerank
from langchain_community.llms import Cohere
from langchain_groq import ChatGroq
#from langchain_cohere import Cohere
# ---
# Cohere Rerank
compressor = CohereRerank()
compression_retriever = ContextualCompressionRetriever(
base_compressor=compressor, base_retriever=retriever
)
# ---
compressed_docs = compression_retriever.invoke(
"What is Abenomics?"
)
pretty_print_docs(compressed_docs)
D先生: “えっ?CohereのRerankの機能を使うんですか?それは贅沢ですねえ・・・。”
QEU:FOUNDER : “今回のような使用方法では、「compression_retriever」が有用だとおもっているからです。”
D先生: “今回は、そんなに特別な方法をとってましたっけ?”
QEU:FOUNDER : “今回のディベートのモデルは、「Question to Question」を通じて質問を深堀していきます。つまり、その過程で得られるRAGデータって、おそらく互いに似通っているんです。議論を深めるほど、似た情報が蓄積されてしまいます。Rerankを使うことによって、それによって発生する不利益を解決できるとおもうんです。じゃあ、さらにコードを続けます。”
# ---
from langchain.chains import RetrievalQA
from langchain import PromptTemplate
# ---
prompt_template = """
<|system|>
You are an expert assistant. If you don't know the answer, just say "I don't know." Don't try to make up an answer.
Use only the following pieces of context to answer the question at the end.
<|end|>
<|user|>
Context: {context}
Question is below. Remember to answer in English:
Question: {question}
Don't use words such as 'Fact 1, Fact 2, etc...', you should write their content instead.
<|end|>
<|assistant|>
"""
# ---
PROMPT = PromptTemplate(
template = prompt_template,
input_variables = ["context", "question"]
)
#print(PROMPT)
# ---
import time
import textwrap
# Post-process outputs
def wrap_text_preserve_newlines(text, width=1500):
# Split the input text into lines based on newline characters
lines = text.split('\n')
# Wrap each line individually
wrapped_lines = [textwrap.fill(line, width=width) for line in lines]
# Join the wrapped lines back together using newline characters
wrapped_text = '\n'.join(wrapped_lines)
return wrapped_text
def process_llm_response(llm_response):
ans = wrap_text_preserve_newlines(llm_response['result'])
### return only the text after the pattern
pattern = "<|assistant|>"
index = ans.find(pattern)
if index != -1:
ans = ans[index + len(pattern):]
return ans.strip()
def llm_ans(query):
start = time.time()
llm_response = qa_chain.invoke(query)
ans = process_llm_response(llm_response)
end = time.time()
time_elapsed = int(round(end - start, 0))
time_elapsed_str = f'\n\nTime elapsed: {time_elapsed} s'
return ans + time_elapsed_str
# ---
qa_chain = RetrievalQA.from_chain_type(
llm = ChatGroq(temperature=0.3, model_name="mixtral-8x7b-32768"),
chain_type = "stuff", # map_reduce, map_rerank, stuff, refine
retriever = compression_retriever,
chain_type_kwargs = {"prompt": PROMPT},
return_source_documents = True,
verbose = False
)
# ---
# Ask Questions
query = "Japan's post-war reconstruction and government intervention played a significant role in its economic growth in the 20th century, with the establishment of MITI guiding the country's eco-nomic development and industrial policy. What specific policies and decisions made by MITI con-tributed to Japan's rapid economic growth during this period?"
result = llm_ans(query)
print(result)
D先生: “おっと・・・。面白いLLMモデル(↓)をつかっています。なんと、ミストラルですか・・・。また、何で!?”
QEU:FOUNDER : “このモデルはLlama3やCommand-rシリーズよりも古いんだよね。それでも、今回は敢えて使いたかったんです。一般論をいえば、LLMモデルが新しくなると、計算リソースの節約や計算時間が速くなるかもしれません。それでも、回答文の品質は、結局のところ学習させた情報に依存します。そこらへんの学習情報に、「お国柄(F国)が出る」と思ってね・・・。”
D先生: “主要なLLMはA国からですからね。じゃあ、最初のQ&Aをお願いします。”
(質問)
Japan's post-war reconstruction and government intervention played a significant role in its eco-nomic growth in the 20th century, with the establishment of MITI guiding the country's economic development and industrial policy. What specific policies and decisions made by MITI contributed to Japan's rapid economic growth during this period?
20 世紀の日本の経済成長には、戦後の復興と政府の介入が重要な役割を果たし、通商産業省の設立が国の経済発展と産業政策を導きました。この時期の日本の急速な経済成長に貢献したのは、具体的にはどのような通商産業省の政策と決定だったのでしょうか。
(Mixtral)
MITI's "Policy Concerning Industrial Rationalization" (1950) was a significant policy that coordi-nated efforts by industries to counteract the effects of SCAP's deflationary regulations. This policy formalized cooperation between the Japanese government and private industry, enabling a smooth partnership that would drive economic growth.
One of the key aspects of MITI's role was its ability to coordinate various industries, including the neo-zaibatsu (large industrial combines) that already had the necessary resources and infrastructure to rapidly expand production. For example, if MITI decided to double steel production, the neo-zaibatsu would have the capital, construction assets, production machinery, and other required fac-tors readily available. This streamlined the process of economic development and industrial growth.
Moreover, MITI played a crucial role in guiding Japan's economic development and industrial policy by fostering cooperation and strategic planning among Japanese industries. This allowed Japan to focus its efforts on specific industries and technologies, ensuring that the country remained competi-tive in the global market. As a result, Japan's post-war reconstruction and government intervention, with MITI at the helm, significantly contributed to the country's rapid economic growth during the 20th century.
通産省の「産業合理化政策」(1950 年)は、SCAP のデフレ規制の影響に対抗するために各業界の取り組みを調整する重要な政策でした。この政策により、日本政府と民間産業の協力が正式に確立され、経済成長を促進する円滑なパートナーシップが可能になりました。
通産省の役割の重要な側面の 1 つは、生産を急速に拡大するために必要なリソースとインフラストラクチャをすでに備えていた新財閥 (大規模な産業コンビナート) を含むさまざまな産業を調整する能力でした。たとえば、通産省が鉄鋼生産を 2 倍にすることを決定した場合、新財閥は資本、建設資産、生産機械、その他の必要な要素をすぐに利用できるようになります。これにより、経済発展と産業成長のプロセスが合理化されました。
さらに、通産省は、日本の産業間の協力と戦略的計画を促進することにより、日本の経済発展と産業政策を導く上で重要な役割を果たしました。これにより、日本は特定の産業と技術に努力を集中することができ、世界市場での競争力を維持できました。その結果、日本の戦後復興と通産省主導の政府介入は、20 世紀の日本の急速な経済成長に大きく貢献しました。
Time elapsed: 2 s
D先生: “見事な質問(Q)、見事な回答(A)でした。回答の量が少なめなのが、逆に好感が持てます。”
QEU:FOUNDER : “じゃあ、次に行きます。”
質問: A high savings rate, driven by cultural factors and a lack of social safety nets, provided a pool of funds for investment in education and infrastructure, supporting Japan's economic expansion. How did the cultural factors influence the high savings rate, and what were the implications of this rate on the country's economic growth?
文化的要因と社会的セーフティネットの欠如によってもたらされた高い貯蓄率は、教育とインフラへの投資のための資金プールを提供し、日本の経済成長を支えました。文化的要因は高い貯蓄率にどのように影響したのでしょうか。また、この貯蓄率は国の経済成長にどのような意味を持っていたのでしょうか。
(Mixtral)
The cultural factors that influenced the high savings rate in Japan during the 1950s and 60s included a strong emphasis on thrift and frugality, which were deeply ingrained in the Japanese society. These values were often reinforced by the lack of extensive social safety nets, prompting individuals to save for their own future needs and unforeseen circumstances.
The implications of this high savings rate on the country's economic growth were significant. A large pool of funds was available for investment in areas crucial for economic expansion, such as education and infrastructure. Investment in education led to a well-educated workforce, which was a key factor in Japan's ability to adopt and improve advanced foreign technology. A high-quality workforce, in turn, contributed to the production of reliable and high-quality goods, further bolstering Japan's competitive advantage.
Moreover, the high savings rate provided ample capital for domestic investment, reducing the need for external financing and ensuring a steady source of funds for economic development. This self-sufficiency in capital, coupled with the government's activist role in providing guidance, support, and subsidies, created an ideal environment for rapid and sustained economic growth.
1950 年代から 60 年代にかけて日本の高い貯蓄率に影響を与えた文化的要因には、倹約と質素倹約が強く重視されたことなどがあり、これらは日本社会に深く根付いていました。これらの価値観は、広範な社会保障の欠如によって強化されることが多く、個人が将来のニーズや不測の事態に備えて貯蓄するようになりました。
この高い貯蓄率が国の経済成長に与える影響は重大でした。教育やインフラなど、経済拡大に不可欠な分野への投資に利用できる資金が大量にありました。教育への投資は、教育水準の高い労働力を生み出し、それが日本が先進的な外国技術を採用し、改善する能力の重要な要因となりました。質の高い労働力は、信頼性が高く高品質の製品の生産に貢献し、日本の競争上の優位性をさらに強化しました。
さらに、高い貯蓄率は国内投資に十分な資本を提供し、外部からの資金調達の必要性を減らし、経済発展のための安定した資金源を確保しました。この資本の自給自足と、指導、支援、補助金を提供する政府の積極的な役割が相まって、急速かつ持続的な経済成長のための理想的な環境が生まれました。
Time elapsed: 2 s
D先生: “この回答も見事だなあ・・・。”
QEU:FOUNDER : “じゃあ、ちょっと「いまいち」の事例も見てみましょう。”
質問: Japan's protectionist policies, including agricultural tariffs, stifled competition and inhibited economic growth. What were the motivations behind these protectionist policies, and how did they benefit or harm specific industries and stakeholders in Japan?
農業関税を含む日本の保護主義政策は競争を抑制し、経済成長を阻害しました。これらの保護主義政策の背後にある動機は何でしたか。また、日本の特定の産業や利害関係者にどのような利益や損害を与えましたか。
(Mixtral)
The motivations behind Japan's protectionist policies, particularly in the agricultural sector, were multifaceted. Historically, these policies were designed to protect domestic farmers and rural com-munities, which are significant constituents in Japan's political landscape. The small-scale farming practices, favored by government regulations, are deeply ingrained in Japan's cultural heritage and societal values, contributing to the country's food security and self-sufficiency.
The high tariffs, such as the 777.7% on rice, were intended to shield domestic farmers from foreign competition. This protection allowed them to maintain their production levels and livelihoods, even as the global agricultural sector modernized and scaled up. However, these benefits came at a cost. The protectionist policies stifled competition and inhibited the agricultural sector's growth and effi-ciency. They also led to higher prices for Japanese consumers and limited the country's capacity to become a global leader in high-quality and high-value agricultural products.
Moreover, these policies negatively affected Japan's trade relationships, irritating trading partners and limiting Japan's capacity to enter into free trade agreements. This hindered the country's overall economic growth and its competitiveness in international markets, particularly in sectors where Ja-pan once led, such as electronics. The massive investments in R&D did not yield the expected results due to the lack of competition and innovation. Firms like Sony, Panasonic, and Sharp suffered signif-icant losses and were overtaken by competitors from the US, Korea, and China.
In summary, the motivations behind Japan's protectionist policies were to protect domestic farmers and rural communities, maintain food security, and preserve cultural practices. While these policies provided some benefits to the targeted groups, they also stifled competition, hindered economic growth, and negatively affected trade relationships. The harm caused by these policies was particu-larly evident in industries like electronics, where Japan's global competitiveness was significantly reduced.
日本の保護主義政策、特に農業分野における政策の背後にある動機は多面的でした。歴史的に、これらの政策は日本の政治情勢において重要な構成要素である国内の農家と農村コミュニティを保護するために設計されました。政府の規制によって好まれる小規模農業の慣行は、日本の文化遺産と社会的価値観に深く根付いており、国の食糧安全保障と自給自足に貢献しています。
米に対する777.7%などの高関税は、国内農家を外国の競争から守ることを意図していました。この保護により、世界の農業分野が近代化され規模が拡大しても、農家は生産レベルと生計を維持することができました。しかし、これらの利益には代償が伴いました。保護主義政策は競争を抑制し、農業分野の成長と効率を阻害しました。また、日本の消費者にとって価格の上昇を招き、高品質で高価値の農産物で世界をリードする国になる能力を制限しました。
さらに、これらの政策は日本の貿易関係に悪影響を及ぼし、貿易相手国を苛立たせ、日本の自由貿易協定締結能力を制限した。これにより、日本の全体的な経済成長と国際市場での競争力が妨げられ、特に電子機器など日本がかつてリードしていた分野で顕著となった。研究開発への巨額の投資は、競争と革新の欠如により期待された結果をもたらさなかった。ソニー、パナソニック、シャープなどの企業は大きな損失を被り、米国、韓国、中国の競合他社に追い抜かれた。
要約すると、日本の保護主義政策の背後にある動機は、国内の農家と農村コミュニティを保護し、食糧安全保障を維持し、文化的慣習を保護することであった。これらの政策は対象グループに一定の利益をもたらしたが、競争を抑制し、経済成長を妨げ、貿易関係に悪影響を及ぼした。これらの政策によって引き起こされた損害は、日本の国際競争力が大幅に低下した電子機器などの業界で特に顕著であった。
Time elapsed: 2 s
D先生:“ん?「農業分野の保護主義政策」って、J国の経済衰退に関係がありますか?”
QEU:FOUNDER : “小生の意見では、「ないと思う」けどねえ・・・。こんな違和感を得るたびに、「ご当地LLMがあれば、いいなあ・・・。」という感慨を持つんですよ。ちなみに、小生のGOAL_Aの設定では、農業保護政策に関する記述は、全くの反対のニュアンスですからね。”
(GOAL_A)
The fundamental reason for Japan's long-term economic stagnation is the neglect of investment in education for young people, especially the neglect of liberal arts, and the neglect of protecting and nurturing domestic industries. The fact that there has been no innovation originating from Japan since the beginning of the 21st century is evidence of a decline in the level of education.
The problem is thought to be the excessive deregulation promoted by the LDP. These deregulations only worked to the advantage of foreign financial institutions and some vested interests, and did not help the overall growth of domestic industries. As a result, the Japanese government seems to have sacrificed other industries, especially the semiconductor industry and agriculture, in order to protect the automobile industry.
Due to the increase in hereditary politicians in the LDP, the driving force for changing society through political activities was lost. As a result, collusion and corruption with some large companies progressed. For large companies, being able to borrow money at low interest rates and low wages for labor are an easy way to protect themselves. As a result, low-wage labor became rampant in order to increase productivity, and domestic consumption cooled.
The impoverishment of young people led to a decline in the birth rate. The lack of diversity in society makes it difficult for innovation to occur. Low wages mean it is difficult to invite talented students from overseas, and there are few immigrants.
日本の長期経済停滞の根本的な原因は、若者への教育投資、特に文系教育への投資の怠慢と、国内産業の保護・育成の怠慢である。21世紀に入ってから日本発のイノベーションが生まれていないのは、教育水準の低下の証拠である。
問題は、自民党が推進した過度な規制緩和にあると考えられる。これらの規制緩和は、外国金融機関や一部の既得権益者に有利に働くだけで、国内産業全体の成長にはつながらなかった。その結果、日本政府は自動車産業を守るために、他の産業、特に半導体産業や農業を犠牲にしてきたように思える。
自民党の世襲政治家の増加により、政治活動を通じて社会を変える原動力が失われた。その結果、一部の大企業との癒着や腐敗が進んだ。大企業にとって、低金利でお金を借りられることや、労働賃金が低いことは、身を守るための安易な手段である。その結果、生産性を上げるために低賃金労働が横行し、国内消費が冷え込んだ。
若者の貧困化は出生率の低下を招いた。社会の多様性の欠如はイノベーションを生みにくい。賃金が低いため海外から優秀な学生を招きにくく、移民も少ない。
D先生: “まあ、仮にA国製のLLMモデルでやっても、これと同じ結果になるだろうなあ・・・。さて、FACT_BASED_QUESTIONは、初期質問1件に対して5件づつ発生しますから、QQは5x16件も生成します。この大量の情報はどうするんですか?”
QEU:FOUNDER : “まあ多いと言っても、大した量でもありません。FBQの出来栄えを見て取捨を決めようかと思います。何しろ、FBQ(FACT_BASED_QUESTION)って難しいからね。実際のところ、歩留が低いんじゃない?”
D先生: “学習用のデータが揃ったら、ファインチューニングにいきましょう。”
~ まとめ ~
・・・ 本当は「前回の続き」をやりたかったが、突然の閑話休題です ・・・
QEU:FOUNDER : “本当に「うんざり」するね。本件は(↓)・・・。”
C部長 : “実は、ボクも同じです。なんか・・・、この話(↓)とダブるんですよね。しようこりもなく、「J国スゴイ」をしたいのか?”
QEU:FOUNDER : “あれ?驚いた。まさか、Cさんと同意見とは思わんだ・・・。我々2人とも、アマノジャクだね。僕らはオッサン(↓)のように考えないんです。”
C部長: “ははは・・・。僕たちは当事者じゃないですから・・・。こちらは外側から見てて、すごくシラケました。”
QEU:FOUNDER : “こんなモン、民主主義に付帯した些細なコストにすぎんよ。C国、K国、TWとか、もっと高いコストを払って社会と維持させているんです。誕生会でパーティールームを予約して、宴が終わった後でゴミ掃除をしている無駄に意識高い系ママさんのような「マヌケさ」を感じるわ・・・。そんなもん、(清掃費は)パーティー会場のレンタル料に含まれているわ!!”
C部長: “へっ!?C国の民主主義!?”
QEU:FOUNDER : “彼らには、彼らのやり方があるんだよ。大監督のこの映画(↑)は、あまり有名じゃないでしょう?しかし、リリース当初は、C国内で大きな話題になりました。かなり「敏感な話題」でもありますからね。テレビ上で、この映画への支持をあえて表明した芸能人もおおかった。たぶん、それには多少のリスクがあったんじゃないかな?”
C部長 : “うへえ・・・。あの「世界の大女優」をこんな役柄で使うんですか?”
QEU:FOUNDER : “すごい映画だよ。これは・・・。こんなバイタリティがある社会だから、よその国よりも高い頻度で大人物が生まれ、イノベーションが生まれる。どこぞの三流国とは違うんです。”