Views
No views yet
ollama run huihui_ai/gpt-oss-abliteratedllama-cli -m huihui-ai/Huihui-gpt-oss-20b-BF16-abliterated/GGUF/ggml-model-Q4_K_M.gguf -n 8192
transformers library:1from transformers import AutoModelForCausalLM, AutoTokenizer, 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-gpt-oss-20b-BF16-abliterated"
23print(f"Load Model {NEW_MODEL_ID} ... ")
24
25model = AutoModelForCausalLM.from_pretrained(
26 NEW_MODEL_ID,
27 device_map="auto",
28 trust_remote_code=True,
29 torch_dtype=torch.bfloat16,
30 low_cpu_mem_usage=True,
31)
32#print(model)
33#print(model.config)
34
35tokenizer = AutoTokenizer.from_pretrained(NEW_MODEL_ID, trust_remote_code=True)
36
37messages = []
38skip_prompt=False
39skip_special_tokens=False
40do_sample = True
41
42class CustomTextStreamer(TextStreamer):
43 def __init__(self, tokenizer, skip_prompt=True, skip_special_tokens=True):
44 super().__init__(tokenizer, skip_prompt=skip_prompt, skip_special_tokens=skip_special_tokens)
45 self.generated_text = ""
46 self.stop_flag = False
47 self.init_time = time.time() # Record initialization time
48 self.end_time = None # To store end time
49 self.first_token_time = None # To store first token generation time
50 self.token_count = 0 # To track total tokens
51
52 def on_finalized_text(self, text: str, stream_end: bool = False):
53 if self.first_token_time is None and text.strip(): # Set first token time on first non-empty text
54 self.first_token_time = time.time()
55 self.generated_text += text
56 # Count tokens in the generated text
57 tokens = self.tokenizer.encode(text, add_special_tokens=False)
58 self.token_count += len(tokens)
59 print(text, end="", flush=True)
60 if stream_end:
61 self.end_time = time.time() # Record end time when streaming ends
62 if self.stop_flag:
63 raise StopIteration
64
65 def stop_generation(self):
66 self.stop_flag = True
67 self.end_time = time.time() # Record end time when generation is stopped
68
69 def get_metrics(self):
70 """Returns initialization time, first token time, first token latency, end time, total time, total tokens, and tokens per second."""
71 if self.end_time is None:
72 self.end_time = time.time() # Set end time if not already set
73 total_time = self.end_time - self.init_time # Total time from init to end
74 tokens_per_second = self.token_count / total_time if total_time > 0 else 0
75 first_token_latency = (self.first_token_time - self.init_time) if self.first_token_time is not None else None
76 metrics = {
77 "init_time": self.init_time,
78 "first_token_time": self.first_token_time,
79 "first_token_latency": first_token_latency,
80 "end_time": self.end_time,
81 "total_time": total_time, # Total time in seconds
82 "total_tokens": self.token_count,
83 "tokens_per_second": tokens_per_second
84 }
85 return metrics
86
87def generate_stream(model, tokenizer, messages, skip_prompt, skip_special_tokens, do_sample, max_new_tokens):
88 input_ids = tokenizer.apply_chat_template(
89 messages,
90 add_generation_prompt=True,
91 return_tensors="pt",
92 return_dict=True,
93 ).to(model.device)
94
95 streamer = CustomTextStreamer(tokenizer, skip_prompt=skip_prompt, skip_special_tokens=skip_special_tokens)
96
97 def signal_handler(sig, frame):
98 streamer.stop_generation()
99 print("\n[Generation stopped by user with Ctrl+C]")
100
101 signal.signal(signal.SIGINT, signal_handler)
102
103 generate_kwargs = {}
104 if do_sample:
105 generate_kwargs = {
106 "do_sample": do_sample,
107 "max_length": max_new_tokens,
108 "temperature": 0.7,
109 "top_k": 20,
110 "top_p": 0.8,
111 "repetition_penalty": 1.2,
112 "no_repeat_ngram_size": 2
113 }
114 else:
115 generate_kwargs = {
116 "do_sample": do_sample,
117 "max_length": max_new_tokens,
118 "repetition_penalty": 1.2,
119 "no_repeat_ngram_size": 2
120 }
121
122
123 print("Response: ", end="", flush=True)
124 try:
125 generated_ids = model.generate(
126 **input_ids,
127 streamer=streamer,
128 **generate_kwargs
129 )
130 del generated_ids
131 except StopIteration:
132 print("\n[Stopped by user]")
133
134 del input_ids
135 torch.cuda.empty_cache()
136 signal.signal(signal.SIGINT, signal.SIG_DFL)
137
138 return streamer.generated_text, streamer.stop_flag, streamer.get_metrics()
139
140while True:
141 print(f"skip_prompt: {skip_prompt}")
142 print(f"skip_special_tokens: {skip_special_tokens}")
143 print(f"do_sample: {do_sample}")
144
145 user_input = input("User: ").strip()
146 if user_input.lower() == "/exit":
147 print("Exiting chat.")
148 break
149 if user_input.lower() == "/clear":
150 messages = []
151 print("Chat history cleared. Starting a new conversation.")
152 continue
153 if user_input.lower() == "/skip_prompt":
154 skip_prompt = not skip_prompt
155 continue
156 if user_input.lower() == "/skip_special_tokens":
157 skip_special_tokens = not skip_special_tokens
158 continue
159 if user_input.lower() == "/do_sample":
160 do_sample = not do_sample
161 continue
162 if not user_input:
163 print("Input cannot be empty. Please enter something.")
164 continue
165
166
167 messages.append({"role": "user", "content": user_input})
168 response, stop_flag, metrics = generate_stream(model, tokenizer, messages, skip_prompt, skip_special_tokens, do_sample, 40960)
169 print("\n\nMetrics:")
170 for key, value in metrics.items():
171 print(f" {key}: {value}")
172
173 print("", flush=True)
174 if stop_flag:
175 continue
176 messages.append({"role": "assistant", "content": response}) bc1qqnkhuchxw0zqjh2ku3lu4hq45hc6gy84uk70ge