Meta の言語モデルと日本語で対話できる chatBOT プログラム(chatBOT)(FlexGen, DeepL, Python を使用)(Windows 上)
FlexGen は,英語,中国語に対応しているようである. そこで,日本語から英語,英語から日本語への翻訳を DeepL API を用いて行い,日本語での対話ができる chatBOT を作る.Python のプログラムを紹介.
【サイト内の関連ページ】
- FlexGen のインストールと動作確認(大規模言語モデル,チャットボット)(Python,PyTorch を使用)(Windows 上): 別ページ »で説明
- DeepL API の認証キーの取得と操舵確認: 別ページ »で説明
- DeepL API を用いて日本語を英語に翻訳,音声合成(音声合成,人工知能による翻訳)(win32api, DeepL, Python を使用)(Windows 上)別ページ »で説明
- 対話システム,chatBOT: PDFファイル, パワーポイントファイル
【関連する外部ページ】
- FlexGen の GitHub のページ: https://github.com/FMInference/FlexGen
- DeepL Pro のページ: https://www.deepl.com/pro#developer
前準備
Build Tools for Visual Studio 2022 (ビルドツール for Visual Studio 2022)または Visual Studio 2022 のインストール(Windows 上)
【インストールの判断】 Build Tools for Visual Studio は,開発ツールセットである. Visual Studio は統合開発環境であり,いくつかの種類があり,Build Tools for Visual Studioの機能を含むか連携して使用するものである.インストールは以下の基準で判断してください:
- Build Tools for Visual Studio の機能のみが必要な場合
- Visual Studio の機能が必要である,あるいは,よく分からない場合
Visual Studio 2022 をインストールする際に,「C++ によるデスクトップ開発」を選択することで, Build Tools for Visual Studio 2022 の機能も一緒にインストールされる.
不明な点がある場合は,Visual Studio 全体をインストール を行う方が良い.
Build Tools for Visual Studio 2022 のインストール(Windows 上)
- Windows で,コマンドプロンプトを管理者権限で起動する(例:Windowsキーを押し,「cmd」と入力し,「管理者として実行」を選択)
次のコマンドを実行
次のコマンドは,Build Tools for Visual Studio 2022と VC2015 再配布可能パッケージをインストールするものである.
- Build Tools for Visual Studio 2022 での C++ によるデスクトップ開発,CLI,ATL,MFC のインストール(Windows 上)
- Visual Studio Installer の起動
起動方法: スタートメニューの「Visual Studio Installer」を選ぶ.
- Visual Studio Build Tools 2022 で「変更」を選ぶ.
- 「C++ によるデスクトップ開発」をクリック.そして,画面右側の「インストール」の詳細で「v143 ビルドツール用 C++/CLI サポート(最新)」,「ATL」,「MFC」をチェックする.その後,「変更」をクリック.
- Visual Studio Installer の起動
Visual Studio のインストール(Windows 上)
- Windows で,コマンドプロンプトを管理者権限で起動する(例:Windowsキーを押し,「cmd」と入力し,「管理者として実行」を選択)
次のコマンドを実行
- コマンドプロンプトを管理者権限で起動する(例:Windowsキーを押し,「cmd」と入力し,「管理者として実行」を選択)
- インストールコマンドの実行
winget install Microsoft.VisualStudio.2022.Community --scope machine --override "--add Microsoft.VisualStudio.Workload.NativeDesktop Microsoft.VisualStudio.ComponentGroup.NativeDesktop.Core Microsoft.VisualStudio.Component.VC.CLI.Support Microsoft.VisualStudio.Component.CoreEditor Microsoft.VisualStudio.Component.NuGet Microsoft.VisualStudio.Component.Roslyn.Compiler Microsoft.VisualStudio.Component.TextTemplating Microsoft.VisualStudio.Component.Windows.SDK.Latest Microsoft.VisualStudio.Component.VC.Tools.x86.x64 Microsoft.VisualStudio.Component.VC.ATL Microsoft.VisualStudio.Component.VC.ATLMFC" winget install Microsoft.VisualStudio.2022.Community --scope machine Microsoft.VCRedist.2015+.x64
インストールされるコンポーネントの説明:
NativeDesktop
:C++によるデスクトップアプリケーション開発のためのワークロード一式NativeDesktop.Core
:C++デスクトップ開発に必要な基本コンポーネント群VC.CLI.Support
:マネージドコードとネイティブコードの統合開発を可能にするC++/CLIサポートCoreEditor
:コード編集,デバッグ,検索などの基本機能を提供するVisual StudioのコアエディタNuGet
:.NETライブラリの依存関係を管理するパッケージ管理システムWindows.SDK.Latest
:Windows 向けアプリケーション開発用SDK(Software Development Kit)VC.Tools.x86.x64
:32ビット及び64ビット向けC++コンパイラとビルドツールVC.ATL
:Windowsコンポーネント開発用のActive Template LibraryVC.ATLMFC
:デスクトップアプリケーション開発用のMicrosoft Foundation Class Library
システム要件と注意事項:
- 管理者権限でのインストールが必須
- 必要ディスク容量:10GB以上
- 推奨メモリ:8GB以上のRAM
- インストール過程でシステムの再起動が要求される可能性がある
- 安定したインターネット接続環境が必要
追加のコンポーネントが必要な場合は,Visual Studio Installerを使用して個別にインストールすることが可能である.
- インストール完了の確認
winget list Microsoft.VisualStudio.2022.Community
トラブルシューティング:
インストール失敗時は,以下のログファイルを確認:
%TEMP%\dd_setup_<timestamp>.log %TEMP%\dd_bootstrapper_<timestamp>.log
- Visual Studio での C++ によるデスクトップ開発,CLI のインストール(Windows 上)
- Visual Studio Installer の起動
起動方法: スタートメニューの「Visual Studio Installer」を選ぶ.
- Visual Studio Community 2022 で「変更」を選ぶ.
- 「C++ によるデスクトップ開発」をチェック.そして,画面右側の「インストール」の詳細で「v143 ビルドツール用 C++/CLI サポート(最新)」をチェックする.その後,「インストール」をクリック.
- Visual Studio Installer の起動
Python 3.10,Git のインストール(Windows 上)
Pythonは,プログラミング言語の1つ. Gitは,分散型のバージョン管理システム.
【手順】
- Windows で,コマンドプロンプトを管理者権限で起動する(例:Windowsキーを押し,「cmd」と入力し,「管理者として実行」を選択)
次のコマンドを実行
次のコマンドは,Python ランチャーとPython 3.10とGitをインストールし,Gitにパスを通すものである.
次のコマンドでインストールされるGitは 「git for Windows」と呼ばれるものであり, Git,MinGW などから構成されている.
winget install --scope machine Python.Launcher winget install --scope machine Python.Python.3.10 winget install --scope machine Git.Git powershell -command "$oldpath = [System.Environment]::GetEnvironmentVariable(\"Path\", \"Machine\"); $oldpath += \";c:\Program Files\Git\cmd\"; [System.Environment]::SetEnvironmentVariable(\"Path\", $oldpath, \"Machine\")"
【関連する外部ページ】
- Python の公式ページ: https://www.python.org/
- Git の公式ページ: https://git-scm.com/
【サイト内の関連ページ】
【関連項目】 Python, Git バージョン管理システム, Git の利用
Build Tools for Visual Studio 2022,NVIDIA ドライバ,NVIDIA CUDA ツールキット 11.8,NVIDIA cuDNN 8.9.7 のインストール(Windows 上)
【サイト内の関連ページ】 NVIDIA グラフィックスボードを搭載しているパソコンの場合には, NVIDIA ドライバ, NVIDIA CUDA ツールキット, NVIDIA cuDNN のインストールを行う.
- Windows での Build Tools for Visual Studio 2022 のインストール: 別ページ »で説明
- Windows での NVIDIA ドライバ,NVIDIA CUDA ツールキット 11.8,NVIDIA cuDNN v8.9.7 のインストール手順: 別ページ »で説明
【関連する外部ページ】
- Build Tools for Visual Studio 2022 (ビルドツール for Visual Studio 2022)の公式ダウンロードページ: https://visualstudio.microsoft.com/ja/visual-cpp-build-tools/
- NVIDIA ドライバのダウンロードの公式ページ: https://www.nvidia.co.jp/Download/index.aspx?lang=jp
- NVIDIA CUDA ツールキットのアーカイブの公式ページ: https://developer.nvidia.com/cuda-toolkit-archive
- NVIDIA cuDNN のダウンロードの公式ページ: https://developer.nvidia.com/cudnn
PyTorch のインストール(Windows 上)
- Windows で,コマンドプロンプトを管理者権限で起動する(例:Windowsキーを押し,「cmd」と入力し,「管理者として実行」を選択)
- PyTorch のページを確認
- 次のようなコマンドを実行(実行するコマンドは,PyTorch のページの表示されるコマンドを使う).
次のコマンドを実行することにより, PyTorch 2.3 (NVIDIA CUDA 11.8 用)がインストールされる. 但し,Anaconda3を使いたい場合には別手順になる.
事前に NVIDIA CUDA のバージョンを確認しておくこと(ここでは,NVIDIA CUDA ツールキット 11.8 が前もってインストール済みであるとする).
PyTorch で,GPU が動作している場合には,「torch.cuda.is_available()」により,True が表示される.
python -m pip install -U --ignore-installed pip python -m pip uninstall -y torch torchvision torchaudio torchtext xformers python -m pip install -U torch torchvision torchaudio numpy --index-url https://download.pytorch.org/whl/cu118 python -c "import torch; print(torch.__version__, torch.cuda.is_available())"
Anaconda3を使いたい場合には, Anaconda プロンプト (Anaconda Prompt) を管理者として実行し, 次のコマンドを実行する. (PyTorch と NVIDIA CUDA との連携がうまくいかない可能性があるため,Anaconda3を使わないことも検討して欲しい).
conda install -y pytorch torchvision torchaudio pytorch-cuda=11.8 cudnn -c pytorch -c nvidia py -c "import torch; print(torch.__version__, torch.cuda.is_available())"
【サイト内の関連ページ】
【関連する外部ページ】
Python の deepl のインストール(Windows 上)
Windows では次のコマンドを実行.
python -m pip install -U deepl

Ubuntu では次のコマンドを実行.
sudo pip3 install -U deepl
DeepL API の認証キー
DeepL API の認証キーの取得はオンラインで可能である.クレジットカード番号の登録などが必要になる.
DeepL API の認証キーの取得と操舵確認: 別ページ »で説明
Meta の言語モデルと日本語で対話できる chatBOT プログラム(FlexGen, DeepL, Python を使用)(Windows 上)
次のプログラムは,FlexGen に同封のプログラムを,DeepL 翻訳も行うように書き換えたもの.
使用するときは,「auth_key = "<DeepL API の AUTH KEY>"」には, DeepL API の認証キーを書くこと.
プログラム実行は,次のプログラムを c.pyのようなファイル名で保存し,「python c.py --model facebook/opt-6.7b」のようなコマンドで行う.「opt-6.7b」のところは,使用するOPT言語モデル名を指定.
"""Run a chatBOT with FlexGen and OPT models."""
# usage: python c.py --model facebook/opt-6.7b
import argparse
import sys
import deepl
import win32com.client
import flexgen
from flexgen.flex_opt import (Policy, OptLM, ExecutionEnv, CompressionConfig, str2bool)
from transformers import AutoTokenizer
auth_key = "<DeepL API の AUTH KEY>"
translator = deepl.Translator(auth_key)
speech = win32com.client.Dispatch("Sapi.SpVoice")
from transformers import AutoTokenizer
from flexgen.flex_opt import (Policy, OptLM, ExecutionEnv, CompressionConfig,
str2bool)
def main(args):
# Initialize environment
env = ExecutionEnv.create(args.offload_dir)
# Offloading policy
policy = Policy(1, 1,
args.percent[0], args.percent[1],
args.percent[2], args.percent[3],
args.percent[4], args.percent[5],
overlap=True, sep_layer=True, pin_weight=args.pin_weight,
cpu_cache_compute=False, attn_sparsity=1.0,
compress_weight=args.compress_weight,
comp_weight_config=CompressionConfig(
num_bits=4, group_size=64,
group_dim=0, symmetric=False),
compress_cache=args.compress_cache,
comp_cache_config=CompressionConfig(
num_bits=4, group_size=64,
group_dim=2, symmetric=False))
# Model
print("Initialize...")
tokenizer = AutoTokenizer.from_pretrained("facebook/opt-30b", padding_side="left")
tokenizer.add_bos_token = False
stop = tokenizer("\n").input_ids[0]
model = OptLM(args.model, env, args.path, policy)
context = (
"A chat between a curious human and a knowledgeable artificial intelligence assistant.\n"
"Human: Hello! What can you do?\n"
"Assistant: As an AI assistant, I can answer questions and chat with you.\n"
)
# Chat
print(context, end="")
while True:
inp = input("Human: ")
if not inp:
print("exit...")
break
speech.Speak(inp)
result = translator.translate_text(inp, target_lang="EN-US")
print(result)
context += "Human: " + result.text + "\n"
inputs = tokenizer([context])
output_ids = model.generate(
inputs.input_ids,
do_sample=True,
temperature=0.7,
max_new_tokens=96,
stop=stop)
outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0]
try:
index = outputs.index("\n", len(context))
except ValueError:
outputs += "\n"
index = outputs.index("\n", len(context))
outputs = outputs[:index + 1]
print(outputs[len(context):], end="")
translated = translator.translate_text(outputs[len(context):], target_lang="JA")
print(translated)
speech.Speak(translated)
context = outputs
# TODO: optimize the performance by reusing context cache and reducing redundant computation.
# Shutdown
env.close_copy_threads()
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--model", type=str, default="facebook/opt-6.7b",
help="The model name.")
parser.add_argument("--path", type=str, default="~/opt_weights",
help="The path to the model weights. If there are no cached weights, "
"FlexGen will automatically download them from HuggingFace.")
parser.add_argument("--offload-dir", type=str, default="~/flexgen_offload_dir",
help="The directory to offload tensors. ")
parser.add_argument("--percent", nargs="+", type=int,
default=[100, 0, 100, 0, 100, 0],
help="Six numbers. They are "
"the percentage of weight on GPU, "
"the percentage of weight on CPU, "
"the percentage of attention cache on GPU, "
"the percentage of attention cache on CPU, "
"the percentage of activations on GPU, "
"the percentage of activations on CPU")
parser.add_argument("--pin-weight", type=str2bool, nargs="?",
const=True, default=True)
parser.add_argument("--compress-weight", action="store_true",
help="Whether to compress weight.")
parser.add_argument("--compress-cache", action="store_true",
help="Whether to compress cache.")
args = parser.parse_args()
assert len(args.percent) == 6
main(args)
下の実行結果では,エベレストの高さを回答している.

下の実行結果では,利用者からの質問により,コンピュータ,チャットボット について説明している
