File size: 8,066 Bytes
5a07453 | 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 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 | import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, StoppingCriteria, StoppingCriteriaList
# Settings
MODEL_PATH = "DrontChat-200m" # path to local model
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
TEMPERATURE = 0.3
MAX_NEW_TOKENS = 256
TOP_P = 0.90
TOP_K = 50
class StopOnTokens(StoppingCriteria):
"""Class to stop generation when encountering stop tokens"""
def __init__(self, stop_token_ids):
self.stop_token_ids = set(stop_token_ids)
def __call__(self, input_ids, scores, **kwargs):
# Check the last generated token
if input_ids.shape[-1] > 0:
last_token = input_ids[0, -1].item()
if last_token in self.stop_token_ids:
return True
return False
class LocalChatBot:
def __init__(self, model_path):
print(f"Loading model from {model_path}...")
# Load tokenizer and model
self.tokenizer = AutoTokenizer.from_pretrained(
model_path,
trust_remote_code=True,
padding_side="left"
)
# Define special tokens
special_tokens = {
"pad_token": "<|endoftext|>",
"eos_token": "<|endoftext|>",
"sep_token": "<|endoftext|>",
"additional_special_tokens": ["<|user|>", "<|assistant|>", "<system>", "</system>"]
}
# Add special tokens
self.tokenizer.add_special_tokens(special_tokens)
self.model = AutoModelForCausalLM.from_pretrained(
model_path,
torch_dtype=torch.float16 if DEVICE == "cuda" else torch.float32,
device_map="auto",
trust_remote_code=True,
low_cpu_mem_usage=True
)
# If new tokens were added, resize embeddings
if len(self.tokenizer) > self.model.config.vocab_size:
self.model.resize_token_embeddings(len(self.tokenizer))
self.model.eval()
# Get stop token IDs
self.stop_token_ids = self._get_stop_token_ids()
if DEVICE == "cuda":
print(f"Model loaded on GPU: {torch.cuda.get_device_name()}")
else:
print("WARNING: CUDA not available, using CPU!")
def _get_stop_token_ids(self):
"""Get IDs of all stop tokens"""
stop_tokens = [
"<|endoftext|>",
"<|user|>", # Stop if model starts generating for user
"<|assistant|>", # Stop if model generates new response
"<system>", # Stop if model starts new system prompt
]
stop_ids = []
for token in stop_tokens:
token_id = self.tokenizer.convert_tokens_to_ids(token)
if token_id is not None and token_id != -1:
stop_ids.append(token_id)
print(f"Stop token '{token}' -> ID: {token_id}")
else:
print(f"Warning: token '{token}' not found in tokenizer")
return stop_ids
def format_prompt(self, system_message, user_input, history=[]):
"""Format prompt with conversation history"""
prompt = f"<system>{system_message}</system>"
# Add conversation history
for user_msg, assistant_msg in history:
prompt += f"<|user|>{user_msg}<|endoftext|>"
prompt += f"<|assistant|>{assistant_msg}<|endoftext|>"
# Add current message
prompt += f"<|user|>{user_input}<|endoftext|>"
prompt += "<|assistant|>"
return prompt
def generate_response(self, prompt):
"""Generate model response with proper stopping"""
inputs = self.tokenizer.encode(
prompt,
return_tensors="pt",
truncation=True,
max_length=2048,
add_special_tokens=False
).to(DEVICE)
# Create stopping criteria
stopping_criteria = StoppingCriteriaList([StopOnTokens(self.stop_token_ids)])
with torch.no_grad():
outputs = self.model.generate(
inputs,
max_new_tokens=MAX_NEW_TOKENS,
temperature=TEMPERATURE,
do_sample=True if TEMPERATURE > 0 else False,
top_p=TOP_P,
top_k=TOP_K,
pad_token_id=self.tokenizer.pad_token_id,
eos_token_id=self.tokenizer.eos_token_id,
repetition_penalty=1.1,
num_return_sequences=1,
stopping_criteria=stopping_criteria, # Add stopping criteria
)
# Decode only new tokens
response = self.tokenizer.decode(
outputs[0][inputs.shape[1]:],
skip_special_tokens=True
).strip()
# Additional cleanup from possible markers
response = self._clean_response(response)
return response
def _clean_response(self, response):
"""Clean response from service tokens"""
# List of markers for cleanup
markers = [
"<|endoftext|>",
"<|user|>",
"<|assistant|>",
"<system>",
"</system>"
]
for marker in markers:
if marker in response:
response = response.split(marker)[0].strip()
return response
def chat(self):
"""Interactive chat"""
print("\n" + "=" * 50)
print("Local chat bot started!")
print(f"Temperature: {TEMPERATURE}")
print(f"Device: {DEVICE}")
print("Commands: 'clear' - clear history, 'exit' - exit")
print("=" * 50 + "\n")
system_message = "You are a AI, you can smol talk, you have name DrontAI."
history = []
while True:
try:
user_input = input("You: ").strip()
if not user_input:
continue
if user_input.lower() == 'exit':
print("Goodbye!")
break
if user_input.lower() == 'clear':
history = []
print("Conversation history cleared.")
continue
if user_input.lower().startswith('system:'):
system_message = user_input[7:].strip()
print(f"System message updated: {system_message}")
continue
# Format prompt
prompt = self.format_prompt(system_message, user_input, history)
# Generate response
response = self.generate_response(prompt)
# Check if response is not empty
if not response:
response = "(empty response)"
# Save to history
history.append((user_input, response))
# Limit history to last 5 exchanges
if len(history) > 5:
history = history[-5:]
print(f"Bot: {response}\n")
except KeyboardInterrupt:
print("\nInterrupted by user.")
break
except Exception as e:
print(f"Error: {e}")
continue
def main():
"""Main function"""
try:
# Check CUDA availability
if torch.cuda.is_available():
print(f"CUDA available: {torch.cuda.get_device_name(0)}")
print(f"GPU Memory: {torch.cuda.get_device_properties(0).total_memory / 1e9:.1f} GB")
# Clear CUDA cache
torch.cuda.empty_cache()
else:
print("CUDA not available. Will use CPU (slow).")
# Create and run bot
bot = LocalChatBot(MODEL_PATH)
bot.chat()
except Exception as e:
print(f"Critical error: {e}")
import traceback
traceback.print_exc()
if __name__ == "__main__":
main() |