rahul7star commited on
Commit
2051f2d
·
verified ·
1 Parent(s): f2fce5e

Update app_cpu.py

Browse files
Files changed (1) hide show
  1. app_cpu.py +61 -59
app_cpu.py CHANGED
@@ -6,17 +6,17 @@ import gradio as gr
6
  from huggingface_hub import snapshot_download
7
 
8
  # ============================================================
9
- # 1️⃣ Model auto-download during app load
10
  # ============================================================
11
 
12
- DEFAULT_MODEL_PATH = os.environ.get("MODEL_OUTPUT_PATH", "PromptEnhancer/PromptEnhancer-32B")
13
 
14
- print(f"🔄 Checking local model at startup: {DEFAULT_MODEL_PATH}")
15
- local_model_dir = snapshot_download(repo_id=DEFAULT_MODEL_PATH)
16
- print(f"✅ Model downloaded and cached at: {local_model_dir}")
17
 
18
  # ============================================================
19
- # 2️⃣ Helper utils
20
  # ============================================================
21
 
22
  try:
@@ -26,46 +26,52 @@ except Exception:
26
  return None, None
27
 
28
  def replace_single_quotes(text):
 
29
  pattern = r"\B'([^']*)'\B"
30
  replaced_text = re.sub(pattern, r'"\1"', text)
31
- replaced_text = replaced_text.replace("’", "”").replace("‘", "“")
32
- return replaced_text
33
 
34
  def _str_to_dtype(dtype_str):
35
- if dtype_str in ("bfloat16", "float16", "float32"):
36
- return dtype_str
37
- return "float32"
38
 
39
  # ============================================================
40
- # 3️⃣ CPU inference function
41
  # ============================================================
42
 
43
- def cpu_predict(model_path, torch_dtype, prompt_cot, sys_prompt, temperature, max_new_tokens):
44
- import torch
45
- from transformers import Qwen2_5_VLForConditionalGeneration, AutoProcessor
46
 
47
- if not logging.getLogger(__name__).handlers:
48
- logging.basicConfig(level=logging.INFO)
49
- logger = logging.getLogger(__name__)
50
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
  dtype = {
52
  "bfloat16": torch.bfloat16,
53
  "float16": torch.float16,
54
  "float32": torch.float32,
55
  }.get(torch_dtype, torch.float32)
56
 
57
- # Force CPU
58
  device = "cpu"
59
 
60
- logger.info("🔧 Loading model to CPU...")
61
- model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
62
- model_path,
63
- torch_dtype=dtype,
64
- device_map={"": device}, # CPU-only mapping
65
- attn_implementation="sdpa",
66
- )
67
- processor = AutoProcessor.from_pretrained(model_path)
68
-
69
  org_prompt_cot = prompt_cot
70
  user_prompt_format = sys_prompt + "\n" + org_prompt_cot
71
  messages = [{"role": "user", "content": [{"type": "text", "text": user_prompt_format}]}]
@@ -81,7 +87,7 @@ def cpu_predict(model_path, torch_dtype, prompt_cot, sys_prompt, temperature, ma
81
  return_tensors="pt",
82
  ).to(device)
83
 
84
- logger.info("🧠 Running generation on CPU...")
85
  generated_ids = model.generate(
86
  **inputs,
87
  max_new_tokens=int(max_new_tokens),
@@ -103,6 +109,7 @@ def cpu_predict(model_path, torch_dtype, prompt_cot, sys_prompt, temperature, ma
103
  output_res = output_text[0]
104
 
105
  try:
 
106
  assert output_res.count("think>") == 2
107
  new_prompt = output_res.split("think>")[-1].lstrip("\n")
108
  new_prompt = replace_single_quotes(new_prompt)
@@ -112,65 +119,60 @@ def cpu_predict(model_path, torch_dtype, prompt_cot, sys_prompt, temperature, ma
112
  return new_prompt, ""
113
 
114
  # ============================================================
115
- # 4️⃣ Gradio interface
116
  # ============================================================
117
 
118
  def run_single(prompt, sys_prompt, temperature, max_new_tokens, torch_dtype, state):
 
119
  if not prompt.strip():
120
- return "", "请先输入提示词。", state
121
 
122
  t0 = time.time()
123
  try:
124
- new_prompt, err = cpu_predict(
125
- model_path=local_model_dir,
126
- torch_dtype=_str_to_dtype(torch_dtype),
127
- prompt_cot=prompt,
128
- sys_prompt=sys_prompt,
129
- temperature=temperature,
130
- max_new_tokens=max_new_tokens,
131
- )
132
  dt = time.time() - t0
133
- msg = f"耗时:{dt:.2f}s"
134
  if err:
135
- msg = f"{err}{msg}"
136
  return new_prompt, msg, state
137
  except Exception as e:
138
- return "", f"调用失败:{e}", state
139
 
140
  # ============================================================
141
- # 5️⃣ UI
142
  # ============================================================
143
 
144
- test_list_zh = [
145
- "第三人称视角,赛车在城市赛道上飞驰,左上角是小地图,地图下面是当前名次,右下角仪表盘显示当前速度。",
146
- ]
147
- test_list_en = [
148
- "Create a painting depicting a 30-year-old white-collar worker on a business trip by plane.",
 
149
  ]
150
 
151
- with gr.Blocks(title="Prompt Enhancer (CPU Mode)") as demo:
152
- gr.Markdown("## 🧩 Prompt Enhancer (CPU Mode — model preloaded)")
153
  with gr.Row():
154
  sys_prompt = gr.Textbox(
155
- label="系统提示词",
156
- value="请根据用户的输入,生成思考过程的思维链并改写提示词:",
157
  lines=3
158
  )
159
  temperature = gr.Slider(0, 1, value=0.1, step=0.05, label="Temperature")
160
  max_new_tokens = gr.Slider(16, 4096, value=2048, step=16, label="Max New Tokens")
161
- torch_dtype = gr.Dropdown(["float32", "float16", "bfloat16"], value="float32", label="torch_dtype")
162
 
163
  state = gr.State(value=None)
164
 
165
- with gr.Tab("推理"):
166
  with gr.Row():
167
  with gr.Column(scale=2):
168
- prompt = gr.Textbox(label="输入提示词", lines=6, placeholder="在此粘贴要改写的提示词...")
169
- run_btn = gr.Button("生成重写", variant="primary")
170
- gr.Examples(examples=test_list_zh + test_list_en, inputs=prompt)
171
  with gr.Column(scale=3):
172
- out_text = gr.Textbox(label="重写结果", lines=10)
173
- out_info = gr.Markdown("✅ 模型已在CPU加载。")
174
 
175
  run_btn.click(
176
  run_single,
 
6
  from huggingface_hub import snapshot_download
7
 
8
  # ============================================================
9
+ # 1️⃣ Pre-download model during app startup
10
  # ============================================================
11
 
12
+ DEFAULT_MODEL_REPO = os.environ.get("MODEL_OUTPUT_PATH", "PromptEnhancer/PromptEnhancer-32B")
13
 
14
+ print(f"🔄 Checking and downloading model repo: {DEFAULT_MODEL_REPO}")
15
+ local_model_dir = snapshot_download(repo_id=DEFAULT_MODEL_REPO)
16
+ print(f"✅ Model cached locally at: {local_model_dir}")
17
 
18
  # ============================================================
19
+ # 2️⃣ Utilities
20
  # ============================================================
21
 
22
  try:
 
26
  return None, None
27
 
28
  def replace_single_quotes(text):
29
+ """Replace single quotes inside words with double quotes for consistency."""
30
  pattern = r"\B'([^']*)'\B"
31
  replaced_text = re.sub(pattern, r'"\1"', text)
32
+ return replaced_text.replace("’", "”").replace("‘", "“")
 
33
 
34
  def _str_to_dtype(dtype_str):
35
+ """Normalize torch dtype string."""
36
+ return dtype_str if dtype_str in ("bfloat16", "float16", "float32") else "float32"
 
37
 
38
  # ============================================================
39
+ # 3️⃣ Load model once (from local snapshot)
40
  # ============================================================
41
 
42
+ import torch
43
+ from transformers import Qwen2_5_VLForConditionalGeneration, AutoProcessor
 
44
 
45
+ logging.basicConfig(level=logging.INFO)
46
+ logger = logging.getLogger("PromptEnhancerCPU")
 
47
 
48
+ dtype = torch.float32 # Default for CPU
49
+ logger.info("🔧 Loading pre-downloaded model from local path...")
50
+
51
+ model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
52
+ local_model_dir,
53
+ torch_dtype=dtype,
54
+ device_map={"": "cpu"}, # Force CPU only
55
+ attn_implementation="sdpa",
56
+ )
57
+ processor = AutoProcessor.from_pretrained(local_model_dir)
58
+
59
+ logger.info("✅ Model loaded and ready on CPU.")
60
+
61
+ # ============================================================
62
+ # 4️⃣ Inference (uses already-loaded model)
63
+ # ============================================================
64
+
65
+ def cpu_predict(prompt_cot, sys_prompt, temperature, max_new_tokens, torch_dtype):
66
+ """Generate rewritten prompt using preloaded model on CPU."""
67
  dtype = {
68
  "bfloat16": torch.bfloat16,
69
  "float16": torch.float16,
70
  "float32": torch.float32,
71
  }.get(torch_dtype, torch.float32)
72
 
 
73
  device = "cpu"
74
 
 
 
 
 
 
 
 
 
 
75
  org_prompt_cot = prompt_cot
76
  user_prompt_format = sys_prompt + "\n" + org_prompt_cot
77
  messages = [{"role": "user", "content": [{"type": "text", "text": user_prompt_format}]}]
 
87
  return_tensors="pt",
88
  ).to(device)
89
 
90
+ logger.info("🧠 Running generation (CPU)...")
91
  generated_ids = model.generate(
92
  **inputs,
93
  max_new_tokens=int(max_new_tokens),
 
109
  output_res = output_text[0]
110
 
111
  try:
112
+ # Extract part after "think>" if present
113
  assert output_res.count("think>") == 2
114
  new_prompt = output_res.split("think>")[-1].lstrip("\n")
115
  new_prompt = replace_single_quotes(new_prompt)
 
119
  return new_prompt, ""
120
 
121
  # ============================================================
122
+ # 5️⃣ Gradio Logic
123
  # ============================================================
124
 
125
  def run_single(prompt, sys_prompt, temperature, max_new_tokens, torch_dtype, state):
126
+ """Handle one user query from Gradio."""
127
  if not prompt.strip():
128
+ return "", "Please enter a prompt first.", state
129
 
130
  t0 = time.time()
131
  try:
132
+ new_prompt, err = cpu_predict(prompt, sys_prompt, temperature, max_new_tokens, torch_dtype)
 
 
 
 
 
 
 
133
  dt = time.time() - t0
134
+ msg = f"Time taken: {dt:.2f}s"
135
  if err:
136
+ msg = f"{err} ({msg})"
137
  return new_prompt, msg, state
138
  except Exception as e:
139
+ return "", f"Error: {e}", state
140
 
141
  # ============================================================
142
+ # 6️⃣ Gradio UI
143
  # ============================================================
144
 
145
+ example_prompts = [
146
+ "Third-person view: a race car speeding through a city track, with a mini-map in the top-left corner and a speedometer in the bottom-right.",
147
+ "Anime-style portrait of a girl with short purple hair and soft lighting.",
148
+ "Pointillism painting: two fishermen carrying crates by the seaside, with boats docked nearby.",
149
+ "A Van Gogh-inspired wheat field tangled with swirling blue nebulae and fiery sunflowers.",
150
+ "Create a painting depicting a 30-year-old businesswoman on a plane trip.",
151
  ]
152
 
153
+ with gr.Blocks(title="Prompt Enhancer (CPU Preload)") as demo:
154
+ gr.Markdown("## 🧩 Prompt Enhancer (CPU Mode — Model Preloaded via `snapshot_download`)")
155
  with gr.Row():
156
  sys_prompt = gr.Textbox(
157
+ label="System Prompt",
158
+ value="Please think step-by-step and rewrite the user’s prompt in a more refined, creative, and detailed way:",
159
  lines=3
160
  )
161
  temperature = gr.Slider(0, 1, value=0.1, step=0.05, label="Temperature")
162
  max_new_tokens = gr.Slider(16, 4096, value=2048, step=16, label="Max New Tokens")
163
+ torch_dtype = gr.Dropdown(["float32", "float16", "bfloat16"], value="float32", label="Torch Dtype")
164
 
165
  state = gr.State(value=None)
166
 
167
+ with gr.Tab("Inference"):
168
  with gr.Row():
169
  with gr.Column(scale=2):
170
+ prompt = gr.Textbox(label="Input Prompt", lines=6, placeholder="Paste the prompt to rewrite here...")
171
+ run_btn = gr.Button("Generate Rewrite", variant="primary")
172
+ gr.Examples(examples=example_prompts, inputs=prompt)
173
  with gr.Column(scale=3):
174
+ out_text = gr.Textbox(label="Rewritten Prompt", lines=10)
175
+ out_info = gr.Markdown("✅ Model loaded on CPU (from `snapshot_download` cache).")
176
 
177
  run_btn.click(
178
  run_single,