Upload folder using huggingface_hub
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+12-58
- .gitignoreAdded+8
- LICENSEAdded+21
- POMA_BENCH/eval_scene_retrieval.pyAdded+275
- POMA_BENCH/eval_view_retrieval.pyAdded+488
- POMA_BENCH/job/internvl3_8b_fine_tune_coco_job_error_50985.txtAdded+1
- POMA_BENCH/job/internvl3_8b_fine_tune_coco_job_error_50989.txtAdded+1
- POMA_BENCH/job/internvl3_8b_fine_tune_coco_job_error_51020.txtAdded+1
- POMA_BENCH/job/internvl3_8b_fine_tune_coco_job_error_51021.txtAdded+1
- POMA_BENCH/job/internvl3_8b_fine_tune_coco_job_error_51022.txtAdded+1
- POMA_BENCH/job/internvl3_8b_fine_tune_coco_job_error_51029.txtAdded+1
- POMA_BENCH/job/internvl3_8b_fine_tune_coco_job_error_51042.txtAdded+1
- POMA_BENCH/job/internvl3_8b_fine_tune_coco_job_error_51044.txtAdded+1
- POMA_BENCH/job/internvl3_8b_fine_tune_coco_job_error_51045.txtAdded+1
- POMA_BENCH/job/internvl3_8b_fine_tune_coco_job_output_50985.txtAdded
- POMA_BENCH/job/internvl3_8b_fine_tune_coco_job_output_50989.txtAdded
- POMA_BENCH/job/internvl3_8b_fine_tune_coco_job_output_51020.txtAdded
- POMA_BENCH/job/internvl3_8b_fine_tune_coco_job_output_51021.txtAdded
- POMA_BENCH/job/internvl3_8b_fine_tune_coco_job_output_51022.txtAdded
- POMA_BENCH/job/internvl3_8b_fine_tune_coco_job_output_51029.txtAdded
- POMA_BENCH/job/internvl3_8b_fine_tune_coco_job_output_51042.txtAdded
- POMA_BENCH/job/internvl3_8b_fine_tune_coco_job_output_51044.txtAdded
- POMA_BENCH/job/internvl3_8b_fine_tune_coco_job_output_51045.txtAdded
- POMA_BENCH/nr3d_retrieval.jsonlAdded+3
- POMA_BENCH/ret.shAdded+36
- POMA_BENCH/scanrefer_retrieval.jsonlAdded+3
- POMA_BENCH/scene_cap.jsonAdded
- POMA_BENCH/sr3d_retrieval.jsonlAdded+3
- POMA_BENCH/ssg_ref_total_by_view.jsonlAdded+3
- POMA_BENCH/ssg_ref_total_by_view_full.jsonlAdded+3
- assets/logo025.pngAdded
- assets/overview.pngAdded
- chamfer_rankings.jsonAdded+3
- common/__pycache__/box_utils.cpython-310.pycAdded
- common/__pycache__/box_utils.cpython-39.pycAdded
- common/__pycache__/dist_utils.cpython-310.pycAdded
- common/__pycache__/dist_utils.cpython-39.pycAdded
- common/__pycache__/io_utils.cpython-310.pycAdded
- common/__pycache__/io_utils.cpython-39.pycAdded
- common/__pycache__/launch_utils.cpython-310.pycAdded
- common/__pycache__/launch_utils.cpython-313.pycAdded
- common/__pycache__/launch_utils.cpython-39.pycAdded
- common/__pycache__/misc.cpython-310.pycAdded
- common/__pycache__/misc.cpython-39.pycAdded
- common/__pycache__/type_utils.cpython-310.pycAdded
- common/__pycache__/type_utils.cpython-39.pycAdded
- common/box_utils.pyAdded+66
- common/dist_utils.pyAdded+220
- common/io_utils.pyAdded+133
- common/launch_utils.pyAdded+121
1234567891011121314151617181920212223242526128293031323334353637383940414243444546474849505152535455565758592345678910111213*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text*.ckpt filter=lfs diff=lfs merge=lfs -text*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.lz4 filter=lfs diff=lfs merge=lfs -text*.mds filter=lfs diff=lfs merge=lfs -text*.mlmodel filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text*.msgpack filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -text*.npz filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.ot filter=lfs diff=lfs merge=lfs -text*.parquet filter=lfs diff=lfs merge=lfs -text*.pb filter=lfs diff=lfs merge=lfs -text*.pickle filter=lfs diff=lfs merge=lfs -text*.pkl filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text*.pth filter=lfs diff=lfs merge=lfs -text*.rar filter=lfs diff=lfs merge=lfs -text*.safetensors filter=lfs diff=lfs merge=lfs -textsaved_model/**/* filter=lfs diff=lfs merge=lfs -text*.tar.* filter=lfs diff=lfs merge=lfs -text*.tar filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.tgz filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.xz filter=lfs diff=lfs merge=lfs -text*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text# Audio files - uncompressed*.pcm filter=lfs diff=lfs merge=lfs -text*.sam filter=lfs diff=lfs merge=lfs -text*.raw filter=lfs diff=lfs merge=lfs -text# Audio files - compressed*.aac filter=lfs diff=lfs merge=lfs -text*.flac filter=lfs diff=lfs merge=lfs -text*.mp3 filter=lfs diff=lfs merge=lfs -text*.ogg filter=lfs diff=lfs merge=lfs -text*.wav filter=lfs diff=lfs merge=lfs -text# Image files - uncompressed*.bmp filter=lfs diff=lfs merge=lfs -text*.gif filter=lfs diff=lfs merge=lfs -text*.png filter=lfs diff=lfs merge=lfs -text*.tiff filter=lfs diff=lfs merge=lfs -text# Image files - compressed*.jpg filter=lfs diff=lfs merge=lfs -text*.jpeg filter=lfs diff=lfs merge=lfs -text*.webp filter=lfs diff=lfs merge=lfs -text# Video files - compressed*.mp4 filter=lfs diff=lfs merge=lfs -text*.webm filter=lfs diff=lfs merge=lfs -textPOMA_BENCH/nr3d_retrieval.jsonl filter=lfs diff=lfs merge=lfs -textPOMA_BENCH/scanrefer_retrieval.jsonl filter=lfs diff=lfs merge=lfs -textPOMA_BENCH/sr3d_retrieval.jsonl filter=lfs diff=lfs merge=lfs -textPOMA_BENCH/ssg_ref_total_by_view.jsonl filter=lfs diff=lfs merge=lfs -textPOMA_BENCH/ssg_ref_total_by_view_full.jsonl filter=lfs diff=lfs merge=lfs -textassets/logo025.png filter=lfs diff=lfs merge=lfs -textassets/overview.png filter=lfs diff=lfs merge=lfs -textchamfer_rankings.json filter=lfs diff=lfs merge=lfs -textlight_3rscan_chamfer_rankings.json filter=lfs diff=lfs merge=lfs -textlight_arkitscenes_chamfer_rankings.json filter=lfs diff=lfs merge=lfs -textlight_scannet_chamfer_rankings.json filter=lfs diff=lfs merge=lfs -textscripts/job/internvl3_8b_fine_tune_coco_job_output_44548.txt filter=lfs diff=lfs merge=lfs -text12345678fg-clip-base/model.safetensorsPointMapVerseresults/vis/wandb/lmms-finetunecc3m_1Mcaptions123456789101112131415161718192021MIT License
Copyright (c) 2024 scene-verse
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275import osimport globimport jsonimport argparsefrom typing import Dict, List, Tuple
import torchimport torch.nn as nnimport torch.nn.functional as Ffrom safetensors.torch import load_filefrom transformers import AutoImageProcessor, AutoModelForCausalLM, AutoTokenizerfrom huggingface_hub import hf_hub_downloadfrom peft import LoraConfig, get_peft_model
# -----------------------------# Utils# -----------------------------def load_json(path: str) -> dict: with open(path, "r") as f: return json.load(f)
def find_scan_safetensor(scan_root: str, scan_id: str) -> str: direct = os.path.join(scan_root, f"{scan_id}.safetensors") if os.path.exists(direct): return direct
pattern = os.path.join(scan_root, "**", f"{scan_id}.safetensors") matches = glob.glob(pattern, recursive=True) if not matches: raise FileNotFoundError(f"Cannot find safetensor for scan_id={scan_id} under {scan_root}") matches = sorted(matches, key=len) return matches[0]
def to_vchw(point_map: torch.Tensor) -> torch.Tensor: """ Convert point_map to (V, 3, H, W) float tensor. Accepts: (V, 3, H, W) (V, H, W, 3) """ if point_map.dim() != 4: raise ValueError(f"Expected 4D point_map, got shape={tuple(point_map.shape)}")
V, a, b, c = point_map.shape if a == 3: out = point_map elif c == 3: out = point_map.permute(0, 3, 1, 2).contiguous() else: raise ValueError(f"Unrecognized point_map layout: shape={tuple(point_map.shape)}")
return out.float()
def load_safetensor_from_hf(repo_id, filename, repo_type="dataset"): cached_path = hf_hub_download( repo_id=repo_id, filename=filename, repo_type=repo_type, local_files_only=False ) return load_file(cached_path)
def load_pretrain(model, pretrain_ckpt_path: str): print(f"📂 Loading pretrained weights from: {str(pretrain_ckpt_path)}")
model_weight_path_pattern = os.path.join(pretrain_ckpt_path, "model*.safetensors") model_weight_paths = glob.glob(model_weight_path_pattern)
if len(model_weight_paths) == 0: raise FileNotFoundError(f"❌ Cannot find any model*.safetensors in {str(pretrain_ckpt_path)}")
weights = {} for model_weight_path in model_weight_paths: print(f"📥 Loading weights from: {model_weight_path}") weights.update(load_file(model_weight_path, device="cpu"))
result = model.load_state_dict(weights, strict=False)
model_keys = set(model.state_dict().keys()) loaded_keys = model_keys.intersection(weights.keys()) print(f"✅ Loaded keys: {len(loaded_keys)} / {len(model_keys)}") print(f"❌ Missing keys: {len(result.missing_keys)}") print(f"⚠️ Unexpected keys: {len(result.unexpected_keys)}")
# -----------------------------# Model wrapper# -----------------------------class RepModel(nn.Module): def __init__(self, model_root: str = "fg-clip-base"): super().__init__()
self.pm_encoder = AutoModelForCausalLM.from_pretrained(f'../{model_root}', trust_remote_code=True) self.tokenizer = AutoTokenizer.from_pretrained(f'../{model_root}', trust_remote_code=True, use_fast=True) self.image_processor = AutoImageProcessor.from_pretrained(f'../{model_root}')
# Optional: print trainable params try: self.pm_encoder.print_trainable_parameters() except Exception: pass
def encode_views_batched(self, pm_vchw: torch.Tensor, batch_views: int = 32) -> torch.Tensor: """ pm_vchw: (V,3,H,W) on device returns: (V,D) normalized """ feats_all = [] V = pm_vchw.shape[0] for s in range(0, V, batch_views): chunk = pm_vchw[s : s + batch_views] # (b,3,H,W) _, feats = self.pm_encoder.get_image_features(chunk) feats = F.normalize(feats.float(), dim=-1) feats_all.append(feats) return torch.cat(feats_all, dim=0)
@torch.no_grad() def encode_text(self, texts: List[str]) -> torch.Tensor: """ texts: list[str] returns: (B,D) normalized """ tok = self.tokenizer( texts, padding="max_length", truncation=True, max_length=248, return_tensors="pt", ).to(next(self.parameters()).device)
feats = self.pm_encoder.get_text_features(tok["input_ids"], walk_short_pos=False) feats = F.normalize(feats.float(), dim=-1) return feats
# -----------------------------# Scene retrieval# -----------------------------def build_queries_from_caption_json(caption_json: dict) -> List[dict]: """ Convert: { scene_id: { "captions": [c1,c2,...] }, ... } into: [ { "scene_id": scene_id, "caption": c }, ... ] """ queries = [] for scene_id, payload in caption_json.items(): caps = payload.get("captions", []) for c in caps: c = (c or "").strip() if c: queries.append({"scene_id": scene_id, "caption": c}) return queries
@torch.no_grad()def eval_scene_retrieval( model: RepModel, caption_json: dict, scan_root: str, device: str = "cuda", batch_views: int = 32, recall_ks: Tuple[int, ...] = (1, 5, 10),) -> Dict[str, float]: """ For each caption, retrieve the correct scene among all scenes in caption_json. Scene embedding = mean pooling over view embeddings. """ model.eval().to(device)
scene_ids = sorted(list(caption_json.keys())) if len(scene_ids) == 0: return {"n": 0}
# Cache: scene_id -> pooled scene feature (D,) on CPU scene_feat_cache: Dict[str, torch.Tensor] = {}
# Precompute all scene pooled features once (so retrieval is fast) for sid in scene_ids: filename = f'light_scannet/{sid}.safetensors' data = load_safetensor_from_hf('MatchLab/ScenePoint', filename, repo_type="dataset")
pm = to_vchw(data["point_map"]) # (V,3,H,W) on CPU pm = pm.to(device, non_blocking=True)
view_feats = model.encode_views_batched(pm, batch_views=batch_views) # (V,D) on GPU scene_feat = view_feats.mean(dim=0) # (D,) scene_feat = F.normalize(scene_feat, dim=-1)
scene_feat_cache[sid] = scene_feat.detach().cpu()
# Stack gallery: (N,D) gallery = torch.stack([scene_feat_cache[sid] for sid in scene_ids], dim=0) # CPU gallery = gallery.to(device)
# Build queries queries = build_queries_from_caption_json(caption_json)
total = 0 top1_correct = 0 recall_correct = {k: 0 for k in recall_ks}
for q in queries: gt_sid = q["scene_id"] caption = q["caption"]
if gt_sid not in scene_feat_cache: continue
text_feat = model.encode_text([caption])[0] # (D,) on GPU
# similarity over all scenes: (N,) sims = gallery @ text_feat.unsqueeze(-1) # (N,1) sims = sims.squeeze(-1)
ranked = torch.argsort(sims, descending=True) # indices into scene_ids pred_sid = scene_ids[int(ranked[0].item())]
total += 1 if pred_sid == gt_sid: top1_correct += 1
for k in recall_ks: k_eff = min(k, len(scene_ids)) topk_idx = ranked[:k_eff].tolist() topk_sids = [scene_ids[i] for i in topk_idx] if gt_sid in topk_sids: recall_correct[k] += 1
# optional debug print print(f"[Q] GT={gt_sid} | Pred={pred_sid} | caption={caption[:80]}...")
if total == 0: return {"n": 0}
out = {"n": total, "top1_acc": top1_correct / total} for k in recall_ks: out[f"recall@{k}"] = recall_correct[k] / total return out
def main(): ap = argparse.ArgumentParser() ap.add_argument("--caption_json", type=str, required=True, help="JSON mapping scene_id -> {captions:[...]}") ap.add_argument("--scan_root", type=str, required=True, help="Root dir containing scene safetensors") ap.add_argument("--ckpt", type=str, default="", help="Optional: dir with model*.safetensors") ap.add_argument("--model_root", type=str, default="fg-clip-base") ap.add_argument("--device", type=str, default="cuda") ap.add_argument("--batch_views", type=int, default=32) args = ap.parse_args()
caption_json = load_json(args.caption_json)
model = RepModel(model_root=args.model_root) if args.ckpt: load_pretrain(model, args.ckpt)
metrics = eval_scene_retrieval( model=model, caption_json=caption_json, scan_root=args.scan_root, device=args.device, batch_views=args.batch_views, recall_ks=(1, 5, 10), )
print("\n=== Scene Retrieval Results ===") for k, v in metrics.items(): if isinstance(v, float): print(f"{k:>10}: {v:.4f}") else: print(f"{k:>10}: {v}")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488import osimport globimport jsonimport argparsefrom typing import Dict, List, Tuple
import torchimport torch.nn as nnimport torch.nn.functional as Ffrom safetensors.torch import load_filefrom huggingface_hub import hf_hub_downloadfrom transformers import AutoImageProcessor, AutoModelForCausalLM, AutoTokenizer
# -----------------------------# Utils# -----------------------------def load_jsonl(path: str) -> List[dict]: data = [] with open(path, "r") as f: for line in f: line = line.strip() if not line: continue data.append(json.loads(line)) return data
def load_safetensor_from_hf(repo_id, filename, repo_type="dataset"): cached_path = hf_hub_download( repo_id=repo_id, filename=filename, repo_type=repo_type, local_files_only=False ) return load_file(cached_path)
def to_vchw(point_map: torch.Tensor) -> torch.Tensor: """ Convert point_map to (V, 3, H, W) float tensor. Accepts common layouts: (V, 3, H, W) -> ok (V, H, W, 3) -> permute (V, H, W, C) where C=3 -> permute """ if point_map.dim() != 4: raise ValueError(f"Expected point_map to be 4D (V,*,*,*), got shape={tuple(point_map.shape)}")
V, a, b, c = point_map.shape
# (V, 3, H, W) if a == 3: out = point_map # (V, H, W, 3) elif c == 3: out = point_map.permute(0, 3, 1, 2).contiguous() else: raise ValueError(f"Unrecognized point_map layout: shape={tuple(point_map.shape)}")
return out.float()
def load_pretrain(model, pretrain_ckpt_path): print(f"📂 Loading pretrained weights from: {str(pretrain_ckpt_path)}") # Search for safetensors files model_weight_path_pattern = pretrain_ckpt_path + "/model*.safetensors" model_weight_paths = glob.glob(model_weight_path_pattern)
if len(model_weight_paths) == 0: raise FileNotFoundError(f"❌ Cannot find any .safetensors file in {str(pretrain_ckpt_path)}")
# Load and merge weights weights = {} for model_weight_path in model_weight_paths: print(f"📥 Loading weights from: {model_weight_path}") weights.update(load_file(model_weight_path, device="cpu"))
# Load weights with strict=False result = model.load_state_dict(weights, strict=False) model_keys = set(model.state_dict().keys()) loaded_keys = model_keys.intersection(weights.keys()) missing_keys = result.missing_keys unexpected_keys = result.unexpected_keys print(f"✅ Loaded keys: {len(loaded_keys)} / {len(model_keys)}") print(f"❌ Missing keys: {len(missing_keys)}") print(f"⚠️ Unexpected keys: {len(unexpected_keys)}")
class _GlobalViewAttnBlock(nn.Module): """One pre-norm Transformer-style block over view tokens (B,V,D).""" def __init__( self, dim: int, num_heads: int, mlp_ratio: float, dropout: float, zero_init_residual: bool, zero_init_attn_out: bool, ): super().__init__() self.zero_init_residual = zero_init_residual self.zero_init_attn_out = zero_init_attn_out
self.norm1 = nn.LayerNorm(dim) self.attn = nn.MultiheadAttention( embed_dim=dim, num_heads=num_heads, dropout=dropout, batch_first=True, bias=True, )
self.norm2 = nn.LayerNorm(dim) hidden_dim = int(dim * mlp_ratio) self.mlp = nn.Sequential( nn.Linear(dim, hidden_dim), nn.GELU(), nn.Dropout(dropout), nn.Linear(hidden_dim, dim), nn.Dropout(dropout), )
self._init_weights()
def forward(self, x, key_padding_mask=None): h = self.norm1(x) attn_out, _ = self.attn( h, h, h, key_padding_mask=key_padding_mask, need_weights=False, ) x = x + attn_out x = x + self.mlp(self.norm2(x)) return x
@torch.no_grad() def _init_weights(self): # LayerNorm for ln in (self.norm1, self.norm2): nn.init.ones_(ln.weight) nn.init.zeros_(ln.bias)
# MultiheadAttention: in_proj for qkv (3D, D) if getattr(self.attn, "in_proj_weight", None) is not None: nn.init.xavier_uniform_(self.attn.in_proj_weight) if getattr(self.attn, "in_proj_bias", None) is not None: nn.init.zeros_(self.attn.in_proj_bias)
# out proj nn.init.xavier_uniform_(self.attn.out_proj.weight) if self.attn.out_proj.bias is not None: nn.init.zeros_(self.attn.out_proj.bias)
# optional: start attn residual near-zero if self.zero_init_attn_out: nn.init.zeros_(self.attn.out_proj.weight) if self.attn.out_proj.bias is not None: nn.init.zeros_(self.attn.out_proj.bias)
# MLP fc1: nn.Linear = self.mlp[0] fc2: nn.Linear = self.mlp[3]
nn.init.xavier_uniform_(fc1.weight) if fc1.bias is not None: nn.init.zeros_(fc1.bias)
# zero-init last projection for stable residual start (recommended) if self.zero_init_residual: nn.init.zeros_(fc2.weight) if fc2.bias is not None: nn.init.zeros_(fc2.bias) else: nn.init.xavier_uniform_(fc2.weight) if fc2.bias is not None: nn.init.zeros_(fc2.bias)
class _GlobalViewGatedAttnBlock(nn.Module): """Pre-norm Transformer block over view tokens (B,V,D) with gated residuals.""" def __init__( self, dim: int, num_heads: int, mlp_ratio: float, dropout: float, zero_init_residual: bool, zero_init_attn_out: bool, gate_bias_init: float = -2.0, # sigmoid(-2)≈0.12, starts near-identity (small updates) ): super().__init__() self.zero_init_residual = zero_init_residual self.zero_init_attn_out = zero_init_attn_out
self.norm1 = nn.LayerNorm(dim) self.attn = nn.MultiheadAttention( embed_dim=dim, num_heads=num_heads, dropout=dropout, batch_first=True, bias=True, )
# --- Gating for attention residual --- # Produces per-token, per-channel gates in (0,1) self.attn_gate = nn.Linear(dim, dim, bias=True)
self.norm2 = nn.LayerNorm(dim) hidden_dim = int(dim * mlp_ratio) self.mlp = nn.Sequential( nn.Linear(dim, hidden_dim), nn.GELU(), nn.Dropout(dropout), nn.Linear(hidden_dim, dim), nn.Dropout(dropout), )
# --- Gating for MLP residual --- self.mlp_gate = nn.Linear(dim, dim, bias=True)
self._init_weights(gate_bias_init=gate_bias_init)
def forward(self, x: torch.Tensor, key_padding_mask=None) -> torch.Tensor: # x: (B, V, D) h1 = self.norm1(x) attn_out, _ = self.attn( h1, h1, h1, key_padding_mask=key_padding_mask, need_weights=False, ) g_attn = torch.sigmoid(self.attn_gate(h1)) # (B, V, D) x = x + g_attn * attn_out
h2 = self.norm2(x) mlp_out = self.mlp(h2) g_mlp = torch.sigmoid(self.mlp_gate(h2)) # (B, V, D) x = x + g_mlp * mlp_out return x
@torch.no_grad() def _init_weights(self, gate_bias_init: float): # LayerNorm for ln in (self.norm1, self.norm2): nn.init.ones_(ln.weight) nn.init.zeros_(ln.bias)
# MultiheadAttention: in_proj for qkv if getattr(self.attn, "in_proj_weight", None) is not None: nn.init.xavier_uniform_(self.attn.in_proj_weight) if getattr(self.attn, "in_proj_bias", None) is not None: nn.init.zeros_(self.attn.in_proj_bias)
# out proj nn.init.xavier_uniform_(self.attn.out_proj.weight) if self.attn.out_proj.bias is not None: nn.init.zeros_(self.attn.out_proj.bias)
# optional: start attn residual near-zero if self.zero_init_attn_out: nn.init.zeros_(self.attn.out_proj.weight) if self.attn.out_proj.bias is not None: nn.init.zeros_(self.attn.out_proj.bias)
# MLP fc1: nn.Linear = self.mlp[0] fc2: nn.Linear = self.mlp[3] nn.init.xavier_uniform_(fc1.weight) if fc1.bias is not None: nn.init.zeros_(fc1.bias)
if self.zero_init_residual: nn.init.zeros_(fc2.weight) if fc2.bias is not None: nn.init.zeros_(fc2.bias) else: nn.init.xavier_uniform_(fc2.weight) if fc2.bias is not None: nn.init.zeros_(fc2.bias)
# Gates: start “mostly closed” so training is stable, then learn to open nn.init.zeros_(self.attn_gate.weight) nn.init.constant_(self.attn_gate.bias, gate_bias_init)
nn.init.zeros_(self.mlp_gate.weight) nn.init.constant_(self.mlp_gate.bias, gate_bias_init) class GlobalViewAttention(nn.Module): """ Multi-layer global self-attention over multi-view tokens.
Input: x ∈ (B, V, D) Output: x' ∈ (B, V, D) """ def __init__( self, dim: int, num_layers: int = 1, num_heads: int = 8, mlp_ratio: float = 4.0, dropout: float = 0.0, zero_init_residual: bool = True, # recommended (stable when adding layers) zero_init_attn_out: bool = False, # optional extra safety ): super().__init__() assert num_layers >= 1, "num_layers must be >= 1"
self.dim = dim self.num_layers = num_layers self.num_heads = num_heads self.layers = nn.ModuleList([ _GlobalViewAttnBlock( dim=dim, num_heads=num_heads, mlp_ratio=mlp_ratio, dropout=dropout, zero_init_residual=zero_init_residual, zero_init_attn_out=zero_init_attn_out, ) for _ in range(num_layers) ])
def forward(self, x, key_padding_mask=None): """ x: (B, V, D) key_padding_mask: (B, V), True = ignore (padding) """ for layer in self.layers: x = layer(x, key_padding_mask=key_padding_mask) return x class RepModel(nn.Module): def __init__(self, model_root: str = "fg-clip-base"): super().__init__()
self.pm_encoder = AutoModelForCausalLM.from_pretrained(f'../{model_root}', trust_remote_code=True) # self.global_attn = GlobalViewAttention(dim=512, num_heads=8, mlp_ratio=4.0, dropout=0.1) self.tokenizer = AutoTokenizer.from_pretrained(f'../{model_root}', trust_remote_code=True, use_fast=True) self.image_processor = AutoImageProcessor.from_pretrained(f'../{model_root}')
# Optional: print trainable params try: self.pm_encoder.print_trainable_parameters() except Exception: pass
@torch.no_grad() def encode_views(self, pm_batched): # Expect (1,V,3,H,W) or (V,3,H,W) # pm_batched = self.image_processor(images=pm_batched, return_tensors="pt").to('cuda') _, feats = self.pm_encoder.get_image_features(pm_batched) # feats = self.global_attn(feats) feats = torch.nn.functional.normalize(feats.float(), dim=-1) return feats @torch.no_grad() def encode_text(self, texts): tok = self.tokenizer(texts, padding="max_length", truncation=True, max_length=248, return_tensors="pt").to('cuda') feats = self.pm_encoder.get_text_features(tok["input_ids"], walk_short_pos=False) feats = torch.nn.functional.normalize(feats.float(), dim=-1) return feats
# -----------------------------# Retrieval evaluation# -----------------------------@torch.no_grad()def eval_view_retrieval( model: RepModel, items: List[dict], scan_root: str, device: str = "cuda", batch_views: int = 32, recall_ks: Tuple[int, ...] = (1, 5, 10),) -> Dict[str, float]: model.eval() model.to(device)
# Cache: scan_id -> (V, D) view features scan_cache: Dict[str, torch.Tensor] = {}
total = 0 top1_correct = 0 recall_correct = {k: 0 for k in recall_ks}
for it in items: scan_id = it["scan_id"] utter = it["utterance"] gt_views = it.get("view_ground_truth", None) if not gt_views: continue gt = int(gt_views[0]) # "the first of the view gt"
# Load / cache view features for this scan if scan_id not in scan_cache: filename = f'light_scannet/{scan_id}.safetensors' data = load_safetensor_from_hf('MatchLab/ScenePoint', filename, repo_type="dataset")
# if "point_map" not in data: # raise KeyError(f"{st_path} does not contain key 'point_map'. keys={list(data.keys())}")
pm = to_vchw(data["point_map"]) # (V, 3, H, W) # pm = data['color_images'] V = pm.shape[0]
feats = model.encode_views(pm.to(device, non_blocking=True)) # (chunk, D) scan_cache[scan_id] = feats # (V, D) on CPU
view_feats = scan_cache[scan_id] # (V, D), CPU V = view_feats.shape[0] if gt < 0 or gt >= V: # skip invalid gt index continue
# Encode text text_feat = model.encode_text(utter).squeeze(0).unsqueeze(-1) # (D,)
# Similarity: (V,) sims = (view_feats @ text_feat).squeeze(-1) # rank views by similarity (high -> low) ranked = torch.argsort(sims, descending=True)
pred = int(ranked[0].item()) total += 1
if pred == gt: top1_correct += 1 else: # per-sample print (optional) print(f"GT: {gt}, Pred: {pred}, Utterance: {utter}")
# Recall@K for k in recall_ks: k_eff = min(k, V) if (ranked[:k_eff] == gt).any().item(): recall_correct[k] += 1
# ----- after the loop ----- out = {} if total == 0: return {"n": 0}
out["n"] = total out["top1_acc"] = top1_correct / total for k in recall_ks: out[f"recall@{k}"] = recall_correct[k] / total
return out
def main(): ap = argparse.ArgumentParser() ap.add_argument("--jsonl", type=str, required=True, help="SR3D-style jsonl file") ap.add_argument("--scan_root", type=str, required=True, help="Root dir containing scan safetensors") ap.add_argument("--ckpt", type=str, default="", help="Optional: path to .pth/.pt or dir with model*.safetensors") ap.add_argument("--model_root", type=str, default="fg-clip-base") ap.add_argument("--device", type=str, default="cuda") ap.add_argument("--batch_views", type=int, default=32) ap.add_argument("--max_items", type=int, default=-1) args = ap.parse_args()
items = load_jsonl(args.jsonl) if args.max_items > 0: items = items[: args.max_items]
model = RepModel(model_root=args.model_root) if args.ckpt: load_pretrain(model, args.ckpt)
metrics = eval_view_retrieval( model=model, items=items, scan_root=args.scan_root, device=args.device, batch_views=args.batch_views, recall_ks=(1, 5, 10), )
print("\n=== View Retrieval Results ===") for k, v in metrics.items(): if isinstance(v, float): print(f"{k:>10}: {v:.4f}") else: print(f"{k:>10}: {v}")
if __name__ == "__main__": main()1Using a slow image processor as `use_fast` is unset and a slow processor was saved with this model. `use_fast=True` will be the default behavior in v4.52, even if the model was saved with a slow processor. This will result in minor differences in outputs. You'll still be able to use a slow processor with `use_fast=False`.1Using a slow image processor as `use_fast` is unset and a slow processor was saved with this model. `use_fast=True` will be the default behavior in v4.52, even if the model was saved with a slow processor. This will result in minor differences in outputs. You'll still be able to use a slow processor with `use_fast=False`.1Using a slow image processor as `use_fast` is unset and a slow processor was saved with this model. `use_fast=True` will be the default behavior in v4.52, even if the model was saved with a slow processor. This will result in minor differences in outputs. You'll still be able to use a slow processor with `use_fast=False`.1Using a slow image processor as `use_fast` is unset and a slow processor was saved with this model. `use_fast=True` will be the default behavior in v4.52, even if the model was saved with a slow processor. This will result in minor differences in outputs. You'll still be able to use a slow processor with `use_fast=False`.1Using a slow image processor as `use_fast` is unset and a slow processor was saved with this model. `use_fast=True` will be the default behavior in v4.52, even if the model was saved with a slow processor. This will result in minor differences in outputs. You'll still be able to use a slow processor with `use_fast=False`.1Using a slow image processor as `use_fast` is unset and a slow processor was saved with this model. `use_fast=True` will be the default behavior in v4.52, even if the model was saved with a slow processor. This will result in minor differences in outputs. You'll still be able to use a slow processor with `use_fast=False`.1Using a slow image processor as `use_fast` is unset and a slow processor was saved with this model. `use_fast=True` will be the default behavior in v4.52, even if the model was saved with a slow processor. This will result in minor differences in outputs. You'll still be able to use a slow processor with `use_fast=False`.1Using a slow image processor as `use_fast` is unset and a slow processor was saved with this model. `use_fast=True` will be the default behavior in v4.52, even if the model was saved with a slow processor. This will result in minor differences in outputs. You'll still be able to use a slow processor with `use_fast=False`.1Using a slow image processor as `use_fast` is unset and a slow processor was saved with this model. `use_fast=True` will be the default behavior in v4.52, even if the model was saved with a slow processor. This will result in minor differences in outputs. You'll still be able to use a slow processor with `use_fast=False`.123version https://git-lfs.github.com/spec/v1oid sha256:296564ae94258af94f09a5dcf02f660314e438ff53136688e4322bb1e6a18700size 22955141123456789101112131415161718192021222324252627282930313233343536# #!/bin/bash# #SBATCH --job-name=eval# #SBATCH --output=job/internvl3_8b_fine_tune_coco_job_output_%j.txt# #SBATCH --error=job/internvl3_8b_fine_tune_coco_job_error_%j.txt# #SBATCH --time=20:00:00# #SBATCH --ntasks=1# #SBATCH --partition=camera-long# #SBATCH --ntasks-per-node=1# #SBATCH --nodes=1# #SBATCH --gres=gpu:h100:1# #SBATCH --mail-type=ALL# #SBATCH --mail-user=ym621@ic.ac.uk# #SBATCH --qos=normal
# cd /mnt/data-alpha-sg-01/team-camera/home/m50048399/transfered/ye_project/Project2/POMA_BENCH# /home/m50048399/anaconda3/bin/conda init bash# source ~/.bashrc# conda activate sceneverse# export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
python eval_view_retrieval.py \ --jsonl sr3d_retrieval.jsonl \ --scan_root /mnt/new_drive/retreival/light_scannet/light_scannet \ --device cuda \ --ckpt /home/m50048399/transfered/ye_project/Project2/results/sceneverse_scannet_exp1_b64_Pretrain_all_scannet_training_run1/2026-01-19-23:46:36.901933/ckpt/ckpt_20.pth \ --batch_views 32
# python eval_scene_retrieval.py \# --caption_json scene_cap.json \# --scan_root /mnt/new_drive/retreival/light_scannet/light_scannet \# --model_root fg-clip-base \# --ckpt /home/m50048399/transfered/ye_project/Project2/results/sceneverse_scannet_exp1_b128_Pretrain_all_scannet_training_run1/withgeoalign/ckpt/ckpt_100.pth \# --batch_views 32
123version https://git-lfs.github.com/spec/v1oid sha256:77be567de421d2f8593ac04906ff3afaa3a635832b7d55d6c93041d0599d5390size 27430061123version https://git-lfs.github.com/spec/v1oid sha256:9acfb7d5773fbbfc42536e5511bc4fb5890444eb682afe446a9e6e8208abd604size 48231881123version https://git-lfs.github.com/spec/v1oid sha256:7ea1c18e33e8f2255f202599f5596841370c608480e675e8e538020173d02e1esize 10972907123version https://git-lfs.github.com/spec/v1oid sha256:5842e5d224db9aafbee803363ed38218f4fc4adb4e8ac7b9855c853a68875362size 36000916123version https://git-lfs.github.com/spec/v1oid sha256:b6044fbe2930aa318090e012887efaa65d2fb48075bc95ef3bc3c661ee9c4afasize 76539228123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566import numpy as np
def box3d_iou(corners1, corners2): ''' Compute 3D bounding box IoU.
Input: corners1: numpy array (8,3), assume up direction is Z corners2: numpy array (8,3), assume up direction is Z Output: iou: 3D bounding box IoU
''' x_min_1, x_max_1, y_min_1, y_max_1, z_min_1, z_max_1 = get_box3d_min_max(corners1) x_min_2, x_max_2, y_min_2, y_max_2, z_min_2, z_max_2 = get_box3d_min_max(corners2) xA = np.maximum(x_min_1, x_min_2) yA = np.maximum(y_min_1, y_min_2) zA = np.maximum(z_min_1, z_min_2) xB = np.minimum(x_max_1, x_max_2) yB = np.minimum(y_max_1, y_max_2) zB = np.minimum(z_max_1, z_max_2) inter_vol = np.maximum((xB - xA), 0) * np.maximum((yB - yA), 0) * np.maximum((zB - zA), 0) box_vol_1 = (x_max_1 - x_min_1) * (y_max_1 - y_min_1) * (z_max_1 - z_min_1) box_vol_2 = (x_max_2 - x_min_2) * (y_max_2 - y_min_2) * (z_max_2 - z_min_2) iou = inter_vol / (box_vol_1 + box_vol_2 - inter_vol + 1e-8)
return iou
def get_box3d_min_max(corner): ''' Compute min and max coordinates for 3D bounding box Note: only for axis-aligned bounding boxes
Input: corners: numpy array (8,3), assume up direction is Z (batch of N samples) Output: box_min_max: an array for min and max coordinates of 3D bounding box IoU
''' min_coord = corner.min(axis=0) max_coord = corner.max(axis=0) x_min, x_max = min_coord[0], max_coord[0] y_min, y_max = min_coord[1], max_coord[1] z_min, z_max = min_coord[2], max_coord[2] return x_min, x_max, y_min, y_max, z_min, z_max
def get_3d_box(center, box_size): ''' box_size is array(l,w,h), heading_angle is radius clockwise from pos x axis, center is xyz of box center output (8,3) array for 3D box cornders Similar to utils/compute_orientation_3d ''' l,w,h = box_size # x_corners = [l/2,l/2,-l/2,-l/2,l/2,l/2,-l/2,-l/2] # y_corners = [h/2,h/2,h/2,h/2,-h/2,-h/2,-h/2,-h/2] # z_corners = [w/2,-w/2,-w/2,w/2,w/2,-w/2,-w/2,w/2] x_corners = [l/2,l/2,-l/2,-l/2,l/2,l/2,-l/2,-l/2] y_corners = [w/2,-w/2,-w/2,w/2,w/2,-w/2,-w/2,w/2] z_corners = [h/2,h/2,h/2,h/2,-h/2,-h/2,-h/2,-h/2] corners_3d = np.vstack([x_corners,y_corners,z_corners]) corners_3d[0,:] = corners_3d[0,:] + center[0] corners_3d[1,:] = corners_3d[1,:] + center[1] corners_3d[2,:] = corners_3d[2,:] + center[2] corners_3d = np.transpose(corners_3d) return corners_3d123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220import functoolsimport pickleimport torchimport torch.distributed as dist
import logginglogger = logging.getLogger(__name__)
########################### Basic utility for distributed info ################################
def is_dist_avail_and_initialized(): if not dist.is_available(): return False if not dist.is_initialized(): return False return True
def get_rank(): """ Get the rank of the current process. """ if not is_dist_avail_and_initialized(): return 0 return dist.get_rank()
def get_world_size(): """ Get the size of the world. """ if not is_dist_avail_and_initialized(): return 1 return dist.get_world_size()
def is_master_proc(num_gpus=8): """ Determines if the current process is the master process on each node. """ if is_dist_avail_and_initialized(): return dist.get_rank() % num_gpus == 0 else: return True
def is_root_proc(): """ Determines if the current process is the root process. """ if is_dist_avail_and_initialized(): return dist.get_rank() == 0 else: return True
############################## Data gathering across devices ##################################
def _serialize_to_tensor(data, group, max_size=1024): """ Serialize the tensor to ByteTensor. Note that only `gloo` and `nccl` backend is supported. Args: data (data): data to be serialized. group (group): pytorch dist group. Returns: tensor (ByteTensor): tensor that serialized. """ backend = dist.get_backend(group) assert backend in ["gloo", "nccl"] device = torch.device("cpu" if backend == "gloo" else "cuda")
buffer = pickle.dumps(data) if len(buffer) > max_size ** 3: logger.warning( "Rank {} trying to all-gather {:.2f} GB of data on device {}".format( get_rank(), len(buffer) / (max_size ** 3), device ) ) storage = torch.ByteStorage.from_buffer(buffer) tensor = torch.ByteTensor(storage).to(device=device) return tensor
def _pad_to_largest_tensor(tensor, group): """ Padding all the tensors from different GPUs to the largest ones. Args: tensor (tensor): tensor to pad. group (group): pytorch dist group. Returns: list[int]: size of the tensor, on each rank Tensor: padded tensor that has the max size """ world_size = dist.get_world_size(group=group) assert ( world_size >= 1 ), "comm.gather/all_gather must be called from ranks within the given group!" local_size = torch.tensor( [tensor.numel()], dtype=torch.int64, device=tensor.device ) size_list = [ torch.zeros([1], dtype=torch.int64, device=tensor.device) for _ in range(world_size) ] dist.all_gather(size_list, local_size, group=group) size_list = [int(size.item()) for size in size_list]
max_size = max(size_list)
# we pad the tensor because torch all_gather does not support # gathering tensors of different shapes if local_size != max_size: padding = torch.zeros( (max_size - local_size,), dtype=torch.uint8, device=tensor.device ) tensor = torch.cat((tensor, padding), dim=0) return size_list, tensor
def broadcast(object): if isinstance(object, torch.Tensor): dist.broadcast(tensor=object, src=0) else: sync_tensor = torch.Tensor([object]).cuda() dist.broadcast(tensor=sync_tensor, src=0) object = sync_tensor[0].item() return object
def all_gather(tensors): """ All gathers the provided tensors from all processes across machines. Args: tensors (list): tensors to perform all gather across all processes in all machines. """ gather_list = [] output_tensor = [] world_size = dist.get_world_size() for tensor in tensors: tensor_placeholder = [ torch.ones_like(tensor) for _ in range(world_size) ] dist.all_gather(tensor_placeholder, tensor, async_op=False) gather_list.append(tensor_placeholder) for gathered_tensor in gather_list: output_tensor.append(torch.cat(gathered_tensor, dim=0)) return output_tensor
def all_reduce(tensors, average=True): """ All reduce the provided tensors from all processes across machines. Args: tensors (list): tensors to perform all reduce across all processes in all machines. average (bool): scales the reduced tensor by the number of overall processes across all machines. """ for tensor in tensors: dist.all_reduce(tensor, async_op=False) if average: world_size = dist.get_world_size() for tensor in tensors: tensor.mul_(1.0 / world_size) return tensors
@functools.lru_cache()def _get_global_gloo_group(): """ Return a process group based on gloo backend, containing all the ranks The result is cached. Returns: (group): pytorch dist group. """ if dist.get_backend() == "nccl": return dist.new_group(backend="gloo") else: return dist.group.WORLD
def all_gather_unaligned(data, group=None): """ Run all_gather on arbitrary picklable data (not necessarily tensors).
Args: data: any picklable object group: a torch process group. By default, will use a group which contains all ranks on gloo backend.
Returns: list[data]: list of data gathered from each rank """ if get_world_size() == 1: return [data] if group is None: group = _get_global_gloo_group() if dist.get_world_size(group) == 1: return [data]
tensor = _serialize_to_tensor(data, group)
size_list, tensor = _pad_to_largest_tensor(tensor, group) max_size = max(size_list)
# receiving Tensor from all ranks tensor_list = [ torch.empty((max_size,), dtype=torch.uint8, device=tensor.device) for _ in size_list ] dist.all_gather(tensor_list, tensor, group=group)
data_list = [] for size, tensor in zip(size_list, tensor_list): buffer = tensor.cpu().numpy().tobytes()[:size] data_list.append(pickle.loads(buffer))
return data_list123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133import csvimport pickleimport jsonimport cv2import yamlimport numpy as npfrom pathlib import Pathimport torchimport open3dfrom plyfile import PlyData
def make_dir(dir_path): if not Path(dir_path).exists(): Path(dir_path).mkdir(parents=True, exist_ok=True)
def load_imgs(img_paths, option=cv2.IMREAD_COLOR): imgs = [cv2.imread(img_path, option) for img_path in img_paths] return imgs
def load_pickle(filename): with Path(filename).open("rb") as f: return pickle.load(f)
def save_pickle(data, filename): with Path(filename).open("wb") as f: pickle.dump(data, f, protocol=pickle.HIGHEST_PROTOCOL)
def load_json(filename): with Path(filename).open("rb") as f: return json.load(f)
def save_json(data, filename, save_pretty=True, sort_keys=False): with Path(filename).open("w") as f: if save_pretty: f.write(json.dumps(data, indent=4, sort_keys=sort_keys)) else: json.dump(data, f)
def load_jsonl(filename): with Path(filename).open("r") as f: return [json.loads(l.strip("\n")) for l in f.readlines()]
def save_jsonl(data, filename): with Path(filename).open("w") as f: f.write("\n".join([json.dumps(e) for e in data]))
def load_yaml(filename): with Path(filename).open("r") as f: return yaml.load(f, Loader=yaml.SafeLoader)
def save_yaml(data, filename): with Path(filename).open("w") as f: yaml.dump(data, f, default_flow_style=False)
def load_csv(filename, delimiter=","): idx2key = None contents = {} with Path(filename).open("r") as f: reader = csv.reader(f, delimiter=delimiter) for l_idx, row in reader: if l_idx == 0: idx2key = row for k_idx, key in enumerate(idx2key): contents[key] = [] else: for c_idx, col in enumerate(row): contents[idx2key[c_idx]].append(col) return contents, idx2key
def save_csv(data, filename, cols=None, delimiter=","): with Path(filename).open("w") as f: writer = csv.writer(f, delimiter=delimiter) num_entries = len(data[list(data.keys())[0]]) assert cols is not None, "Must have column names for dumping csv files." writer.writerow(cols) for l_idx in range(num_entries): row = [data[key][l_idx] for key in cols] writer.writerow(row)
def load_numpy(filename): return np.load(filename, allow_pickle=True)
def save_numpy(data, filename): np.save(filename, data, allow_pickle=True)
def load_tensor(filename): return torch.load(filename)
def save_tensor(data, filename): torch.save(data, filename)
def load_ply(filepath): with open(filepath, "rb") as f: plydata = PlyData.read(f) data = plydata.elements[0].data coords = np.array([data["x"], data["y"], data["z"]], dtype=np.float32).T feats = None labels = None if ({"red", "green", "blue"} - set(data.dtype.names)) == set(): feats = np.array([data["red"], data["green"], data["blue"]], dtype=np.uint8).T if "label" in data.dtype.names: labels = np.array(data["label"], dtype=np.uint32) return coords, feats, labels
def load_ply_with_normals(filepath): mesh = open3d.io.read_triangle_mesh(str(filepath)) if not mesh.has_vertex_normals(): mesh.compute_vertex_normals() vertices = np.asarray(mesh.vertices) normals = np.asarray(mesh.vertex_normals)
coords, feats, labels = load_ply(filepath) assert np.allclose(coords, vertices), "different coordinates" feats = np.hstack((feats, normals))
return coords, feats, labels123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121import osfrom pathlib import Pathimport subprocess
import submitit
huggingface_fix = f"TRANSFORMERS_OFFLINE=1 CURL_CA_BUNDLE=''"
class SubmititLauncher: def __init__(self, args): self.args = args
def __call__(self): host_name = os.popen( "scontrol show hostnames $SLURM_JOB_NODELIST" ).read().split("\n")[0] self._set_gpu_args() # Using Accelerate for launching multi_gpu = "--multi_gpu" if self.args.num_nodes * self.args.gpu_per_node > 1 else "" opts = " ".join(self.args.opts) if len(self.args.opts) > 0 else "" opts += f" num_gpu={self.args.num_nodes * self.args.gpu_per_node} " full_cfg_path = Path(self.args.config) cfg_path, cfg_file = str(full_cfg_path.parent), str(full_cfg_path.name) cmd = f"{huggingface_fix} accelerate launch --num_machines {self.args.num_nodes} \ --mixed_precision {self.args.mixed_precision} {multi_gpu} \ --num_processes {self.args.gpu_per_node * self.args.num_nodes} \ --num_cpu_threads_per_process {self.args.cpu_per_task} \ --main_process_ip {host_name} \ --main_process_port {self.args.port} \ --machine_rank {self.args.node_id} \ --dynamo_backend no \ {self.args.run_file} \ --config-path {cfg_path} \ --config-name {cfg_file} \ num_gpu={self.args.num_nodes * self.args.gpu_per_node} \ hydra.run.dir=. \ hydra.output_subdir=null \ hydra/job_logging=disabled \ hydra/hydra_logging=disabled {opts}" subprocess.run(cmd, shell=True) def _set_gpu_args(self): job_env = submitit.JobEnvironment() self.args.job_dir = str(self.args.job_dir).replace("%j", job_env.job_id) self.args.node_id = int(job_env.global_rank / self.args.gpu_per_node)
def submitit_launch(args): """ Multi node script launching with Submitit """ additional_parameters = {} if args.nodelist != "": # if specifying node id nodelist = f"{str(args.nodelist)}" additional_parameters["nodelist"] = nodelist
executor = submitit.AutoExecutor(folder=args.job_dir, slurm_max_num_timeout=30) executor.update_parameters( name=args.name, mem_gb=args.mem_per_gpu * args.gpu_per_node * args.num_nodes, gpus_per_node=args.gpu_per_node, tasks_per_node=1, cpus_per_task=args.gpu_per_node * args.cpu_per_task, nodes=args.num_nodes, slurm_qos=args.qos, slurm_partition=args.partition, slurm_account=args.account, slurm_time=args.time * 60, slurm_signal_delay_s=120, slurm_additional_parameters=additional_parameters ) launcher = SubmititLauncher(args) job = executor.submit(launcher) print(f"submitted job: {job.job_id}")
def accelerate_launch(args): """ Single node script launching with Accelerate """ opts = " ".join(args.opts) if len(args.opts) > 0 else "" opts += f" num_gpu={args.num_nodes * args.gpu_per_node} " multi_gpu = "--multi_gpu" if args.num_nodes * args.gpu_per_node > 1 else "" full_cfg_path = Path(args.config) cfg_path, cfg_file = str(full_cfg_path.parent), str(full_cfg_path.name) cmd = f"{huggingface_fix} accelerate launch --num_machines {args.num_nodes} \ {multi_gpu} \ --mixed_precision {args.mixed_precision} \ --num_processes {args.gpu_per_node * args.num_nodes} \ --num_cpu_threads_per_process {args.cpu_per_task} \ --dynamo_backend no \ {args.run_file} \ --config-path {cfg_path} \ --config-name {cfg_file} \ num_gpu={args.num_nodes * args.gpu_per_node} \ hydra.run.dir=. \ hydra.output_subdir=null \ hydra/job_logging=disabled \ hydra/hydra_logging=disabled {opts}" subprocess.run(cmd, shell=True)
def python_launch(args): """ Vanilla python launcher for degbugging purposes """ opts = " ".join(args.opts) if len(args.opts) > 0 else "" full_cfg_path = Path(args.config) cfg_path, cfg_file = str(full_cfg_path.parent), str(full_cfg_path.name) cmd = f"{huggingface_fix} python {args.run_file} " \ f"--config-path {cfg_path} " \ f"--config-name {cfg_file} " \ f"num_gpu=1 " \ f"hydra.run.dir=. " \ f"hydra.output_subdir=null " \ f"hydra/job_logging=disabled " \ f"hydra/hydra_logging=disabled {opts}" subprocess.run(cmd, shell=True).gitattributes+12-58
.gitignoreAdded+8
LICENSEAdded+21
POMA_BENCH/eval_scene_retrieval.pyAdded+275
POMA_BENCH/eval_view_retrieval.pyAdded+488
POMA_BENCH/job/internvl3_8b_fine_tune_coco_job_error_50985.txtAdded+1
POMA_BENCH/job/internvl3_8b_fine_tune_coco_job_error_50989.txtAdded+1
POMA_BENCH/job/internvl3_8b_fine_tune_coco_job_error_51020.txtAdded+1
POMA_BENCH/job/internvl3_8b_fine_tune_coco_job_error_51021.txtAdded+1
POMA_BENCH/job/internvl3_8b_fine_tune_coco_job_error_51022.txtAdded+1
POMA_BENCH/job/internvl3_8b_fine_tune_coco_job_error_51029.txtAdded+1
POMA_BENCH/job/internvl3_8b_fine_tune_coco_job_error_51042.txtAdded+1
POMA_BENCH/job/internvl3_8b_fine_tune_coco_job_error_51044.txtAdded+1
POMA_BENCH/job/internvl3_8b_fine_tune_coco_job_error_51045.txtAdded+1
POMA_BENCH/job/internvl3_8b_fine_tune_coco_job_output_50985.txtAdded
POMA_BENCH/job/internvl3_8b_fine_tune_coco_job_output_50989.txtAdded
POMA_BENCH/job/internvl3_8b_fine_tune_coco_job_output_51020.txtAdded
POMA_BENCH/job/internvl3_8b_fine_tune_coco_job_output_51021.txtAdded
POMA_BENCH/job/internvl3_8b_fine_tune_coco_job_output_51022.txtAdded
POMA_BENCH/job/internvl3_8b_fine_tune_coco_job_output_51029.txtAdded
POMA_BENCH/job/internvl3_8b_fine_tune_coco_job_output_51042.txtAdded
POMA_BENCH/job/internvl3_8b_fine_tune_coco_job_output_51044.txtAdded
POMA_BENCH/job/internvl3_8b_fine_tune_coco_job_output_51045.txtAdded
POMA_BENCH/nr3d_retrieval.jsonlAdded+3
POMA_BENCH/ret.shAdded+36
POMA_BENCH/scanrefer_retrieval.jsonlAdded+3
POMA_BENCH/scene_cap.jsonAdded
POMA_BENCH/sr3d_retrieval.jsonlAdded+3
POMA_BENCH/ssg_ref_total_by_view.jsonlAdded+3
POMA_BENCH/ssg_ref_total_by_view_full.jsonlAdded+3
assets/logo025.pngAdded

Large File Pointer Details
- SHA256: 26b0012c75b78a0e1cd3c44bd5715f1faf149eca4334daa3fdd67c0a44892ad5
- Pointer size: 132 Bytes
- Size of remote file: 1.38 MB
assets/overview.pngAdded

Large File Pointer Details
- SHA256: ba4e2a232e56914ec7cacff5bfd293cd5bd73753df379ff26fe2bf545c9b5b52
- Pointer size: 132 Bytes
- Size of remote file: 6.97 MB
chamfer_rankings.jsonAdded+3
common/__pycache__/box_utils.cpython-310.pycAdded
common/__pycache__/box_utils.cpython-39.pycAdded
common/__pycache__/dist_utils.cpython-310.pycAdded
common/__pycache__/dist_utils.cpython-39.pycAdded
common/__pycache__/io_utils.cpython-310.pycAdded
common/__pycache__/io_utils.cpython-39.pycAdded
common/__pycache__/launch_utils.cpython-310.pycAdded
common/__pycache__/launch_utils.cpython-313.pycAdded
common/__pycache__/launch_utils.cpython-39.pycAdded
common/__pycache__/misc.cpython-310.pycAdded
common/__pycache__/misc.cpython-39.pycAdded
common/__pycache__/type_utils.cpython-310.pycAdded
common/__pycache__/type_utils.cpython-39.pycAdded
common/box_utils.pyAdded+66
common/dist_utils.pyAdded+220
common/io_utils.pyAdded+133
common/launch_utils.pyAdded+121