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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
|
| 4 |
+
import os, glob, re, torch, numpy as np
|
| 5 |
+
from typing import List, Tuple
|
| 6 |
+
from safetensors.torch import load_file
|
| 7 |
+
import gradio as gr
|
| 8 |
+
import plotly.graph_objects as go
|
| 9 |
+
import torch.nn as nn
|
| 10 |
+
from huggingface_hub import hf_hub_download, list_repo_files
|
| 11 |
+
|
| 12 |
+
# =========================
|
| 13 |
+
# Config
|
| 14 |
+
# =========================
|
| 15 |
+
LOCAL_FILE_DEFAULT = "assets/scene0073_00.safetensors" # local safetensors file
|
| 16 |
+
PM_KEY_DEFAULT = "point_map"
|
| 17 |
+
TOPK_VIEWS_DEFAULT = 3
|
| 18 |
+
|
| 19 |
+
VOXEL_SIZE = 0.02
|
| 20 |
+
DOWNSAMPLE_N_MAX = 600_000
|
| 21 |
+
POINT_SIZE_MIN = 1.2
|
| 22 |
+
POINT_SIZE_MAX = 2.0
|
| 23 |
+
|
| 24 |
+
CLR_RED = "rgba(230,40,40,0.98)"
|
| 25 |
+
BG_COLOR = "#f7f9fb"
|
| 26 |
+
GRID_COLOR = "#e6ecf2"
|
| 27 |
+
BOX_COLOR = "rgba(80,80,80,0.6)"
|
| 28 |
+
|
| 29 |
+
TOP_VIEW_IMAGE_PATH = "assets/scene0073_00.png"
|
| 30 |
+
|
| 31 |
+
DEFAULT_CAM = dict(
|
| 32 |
+
eye=dict(x=1.35, y=1.35, z=0.95),
|
| 33 |
+
up=dict(x=0, y=0, z=1),
|
| 34 |
+
center=dict(x=0, y=0, z=0),
|
| 35 |
+
projection=dict(type="perspective"),
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
def _merge_safetensors_dicts(paths: List[str]):
|
| 39 |
+
merged = {}
|
| 40 |
+
for p in paths:
|
| 41 |
+
sd = load_file(p, device="cpu")
|
| 42 |
+
merged.update(sd)
|
| 43 |
+
return merged
|
| 44 |
+
|
| 45 |
+
def _local_all_under(path: str) -> List[str]:
|
| 46 |
+
out = []
|
| 47 |
+
if os.path.isfile(path):
|
| 48 |
+
return [path]
|
| 49 |
+
for root, _, files in os.walk(path):
|
| 50 |
+
for f in files:
|
| 51 |
+
out.append(os.path.join(root, f))
|
| 52 |
+
return sorted(out)
|
| 53 |
+
|
| 54 |
+
# =========================
|
| 55 |
+
# Load pretrained (your existing loader)
|
| 56 |
+
# =========================
|
| 57 |
+
def load_pretrain(
|
| 58 |
+
model: torch.nn.Module,
|
| 59 |
+
ckpt_path: str, # e.g. "assets/ckpt_100.pth" or "assets/model.safetensors"
|
| 60 |
+
repo_id: str = "MatchLab/poma3d-demo",
|
| 61 |
+
revision: str = "main",
|
| 62 |
+
allow_local_fallback: bool = True,
|
| 63 |
+
):
|
| 64 |
+
if allow_local_fallback and (os.path.isfile(ckpt_path) or os.path.isdir(ckpt_path)):
|
| 65 |
+
print(f"📂 Using local checkpoint(s): {ckpt_path}")
|
| 66 |
+
local_files = _local_all_under(ckpt_path)
|
| 67 |
+
else:
|
| 68 |
+
# 2) REMOTE: resolve file list from Space
|
| 69 |
+
print(f"📦 Resolving from HF Space: {repo_id}/{ckpt_path} (rev={revision})")
|
| 70 |
+
files = list_repo_files(repo_id=repo_id, repo_type='model', revision=revision)
|
| 71 |
+
|
| 72 |
+
# Exact file hit?
|
| 73 |
+
if ckpt_path in files:
|
| 74 |
+
to_fetch = [ckpt_path]
|
| 75 |
+
else:
|
| 76 |
+
# Treat ckpt_path as a folder prefix (ensure trailing slash for matching)
|
| 77 |
+
prefix = ckpt_path if ckpt_path.endswith("/") else ckpt_path + "/"
|
| 78 |
+
to_fetch = [f for f in files if f.startswith(prefix)]
|
| 79 |
+
if not to_fetch:
|
| 80 |
+
preview = "\n".join(files[:100])
|
| 81 |
+
raise FileNotFoundError(
|
| 82 |
+
f"'{ckpt_path}' not found in Space '{repo_id}' (rev='{revision}').\n"
|
| 83 |
+
f"Files present (first 100):\n{preview}"
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
# Download all matching files locally
|
| 87 |
+
local_files = []
|
| 88 |
+
for rel in to_fetch:
|
| 89 |
+
lp = hf_hub_download(repo_id=repo_id, filename=rel, repo_type='model', revision=revision)
|
| 90 |
+
local_files.append(lp)
|
| 91 |
+
local_files.sort()
|
| 92 |
+
|
| 93 |
+
# Filter by types we know how to load
|
| 94 |
+
safes = [p for p in local_files if p.endswith(".safetensors")]
|
| 95 |
+
pths = [p for p in local_files if re.search(r"\.(?:pth|pt)$", p)]
|
| 96 |
+
|
| 97 |
+
if safes:
|
| 98 |
+
print(f"🧩 Found {len(safes)} .safetensors shard(s); merging…")
|
| 99 |
+
state = _merge_safetensors_dicts(safes)
|
| 100 |
+
elif pths:
|
| 101 |
+
# pick the largest .pth/.pt to avoid optimizer/state variants
|
| 102 |
+
pths_sorted = sorted(pths, key=lambda p: os.path.getsize(p), reverse=True)
|
| 103 |
+
pick = pths_sorted[0]
|
| 104 |
+
print(f"🧩 Using .pth/.pt: {os.path.basename(pick)} (largest of {len(pths)} candidates)")
|
| 105 |
+
state = torch.load(pick, map_location="cpu")
|
| 106 |
+
# strip common prefixes
|
| 107 |
+
if isinstance(state, dict) and any(k.startswith(("model.", "target_model.")) for k in state.keys()):
|
| 108 |
+
state = { (k.split(".", 1)[1] if k.startswith(("model.", "target_model.")) else k): v
|
| 109 |
+
for k, v in state.items() }
|
| 110 |
+
# nested 'state_dict'
|
| 111 |
+
if isinstance(state, dict) and "state_dict" in state and isinstance(state["state_dict"], dict):
|
| 112 |
+
state = state["state_dict"]
|
| 113 |
+
else:
|
| 114 |
+
raise FileNotFoundError(
|
| 115 |
+
"No loadable checkpoint found. Expecting one or more of: "
|
| 116 |
+
".safetensors or .pth/.pt under the given path."
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
# Load into model
|
| 120 |
+
result = model.load_state_dict(state, strict=False)
|
| 121 |
+
|
| 122 |
+
# Report
|
| 123 |
+
weight_keys = set(state.keys()) if isinstance(state, dict) else set()
|
| 124 |
+
model_keys = set(model.state_dict().keys())
|
| 125 |
+
loaded_keys = model_keys.intersection(weight_keys)
|
| 126 |
+
print("✅ Weights loaded")
|
| 127 |
+
print(f" • Loaded keys: {len(loaded_keys)}")
|
| 128 |
+
print(f" • Missing keys: {len(result.missing_keys)}")
|
| 129 |
+
print(f" • Unexpected keys: {len(result.unexpected_keys)}")
|
| 130 |
+
|
| 131 |
+
return result
|
| 132 |
+
# =========================
|
| 133 |
+
# Representation model (fg-clip-base + LoRA)
|
| 134 |
+
# =========================
|
| 135 |
+
def build_model(device: torch.device):
|
| 136 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, AutoConfig
|
| 137 |
+
from peft import LoraConfig, get_peft_model
|
| 138 |
+
|
| 139 |
+
class RepModel(torch.nn.Module):
|
| 140 |
+
def __init__(self, model_root="qihoo360/fg-clip-base"):
|
| 141 |
+
super().__init__()
|
| 142 |
+
lora_cfg = LoraConfig(
|
| 143 |
+
r=32, lora_alpha=64,
|
| 144 |
+
target_modules=["q_proj","k_proj","v_proj","fc1","fc2"],
|
| 145 |
+
lora_dropout=0.05, bias="none",
|
| 146 |
+
task_type="FEATURE_EXTRACTION"
|
| 147 |
+
)
|
| 148 |
+
cfg = AutoConfig.from_pretrained(model_root, trust_remote_code=True)
|
| 149 |
+
base = AutoModelForCausalLM.from_config(cfg, trust_remote_code=True)
|
| 150 |
+
self.target_model = get_peft_model(base, lora_cfg)
|
| 151 |
+
self.tokenizer = AutoTokenizer.from_pretrained(model_root, trust_remote_code=True, use_fast=True)
|
| 152 |
+
|
| 153 |
+
@torch.no_grad()
|
| 154 |
+
def get_text_feature(self, texts, device):
|
| 155 |
+
tok = self.tokenizer(texts, padding="max_length", truncation=True, max_length=248, return_tensors="pt").to(device)
|
| 156 |
+
feats = self.target_model.get_text_features(tok["input_ids"], walk_short_pos=False)
|
| 157 |
+
feats = torch.nn.functional.normalize(feats.float(), dim=-1)
|
| 158 |
+
return feats
|
| 159 |
+
|
| 160 |
+
@torch.no_grad()
|
| 161 |
+
def get_image_feature(self, pm_batched):
|
| 162 |
+
feats = self.target_model.get_image_features(pm_batched)
|
| 163 |
+
feats = torch.nn.functional.normalize(feats.float(), dim=-1)
|
| 164 |
+
return feats
|
| 165 |
+
|
| 166 |
+
m = RepModel().to(device).eval()
|
| 167 |
+
print("Using fg-clip-base RepModel.")
|
| 168 |
+
return m
|
| 169 |
+
|
| 170 |
+
# =========================
|
| 171 |
+
# Data loading & helpers
|
| 172 |
+
# =========================
|
| 173 |
+
def load_scene_local(path: str, pm_key: str = PM_KEY_DEFAULT) -> torch.Tensor:
|
| 174 |
+
if not os.path.exists(path):
|
| 175 |
+
raise FileNotFoundError(f"Local file not found: {path}")
|
| 176 |
+
sd = load_file(path)
|
| 177 |
+
if pm_key not in sd:
|
| 178 |
+
raise KeyError(f"Key '{pm_key}' not found in {list(sd.keys())}")
|
| 179 |
+
pm = sd[pm_key] # (V,H,W,3)
|
| 180 |
+
if pm.dim() != 4 or pm.shape[-1] != 3:
|
| 181 |
+
raise ValueError(f"Invalid shape {tuple(pm.shape)}, expected (V,H,W,3)")
|
| 182 |
+
return pm.permute(0, 3, 1, 2).contiguous() # -> (V,3,H,W)
|
| 183 |
+
|
| 184 |
+
def _xyz_to_numpy(xyz: torch.Tensor) -> np.ndarray:
|
| 185 |
+
pts = xyz.permute(1, 2, 0).reshape(-1, 3).cpu().numpy().astype(np.float32)
|
| 186 |
+
mask = np.isfinite(pts).all(axis=1)
|
| 187 |
+
return pts[mask]
|
| 188 |
+
|
| 189 |
+
def stack_views(pm: torch.Tensor) -> Tuple[np.ndarray, np.ndarray]:
|
| 190 |
+
pts_all, vid_all = [], []
|
| 191 |
+
for v in range(pm.shape[0]):
|
| 192 |
+
pts = _xyz_to_numpy(pm[v])
|
| 193 |
+
if pts.size == 0: continue
|
| 194 |
+
pts_all.append(pts)
|
| 195 |
+
vid_all.append(np.full((pts.shape[0],), v, dtype=np.int32))
|
| 196 |
+
pts_all = np.concatenate(pts_all, axis=0)
|
| 197 |
+
vid_all = np.concatenate(vid_all, axis=0)
|
| 198 |
+
return pts_all, vid_all
|
| 199 |
+
|
| 200 |
+
def voxel_downsample_with_ids(pts, vids, voxel: float):
|
| 201 |
+
if pts.shape[0] == 0: return pts, vids
|
| 202 |
+
grid = np.floor(pts / voxel).astype(np.int64)
|
| 203 |
+
key = np.core.records.fromarrays(grid.T, names="x,y,z", formats="i8,i8,i8")
|
| 204 |
+
_, uniq_idx = np.unique(key, return_index=True)
|
| 205 |
+
return pts[uniq_idx], vids[uniq_idx]
|
| 206 |
+
|
| 207 |
+
def hard_cap(pts, vids, cap: int):
|
| 208 |
+
N = pts.shape[0]
|
| 209 |
+
if N <= cap: return pts, vids
|
| 210 |
+
idx = np.random.choice(N, size=cap, replace=False)
|
| 211 |
+
return pts[idx], vids[idx]
|
| 212 |
+
|
| 213 |
+
def adaptive_point_size(n: int) -> float:
|
| 214 |
+
ps = 2.4 * (150_000 / max(n, 10)) ** 0.25
|
| 215 |
+
return float(np.clip(ps, POINT_SIZE_MIN, POINT_SIZE_MAX))
|
| 216 |
+
|
| 217 |
+
def scene_bbox(pts: np.ndarray):
|
| 218 |
+
mn, mx = pts.min(axis=0), pts.max(axis=0)
|
| 219 |
+
x0,y0,z0 = mn; x1,y1,z1 = mx
|
| 220 |
+
corners = np.array([
|
| 221 |
+
[x0,y0,z0],[x1,y0,z0],[x1,y1,z0],[x0,y1,z0],
|
| 222 |
+
[x0,y0,z1],[x1,y0,z1],[x1,y1,z1],[x0,y1,z1]
|
| 223 |
+
])
|
| 224 |
+
edges = [(0,1),(1,2),(2,3),(3,0),(4,5),(5,6),(6,7),(7,4),(0,4),(1,5),(2,6),(3,7)]
|
| 225 |
+
xs,ys,zs=[],[],[]
|
| 226 |
+
for a,b in edges:
|
| 227 |
+
xs += [corners[a,0], corners[b,0], None]
|
| 228 |
+
ys += [corners[a,1], corners[b,1], None]
|
| 229 |
+
zs += [corners[a,2], corners[b,2], None]
|
| 230 |
+
return xs,ys,zs
|
| 231 |
+
|
| 232 |
+
@torch.no_grad()
|
| 233 |
+
def rank_views_for_text(model, text, pm, device, topk: int):
|
| 234 |
+
img_feats = model.get_image_feature(pm.float().to(device))
|
| 235 |
+
txt_feat = model.get_text_feature([text], device=device)[0]
|
| 236 |
+
sims = torch.matmul(img_feats, txt_feat)
|
| 237 |
+
order = torch.argsort(sims, descending=True)[:max(1, int(topk))]
|
| 238 |
+
return order.tolist()
|
| 239 |
+
|
| 240 |
+
# =========================
|
| 241 |
+
# Visualization
|
| 242 |
+
# =========================
|
| 243 |
+
def depth_values(pts: np.ndarray) -> np.ndarray:
|
| 244 |
+
z = pts[:, 2]
|
| 245 |
+
z_min, z_max = z.min(), z.max()
|
| 246 |
+
return (z - z_min) / (z_max - z_min + 1e-9)
|
| 247 |
+
|
| 248 |
+
def base_figure_gray_depth(pts: np.ndarray, point_size: float, camera=DEFAULT_CAM) -> go.Figure:
|
| 249 |
+
depth = depth_values(pts)
|
| 250 |
+
fig = go.Figure(go.Scatter3d(
|
| 251 |
+
x=pts[:,0], y=pts[:,1], z=pts[:,2],
|
| 252 |
+
mode="markers",
|
| 253 |
+
marker=dict(size=point_size, color=depth, colorscale="Greys", reversescale=True, opacity=0.50),
|
| 254 |
+
hoverinfo="skip"
|
| 255 |
+
))
|
| 256 |
+
bx,by,bz = scene_bbox(pts)
|
| 257 |
+
fig.add_trace(go.Scatter3d(x=bx,y=by,z=bz,mode="lines",line=dict(color=BOX_COLOR,width=2),hoverinfo="skip"))
|
| 258 |
+
fig.update_layout(scene=dict(aspectmode="data",camera=camera),
|
| 259 |
+
margin=dict(l=0,r=0,b=0,t=0),
|
| 260 |
+
paper_bgcolor=BG_COLOR,
|
| 261 |
+
showlegend=False)
|
| 262 |
+
return fig
|
| 263 |
+
|
| 264 |
+
def highlight_views_3d(pts, view_ids, selected, point_size, camera=DEFAULT_CAM):
|
| 265 |
+
depth = depth_values(pts)
|
| 266 |
+
colors = np.stack([depth, depth, depth], axis=1)
|
| 267 |
+
if selected:
|
| 268 |
+
sel_mask = np.isin(view_ids, np.array(selected, dtype=np.int32))
|
| 269 |
+
colors[sel_mask] = np.array([1, 0, 0])
|
| 270 |
+
fig = go.Figure(go.Scatter3d(
|
| 271 |
+
x=pts[:,0], y=pts[:,1], z=pts[:,2],
|
| 272 |
+
mode="markers",
|
| 273 |
+
marker=dict(size=point_size,
|
| 274 |
+
color=[f"rgb({int(r*255)},{int(g*255)},{int(b*255)})"
|
| 275 |
+
for r,g,b in colors],
|
| 276 |
+
opacity=0.98),
|
| 277 |
+
hoverinfo="skip"
|
| 278 |
+
))
|
| 279 |
+
bx,by,bz = scene_bbox(pts)
|
| 280 |
+
fig.add_trace(go.Scatter3d(x=bx,y=by,z=bz,mode="lines",
|
| 281 |
+
line=dict(color=BOX_COLOR,width=2),hoverinfo="skip"))
|
| 282 |
+
fig.update_layout(scene=dict(aspectmode="data",camera=camera),
|
| 283 |
+
margin=dict(l=0,r=0,b=0,t=0),
|
| 284 |
+
paper_bgcolor=BG_COLOR,
|
| 285 |
+
showlegend=False)
|
| 286 |
+
return fig
|
| 287 |
+
|
| 288 |
+
# =========================
|
| 289 |
+
# App setup
|
| 290 |
+
# =========================
|
| 291 |
+
device = 'cpu'
|
| 292 |
+
model = build_model(device)
|
| 293 |
+
load_pretrain(model, "assets/ckpt_100.pth")
|
| 294 |
+
|
| 295 |
+
with gr.Blocks(
|
| 296 |
+
title="POMA-3D: Text-conditioned 3D Scene Visualization",
|
| 297 |
+
css="#plot3d, #img_ref {height: 450px !important;}"
|
| 298 |
+
) as demo:
|
| 299 |
+
gr.Markdown("### POMA-3D: The Point Map Way to 3D Scene Understanding - Embodied Localization Demo\n"
|
| 300 |
+
"Enter agent's situation text and choose **Top-K**; the most relevant views will turn **red**.")
|
| 301 |
+
|
| 302 |
+
with gr.Row():
|
| 303 |
+
text_in = gr.Textbox(label="Text query", value="I am sleeping on the bed.", scale=4)
|
| 304 |
+
topk_in = gr.Number(label="Top-K views", value=TOPK_VIEWS_DEFAULT, precision=0, minimum=1, maximum=12)
|
| 305 |
+
submit_btn = gr.Button("Locate", variant="primary")
|
| 306 |
+
|
| 307 |
+
with gr.Row(equal_height=True):
|
| 308 |
+
with gr.Column(scale=1, min_width=500):
|
| 309 |
+
plot3d = gr.Plot(label="3D Point Cloud (rotatable)", elem_id="plot3d")
|
| 310 |
+
with gr.Column(scale=1, min_width=500):
|
| 311 |
+
img_ref = gr.Image(label="Top-Down Reference View", value=TOP_VIEW_IMAGE_PATH, elem_id="img_ref")
|
| 312 |
+
|
| 313 |
+
status = gr.Markdown()
|
| 314 |
+
|
| 315 |
+
pm_state = gr.State(None)
|
| 316 |
+
pts_state = gr.State(None)
|
| 317 |
+
vids_state = gr.State(None)
|
| 318 |
+
|
| 319 |
+
# Load scene automatically from LOCAL_FILE_DEFAULT
|
| 320 |
+
def on_load():
|
| 321 |
+
pm = load_scene_local(LOCAL_FILE_DEFAULT)
|
| 322 |
+
pts_all, vids_all = stack_views(pm)
|
| 323 |
+
pts_vx, vids_vx = voxel_downsample_with_ids(pts_all, vids_all, VOXEL_SIZE)
|
| 324 |
+
pts_vx, vids_vx = hard_cap(pts_vx, vids_vx, DOWNSAMPLE_N_MAX)
|
| 325 |
+
ps = adaptive_point_size(pts_vx.shape[0])
|
| 326 |
+
fig3d = base_figure_gray_depth(pts_vx, ps, camera=DEFAULT_CAM)
|
| 327 |
+
msg = f"✅ Loaded {os.path.basename(LOCAL_FILE_DEFAULT)} | Views: {pm.shape[0]} | Points: {pts_vx.shape[0]:,}"
|
| 328 |
+
return fig3d, TOP_VIEW_IMAGE_PATH, msg, pm, pts_vx, vids_vx
|
| 329 |
+
|
| 330 |
+
def on_submit(text, topk, pm, pts_vx, vids_vx):
|
| 331 |
+
if pm is None:
|
| 332 |
+
return gr.update(), TOP_VIEW_IMAGE_PATH, "⚠️ Scene not loaded yet."
|
| 333 |
+
k = int(max(1, min(12, int(topk)))) if topk else TOPK_VIEWS_DEFAULT
|
| 334 |
+
top_views = rank_views_for_text(model, text, pm, device, topk=k)
|
| 335 |
+
ps = adaptive_point_size(pts_vx.shape[0])
|
| 336 |
+
fig = highlight_views_3d(pts_vx, vids_vx, top_views, ps, camera=DEFAULT_CAM)
|
| 337 |
+
msg = f"Highlighted views (top-{k}): {top_views}"
|
| 338 |
+
return fig, TOP_VIEW_IMAGE_PATH, msg
|
| 339 |
+
|
| 340 |
+
demo.load(on_load, inputs=[], outputs=[plot3d, img_ref, status, pm_state, pts_state, vids_state])
|
| 341 |
+
submit_btn.click(on_submit, inputs=[text_in, topk_in, pm_state, pts_state, vids_state],
|
| 342 |
+
outputs=[plot3d, img_ref, status])
|
| 343 |
+
|
| 344 |
+
if __name__ == "__main__":
|
| 345 |
+
demo.launch()
|
assets/scene0073_00.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:1f99163e32be5d157c264a54d35b2514b57377713150c2da5fd1dd71eb4ad957
|
| 3 |
+
size 169390352
|
requirements.txt
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# --- Core runtime ---
|
| 2 |
+
numpy>=1.24,<2.3
|
| 3 |
+
torch==2.2.2
|
| 4 |
+
safetensors>=0.4.3
|
| 5 |
+
|
| 6 |
+
# --- Hugging Face stack (compatible pins) ---
|
| 7 |
+
transformers==4.44.2
|
| 8 |
+
huggingface_hub==0.24.6
|
| 9 |
+
accelerate>=0.33.0
|
| 10 |
+
peft==0.12.0
|
| 11 |
+
sentencepiece>=0.1.99
|
| 12 |
+
protobuf>=4.25.0
|
| 13 |
+
|
| 14 |
+
# --- App / UI ---
|
| 15 |
+
gradio==4.44.0
|
| 16 |
+
plotly>=5.22.0
|
| 17 |
+
|
| 18 |
+
# --- Nice-to-have for many HF vision/text models ---
|
| 19 |
+
timm>=0.9.16
|