Upload chatbot.py with huggingface_hub
Browse files- chatbot.py +120 -0
chatbot.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Interactive Streaming Chatbot for Qwen3.5-0.8B (Refusal-Ablated / Orthogonalized)
|
| 4 |
+
Repository: jayesh20/swapper
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import os
|
| 8 |
+
import sys
|
| 9 |
+
import warnings
|
| 10 |
+
|
| 11 |
+
# Suppress PyTorch compile/redirect warnings on macOS
|
| 12 |
+
os.environ["HF_DEACTIVATE_ASYNC_LOAD"] = "1"
|
| 13 |
+
os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
| 14 |
+
warnings.filterwarnings("ignore")
|
| 15 |
+
|
| 16 |
+
import torch
|
| 17 |
+
from transformers import AutoProcessor, AutoModelForMultimodalLM, TextStreamer
|
| 18 |
+
|
| 19 |
+
# Default to current directory if model.safetensors exists here, else HuggingFace repo
|
| 20 |
+
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
|
| 21 |
+
if len(sys.argv) > 1:
|
| 22 |
+
MODEL_PATH = sys.argv[1]
|
| 23 |
+
elif os.path.exists(os.path.join(CURRENT_DIR, "model.safetensors")):
|
| 24 |
+
MODEL_PATH = CURRENT_DIR
|
| 25 |
+
elif os.path.exists(os.path.join(CURRENT_DIR, "Qwen3.5-0.8B-orthogonalized")):
|
| 26 |
+
MODEL_PATH = os.path.join(CURRENT_DIR, "Qwen3.5-0.8B-orthogonalized")
|
| 27 |
+
else:
|
| 28 |
+
MODEL_PATH = "jayesh20/swapper"
|
| 29 |
+
|
| 30 |
+
def main():
|
| 31 |
+
print("=" * 60)
|
| 32 |
+
print(f"Loading Swapper ({MODEL_PATH})...")
|
| 33 |
+
print("=" * 60)
|
| 34 |
+
|
| 35 |
+
device = "mps" if torch.backends.mps.is_available() else ("cuda" if torch.cuda.is_available() else "cpu")
|
| 36 |
+
print(f"Using device: {device}")
|
| 37 |
+
|
| 38 |
+
try:
|
| 39 |
+
processor = AutoProcessor.from_pretrained(MODEL_PATH)
|
| 40 |
+
except Exception:
|
| 41 |
+
processor = AutoProcessor.from_pretrained("Qwen/Qwen3.5-0.8B")
|
| 42 |
+
|
| 43 |
+
model = AutoModelForMultimodalLM.from_pretrained(
|
| 44 |
+
MODEL_PATH,
|
| 45 |
+
dtype=torch.float32,
|
| 46 |
+
device_map="auto"
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
streamer = TextStreamer(processor.tokenizer, skip_prompt=True, skip_special_tokens=True)
|
| 50 |
+
|
| 51 |
+
print("\n" + "=" * 60)
|
| 52 |
+
print("Chatbot Ready! Type your message and press Enter.")
|
| 53 |
+
print("Commands:")
|
| 54 |
+
print(" 'exit' or 'quit' -> Close chatbot")
|
| 55 |
+
print(" 'clear' -> Reset conversation memory")
|
| 56 |
+
print("=" * 60 + "\n")
|
| 57 |
+
|
| 58 |
+
messages = []
|
| 59 |
+
|
| 60 |
+
while True:
|
| 61 |
+
try:
|
| 62 |
+
user_input = input("\nYou: ").strip()
|
| 63 |
+
except (KeyboardInterrupt, EOFError):
|
| 64 |
+
print("\nGoodbye!")
|
| 65 |
+
break
|
| 66 |
+
|
| 67 |
+
if not user_input:
|
| 68 |
+
continue
|
| 69 |
+
|
| 70 |
+
if user_input.lower() in ("exit", "quit", "q"):
|
| 71 |
+
print("Goodbye!")
|
| 72 |
+
break
|
| 73 |
+
|
| 74 |
+
if user_input.lower() == "clear":
|
| 75 |
+
messages = []
|
| 76 |
+
print("Conversation memory cleared.")
|
| 77 |
+
continue
|
| 78 |
+
|
| 79 |
+
messages.append({
|
| 80 |
+
"role": "user",
|
| 81 |
+
"content": [{"type": "text", "text": user_input}]
|
| 82 |
+
})
|
| 83 |
+
|
| 84 |
+
try:
|
| 85 |
+
inputs = processor.apply_chat_template(
|
| 86 |
+
messages,
|
| 87 |
+
add_generation_prompt=True,
|
| 88 |
+
tokenize=True,
|
| 89 |
+
return_dict=True,
|
| 90 |
+
return_tensors="pt",
|
| 91 |
+
).to(model.device)
|
| 92 |
+
except Exception:
|
| 93 |
+
# Fallback direct formatting
|
| 94 |
+
prompt_text = f"<|im_start|>user\n{user_input}<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n"
|
| 95 |
+
inputs = processor.tokenizer(prompt_text, return_tensors="pt").to(model.device)
|
| 96 |
+
|
| 97 |
+
print("\nSwapper: ", end="", flush=True)
|
| 98 |
+
|
| 99 |
+
input_token_len = inputs["input_ids"].shape[-1]
|
| 100 |
+
with torch.no_grad():
|
| 101 |
+
outputs = model.generate(
|
| 102 |
+
**inputs,
|
| 103 |
+
max_new_tokens=4096,
|
| 104 |
+
streamer=streamer,
|
| 105 |
+
do_sample=True,
|
| 106 |
+
temperature=0.7,
|
| 107 |
+
top_p=0.9,
|
| 108 |
+
pad_token_id=processor.tokenizer.pad_token_id,
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
# Decode assistant reply for conversation history
|
| 112 |
+
reply = processor.decode(outputs[0][input_token_len:], skip_special_tokens=True).strip()
|
| 113 |
+
|
| 114 |
+
messages.append({
|
| 115 |
+
"role": "assistant",
|
| 116 |
+
"content": [{"type": "text", "text": reply}]
|
| 117 |
+
})
|
| 118 |
+
|
| 119 |
+
if __name__ == "__main__":
|
| 120 |
+
main()
|