-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathreconstruct.py
More file actions
198 lines (148 loc) · 6 KB
/
reconstruct.py
File metadata and controls
198 lines (148 loc) · 6 KB
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
#!/usr/bin/env python3
"""
RAE Image Reconstruction Script
This script loads a pre-trained RAE-SigLIP model and reconstructs a fixed COCO image.
The reconstructed image is saved to the specified output path.
Usage:
python reconstruct.py --model_path /path/to/model --output_path /path/to/output.png
"""
import argparse
import os
from pathlib import Path
import torch
from torchvision.transforms.functional import to_pil_image
from transformers import AutoProcessor
from transformers.image_utils import load_image
from lmms_engine.models.rae_siglip.modeling_rae_siglip import RaeSiglipModel
def parse_args():
"""Parse command line arguments."""
parser = argparse.ArgumentParser(
description="Reconstruct an image using a pre-trained RAE-SigLIP model",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=__doc__,
)
parser.add_argument(
"--model_path",
type=str,
required=True,
help="Path to the pre-trained model checkpoint directory",
)
parser.add_argument(
"--output_path",
type=str,
required=True,
help="Path where the reconstructed image will be saved",
)
parser.add_argument(
"--use_ema",
action="store_true",
help="Use EMA (Exponential Moving Average) weights for inference (recommended for better quality)",
)
return parser.parse_args()
def load_ema_weights(model, ema_state_path: str):
"""Load EMA weights into the model."""
try:
print(f"Loading EMA weights from: {ema_state_path}")
ema_state = torch.load(ema_state_path, map_location="cpu")
# Load EMA weights into model
with torch.no_grad():
for name, param in model.named_parameters():
if name in ema_state:
param.copy_(ema_state[name])
else:
print(f"Warning: EMA state missing for parameter: {name}")
print("EMA weights loaded successfully!")
return model
except Exception as e:
print(f"Error loading EMA weights: {e}")
print("Continuing with regular model weights...")
return model
def load_model_and_processor(model_path: str, use_ema: bool = False):
"""Load the RAE model and processor from the checkpoint path."""
try:
print(f"Loading model from: {model_path}")
model = RaeSiglipModel.from_pretrained(model_path)
# Load EMA weights if requested
if use_ema:
ema_path = os.path.join(model_path, "ema_state.pt")
if os.path.exists(ema_path):
model = load_ema_weights(model, ema_path)
else:
print(f"Warning: EMA weights not found at {ema_path}")
print("Using regular model weights instead.")
print("Loading processor...")
processor = AutoProcessor.from_pretrained(model_path)
print("Model and processor loaded successfully!")
return model, processor
except Exception as e:
print(f"Error loading model or processor: {e}")
print(f"Make sure the model path '{model_path}' is correct and contains the required files.")
exit(1)
def load_input_image():
"""Load the fixed COCO input image from URL."""
try:
print("Loading COCO image from URL...")
image_url = "https://huggingface.co/datasets/merve/coco/resolve/main/val2017/000000000285.jpg"
image = load_image(image_url)
print(f"Image loaded successfully! Size: {image.size}, Mode: {image.mode}")
return image
except Exception as e:
print(f"Error loading image from URL: {e}")
print("Make sure you have internet connection and the URL is accessible.")
exit(1)
def reconstruct_image(model, processor, image, device):
"""Reconstruct the image using the RAE model."""
print("Processing image with model...")
# Set model to evaluation mode
model.eval()
# Prepare inputs
inputs = processor(images=[image], return_tensors="pt")
# Move inputs to the same device as the model
if hasattr(model, "device"):
inputs = {k: v.to(model.device) for k, v in inputs.items()}
else:
inputs = {k: v.to(device) for k, v in inputs.items()}
# Run inference
with torch.no_grad():
outputs = model(**inputs)
print("Image reconstruction completed!")
return outputs
def save_reconstructed_image(outputs, output_path: str):
"""Save the reconstructed image to the specified path."""
try:
print(f"Saving reconstructed image to: {output_path}")
# Extract the reconstructed pixels
out_pixels = outputs.out_pixels.squeeze(0)
# The model already outputs in [0, 1] range after denormalization
# No need to convert from [-1, 1] - just clamp to ensure valid range
img_tensor = out_pixels.clamp(0, 1)
# Convert to PIL image
img = to_pil_image(img_tensor)
# Ensure output directory exists
output_file = Path(output_path)
output_file.parent.mkdir(parents=True, exist_ok=True)
# Save the image
img.save(output_path)
print(f"Reconstructed image saved successfully to: {output_path}")
except Exception as e:
print(f"Error saving reconstructed image: {e}")
exit(1)
def main():
"""Main function to run the image reconstruction pipeline."""
# Parse command line arguments
args = parse_args()
# Load model and processor
model, processor = load_model_and_processor(args.model_path, use_ema=args.use_ema)
# Load input image
input_image = load_input_image()
# Determine device
device = "cuda" if torch.cuda.is_available() else "cpu"
model = model.to(device)
print(f"Using device: {device}")
# Reconstruct the image
outputs = reconstruct_image(model, processor, input_image, device)
# Save the reconstructed image
save_reconstructed_image(outputs, args.output_path)
print("Image reconstruction pipeline completed successfully!")
if __name__ == "__main__":
main()