雙語聊天助手教學
在這個教學中,我們將實現一個由 Arcee 的 Meraj-Mini 模型驅動的雙語聊天助手,並在 Google Colab 上使用 T4 GPU 無縫部署。這個教學展示了開源語言模型的能力,同時提供了一個實用的實作經驗,讓我們能在免費的雲資源下部署最先進的人工智慧解決方案。我們將使用一套強大的工具,包括:
- Arcee 的 Meraj-Mini 模型
- Transformers 函式庫用於模型加載和標記化
- Accelerate 和 bitsandbytes 用於高效量化
- PyTorch 用於深度學習計算
- Gradio 用於創建互動式網頁介面
啟用 GPU 加速
!pip install -qU transformers accelerate bitsandbytes
!pip install -q gradio
首先,我們使用 nvidia-smi 命令查詢 GPU 的名稱和總記憶體,以啟用 GPU 加速。接著安裝和更新關鍵的 Python 函式庫,例如 transformers、accelerate、bitsandbytes 和 gradio,以支援機器學習任務和部署互動應用程式。
配置模型
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline, BitsAndBytesConfig
quant_config = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type=”nf4″,
bnb_4bit_compute_dtype=torch.float16,
bnb_4bit_use_double_quant=True
)
model = AutoModelForCausalLM.from_pretrained(
“arcee-ai/Meraj-Mini”,
quantization_config=quant_config,
device_map=”auto”
)
tokenizer = AutoTokenizer.from_pretrained(“arcee-ai/Meraj-Mini”)
然後,我們使用 BitsAndBytesConfig 配置 4 位元量化設置,以高效加載模型,並從 Hugging Face 加載 “arcee-ai/Meraj-Mini” 的因果語言模型及其標記器,自動映射設備以獲得最佳性能。
建立聊天管道
“text-generation”,
model=model,
tokenizer=tokenizer,
max_new_tokens=512,
temperature=0.7,
top_p=0.9,
repetition_penalty=1.1,
do_sample=True
)
在這裡,我們使用 Hugging Face 的管道函數創建一個專為聊天互動設計的文本生成管道。它配置了最大新標記數、溫度、top_p 和重複懲罰,以平衡文本生成過程中的多樣性和一致性。
定義聊天功能
prompt = “”
for msg in messages:
prompt += f”<|im_start|>msg[‘role’]nmsg[‘content’]<|im_end|>n”
prompt += “<|im_start|>assistantn”
return prompt
def generate_response(user_input, history=[]):
history.append({“role”: “user”, “content”: user_input})
formatted_prompt = format_chat(history)
output = chat_pipeline(formatted_prompt)[0][‘generated_text’]
assistant_response = output.split(“<|im_start|>assistantn”)[-1].split(“<|im_end|>”)[0]
history.append({“role”: “assistant”, “content”: assistant_response})
return assistant_response, history
我們定義了兩個函數來促進對話介面。第一個函數將聊天歷史格式化為結構化的提示,並使用自定義分隔符,第二個函數則附加新的用戶消息,使用文本生成管道生成回應,並相應地更新對話歷史。
建立網頁聊天介面
with gr.Blocks() as demo:
chatbot = gr.Chatbot()
msg = gr.Textbox(label=”Message”)
clear = gr.Button(“Clear History”)
def respond(message, chat_history):
response, _ = generate_response(message, chat_history.copy())
return response, chat_history + [(message, response)]
msg.submit(respond, [msg, chatbot], [msg, chatbot])
clear.click(lambda: None, None, chatbot, queue=False)
demo.launch(share=True)
最後,我們使用 Gradio 建立了一個基於網頁的聊天機器人介面。它創建了聊天歷史、消息輸入和清除歷史按鈕的 UI 元素,並定義了一個回應函數,與文本生成管道整合以更新對話。最後,啟動演示並啟用共享,以便公眾訪問。
這裡是 Colab 筆記本。別忘了在 Twitter 上關注我們,加入我們的 Telegram 頻道和 LinkedIn 群組。還有,記得加入我們的 80k+ ML SubReddit。
本文由 AI 台灣 運用 AI 技術編撰,內容僅供參考,請自行核實相關資訊。
歡迎加入我們的 AI TAIWAN 台灣人工智慧中心 FB 社團,
隨時掌握最新 AI 動態與實用資訊!