Views
No views yet
ollama run huihui_ai/hy-mt1.5-abliteratedtransformers library:1from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig, TextStreamer
2import torch
3import os
4import signal
5import random
6import numpy as np
7import time
8from collections import Counter
9
10cpu_count = os.cpu_count()
11print(f"Number of CPU cores in the system: {cpu_count}")
12half_cpu_count = cpu_count // 2
13os.environ["MKL_NUM_THREADS"] = str(half_cpu_count)
14os.environ["OMP_NUM_THREADS"] = str(half_cpu_count)
15torch.set_num_threads(half_cpu_count)
16
17print(f"PyTorch threads: {torch.get_num_threads()}")
18print(f"MKL threads: {os.getenv('MKL_NUM_THREADS')}")
19print(f"OMP threads: {os.getenv('OMP_NUM_THREADS')}")
20
21# Load the model and tokenizer
22NEW_MODEL_ID = "huihui-ai/Huihui-HY-MT1.5-7B-abliterated"
23print(f"Load Model {NEW_MODEL_ID} ... ")
24quant_config_4 = BitsAndBytesConfig(
25 load_in_4bit=True,
26 bnb_4bit_compute_dtype=torch.bfloat16,
27 bnb_4bit_use_double_quant=True,
28 llm_int8_enable_fp32_cpu_offload=True,
29)
30
31model = AutoModelForCausalLM.from_pretrained(
32 NEW_MODEL_ID,
33 device_map="balanced",
34 trust_remote_code=True,
35 #quantization_config=quant_config_4,
36 torch_dtype=torch.bfloat16,
37 low_cpu_mem_usage=True,
38)
39#print(model)
40#print(model.config)
41
42tokenizer = AutoTokenizer.from_pretrained(NEW_MODEL_ID, trust_remote_code=True)
43
44messages = []
45skip_prompt=True
46skip_special_tokens=True
47
48class CustomTextStreamer(TextStreamer):
49 def __init__(self, tokenizer, skip_prompt=True, skip_special_tokens=True):
50 super().__init__(tokenizer, skip_prompt=skip_prompt, skip_special_tokens=skip_special_tokens)
51 self.generated_text = ""
52 self.stop_flag = False
53 self.init_time = time.time() # Record initialization time
54 self.end_time = None # To store end time
55 self.first_token_time = None # To store first token generation time
56 self.token_count = 0 # To track total tokens
57
58 def on_finalized_text(self, text: str, stream_end: bool = False):
59 if self.first_token_time is None and text.strip(): # Set first token time on first non-empty text
60 self.first_token_time = time.time()
61 self.generated_text += text
62 # Count tokens in the generated text
63 self.token_count += 1
64 print(text, end="", flush=True)
65 if stream_end:
66 self.end_time = time.time() # Record end time when streaming ends
67 if self.stop_flag:
68 raise StopIteration
69
70 def stop_generation(self):
71 self.stop_flag = True
72 self.end_time = time.time() # Record end time when generation is stopped
73
74 def get_metrics(self):
75 """Returns initialization time, first token time, first token latency, end time, total time, total tokens, and tokens per second."""
76 if self.end_time is None:
77 self.end_time = time.time() # Set end time if not already set
78 total_time = self.end_time - self.init_time # Total time from init to end
79 tokens_per_second = self.token_count / total_time if total_time > 0 else 0
80 first_token_latency = (self.first_token_time - self.init_time) if self.first_token_time is not None else None
81 metrics = {
82 "init_time": self.init_time,
83 "first_token_time": self.first_token_time,
84 "first_token_latency": first_token_latency,
85 "end_time": self.end_time,
86 "total_time": total_time, # Total time in seconds
87 "total_tokens": self.token_count,
88 "tokens_per_second": tokens_per_second
89 }
90 return metrics
91
92def generate_stream(model, tokenizer, messages, skip_prompt, skip_special_tokens, max_new_tokens):
93 input_ids = tokenizer.apply_chat_template(
94 messages,
95 tokenize=True,
96 add_generation_prompt=False,
97 return_tensors="pt"
98 )
99
100 attention_mask = torch.ones_like(input_ids, dtype=torch.long)
101
102 tokens = input_ids.to(model.device)
103 attention_mask = attention_mask.to(model.device)
104
105 streamer = CustomTextStreamer(tokenizer, skip_prompt=skip_prompt, skip_special_tokens=skip_special_tokens)
106
107 def signal_handler(sig, frame):
108 streamer.stop_generation()
109 print("\n[Generation stopped by user with Ctrl+C]")
110
111 signal.signal(signal.SIGINT, signal_handler)
112
113 print("Response: ", end="", flush=True)
114 try:
115 generated_ids = model.generate(
116 tokens,
117 attention_mask=attention_mask,
118 use_cache=True,
119 max_new_tokens=max_new_tokens,
120 do_sample=True,
121 #pad_token_id=tokenizer.pad_token_id,
122 streamer=streamer
123 )
124 del generated_ids
125 except StopIteration:
126 print("\n[Stopped by user]")
127
128 del input_ids, attention_mask, tokens
129 torch.cuda.empty_cache()
130 signal.signal(signal.SIGINT, signal.SIG_DFL)
131
132 return streamer.generated_text, streamer.stop_flag, streamer.get_metrics()
133
134while True:
135 print(f"skip_prompt: {skip_prompt}")
136 print(f"skip_special_tokens: {skip_special_tokens}")
137
138 user_input = input("User: ")
139
140 if user_input.lower() == "/exit":
141 print("Exiting chat.")
142 break
143 if user_input.lower() == "/clear":
144 messages = []
145 print("Chat history cleared. Starting a new conversation.")
146 continue
147 if user_input.lower() == "/skip_prompt":
148 skip_prompt = not skip_prompt
149 continue
150 if user_input.lower() == "/skip_special_tokens":
151 skip_special_tokens = not skip_special_tokens
152 continue
153 if not user_input:
154 print("Input cannot be empty. Please enter something.")
155 continue
156
157
158 messages.append({"role": "user", "content": user_input})
159 activated_experts = []
160 response, stop_flag, metrics = generate_stream(model, tokenizer, messages, skip_prompt, skip_special_tokens, 40960)
161 print("\n\nMetrics:")
162 for key, value in metrics.items():
163 print(f" {key}: {value}")
164
165 print("", flush=True)
166 if stop_flag:
167 continue
168 messages.append({"role": "assistant", "content": response})
169
170 bc1qqnkhuchxw0zqjh2ku3lu4hq45hc6gy84uk70ge