swapper / chat.py
jayesh20's picture
Upload chat.py with huggingface_hub
bea1214 verified
Raw History Blame Contribute Delete
1.7 kB
import torch
from transformers import AutoProcessor, AutoModelForMultimodalLM, TextStreamer
# 1. Load model & processor
SAVE_DIR = "Qwen3.5-0.8B-heretic"
processor = AutoProcessor.from_pretrained(SAVE_DIR)
model = AutoModelForMultimodalLM.from_pretrained(SAVE_DIR, torch_dtype=torch.float32, device_map="auto")
streamer = TextStreamer(processor.tokenizer, skip_prompt=True, skip_special_tokens=True)
# 2. Interactive Loop with Memory
messages = []
print("Chatbot started! Type 'exit' to quit or 'clear' to reset memory.\n")
while True:
user_msg = input("You: ").strip()
if not user_msg or user_msg.lower() in ("exit", "quit"):
print("Chat ended.")
break
if user_msg.lower() == "clear":
messages = []
print("[Memory cleared]\n")
continue
# Append user turn
messages.append({"role": "user", "content": [{"type": "text", "text": user_msg}]})
# Prepare input with full conversation history
inputs = processor.apply_chat_template(
messages, add_generation_prompt=True, tokenize=True,
return_dict=True, return_tensors="pt"
).to(model.device)
print("\nAssistant: ", end="")
with torch.no_grad():
out = model.generate(
**inputs,
max_new_tokens=4096, # Model finishes naturally on its own
streamer=streamer,
do_sample=True,
temperature=0.7,
top_p=0.9
)
# Store assistant response back into conversation history
reply = processor.decode(out[0][inputs["input_ids"].shape[-1]:], skip_special_tokens=True).strip()
messages.append({"role": "assistant", "content": [{"type": "text", "text": reply}]})
print()