#!/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\n\n\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()