SlekLi commited on
Commit
dbb8ee1
·
verified ·
1 Parent(s): cff5241

Delete infer_upsample.py

Browse files
Files changed (1) hide show
  1. infer_upsample.py +0 -456
infer_upsample.py DELETED
@@ -1,456 +0,0 @@
1
- """
2
- infer_upsample.py
3
- =================
4
- 使用训练好的 Transformer,从粗尺度(Ln)自回归生成细尺度(L(n-1))。
5
-
6
- 流程:
7
- 1. 读取粗尺度量化数据(.npz)
8
- 2. 为每个粗节点构造前缀序列(parent + uncles)
9
- 3. 自回归生成子节点(遇到 role=EOS 或超过 MAX_CHILDREN 则停止)
10
- 4. 将子节点量化索引解码为真实属性(查 codebook)
11
- 5. 写出新的 .ply 文件
12
-
13
- role 编码(与训练一致):
14
- 0 = parent 1 = uncle 2 = child 3 = EOS 4 = PAD
15
- """
16
-
17
- import os
18
- import argparse
19
- import pickle
20
- import numpy as np
21
-
22
- import torch
23
- import torch.nn.functional as F
24
- from plyfile import PlyData, PlyElement
25
-
26
- # ─────────────────────────────────────────────
27
- # 常量(与 build_sequences / train_transformer 一致)
28
- # ─────────────────────────────────────────────
29
-
30
- ROLE_PARENT = 0
31
- ROLE_UNCLE = 1
32
- ROLE_CHILD = 2
33
- ROLE_EOS = 3
34
- ROLE_PAD = 4
35
-
36
- MAX_CHILDREN = 32
37
- MAX_UNCLES = 4
38
- MAX_SEQ_LEN = 1 + MAX_UNCLES + MAX_CHILDREN + 1 # = 38
39
-
40
- N_SCALE = 16384
41
- N_ROT = 16384
42
- N_DC = 4096
43
- N_SH = 4096
44
- N_ROLE = 4
45
-
46
- TOKEN_DTYPE = np.dtype([
47
- ('dx', np.float32),
48
- ('dy', np.float32),
49
- ('dz', np.float32),
50
- ('scale_idx', np.int32),
51
- ('rot_idx', np.int32),
52
- ('dc_idx', np.int32),
53
- ('sh_idx', np.int32),
54
- ('opacity', np.float32),
55
- ('role', np.uint8),
56
- ])
57
-
58
-
59
- # ─────────────────────────────────────────────
60
- # 1. 加载模型
61
- # ─────────────────────────────────────────────
62
-
63
- def load_model(ckpt_path: str, device: str = 'cpu'):
64
- from train_transformer import SplitTransformer
65
-
66
- ckpt = torch.load(ckpt_path, map_location=device)
67
- config = ckpt.get('config', {})
68
- model = SplitTransformer(**config).to(device)
69
- state = ckpt.get('model_state', ckpt)
70
- model.load_state_dict(state)
71
- model.eval()
72
- print(f"[load] {os.path.basename(ckpt_path)} "
73
- f"d_model={config.get('d_model')}, "
74
- f"n_layers={config.get('n_layers')}")
75
- return model
76
-
77
-
78
- # ─────────────────────────────────────────────
79
- # 2. 加载 codebook
80
- # ─────────────────────────────────────────────
81
-
82
- def load_codebooks(codebook_dir: str) -> dict:
83
- cbs = {}
84
- for name in ['scale', 'rotation', 'dc', 'sh']:
85
- path = os.path.join(codebook_dir, f"{name}_codebook.npz")
86
- cbs[name] = np.load(path)['codebook'].astype(np.float32)
87
- print(f"[load] {name}_codebook: {cbs[name].shape}")
88
- return cbs
89
-
90
-
91
- # ─────────────────────────────────────────────
92
- # 3. 加载量化数据
93
- # ─────────────────────────────────────────────
94
-
95
- def load_quantized(npz_path: str) -> dict:
96
- npz = np.load(npz_path)
97
- return {
98
- 'scale_indices': npz['scale_indices'],
99
- 'rotation_indices': npz['rotation_indices'],
100
- 'dc_indices': npz['dc_indices'],
101
- 'sh_indices': npz['sh_indices'],
102
- 'positions': npz['positions'],
103
- 'opacities': npz['opacities'].squeeze(),
104
- }
105
-
106
-
107
- # ─────────────────────────────────────────────
108
- # 4. 构造前缀 batch(parent + uncles)
109
- # ─────────────────────────────────────────────
110
-
111
- def make_prefix_batch(
112
- p_idx: int,
113
- quant: dict,
114
- max_uncles: int = MAX_UNCLES,
115
- device: str = 'cpu',
116
- ) -> tuple:
117
- """
118
- 构造粗节点 p_idx 的前缀 batch(parent + uncles),
119
- 返回 (batch_dict, parent_pos)。
120
- batch_dict 中每个张量 shape (1, prefix_len)。
121
- """
122
- N = quant['positions'].shape[0]
123
- parent_pos = quant['positions'][p_idx]
124
-
125
- tokens = []
126
-
127
- # ── parent(坐标置零)─────────────────────
128
- t = _make_np_token(p_idx, quant, parent_pos, ROLE_PARENT)
129
- t['dx'] = t['dy'] = t['dz'] = 0.0
130
- tokens.append(t)
131
-
132
- # ── uncle ──────────────────────────────────
133
- half = max_uncles // 2
134
- added_uncles = 0
135
- for offset in list(range(-half, 0)) + list(range(1, half + 1)):
136
- u_idx = p_idx + offset
137
- if 0 <= u_idx < N and added_uncles < max_uncles:
138
- tokens.append(_make_np_token(u_idx, quant, parent_pos, ROLE_UNCLE))
139
- added_uncles += 1
140
-
141
- seq = np.array(tokens, dtype=TOKEN_DTYPE)
142
- return _seq_to_batch(seq, device), parent_pos
143
-
144
-
145
- def _make_np_token(gauss_idx: int, quant: dict,
146
- parent_pos: np.ndarray, role: int) -> np.ndarray:
147
- pos = quant['positions'][gauss_idx]
148
- delta = pos - parent_pos
149
- token = np.zeros(1, dtype=TOKEN_DTYPE)
150
- token['dx'] = delta[0]
151
- token['dy'] = delta[1]
152
- token['dz'] = delta[2]
153
- token['scale_idx'] = quant['scale_indices'][gauss_idx]
154
- token['rot_idx'] = quant['rotation_indices'][gauss_idx]
155
- token['dc_idx'] = quant['dc_indices'][gauss_idx]
156
- token['sh_idx'] = quant['sh_indices'][gauss_idx]
157
- token['opacity'] = quant['opacities'][gauss_idx]
158
- token['role'] = role
159
- return token[0]
160
-
161
-
162
- def _seq_to_batch(seq: np.ndarray, device: str) -> dict:
163
- """将 numpy 序列转为模型输入 dict,batch_size=1。"""
164
- L = len(seq)
165
- xyz = np.stack([seq['dx'], seq['dy'], seq['dz']], axis=1) # (L, 3)
166
- return {
167
- 'xyz': torch.tensor(xyz, device=device).float().unsqueeze(0),
168
- 'scale': torch.tensor(seq['scale_idx'].astype(np.int64), device=device).unsqueeze(0),
169
- 'rot': torch.tensor(seq['rot_idx'].astype(np.int64), device=device).unsqueeze(0),
170
- 'dc': torch.tensor(seq['dc_idx'].astype(np.int64), device=device).unsqueeze(0),
171
- 'sh': torch.tensor(seq['sh_idx'].astype(np.int64), device=device).unsqueeze(0),
172
- 'opacity': torch.tensor(seq['opacity'].astype(np.float32), device=device).unsqueeze(0),
173
- 'role': torch.tensor(seq['role'].astype(np.int64), device=device).unsqueeze(0),
174
- 'attn_mask': torch.ones(1, L, dtype=torch.bool, device=device),
175
- # Dataset 里的两个 loss_mask 推断时不需要,但 forward 不用它们,可省略
176
- }
177
-
178
-
179
- def _append_token(batch: dict, token_np: np.ndarray, device: str) -> dict:
180
- """将新预测的 token 拼接到 batch 末尾,用于下一步自回归。"""
181
- new_xyz = torch.tensor(
182
- [[[token_np['dx'], token_np['dy'], token_np['dz']]]],
183
- dtype=torch.float32, device=device
184
- )
185
- def cat(key, val, dtype):
186
- new = torch.tensor([[val]], dtype=dtype, device=device)
187
- return torch.cat([batch[key], new], dim=1)
188
-
189
- return {
190
- 'xyz': torch.cat([batch['xyz'], new_xyz], dim=1),
191
- 'scale': cat('scale', int(token_np['scale_idx']), torch.int64),
192
- 'rot': cat('rot', int(token_np['rot_idx']), torch.int64),
193
- 'dc': cat('dc', int(token_np['dc_idx']), torch.int64),
194
- 'sh': cat('sh', int(token_np['sh_idx']), torch.int64),
195
- 'opacity': cat('opacity', float(token_np['opacity']), torch.float32),
196
- 'role': cat('role', int(token_np['role']), torch.int64),
197
- 'attn_mask': torch.cat([
198
- batch['attn_mask'],
199
- torch.ones(1, 1, dtype=torch.bool, device=device)
200
- ], dim=1),
201
- }
202
-
203
-
204
- # ─────────────────────────────────────────────
205
- # 5. 自回归生成子节点
206
- # ─────────────────────────────────────────────
207
-
208
- def generate_children(
209
- model: object,
210
- prefix_batch: dict,
211
- parent_pos: np.ndarray,
212
- max_children: int = MAX_CHILDREN,
213
- temperature: float = 0.8,
214
- top_k: int = 50,
215
- device: str = 'cpu',
216
- ) -> list:
217
- """
218
- 给定前缀 batch(parent + uncles),自回归采样子节点。
219
-
220
- 每步先预测 role:
221
- role=2(child) → 继续预测特征,加入序列
222
- role=3(EOS) → 提前终止
223
- 其他 → 异常,强制终止
224
-
225
- 返回 list of dict,每个 dict 包含子节点所有字段 + world_pos。
226
- """
227
- current_batch = prefix_batch
228
- children = []
229
-
230
- def _sample_cls(logits: torch.Tensor, n_classes: int) -> int:
231
- logits = logits / temperature
232
- if top_k > 0:
233
- k = min(top_k, n_classes)
234
- topk_vals, _ = torch.topk(logits, k)
235
- threshold = topk_vals[-1]
236
- logits = logits.masked_fill(logits < threshold, float('-inf'))
237
- probs = F.softmax(logits, dim=-1)
238
- return int(torch.multinomial(probs, 1).item())
239
-
240
- for _ in range(max_children):
241
- with torch.no_grad():
242
- pred = model(current_batch)
243
-
244
- # ── 先预测 role ────────────────────────
245
- role_logits = pred['role'][0, -1, :] # (4,)
246
- pred_role = _sample_cls(role_logits, N_ROLE)
247
-
248
- if pred_role == ROLE_EOS:
249
- break # 模型预测到结束符,停止
250
-
251
- if pred_role != ROLE_CHILD:
252
- # 预测出了 parent/uncle,模型异常,强制终止
253
- break
254
-
255
- # ── role=child,预测其他特征 ────────────
256
- pred_scale = _sample_cls(pred['scale'][0, -1, :], N_SCALE)
257
- pred_rot = _sample_cls(pred['rot'][0, -1, :], N_ROT)
258
- pred_dc = _sample_cls(pred['dc'][0, -1, :], N_DC)
259
- pred_sh = _sample_cls(pred['sh'][0, -1, :], N_SH)
260
-
261
- pred_xyz = pred['xyz'][0, -1, :].cpu().numpy() # (3,) 相对偏移
262
- pred_opa = float(pred['opacity'][0, -1, 0].cpu())
263
-
264
- # 记录子节点信息
265
- child = {
266
- 'dx': float(pred_xyz[0]),
267
- 'dy': float(pred_xyz[1]),
268
- 'dz': float(pred_xyz[2]),
269
- 'scale_idx': pred_scale,
270
- 'rot_idx': pred_rot,
271
- 'dc_idx': pred_dc,
272
- 'sh_idx': pred_sh,
273
- 'opacity': float(np.clip(pred_opa, -10, 10)),
274
- 'role': ROLE_CHILD,
275
- 'world_pos': parent_pos + pred_xyz, # 世界坐标
276
- }
277
- children.append(child)
278
-
279
- # 将新 token 加入序列(供下一步生成)
280
- np_token = np.zeros(1, dtype=TOKEN_DTYPE)
281
- np_token['dx'] = child['dx']
282
- np_token['dy'] = child['dy']
283
- np_token['dz'] = child['dz']
284
- np_token['scale_idx'] = pred_scale
285
- np_token['rot_idx'] = pred_rot
286
- np_token['dc_idx'] = pred_dc
287
- np_token['sh_idx'] = pred_sh
288
- np_token['opacity'] = child['opacity']
289
- np_token['role'] = ROLE_CHILD
290
- current_batch = _append_token(current_batch, np_token[0], device)
291
-
292
- return children
293
-
294
-
295
- # ─────────────────────────────────────────────
296
- # 6. 写出 .ply
297
- # ─────────────────────────────────────────────
298
-
299
- def children_to_ply(
300
- all_children: list,
301
- codebooks: dict,
302
- save_path: str,
303
- n_sh_rest: int = 45,
304
- ) -> None:
305
- N = len(all_children)
306
- if N == 0:
307
- print("[write_ply] 警告:没有任何子节点,跳过写出")
308
- return
309
-
310
- print(f"[write_ply] 共 {N} 个子节点,解码并写出 {save_path} ...")
311
-
312
- positions = np.array([c['world_pos'] for c in all_children], dtype=np.float32)
313
- opacities = np.array([c['opacity'] for c in all_children], dtype=np.float32)
314
- scale_idx = np.array([c['scale_idx'] for c in all_children], dtype=np.int32)
315
- rot_idx = np.array([c['rot_idx'] for c in all_children], dtype=np.int32)
316
- dc_idx = np.array([c['dc_idx'] for c in all_children], dtype=np.int32)
317
- sh_idx = np.array([c['sh_idx'] for c in all_children], dtype=np.int32)
318
-
319
- # 量化索引 → 真实属性(codebook 查表)
320
- scales = codebooks['scale'][scale_idx] # (N, 3)
321
- rotations = codebooks['rotation'][rot_idx] # (N, 4)
322
- dc = codebooks['dc'][dc_idx] # (N, 3)
323
- sh_rest = codebooks['sh'][sh_idx] # (N, 45)
324
-
325
- # 构造 PLY vertex 结构
326
- fields = (
327
- [('x','f4'), ('y','f4'), ('z','f4'),
328
- ('opacity','f4'),
329
- ('scale_0','f4'), ('scale_1','f4'), ('scale_2','f4'),
330
- ('rot_0','f4'), ('rot_1','f4'), ('rot_2','f4'), ('rot_3','f4'),
331
- ('f_dc_0','f4'), ('f_dc_1','f4'), ('f_dc_2','f4')] +
332
- [(f'f_rest_{i}', 'f4') for i in range(n_sh_rest)]
333
- )
334
- vd = np.zeros(N, dtype=np.dtype(fields))
335
-
336
- vd['x'] = positions[:, 0]
337
- vd['y'] = positions[:, 1]
338
- vd['z'] = positions[:, 2]
339
- vd['opacity'] = opacities
340
- vd['scale_0'] = scales[:, 0]
341
- vd['scale_1'] = scales[:, 1]
342
- vd['scale_2'] = scales[:, 2]
343
- vd['rot_0'] = rotations[:, 0]
344
- vd['rot_1'] = rotations[:, 1]
345
- vd['rot_2'] = rotations[:, 2]
346
- vd['rot_3'] = rotations[:, 3]
347
- vd['f_dc_0'] = dc[:, 0]
348
- vd['f_dc_1'] = dc[:, 1]
349
- vd['f_dc_2'] = dc[:, 2]
350
- for i in range(n_sh_rest):
351
- vd[f'f_rest_{i}'] = sh_rest[:, i]
352
-
353
- os.makedirs(os.path.dirname(os.path.abspath(save_path)), exist_ok=True)
354
- PlyData([PlyElement.describe(vd, 'vertex')]).write(save_path)
355
- size_mb = os.path.getsize(save_path) / 1024 / 1024
356
- print(f"[write_ply] 完成 {size_mb:.2f} MB")
357
-
358
-
359
- # ─────────────────────────────────────────────
360
- # 7. 主推断流程
361
- # ──────────��──────────────────────────────────
362
-
363
- def infer_upsample(
364
- ckpt_path: str,
365
- quant_npz: str,
366
- codebook_dir: str,
367
- save_path: str,
368
- max_uncles: int = MAX_UNCLES,
369
- max_children: int = MAX_CHILDREN,
370
- temperature: float = 0.8,
371
- top_k: int = 50,
372
- device: str = 'auto',
373
- max_gaussians: int = -1,
374
- ) -> None:
375
- if device == 'auto':
376
- device = 'cuda' if torch.cuda.is_available() else 'cpu'
377
- print(f"[infer] device={device}")
378
-
379
- model = load_model(ckpt_path, device)
380
- codebooks = load_codebooks(codebook_dir)
381
- quant = load_quantized(quant_npz)
382
-
383
- N = quant['positions'].shape[0]
384
- if max_gaussians > 0:
385
- N = min(N, max_gaussians)
386
- print(f"[infer] 处理 {N} 个粗节点,最多生成 {N * max_children} 个子节点")
387
-
388
- all_children = []
389
- total_generated = 0
390
- early_stop_count = 0
391
-
392
- for p_idx in range(N):
393
- if p_idx % 5000 == 0:
394
- print(f" 进度:{p_idx}/{N} 已生成子节点:{total_generated}")
395
-
396
- prefix_batch, parent_pos = make_prefix_batch(
397
- p_idx, quant, max_uncles=max_uncles, device=device
398
- )
399
- children = generate_children(
400
- model, prefix_batch, parent_pos,
401
- max_children=max_children,
402
- temperature=temperature,
403
- top_k=top_k,
404
- device=device,
405
- )
406
-
407
- if len(children) < max_children:
408
- early_stop_count += 1
409
-
410
- all_children.extend(children)
411
- total_generated += len(children)
412
-
413
- print(f"\n[infer] 生成完成")
414
- print(f" 总子节点数:{total_generated}")
415
- print(f" 平均每粗节点子节点数:{total_generated / max(N, 1):.2f}")
416
- print(f" EOS 提前终止次数:{early_stop_count} / {N} "
417
- f"({100 * early_stop_count / max(N, 1):.1f}%)")
418
-
419
- children_to_ply(all_children, codebooks, save_path)
420
- print(f"\n[infer] 完成!输出 → {save_path}")
421
-
422
-
423
- # ─────────────────────────────────────────────
424
- # 8. CLI
425
- # ─────────────────────────────────────────────
426
-
427
- def parse_args():
428
- p = argparse.ArgumentParser(description="用 Transformer 从粗尺度生成细尺度 3DGS")
429
- p.add_argument('--ckpt', required=True, help='模型 checkpoint 路径')
430
- p.add_argument('--quant_npz', required=True, help='粗尺度量化数据 .npz')
431
- p.add_argument('--codebook_dir', required=True, help='codebook 目录')
432
- p.add_argument('--save_path', required=True, help='输出 .ply 路径')
433
- p.add_argument('--max_uncles', type=int, default=MAX_UNCLES)
434
- p.add_argument('--max_children', type=int, default=MAX_CHILDREN)
435
- p.add_argument('--temperature', type=float, default=0.8)
436
- p.add_argument('--top_k', type=int, default=50)
437
- p.add_argument('--device', default='auto')
438
- p.add_argument('--max_gaussians', type=int, default=-1,
439
- help='调试用:只处理前 N 个粗节点')
440
- return p.parse_args()
441
-
442
-
443
- if __name__ == '__main__':
444
- args = parse_args()
445
- infer_upsample(
446
- ckpt_path=args.ckpt,
447
- quant_npz=args.quant_npz,
448
- codebook_dir=args.codebook_dir,
449
- save_path=args.save_path,
450
- max_uncles=args.max_uncles,
451
- max_children=args.max_children,
452
- temperature=args.temperature,
453
- top_k=args.top_k,
454
- device=args.device,
455
- max_gaussians=args.max_gaussians,
456
- )