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