QEUR23_PHI2SFT16: Reasoningを推論で大量に生成する
~ Llama3も使ってみましょう ~
・・・ 前回のつづきです ・・・
QEU:FOUNDER : “最近、強力な(L3)モデルリリースの大ニュースがあったでしょ?これからReasoningを量産することになるが、その「エンジン」を切り替えることも考えています。”
D先生 : “初めて見たけど、8bってサイズがあるんですね。このL3モデルは、(Tesla)T4クラスで動くんですか?”
QEU:FOUNDER : “いやあ、いまのところはわからないです。いまのところ、L3を推論用に使うことになるが、最低でも推論だけでもいいから、T4環境でイケるのかどうかは半々です。まあ、T4の環境でSFT学習は絶対に無理だろうけどね。まあ、せっかくPhi-2でよい学習ができたので、これからも使ってみたいよね。さて、Qloraの学習結果を読み込み、それをモデルに結合させて連続推論するプログラムをつくりました。プログラムをドン!”
# -----
# 普通の推論(1)
# -----
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
torch.set_default_device("cuda")
tokenizer = AutoTokenizer.from_pretrained("microsoft/phi-2", trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained("microsoft/phi-2", torch_dtype="auto", trust_remote_code=True, eos_token_id=50256, pad_token_id=50256)
# -----
# 普通の推論(2)
# -----
inputs = tokenizer('''What is the most highest mountain in Japan?''', return_tensors="pt", re-turn_attention_mask=True)
outputs = model.generate(**inputs, max_length=200)
text = tokenizer.batch_decode(outputs)[0]
print(text)
# -----
# QLoraを呼び込む
# -----
from peft import (
LoraConfig,
PeftModel,
prepare_model_for_kbit_training,
get_peft_model,
)
# QLoRAアダプタの読み込み
model_lora = PeftModel.from_pretrained(
model,
"./Reasoning_no2/checkpoint-2031/",
device_map="cuda"
)
model_lora.eval()
# ---
# 推論開始
# ---
from transformers import (
AutoModelForCausalLM,
AutoTokenizer,
BitsAndBytesConfig,
HfArgumentParser,
TrainingArguments,
pipeline,
logging,
)
# ---
# システムメッセージの一覧
# ---
sys_message_AIassistant = "You are an AI assistant who is good at providing answers in multiple languages. Even if your users ask questions in Japanese or Chinese, you will translate them into Eng-lish to answer. You will answer appropriately by referring information called Reasoning."
sys_message_translator = "You are translator who is fluent in multiple languages.You will answer appropriately by referring information called Reasoning."
sys_message_creator = "You are creator who create amazing content with your free ideas. You at-tract readers with your beautiful writing such as novel or advertisement. Even if users ask questions in Japanese or Chinese, you will translate their instructions into English to answer properly. You will answer appropriately by referring information called Reasoning."
sys_message_logician = "You are an excellent logician and are instructing users on \"thinking proce-dures for providing better quality reasoning to user-provided questions.\". "
# ---
# AI assistant
# ---
# プロンプト変換用の関数(Individual: For Reasoning)
def create_prompts_func(examples, sys_message):
# ---
instruction = examples[0]
input_text = examples[1]
# ---
if len(input_text) >= 2:
text = f'''
<|system|>{sys_message}\n<|instruction|>{instruction}\n<|context|>{input_text}\n<|reasoning|>
'''
else:
text = f'''
<|system|>{sys_message}\n<|instruction|>{instruction}\n<|reasoning|>
'''
return text
# -----
# 推論パラメタを設定する
# -----
temperature = 0.3
top_p = 0.9
top_k = 50
repetition_penalty = 1.1
# -----
# プロンプトを生成する(推論タイプA)
# -----
instruction = "Please generate reasoning of the following question. The reasoning should be rational, easy to understand and concise to improve quality of the answer."
input_text = "Write a letter to invite a birthday party."
# ---
# システムメッセージの選択
#sys_message = sys_message_AIassistant
#sys_message = sys_message_translator
#sys_message = sys_message_creator
sys_message = sys_message_logician
# ---
examples = [instruction, input_text]
prompt = create_prompts_func(examples, sys_message)
print("--- <prompt> ---")
print(prompt)
# -----
# 個別の推論を実行する
# -----
inputs = tokenizer(prompt, return_tensors="pt", return_attention_mask=True)
outputs = model.generate(**inputs, max_length=400, do_sample=True, top_p=top_p, top_k=top_k, repetition_penalty=repetition_penalty)
text = tokenizer.batch_decode(outputs)[0]
print("--- <text> ---")
print(text)
##############################
# INPUT連続出力
##############################
import random
import re
def cut_text_after_last_token(text, token):
last_occurrence = text.rfind(token)
if last_occurrence != -1:
result = text[last_occurrence + len(token):].strip()
return result
else:
return None
# ----
def create_text(message, temperature, top_p, top_k, repetition_penalty):
# ---
inputs = tokenizer(message, return_tensors="pt", return_attention_mask=True)
outputs = model.generate(**inputs, max_length=400, do_sample=True, top_p=top_p, top_k = top_k, repetition_penalty = repetition_penalty)
response = tokenizer.decode(outputs[0], skip_special_tokens=True)
# ---
token = "<|response|>"
cut_response = cut_text_after_last_token(response, token)
#print(" --- <cut_response> --- ")
#print(cut_response)
return cut_response
#########################
# JSONファイルを読み込む
###################################
# JSONデータを読み込み、EXCELに出力する
# reading JSON
import pandas as pd
import json
# -----
# JSONファイルを読み込む
df = pd.read_json('alpaca_multi_language_train0416_openqa_simple.json')
#print(df)
# -----
# DF内容出力
arr_seq = df.loc[:,"seq"]
arr_input = df.loc[:,"input"]
arr_instruction = df.loc[:,"instruction"]
arr_question = df.loc[:,"question"]
print(arr_question[0:10])
#########################
# 実行テスト(その1)
###################################
# -----
# リストの初期化
arr_prompt = []
arr_response = []
# -----
# 推論の連続実行
# -----
for i in range(len(arr_input)): # len(arr_input)
# ----
str_question = arr_question[i]
instruction = str_question
input_text = ""
# ----
examples = [instruction, input_text]
prompt = create_prompts_func(examples, sys_message)
# ----
# プロンプトの出力
#print(f" --- {i}:<prompt> --- ")
#print(prompt)
# ----
response = create_text(prompt, temperature, top_p, top_k, repetition_penalty)
print(f" --- {i}:<response> --- ")
print(response)
arr_prompt.append(str_question)
arr_response.append(response)
# -----
# EXCELへの出力
# -----
# データフレームの作成
df_out = pd.DataFrame(arr_seq[0:10], columns=["seq"])
df_out.loc[:,"question"] = arr_prompt
df_out.loc[:,"response"] = arr_response
#df_out
# ---
# EXCEL出力
df_out.to_excel('alpaca_multi_language_train0416_inference.xlsx', sheet_name='new_sheet_name')
QEU:FOUNDER : “いきなり、Phi-2(P2)モデルで推論の連続生成した結果をだすよ。どう?すごいでしょ!?”
D先生(設定年齢65歳) : “「う~ん、すごいねえ・・・。」と言いたいところですが、なぜいきなりL3の推論結果が出てくるんですか(笑)?”
(Question)
Find the square root of 156.
(L3)
To accurately solve this problem, I consider basic mathematical concepts, specifically algebra and arithmetic. I employ the square root operation, taking into account the order of operations and the possibility of simplifying the calculation. By recognizing the nature of the problem as a simple alge-braic operation, I will be able to provide a correct and efficient solution. この問題を正確に解決するために、基本的な数学の概念、特に代数と算術を検討します。 演算順序と計算の簡略化を考慮して平方根演算を採用しています。 問題の性質を単純な代数演算として認識することで、正しく効率的な解決策を提供できるようになります。
(P2) I calculate the square root of 156 as approximately 12.49. This is done by finding a number that, when multiplied by itself, equals 156. Using a calculator or other appropriate method, I determine that the square root of 156 is approximately 12.49. Providing this precise solution 156 の平方根は約 12.49 と計算されます。 これは、それ自体を掛け合わせると 156 に等しくなる数値を見つけることによって行われます。電卓またはその他の適切な方法を使用して、156 の平方根が約 12.49 であると判断します。 この正確なソリューションを提供します。
QEU:FOUNDER(設定年齢65歳) : “L3とP2モデルでは、生成されたReasoningの品質にかなり大きな差異がありますよね。P2モデルでは、モデルが我慢できずに「答え」を言っていることが多いです。さて、L3による推論にあたり、このサービス(↓)を使ってみました。”
D先生(設定年齢65歳) : “この推論サービスはただなの?日本語はOK?”
QEU:FOUNDER(設定年齢65歳) : “今のところ、ただですよ。いろいろ試してみたが、やはり8bでは日本語処理には大した性能はでないよ。”
D先生(設定年齢65歳) : “がっかり・・・。でも、学習するレコードは数千はあるんだから、GUIで手作業でやっていたら大変でしょ?”
(Question)
Given a text, find the most relevant keyword to describe it
A wind turbine is a device that converts wind energy into electrical energy.
(L3)
To analyze the given text and extract the most relevant keyword, I apply a process of semantic analy-sis. I identify key phrases and interpret the context in which the text is written. Considering the text describes a wind turbine, I infer that the most relevant keyword is 'renewable energy', as it encapsu-lates the fundamental concept and purpose of the device described. 与えられたテキストを分析し、最も関連性の高いキーワードを抽出するために、意味分析のプロセスを適用します。 キーフレーズを特定し、テキストが書かれている文脈を解釈します。 本文が風力タービンについて説明していることを考慮すると、説明されている装置の基本的な概念と目的が要約されているため、最も関連性の高いキーワードは「再生可能エネルギー」であると推測します。
(P2)
The key keyword in this text is "wind turbine". This keyword helps to specify the type of device being described - one that converts wind energy into electrical energy. It provides context about the pur-pose and function of the device, allowing for a more accurate understanding of its capabilities. By focusing on this specific keyword, we can provide a more precise description of the device and its role in harnessing renewable energy sources. このテキストの重要なキーワードは「風力タービン」です。 このキーワードは、風力エネルギーを電気エネルギーに変換するデバイスの種類を指定するのに役立ちます。 デバイスの目的と機能に関するコンテキストが提供され、デバイスの機能をより正確に理解できるようになります。 この特定のキーワードに焦点を当てることで、デバイスと再生可能エネルギー源の活用におけるその役割についてより正確に説明することができます。
QEU:FOUNDER(設定年齢65歳) : “実は、今回の推論において、GUIを使った手作業ではやっていません。これ以上のタネアカシは、今回のテーマから外れているので説明しません。それでもね・・・。自分たちが育てたP2モデルでもかなり良さげな推論を出してくれるんですよ。もちろん良さげなのは一部だけなのだが、それでもすごいとおもわん?”
(重要:MITライセンスへのリンク:これからは、ず~っと使うよ)
D先生(設定年齢65歳) : “ここはP2モデルベースでの開発に、あくまでこだわりたいですよね。学習コストと手間が圧倒的に違うんです。もし、今、我々がやっている開発のベースが7bモデルだと・・・。”
QEU:FOUNDER : “コストと手間が酷くて、とてもじゃないが続けられません。さて、いままでの開発を通じて、AIアプリの開発者がどのようなことをやっているのか、おぼろげながらわかってきました。”
QEU:FOUNDER : “今回、せっかく2つのLLMからの推論出力が出てきたのだから、アンサンブル処理をやってみたいと思うんだ。”
D先生 : “古典的な機械学習では、ランダムフォレスト(RF)のような手法ですか?LLMで、そんなことができるんですか?”
QEU:FOUNDER : “RF法とは使う技術は全く違うが、Prompt Engineeringを使えば楽勝にアンサンブルできますよ。これから、どんどん面白くなってくるこのBONSAIプロジェクト・・・。是非、カンパをお願いします。”
>寄付のお願い(click here for buy me a cup of coffee)<
D先生: “皆さま、「Buy me a cup of coffee」をいただけませんでしょうか。”
~ まとめ ~
・・・ 前回のつづきです ・・・
QEU:FOUNDER(設定年齢65歳) : “このBONSAIプロジェクトで徐々に汎用技術構造の正体が明らかになってくるでしょう。このプロジェクトがうまく行くと、世の中の景気がもうすこしよくなると思いますよ。景気の問題の本質は、供給側ではなく需要側なんですから・・・。平成でむちゃくちゃになった、社会と経済をすこしでもよくしたい。それは、我々「新しいオッサン」の役目だと思うんです。”
C部長(設定年齢50歳前半) : “とうとう、「新しいオッサン」という用語まで発明しおった・・・。それにしても、21世紀も4分の1に近づき、J国もかなり破壊されましたね。この原因はなんだと思いますか?”
QEU:FOUNDER : “「古いオッサン」が、長い間、なにもしなかったから。昭和では「魔法の杖」でも、令和では「田吾作の天秤棒」になるのはしようがないよ。なにもしなければね・・・。すべての問題の本質は「価値論(↓)」にある。”
(旧:モノの価値とは)
- (生活が、仕事が)便利になる
- 自分を変えることができる
- モノがあると快適、楽しい
- 条件付け(広告、ステルス・マーケティング、画一教育、ハラスメント)
C部長 : “この着眼点は新鮮だと思います。これがなぜ、経済と社会を破壊するほどのパワーを持つんですか?”
QEU:FOUNDER : “さきほど小生が挙げた4種類のモノの価値のバランスは国によって、文化によってちがいます。しかし、J国の21世紀以降では「条件付け」の要因がもっとも大きい。そして、その結果として条件付けを商売にする会社が強くなってきます。”
C部長 : “他の文化ではちがうんですかねえ?”
QEU:FOUNDER : “たとえば、「インダストリー5.0」を提案した地域の文化って、J国とはかなり違うでしょ?だから、小生も彼らの考え方に対して、かなり違和感があったんです。でも、よく考えてみると、彼らはすでに「パーソナリゼーションなんてあたりまえ」の段階に来ているのかもしれない。”
C部長 : “つまり、QEUプロジェクトのコンセプトは、世界規模の視点でいえば「チャーハン(周回遅れ)」であると・・・(笑)。なるほどね。そうかもしれない・・・。”
QEU:FOUNDER : “そうそう・・・。個人的には、東アジア全般として同レベルであると思うがね。経済と文化の破壊が進んだ分だけ、J国は先端にいるんじゃないかな?だから、いままで条件付けに頼ってきた価値のしくみを変えていかないと、これからの時代はもたないんですよ。”
(新:モノの価値とは)
- (生活が、仕事が)便利になる
- 自分を変えることができる
- モノがあると快適、楽しい
- 条件付け→パーソナリゼーション
C部長 : “これから、大きくかわっていくでしょうね・・・。”
QEU:FOUNDER : “楽観的にいうと、大きくかわるでしょう。”
C部長 : “悲観的には・・・?”
QEU:FOUNDER : “破滅ですな・・・(笑)。”
コメント
コメントを投稿