File size: 3,764 Bytes
c21d893
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
#!/usr/bin/env python3
"""
Interactive Streaming Chatbot for Qwen3.5-0.8B (Refusal-Ablated / Orthogonalized)
Repository: jayesh20/swapper
"""

import os
import sys
import warnings

# Suppress PyTorch compile/redirect warnings on macOS
os.environ["HF_DEACTIVATE_ASYNC_LOAD"] = "1"
os.environ["TOKENIZERS_PARALLELISM"] = "false"
warnings.filterwarnings("ignore")

import torch
from transformers import AutoProcessor, AutoModelForMultimodalLM, TextStreamer

# Default to current directory if model.safetensors exists here, else HuggingFace repo
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
if len(sys.argv) > 1:
    MODEL_PATH = sys.argv[1]
elif os.path.exists(os.path.join(CURRENT_DIR, "model.safetensors")):
    MODEL_PATH = CURRENT_DIR
elif os.path.exists(os.path.join(CURRENT_DIR, "Qwen3.5-0.8B-orthogonalized")):
    MODEL_PATH = os.path.join(CURRENT_DIR, "Qwen3.5-0.8B-orthogonalized")
else:
    MODEL_PATH = "jayesh20/swapper"

def main():
    print("=" * 60)
    print(f"Loading Swapper ({MODEL_PATH})...")
    print("=" * 60)

    device = "mps" if torch.backends.mps.is_available() else ("cuda" if torch.cuda.is_available() else "cpu")
    print(f"Using device: {device}")

    try:
        processor = AutoProcessor.from_pretrained(MODEL_PATH)
    except Exception:
        processor = AutoProcessor.from_pretrained("Qwen/Qwen3.5-0.8B")

    model = AutoModelForMultimodalLM.from_pretrained(
        MODEL_PATH,
        dtype=torch.float32,
        device_map="auto"
    )

    streamer = TextStreamer(processor.tokenizer, skip_prompt=True, skip_special_tokens=True)

    print("\n" + "=" * 60)
    print("Chatbot Ready! Type your message and press Enter.")
    print("Commands:")
    print("  'exit' or 'quit' -> Close chatbot")
    print("  'clear'          -> Reset conversation memory")
    print("=" * 60 + "\n")

    messages = []

    while True:
        try:
            user_input = input("\nYou: ").strip()
        except (KeyboardInterrupt, EOFError):
            print("\nGoodbye!")
            break

        if not user_input:
            continue

        if user_input.lower() in ("exit", "quit", "q"):
            print("Goodbye!")
            break

        if user_input.lower() == "clear":
            messages = []
            print("Conversation memory cleared.")
            continue

        messages.append({
            "role": "user",
            "content": [{"type": "text", "text": user_input}]
        })

        try:
            inputs = processor.apply_chat_template(
                messages,
                add_generation_prompt=True,
                tokenize=True,
                return_dict=True,
                return_tensors="pt",
            ).to(model.device)
        except Exception:
            # Fallback direct formatting
            prompt_text = f"<|im_start|>user\n{user_input}<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n"
            inputs = processor.tokenizer(prompt_text, return_tensors="pt").to(model.device)

        print("\nSwapper: ", end="", flush=True)

        input_token_len = inputs["input_ids"].shape[-1]
        with torch.no_grad():
            outputs = model.generate(
                **inputs,
                max_new_tokens=4096,
                streamer=streamer,
                do_sample=True,
                temperature=0.7,
                top_p=0.9,
                pad_token_id=processor.tokenizer.pad_token_id,
            )

        # Decode assistant reply for conversation history
        reply = processor.decode(outputs[0][input_token_len:], skip_special_tokens=True).strip()

        messages.append({
            "role": "assistant",
            "content": [{"type": "text", "text": reply}]
        })

if __name__ == "__main__":
    main()