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