Update app_cpu.py
Browse files- 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️⃣
|
| 10 |
# ============================================================
|
| 11 |
|
| 12 |
-
|
| 13 |
|
| 14 |
-
print(f"🔄 Checking
|
| 15 |
-
local_model_dir = snapshot_download(repo_id=
|
| 16 |
-
print(f"✅ Model
|
| 17 |
|
| 18 |
# ============================================================
|
| 19 |
-
# 2️⃣
|
| 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 |
-
|
| 32 |
-
return replaced_text
|
| 33 |
|
| 34 |
def _str_to_dtype(dtype_str):
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
return "float32"
|
| 38 |
|
| 39 |
# ============================================================
|
| 40 |
-
# 3️⃣
|
| 41 |
# ============================================================
|
| 42 |
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
from transformers import Qwen2_5_VLForConditionalGeneration, AutoProcessor
|
| 46 |
|
| 47 |
-
|
| 48 |
-
|
| 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
|
| 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 |
-
#
|
| 116 |
# ============================================================
|
| 117 |
|
| 118 |
def run_single(prompt, sys_prompt, temperature, max_new_tokens, torch_dtype, state):
|
|
|
|
| 119 |
if not prompt.strip():
|
| 120 |
-
return "", "
|
| 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"
|
| 134 |
if err:
|
| 135 |
-
msg = f"{err}
|
| 136 |
return new_prompt, msg, state
|
| 137 |
except Exception as e:
|
| 138 |
-
return "", f"
|
| 139 |
|
| 140 |
# ============================================================
|
| 141 |
-
#
|
| 142 |
# ============================================================
|
| 143 |
|
| 144 |
-
|
| 145 |
-
"
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
"
|
|
|
|
| 149 |
]
|
| 150 |
|
| 151 |
-
with gr.Blocks(title="Prompt Enhancer (CPU
|
| 152 |
-
gr.Markdown("## 🧩 Prompt Enhancer (CPU Mode —
|
| 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="
|
| 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="
|
| 169 |
-
run_btn = gr.Button("
|
| 170 |
-
gr.Examples(examples=
|
| 171 |
with gr.Column(scale=3):
|
| 172 |
-
out_text = gr.Textbox(label="
|
| 173 |
-
out_info = gr.Markdown("✅
|
| 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,
|