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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da49528
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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
# patch gradio_client bug β€” "const" in bool raises TypeError
import gradio_client.utils as _gcu
_original_get_type = _gcu.get_type

def _patched_get_type(schema):
    if not isinstance(schema, dict):
        return "Any"
    return _original_get_type(schema)

_gcu.get_type = _patched_get_type

# now import gradio normally
import gradio as gr
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.transforms.functional as TF
import math
import numpy as np
from PIL import Image



class PatchEmbedding(nn.Module):
    def __init__(self, in_channels=3, embed_dim=192, patch_size=4, img_size=64):
        super().__init__()
        self.in_channels = in_channels
        self.embed_dim   = embed_dim
        num_patches      = (img_size // patch_size) ** 2
        self.proj        = nn.Conv2d(in_channels, embed_dim, kernel_size=patch_size, stride=patch_size)
        self.pos_embed   = nn.Parameter(torch.randn(1, num_patches, embed_dim) * 0.02)
        nn.init.trunc_normal_(self.proj.weight, std=0.02)
        nn.init.zeros_(self.proj.bias)

    def forward(self, x):
        x = self.proj(x)        # [B,3,64,64] β†’ [B,192,16,16]
        x = x.flatten(2)        # β†’ [B,192,256]
        x = x.transpose(1, 2)   # β†’ [B,256,192]
        x = x + self.pos_embed
        return x


class MultiHeadSelfAttention(nn.Module):
    def __init__(self, embed_dim=192, num_heads=6, attn_drop=0.1):
        super().__init__()
        assert embed_dim % num_heads == 0, \
            f"embed_dim {embed_dim} must be divisible by num_heads {num_heads}"
        self.embed_dim = embed_dim
        self.num_heads = num_heads
        self.head_dim  = embed_dim // num_heads
        self.q_proj    = nn.Linear(embed_dim, embed_dim)
        self.k_proj    = nn.Linear(embed_dim, embed_dim)
        self.v_proj    = nn.Linear(embed_dim, embed_dim)
        self.out_proj  = nn.Linear(embed_dim, embed_dim)
        self.attn_drop = nn.Dropout(attn_drop)

    def forward(self, x):
        q = self.q_proj(x)
        k = self.k_proj(x)
        v = self.v_proj(x)
        B, N, D = q.shape
        q = q.reshape(B, N, self.num_heads, self.head_dim).transpose(1, 2)
        k = k.reshape(B, N, self.num_heads, self.head_dim).transpose(1, 2)
        v = v.reshape(B, N, self.num_heads, self.head_dim).transpose(1, 2)
        scores  = (q @ k.transpose(2, 3)) / math.sqrt(self.head_dim)
        weights = self.attn_drop(F.softmax(scores, dim=-1))
        output  = (weights @ v).transpose(1, 2).contiguous()
        output  = output.reshape(B, N, self.embed_dim)
        output  = self.out_proj(output)
        return output

class GDFN(nn.Module):
    def __init__(self, embed_dim, ffn_expansion = 4, grid_size = 16):
        super().__init__()
        self.embed_dim = embed_dim
        self.ffn_expansion = ffn_expansion
        self.grid_size = grid_size
        self.hidden = embed_dim * ffn_expansion

        self.g_proj = nn.Linear(embed_dim, 2*self.hidden)
        self.path_1 = nn.Conv2d(self.hidden, self.hidden, 3, padding=1, groups=self.hidden)
        self.path_2 = nn.Conv2d(self.hidden, self.hidden, 3, padding=1, groups=self.hidden)

        self.out_proj = nn.Linear(self.hidden, embed_dim)

    
    def forward(self, x):
        x = self.g_proj(x)
        x1, x2 = x.chunk(2, dim=-1)
        B, N, C = x1.shape
        x1 = x1.transpose(1,2).reshape(B, C, self.grid_size, self.grid_size)
        x2 = x2.transpose(1,2).reshape(B, C, self.grid_size, self.grid_size) 
        x1 = self.path_1(x1)
        x2 = self.path_2(x2)
        x1 = x1.flatten(2).transpose(1,2)
        x2 = x2.flatten(2).transpose(1,2)
        x = x1 * F.gelu(x2)
        x = self.out_proj(x)
        return x


class TransformerBlock(nn.Module):
    def __init__(self, embed_dim=192, num_heads=6, attn_drop=0.1):
        super().__init__()
        self.norm1  = nn.LayerNorm(embed_dim)
        self.norm2  = nn.LayerNorm(embed_dim)
        self.attn   = MultiHeadSelfAttention(embed_dim, num_heads, attn_drop)
        self.ffn = GDFN(embed_dim)
        self.gamma1 = nn.Parameter(1e-4 * torch.ones(embed_dim))
        self.gamma2 = nn.Parameter(1e-4 * torch.ones(embed_dim))

    def forward(self, x):
        x = x + self.gamma1 * self.attn(self.norm1(x))
        x = x + self.gamma2 * self.ffn(self.norm2(x))
        return x


class ImageSRTransformer(nn.Module):
    def __init__(self,
                 embed_dims=[192, 256, 288, 384],
                 num_heads=[6, 8, 6, 8],
                 depths=[3, 3, 3, 3],
                 patch_size=4,
                 img_size=64):
        super().__init__()

        self.embed_dims = embed_dims
        self.grid_size = img_size // patch_size 

        self.patch_embed = PatchEmbedding(embed_dim=embed_dims[0], patch_size=patch_size, img_size=img_size)
        self.stages = nn.ModuleList([
                            nn.ModuleList([TransformerBlock(embed_dims[i], num_heads[i]) 
                                           for _ in range(depths[i])]) for i in range(len(embed_dims))])
        
        self.projections = nn.ModuleList([
            nn.Linear(embed_dims[i], embed_dims[i+1])
                    for i in range(len(embed_dims) - 1)
                    ])

        self.head = nn.Sequential(
            nn.Conv2d(1120, 192, 3, padding=1),
            nn.LeakyReLU(0.2),
            nn.Conv2d(192, 768, 3, padding=1),
            nn.PixelShuffle(2),
            nn.Conv2d(192, 768, 3, padding=1),
            nn.PixelShuffle(2),
            nn.Conv2d(192, 768, 3, padding=1),
            nn.PixelShuffle(2),
            nn.Conv2d(192, 768, 3, padding=1),
            nn.PixelShuffle(2),
            nn.Conv2d(192, 3, 3, padding=1)
        )

    def forward(self, x):
        lr = x
        x = self.patch_embed(x)
        stage_outputs = []

        for i, stage in enumerate(self.stages):
            for block in stage:
                x = block(x)
            stage_outputs.append(x)
            if i < len(self.stages) -1:
                x = self.projections[i](x)

        x = torch.cat(stage_outputs, dim=-1)
        B, N, C = x.shape
        x = x.transpose(1,2).reshape(B, C, self.grid_size, self.grid_size)
        x = self.head(x)
        base = F.interpolate(lr, size=(256, 256), mode="bicubic", align_corners=False)
        return base + x


def psnr(pred, target):
    mse = torch.mean((pred - target) ** 2)
    return 10 * torch.log10(1.0 / (mse + 1e-8))


def ssim(pred, target, window_size=11):
    C1 = 0.01 ** 2
    C2 = 0.03 ** 2
    mu1     = F.avg_pool2d(pred,        window_size, 1, window_size // 2)
    mu2     = F.avg_pool2d(target,      window_size, 1, window_size // 2)
    mu1_sq  = mu1 ** 2
    mu2_sq  = mu2 ** 2
    mu1_mu2 = mu1 * mu2
    s1  = F.avg_pool2d(pred ** 2,     window_size, 1, window_size // 2) - mu1_sq
    s2  = F.avg_pool2d(target ** 2,   window_size, 1, window_size // 2) - mu2_sq
    s12 = F.avg_pool2d(pred * target, window_size, 1, window_size // 2) - mu1_mu2
    num = (2 * mu1_mu2 + C1) * (2 * s12   + C2)
    den = (mu1_sq + mu2_sq + C1) * (s1 + s2 + C2)
    return (num / den).mean().item()


# ── Load model ────────────────────────────────────────────────────────────────
model = ImageSRTransformer()
checkpoint = torch.load(
    "sr_best_v4_resumed.pt",
    map_location="cpu",
    weights_only=False
)
model.load_state_dict(checkpoint["model_state_dict"])
model.eval()
print(f"Model loaded β€” val PSNR: {checkpoint['val_psnr']:.2f} dB")


# ── Inference ─────────────────────────────────────────────────────────────────
def run_sr(img_pil):
    device = "cuda" if torch.cuda.is_available() else "cpu"
    model.to(device)

    w, h = img_pil.size
    if w < 256 or h < 256:
        scale = max(256 / w, 256 / h)
        img_pil = img_pil.resize(
            (int(w * scale), int(h * scale)), Image.BICUBIC)
        w, h = img_pil.size

    left = (w - 256) // 2
    top  = (h - 256) // 2
    gt   = img_pil.crop((left, top, left + 256, top + 256))
    lr   = gt.resize((64, 64), Image.BICUBIC)

    lr_t = TF.to_tensor(lr).unsqueeze(0).to(device)
    gt_t = TF.to_tensor(gt).unsqueeze(0).to(device)

    with torch.no_grad():
        with torch.autocast(device_type="cuda",
                            dtype=torch.bfloat16,
                            enabled=(device == "cuda")):
            sr_t = model(lr_t)
        sr_t = sr_t.float().clamp(0, 1)

    lr_display_t = F.interpolate(
        lr_t.float(), size=(256, 256),
        mode="bilinear", align_corners=False)

    psnr_lr = psnr(lr_display_t, gt_t).item()
    ssim_lr = ssim(lr_display_t, gt_t)
    psnr_sr = psnr(sr_t, gt_t).item()
    ssim_sr = ssim(sr_t, gt_t)

    def to_pil(t):
        return TF.to_pil_image(t.squeeze(0).cpu())

    metrics = (
        f"**LR baseline** β€” PSNR: {psnr_lr:.2f} dB | SSIM: {ssim_lr:.4f}\n\n"
        f"**SR output** β€” PSNR: {psnr_sr:.2f} dB | SSIM: {ssim_sr:.4f}\n\n"
        f"**Improvement** β€” Ξ”PSNR: +{psnr_sr - psnr_lr:.2f} dB | "
        f"Ξ”SSIM: +{ssim_sr - ssim_lr:.4f}"
    )

    return to_pil(lr_display_t), to_pil(sr_t), gt, metrics


# ── Example images ────────────────────────────────────────────────────────────
# 6 examples chosen to showcase V4 strengths:
# structured geometry, satellite textures, fine text edges,
# smooth skin + sharp boundary, urban grid, natural foliage
EXAMPLES = [
    ["examples/urban.png"],
    ["examples/aerial.png"],
    ["examples/architecture.png"],
    ["examples/nature.png"],
    ["examples/portrait.png"],
    ["examples/texture.png"],
]


# ── CSS ───────────────────────────────────────────────────────────────────────
CSS = """
/* ── Global ── */
body, .gradio-container {
    background: #0a0c10 !important;
    color: #c9d1d9 !important;
    font-family: 'Inter', system-ui, sans-serif !important;
}

/* ── Header ── */
.header-block {
    text-align: center;
    padding: 2rem 1rem 1rem;
    border-bottom: 1px solid #1e2128;
    margin-bottom: 1.5rem;
}
.header-title {
    font-size: 1.8rem;
    font-weight: 700;
    color: #2dd4bf;
    letter-spacing: -0.02em;
    margin-bottom: 0.25rem;
}
.header-sub {
    font-size: 0.85rem;
    color: #6e7681;
    margin-bottom: 0.5rem;
}
.header-author {
    font-size: 0.8rem;
    color: #3a3f4a;
}
.header-author span {
    color: #2dd4bf;
}

/* ── Metric output ── */
.metric-box textarea, .metric-box .prose {
    background: #111318 !important;
    border: 1px solid #1e2128 !important;
    color: #c9d1d9 !important;
    border-radius: 8px !important;
    font-family: 'JetBrains Mono', monospace !important;
    font-size: 0.82rem !important;
    padding: 12px !important;
}

/* ── Image labels ── */
.image-label {
    font-size: 0.75rem;
    color: #6e7681;
    text-align: center;
    margin-top: 4px;
    letter-spacing: 0.05em;
    text-transform: uppercase;
}

/* ── Buttons ── */
.run-btn {
    background: #2dd4bf !important;
    color: #0a0c10 !important;
    border: none !important;
    font-weight: 700 !important;
    font-size: 0.9rem !important;
    border-radius: 8px !important;
    padding: 0.6rem 2rem !important;
}
.run-btn:hover {
    background: #5eead4 !important;
}

/* ── Collapsible info ── */
.accordion {
    background: #111318 !important;
    border: 1px solid #1e2128 !important;
    border-radius: 8px !important;
    margin-top: 1.5rem !important;
}
.accordion .label-wrap {
    color: #6e7681 !important;
    font-size: 0.8rem !important;
    letter-spacing: 0.08em !important;
    text-transform: uppercase !important;
}

/* ── Image components ── */
.image-frame img {
    border-radius: 8px !important;
    border: 1px solid #1e2128 !important;
}

/* ── Upload zone ── */
.upload-button {
    background: #111318 !important;
    border: 1px dashed #2dd4bf !important;
    color: #2dd4bf !important;
    border-radius: 8px !important;
}

/* ── Examples ── */
.examples-holder {
    background: #111318 !important;
    border: 1px solid #1e2128 !important;
    border-radius: 8px !important;
}
"""


# ── Architecture info (collapsible) ──────────────────────────────────────────
ARCH_INFO = """

> "Isotropic constant-resolution hierarchical ViT with inter-stage dense feature aggregation β€” eliminating spatial bottlenecks while preserving coordinate integrity throughout all processing stages."

### Key architectural decisions

**Isotropic token grid** β€” constant 16Γ—16 spatial resolution across all 4 transformer stages. Zero patch merging, zero token downsampling. Every token maps to the same 4Γ—4 pixel region from input to output.

**Hierarchical embed dims [192 β†’ 256 β†’ 288 β†’ 384]** β€” representational capacity scales with feature complexity. Early stages learn local edges and textures (192-dim is sufficient). Deep stages reason about global scene semantics (384-dim is necessary).

**Inter-stage macro concatenation** β€” outputs from all 4 stages concatenated directly to the reconstruction head: `cat([h1, h2, h3, h4]) β†’ [B, 256, 1120]`. The head receives low-level edge maps (h1) and high-level semantic context (h4) simultaneously.

**GDFN feed-forward** β€” replaces standard MLPs with Gated Depthwise Feed-Forward Networks. Each token sees its 3Γ—3 spatial neighborhood during the MLP step. Local spatial context injected at every attention layer.

**Bilinear skip connection** β€” `output = F.interpolate(lr, 256Γ—256) + vit_residual`. Model learns residual correction only, not full reconstruction from scratch.

### Key deviation from DRCT
DRCT uses spatial downsampling and local block-level residuals. Dense-Iso-ViT maintains an isotropic constant token grid throughout β€” no spatial coordinate drift at any stage.

### Results
| Benchmark | PSNR | SSIM |
|-----------|------|------|
| DIV2K validation | 25.20 dB | 0.8298 |

"""


# ── Gradio UI ─────────────────────────────────────────────────────────────────
with gr.Blocks(css=CSS, title="Dense-Iso-ViT SR") as demo:

    # header
    gr.HTML("""
    <div class="header-block">
        <div class="header-title">Dense-Iso-ViT</div>
        <div class="header-sub">
            Constant-Resolution Hierarchical Vision Transformer for Γ—4 Image Super-Resolution
        </div>
        <div class="header-author">
            by <span>Sathya77</span> &nbsp;Β·&nbsp;
            23.8M params &nbsp;Β·&nbsp;
            24.11 dB LSDIR &nbsp;Β·&nbsp;
            25.20 dB DIV2K val
        </div>
    </div>
    """)

    with gr.Row():
        with gr.Column(scale=1):
            input_img = gr.Image(
                type="pil",
                label="Upload any image",
                elem_classes=["image-frame"],
            )
            run_btn = gr.Button(
                "Run Γ—4 Super-Resolution",
                variant="primary",
                elem_classes=["run-btn"],
            )

        with gr.Column(scale=3):
            with gr.Row():
                lr_out = gr.Image(
                    label="LR Input (bilinear upscaled for display)",
                    elem_classes=["image-frame"],
                )
                sr_out = gr.Image(
                    label="SR Output β€” Dense-Iso-ViT",
                    elem_classes=["image-frame"],
                )
                gt_out = gr.Image(
                    label="Ground Truth (original crop)",
                    elem_classes=["image-frame"],
                )

            metrics_out = gr.Markdown(
                elem_classes=["metric-box"],
            )

    # examples
    gr.Examples(
        examples=EXAMPLES,
        inputs=[input_img],
        label="Examples β€” showing V4 strengths",
    )

    # collapsible architecture info
    with gr.Accordion(
        "Architecture details β€” Dense-Iso-ViT",
        open=False,
        elem_classes=["accordion"],
    ):
        gr.Markdown(ARCH_INFO)

    # wire up
    run_btn.click(
        fn=run_sr,
        inputs=[input_img],
        outputs=[lr_out, sr_out, gt_out, metrics_out],
    )

    # also trigger on image upload
    input_img.change(
        fn=run_sr,
        inputs=[input_img],
        outputs=[lr_out, sr_out, gt_out, metrics_out],
    )


if __name__ == "__main__":
    demo.launch(server_name="0.0.0.0", server_port=7860)