Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -4,14 +4,12 @@ import os
|
|
| 4 |
import time
|
| 5 |
from train_vlm import train_vlm_stage
|
| 6 |
from transformers import AutoImageProcessor, AutoTokenizer
|
| 7 |
-
from custom_vlm import CustomScratchVLM
|
| 8 |
import torch
|
| 9 |
|
| 10 |
-
# --- Config ---
|
| 11 |
CHECKPOINT_ROOT = "./checkpoints"
|
| 12 |
os.makedirs(CHECKPOINT_ROOT, exist_ok=True)
|
| 13 |
|
| 14 |
-
# --- Global state for the model ---
|
| 15 |
current_stage = 0
|
| 16 |
model = None
|
| 17 |
image_processor = None
|
|
@@ -19,17 +17,13 @@ tokenizer = None
|
|
| 19 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 20 |
|
| 21 |
print(f"๐ฅ๏ธ Running on device: {device}")
|
| 22 |
-
if device == "cuda":
|
| 23 |
-
print(f"๐ฎ GPU: {torch.cuda.get_device_name(0)}")
|
| 24 |
|
| 25 |
def load_model_for_stage(stage):
|
| 26 |
-
"""Loads the appropriate custom model and processors for a given stage."""
|
| 27 |
global model, image_processor, tokenizer, current_stage
|
| 28 |
-
|
| 29 |
current_stage = stage
|
| 30 |
ckpt_path = f"{CHECKPOINT_ROOT}/stage_{stage}"
|
| 31 |
|
| 32 |
-
# Check for a saved model config, which indicates a trained checkpoint
|
| 33 |
if os.path.exists(os.path.join(ckpt_path, "config.json")):
|
| 34 |
print(f"โ
Loading FROM-SCRATCH checkpoint: Stage {stage}")
|
| 35 |
if model is not None: del model
|
|
@@ -39,103 +33,79 @@ def load_model_for_stage(stage):
|
|
| 39 |
image_processor = AutoImageProcessor.from_pretrained(ckpt_path)
|
| 40 |
tokenizer = AutoTokenizer.from_pretrained(ckpt_path)
|
| 41 |
else:
|
| 42 |
-
# Before any training, there is no model to load.
|
| 43 |
print(f"โ ๏ธ No checkpoint for Stage {stage} โ model is not loaded.")
|
| 44 |
-
model = None
|
| 45 |
-
image_processor = None
|
| 46 |
-
tokenizer = None
|
| 47 |
|
| 48 |
def chat_with_image(image, text, chat_history):
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
return "", chat_history + [{"role": "assistant", "content": "Model is not loaded or is currently training from scratch. Please wait."}]
|
| 52 |
|
| 53 |
if image is None:
|
| 54 |
return "", chat_history + [{"role": "user", "content": text}, {"role": "assistant", "content": "Please upload an image."}]
|
| 55 |
|
| 56 |
try:
|
| 57 |
-
# Prepare inputs for our custom model
|
| 58 |
pixel_values = image_processor(image, return_tensors="pt").pixel_values.to(device)
|
| 59 |
|
| 60 |
-
#
|
| 61 |
-
prompt = f"USER:
|
| 62 |
-
|
|
|
|
|
|
|
| 63 |
|
| 64 |
-
# Use our custom generate method
|
| 65 |
output_ids = model.generate(
|
| 66 |
pixel_values=pixel_values,
|
| 67 |
-
|
|
|
|
| 68 |
max_new_tokens=256,
|
| 69 |
do_sample=True,
|
| 70 |
-
temperature=0.7
|
|
|
|
| 71 |
)
|
| 72 |
|
| 73 |
-
# Decode the generated
|
| 74 |
-
response = tokenizer.decode(output_ids[0][
|
| 75 |
|
| 76 |
chat_history.append({"role": "user", "content": text})
|
| 77 |
-
chat_history.append({"role": "assistant", "content": response})
|
| 78 |
return "", chat_history
|
| 79 |
except Exception as e:
|
| 80 |
-
return "", chat_history + [{"role": "user", "content": text}, {"role": "assistant", "content": f"โ ๏ธ Error: {
|
| 81 |
-
|
| 82 |
|
| 83 |
def run_autonomous_training_and_update_ui():
|
| 84 |
-
"
|
| 85 |
-
yield "๐ Initializing COCONUT-VLM Autonomous Trainer (FROM SCRATCH)..."
|
| 86 |
-
|
| 87 |
-
training_failed = False
|
| 88 |
for stage in [1, 2, 3]:
|
| 89 |
ckpt_path = f"{CHECKPOINT_ROOT}/stage_{stage}"
|
| 90 |
-
|
| 91 |
if os.path.exists(os.path.join(ckpt_path, "config.json")):
|
| 92 |
status_message = f"โญ๏ธ Stage {stage} already trained โ loading..."
|
| 93 |
yield status_message
|
| 94 |
load_model_for_stage(stage)
|
| 95 |
continue
|
| 96 |
|
| 97 |
-
status_message = f"โถ๏ธ AUTO-TRAINING FROM SCRATCH
|
| 98 |
yield status_message
|
| 99 |
-
|
| 100 |
try:
|
| 101 |
-
# Call the training function (no longer needs model_name)
|
| 102 |
train_vlm_stage(stage, ckpt_path)
|
| 103 |
status_message = f"โ
Stage {stage} completed! Loading new model..."
|
| 104 |
yield status_message
|
| 105 |
load_model_for_stage(stage)
|
| 106 |
except Exception as e:
|
| 107 |
status_message = f"โ Stage {stage} failed: {e}"
|
| 108 |
-
yield status_message
|
| 109 |
-
|
| 110 |
-
break
|
| 111 |
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
yield "๐ Training stopped due to an error."
|
| 116 |
-
|
| 117 |
-
# --- Gradio UI (No Changes) ---
|
| 118 |
-
with gr.Blocks(title="๐ฅฅ COCONUT-VLM Autonomous Trainer") as demo:
|
| 119 |
-
gr.Markdown("# ๐ฅฅ COCONUT-VLM: Autonomous Vision-Language Trainer (From Scratch)")
|
| 120 |
-
gr.Markdown("Model is training itself **from random initialization**. This will take a very long time and requires significant compute. You can interact with the latest trained model.")
|
| 121 |
-
# ... rest of UI is the same ...
|
| 122 |
with gr.Row():
|
| 123 |
with gr.Column(scale=1):
|
| 124 |
-
status = gr.Textbox(
|
| 125 |
-
label="Training Status", value="Waiting to start...", interactive=False,
|
| 126 |
-
lines=10, max_lines=20
|
| 127 |
-
)
|
| 128 |
-
gr.Markdown("๐ก _Training runs automatically on page load._")
|
| 129 |
-
|
| 130 |
with gr.Column(scale=2):
|
| 131 |
image_input = gr.Image(type="pil", label="Upload Image")
|
| 132 |
chatbot = gr.Chatbot(label="Chat with the VLM", height=400)
|
| 133 |
-
msg = gr.Textbox(label="Ask a question
|
| 134 |
clear = gr.Button("Clear Chat")
|
| 135 |
-
|
| 136 |
msg.submit(chat_with_image, [image_input, msg, chatbot], [msg, chatbot])
|
| 137 |
clear.click(lambda: (None, None, []), None, [image_input, msg, chatbot])
|
| 138 |
-
|
| 139 |
demo.load(fn=run_autonomous_training_and_update_ui, inputs=None, outputs=status)
|
| 140 |
|
| 141 |
demo.queue().launch(debug=True)
|
|
|
|
| 4 |
import time
|
| 5 |
from train_vlm import train_vlm_stage
|
| 6 |
from transformers import AutoImageProcessor, AutoTokenizer
|
| 7 |
+
from custom_vlm import CustomScratchVLM
|
| 8 |
import torch
|
| 9 |
|
|
|
|
| 10 |
CHECKPOINT_ROOT = "./checkpoints"
|
| 11 |
os.makedirs(CHECKPOINT_ROOT, exist_ok=True)
|
| 12 |
|
|
|
|
| 13 |
current_stage = 0
|
| 14 |
model = None
|
| 15 |
image_processor = None
|
|
|
|
| 17 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 18 |
|
| 19 |
print(f"๐ฅ๏ธ Running on device: {device}")
|
| 20 |
+
if device == "cuda": print(f"๐ฎ GPU: {torch.cuda.get_device_name(0)}")
|
|
|
|
| 21 |
|
| 22 |
def load_model_for_stage(stage):
|
|
|
|
| 23 |
global model, image_processor, tokenizer, current_stage
|
|
|
|
| 24 |
current_stage = stage
|
| 25 |
ckpt_path = f"{CHECKPOINT_ROOT}/stage_{stage}"
|
| 26 |
|
|
|
|
| 27 |
if os.path.exists(os.path.join(ckpt_path, "config.json")):
|
| 28 |
print(f"โ
Loading FROM-SCRATCH checkpoint: Stage {stage}")
|
| 29 |
if model is not None: del model
|
|
|
|
| 33 |
image_processor = AutoImageProcessor.from_pretrained(ckpt_path)
|
| 34 |
tokenizer = AutoTokenizer.from_pretrained(ckpt_path)
|
| 35 |
else:
|
|
|
|
| 36 |
print(f"โ ๏ธ No checkpoint for Stage {stage} โ model is not loaded.")
|
| 37 |
+
model, image_processor, tokenizer = None, None, None
|
|
|
|
|
|
|
| 38 |
|
| 39 |
def chat_with_image(image, text, chat_history):
|
| 40 |
+
if not all([model, image_processor, tokenizer]):
|
| 41 |
+
return "", chat_history + [{"role": "assistant", "content": "Model is not loaded or is currently training. Please wait."}]
|
|
|
|
| 42 |
|
| 43 |
if image is None:
|
| 44 |
return "", chat_history + [{"role": "user", "content": text}, {"role": "assistant", "content": "Please upload an image."}]
|
| 45 |
|
| 46 |
try:
|
|
|
|
| 47 |
pixel_values = image_processor(image, return_tensors="pt").pixel_values.to(device)
|
| 48 |
|
| 49 |
+
# For inference, we do not include the <IMAGE> token in the text prompt
|
| 50 |
+
prompt = f"USER: \nQuestion: {text}\nASSISTANT:"
|
| 51 |
+
inputs = tokenizer(prompt, return_tensors="pt")
|
| 52 |
+
input_ids = inputs.input_ids.to(device)
|
| 53 |
+
attention_mask = inputs.attention_mask.to(device)
|
| 54 |
|
|
|
|
| 55 |
output_ids = model.generate(
|
| 56 |
pixel_values=pixel_values,
|
| 57 |
+
input_ids=input_ids,
|
| 58 |
+
attention_mask=attention_mask,
|
| 59 |
max_new_tokens=256,
|
| 60 |
do_sample=True,
|
| 61 |
+
temperature=0.7,
|
| 62 |
+
pad_token_id=tokenizer.eos_token_id
|
| 63 |
)
|
| 64 |
|
| 65 |
+
# Decode only the newly generated tokens
|
| 66 |
+
response = tokenizer.decode(output_ids[0][input_ids.shape[1]:], skip_special_tokens=True)
|
| 67 |
|
| 68 |
chat_history.append({"role": "user", "content": text})
|
| 69 |
+
chat_history.append({"role": "assistant", "content": response or "[No response generated]"})
|
| 70 |
return "", chat_history
|
| 71 |
except Exception as e:
|
| 72 |
+
return "", chat_history + [{"role": "user", "content": text}, {"role": "assistant", "content": f"โ ๏ธ Error: {e}"}]
|
|
|
|
| 73 |
|
| 74 |
def run_autonomous_training_and_update_ui():
|
| 75 |
+
yield "๐ Initializing From-Scratch Trainer..."
|
|
|
|
|
|
|
|
|
|
| 76 |
for stage in [1, 2, 3]:
|
| 77 |
ckpt_path = f"{CHECKPOINT_ROOT}/stage_{stage}"
|
|
|
|
| 78 |
if os.path.exists(os.path.join(ckpt_path, "config.json")):
|
| 79 |
status_message = f"โญ๏ธ Stage {stage} already trained โ loading..."
|
| 80 |
yield status_message
|
| 81 |
load_model_for_stage(stage)
|
| 82 |
continue
|
| 83 |
|
| 84 |
+
status_message = f"โถ๏ธ AUTO-TRAINING FROM SCRATCH: Stage {stage}"
|
| 85 |
yield status_message
|
|
|
|
| 86 |
try:
|
|
|
|
| 87 |
train_vlm_stage(stage, ckpt_path)
|
| 88 |
status_message = f"โ
Stage {stage} completed! Loading new model..."
|
| 89 |
yield status_message
|
| 90 |
load_model_for_stage(stage)
|
| 91 |
except Exception as e:
|
| 92 |
status_message = f"โ Stage {stage} failed: {e}"
|
| 93 |
+
yield status_message; raise e # Stop execution on failure
|
| 94 |
+
yield "๐ COCONUT-VLM Training Complete โ All 3 Stages Finished!"
|
|
|
|
| 95 |
|
| 96 |
+
with gr.Blocks(title="๐ฅฅ COCONUT-VLM From Scratch") as demo:
|
| 97 |
+
gr.Markdown("# ๐ฅฅ COCONUT-VLM: Autonomous Trainer (From Scratch)")
|
| 98 |
+
gr.Markdown("Model is training itself **from random initialization**. You can interact with the latest trained model.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
with gr.Row():
|
| 100 |
with gr.Column(scale=1):
|
| 101 |
+
status = gr.Textbox(label="Training Status", value="Waiting to start...", interactive=False, lines=10)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
with gr.Column(scale=2):
|
| 103 |
image_input = gr.Image(type="pil", label="Upload Image")
|
| 104 |
chatbot = gr.Chatbot(label="Chat with the VLM", height=400)
|
| 105 |
+
msg = gr.Textbox(label="Ask a question")
|
| 106 |
clear = gr.Button("Clear Chat")
|
|
|
|
| 107 |
msg.submit(chat_with_image, [image_input, msg, chatbot], [msg, chatbot])
|
| 108 |
clear.click(lambda: (None, None, []), None, [image_input, msg, chatbot])
|
|
|
|
| 109 |
demo.load(fn=run_autonomous_training_and_update_ui, inputs=None, outputs=status)
|
| 110 |
|
| 111 |
demo.queue().launch(debug=True)
|