Views
No views yet
ollama run huihui_ai/mirothinker1-abliteratedtransformers library:1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3
4import argparse
5from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig, TextStreamer
6import torch
7import os
8import signal
9import time
10
11def parse_args():
12 parser = argparse.ArgumentParser(
13 description="Load HuggingFace model."
14 )
15 parser.add_argument(
16 "--base_model",
17 type=str,
18 default="huihui-ai/Huihui-MiroThinker-v1.0-8B-abliterated",
19 help="HuggingFace repo or local path of the base model.",
20 )
21 parser.add_argument(
22 "--dtype",
23 type=str,
24 default="bfloat16",
25 choices=["float16", "bfloat16", "float32"],
26 help="Data type for loading the base model (default: bfloat16).",
27 )
28 parser.add_argument(
29 "--device_map",
30 type=str,
31 default="auto",
32 help="Device map for model loading (e.g. 'cpu', 'auto').",
33 )
34 return parser.parse_args()
35
36def main():
37 cpu_count = os.cpu_count()
38 print(f"Number of CPU cores in the system: {cpu_count}")
39 half_cpu_count = cpu_count // 2
40 os.environ["MKL_NUM_THREADS"] = str(half_cpu_count)
41 os.environ["OMP_NUM_THREADS"] = str(half_cpu_count)
42 torch.set_num_threads(half_cpu_count)
43
44 print(f"PyTorch threads: {torch.get_num_threads()}")
45 print(f"MKL threads: {os.getenv('MKL_NUM_THREADS')}")
46 print(f"OMP threads: {os.getenv('OMP_NUM_THREADS')}")
47
48 args = parse_args()
49
50 # Load the model and tokenizer
51 print(f"Load Model {args.base_model} ... ")
52 quant_config_4 = BitsAndBytesConfig(
53 load_in_4bit=True,
54 bnb_4bit_compute_dtype=torch.bfloat16,
55 bnb_4bit_quant_type="nf4" if args.device_map == "cpu" else "fp4",
56 bnb_4bit_use_double_quant=True,
57 llm_int8_enable_fp32_cpu_offload=True,
58 )
59
60 torch_dtype = {
61 "float16": torch.float16,
62 "bfloat16": torch.bfloat16,
63 "float32": torch.float32,
64 }[args.dtype]
65
66 model = AutoModelForCausalLM.from_pretrained(
67 args.base_model,
68 dtype=torch_dtype,
69 device_map=args.device_map,
70 trust_remote_code=True,
71 #quantization_config=quant_config_4,
72 #attn_implementation="eager",
73 )
74
75 tokenizer = AutoTokenizer.from_pretrained(args.base_model, trust_remote_code=True)
76 tokenizer.padding_side = 'left'
77 tokenizer.pad_token = tokenizer.eos_token
78 tokenizer.pad_token_id = tokenizer.eos_token_id
79
80 messages = []
81 skip_prompt=True
82 skip_special_tokens=True
83
84 class CustomTextStreamer(TextStreamer):
85 def __init__(self, tokenizer, skip_prompt=True, skip_special_tokens=True):
86 super().__init__(tokenizer, skip_prompt=skip_prompt, skip_special_tokens=skip_special_tokens)
87 self.generated_text = ""
88 self.stop_flag = False
89 self.init_time = time.time() # Record initialization time
90 self.end_time = None # To store end time
91 self.first_token_time = None # To store first token generation time
92 self.token_count = 0 # To track total tokens
93
94 def on_finalized_text(self, text: str, stream_end: bool = False):
95 if self.first_token_time is None and text.strip(): # Set first token time on first non-empty text
96 self.first_token_time = time.time()
97 if stream_end:
98 self.end_time = time.time() # Record end time when streaming ends
99
100 self.generated_text += text
101 self.token_count += 1
102 print(text, end="", flush=True)
103
104 if self.stop_flag:
105 raise StopIteration
106
107 def stop_generation(self):
108 self.stop_flag = True
109 self.end_time = time.time() # Record end time when generation is stopped
110
111 def get_metrics(self):
112 """Returns initialization time, first token time, first token latency, end time, total time, total tokens, and tokens per second."""
113 if self.end_time is None:
114 self.end_time = time.time() # Set end time if not already set
115 total_time = self.end_time - self.init_time # Total time from init to end
116 tokens_per_second = self.token_count / total_time if total_time > 0 else 0
117 first_token_latency = (self.first_token_time - self.init_time) if self.first_token_time is not None else None
118 metrics = {
119 "init_time": self.init_time,
120 "first_token_time": self.first_token_time,
121 "first_token_latency": first_token_latency,
122 "end_time": self.end_time,
123 "total_time": total_time, # Total time in seconds
124 "total_tokens": self.token_count,
125 "tokens_per_second": tokens_per_second
126 }
127 return metrics
128
129 def generate_stream(model, tokenizer, messages, skip_prompt, skip_special_tokens, max_new_tokens):
130 text = tokenizer.apply_chat_template(
131 messages,
132 tokenize=False,
133 add_generation_prompt=True,
134 )
135 inputs = tokenizer(
136 text,
137 return_tensors="pt",
138 ).to(model.device)
139
140 streamer = CustomTextStreamer(tokenizer, skip_prompt=skip_prompt, skip_special_tokens=skip_special_tokens)
141
142 def signal_handler(sig, frame):
143 streamer.stop_generation()
144 print("\n[Generation stopped by user with Ctrl+C]")
145
146 signal.signal(signal.SIGINT, signal_handler)
147
148 print("Response: ", end="", flush=True)
149 try:
150 generated_ids = model.generate(
151 **inputs,
152 max_new_tokens=max_new_tokens,
153 #pad_token_id=tokenizer.pad_token_id,
154 #eos_token_id=tokenizer.eos_token_id,
155 streamer=streamer
156 )
157 del generated_ids
158 except StopIteration:
159 print("\n[Stopped by user]")
160
161 del inputs
162 torch.cuda.empty_cache()
163 signal.signal(signal.SIGINT, signal.SIG_DFL)
164
165 return streamer.generated_text, streamer.stop_flag, streamer.get_metrics()
166
167 while True:
168 user_input = input("User: ").strip()
169 if user_input.lower() == "/exit":
170 print("Exiting chat.")
171 break
172 if user_input.lower() == "/clear":
173 messages = []
174 print("Chat history cleared. Starting a new conversation.")
175 continue
176 if user_input.lower() == "/skip_prompt":
177 if skip_prompt:
178 skip_prompt = False
179 print("skip_prompt = False.")
180 else:
181 skip_prompt = True
182 print("skip_prompt = True.")
183 continue
184 if user_input.lower() == "/skip_special_tokens":
185 if skip_special_tokens:
186 skip_special_tokens = False
187 print("skip_special_tokens = False.")
188 else:
189 skip_special_tokens = True
190 print("skip_special_tokens = True.")
191 continue
192 if not user_input:
193 print("Input cannot be empty. Please enter something.")
194 continue
195
196 messages.append({"role": "user", "content": user_input})
197 response, stop_flag, metrics = generate_stream(model, tokenizer, messages, skip_prompt, skip_special_tokens, 40960)
198 print("\n\nMetrics:")
199 for key, value in metrics.items():
200 print(f" {key}: {value}")
201
202 print("", flush=True)
203
204 if stop_flag:
205 continue
206 messages.append({"role": "assistant", "content": response})
207
208if __name__ == "__main__":
209 main() bc1qqnkhuchxw0zqjh2ku3lu4hq45hc6gy84uk70ge