SlekLi commited on
Commit
e2f0fbc
·
verified ·
1 Parent(s): 5e6f2f6

Delete infer_upsample.py

Browse files
Files changed (1) hide show
  1. infer_upsample.py +0 -704
infer_upsample.py DELETED
@@ -1,704 +0,0 @@
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
- [(f'f_rest_{i}', 'f4') for i in range(n_sh_rest)]
573
- )
574
- vd = np.zeros(N, dtype=np.dtype(fields))
575
-
576
- vd['x'] = positions[:, 0]
577
- vd['y'] = positions[:, 1]
578
- vd['z'] = positions[:, 2]
579
- vd['opacity'] = opacities
580
- vd['scale_0'] = scales[:, 0]
581
- vd['scale_1'] = scales[:, 1]
582
- vd['scale_2'] = scales[:, 2]
583
- vd['rot_0'] = rotations[:, 0]
584
- vd['rot_1'] = rotations[:, 1]
585
- vd['rot_2'] = rotations[:, 2]
586
- vd['rot_3'] = rotations[:, 3]
587
- vd['f_dc_0'] = dc[:, 0]
588
- vd['f_dc_1'] = dc[:, 1]
589
- vd['f_dc_2'] = dc[:, 2]
590
- for i in range(n_sh_rest):
591
- vd[f'f_rest_{i}'] = sh_rest[:, i]
592
-
593
- os.makedirs(os.path.dirname(os.path.abspath(save_path)), exist_ok=True)
594
- PlyData([PlyElement.describe(vd, 'vertex')]).write(save_path)
595
- size_mb = os.path.getsize(save_path) / 1024 / 1024
596
- print(f"[write_ply] 完成 {size_mb:.2f} MB")
597
-
598
-
599
- # ─────────────────────────────────────────────
600
- # 7. 主推断流程
601
- # ─────────────────────────────────────────────
602
-
603
- def infer_upsample(
604
- ckpt_path: str,
605
- quant_npz: str,
606
- codebook_dir: str,
607
- save_path: str,
608
- max_uncles: int = MAX_UNCLES,
609
- max_children: int = MAX_CHILDREN,
610
- temperature: float = 0.8,
611
- top_k: int = 50,
612
- device: str = 'auto',
613
- max_gaussians: int = -1,
614
- batch_size: int = 1024,
615
- ) -> None:
616
- if device == 'auto':
617
- device = 'cuda' if torch.cuda.is_available() else 'cpu'
618
- print(f"[infer] device={device}")
619
-
620
- model = load_model(ckpt_path, device)
621
- codebooks = load_codebooks(codebook_dir)
622
- quant = load_quantized(quant_npz)
623
- cb_norms = prepare_codebook_norms(model)
624
-
625
- N = quant['positions'].shape[0]
626
- if max_gaussians > 0:
627
- N = min(N, max_gaussians)
628
- batch_size = max(1, int(batch_size))
629
- print(f"[infer] batch_size={batch_size}")
630
- print(f"[infer] 处理 {N} 个粗节点")
631
-
632
- all_children = []
633
- total_generated = 0
634
- early_stop_count = 0
635
-
636
- for start in range(0, N, batch_size):
637
- end = min(start + batch_size, N)
638
- print(f" progress: {start}/{N} generated: {total_generated}")
639
-
640
- p_indices = np.arange(start, end, dtype=np.int64)
641
- prefix_batch, parent_positions, lengths = make_prefix_batch_many(
642
- p_indices, quant, max_uncles=max_uncles, device=device
643
- )
644
- children, child_counts = generate_children_batch(
645
- model,
646
- prefix_batch,
647
- parent_positions,
648
- lengths,
649
- cb_norms,
650
- max_children=max_children,
651
- temperature=temperature,
652
- top_k=top_k,
653
- device=device,
654
- )
655
-
656
- early_stop_count += int((child_counts < max_children).sum())
657
- all_children.extend(children)
658
- total_generated += len(children)
659
-
660
- print(f"\n[infer] 生成完成")
661
- print(f" 总子节点数:{total_generated}")
662
- print(f" 平均每粗节点子节点数:{total_generated / max(N, 1):.2f}")
663
- print(f" EOS 提前终止:{early_stop_count}/{N} "
664
- f"({100 * early_stop_count / max(N, 1):.1f}%)")
665
-
666
- children_to_ply(all_children, codebooks, save_path)
667
- print(f"\n[infer] 完成!输出 → {save_path}")
668
-
669
-
670
- # ─────────────────────────────────────────────
671
- # 8. CLI
672
- # ─────────────────────────────────────────────
673
-
674
- def parse_args():
675
- p = argparse.ArgumentParser(description="用 Transformer 上采样 3DGS")
676
- p.add_argument('--ckpt', required=True)
677
- p.add_argument('--quant_npz', required=True)
678
- p.add_argument('--codebook_dir', required=True)
679
- p.add_argument('--save_path', required=True)
680
- p.add_argument('--max_uncles', type=int, default=MAX_UNCLES)
681
- p.add_argument('--max_children', type=int, default=MAX_CHILDREN)
682
- p.add_argument('--temperature', type=float, default=0.8)
683
- p.add_argument('--top_k', type=int, default=50)
684
- p.add_argument('--device', default='auto')
685
- p.add_argument('--max_gaussians', type=int, default=-1)
686
- p.add_argument('--batch_size', type=int, default=1024)
687
- return p.parse_args()
688
-
689
-
690
- if __name__ == '__main__':
691
- args = parse_args()
692
- infer_upsample(
693
- ckpt_path=args.ckpt,
694
- quant_npz=args.quant_npz,
695
- codebook_dir=args.codebook_dir,
696
- save_path=args.save_path,
697
- max_uncles=args.max_uncles,
698
- max_children=args.max_children,
699
- temperature=args.temperature,
700
- top_k=args.top_k,
701
- device=args.device,
702
- max_gaussians=args.max_gaussians,
703
- batch_size=args.batch_size,
704
- )