Views
No views yet
transformers 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-granite-4.0-micro-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 tokens = self.tokenizer.encode(text, add_special_tokens=False)
64 self.token_count += len(tokens)
65 print(text, end="", flush=True)
66 if stream_end:
67 self.end_time = time.time() # Record end time when streaming ends
68 if self.stop_flag:
69 raise StopIteration
70
71 def stop_generation(self):
72 self.stop_flag = True
73 self.end_time = time.time() # Record end time when generation is stopped
74
75 def get_metrics(self):
76 """Returns initialization time, first token time, first token latency, end time, total time, total tokens, and tokens per second."""
77 if self.end_time is None:
78 self.end_time = time.time() # Set end time if not already set
79 total_time = self.end_time - self.init_time # Total time from init to end
80 tokens_per_second = self.token_count / total_time if total_time > 0 else 0
81 first_token_latency = (self.first_token_time - self.init_time) if self.first_token_time is not None else None
82 metrics = {
83 "init_time": self.init_time,
84 "first_token_time": self.first_token_time,
85 "first_token_latency": first_token_latency,
86 "end_time": self.end_time,
87 "total_time": total_time, # Total time in seconds
88 "total_tokens": self.token_count,
89 "tokens_per_second": tokens_per_second
90 }
91 return metrics
92
93def generate_stream(model, tokenizer, messages, skip_prompt, skip_special_tokens, max_new_tokens):
94 formatted_prompt = tokenizer.apply_chat_template(
95 messages,
96 tokenize=False,
97 add_generation_prompt=True,
98 )
99
100 toks = tokenizer(
101 formatted_prompt,
102 return_tensors="pt",
103 ).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 generate_kwargs = {}
114
115 print("Response: ", end="", flush=True)
116 try:
117 generated_ids = model.generate(
118 **toks,
119 max_new_tokens=max_new_tokens,
120 streamer=streamer,
121 #**generate_kwargs
122 )
123 del generated_ids
124 except StopIteration:
125 print("\n[Stopped by user]")
126
127 del toks
128 torch.cuda.empty_cache()
129 signal.signal(signal.SIGINT, signal.SIG_DFL)
130
131 return streamer.generated_text, streamer.stop_flag, streamer.get_metrics()
132
133while True:
134 print(f"skip_prompt: {skip_prompt}")
135 print(f"skip_special_tokens: {skip_special_tokens}")
136
137 user_input = input("User: ").strip()
138 if user_input.lower() == "/exit":
139 print("Exiting chat.")
140 break
141 if user_input.lower() == "/clear":
142 messages = []
143 print("Chat history cleared. Starting a new conversation.")
144 continue
145 if user_input.lower() == "/skip_prompt":
146 skip_prompt = not skip_prompt
147 continue
148 if user_input.lower() == "/skip_special_tokens":
149 skip_special_tokens = not skip_special_tokens
150 continue
151 if not user_input:
152 print("Input cannot be empty. Please enter something.")
153 continue
154
155
156 messages.append({"role": "user", "content": user_input})
157
158 response, stop_flag, metrics = generate_stream(model, tokenizer, messages, skip_prompt, skip_special_tokens, 40960)
159 print("\n\nMetrics:")
160 for key, value in metrics.items():
161 print(f" {key}: {value}")
162
163 print("", flush=True)
164 if stop_flag:
165 continue
166 messages.append({"role": "assistant", "content": response})
167 bc1qqnkhuchxw0zqjh2ku3lu4hq45hc6gy84uk70ge