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