In [1]:
import os
import psutil
import time
import litert_lm
In [9]:
process = psutil.Process(os.getpid())
mem_before = process.memory_info().rss / 1024**2 # MB
model_path = r"H:\LLM_Models\litert-lm\qwen2.5-corder-7b-it-dynamic_wi4_afp32\qwen2.5-corder-7b-it-dynamic_wi4_afp32.litertlm"
PROMPT = (
"transformersとFAISSとstreamlitを使った、"
"QAチャットボットをPythonで構築して。"
)
process = psutil.Process(os.getpid())
mem_before = process.memory_info().rss / 1024**2
start = time.perf_counter()
with litert_lm.Engine(
str(model_path),
backend=litert_lm.Backend.CPU(),
) as engine:
with engine.create_conversation() as conversation:
response = conversation.send_message(PROMPT)
answer = response["content"][0]["text"]
mem_during = process.memory_info().rss / 1024**2
end = time.perf_counter()
mem_after = process.memory_info().rss / 1024**2
print(answer)
print("=" * 60)
print(f"実行前メモリ使用量 : {mem_before:.2f} MB")
print(f"モデル使用中メモリ使用量 : {mem_during:.2f} MB")
print(f"解放後メモリ使用量 : {mem_after:.2f} MB")
print(f"モデル使用中の増加量 : {mem_during - mem_before:.2f} MB")
print(f"実行時間 : {end - start:.3f} 秒")
もちろんです。以下は、transformersとFAISSとstreamlitを使用して質問応答チャットボットを構築するためのPythonコードの基本的な例です。
まず、必要なライブラリをインストールします。
```
pip install transformers faiss-cpu streamlit
```
次に、以下のコードを実行します。
```python
import streamlit as st
from transformers import pipeline
import faiss
import numpy as np
# transformersのpipelineを使用して、質問応答モデルをロードします。
qa = pipeline("question-answering")
# ここでは、事前に学習済みのモデルを使用しますが、必要に応じて独自のモデルを読み込むこともできます。
model_name = "bert-base-japanese"
# データセットをロードします。ここでは、事前に学習済みのモデルを使用しますが、必要に応じて独自のデータセットを使用することもできます。
# dataset = load_dataset("squad_japanese")
# データをベクトル化します。
# sentences = dataset["train"]["context"] + dataset["train"]["question"]
# inputs = qa.tokenizer(sentences, return_tensors="pt", truncation=True, padding=True)
# with torch.no_grad():
# embeddings = model(**inputs).last_hidden_state
# ベクトルを保存します。
# np.save("embeddings.npy", embeddings)
# 事前に学習済みのベクトルを読み込みます。
embeddings = np.load("embeddings.npy")
# FAISSでインデックスを作成します。
index = faiss.IndexFlatL2(embeddings.shape[1])
index.add(embeddings)
# Streamlitのアプリケーションを作成します。
st.title("質問応答チャットボット")
# ユーザーからの入力を取得します。
query = st.text_input("質問を入力してください:")
# 入力された質問をベクトル化します。
inputs = qa.tokenizer([query], return_tensors="pt", truncation=True, padding=True)
with torch.no_grad():
query_embedding = model(**inputs).last_hidden_state
# 最も近いベクトルを検索します。
D, I = index.search(query_embedding, 1)
# 最も近いベクトルに対応する回答を取得します。
answer = qa(question=query, context=dataset["train"]["context"][I[0][0]])["answer"]
# 回答を表示します。
st.write(answer)
```
このコードは、質問応答モデルを使用してユーザーからの質問を処理し、最も近いベクトルに対応する回答を返すシンプルなチャットボットを実装しています。ただし、このコードは非常に単純なものです。実際のアプリケーションでは、データの事前処理、モデルの調整、ユーザーインターフェースの改善など、多くの要素を考慮する必要があります。
============================================================
実行前メモリ使用量 : 646.44 MB
モデル使用中メモリ使用量 : 4143.16 MB
解放後メモリ使用量 : 101.20 MB
モデル使用中の増加量 : 3496.73 MB
実行時間 : 87.121 秒
In [ ]: