Nausad commited on
Commit
2cb3b95
Β·
verified Β·
1 Parent(s): cb11ea2

Upload 2 files

Browse files
Files changed (2) hide show
  1. Dockerfile +67 -0
  2. app.py +223 -0
Dockerfile ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ─── Stage 1: Base Image ───────────────────────────────────────────────────
2
+ FROM python:3.10-slim
3
+
4
+ # Set working directory
5
+ WORKDIR /app
6
+
7
+ # ─── Environment Variables ─────────────────────────────────────────────────
8
+ # Prevent Python from writing .pyc files
9
+ ENV PYTHONDONTWRITEBYTECODE=1
10
+ # Prevent Python from buffering stdout/stderr
11
+ ENV PYTHONUNBUFFERED=1
12
+ # HuggingFace Spaces runs on port 7860
13
+ ENV PORT=7860
14
+ # Pin CPU threads β€” prevents over-subscription on HF free-tier (2 vCPUs)
15
+ ENV OMP_NUM_THREADS=2
16
+ ENV MKL_NUM_THREADS=2
17
+
18
+ # ─── Create a non-root user FIRST (HuggingFace requirement) ────────────────
19
+ RUN useradd -m -u 1000 appuser
20
+
21
+ # ─── Install System Dependencies ───────────────────────────────────────────
22
+ RUN apt-get update && apt-get install -y --no-install-recommends \
23
+ libglib2.0-0 \
24
+ libsm6 \
25
+ libxrender1 \
26
+ libxext6 \
27
+ && apt-get clean \
28
+ && rm -rf /var/lib/apt/lists/*
29
+
30
+ # ─── Install Python Dependencies ───────────────────────────────────────────
31
+ COPY requirements.txt .
32
+
33
+ # Use CPU-only PyTorch index to keep image lean and avoid CUDA download timeouts
34
+ RUN pip install --no-cache-dir \
35
+ --extra-index-url https://download.pytorch.org/whl/cpu \
36
+ -r requirements.txt
37
+
38
+ # ─── Copy Application Files ────────────────────────────────────────────────
39
+ COPY app.py .
40
+ COPY cifar10_model.pth .
41
+ COPY templates/ ./templates/
42
+
43
+ # ─── Fix file ownership so appuser can read all files ──────────────────────
44
+ RUN chown -R appuser:appuser /app
45
+
46
+ # ─── Switch to non-root user ───────────────────────────────────────────────
47
+ USER appuser
48
+
49
+ # ─── Expose Port ───────────────────────────────────────────────────────────
50
+ EXPOSE 7860
51
+
52
+ # ─── Launch with Gunicorn (production WSGI server) ─────────────────────────
53
+ # --worker-class gthread: Uses a threaded worker so the heartbeat thread
54
+ # stays alive during long CPU inference (sync workers block the heartbeat
55
+ # and get killed by the arbiter even when timeout is set high).
56
+ # --threads 2: One thread handles the request, the other keeps heartbeat alive.
57
+ # --timeout 300: Safety net for very slow inference on free-tier CPUs.
58
+ # --preload: Load the model once before forking (saves memory).
59
+ CMD ["gunicorn", \
60
+ "--bind", "0.0.0.0:7860", \
61
+ "--workers", "1", \
62
+ "--worker-class", "gthread", \
63
+ "--threads", "2", \
64
+ "--timeout", "300", \
65
+ "--preload", \
66
+ "--log-level", "info", \
67
+ "app:app"]
app.py ADDED
@@ -0,0 +1,223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask, request, jsonify, render_template
2
+ import torch
3
+ import torch.nn as nn
4
+ import torch.nn.functional as F
5
+ from torchvision import transforms
6
+ from PIL import Image
7
+ import io
8
+ import json
9
+ import time
10
+ import os
11
+ import sys
12
+ from pathlib import Path
13
+
14
+ # ── CPU Inference Optimizations ─────────────────────────────────────────────
15
+ # Limit threads to avoid over-subscription on constrained HF Spaces hardware
16
+ _NUM_THREADS = int(os.environ.get("OMP_NUM_THREADS", "2"))
17
+ torch.set_num_threads(_NUM_THREADS)
18
+ torch.set_num_interop_threads(1) # single inter-op thread for small batch inference
19
+ # Globally disable gradient tracking β€” we never train in this app
20
+ torch.set_grad_enabled(False)
21
+
22
+ # ── Paths ──────────────────────────────────────────────────────────────────
23
+ BASE_DIR = Path(__file__).parent.resolve()
24
+
25
+ app = Flask(__name__, template_folder=str(BASE_DIR / "templates"))
26
+
27
+ # ── CIFAR-10 Classes ────────────────────────────────────────────────────────
28
+ CLASSES = ["airplane", "automobile", "bird", "cat", "deer",
29
+ "dog", "frog", "horse", "ship", "truck"]
30
+
31
+ # ── Model Definition ────────────────────────────────────────────────────────
32
+ class PatchEmbedding(nn.Module):
33
+ def __init__(self, img_size=32, patch_size=4, in_channels=3, embed_dim=256):
34
+ super().__init__()
35
+ self.proj = nn.Conv2d(in_channels, embed_dim, kernel_size=patch_size, stride=patch_size)
36
+ num_patches = (img_size // patch_size) ** 2
37
+ self.cls_token = nn.Parameter(torch.randn(1, 1, embed_dim))
38
+ self.pos_embed = nn.Parameter(torch.randn(1, 1 + num_patches, embed_dim))
39
+
40
+ def forward(self, x):
41
+ B = x.size(0)
42
+ x = self.proj(x).flatten(2).transpose(1, 2)
43
+ cls_token = self.cls_token.expand(B, -1, -1)
44
+ x = torch.cat((cls_token, x), dim=1) + self.pos_embed
45
+ return x
46
+
47
+ class MLP(nn.Module):
48
+ def __init__(self, in_features, hidden_features, drop_rate):
49
+ super().__init__()
50
+ self.fc1 = nn.Linear(in_features, hidden_features)
51
+ self.fc2 = nn.Linear(hidden_features, in_features)
52
+ self.dropout = nn.Dropout(drop_rate)
53
+
54
+ def forward(self, x):
55
+ return self.dropout(self.fc2(self.dropout(F.gelu(self.fc1(x)))))
56
+
57
+ class TransformerEncoderBlock(nn.Module):
58
+ def __init__(self, embed_dim, num_heads, mlp_dim, drop_rate):
59
+ super().__init__()
60
+ self.norm1 = nn.LayerNorm(embed_dim)
61
+ self.attn = nn.MultiheadAttention(embed_dim, num_heads, dropout=drop_rate, batch_first=True)
62
+ self.norm2 = nn.LayerNorm(embed_dim)
63
+ self.mlp = MLP(embed_dim, mlp_dim, drop_rate)
64
+
65
+ def forward(self, x):
66
+ x = x + self.attn(self.norm1(x), self.norm1(x), self.norm1(x))[0]
67
+ x = x + self.mlp(self.norm2(x))
68
+ return x
69
+
70
+ class VisionTransformer(nn.Module):
71
+ def __init__(self, img_size=32, patch_size=4, in_channels=3, num_classes=10,
72
+ embed_dim=256, depth=20, num_heads=8, mlp_dim=512, drop_rate=0.1):
73
+ super().__init__()
74
+ self.patch_embed = PatchEmbedding(img_size, patch_size, in_channels, embed_dim)
75
+ self.encoder = nn.Sequential(*[TransformerEncoderBlock(embed_dim, num_heads, mlp_dim, drop_rate) for _ in range(depth)])
76
+ self.norm = nn.LayerNorm(embed_dim)
77
+ self.head = nn.Linear(embed_dim, num_classes)
78
+
79
+ def forward(self, x):
80
+ x = self.patch_embed(x)
81
+ x = self.encoder(x)
82
+ return self.head(self.norm(x)[:, 0])
83
+
84
+ # ── Load Model ──────────────────────────────────────────────────────────────
85
+ device = torch.device("cpu")
86
+ model = VisionTransformer()
87
+
88
+ model_path = BASE_DIR / "cifar10_model.pth"
89
+ if not model_path.exists():
90
+ print(f"[ERROR] Model file not found at {model_path}", file=sys.stderr)
91
+ sys.exit(1)
92
+
93
+ try:
94
+ # weights_only=True is required in PyTorch >= 2.0 for safe loading
95
+ state_dict = torch.load(model_path, map_location=device, weights_only=True)
96
+ except Exception:
97
+ # Fallback for older checkpoints saved without safe tensors
98
+ state_dict = torch.load(model_path, map_location=device)
99
+
100
+ model.load_state_dict(state_dict)
101
+ model.eval()
102
+ print(f"[OK] Model loaded from {model_path}")
103
+ print(f" Parameters: {sum(p.numel() for p in model.parameters()):,}")
104
+
105
+ # ── Image Transform ──────────────────────────────────────────────────────���──
106
+ transform = transforms.Compose([
107
+ transforms.Resize((32, 32)),
108
+ transforms.ToTensor(),
109
+ transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
110
+ ])
111
+
112
+ # ── Flask Config ────────────────────────────────────────────────────────────
113
+ # Limit upload size to 16 MB to prevent memory issues on HF Spaces free tier
114
+ app.config["MAX_CONTENT_LENGTH"] = 16 * 1024 * 1024
115
+
116
+ # ── Routes ──────────────────────────────────────────────────────────────────
117
+ @app.route("/")
118
+ def index():
119
+ return render_template("index.html")
120
+
121
+ @app.route("/predict", methods=["POST"])
122
+ def predict():
123
+ if "file" not in request.files:
124
+ return jsonify({"error": "No file uploaded"}), 400
125
+
126
+ file = request.files["file"]
127
+ if file.filename == "":
128
+ return jsonify({"error": "Empty filename"}), 400
129
+
130
+ try:
131
+ # ── Step 1: Read raw bytes robustly ─────────────────────────────────
132
+ # Reset the stream pointer β€” gunicorn/Werkzeug may have consumed it
133
+ # during multipart parsing. Try both the Werkzeug FileStorage seek
134
+ # and the underlying stream directly.
135
+ try:
136
+ file.seek(0)
137
+ except Exception:
138
+ pass
139
+ try:
140
+ file.stream.seek(0)
141
+ except Exception:
142
+ pass
143
+
144
+ img_bytes = file.read()
145
+
146
+ # Debug: log what we actually received
147
+ byte_count = len(img_bytes)
148
+ magic = img_bytes[:8].hex() if img_bytes else "empty"
149
+ print(f"[PREDICT] filename={file.filename!r} bytes={byte_count} magic={magic}")
150
+
151
+ if byte_count == 0:
152
+ return jsonify({
153
+ "error": "Server received 0 bytes. The upload stream was empty. "
154
+ "Try a smaller image (< 5 MB) or a different format."
155
+ }), 400
156
+
157
+ # ── Step 2: Open with PIL ─────────────────────────────────────────────
158
+ try:
159
+ img = Image.open(io.BytesIO(img_bytes))
160
+ img.load() # force eager decode while BytesIO is still alive
161
+ img = img.convert("RGB")
162
+ except Exception as pil_err:
163
+ return jsonify({
164
+ "error": f"Cannot read image ({pil_err}). "
165
+ "Please upload a valid JPEG, PNG, WEBP, or BMP file."
166
+ }), 400
167
+
168
+ # ── Step 3: Inference ────────────────────────────────────────────────
169
+ t0_preprocess = time.time()
170
+ tensor = transform(img).unsqueeze(0).to(device)
171
+ preprocess_ms = round((time.time() - t0_preprocess) * 1000, 2)
172
+
173
+ t0 = time.time()
174
+ with torch.inference_mode(): # faster than torch.no_grad() on CPU
175
+ logits = model(tensor)
176
+ probs = F.softmax(logits, dim=1).squeeze(0)
177
+ inference_ms = round((time.time() - t0) * 1000, 2)
178
+
179
+ print(f"[PREDICT] preprocess={preprocess_ms}ms inference={inference_ms}ms")
180
+ sys.stdout.flush()
181
+
182
+ results = sorted(
183
+ [{"class": CLASSES[i], "probability": float(probs[i])} for i in range(10)],
184
+ key=lambda x: x["probability"], reverse=True
185
+ )
186
+ return jsonify({
187
+ "top_class": results[0]["class"],
188
+ "top_probability": results[0]["probability"],
189
+ "all_predictions": results,
190
+ "inference_ms": inference_ms
191
+ })
192
+
193
+ except Exception as e:
194
+ import traceback
195
+ traceback.print_exc()
196
+ return jsonify({"error": str(e)}), 500
197
+
198
+ @app.errorhandler(413)
199
+ def too_large(e):
200
+ return jsonify({"error": "File too large. Maximum size is 16 MB."}), 413
201
+
202
+ @app.route("/model-info")
203
+ def model_info():
204
+ return jsonify({
205
+ "architecture": "Vision Transformer (ViT)",
206
+ "parameters": sum(p.numel() for p in model.parameters()),
207
+ "depth": 20,
208
+ "embed_dim": 256,
209
+ "num_heads": 8,
210
+ "patch_size": "4Γ—4",
211
+ "input_size": "32Γ—32",
212
+ "classes": CLASSES,
213
+ "train_accuracy": "72.59%",
214
+ "test_accuracy": "70.51%",
215
+ "epochs": 25,
216
+ })
217
+
218
+ # ── Run ──────────────────────────────────────────────────────────────────────
219
+ if __name__ == "__main__":
220
+ port = int(os.environ.get("PORT", 5000))
221
+ host = "0.0.0.0" # bind to all interfaces (required for Docker / HF Spaces)
222
+ debug = os.environ.get("FLASK_DEBUG", "0") == "1"
223
+ app.run(debug=debug, host=host, port=port)