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