Allen Poston commited on
Commit
345e05b
·
verified ·
1 Parent(s): 7a70792

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +470 -15
README.md CHANGED
@@ -17,26 +17,481 @@ inference:
17
  do_sample: true
18
  ---
19
 
 
20
 
21
- # EnterNameBros/mistral-anime-ai
 
 
 
 
22
 
23
- A conversational fine-tuned Mistral model designed for anime-style dialogue and character interaction.
 
 
 
 
 
24
 
25
- ## 🗨️ Chat Usage (OpenAI-compatible)
 
 
 
 
 
 
26
 
27
- Supports OpenAI-style usage via:
 
 
 
 
28
 
29
- ```python
30
- from openai import OpenAI
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
 
32
- client = OpenAI(base_url="https://your-endpoint.com/v1", api_key="your-key")
 
 
 
 
 
 
33
 
34
- response = client.chat.completions.create(
35
- model="EnterNameBros/mistral-anime-ai",
36
- messages=[
37
- {"role": "system", "content": "You are an anime girl who speaks in a cheerful and curious tone."},
38
- {"role": "user", "content": "What's your favorite anime?"},
39
- ]
40
- )
 
 
 
41
 
42
- print(response.choices[0].message.content)
 
 
 
 
 
17
  do_sample: true
18
  ---
19
 
20
+ > Talk to model requires gpu
21
 
22
+ ```python
23
+ import os, torch, gc, threading, time, traceback
24
+ from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig, TextIteratorStreamer
25
+ from queue import Queue, Empty
26
+ import logging
27
 
28
+ os.environ["TOKENIZERS_PARALLELISM"] = "false"
29
+ os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "max_split_size_mb:128"
30
+ torch.backends.cudnn.benchmark = True
31
+ torch.backends.cuda.matmul.allow_tf32 = True
32
+ torch.set_float32_matmul_precision("high")
33
+ logging.getLogger("transformers").setLevel(logging.ERROR)
34
 
35
+ BOT_NAME = "Senko"
36
+ PROMPT_FILE = "instructions_prompt.txt"
37
+ MODEL_ID = "EnterNameBros/mistral-anime-ai"
38
+ RESPONSE_TIMEOUT = 300 # Increased timeout for longer responses
39
+ MAX_CONTEXT_LENGTH = 10240
40
+ MAX_NEW_TOKENS = 8192 # Increased max tokens for longer responses
41
+ MEMORY_SIZE = 20
42
 
43
+ def check_bitsandbytes_version():
44
+ try:
45
+ import bitsandbytes as bnb
46
+ version = bnb.__version__
47
+ print(f"Bitsandbytes version: {version}")
48
 
49
+ version_parts = version.split('.')
50
+ major, minor = int(version_parts[0]), int(version_parts[1])
51
+
52
+ if major > 0 or (major == 0 and minor >= 41):
53
+ return True
54
+ else:
55
+ print(f"Warning: Bitsandbytes {version} may not support 4-bit quantization")
56
+ return False
57
+ except ImportError:
58
+ print("Bitsandbytes not installed")
59
+ return False
60
+ except Exception as e:
61
+ print(f"Error checking bitsandbytes version: {e}")
62
+ return False
63
+
64
+ class OptimizedChatBot:
65
+ def __init__(self):
66
+ self.model = None
67
+ self.tokenizer = None
68
+ self.system_prompt = ""
69
+ self.memory = []
70
+ self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
71
+ self.generation_lock = threading.Lock()
72
+ self.is_generating = False
73
+ self.use_quantization = False
74
+
75
+ def load_system_prompt(self, bot_name, filename=PROMPT_FILE):
76
+ try:
77
+ with open(filename, "r", encoding="utf-8") as f:
78
+ self.system_prompt = f.read().replace("{BOT_NAME}", bot_name)
79
+ print(f"Loaded system prompt from {filename}")
80
+ except FileNotFoundError:
81
+ print(f"Warning: {filename} not found. Using default prompt.")
82
+ self.system_prompt =
83
+ def load_model(self):
84
+ print("Loading model...")
85
+ start_time = time.time()
86
+
87
+ try:
88
+ print("Loading tokenizer...")
89
+ self.tokenizer = AutoTokenizer.from_pretrained(
90
+ MODEL_ID,
91
+ use_fast=True,
92
+ trust_remote_code=True
93
+ )
94
+ self.tokenizer.pad_token = self.tokenizer.pad_token or self.tokenizer.eos_token
95
+ self.tokenizer.padding_side = "left"
96
+ print("Tokenizer loaded successfully")
97
+
98
+ print("Loading model weights...")
99
+ if torch.cuda.is_available():
100
+ print(f"Using GPU: {torch.cuda.get_device_name()}")
101
+ print(f"Available VRAM: {torch.cuda.get_device_properties(0).total_memory / 1024**3:.1f}GB")
102
+
103
+ can_use_4bit = check_bitsandbytes_version()
104
+
105
+ if can_use_4bit:
106
+ print("Using 4-bit quantization")
107
+ config = BitsAndBytesConfig(
108
+ load_in_4bit=True,
109
+ bnb_4bit_compute_dtype=torch.bfloat16,
110
+ bnb_4bit_use_double_quant=True,
111
+ bnb_4bit_quant_type="nf4",
112
+ bnb_4bit_quant_storage=torch.bfloat16
113
+ )
114
+ self.use_quantization = True
115
+ else:
116
+ print("Using 8-bit quantization fallback")
117
+ config = BitsAndBytesConfig(
118
+ load_in_8bit=True,
119
+ llm_int8_threshold=6.0,
120
+ llm_int8_skip_modules=None,
121
+ )
122
+ self.use_quantization = True
123
+
124
+ try:
125
+ attn_impl = "flash_attention_2" if torch.cuda.get_device_capability()[0] >= 8 else "sdpa"
126
+ print(f"Using attention implementation: {attn_impl}")
127
+ except:
128
+ attn_impl = "sdpa"
129
+
130
+ try:
131
+ if self.use_quantization:
132
+ self.model = AutoModelForCausalLM.from_pretrained(
133
+ MODEL_ID,
134
+ device_map="auto",
135
+ torch_dtype=torch.bfloat16,
136
+ quantization_config=config,
137
+ trust_remote_code=True,
138
+ low_cpu_mem_usage=True,
139
+ use_cache=True,
140
+ )
141
+ else:
142
+ raise Exception("Quantization not available")
143
+
144
+ except Exception as quant_error:
145
+ print(f"Quantization failed: {quant_error}")
146
+ print("Falling back to regular fp16 loading...")
147
+ self.model = AutoModelForCausalLM.from_pretrained(
148
+ MODEL_ID,
149
+ device_map="auto",
150
+ torch_dtype=torch.bfloat16,
151
+ trust_remote_code=True,
152
+ low_cpu_mem_usage=True,
153
+ use_cache=True,
154
+ )
155
+ self.use_quantization = False
156
+
157
+ else:
158
+ print("Using CPU (this will be slow)")
159
+ self.model = AutoModelForCausalLM.from_pretrained(
160
+ MODEL_ID,
161
+ device_map="cpu",
162
+ torch_dtype=torch.float32,
163
+ trust_remote_code=True,
164
+ use_cache=True
165
+ )
166
+
167
+ self.model.eval()
168
+
169
+ if False and hasattr(torch, 'compile') and torch.cuda.is_available():
170
+ try:
171
+ print("Compiling model for optimization...")
172
+ self.model = torch.compile(
173
+ self.model,
174
+ mode="reduce-overhead",
175
+ fullgraph=False,
176
+ dynamic=True
177
+ )
178
+ print("Model compilation successful")
179
+ except Exception as e:
180
+ print(f"Model compilation failed (continuing without): {e}")
181
+
182
+ load_time = time.time() - start_time
183
+ print(f"Model loaded successfully in {load_time:.2f}s")
184
+ print(f"Quantization used: {self.use_quantization}")
185
+
186
+ if torch.cuda.is_available():
187
+ memory_used = torch.cuda.memory_allocated() / 1024**3
188
+ print(f"GPU memory used: {memory_used:.2f}GB")
189
+
190
+ except Exception as e:
191
+ print(f"Failed to load model: {e}")
192
+ traceback.print_exc()
193
+ raise
194
+
195
+ def prepare_prompt(self, user_input):
196
+ self.memory.append({"user": user_input, "bot": None})
197
+
198
+ if len(self.memory) > MEMORY_SIZE:
199
+ self.memory = self.memory[-MEMORY_SIZE:]
200
+
201
+ conversation_history = ""
202
+ for turn in self.memory[:-1]:
203
+ if turn["bot"] is not None:
204
+ conversation_history += f"User: {turn['user']}\n{BOT_NAME}: {turn['bot']}\n\n"
205
+
206
+ conversation_history += f"User: {user_input}\n{BOT_NAME}:"
207
+
208
+ full_prompt = f"{self.system_prompt}\n\n{conversation_history}"
209
+
210
+ tokens = self.tokenizer.encode(full_prompt)
211
+ if len(tokens) > MAX_CONTEXT_LENGTH - MAX_NEW_TOKENS:
212
+ print(f"[Truncating context: {len(tokens)} -> ~{MAX_CONTEXT_LENGTH - MAX_NEW_TOKENS} tokens]")
213
+ recent_history = ""
214
+ for turn in self.memory[-3:]:
215
+ if turn["bot"] is not None:
216
+ recent_history += f"User: {turn['user']}\n{BOT_NAME}: {turn['bot']}\n\n"
217
+ recent_history += f"User: {user_input}\n{BOT_NAME}:"
218
+ return f"{self.system_prompt}\n\n{recent_history}"
219
+
220
+ return full_prompt
221
+
222
+ def is_natural_stopping_point(self, text):
223
+ """
224
+ Only stop at very clear natural ending points to allow for longer responses.
225
+ This is much more permissive than the original function.
226
+ """
227
+ if not text or len(text.strip()) < 20:
228
+ return False
229
+
230
+ stripped = text.strip()
231
+
232
+ # Stop if we detect role confusion (user/assistant switching)
233
+ if any(indicator in stripped.lower() for indicator in ["user:", "user ", "\nuser", "human:", "assistant:"]):
234
+ return True
235
+
236
+ # Allow very long responses - only stop if we have clear dialogue markers
237
+ # that suggest the response is complete
238
+ if len(stripped) > 2000: # Only consider stopping after 2000+ characters
239
+ # Look for clear ending patterns
240
+ ending_patterns = [
241
+ "That is all.",
242
+ "The end.",
243
+ "Goodbye.",
244
+ "Farewell.",
245
+ "Until next time.",
246
+ "That concludes",
247
+ "In conclusion",
248
+ ]
249
+
250
+ if any(pattern.lower() in stripped.lower()[-100:] for pattern in ending_patterns):
251
+ return True
252
+
253
+ return False
254
+
255
+ def generate_reply_with_timeout(self, prompt, timeout=RESPONSE_TIMEOUT):
256
+ with self.generation_lock:
257
+ if self.is_generating:
258
+ print("[Already generating, please wait...]")
259
+ return None
260
+
261
+ self.is_generating = True
262
+
263
+ try:
264
+ return self._generate_reply(prompt, timeout)
265
+ finally:
266
+ self.is_generating = False
267
+
268
+ def _generate_reply(self, prompt, timeout):
269
+ try:
270
+ print(f"[Generating response...]")
271
+ inputs = self.tokenizer(
272
+ prompt,
273
+ return_tensors="pt",
274
+ truncation=True,
275
+ max_length=MAX_CONTEXT_LENGTH - MAX_NEW_TOKENS,
276
+ padding=False
277
+ ).to(self.device)
278
+
279
+ streamer = TextIteratorStreamer(
280
+ self.tokenizer,
281
+ skip_special_tokens=True,
282
+ skip_prompt=True,
283
+ timeout=120.0 # Increased timeout for streaming
284
+ )
285
+
286
+ generation_kwargs = {
287
+ **inputs,
288
+ "max_new_tokens": MAX_NEW_TOKENS,
289
+ "do_sample": True,
290
+ "temperature": 0.7,
291
+ "top_p": 0.9,
292
+ "top_k": 50,
293
+ "repetition_penalty": 1.1,
294
+ "pad_token_id": self.tokenizer.eos_token_id,
295
+ "eos_token_id": self.tokenizer.eos_token_id,
296
+ "use_cache": True,
297
+ "streamer": streamer,
298
+ "num_beams": 1,
299
+ "no_repeat_ngram_size": 3,
300
+ "min_length": 0,
301
+ "early_stopping": False,
302
+ "length_penalty": 1.0,
303
+ "num_return_sequences": 1,
304
+ "diversity_penalty": 0.0,
305
+ "stop_sequences": [],
306
+ "forced_eos_token_id": None,
307
+ "num_beam_groups": 1,
308
+ }
309
+
310
+ generation_thread = threading.Thread(
311
+ target=self._run_generation,
312
+ args=(generation_kwargs,)
313
+ )
314
+ generation_thread.daemon = True
315
+ generation_thread.start()
316
+
317
+ print(f"{BOT_NAME}: ", end="", flush=True)
318
+ full_response = ""
319
+ start_time = time.time()
320
+ last_token_time = start_time
321
+
322
+ while True:
323
+ current_time = time.time()
324
+
325
+ # Extended timeout for long responses
326
+ if current_time - start_time > timeout:
327
+ print(f"\n[Generation timeout after {timeout}s]")
328
+ break
329
+
330
+ # Increased patience for token generation
331
+ if current_time - last_token_time > 60.0: # Wait up to 60s for next token
332
+ print(f"\n[No new tokens for 60s, stopping]")
333
+ break
334
+
335
+ try:
336
+ token = next(streamer)
337
+ print(token, end="", flush=True)
338
+ full_response += token
339
+ last_token_time = current_time
340
+
341
+ # Only check for stopping at natural points, not arbitrary length limits
342
+ if len(full_response.strip()) > 100: # Minimum response length
343
+ if self.is_natural_stopping_point(full_response.strip()):
344
+ break
345
+
346
+ except StopIteration:
347
+ print(f"\n[Generation completed naturally]")
348
+ break
349
+ except Empty:
350
+ time.sleep(0.1)
351
+ continue
352
+ except Exception as e:
353
+ print(f"\n[Streaming error: {e}]")
354
+ break
355
+
356
+ generation_thread.join(timeout=15.0)
357
+
358
+ response = full_response.strip()
359
+
360
+ # Clean up any role confusion but preserve the response content
361
+ lines = response.split('\n')
362
+ clean_lines = []
363
+ for line in lines:
364
+ line = line.strip()
365
+ # Remove lines that start with role indicators
366
+ if any(line.lower().startswith(indicator) for indicator in ["user:", "user ", "human:", "assistant:", f"{BOT_NAME.lower()}:"]):
367
+ continue
368
+ if line:
369
+ clean_lines.append(line)
370
+
371
+ response = '\n'.join(clean_lines).strip()
372
+
373
+ if response:
374
+ if self.memory and self.memory[-1]["bot"] is None:
375
+ self.memory[-1]["bot"] = response
376
+ print(f"\n[Response length: {len(response)} characters]")
377
+ return response
378
+ else:
379
+ print(f"\n[Empty response generated]")
380
+ return None
381
+
382
+ except Exception as e:
383
+ print(f"\n[Generation error: {e}]")
384
+ traceback.print_exc()
385
+ return None
386
+ finally:
387
+ if torch.cuda.is_available():
388
+ torch.cuda.empty_cache()
389
+
390
+ def _run_generation(self, kwargs):
391
+ try:
392
+ torch.set_grad_enabled(False)
393
+ if torch.cuda.is_available():
394
+ with torch.amp.autocast(device_type="cuda", dtype=torch.bfloat16):
395
+ self.model.generate(**kwargs)
396
+ else:
397
+ self.model.generate(**kwargs)
398
+ except Exception as e:
399
+ print(f"\n[Generation thread error: {e}]")
400
+
401
+ def cleanup_memory(self):
402
+ if torch.cuda.is_available():
403
+ torch.cuda.empty_cache()
404
+ torch.cuda.synchronize()
405
+ gc.collect()
406
+
407
+ def get_memory_info(self):
408
+ if torch.cuda.is_available():
409
+ allocated = torch.cuda.memory_allocated() / 1024**3
410
+ cached = torch.cuda.memory_reserved() / 1024**3
411
+ return f"GPU Memory - Allocated: {allocated:.2f}GB, Cached: {cached:.2f}GB"
412
+ else:
413
+ import psutil
414
+ memory = psutil.virtual_memory()
415
+ return f"RAM Usage: {memory.percent}% ({memory.used / 1024**3:.2f}GB used)"
416
+
417
+ def main():
418
+ bot = OptimizedChatBot()
419
+
420
+ try:
421
+ print("Initializing chatbot...")
422
+ bot.load_system_prompt(BOT_NAME)
423
+ bot.load_model()
424
+
425
+ print(f"\n{'='*50}")
426
+ print(f"{BOT_NAME} is ready! (Unlimited response length)")
427
+ print("Commands:")
428
+ print(" 'exit' - Quit the program")
429
+ print(" 'clear' - Reset conversation memory")
430
+ print(" 'memory' - Show memory usage")
431
+ print(" 'status' - Show bot status")
432
+ print(f"{'='*50}\n")
433
+
434
+ conversation_count = 0
435
+
436
+ while True:
437
+ try:
438
+ user_input = input("You: ").strip()
439
+
440
+ if user_input.lower() == "exit":
441
+ print("Goodbye! 👋")
442
+ break
443
+ elif user_input.lower() == "clear":
444
+ bot.memory = []
445
+ print("✅ Conversation memory cleared.")
446
+ continue
447
+ elif user_input.lower() == "memory":
448
+ print(f"📊 {bot.get_memory_info()}")
449
+ continue
450
+ elif user_input.lower() == "status":
451
+ status = "🟢 Ready" if not bot.is_generating else "🟡 Generating"
452
+ print(f"Status: {status}")
453
+ print(f"Conversation turns: {len([t for t in bot.memory if t['bot'] is not None])}")
454
+ continue
455
+ elif not user_input:
456
+ continue
457
+
458
+ start_time = time.time()
459
+ prompt = bot.prepare_prompt(user_input)
460
+ response = bot.generate_reply_with_timeout(prompt)
461
+
462
+ if response:
463
+ response_time = time.time() - start_time
464
+ print(f"[⏱️ {response_time:.2f}s]")
465
+ else:
466
+ print("❌ Failed to generate response. Try again or type 'clear' to reset.")
467
+
468
+ conversation_count += 1
469
+
470
+ if conversation_count % 10 == 0:
471
+ print("[🧹 Cleaning up memory...]")
472
+ bot.cleanup_memory()
473
 
474
+ except KeyboardInterrupt:
475
+ print("\n\n⚠️ Interrupted by user. Exiting gracefully...")
476
+ break
477
+ except Exception as e:
478
+ print(f"\n❌ Conversation error: {e}")
479
+ traceback.print_exc()
480
+ print("Continuing... (type 'exit' to quit)")
481
 
482
+ except Exception as e:
483
+ print(f"💥 Startup error: {e}")
484
+ traceback.print_exc()
485
+ finally:
486
+ print("\n🧹 Performing final cleanup...")
487
+ if torch.cuda.is_available():
488
+ torch.cuda.empty_cache()
489
+ torch.cuda.synchronize()
490
+ gc.collect()
491
+ print("✅ Cleanup completed. Goodbye!")
492
 
493
+ if __name__ == "__main__":
494
+ torch.cuda.empty_cache()
495
+ import gc
496
+ gc.collect()
497
+ main()```