multimodalart HF Staff commited on
Commit
cfbeebf
·
verified ·
1 Parent(s): a93c28d

Delete files tmp/hugging-demos-build-paper_2603.22042-glgclg0e/space/app.py with huggingface_hub

Browse files
tmp/hugging-demos-build-paper_2603.22042-glgclg0e/space/app.py DELETED
@@ -1,493 +0,0 @@
1
- """
2
- UNCHA: Uncertainty-guided Compositional Hyperbolic Alignment
3
- Zero-shot image classification demo using hyperbolic (Lorentz) embeddings.
4
-
5
- Paper: https://arxiv.org/abs/2603.22042
6
- Code: https://github.com/jeeit17/UNCHA
7
- """
8
-
9
- import os
10
- os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
11
-
12
- import spaces # MUST come before torch / any CUDA-touching import
13
-
14
- import gzip
15
- import html
16
- import math
17
- import re
18
- import regex
19
- from collections import OrderedDict
20
- from pathlib import Path
21
-
22
- import numpy as np
23
- import torch
24
- from torch import nn
25
- from torch.nn import functional as F
26
- import timm
27
- import gradio as gr
28
- from PIL import Image
29
-
30
- import torchvision.transforms as T
31
-
32
- # ---------------------------------------------------------------------------
33
- # Tokenizer (adapted from UNCHA/CLIP BPE tokenizer)
34
- # ---------------------------------------------------------------------------
35
-
36
- class Tokenizer:
37
- """Byte-Pair Encoding tokenizer compatible with CLIP / UNCHA checkpoints."""
38
-
39
- def __init__(self, bpe_path: str | Path | None = None):
40
- bs = (
41
- list(range(ord("!"), ord("~") + 1))
42
- + list(range(ord("\xa1"), ord("\xac") + 1))
43
- + list(range(ord("\xae"), ord("\xff") + 1))
44
- )
45
- self.byte_encoder = {b: chr(b) for b in bs}
46
- n = 0
47
- for b in range(2**8):
48
- if b not in self.byte_encoder:
49
- self.byte_encoder[b] = chr(2**8 + n)
50
- n += 1
51
-
52
- if bpe_path is None:
53
- bpe_path = Path(__file__).resolve().parent / "bpe_simple_vocab_16e6.txt.gz"
54
- merges = gzip.open(bpe_path).read().decode("utf-8").split("\n")
55
- merges = merges[1 : 49152 - 256 - 2 + 1]
56
- merges = [tuple(merge.split()) for merge in merges]
57
- vocab = list(self.byte_encoder.values())
58
- vocab = vocab + [v + "</w>" for v in vocab]
59
- for merge in merges:
60
- vocab.append("".join(merge))
61
- vocab.extend(["<|startoftext|>", ""])
62
-
63
- self.encoder = dict(zip(vocab, range(len(vocab))))
64
- self.bpe_ranks = dict(zip(merges, range(len(merges))))
65
- self.cache = {"<|startoftext|>": "<|startoftext|>", "": ""}
66
- self.pat = regex.compile(
67
- r"""<\|startoftext\|>|<\|endoftext\|>|'s|'t|'re|'ve|'m|'ll|'d|[\p{L}]+|[\p{N}]|[^\s\p{L}\p{N}]+""",
68
- regex.IGNORECASE,
69
- )
70
-
71
- def __call__(self, text):
72
- import ftfy
73
-
74
- text_list = [text] if isinstance(text, str) else text
75
- token_tensors = []
76
- for text in text_list:
77
- bpe_tokens = []
78
- text = ftfy.fix_text(text)
79
- text = html.unescape(html.unescape(text))
80
- text = re.sub(r"\s+", " ", text)
81
- text = text.strip().lower()
82
- for token in regex.findall(self.pat, text):
83
- token = "".join(self.byte_encoder[b] for b in token.encode("utf-8"))
84
- bpe_tokens.extend(
85
- self.encoder[bpe_token]
86
- for bpe_token in self.bpe(token).split(" ")
87
- )
88
- sot = self.encoder["<|startoftext|>"]
89
- eot = self.encoder[""]
90
- bpe_tokens = [sot, *bpe_tokens, eot]
91
- token_tensors.append(torch.IntTensor(bpe_tokens))
92
- return token_tensors
93
-
94
- @staticmethod
95
- def get_pairs(word):
96
- pairs = set()
97
- prev_char = word[0]
98
- for char in word[1:]:
99
- pairs.add((prev_char, char))
100
- prev_char = char
101
- return pairs
102
-
103
- def bpe(self, token):
104
- if token in self.cache:
105
- return self.cache[token]
106
- word = tuple(token[:-1]) + (token[-1] + "</w>",)
107
- pairs = self.get_pairs(word)
108
- if not pairs:
109
- return token + "</w>"
110
- while True:
111
- bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
112
- if bigram not in self.bpe_ranks:
113
- break
114
- first, second = bigram
115
- new_word = []
116
- i = 0
117
- while i < len(word):
118
- try:
119
- j = word.index(first, i)
120
- new_word.extend(word[i:j])
121
- i = j
122
- except ValueError:
123
- new_word.extend(word[i:])
124
- break
125
- if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
126
- new_word.append(first + second)
127
- i += 2
128
- else:
129
- new_word.append(word[i])
130
- i += 1
131
- new_word = tuple(new_word)
132
- word = new_word
133
- if len(word) == 1:
134
- break
135
- else:
136
- pairs = self.get_pairs(word)
137
- word = " ".join(word)
138
- self.cache[token] = word
139
- return word
140
-
141
-
142
- # ---------------------------------------------------------------------------
143
- # Lorentz model hyperbolic operations (adapted from UNCHA/meru)
144
- # ---------------------------------------------------------------------------
145
-
146
- def pairwise_inner(x, y, curv=1.0):
147
- x_time = torch.sqrt(1 / curv + torch.sum(x**2, dim=-1, keepdim=True))
148
- y_time = torch.sqrt(1 / curv + torch.sum(y**2, dim=-1, keepdim=True))
149
- return x @ y.T - x_time @ y_time.T
150
-
151
-
152
- def exp_map0(x, curv=1.0, eps=1e-8):
153
- rc_xnorm = curv**0.5 * torch.norm(x, dim=-1, keepdim=True)
154
- sinh_input = torch.clamp(rc_xnorm, min=eps, max=math.asinh(2**15))
155
- return torch.sinh(sinh_input) * x / torch.clamp(rc_xnorm, min=eps)
156
-
157
-
158
- # ---------------------------------------------------------------------------
159
- # Text encoder (adapted from UNCHA TransformerTextEncoder)
160
- # ---------------------------------------------------------------------------
161
-
162
- class _TransformerBlock(nn.Module):
163
- def __init__(self, d_model, n_head):
164
- super().__init__()
165
- self.attn = nn.MultiheadAttention(d_model, n_head, batch_first=True)
166
- self.ln_1 = nn.LayerNorm(d_model)
167
- self.mlp = nn.Sequential(
168
- OrderedDict([
169
- ("c_fc", nn.Linear(d_model, d_model * 4)),
170
- ("gelu", nn.GELU()),
171
- ("c_proj", nn.Linear(d_model * 4, d_model)),
172
- ])
173
- )
174
- self.ln_2 = nn.LayerNorm(d_model)
175
-
176
- def forward(self, x, attn_mask=None):
177
- lx = self.ln_1(x)
178
- ax = self.attn(lx, lx, lx, need_weights=False, attn_mask=attn_mask)[0]
179
- x = x + ax
180
- x = x + self.mlp(self.ln_2(x))
181
- return x
182
-
183
-
184
- class TransformerTextEncoder(nn.Module):
185
- def __init__(self, arch="L12_W512", vocab_size=49408, context_length=77):
186
- super().__init__()
187
- self.vocab_size = vocab_size
188
- self.context_length = context_length
189
- self.layers = int(re.search(r"L(\d+)", arch).group(1))
190
- self.width = int(re.search(r"W(\d+)", arch).group(1))
191
- _attn = re.search(r"A(\d+)", arch)
192
- self.heads = int(_attn.group(1)) if _attn else self.width // 64
193
-
194
- self.token_embed = nn.Embedding(vocab_size, self.width)
195
- self.posit_embed = nn.Parameter(torch.empty(context_length, self.width))
196
- _resblocks = [_TransformerBlock(self.width, self.heads) for _ in range(self.layers)]
197
- self.resblocks = nn.ModuleList(_resblocks)
198
- self.ln_final = nn.LayerNorm(self.width)
199
-
200
- attn_mask = torch.triu(
201
- torch.full((context_length, context_length), float("-inf")), diagonal=1
202
- )
203
- self.register_buffer("attn_mask", attn_mask.bool())
204
-
205
- nn.init.normal_(self.token_embed.weight, std=0.02)
206
- nn.init.normal_(self.posit_embed.data, std=0.01)
207
- out_proj_std = (2 * self.width * self.layers) ** -0.5
208
- for block in self.resblocks:
209
- nn.init.normal_(block.attn.in_proj_weight, std=self.width**-0.5)
210
- nn.init.normal_(block.attn.out_proj.weight, std=out_proj_std)
211
- nn.init.normal_(block.mlp[0].weight, std=(2 * self.width) ** -0.5)
212
- nn.init.normal_(block.mlp[2].weight, std=out_proj_std)
213
-
214
-
215
- def build_timm_vit(arch="vit_base_patch16_224", global_pool="token",
216
- use_sincos2d_pos=True):
217
- model = timm.create_model(
218
- arch, num_classes=0, global_pool=global_pool,
219
- class_token=global_pool == "token", norm_layer=nn.LayerNorm,
220
- )
221
- model.width = model.embed_dim
222
- if use_sincos2d_pos:
223
- h, w = model.patch_embed.grid_size
224
- grid_w = torch.arange(w, dtype=torch.float32)
225
- grid_h = torch.arange(h, dtype=torch.float32)
226
- grid_w, grid_h = torch.meshgrid(grid_w, grid_h)
227
- pos_dim = model.embed_dim // 4
228
- omega = torch.arange(pos_dim, dtype=torch.float32) / pos_dim
229
- omega = 1.0 / (10000.0**omega)
230
- out_w = torch.einsum("m,d->md", [grid_w.flatten(), omega])
231
- out_h = torch.einsum("m,d->md", [grid_h.flatten(), omega])
232
- pos_emb = torch.cat(
233
- [torch.sin(out_w), torch.cos(out_w), torch.sin(out_h), torch.cos(out_h)],
234
- dim=1,
235
- )[None, :, :]
236
- if global_pool == "token":
237
- pe_token = torch.zeros([1, 1, model.embed_dim], dtype=torch.float32)
238
- pos_emb = torch.cat([pe_token, pos_emb], dim=1)
239
- model.pos_embed.data.copy_(pos_emb)
240
- model.pos_embed.requires_grad = False
241
- return model
242
-
243
-
244
- # ---------------------------------------------------------------------------
245
- # UNCHA model (inference-only)
246
- # ---------------------------------------------------------------------------
247
-
248
- class UNCHAModel(nn.Module):
249
- """Inference-only UNCHA model: hyperbolic image-text alignment."""
250
-
251
- def __init__(self, embed_dim=512, visual_arch="vit_base_patch16_224",
252
- text_arch="L12_W512", vocab_size=49408, context_length=77):
253
- super().__init__()
254
- self.visual = build_timm_vit(arch=visual_arch)
255
- self.textual = TransformerTextEncoder(
256
- arch=text_arch, vocab_size=vocab_size, context_length=context_length
257
- )
258
- self.embed_dim = embed_dim
259
- self.visual_proj = nn.Linear(self.visual.width, embed_dim, bias=False)
260
- self.textual_proj = nn.Linear(self.textual.width, embed_dim, bias=False)
261
- self.logit_scale = nn.Parameter(torch.tensor(1 / 0.07).log())
262
- self.curv = nn.Parameter(torch.tensor(1.0).log())
263
- self.visual_alpha = nn.Parameter(torch.tensor(embed_dim**-0.5).log())
264
- self.textual_alpha = nn.Parameter(torch.tensor(embed_dim**-0.5).log())
265
- self.tokenizer = Tokenizer()
266
- self.register_buffer("pixel_mean", torch.tensor((0.485, 0.456, 0.406)).view(-1, 1, 1))
267
- self.register_buffer("pixel_std", torch.tensor((0.229, 0.224, 0.225)).view(-1, 1, 1))
268
-
269
- @property
270
- def device(self):
271
- return self.logit_scale.device
272
-
273
- def encode_image(self, images, project=True):
274
- images = (images - self.pixel_mean) / self.pixel_std
275
- feats = self.visual(images)
276
- feats = self.visual_proj(feats)
277
- if project:
278
- feats = feats * self.visual_alpha.exp()
279
- with torch.autocast(self.device.type, dtype=torch.float32):
280
- feats = exp_map0(feats, self.curv.exp())
281
- return feats
282
-
283
- def encode_text(self, tokens, project=True):
284
- context_len = self.textual.context_length
285
- batch_size = len(tokens)
286
- padded = torch.zeros((batch_size, context_len), dtype=torch.long)
287
- for idx, inst in enumerate(tokens):
288
- L_ = min(inst.shape[0], context_len)
289
- if inst.shape[0] > context_len:
290
- inst = inst[:context_len]
291
- padded[idx, :L_] = inst[:L_]
292
- padded = padded.to(self.device)
293
- feats = self.textual(padded)
294
- eos = padded.argmax(dim=-1)
295
- batch_idx = torch.arange(batch_size, device=self.device)
296
- feats = feats[batch_idx, eos]
297
- feats = self.textual_proj(feats)
298
- if project:
299
- feats = feats * self.textual_alpha.exp()
300
- with torch.autocast(self.device.type, dtype=torch.float32):
301
- feats = exp_map0(feats, self.curv.exp())
302
- return feats
303
-
304
-
305
- # ---------------------------------------------------------------------------
306
- # Image preprocessing (matching the evaluation pipeline)
307
- # ---------------------------------------------------------------------------
308
-
309
- IMAGE_TRANSFORM = T.Compose([
310
- T.Resize(224, T.InterpolationMode.BICUBIC),
311
- T.CenterCrop(224),
312
- T.ToTensor(),
313
- ])
314
-
315
- # ---------------------------------------------------------------------------
316
- # Load model at module scope
317
- # ---------------------------------------------------------------------------
318
-
319
- CHECKPOINT_REPO = "hayeonkim/uncha"
320
- CHECKPOINT_FILE = "uncha_vit_b.pth"
321
-
322
- print("Loading UNCHA model...")
323
- model = UNCHAModel(
324
- embed_dim=512,
325
- visual_arch="vit_base_patch16_224",
326
- text_arch="L12_W512",
327
- vocab_size=49408,
328
- context_length=77,
329
- )
330
-
331
- # Download and load checkpoint
332
- from huggingface_hub import hf_hub_download
333
- _ckpt_path = hf_hub_download(CHECKPOINT_REPO, CHECKPOINT_FILE)
334
- _ckpt = torch.load(_ckpt_path, map_location="cpu", weights_only=False)
335
- _sd = _ckpt["model"]
336
-
337
- # The checkpoint may contain min_radius_head keys from the text encoder that
338
- # our inference model doesn't have — filter them out.
339
- _model_sd = model.state_dict()
340
- _filtered_sd = {}
341
- for k, v in _sd.items():
342
- if k in _model_sd:
343
- _filtered_sd[k] = v
344
- else:
345
- print(f" Skipping checkpoint key not in model: {k}")
346
-
347
- _missing, _unexpected = model.load_state_dict(_filtered_sd, strict=False)
348
- if _missing:
349
- print(f" Missing keys: {_missing}")
350
- if _unexpected:
351
- print(f" Unexpected keys: {_unexpected}")
352
-
353
- model = model.eval().to("cuda")
354
- print(f"Model loaded. curv={model.curv.exp().item():.4f}, "
355
- f"visual_alpha={model.visual_alpha.exp().item():.4f}, "
356
- f"textual_alpha={model.textual_alpha.exp().item():.4f}")
357
-
358
- # ---------------------------------------------------------------------------
359
- # Inference
360
- # ---------------------------------------------------------------------------
361
-
362
- PROMPT_TEMPLATES = [
363
- "a photo of a {}.",
364
- "a blurry photo of a {}.",
365
- "a black and white photo of a {}.",
366
- "a low contrast photo of a {}.",
367
- "a high contrast photo of a {}.",
368
- "a bad photo of a {}.",
369
- "a good photo of a {}.",
370
- "a photo of a small {}.",
371
- "a photo of a big {}.",
372
- "a photo of the {}.",
373
- ]
374
-
375
- @spaces.GPU(duration=60)
376
- def classify(image: Image.Image, candidate_labels: str) -> dict:
377
- """Zero-shot image classification using UNCHA hyperbolic vision-language model.
378
-
379
- Args:
380
- image: Input image to classify.
381
- candidate_labels: Comma-separated list of candidate class labels.
382
-
383
- Returns:
384
- Dictionary mapping each label to its probability score.
385
- """
386
- if image is None:
387
- return {}
388
- if image.mode != "RGB":
389
- image = image.convert("RGB")
390
-
391
- # Parse labels
392
- labels = [l.strip() for l in candidate_labels.split(",") if l.strip()]
393
- if not labels:
394
- return {}
395
-
396
- # Preprocess image
397
- img_tensor = IMAGE_TRANSFORM(image).unsqueeze(0).to(model.device)
398
-
399
- # Encode image into hyperbolic space
400
- with torch.inference_mode():
401
- img_feats = model.encode_image(img_tensor, project=True) # (1, D)
402
-
403
- # Encode text prompts for each label (prompt ensemble in tangent space)
404
- with torch.inference_mode():
405
- all_class_feats = []
406
- for label in labels:
407
- prompts = [pt.format(label) for pt in PROMPT_TEMPLATES]
408
- tokens = model.tokenizer(prompts)
409
- text_feats = model.encode_text(tokens, project=False) # (N_prompts, D)
410
- # Ensemble in tangent space, then project to hyperboloid
411
- text_feats = text_feats.mean(dim=0) # (D,)
412
- text_feats = text_feats * model.textual_alpha.exp()
413
- text_feats = exp_map0(text_feats.unsqueeze(0), model.curv.exp()) # (1, D)
414
- all_class_feats.append(text_feats.squeeze(0))
415
-
416
- classifier = torch.stack(all_class_feats, dim=0) # (num_classes, D)
417
-
418
- # Lorentzian pairwise inner product as classification scores
419
- scores = pairwise_inner(img_feats, classifier, model.curv.exp()) # (1, num_classes)
420
- scores = scores.squeeze(0) # (num_classes,)
421
-
422
- # Convert to probabilities via softmax
423
- probs = F.softmax(scores * model.logit_scale.exp(), dim=-1)
424
-
425
- # Build label->prob dict, sorted by probability
426
- result = {label: float(probs[i]) for i, label in enumerate(labels)}
427
- result = dict(sorted(result.items(), key=lambda x: x[1], reverse=True))
428
- return result
429
-
430
-
431
- # ---------------------------------------------------------------------------
432
- # Gradio UI
433
- # ---------------------------------------------------------------------------
434
-
435
- CSS = """
436
- #col-container { max-width: 1100px; margin: 0 auto; }
437
- .dark .gradio-container { color: var(--body-text-color); }
438
- """
439
-
440
- with gr.Blocks(elem_id="col-container", css=CSS) as demo:
441
- with gr.Column(elem_id="col-container"):
442
- gr.Markdown(
443
- """
444
- # UNCHA: Uncertainty-guided Compositional Hyperbolic Alignment
445
-
446
- Zero-shot image classification using a hyperbolic vision-language model.
447
- Upload an image and provide candidate labels — the model will compute
448
- similarity scores using Lorentzian (hyperbolic) geometry.
449
-
450
- [Paper](https://arxiv.org/abs/2603.22042) | [Code](https://github.com/jeeit17/UNCHA) | [Model](https://huggingface.co/hayeonkim/uncha)
451
- """
452
- )
453
-
454
- with gr.Row():
455
- with gr.Column(scale=1):
456
- image_input = gr.Image(
457
- type="pil", label="Input Image",
458
- sources=["upload", "clipboard"],
459
- )
460
- labels_input = gr.Textbox(
461
- label="Candidate Labels (comma-separated)",
462
- placeholder="cat, dog, bird, car, person",
463
- value="cat, dog, bird, car, person",
464
- )
465
- run_btn = gr.Button("Classify", variant="primary")
466
-
467
- with gr.Column(scale=1):
468
- output_labels = gr.Label(
469
- label="Classification Scores",
470
- num_top_classes=10,
471
- )
472
-
473
- run_btn.click(
474
- fn=classify,
475
- inputs=[image_input, labels_input],
476
- outputs=output_labels,
477
- api_name="classify",
478
- )
479
-
480
- gr.Examples(
481
- examples=[
482
- ["examples/sample1.jpg", "dog, cat, animal, pet, mammal"],
483
- ["examples/sample2.jpg", "building, landscape, nature, city, water"],
484
- ["examples/sample3.jpg", "person, food, vehicle, animal, plant"],
485
- ],
486
- inputs=[image_input, labels_input],
487
- outputs=output_labels,
488
- fn=classify,
489
- cache_examples=True,
490
- cache_mode="lazy",
491
- )
492
-
493
- demo.launch(mcp_server=True, theme=gr.themes.Citrus())