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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
infer_upsample.py
|
| 3 |
+
=================
|
| 4 |
+
ไฝฟ็จ่ฎญ็ปๅฅฝ็ Transformer๏ผไป็ฒๅฐบๅบฆ๏ผLn๏ผ่ชๅๅฝ็ๆ็ปๅฐบๅบฆ๏ผL(n-1)๏ผใ
|
| 5 |
+
|
| 6 |
+
flow๏ผ
|
| 7 |
+
1. ่ฏปๅ็ฒๅฐบๅบฆ้ๅๆฐๆฎ๏ผ.npz๏ผ
|
| 8 |
+
2. ไธบๆฏไธช็ฒ่็นๆ้ ๅ็ผๅบๅ๏ผparent + uncles๏ผ
|
| 9 |
+
3. ่ชๅๅฝ็ๆๅญ่็น๏ผ
|
| 10 |
+
- role ็จ softmax ้ๆ ท๏ผ4็ฑป๏ผ
|
| 11 |
+
- xyz / opacity ็จๅๅฝ้ขๆต
|
| 12 |
+
- scale/rot/dc/sh ็จ embedding ๆ่ฟ้ปๆ็ดข่ฟๅ codebook ็ดขๅผ
|
| 13 |
+
4. ๅฐๅญ่็น codebook ็ดขๅผ่งฃ็ ไธบ็ๅฎๅฑๆง๏ผๆฅ่กจ๏ผ
|
| 14 |
+
5. ๅๅบๆฐ็ .ply ๆไปถ
|
| 15 |
+
|
| 16 |
+
role ็ผ็ ๏ผ
|
| 17 |
+
0 = parent 1 = uncle 2 = child 3 = EOS 4 = PAD
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
import os
|
| 21 |
+
import argparse
|
| 22 |
+
import numpy as np
|
| 23 |
+
|
| 24 |
+
import torch
|
| 25 |
+
import torch.nn.functional as F
|
| 26 |
+
from plyfile import PlyData, PlyElement
|
| 27 |
+
|
| 28 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 29 |
+
# ๅธธ้๏ผไธ train_transformer.py ไธ่ด๏ผ
|
| 30 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 31 |
+
|
| 32 |
+
ROLE_PARENT = 0
|
| 33 |
+
ROLE_UNCLE = 1
|
| 34 |
+
ROLE_CHILD = 2
|
| 35 |
+
ROLE_EOS = 3
|
| 36 |
+
ROLE_PAD = 4
|
| 37 |
+
|
| 38 |
+
MAX_CHILDREN = 32
|
| 39 |
+
MAX_UNCLES = 4
|
| 40 |
+
MAX_SEQ_LEN = 1 + MAX_UNCLES + MAX_CHILDREN + 1 # = 38
|
| 41 |
+
|
| 42 |
+
N_SCALE = 16384
|
| 43 |
+
N_ROT = 16384
|
| 44 |
+
N_DC = 4096
|
| 45 |
+
N_SH = 4096
|
| 46 |
+
N_ROLE = 4
|
| 47 |
+
|
| 48 |
+
TOKEN_DTYPE = np.dtype([
|
| 49 |
+
('dx', np.float32),
|
| 50 |
+
('dy', np.float32),
|
| 51 |
+
('dz', np.float32),
|
| 52 |
+
('scale_idx', np.int32),
|
| 53 |
+
('rot_idx', np.int32),
|
| 54 |
+
('dc_idx', np.int32),
|
| 55 |
+
('sh_idx', np.int32),
|
| 56 |
+
('opacity', np.float32),
|
| 57 |
+
('role', np.uint8),
|
| 58 |
+
])
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 62 |
+
# 1. ๅ ่ฝฝๆจกๅ
|
| 63 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 64 |
+
|
| 65 |
+
def load_model(ckpt_path: str, device: str = 'cpu'):
|
| 66 |
+
from train_transformer import SplitTransformer
|
| 67 |
+
|
| 68 |
+
ckpt = torch.load(ckpt_path, map_location=device)
|
| 69 |
+
config = ckpt.get('config', {})
|
| 70 |
+
model = SplitTransformer(**config).to(device)
|
| 71 |
+
state = ckpt.get('model_state', ckpt)
|
| 72 |
+
model.load_state_dict(state)
|
| 73 |
+
model.eval()
|
| 74 |
+
print(f"[load] {os.path.basename(ckpt_path)} "
|
| 75 |
+
f"d_model={config.get('d_model')}, "
|
| 76 |
+
f"n_layers={config.get('n_layers')}, "
|
| 77 |
+
f"d_cb={config.get('d_cb')}")
|
| 78 |
+
return model
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 82 |
+
# 2. ๅ ่ฝฝ codebook๏ผ็จไบๆ็ป่งฃ็ ็ดขๅผโ็ๅฎๅฑๆง๏ผ
|
| 83 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 84 |
+
|
| 85 |
+
def load_codebooks(codebook_dir: str) -> dict:
|
| 86 |
+
cbs = {}
|
| 87 |
+
for name in ['scale', 'rotation', 'dc', 'sh']:
|
| 88 |
+
path = os.path.join(codebook_dir, f"{name}_codebook.npz")
|
| 89 |
+
cbs[name] = np.load(path)['codebook'].astype(np.float32)
|
| 90 |
+
print(f"[load] {name}_codebook: {cbs[name].shape}")
|
| 91 |
+
return cbs
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 95 |
+
# 3. ๅ ่ฝฝ้ๅๆฐๆฎ
|
| 96 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 97 |
+
|
| 98 |
+
def load_quantized(npz_path: str) -> dict:
|
| 99 |
+
npz = np.load(npz_path)
|
| 100 |
+
return {
|
| 101 |
+
'scale_indices': npz['scale_indices'],
|
| 102 |
+
'rotation_indices': npz['rotation_indices'],
|
| 103 |
+
'dc_indices': npz['dc_indices'],
|
| 104 |
+
'sh_indices': npz['sh_indices'],
|
| 105 |
+
'positions': npz['positions'],
|
| 106 |
+
'opacities': npz['opacities'].squeeze(),
|
| 107 |
+
}
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 111 |
+
# 4. ๆ้ ๅ็ผ batch๏ผparent + uncles๏ผ
|
| 112 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 113 |
+
|
| 114 |
+
def _make_np_token(gauss_idx: int, quant: dict,
|
| 115 |
+
parent_pos: np.ndarray, role: int) -> np.ndarray:
|
| 116 |
+
pos = quant['positions'][gauss_idx]
|
| 117 |
+
delta = pos - parent_pos
|
| 118 |
+
token = np.zeros(1, dtype=TOKEN_DTYPE)
|
| 119 |
+
token['dx'] = delta[0]
|
| 120 |
+
token['dy'] = delta[1]
|
| 121 |
+
token['dz'] = delta[2]
|
| 122 |
+
token['scale_idx'] = quant['scale_indices'][gauss_idx]
|
| 123 |
+
token['rot_idx'] = quant['rotation_indices'][gauss_idx]
|
| 124 |
+
token['dc_idx'] = quant['dc_indices'][gauss_idx]
|
| 125 |
+
token['sh_idx'] = quant['sh_indices'][gauss_idx]
|
| 126 |
+
token['opacity'] = quant['opacities'][gauss_idx] / 10.0 # ไธ่ฎญ็ปๅฝไธๅไธ่ด
|
| 127 |
+
token['role'] = role
|
| 128 |
+
return token[0]
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def _seq_to_batch(seq: np.ndarray, device: str) -> dict:
|
| 132 |
+
L = len(seq)
|
| 133 |
+
xyz = np.stack([seq['dx'], seq['dy'], seq['dz']], axis=1)
|
| 134 |
+
return {
|
| 135 |
+
'xyz': torch.tensor(xyz, device=device).float().unsqueeze(0),
|
| 136 |
+
'scale': torch.tensor(seq['scale_idx'].astype(np.int64), device=device).unsqueeze(0),
|
| 137 |
+
'rot': torch.tensor(seq['rot_idx'].astype(np.int64), device=device).unsqueeze(0),
|
| 138 |
+
'dc': torch.tensor(seq['dc_idx'].astype(np.int64), device=device).unsqueeze(0),
|
| 139 |
+
'sh': torch.tensor(seq['sh_idx'].astype(np.int64), device=device).unsqueeze(0),
|
| 140 |
+
'opacity': torch.tensor(seq['opacity'].astype(np.float32), device=device).unsqueeze(0),
|
| 141 |
+
'role': torch.tensor(seq['role'].astype(np.int64), device=device).unsqueeze(0),
|
| 142 |
+
'attn_mask': torch.ones(1, L, dtype=torch.bool, device=device),
|
| 143 |
+
}
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def make_prefix_batch(p_idx: int, quant: dict,
|
| 147 |
+
max_uncles: int = MAX_UNCLES,
|
| 148 |
+
device: str = 'cpu') -> tuple:
|
| 149 |
+
N = quant['positions'].shape[0]
|
| 150 |
+
parent_pos = quant['positions'][p_idx]
|
| 151 |
+
tokens = []
|
| 152 |
+
|
| 153 |
+
# parent๏ผๅๆ ็ฝฎ้ถ๏ผ
|
| 154 |
+
t = _make_np_token(p_idx, quant, parent_pos, ROLE_PARENT)
|
| 155 |
+
t['dx'] = t['dy'] = t['dz'] = 0.0
|
| 156 |
+
tokens.append(t)
|
| 157 |
+
|
| 158 |
+
# uncles
|
| 159 |
+
half = max_uncles // 2
|
| 160 |
+
added = 0
|
| 161 |
+
for offset in list(range(-half, 0)) + list(range(1, half + 1)):
|
| 162 |
+
u_idx = p_idx + offset
|
| 163 |
+
if 0 <= u_idx < N and added < max_uncles:
|
| 164 |
+
tokens.append(_make_np_token(u_idx, quant, parent_pos, ROLE_UNCLE))
|
| 165 |
+
added += 1
|
| 166 |
+
|
| 167 |
+
return _seq_to_batch(np.array(tokens, dtype=TOKEN_DTYPE), device), parent_pos
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def _append_token(batch: dict, token_np: np.ndarray, device: str) -> dict:
|
| 171 |
+
new_xyz = torch.tensor(
|
| 172 |
+
[[[token_np['dx'], token_np['dy'], token_np['dz']]]],
|
| 173 |
+
dtype=torch.float32, device=device
|
| 174 |
+
)
|
| 175 |
+
def cat(key, val, dtype):
|
| 176 |
+
return torch.cat([batch[key],
|
| 177 |
+
torch.tensor([[val]], dtype=dtype, device=device)], dim=1)
|
| 178 |
+
return {
|
| 179 |
+
'xyz': torch.cat([batch['xyz'], new_xyz], dim=1),
|
| 180 |
+
'scale': cat('scale', int(token_np['scale_idx']), torch.int64),
|
| 181 |
+
'rot': cat('rot', int(token_np['rot_idx']), torch.int64),
|
| 182 |
+
'dc': cat('dc', int(token_np['dc_idx']), torch.int64),
|
| 183 |
+
'sh': cat('sh', int(token_np['sh_idx']), torch.int64),
|
| 184 |
+
'opacity': cat('opacity', float(token_np['opacity']), torch.float32),
|
| 185 |
+
'role': cat('role', int(token_np['role']), torch.int64),
|
| 186 |
+
'attn_mask': torch.cat([batch['attn_mask'],
|
| 187 |
+
torch.ones(1, 1, dtype=torch.bool, device=device)], dim=1),
|
| 188 |
+
}
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def make_prefix_batch_many(p_indices: np.ndarray,
|
| 192 |
+
quant: dict,
|
| 193 |
+
max_uncles: int = MAX_UNCLES,
|
| 194 |
+
device: str = 'cpu') -> tuple:
|
| 195 |
+
"""Build a padded prefix batch for multiple parent points."""
|
| 196 |
+
rows = []
|
| 197 |
+
parent_positions = quant['positions'][p_indices]
|
| 198 |
+
lengths = []
|
| 199 |
+
|
| 200 |
+
for p_idx, parent_pos in zip(p_indices, parent_positions):
|
| 201 |
+
tokens = []
|
| 202 |
+
|
| 203 |
+
t = _make_np_token(int(p_idx), quant, parent_pos, ROLE_PARENT)
|
| 204 |
+
t['dx'] = t['dy'] = t['dz'] = 0.0
|
| 205 |
+
tokens.append(t)
|
| 206 |
+
|
| 207 |
+
n_points = quant['positions'].shape[0]
|
| 208 |
+
half = max_uncles // 2
|
| 209 |
+
added = 0
|
| 210 |
+
for offset in list(range(-half, 0)) + list(range(1, half + 1)):
|
| 211 |
+
u_idx = int(p_idx) + offset
|
| 212 |
+
if 0 <= u_idx < n_points and added < max_uncles:
|
| 213 |
+
tokens.append(_make_np_token(u_idx, quant, parent_pos, ROLE_UNCLE))
|
| 214 |
+
added += 1
|
| 215 |
+
|
| 216 |
+
row = np.array(tokens, dtype=TOKEN_DTYPE)
|
| 217 |
+
rows.append(row)
|
| 218 |
+
lengths.append(len(row))
|
| 219 |
+
|
| 220 |
+
batch_size = len(rows)
|
| 221 |
+
max_len = max(lengths) if lengths else 0
|
| 222 |
+
|
| 223 |
+
xyz = np.zeros((batch_size, max_len, 3), dtype=np.float32)
|
| 224 |
+
scale = np.zeros((batch_size, max_len), dtype=np.int64)
|
| 225 |
+
rot = np.zeros((batch_size, max_len), dtype=np.int64)
|
| 226 |
+
dc = np.zeros((batch_size, max_len), dtype=np.int64)
|
| 227 |
+
sh = np.zeros((batch_size, max_len), dtype=np.int64)
|
| 228 |
+
opacity = np.zeros((batch_size, max_len), dtype=np.float32)
|
| 229 |
+
role = np.full((batch_size, max_len), ROLE_PAD, dtype=np.int64)
|
| 230 |
+
attn_mask = np.zeros((batch_size, max_len), dtype=bool)
|
| 231 |
+
|
| 232 |
+
for i, row in enumerate(rows):
|
| 233 |
+
L = len(row)
|
| 234 |
+
xyz[i, :L, :] = np.stack([row['dx'], row['dy'], row['dz']], axis=1)
|
| 235 |
+
scale[i, :L] = row['scale_idx'].astype(np.int64)
|
| 236 |
+
rot[i, :L] = row['rot_idx'].astype(np.int64)
|
| 237 |
+
dc[i, :L] = row['dc_idx'].astype(np.int64)
|
| 238 |
+
sh[i, :L] = row['sh_idx'].astype(np.int64)
|
| 239 |
+
opacity[i, :L] = row['opacity'].astype(np.float32)
|
| 240 |
+
role[i, :L] = row['role'].astype(np.int64)
|
| 241 |
+
attn_mask[i, :L] = True
|
| 242 |
+
|
| 243 |
+
batch = {
|
| 244 |
+
'xyz': torch.from_numpy(xyz).to(device=device, dtype=torch.float32),
|
| 245 |
+
'scale': torch.from_numpy(scale).to(device=device, dtype=torch.int64),
|
| 246 |
+
'rot': torch.from_numpy(rot).to(device=device, dtype=torch.int64),
|
| 247 |
+
'dc': torch.from_numpy(dc).to(device=device, dtype=torch.int64),
|
| 248 |
+
'sh': torch.from_numpy(sh).to(device=device, dtype=torch.int64),
|
| 249 |
+
'opacity': torch.from_numpy(opacity).to(device=device, dtype=torch.float32),
|
| 250 |
+
'role': torch.from_numpy(role).to(device=device, dtype=torch.int64),
|
| 251 |
+
'attn_mask': torch.from_numpy(attn_mask).to(device=device, dtype=torch.bool),
|
| 252 |
+
}
|
| 253 |
+
return batch, parent_positions.astype(np.float32), torch.tensor(lengths, device=device, dtype=torch.long)
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
def _append_tokens_batched(batch: dict,
|
| 257 |
+
row_idx: torch.Tensor,
|
| 258 |
+
lengths: torch.Tensor,
|
| 259 |
+
child_data: dict,
|
| 260 |
+
device: str) -> dict:
|
| 261 |
+
"""Append one generated child token for each active row."""
|
| 262 |
+
if row_idx.numel() == 0:
|
| 263 |
+
return batch
|
| 264 |
+
|
| 265 |
+
next_len = int(lengths[row_idx].max().item()) + 1
|
| 266 |
+
cur_len = batch['role'].shape[1]
|
| 267 |
+
if next_len > cur_len:
|
| 268 |
+
pad_len = next_len - cur_len
|
| 269 |
+
B = batch['role'].shape[0]
|
| 270 |
+
batch = {
|
| 271 |
+
'xyz': torch.cat([batch['xyz'], torch.zeros(B, pad_len, 3, device=device)], dim=1),
|
| 272 |
+
'scale': torch.cat([batch['scale'], torch.zeros(B, pad_len, dtype=torch.long, device=device)], dim=1),
|
| 273 |
+
'rot': torch.cat([batch['rot'], torch.zeros(B, pad_len, dtype=torch.long, device=device)], dim=1),
|
| 274 |
+
'dc': torch.cat([batch['dc'], torch.zeros(B, pad_len, dtype=torch.long, device=device)], dim=1),
|
| 275 |
+
'sh': torch.cat([batch['sh'], torch.zeros(B, pad_len, dtype=torch.long, device=device)], dim=1),
|
| 276 |
+
'opacity': torch.cat([batch['opacity'], torch.zeros(B, pad_len, device=device)], dim=1),
|
| 277 |
+
'role': torch.cat([batch['role'], torch.full((B, pad_len), ROLE_PAD, dtype=torch.long, device=device)], dim=1),
|
| 278 |
+
'attn_mask': torch.cat([batch['attn_mask'], torch.zeros(B, pad_len, dtype=torch.bool, device=device)], dim=1),
|
| 279 |
+
}
|
| 280 |
+
|
| 281 |
+
pos = lengths[row_idx]
|
| 282 |
+
batch['xyz'][row_idx, pos, :] = child_data['xyz']
|
| 283 |
+
batch['scale'][row_idx, pos] = child_data['scale']
|
| 284 |
+
batch['rot'][row_idx, pos] = child_data['rot']
|
| 285 |
+
batch['dc'][row_idx, pos] = child_data['dc']
|
| 286 |
+
batch['sh'][row_idx, pos] = child_data['sh']
|
| 287 |
+
batch['opacity'][row_idx, pos] = child_data['opacity_norm']
|
| 288 |
+
batch['role'][row_idx, pos] = ROLE_CHILD
|
| 289 |
+
batch['attn_mask'][row_idx, pos] = True
|
| 290 |
+
lengths[row_idx] += 1
|
| 291 |
+
return batch
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
def _sample_roles_batched(logits: torch.Tensor,
|
| 295 |
+
temperature: float,
|
| 296 |
+
top_k: int) -> torch.Tensor:
|
| 297 |
+
logits = logits / max(temperature, 1e-8)
|
| 298 |
+
if top_k > 0:
|
| 299 |
+
k = min(top_k, logits.shape[-1])
|
| 300 |
+
topk_vals, _ = torch.topk(logits, k, dim=-1)
|
| 301 |
+
threshold = topk_vals[:, -1].unsqueeze(-1)
|
| 302 |
+
logits = logits.masked_fill(logits < threshold, float('-inf'))
|
| 303 |
+
probs = F.softmax(logits, dim=-1)
|
| 304 |
+
return torch.multinomial(probs, 1).squeeze(1)
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
def _nearest_codebook_batched(pred_emb: torch.Tensor,
|
| 308 |
+
cb_norm: torch.Tensor) -> torch.Tensor:
|
| 309 |
+
pred_norm = F.normalize(pred_emb, dim=-1, eps=1e-8)
|
| 310 |
+
return torch.matmul(pred_norm, cb_norm.t()).argmax(dim=-1)
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
def prepare_codebook_norms(model) -> dict:
|
| 314 |
+
with torch.no_grad():
|
| 315 |
+
return {
|
| 316 |
+
'scale': F.normalize(model.get_cb_emb('scale'), dim=-1, eps=1e-8),
|
| 317 |
+
'rot': F.normalize(model.get_cb_emb('rot'), dim=-1, eps=1e-8),
|
| 318 |
+
'dc': F.normalize(model.get_cb_emb('dc'), dim=-1, eps=1e-8),
|
| 319 |
+
'sh': F.normalize(model.get_cb_emb('sh'), dim=-1, eps=1e-8),
|
| 320 |
+
}
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 324 |
+
# 5. ่ชๅๅฝ็ๆๅญ่็น
|
| 325 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 326 |
+
|
| 327 |
+
def generate_children(
|
| 328 |
+
model,
|
| 329 |
+
prefix_batch: dict,
|
| 330 |
+
parent_pos: np.ndarray,
|
| 331 |
+
max_children: int = MAX_CHILDREN,
|
| 332 |
+
temperature: float = 0.8,
|
| 333 |
+
top_k: int = 50,
|
| 334 |
+
device: str = 'cpu',
|
| 335 |
+
) -> list:
|
| 336 |
+
current_batch = prefix_batch
|
| 337 |
+
children = []
|
| 338 |
+
|
| 339 |
+
# ้ข่ฎก็ฎ codebook embedding๏ผๅช็ฎไธๆฌก๏ผ
|
| 340 |
+
with torch.no_grad():
|
| 341 |
+
cb_embs = {
|
| 342 |
+
'scale': model.get_cb_emb('scale'),
|
| 343 |
+
'rot': model.get_cb_emb('rot'),
|
| 344 |
+
'dc': model.get_cb_emb('dc'),
|
| 345 |
+
'sh': model.get_cb_emb('sh'),
|
| 346 |
+
}
|
| 347 |
+
|
| 348 |
+
def _sample_role(logits: torch.Tensor) -> int:
|
| 349 |
+
logits = logits / temperature
|
| 350 |
+
if top_k > 0:
|
| 351 |
+
k = min(top_k, N_ROLE)
|
| 352 |
+
topk_vals, _ = torch.topk(logits, k)
|
| 353 |
+
logits = logits.masked_fill(logits < topk_vals[-1], float('-inf'))
|
| 354 |
+
probs = F.softmax(logits, dim=-1)
|
| 355 |
+
return int(torch.multinomial(probs, 1).item())
|
| 356 |
+
|
| 357 |
+
def _nearest(pred_emb: torch.Tensor, name: str) -> int:
|
| 358 |
+
# L2 normalize ๅๆ่ฟ้ป๏ผไธ่ฎญ็ปๆถ็ normalize MSE ไธ่ด๏ผ
|
| 359 |
+
pred_norm = F.normalize(pred_emb.unsqueeze(0), dim=-1) # (1, d_cb)
|
| 360 |
+
cb_norm = F.normalize(cb_embs[name], dim=-1) # (K, d_cb)
|
| 361 |
+
dist2 = ((cb_norm - pred_norm) ** 2).sum(dim=-1) # (K,)
|
| 362 |
+
return int(dist2.argmin().item())
|
| 363 |
+
|
| 364 |
+
for _ in range(max_children):
|
| 365 |
+
with torch.no_grad():
|
| 366 |
+
pred = model(current_batch)
|
| 367 |
+
|
| 368 |
+
# ๅ
้ขๆต role
|
| 369 |
+
pred_role = _sample_role(pred['role'][0, -1, :])
|
| 370 |
+
|
| 371 |
+
if pred_role == ROLE_EOS:
|
| 372 |
+
break
|
| 373 |
+
if pred_role != ROLE_CHILD:
|
| 374 |
+
break
|
| 375 |
+
|
| 376 |
+
# ้ขๆต xyz / opacity๏ผๅๅฝ๏ผ
|
| 377 |
+
pred_xyz = pred['xyz'][0, -1, :].cpu().numpy()
|
| 378 |
+
pred_opa = float(pred['opacity'][0, -1, 0].cpu()) * 10.0 # ๅๅฝไธๅ
|
| 379 |
+
|
| 380 |
+
# ้ขๆต scale/rot/dc/sh๏ผๆ่ฟ้ป๏ผ
|
| 381 |
+
pred_scale = _nearest(pred['scale_emb'][0, -1, :], 'scale')
|
| 382 |
+
pred_rot = _nearest(pred['rot_emb'][0, -1, :], 'rot')
|
| 383 |
+
pred_dc = _nearest(pred['dc_emb'][0, -1, :], 'dc')
|
| 384 |
+
pred_sh = _nearest(pred['sh_emb'][0, -1, :], 'sh')
|
| 385 |
+
|
| 386 |
+
child = {
|
| 387 |
+
'dx': float(pred_xyz[0]),
|
| 388 |
+
'dy': float(pred_xyz[1]),
|
| 389 |
+
'dz': float(pred_xyz[2]),
|
| 390 |
+
'scale_idx': pred_scale,
|
| 391 |
+
'rot_idx': pred_rot,
|
| 392 |
+
'dc_idx': pred_dc,
|
| 393 |
+
'sh_idx': pred_sh,
|
| 394 |
+
'opacity': float(np.clip(pred_opa, -20, 20)),
|
| 395 |
+
'role': ROLE_CHILD,
|
| 396 |
+
'world_pos': parent_pos + pred_xyz,
|
| 397 |
+
}
|
| 398 |
+
children.append(child)
|
| 399 |
+
|
| 400 |
+
# ๆๆฐ token ๅ ๅ
ฅๅบๅ๏ผopacity ไฟๆๅฝไธๅ็ถๆ๏ผ
|
| 401 |
+
np_token = np.zeros(1, dtype=TOKEN_DTYPE)
|
| 402 |
+
np_token['dx'] = child['dx']
|
| 403 |
+
np_token['dy'] = child['dy']
|
| 404 |
+
np_token['dz'] = child['dz']
|
| 405 |
+
np_token['scale_idx'] = pred_scale
|
| 406 |
+
np_token['rot_idx'] = pred_rot
|
| 407 |
+
np_token['dc_idx'] = pred_dc
|
| 408 |
+
np_token['sh_idx'] = pred_sh
|
| 409 |
+
np_token['opacity'] = pred_opa / 10.0
|
| 410 |
+
np_token['role'] = ROLE_CHILD
|
| 411 |
+
current_batch = _append_token(current_batch, np_token[0], device)
|
| 412 |
+
|
| 413 |
+
return children
|
| 414 |
+
|
| 415 |
+
|
| 416 |
+
def generate_children_batch(
|
| 417 |
+
model,
|
| 418 |
+
prefix_batch: dict,
|
| 419 |
+
parent_positions: np.ndarray,
|
| 420 |
+
lengths: torch.Tensor,
|
| 421 |
+
cb_norms: dict,
|
| 422 |
+
max_children: int = MAX_CHILDREN,
|
| 423 |
+
temperature: float = 0.8,
|
| 424 |
+
top_k: int = 50,
|
| 425 |
+
device: str = 'cpu',
|
| 426 |
+
) -> tuple:
|
| 427 |
+
batch = prefix_batch
|
| 428 |
+
B = parent_positions.shape[0]
|
| 429 |
+
active = torch.ones(B, dtype=torch.bool, device=device)
|
| 430 |
+
child_counts = np.zeros(B, dtype=np.int32)
|
| 431 |
+
children_by_row = [[] for _ in range(B)]
|
| 432 |
+
|
| 433 |
+
parent_positions_t = torch.from_numpy(parent_positions).to(device=device, dtype=torch.float32)
|
| 434 |
+
|
| 435 |
+
with torch.inference_mode():
|
| 436 |
+
for _ in range(max_children):
|
| 437 |
+
row_idx = torch.nonzero(active, as_tuple=False).squeeze(1)
|
| 438 |
+
if row_idx.numel() == 0:
|
| 439 |
+
break
|
| 440 |
+
|
| 441 |
+
active_lengths = lengths[row_idx]
|
| 442 |
+
cur_len = int(active_lengths.max().item())
|
| 443 |
+
active_batch = {k: v[row_idx, :cur_len] for k, v in batch.items()}
|
| 444 |
+
|
| 445 |
+
pred = model(active_batch)
|
| 446 |
+
gather_pos = (active_lengths - 1).view(-1, 1, 1)
|
| 447 |
+
|
| 448 |
+
role_logits = pred['role'].gather(
|
| 449 |
+
1, gather_pos.expand(-1, 1, pred['role'].shape[-1])
|
| 450 |
+
).squeeze(1)
|
| 451 |
+
pred_role = _sample_roles_batched(role_logits, temperature, top_k)
|
| 452 |
+
|
| 453 |
+
child_mask = pred_role == ROLE_CHILD
|
| 454 |
+
if not child_mask.any():
|
| 455 |
+
active[row_idx] = False
|
| 456 |
+
continue
|
| 457 |
+
|
| 458 |
+
stopped_rows = row_idx[~child_mask]
|
| 459 |
+
if stopped_rows.numel() > 0:
|
| 460 |
+
active[stopped_rows] = False
|
| 461 |
+
|
| 462 |
+
child_rows = row_idx[child_mask]
|
| 463 |
+
child_local_idx = torch.nonzero(child_mask, as_tuple=False).squeeze(1)
|
| 464 |
+
child_pos = (active_lengths[child_mask] - 1).view(-1, 1, 1)
|
| 465 |
+
|
| 466 |
+
pred_xyz = pred['xyz'][child_local_idx].gather(
|
| 467 |
+
1, child_pos.expand(-1, 1, pred['xyz'].shape[-1])
|
| 468 |
+
).squeeze(1)
|
| 469 |
+
pred_opa = pred['opacity'][child_local_idx].gather(
|
| 470 |
+
1, child_pos.expand(-1, 1, pred['opacity'].shape[-1])
|
| 471 |
+
).squeeze(1).squeeze(-1) * 10.0
|
| 472 |
+
|
| 473 |
+
pred_scale_emb = pred['scale_emb'][child_local_idx].gather(
|
| 474 |
+
1, child_pos.expand(-1, 1, pred['scale_emb'].shape[-1])
|
| 475 |
+
).squeeze(1)
|
| 476 |
+
pred_rot_emb = pred['rot_emb'][child_local_idx].gather(
|
| 477 |
+
1, child_pos.expand(-1, 1, pred['rot_emb'].shape[-1])
|
| 478 |
+
).squeeze(1)
|
| 479 |
+
pred_dc_emb = pred['dc_emb'][child_local_idx].gather(
|
| 480 |
+
1, child_pos.expand(-1, 1, pred['dc_emb'].shape[-1])
|
| 481 |
+
).squeeze(1)
|
| 482 |
+
pred_sh_emb = pred['sh_emb'][child_local_idx].gather(
|
| 483 |
+
1, child_pos.expand(-1, 1, pred['sh_emb'].shape[-1])
|
| 484 |
+
).squeeze(1)
|
| 485 |
+
|
| 486 |
+
pred_scale = _nearest_codebook_batched(pred_scale_emb, cb_norms['scale'])
|
| 487 |
+
pred_rot = _nearest_codebook_batched(pred_rot_emb, cb_norms['rot'])
|
| 488 |
+
pred_dc = _nearest_codebook_batched(pred_dc_emb, cb_norms['dc'])
|
| 489 |
+
pred_sh = _nearest_codebook_batched(pred_sh_emb, cb_norms['sh'])
|
| 490 |
+
|
| 491 |
+
world_pos = parent_positions_t[child_rows] + pred_xyz
|
| 492 |
+
pred_opa_clipped = pred_opa.clamp(-20.0, 20.0)
|
| 493 |
+
|
| 494 |
+
rows_cpu = child_rows.cpu().numpy()
|
| 495 |
+
xyz_cpu = pred_xyz.cpu().numpy()
|
| 496 |
+
opa_cpu = pred_opa_clipped.cpu().numpy()
|
| 497 |
+
world_cpu = world_pos.cpu().numpy()
|
| 498 |
+
scale_cpu = pred_scale.cpu().numpy()
|
| 499 |
+
rot_cpu = pred_rot.cpu().numpy()
|
| 500 |
+
dc_cpu = pred_dc.cpu().numpy()
|
| 501 |
+
sh_cpu = pred_sh.cpu().numpy()
|
| 502 |
+
|
| 503 |
+
for j, row in enumerate(rows_cpu):
|
| 504 |
+
children_by_row[int(row)].append({
|
| 505 |
+
'dx': float(xyz_cpu[j, 0]),
|
| 506 |
+
'dy': float(xyz_cpu[j, 1]),
|
| 507 |
+
'dz': float(xyz_cpu[j, 2]),
|
| 508 |
+
'scale_idx': int(scale_cpu[j]),
|
| 509 |
+
'rot_idx': int(rot_cpu[j]),
|
| 510 |
+
'dc_idx': int(dc_cpu[j]),
|
| 511 |
+
'sh_idx': int(sh_cpu[j]),
|
| 512 |
+
'opacity': float(opa_cpu[j]),
|
| 513 |
+
'role': ROLE_CHILD,
|
| 514 |
+
'world_pos': world_cpu[j],
|
| 515 |
+
})
|
| 516 |
+
child_counts[row] += 1
|
| 517 |
+
|
| 518 |
+
batch = _append_tokens_batched(
|
| 519 |
+
batch,
|
| 520 |
+
child_rows,
|
| 521 |
+
lengths,
|
| 522 |
+
{
|
| 523 |
+
'xyz': pred_xyz,
|
| 524 |
+
'scale': pred_scale,
|
| 525 |
+
'rot': pred_rot,
|
| 526 |
+
'dc': pred_dc,
|
| 527 |
+
'sh': pred_sh,
|
| 528 |
+
'opacity_norm': pred_opa / 10.0,
|
| 529 |
+
},
|
| 530 |
+
device,
|
| 531 |
+
)
|
| 532 |
+
|
| 533 |
+
children = [child for row_children in children_by_row for child in row_children]
|
| 534 |
+
return children, child_counts
|
| 535 |
+
|
| 536 |
+
|
| 537 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 538 |
+
# 6. ๅๅบ .ply
|
| 539 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 540 |
+
|
| 541 |
+
def children_to_ply(
|
| 542 |
+
all_children: list,
|
| 543 |
+
codebooks: dict,
|
| 544 |
+
save_path: str,
|
| 545 |
+
n_sh_rest: int = 45,
|
| 546 |
+
) -> None:
|
| 547 |
+
N = len(all_children)
|
| 548 |
+
if N == 0:
|
| 549 |
+
print("[write_ply] ่ญฆๅ๏ผๆฒกๆๅญ่็น๏ผ่ทณ่ฟ")
|
| 550 |
+
return
|
| 551 |
+
|
| 552 |
+
print(f"[write_ply] ๅ
ฑ {N} ไธชๅญ่็น๏ผ่งฃ็ ๅนถๅๅบ {save_path} ...")
|
| 553 |
+
|
| 554 |
+
positions = np.array([c['world_pos'] for c in all_children], dtype=np.float32)
|
| 555 |
+
opacities = np.array([c['opacity'] for c in all_children], dtype=np.float32)
|
| 556 |
+
scale_idx = np.array([c['scale_idx'] for c in all_children], dtype=np.int32)
|
| 557 |
+
rot_idx = np.array([c['rot_idx'] for c in all_children], dtype=np.int32)
|
| 558 |
+
dc_idx = np.array([c['dc_idx'] for c in all_children], dtype=np.int32)
|
| 559 |
+
sh_idx = np.array([c['sh_idx'] for c in all_children], dtype=np.int32)
|
| 560 |
+
|
| 561 |
+
scales = codebooks['scale'][scale_idx]
|
| 562 |
+
rotations = codebooks['rotation'][rot_idx]
|
| 563 |
+
dc = codebooks['dc'][dc_idx]
|
| 564 |
+
sh_rest = codebooks['sh'][sh_idx]
|
| 565 |
+
|
| 566 |
+
fields = (
|
| 567 |
+
[('x','f4'), ('y','f4'), ('z','f4'),
|
| 568 |
+
('opacity','f4'),
|
| 569 |
+
('scale_0','f4'), ('scale_1','f4'), ('scale_2','f4'),
|
| 570 |
+
('rot_0','f4'), ('rot_1','f4'), ('rot_2','f4'), ('rot_3','f4'),
|
| 571 |
+
('f_dc_0','f4'), ('f_dc_1','f4'), ('f_dc_2','f4'),
|
| 572 |
+
('filter_3D','f4')] +
|
| 573 |
+
[(f'f_rest_{i}', 'f4') for i in range(n_sh_rest)]
|
| 574 |
+
)
|
| 575 |
+
vd = np.zeros(N, dtype=np.dtype(fields))
|
| 576 |
+
|
| 577 |
+
vd['x'] = positions[:, 0]
|
| 578 |
+
vd['y'] = positions[:, 1]
|
| 579 |
+
vd['z'] = positions[:, 2]
|
| 580 |
+
vd['opacity'] = opacities
|
| 581 |
+
vd['scale_0'] = scales[:, 0]
|
| 582 |
+
vd['scale_1'] = scales[:, 1]
|
| 583 |
+
vd['scale_2'] = scales[:, 2]
|
| 584 |
+
vd['rot_0'] = rotations[:, 0]
|
| 585 |
+
vd['rot_1'] = rotations[:, 1]
|
| 586 |
+
vd['rot_2'] = rotations[:, 2]
|
| 587 |
+
vd['rot_3'] = rotations[:, 3]
|
| 588 |
+
vd['f_dc_0'] = dc[:, 0]
|
| 589 |
+
vd['f_dc_1'] = dc[:, 1]
|
| 590 |
+
vd['f_dc_2'] = dc[:, 2]
|
| 591 |
+
vd['filter_3D'] = 0.0
|
| 592 |
+
for i in range(n_sh_rest):
|
| 593 |
+
vd[f'f_rest_{i}'] = sh_rest[:, i]
|
| 594 |
+
|
| 595 |
+
os.makedirs(os.path.dirname(os.path.abspath(save_path)), exist_ok=True)
|
| 596 |
+
PlyData([PlyElement.describe(vd, 'vertex')]).write(save_path)
|
| 597 |
+
size_mb = os.path.getsize(save_path) / 1024 / 1024
|
| 598 |
+
print(f"[write_ply] ๅฎๆ {size_mb:.2f} MB")
|
| 599 |
+
|
| 600 |
+
|
| 601 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 602 |
+
# 7. ไธปๆจๆญๆต็จ
|
| 603 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 604 |
+
|
| 605 |
+
def infer_upsample(
|
| 606 |
+
ckpt_path: str,
|
| 607 |
+
quant_npz: str,
|
| 608 |
+
codebook_dir: str,
|
| 609 |
+
save_path: str,
|
| 610 |
+
max_uncles: int = MAX_UNCLES,
|
| 611 |
+
max_children: int = MAX_CHILDREN,
|
| 612 |
+
temperature: float = 0.8,
|
| 613 |
+
top_k: int = 50,
|
| 614 |
+
device: str = 'auto',
|
| 615 |
+
max_gaussians: int = -1,
|
| 616 |
+
batch_size: int = 1024,
|
| 617 |
+
) -> None:
|
| 618 |
+
if device == 'auto':
|
| 619 |
+
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
| 620 |
+
print(f"[infer] device={device}")
|
| 621 |
+
|
| 622 |
+
model = load_model(ckpt_path, device)
|
| 623 |
+
codebooks = load_codebooks(codebook_dir)
|
| 624 |
+
quant = load_quantized(quant_npz)
|
| 625 |
+
cb_norms = prepare_codebook_norms(model)
|
| 626 |
+
|
| 627 |
+
N = quant['positions'].shape[0]
|
| 628 |
+
if max_gaussians > 0:
|
| 629 |
+
N = min(N, max_gaussians)
|
| 630 |
+
batch_size = max(1, int(batch_size))
|
| 631 |
+
print(f"[infer] batch_size={batch_size}")
|
| 632 |
+
print(f"[infer] ๅค็ {N} ไธช็ฒ่็น")
|
| 633 |
+
|
| 634 |
+
all_children = []
|
| 635 |
+
total_generated = 0
|
| 636 |
+
early_stop_count = 0
|
| 637 |
+
|
| 638 |
+
for start in range(0, N, batch_size):
|
| 639 |
+
end = min(start + batch_size, N)
|
| 640 |
+
print(f" progress: {start}/{N} generated: {total_generated}")
|
| 641 |
+
|
| 642 |
+
p_indices = np.arange(start, end, dtype=np.int64)
|
| 643 |
+
prefix_batch, parent_positions, lengths = make_prefix_batch_many(
|
| 644 |
+
p_indices, quant, max_uncles=max_uncles, device=device
|
| 645 |
+
)
|
| 646 |
+
children, child_counts = generate_children_batch(
|
| 647 |
+
model,
|
| 648 |
+
prefix_batch,
|
| 649 |
+
parent_positions,
|
| 650 |
+
lengths,
|
| 651 |
+
cb_norms,
|
| 652 |
+
max_children=max_children,
|
| 653 |
+
temperature=temperature,
|
| 654 |
+
top_k=top_k,
|
| 655 |
+
device=device,
|
| 656 |
+
)
|
| 657 |
+
|
| 658 |
+
early_stop_count += int((child_counts < max_children).sum())
|
| 659 |
+
all_children.extend(children)
|
| 660 |
+
total_generated += len(children)
|
| 661 |
+
|
| 662 |
+
print(f"\n[infer] ็ๆๅฎๆ")
|
| 663 |
+
print(f" ๆปๅญ่็นๆฐ๏ผ{total_generated}")
|
| 664 |
+
print(f" ๅนณๅๆฏ็ฒ่็นๅญ่็นๆฐ๏ผ{total_generated / max(N, 1):.2f}")
|
| 665 |
+
print(f" EOS ๆๅ็ปๆญข๏ผ{early_stop_count}/{N} "
|
| 666 |
+
f"({100 * early_stop_count / max(N, 1):.1f}%)")
|
| 667 |
+
|
| 668 |
+
children_to_ply(all_children, codebooks, save_path)
|
| 669 |
+
print(f"\n[infer] ๅฎๆ๏ผ่พๅบ โ {save_path}")
|
| 670 |
+
|
| 671 |
+
|
| 672 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 673 |
+
# 8. CLI
|
| 674 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 675 |
+
|
| 676 |
+
def parse_args():
|
| 677 |
+
p = argparse.ArgumentParser(description="็จ Transformer ไธ้ๆ ท 3DGS")
|
| 678 |
+
p.add_argument('--ckpt', required=True)
|
| 679 |
+
p.add_argument('--quant_npz', required=True)
|
| 680 |
+
p.add_argument('--codebook_dir', required=True)
|
| 681 |
+
p.add_argument('--save_path', required=True)
|
| 682 |
+
p.add_argument('--max_uncles', type=int, default=MAX_UNCLES)
|
| 683 |
+
p.add_argument('--max_children', type=int, default=MAX_CHILDREN)
|
| 684 |
+
p.add_argument('--temperature', type=float, default=0.8)
|
| 685 |
+
p.add_argument('--top_k', type=int, default=50)
|
| 686 |
+
p.add_argument('--device', default='auto')
|
| 687 |
+
p.add_argument('--max_gaussians', type=int, default=-1)
|
| 688 |
+
p.add_argument('--batch_size', type=int, default=1024)
|
| 689 |
+
return p.parse_args()
|
| 690 |
+
|
| 691 |
+
|
| 692 |
+
if __name__ == '__main__':
|
| 693 |
+
args = parse_args()
|
| 694 |
+
infer_upsample(
|
| 695 |
+
ckpt_path=args.ckpt,
|
| 696 |
+
quant_npz=args.quant_npz,
|
| 697 |
+
codebook_dir=args.codebook_dir,
|
| 698 |
+
save_path=args.save_path,
|
| 699 |
+
max_uncles=args.max_uncles,
|
| 700 |
+
max_children=args.max_children,
|
| 701 |
+
temperature=args.temperature,
|
| 702 |
+
top_k=args.top_k,
|
| 703 |
+
device=args.device,
|
| 704 |
+
max_gaussians=args.max_gaussians,
|
| 705 |
+
batch_size=args.batch_size,
|
| 706 |
+
)
|