Views
No views yet
pip install torch torchvision timm huggingface_hub1import torch
2from huggingface_hub import hf_hub_download
3
4# Download model
5model_path = hf_hub_download(
6 repo_id="jfang/crater-intelli-v1-vit-b-256-0820",
7 filename="pytorch_model.bin"
8)
9
10# Load model (simple version)
11import timm
12import torch.nn as nn
13
14class CraterEmbedder(nn.Module):
15 def __init__(self, model_path):
16 super().__init__()
17 # Create ViT backbone
18 self.backbone = timm.create_model(
19 'vit_base_patch16_224',
20 in_chans=1,
21 num_classes=0,
22 global_pool='token'
23 )
24 # Projection head
25 self.proj = nn.Sequential(
26 nn.Linear(768, 1024),
27 nn.GELU(),
28 nn.Linear(1024, 256)
29 )
30 # Load weights
31 state_dict = torch.load(model_path, map_location='cpu')
32 self.load_state_dict(state_dict)
33
34 def forward(self, x):
35 # x: [B, 1, 224, 224]
36 features = self.backbone(x)
37 embeddings = self.proj(features)
38 # L2 normalize
39 return torch.nn.functional.normalize(embeddings, p=2, dim=-1)
40
41# Initialize model
42model = CraterEmbedder(model_path)
43model.eval()
44
45# Process crater image
46from PIL import Image
47import torchvision.transforms as T
48
49transform = T.Compose([
50 T.Grayscale(num_output_channels=1),
51 T.Resize((224, 224)),
52 T.ToTensor(),
53 T.Normalize(mean=[0.5], std=[0.25])
54])
55
56# Load your crater image
57img = Image.open("crater.jpg")
58img_tensor = transform(img).unsqueeze(0) # [1, 1, 224, 224]
59
60# Get embedding
61with torch.no_grad():
62 embedding = model(img_tensor) # [1, 256]
63
64print(f"Embedding shape: {embedding.shape}")
65print(f"Embedding norm: {embedding.norm():.3f}") # Should be ~1.01import numpy as np
2import torch
3import torch.nn.functional as F
4from typing import List, Tuple
5
6class CraterRetriever:
7 def __init__(self, model):
8 self.model = model
9 self.model.eval()
10 self.gallery_embeddings = None
11 self.gallery_ids = None
12
13 def build_gallery(self, images: List[torch.Tensor], crater_ids: List[str]):
14 """Build gallery of crater embeddings."""
15 embeddings = []
16 with torch.no_grad():
17 for img_batch in torch.split(torch.stack(images), 32):
18 emb = self.model(img_batch)
19 embeddings.append(emb)
20
21 self.gallery_embeddings = torch.cat(embeddings, dim=0)
22 self.gallery_ids = crater_ids
23
24 def retrieve(self, query_image: torch.Tensor, k: int = 10) -> List[Tuple[str, float]]:
25 """Retrieve k most similar craters."""
26 with torch.no_grad():
27 query_emb = self.model(query_image.unsqueeze(0))
28
29 # Compute cosine similarities
30 similarities = F.cosine_similarity(
31 query_emb.unsqueeze(1),
32 self.gallery_embeddings.unsqueeze(0),
33 dim=2
34 ).squeeze(0)
35
36 # Get top-k
37 topk_sims, topk_indices = similarities.topk(k)
38
39 results = []
40 for sim, idx in zip(topk_sims, topk_indices):
41 results.append((self.gallery_ids[idx], sim.item()))
42
43 return results
44
45# Example usage
46retriever = CraterRetriever(model)
47
48# Build gallery from your crater database
49gallery_images = [...] # List of preprocessed crater tensors
50gallery_ids = [...] # List of crater IDs
51
52retriever.build_gallery(gallery_images, gallery_ids)
53
54# Query with a new crater
55query = transform(Image.open("query_crater.jpg")).unsqueeze(0)
56results = retriever.retrieve(query, k=5)
57
58for crater_id, similarity in results:
59 print(f"Crater {crater_id}: {similarity:.3f}")1def process_crater_batch(model, image_paths: List[str], batch_size: int = 32):
2 """Process multiple crater images efficiently."""
3
4 embeddings = []
5
6 for i in range(0, len(image_paths), batch_size):
7 batch_paths = image_paths[i:i+batch_size]
8 batch_tensors = []
9
10 for path in batch_paths:
11 img = Image.open(path)
12 img_tensor = transform(img)
13 batch_tensors.append(img_tensor)
14
15 batch = torch.stack(batch_tensors)
16
17 with torch.no_grad():
18 batch_embeddings = model(batch)
19 embeddings.append(batch_embeddings)
20
21 return torch.cat(embeddings, dim=0)
22
23# Process large crater catalog
24crater_paths = ["crater1.jpg", "crater2.jpg", ...]
25all_embeddings = process_crater_batch(model, crater_paths)1@model{crater_intelligence_v1,
2 title={Crater Intelligence v1: Mars Crater Instance Embedding},
3 author={Fang, J},
4 year={2024},
5 publisher={HuggingFace},
6 howpublished={\url{https://huggingface.co/jfang/crater-intelli-v1-vit-b-256-0820}}
7}