Upload chat_light.py with huggingface_hub
Browse files- chat_light.py +42 -0
chat_light.py
ADDED
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
3 |
+
|
4 |
+
# Load a small, fast model
|
5 |
+
model_name = "distilgpt2" # smaller than full GPT-2, uses less memory
|
6 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
7 |
+
model = AutoModelForCausalLM.from_pretrained(model_name)
|
8 |
+
|
9 |
+
conversation = "You are a kind AI assistant. Stay on topic.\n"
|
10 |
+
print("\nType your messages below. Type 'quit' to exit.\n")
|
11 |
+
|
12 |
+
while True:
|
13 |
+
try:
|
14 |
+
user_input = input("You: ")
|
15 |
+
except KeyboardInterrupt:
|
16 |
+
print("\nEnding chat. Bye!")
|
17 |
+
break
|
18 |
+
|
19 |
+
if user_input.lower() in ["quit", "exit"]:
|
20 |
+
print("Ending chat. Bye!")
|
21 |
+
break
|
22 |
+
|
23 |
+
conversation += f"User: {user_input}\nAI:"
|
24 |
+
|
25 |
+
# Tokenize efficiently and limit input size to avoid memory issues
|
26 |
+
inputs = tokenizer(conversation, return_tensors="pt", truncation=True, max_length=512)
|
27 |
+
|
28 |
+
# Generate a short response to save memory and speed
|
29 |
+
output = model.generate(
|
30 |
+
**inputs,
|
31 |
+
max_new_tokens=40, # shorter responses = faster
|
32 |
+
temperature=0.7,
|
33 |
+
do_sample=True,
|
34 |
+
pad_token_id=tokenizer.eos_token_id
|
35 |
+
)
|
36 |
+
|
37 |
+
# Decode and extract AI response
|
38 |
+
ai_response = tokenizer.decode(output[0], skip_special_tokens=True).split("AI:")[-1].strip()
|
39 |
+
print(f"Baby AI: {ai_response}")
|
40 |
+
|
41 |
+
# Add AI response to conversation for context
|
42 |
+
conversation += f"{ai_response}\n"
|