Upload chat.py with huggingface_hub
Browse files
chat.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from transformers import AutoProcessor, AutoModelForMultimodalLM, TextStreamer
|
| 3 |
+
|
| 4 |
+
# 1. Load model & processor
|
| 5 |
+
SAVE_DIR = "Qwen3.5-0.8B-heretic"
|
| 6 |
+
processor = AutoProcessor.from_pretrained(SAVE_DIR)
|
| 7 |
+
model = AutoModelForMultimodalLM.from_pretrained(SAVE_DIR, torch_dtype=torch.float32, device_map="auto")
|
| 8 |
+
streamer = TextStreamer(processor.tokenizer, skip_prompt=True, skip_special_tokens=True)
|
| 9 |
+
|
| 10 |
+
# 2. Interactive Loop with Memory
|
| 11 |
+
messages = []
|
| 12 |
+
print("Chatbot started! Type 'exit' to quit or 'clear' to reset memory.\n")
|
| 13 |
+
|
| 14 |
+
while True:
|
| 15 |
+
user_msg = input("You: ").strip()
|
| 16 |
+
if not user_msg or user_msg.lower() in ("exit", "quit"):
|
| 17 |
+
print("Chat ended.")
|
| 18 |
+
break
|
| 19 |
+
if user_msg.lower() == "clear":
|
| 20 |
+
messages = []
|
| 21 |
+
print("[Memory cleared]\n")
|
| 22 |
+
continue
|
| 23 |
+
|
| 24 |
+
# Append user turn
|
| 25 |
+
messages.append({"role": "user", "content": [{"type": "text", "text": user_msg}]})
|
| 26 |
+
|
| 27 |
+
# Prepare input with full conversation history
|
| 28 |
+
inputs = processor.apply_chat_template(
|
| 29 |
+
messages, add_generation_prompt=True, tokenize=True,
|
| 30 |
+
return_dict=True, return_tensors="pt"
|
| 31 |
+
).to(model.device)
|
| 32 |
+
|
| 33 |
+
print("\nAssistant: ", end="")
|
| 34 |
+
with torch.no_grad():
|
| 35 |
+
out = model.generate(
|
| 36 |
+
**inputs,
|
| 37 |
+
max_new_tokens=4096, # Model finishes naturally on its own
|
| 38 |
+
streamer=streamer,
|
| 39 |
+
do_sample=True,
|
| 40 |
+
temperature=0.7,
|
| 41 |
+
top_p=0.9
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
# Store assistant response back into conversation history
|
| 45 |
+
reply = processor.decode(out[0][inputs["input_ids"].shape[-1]:], skip_special_tokens=True).strip()
|
| 46 |
+
messages.append({"role": "assistant", "content": [{"type": "text", "text": reply}]})
|
| 47 |
+
print()
|