File size: 1,701 Bytes
bea1214
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
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()