File size: 8,670 Bytes
9317120 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 |
"""
SmolVLM Webcam Auto Inference (Fine-tuned)
3์ด๋ง๋ค ์๋์ผ๋ก inference ์ํ
Fine-tuned on Hair classification & description dataset
"""
import torch
from PIL import Image
from transformers import AutoProcessor, AutoModelForImageTextToText
from peft import PeftModel
import gradio as gr
import numpy as np
from datetime import datetime
import time
# =========================
# ์ค์
# =========================
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
BASE_MODEL_ID = "HuggingFaceTB/SmolVLM-256M-Instruct"
FINETUNED_MODEL_PATH = "/root/crying_cv_vlm/checkpoint-105" # โ
์ต์ข
ํ์ต๋ ๋ชจ๋ธ (checkpoint-105)
INFERENCE_INTERVAL = 3 # 3์ด ๊ฐ๊ฒฉ
print(f"๐ง Device: {DEVICE}")
print(f"๐ Fine-tuned Model: {FINETUNED_MODEL_PATH}")
print("Loading model...")
# =========================
# ๋ชจ๋ธ ๋ก๋ (Fine-tuned LoRA)
# =========================
from transformers import AutoModelForImageTextToText
from peft import PeftModel
print("1๏ธโฃ Loading base model...")
model = AutoModelForImageTextToText.from_pretrained(
BASE_MODEL_ID,
dtype=torch.bfloat16 if DEVICE == "cuda" else torch.float32,
device_map="auto",
attn_implementation="eager"
)
print("2๏ธโฃ Loading fine-tuned adapter...")
model = PeftModel.from_pretrained(
model,
FINETUNED_MODEL_PATH,
device_map="auto"
)
print("3๏ธโฃ Merging adapter...")
model = model.merge_and_unload()
model.eval()
print("4๏ธโฃ Loading processor...")
processor = AutoProcessor.from_pretrained(FINETUNED_MODEL_PATH)
print("โ
Model loaded!")
if torch.cuda.is_available():
print(f"๐พ VRAM: {torch.cuda.memory_allocated(0) / 1024**3:.2f} GB")
def inference(image, question):
"""์ด๋ฏธ์ง์ ์ง๋ฌธ์ ๋ฐ์ inference ์ํ"""
if image is None:
return "โ ๏ธ ์น์บ ์์ ์ด๋ฏธ์ง๋ฅผ ์บก์ฒํด์ฃผ์ธ์.", "๋๊ธฐ ์ค"
if not question or question.strip() == "":
question = "Describe this image in detail."
try:
# Convert to PIL Image
if isinstance(image, np.ndarray):
image = Image.fromarray(image).convert('RGB')
elif not isinstance(image, Image.Image):
return "โ ์๋ชป๋ ์ด๋ฏธ์ง ํ์", "์๋ฌ"
elif image.mode != 'RGB':
image = image.convert('RGB')
# Prepare messages
messages = [{
"role": "user",
"content": [{"type": "image"}, {"type": "text", "text": question}]
}]
# Process
prompt = processor.apply_chat_template(messages, add_generation_prompt=True)
inputs = processor(text=prompt, images=[image], return_tensors="pt").to(DEVICE)
# ์
๋ ฅ ๊ธธ์ด ์ ์ฅ
input_len = inputs["input_ids"].shape[-1]
# Generate
with torch.inference_mode():
generated_ids = model.generate(
**inputs,
max_new_tokens=100,
do_sample=True,
temperature=0.7,
top_p=0.9
)
# Decode (์๋ก ์์ฑ๋ ํ ํฐ๋ง)
generated_ids = generated_ids[0][input_len:]
response = processor.decode(generated_ids, skip_special_tokens=True).strip()
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
status = f"โ
{timestamp}"
return response if response else "(๋น ์๋ต)", status
except Exception as e:
import traceback
error_msg = traceback.format_exc()
return f"โ ์๋ฌ: {str(e)}\n\n{error_msg}", "์๋ฌ ๋ฐ์"
# =========================
# Gradio UI
# =========================
with gr.Blocks(title="SmolVLM Auto Inference") as demo:
gr.Markdown("""
# ๐ฅ SmolVLM ์น์บ ์๋ ์ถ๋ก (Fine-tuned)
**3์ด๋ง๋ค ์๋์ผ๋ก ์ถ๋ก ์ ์ํํฉ๋๋ค**
### ๋ชจ๋ธ ์ ๋ณด:
- **Base Model**: HuggingFaceTB/SmolVLM-256M-Instruct
- **Fine-tuned on**: Hair classification & description dataset
- **Training**: 5 epochs, Final loss: 1.1350
### ์ฌ์ฉ ๋ฐฉ๋ฒ:
1. ์น์บ ํ์ฉ ๋ฐ ์ด๋ฏธ์ง ์บก์ฒ
2. ์ง๋ฌธ ์
๋ ฅ
3. "๐ ์๋ ์ถ๋ก ์์" ๋ฒํผ ํด๋ฆญ
4. 3์ด๋ง๋ค ์๋์ผ๋ก ์ถ๋ก ๋ฉ๋๋ค
5. "โธ๏ธ ์ค์ง" ๋ฒํผ์ผ๋ก ๋ฉ์ถ ์ ์์ต๋๋ค
""")
with gr.Row():
with gr.Column(scale=1):
# ์น์บ (streaming ํ์ฑํ)
webcam = gr.Image(
label="๐ท ์น์บ ",
type="numpy",
sources=["webcam"],
streaming=True, # ์คํธ๋ฆฌ๋ฐ ํ์ฑํ
height=400
)
# ์ง๋ฌธ ์
๋ ฅ
question = gr.Textbox(
label="๐ฌ ์ง๋ฌธ",
placeholder="์ด๋ฏธ์ง์ ๋ํด ๋ฌผ์ด๋ณด๊ณ ์ถ์ ๊ฒ์ ์
๋ ฅํ์ธ์",
value="Classify the hair length in this image. Possible values: short, mid, long. Output only one word.",
lines=3
)
with gr.Row():
start_btn = gr.Button("๐ ์๋ ์ถ๋ก ์์", variant="primary", scale=2)
stop_btn = gr.Button("โธ๏ธ ์ค์ง", variant="stop", scale=1)
with gr.Column(scale=1):
# ์ถ๋ ฅ
output = gr.Textbox(
label="๐ค ์๋ต",
lines=15,
max_lines=20
)
# ์ํ
status = gr.Textbox(
label="๐ ์ํ",
value="๋๊ธฐ ์ค",
lines=1
)
# ์๋ ์ถ๋ก ์ํ
auto_status = gr.Textbox(
label="๐ ์๋ ์ถ๋ก ์ํ",
value="๋ฉ์ถค",
lines=1
)
# ์์ ์ง๋ฌธ
gr.Markdown("### ๐ก ์์ ์ง๋ฌธ:")
gr.Examples(
examples=[
["Classify the hair length in this image. Possible values: short, mid, long. Output only one word."],
["Describe the person's hair style, color, and texture in detail."],
["What is the hair length? Answer in one word: short, mid, or long."],
["Describe what you see in this image."],
["์ด ์ฌ๋์ ๋จธ๋ฆฌ ๊ธธ์ด๋ฅผ ๋ถ๋ฅํ์ธ์. ๊ฐ๋ฅํ ๊ฐ: short, mid, long"],
],
inputs=[question],
)
# ์๋ ์ถ๋ก ์ ์ด
is_auto_running = gr.State(value=False)
last_inference_time = gr.State(value=0)
def start_auto_inference():
"""์๋ ์ถ๋ก ์์"""
# ํ์ฌ ์๊ฐ์ผ๋ก ์ค์ ํ์ฌ ์ฆ์ ์ฒซ ์ถ๋ก ์์
return True, "โถ๏ธ ์คํ ์ค (3์ด ๊ฐ๊ฒฉ)", gr.Timer(value=0.5, active=True), time.time() - INFERENCE_INTERVAL
def stop_auto_inference():
"""์๋ ์ถ๋ก ์ค์ง"""
return False, "โธ๏ธ ๋ฉ์ถค", gr.Timer(value=0.5, active=False)
def auto_inference_loop(image, question_text, is_running, last_time):
"""์๋ ์ถ๋ก ๋ฃจํ (3์ด๋ง๋ค ์คํ)"""
if not is_running:
return gr.update(), gr.update(), last_time
current_time = time.time()
# ์ด๋ฏธ์ง ์์ผ๋ฉด ๊ฒฝ๊ณ ๋ฉ์์ง
if image is None:
return gr.update(), "โ ๏ธ ์น์บ ์ด๋ฏธ์ง๋ฅผ ์บก์ฒํด์ฃผ์ธ์", last_time
# 3์ด ๊ฒฝ๊ณผ ํ์ธ
if current_time - last_time >= INFERENCE_INTERVAL:
result, status_msg = inference(image, question_text)
return result, status_msg, current_time
else:
# ๋๊ธฐ ์ค ๋จ์ ์๊ฐ ํ์
remaining = INFERENCE_INTERVAL - (current_time - last_time)
return gr.update(), f"โฑ๏ธ ๋ค์ ์ถ๋ก ๊น์ง {remaining:.1f}์ด", last_time
# ์๋ ์ถ๋ก ํ์ด๋จธ
timer = gr.Timer(value=0.5, active=False)
# ์์ ๋ฒํผ
start_btn.click(
fn=start_auto_inference,
inputs=[],
outputs=[is_auto_running, auto_status, timer, last_inference_time]
)
# ์ค์ง ๋ฒํผ
stop_btn.click(
fn=stop_auto_inference,
inputs=[],
outputs=[is_auto_running, auto_status, timer]
)
# ํ์ด๋จธ ํฑ
timer.tick(
fn=auto_inference_loop,
inputs=[webcam, question, is_auto_running, last_inference_time],
outputs=[output, status, last_inference_time]
)
if __name__ == "__main__":
print("\n" + "="*70)
print("๐ Launching at http://0.0.0.0:7860")
print("="*70 + "\n")
demo.launch(
server_name="0.0.0.0",
server_port=8085,
share=False,
show_error=True
)
|