File size: 10,012 Bytes
2cb3b95 | 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 | from flask import Flask, request, jsonify, render_template
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision import transforms
from PIL import Image
import io
import json
import time
import os
import sys
from pathlib import Path
# ββ CPU Inference Optimizations βββββββββββββββββββββββββββββββββββββββββββββ
# Limit threads to avoid over-subscription on constrained HF Spaces hardware
_NUM_THREADS = int(os.environ.get("OMP_NUM_THREADS", "2"))
torch.set_num_threads(_NUM_THREADS)
torch.set_num_interop_threads(1) # single inter-op thread for small batch inference
# Globally disable gradient tracking β we never train in this app
torch.set_grad_enabled(False)
# ββ Paths ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
BASE_DIR = Path(__file__).parent.resolve()
app = Flask(__name__, template_folder=str(BASE_DIR / "templates"))
# ββ CIFAR-10 Classes ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
CLASSES = ["airplane", "automobile", "bird", "cat", "deer",
"dog", "frog", "horse", "ship", "truck"]
# ββ Model Definition ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
class PatchEmbedding(nn.Module):
def __init__(self, img_size=32, patch_size=4, in_channels=3, embed_dim=256):
super().__init__()
self.proj = nn.Conv2d(in_channels, embed_dim, kernel_size=patch_size, stride=patch_size)
num_patches = (img_size // patch_size) ** 2
self.cls_token = nn.Parameter(torch.randn(1, 1, embed_dim))
self.pos_embed = nn.Parameter(torch.randn(1, 1 + num_patches, embed_dim))
def forward(self, x):
B = x.size(0)
x = self.proj(x).flatten(2).transpose(1, 2)
cls_token = self.cls_token.expand(B, -1, -1)
x = torch.cat((cls_token, x), dim=1) + self.pos_embed
return x
class MLP(nn.Module):
def __init__(self, in_features, hidden_features, drop_rate):
super().__init__()
self.fc1 = nn.Linear(in_features, hidden_features)
self.fc2 = nn.Linear(hidden_features, in_features)
self.dropout = nn.Dropout(drop_rate)
def forward(self, x):
return self.dropout(self.fc2(self.dropout(F.gelu(self.fc1(x)))))
class TransformerEncoderBlock(nn.Module):
def __init__(self, embed_dim, num_heads, mlp_dim, drop_rate):
super().__init__()
self.norm1 = nn.LayerNorm(embed_dim)
self.attn = nn.MultiheadAttention(embed_dim, num_heads, dropout=drop_rate, batch_first=True)
self.norm2 = nn.LayerNorm(embed_dim)
self.mlp = MLP(embed_dim, mlp_dim, drop_rate)
def forward(self, x):
x = x + self.attn(self.norm1(x), self.norm1(x), self.norm1(x))[0]
x = x + self.mlp(self.norm2(x))
return x
class VisionTransformer(nn.Module):
def __init__(self, img_size=32, patch_size=4, in_channels=3, num_classes=10,
embed_dim=256, depth=20, num_heads=8, mlp_dim=512, drop_rate=0.1):
super().__init__()
self.patch_embed = PatchEmbedding(img_size, patch_size, in_channels, embed_dim)
self.encoder = nn.Sequential(*[TransformerEncoderBlock(embed_dim, num_heads, mlp_dim, drop_rate) for _ in range(depth)])
self.norm = nn.LayerNorm(embed_dim)
self.head = nn.Linear(embed_dim, num_classes)
def forward(self, x):
x = self.patch_embed(x)
x = self.encoder(x)
return self.head(self.norm(x)[:, 0])
# ββ Load Model ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
device = torch.device("cpu")
model = VisionTransformer()
model_path = BASE_DIR / "cifar10_model.pth"
if not model_path.exists():
print(f"[ERROR] Model file not found at {model_path}", file=sys.stderr)
sys.exit(1)
try:
# weights_only=True is required in PyTorch >= 2.0 for safe loading
state_dict = torch.load(model_path, map_location=device, weights_only=True)
except Exception:
# Fallback for older checkpoints saved without safe tensors
state_dict = torch.load(model_path, map_location=device)
model.load_state_dict(state_dict)
model.eval()
print(f"[OK] Model loaded from {model_path}")
print(f" Parameters: {sum(p.numel() for p in model.parameters()):,}")
# ββ Image Transform βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
transform = transforms.Compose([
transforms.Resize((32, 32)),
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
])
# ββ Flask Config ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Limit upload size to 16 MB to prevent memory issues on HF Spaces free tier
app.config["MAX_CONTENT_LENGTH"] = 16 * 1024 * 1024
# ββ Routes ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@app.route("/")
def index():
return render_template("index.html")
@app.route("/predict", methods=["POST"])
def predict():
if "file" not in request.files:
return jsonify({"error": "No file uploaded"}), 400
file = request.files["file"]
if file.filename == "":
return jsonify({"error": "Empty filename"}), 400
try:
# ββ Step 1: Read raw bytes robustly βββββββββββββββββββββββββββββββββ
# Reset the stream pointer β gunicorn/Werkzeug may have consumed it
# during multipart parsing. Try both the Werkzeug FileStorage seek
# and the underlying stream directly.
try:
file.seek(0)
except Exception:
pass
try:
file.stream.seek(0)
except Exception:
pass
img_bytes = file.read()
# Debug: log what we actually received
byte_count = len(img_bytes)
magic = img_bytes[:8].hex() if img_bytes else "empty"
print(f"[PREDICT] filename={file.filename!r} bytes={byte_count} magic={magic}")
if byte_count == 0:
return jsonify({
"error": "Server received 0 bytes. The upload stream was empty. "
"Try a smaller image (< 5 MB) or a different format."
}), 400
# ββ Step 2: Open with PIL βββββββββββββββββββββββββββββββββββββββββββββ
try:
img = Image.open(io.BytesIO(img_bytes))
img.load() # force eager decode while BytesIO is still alive
img = img.convert("RGB")
except Exception as pil_err:
return jsonify({
"error": f"Cannot read image ({pil_err}). "
"Please upload a valid JPEG, PNG, WEBP, or BMP file."
}), 400
# ββ Step 3: Inference ββββββββββββββββββββββββββββββββββββββββββββββββ
t0_preprocess = time.time()
tensor = transform(img).unsqueeze(0).to(device)
preprocess_ms = round((time.time() - t0_preprocess) * 1000, 2)
t0 = time.time()
with torch.inference_mode(): # faster than torch.no_grad() on CPU
logits = model(tensor)
probs = F.softmax(logits, dim=1).squeeze(0)
inference_ms = round((time.time() - t0) * 1000, 2)
print(f"[PREDICT] preprocess={preprocess_ms}ms inference={inference_ms}ms")
sys.stdout.flush()
results = sorted(
[{"class": CLASSES[i], "probability": float(probs[i])} for i in range(10)],
key=lambda x: x["probability"], reverse=True
)
return jsonify({
"top_class": results[0]["class"],
"top_probability": results[0]["probability"],
"all_predictions": results,
"inference_ms": inference_ms
})
except Exception as e:
import traceback
traceback.print_exc()
return jsonify({"error": str(e)}), 500
@app.errorhandler(413)
def too_large(e):
return jsonify({"error": "File too large. Maximum size is 16 MB."}), 413
@app.route("/model-info")
def model_info():
return jsonify({
"architecture": "Vision Transformer (ViT)",
"parameters": sum(p.numel() for p in model.parameters()),
"depth": 20,
"embed_dim": 256,
"num_heads": 8,
"patch_size": "4Γ4",
"input_size": "32Γ32",
"classes": CLASSES,
"train_accuracy": "72.59%",
"test_accuracy": "70.51%",
"epochs": 25,
})
# ββ Run ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
if __name__ == "__main__":
port = int(os.environ.get("PORT", 5000))
host = "0.0.0.0" # bind to all interfaces (required for Docker / HF Spaces)
debug = os.environ.get("FLASK_DEBUG", "0") == "1"
app.run(debug=debug, host=host, port=port)
|