QEUR23_PHI2SFT32: RAG(LangChain-Phi3)を使ってみる(前回の出力総合を使う)
~ 今回のモデルはいろいろ使えて、便利です。 ~
QEU:FOUNDER(設定年齢65歳) : “今回で、簡易AGIのサブ・プロジェクトが終わりましたが、その活動を通じていくつかのデータ(↓)が取れました。”
D先生(設定年齢65歳) : “これらの情報は、Q&Aの形になっているから、LLMモデルのfinetuneで使えるんじゃ・・・。”
(モノの価値とは)
- (生活が、仕事が)便利になる
- 自分を変えることができる
- モノがあると快適、楽しい
- パーソナリゼーション
QEU:FOUNDER : “そう思うでしょ?・・でも、小生は、敢てそのステップの前に「RAGによるスクリーニング」の作業を入れます。そうしたほうがハルシネーションを抑えやすいし、「モノの価値」を上げるために、ユーザーがマニュアル作業でLLMモデルに知識を入れる余地が得られます。ちょうど似たプログラムを手に入れました。”
QEU:FOUNDER : “今回は、推論リソースが少なくて済むPhi-3-miniを使います。まずは、パッケージのインストールから・・・。”
# ---
!pip install flash_attn
!pip install pydantic=='1.10.9'
!pip install -U langchain
!pip install -U tiktoken
!pip install -U pypdf
!pip install -U faiss-gpu
!pip install sentence_transformers==2.2.2
!pip install -U InstructorEmbedding
!pip install -U transformers
!pip install -U accelerate
QEU:FOUNDER : “ちなみに、参考サイト(↑)のプログラムを使ったら、初めは山ほどのエラーが出ました(笑)。そのほとんどがインストールするパッケージに関するエラーだったので、もし以下のプログラムを使いたい人は気を付けて・・・。アナタの環境で、うまくいく保証はないです。”
# ---
import os
import glob
import textwrap
import time
import gc
import langchain
### loaders
from langchain.document_loaders import PyPDFLoader, TextLoader, DirectoryLoader
### splits
from langchain.text_splitter import RecursiveCharacterTextSplitter
### prompts
from langchain import PromptTemplate
### vector stores
from langchain_community.vectorstores import FAISS
### models
from langchain.llms import HuggingFacePipeline
from langchain.embeddings import HuggingFaceInstructEmbeddings
### retrievers
from langchain.chains import RetrievalQA
# ---
import torch
#import transformers
from transformers import (
AutoTokenizer, AutoModelForCausalLM,
pipeline
)
# ---
# Config(CFG) class enables easy and organized experimentation
class CFG:
DEBUG = False
# LLM
#model_name = 'microsoft/Phi-3-mini-128k-instruct'
temperature = 0.4
top_p = 0.90
repetition_penalty = 1.15
max_len = 8192
max_new_tokens = 512
# splitting
split_chunk_size = 800
split_overlap = 400
# embeddings
embeddings_model_repo = 'BAAI/bge-base-en-v1.5'
# similar passages
k = 6
# paths
PDFs_path = './input_papers/'
TXTs_path = './input_excels/'
Embeddings_path = '/input_excels/faiss-ml-papers-st'
Output_folder = './ml-papers-vectordb'
D先生(設定年齢65歳) : “ここまでは、パラメタの設定だけですね。”
QEU:FOUNDER(設定年齢65歳) : “以下の処理で、指定ディレクトリ下に配置されている複数のTxtファイルの中のデータを取り出せます。”
# ---
# [TXT]Load data
loader = DirectoryLoader(
CFG.TXTs_path,
glob = "./*.txt",
loader_cls = TextLoader,
show_progress = True,
use_multithreading = True
)
documents = loader.load()
# ---
print(f'We have {len(documents)} pages in total')
# ---
# Splitter
text_splitter = RecursiveCharacterTextSplitter(
chunk_size = CFG.split_chunk_size,
chunk_overlap = CFG.split_overlap
)
texts = text_splitter.split_documents(documents)
print(f'We have created {len(texts)} chunks from {len(documents)} pages')
# ---
# Create Embeddings
### we create the embeddings if they do not already exist in the input folder
if not os.path.exists(CFG.Embeddings_path + '/index.faiss'):
print('Creating embeddings...\n\n')
### download embeddings model
embeddings = HuggingFaceInstructEmbeddings(
model_name = CFG.embeddings_model_repo,
model_kwargs = {"device": "cuda"}
)
### create embeddings and DB
vectordb = FAISS.from_documents(
documents = texts,
embedding = embeddings
)
### persist vector database
vectordb.save_local(f"{CFG.Output_folder}/faiss_index_ml_papers") # save in output folder
# ---
# Load Embeddings
# You can just load the embeddings if you have already created and saved them previously
### download embeddings model
embeddings = HuggingFaceInstructEmbeddings(
model_name = CFG.embeddings_model_repo,
model_kwargs = {"device": "cuda"}
)
### load vector DB embeddings
vectordb = FAISS.load_local(
CFG.Output_folder + '/faiss_index_ml_papers', # from output folder
embeddings,
allow_dangerous_deserialization = True,
)
# ---
### test if vector DB was loaded correctly
vectordb.similarity_search('The European Union')
# ---
model = AutoModelForCausalLM.from_pretrained(
"microsoft/Phi-3-mini-128k-instruct",
device_map="cuda",
torch_dtype="auto",
trust_remote_code=True,
)
tokenizer = AutoTokenizer.from_pretrained("microsoft/Phi-3-mini-128k-instruct")
# ---
# Pipeline
terminators = [
tokenizer.eos_token_id,
tokenizer.bos_token_id
]
### hugging face pipeline
pipe = pipeline(
task = "text-generation",
model = model,
tokenizer = tokenizer,
eos_token_id = terminators,
do_sample = True,
max_new_tokens = CFG.max_new_tokens,
temperature = CFG.temperature,
top_p = CFG.top_p,
repetition_penalty = CFG.repetition_penalty,
)
### langchain pipeline
llm = HuggingFacePipeline(pipeline = pipe)
# ---
# Prompt Template
prompt_template = """
<|system|>
You are an expert assistant that answers questions about machine learning and Large Language Models (LLMs).
You are given some extracted parts from machine learning papers along with a question.
If you don't know the answer, just say "I don't know." Don't try to make up an answer.
It is very important that you ALWAYS answer the question in the same language the question is in. Remember to always do that.
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}
<|end|>
<|assistant|>
"""
# ---
PROMPT = PromptTemplate(
template = prompt_template,
input_variables = ["context", "question"]
)
# ---
# Retrieval chain
# Retrieval chain using previously created vector database
retriever = vectordb.as_retriever(
search_type = "similarity",
search_kwargs = {"k": CFG.k}
)
# ---
qa_chain = RetrievalQA.from_chain_type(
llm = llm,
chain_type = "stuff", # map_reduce, map_rerank, stuff, refine
retriever = retriever,
chain_type_kwargs = {"prompt": PROMPT},
return_source_documents = True,
verbose = False
)
# ---
# 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
# ---
# Ask Questions
query = "What role can regional organizations, such as the European Union and the Organization for Security and Co-operation in Europe (OSCE), play in promoting dialogue and conflict resolution be-tween Russia and Ukraine?"
result = llm_ans(query)
print(result)
D先生(設定年齢65歳) : “やっと答えが出てきました。いやあ、長かった・・・。RAGは、結構面倒なものですね。”
D先生 : “あれ?回答文が短くなっていませんか?私の気のせいか?”
QEU:FOUNDER : “明らかに、今回の方が短いですよ。やはり、モデルのパラメタ数が軽くなっている分だけ、出てくる情報がすくなっているようです。少し、詳しく見てみましょう。”
(質問)
What role can regional organizations, such as the European Union and the Organization for Securi-ty and Co-operation in Europe (OSCE), play in promoting dialogue and conflict resolution between Russia and Ukraine?
欧州連合や欧州安全保障協力機構(OSCE)などの地域組織は、ロシアとウクライナ間の対話と紛争解決を促進する上でどのような役割を果たすことができるのでしょうか?
(前回)¶
Regional organizations, such as the European Union (EU) and the Organization for Security and Co-operation in Europe (OSCE), can play a crucial role in promoting dialogue and conflict resolu-tion between Russia and Ukraine. Here are some ways they can contribute:
1. Facilitating Dialogue: Regional organizations can provide a platform for Russia and Ukraine to engage in constructive dialogue, helping to reduce tensions and build trust. The OSCE, in particular, has a long history of facilitating dialogue and conflict resolution in the region.
2. Mediation and Negotiation: The EU and OSCE can offer mediation and negotiation services to help resolve disputes between Russia and Ukraine. Their involvement can lend credibility and legiti-macy to the negotiation process, increasing the chances of a peaceful resolution.
3. Conflict Prevention and Early Warning: Regional organizations can establish early warning sys-tems to detect potential conflicts and take preventive measures to mitigate their escalation. This can involve monitoring and reporting on potential flashpoints, as well as providing technical assistance to help prevent conflicts.
4. Capacity Building and Technical Assistance: The EU and OSCE can provide capacity-building programs and technical assistance to help Ukraine and Russia strengthen their institutions, improve governance, and enhance their conflict resolution capabilities.
5. Economic Incentives and Sanctions: Regional organizations can offer economic incentives to en-courage cooperation and compliance with agreements, or impose targeted sanctions to deter aggres-sive behavior.
6. Promoting Regional Cooperation: The EU and OSCE can foster regional cooperation and integra-tion, encouraging Russia and Ukraine to work together on issues of common interest, such as energy security, trade, and environmental protection.
7. Supporting Civil Society: Regional organizations can support civil society organizations and grassroots initiatives that promote dialogue, reconciliation, and conflict resolution between Russia and Ukraine.
8. Providing Humanitarian Assistance: In the event of a conflict, regional organizations can provide humanitarian assistance to affected populations, helping to alleviate suffering and promote stability.
In conclusion, regional organizations like the EU and OSCE have a vital role to play in promoting dialogue and conflict resolution between Russia and Ukraine. By leveraging their unique strengths and capabilities, they can help reduce tensions, build trust, and promote a peaceful resolution to the conflict.
欧州連合 (EU) や欧州安全保障協力機構 (OSCE) などの地域組織は、ロシアとウクライナ間の対話と紛争解決を促進する上で重要な役割を果たすことができます。これらの組織が貢献できる方法は次のとおりです。
1. 対話の促進: 地域組織は、ロシアとウクライナが建設的な対話を行うためのプラットフォームを提供し、緊張を緩和し、信頼を築くのに役立ちます。特に OSCE は、この地域での対話と紛争解決を促進してきた長い歴史を持っています。
2. 調停と交渉: EU と OSCE は、ロシアとウクライナ間の紛争の解決を支援するために調停と交渉のサービスを提供することができます。これらの組織が関与することで、交渉プロセスに信頼性と正当性がもたらされ、平和的解決の可能性が高まります。
3. 紛争予防と早期警告: 地域組織は、潜在的な紛争を検出し、そのエスカレーションを緩和するための予防措置を講じるための早期警告システムを確立できます。これには、潜在的な発火点の監視と報告、および紛争の予防に役立つ技術支援の提供が含まれます。
4.能力構築と技術支援: EU と OSCE は、ウクライナとロシアが制度を強化し、統治を改善し、紛争解決能力を高めるのを支援するために、能力構築プログラムと技術支援を提供することができます。
5. 経済的インセンティブと制裁: 地域組織は、協力と協定の遵守を促すために経済的インセンティブを提供したり、攻撃的な行動を抑止するために標的を絞った制裁を課したりすることができます。
6. 地域協力の促進: EU と OSCE は、エネルギー安全保障、貿易、環境保護など、共通の関心事項についてロシアとウクライナが協力するよう促し、地域協力と統合を促進することができます。
7. 市民社会の支援: 地域組織は、ロシアとウクライナ間の対話、和解、紛争解決を促進する市民社会組織や草の根の取り組みを支援することができます。
8. 人道支援の提供: 紛争が発生した場合、地域組織は被災者に人道支援を提供し、苦しみを和らげ、安定を促進することができます。
結論として、EU や OSCE などの地域組織は、ロシアとウクライナ間の対話と紛争解決を促進する上で重要な役割を果たします。それぞれの強みと能力を活用することで、緊張を緩和し、信頼を築き、紛争の平和的解決を促進することができます。
(今回)
Regional organizations like the European Union and the Organization for Security and Co-operation in Europe can significantly assist in fostering dialogue and resolving conflicts between Russia and Ukraine. They can serve as platforms for constructive discussions aimed at reducing ten-sion and building mutual trust. Moreover, these entities possess valuable experiences in mediating and negotiating which could be instrumental in reaching amicable solutions. Furthermore, through various mechanisms including monitoring, verification, providing diplomatic backing, and offering skill enhancement initiatives, the EU and OSCE can greatly contribute to creating conditions favora-ble for a peaceful settlement of the dispute.
欧州連合や欧州安全保障協力機構などの地域組織は、ロシアとウクライナの間の対話を促進し、紛争を解決する上で大きな助けとなる可能性がある。これらの組織は、緊張を緩和し相互信頼を築くことを目的とした建設的な話し合いの場として機能することができる。さらに、これらの組織は仲裁や交渉において貴重な経験を有しており、それが友好的な解決に至る上で役立つ可能性がある。さらに、監視、検証、外交的支援の提供、スキル向上イニシアチブの提供など、さまざまなメカニズムを通じて、EUとOSCEは紛争の平和的解決に有利な条件を作り出すことに大きく貢献できる。
D先生 : “う~ん・・・、なんというか・・・。今回の出力文は、前回の出力の「まとめ」みたいな感じですね。”
QEU:FOUNDER : “D先生・・・、よい着眼点です。さらに、もう一つの例を見てみましょう。”
(質問)
What specific measures can be taken to address Russia's concerns about NATO expansion, and how can NATO member states balance their security interests with Russia's national security concerns?
NATO拡大に対するロシアの懸念に対処するためにどのような具体的な措置を講じることができるか、またNATO加盟国は自国の安全保障上の利益とロシアの国家安全保障上の懸念とをどのようにバランスさせることができるか。
(前回)
To address Russia's concerns about NATO expansion, several specific measures can be taken:
1. Dialogue and Communication: Establish a regular, high-level dialogue between NATO and Russia to discuss concerns, interests, and security issues. This can help build trust and understanding, re-ducing tensions and misconceptions.
2. Transparency and Confidence-Building Measures: Implement confidence-building measures, such as joint military exercises, joint crisis management, and cooperative counter-terrorism efforts. This can foster cooperation and reduce the risk of misperception.
3. NATO-Russia Council: Revitalize the NATO-Russia Council, established in 2002, to facilitate co-operation on issues like counter-terrorism, non-proliferation, and crisis management.
4. Gradual Expansion: Consider a gradual, phased expansion of NATO membership, allowing Rus-sia to adapt to the changing security landscape. This could involve temporary moratoriums on new memberships or the creation of a "waiting room" for aspiring members.
5. Security Guarantees: Offer Russia security guarantees, such as a non-aggression pact or a treaty on mutual security assurances, to alleviate concerns about NATO's intentions.
6. Cooperative Security: Foster cooperative security arrangements, like the NATO-Russia Coopera-tive Airspace Initiative, to promote mutual understanding and trust.
7. Economic Cooperation: Encourage economic cooperation between NATO member states and Russia, promoting interdependence and reducing the likelihood of conflict.
8. Conflict Resolution Mechanisms: Establish mechanisms for resolving conflicts and disputes, such as the OSCE's (Organization for Security and Co-operation in Europe) conflict resolution mecha-nisms.
To balance their security interests with Russia's national security concerns, NATO member states can:¶
1. Diversify Security Partnerships: Develop security partnerships with other countries, reducing dependence on NATO and promoting a more diverse security landscape.
2. Regional Security Initiatives: Support regional security initiatives, such as the European Union's Eastern Partnership, to promote stability and cooperation in Eastern Europe.
3. Risk Reduction Measures: Implement risk reduction measures, like the Incidents at Sea Agree-ment, to reduce the risk of accidental conflict.
4. NATO's Open-Door Policy: Re-evaluate NATO's open-door policy, considering the potential con-sequences of rapid expansion and the need for a more gradual, cooperative approach.
5. Russia-NATO Joint Threat Assessment: Conduct a joint threat assessment with Russia to identify common security challenges and develop cooperative responses.
By implementing these measures, NATO member states can address Russia's concerns about NATO expansion, balance their security interests with Russia's national security concerns, and promote a more stable and cooperative security environment in Europe.
NATO拡大に関するロシアの懸念に対処するには、いくつかの具体的な措置を講じることができます。
1. 対話とコミュニケーション: NATOとロシアの間で、懸念、利益、安全保障問題について話し合うための定期的な高レベルの対話を確立します。これにより、信頼と理解が構築され、緊張と誤解が軽減されます。
2. 透明性と信頼醸成措置: 合同軍事演習、合同危機管理、協力的なテロ対策などの信頼醸成措置を実施します。これにより、協力が促進され、誤解のリスクが軽減されます。
3. NATO-ロシア理事会: 2002年に設立されたNATO-ロシア理事会を再活性化し、テロ対策、核不拡散、危機管理などの問題に関する協力を促進します。
4. 段階的拡大: NATO加盟国の段階的拡大を検討し、ロシアが変化する安全保障環境に適応できるようにします。これには、新規加盟の一時的停止や、加盟希望者のための「待機室」の設置が含まれる可能性がある。
5. 安全保障保証: NATO の意図に関する懸念を軽減するため、ロシアに不可侵条約や相互安全保障条約などの安全保障保証を提供する。
6. 協力的安全保障: NATO とロシアの協力的空域イニシアチブなどの協力的安全保障協定を促進し、相互理解と信頼を促進する。
7. 経済協力: NATO 加盟国とロシア間の経済協力を奨励し、相互依存を促進し、紛争の可能性を減らす。
8. 紛争解決メカニズム: OSCE (欧州安全保障協力機構) の紛争解決メカニズムなど、紛争や論争を解決するメカニズムを確立する。
NATO 加盟国は、自国の安全保障上の利益とロシアの国家安全保障上の懸念とのバランスを取るために、次のことができる。
1.安全保障パートナーシップの多様化: 他の国々との安全保障パートナーシップを構築し、NATOへの依存を減らし、より多様な安全保障環境を推進する。
2. 地域安全保障イニシアチブ: 欧州連合の東方パートナーシップなどの地域安全保障イニシアチブを支援し、東ヨーロッパの安定と協力を促進する。
3. リスク削減措置: 海上事故協定などのリスク削減措置を実施し、偶発的な紛争のリスクを軽減する。
4. NATOの門戸開放政策: 急速な拡大の潜在的な影響と、より段階的で協力的なアプローチの必要性を考慮して、NATOの門戸開放政策を再評価する。
5. ロシアとNATOの共同脅威評価: 共通の安全保障上の課題を特定し、協力的な対応策を策定するために、ロシアと共同で脅威評価を実施する。
これらの措置を実施することで、NATO加盟国はNATOの拡大に関するロシアの懸念に対処し、自国の安全保障上の利益とロシアの国家安全保障上の懸念のバランスを取り、ヨーロッパでより安定した協力的な安全保障環境を促進することができる。
(今回)
Specific measures include diversifying security partnerships, supporting regional security initia-tives, implementing risk reduction measures, reconsidering NATO's open-door policy for a more gradual approach, conducting a joint threat assessment with Russia, establishing high-level dialogues, enhancing transparency through confidence-building measures, revitalizing the NATO-Russia Coun-cil, encouraging economic cooperation, and creating conflict resolution mechanisms. Additionally, offering Russia security guarantees, fostering cooperative security arrangements, and potentially adopting a waiting period before admitting new members into NATO can also help balance both par-ties' security interests and concerns.
具体的な措置としては、安全保障パートナーシップの多様化、地域安全保障イニシアチブの支援、リスク削減措置の実施、NATOの対外開放政策をより段階的なアプローチに再検討すること、ロシアとの共同脅威評価の実施、ハイレベル対話の確立、信頼醸成措置による透明性の向上、NATO・ロシア理事会の再活性化、経済協力の促進、紛争解決メカニズムの創設などがある。さらに、ロシアに安全保障保証を提供し、協力的な安全保障協定を促進し、NATOへの新規加盟を認める前に待機期間を設ける可能性も、双方の安全保障上の利益と懸念のバランスをとるのに役立つ可能性がある。
D先生: “やっぱり、今回の出力は「前回のまとめ」ですね。”
QEU:FOUNDER : “そもそもの問題は、「前回の出力にはOPINIONしかないからこうなった」ことです。もし、前回の出力にFACTが含まれており、それがRAGから供給されていれば、もっと違った回答になっていたでしょう。これは、我々の「Question to Question」の目標である、「キレのある質問」にも同じことが言えます。”
D先生: “さらにいうと、回答だけでなく、質問にもFACTが付加されていなければならない。”
QEU:FOUNDER : “いわゆる「当事者意識」というやつです。当事者意識があれば、質問には必ずFACTが入ってきます。このように、前回の出力をRAG内に入れただけでは、情報が全然足らないことがわかりました。次はFACT情報を注入しましょう。カンパをお願いします。よろしくお願いします。”
>寄付のお願い(click here for buy me a cup of coffee)<
D先生: “どんな情報をRAGに注入するんだろう・・・。”
~ まとめ ~
QEU:FOUNDER : “いやあ、若いなあ・・・。さすがに・・・。 “
C部長 : “あの人が若々しいのはあたりまえです。この動画は、ずいぶん昔ですからね・・・。”
QEU:FOUNDER : “これは、皆が知らない「闇」の件です。”
C部長 : “オッサン・ホイホイの闇・・・。”
QEU:FOUNDER : “若い人は興味がないと思うが、これは見ておいても損はないです。”
コメント
コメントを投稿