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