SlekLi commited on
Commit
357e87e
·
verified ·
1 Parent(s): f222676

Delete infer_upsample.py

Browse files
Files changed (1) hide show
  1. infer_upsample.py +0 -442
infer_upsample.py DELETED
@@ -1,442 +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
- # ─────────────────────────────────────────────
192
- # 5. 自回归生成子节点
193
- # ─────────────────────────────────────────────
194
-
195
- def generate_children(
196
- model,
197
- prefix_batch: dict,
198
- parent_pos: np.ndarray,
199
- max_children: int = MAX_CHILDREN,
200
- temperature: float = 0.8,
201
- top_k: int = 50,
202
- device: str = 'cpu',
203
- ) -> list:
204
- current_batch = prefix_batch
205
- children = []
206
-
207
- # 预计算 codebook embedding(只算一次)
208
- with torch.no_grad():
209
- cb_embs = {
210
- 'scale': model.get_cb_emb('scale'),
211
- 'rot': model.get_cb_emb('rot'),
212
- 'dc': model.get_cb_emb('dc'),
213
- 'sh': model.get_cb_emb('sh'),
214
- }
215
-
216
- def _sample_role(logits: torch.Tensor) -> int:
217
- logits = logits / temperature
218
- if top_k > 0:
219
- k = min(top_k, N_ROLE)
220
- topk_vals, _ = torch.topk(logits, k)
221
- logits = logits.masked_fill(logits < topk_vals[-1], float('-inf'))
222
- probs = F.softmax(logits, dim=-1)
223
- return int(torch.multinomial(probs, 1).item())
224
-
225
- def _nearest(pred_emb: torch.Tensor, name: str) -> int:
226
- # L2 normalize 后最近邻(与训练时的 normalize MSE 一致)
227
- pred_norm = F.normalize(pred_emb.unsqueeze(0), dim=-1) # (1, d_cb)
228
- cb_norm = F.normalize(cb_embs[name], dim=-1) # (K, d_cb)
229
- dist2 = ((cb_norm - pred_norm) ** 2).sum(dim=-1) # (K,)
230
- return int(dist2.argmin().item())
231
-
232
- for _ in range(max_children):
233
- with torch.no_grad():
234
- pred = model(current_batch)
235
-
236
- # 先预测 role
237
- pred_role = _sample_role(pred['role'][0, -1, :])
238
-
239
- if pred_role == ROLE_EOS:
240
- break
241
- if pred_role != ROLE_CHILD:
242
- break
243
-
244
- # 预测 xyz / opacity(回归)
245
- pred_xyz = pred['xyz'][0, -1, :].cpu().numpy()
246
- pred_opa = float(pred['opacity'][0, -1, 0].cpu()) * 10.0 # 反归一化
247
-
248
- # 预测 scale/rot/dc/sh(最近邻)
249
- pred_scale = _nearest(pred['scale_emb'][0, -1, :], 'scale')
250
- pred_rot = _nearest(pred['rot_emb'][0, -1, :], 'rot')
251
- pred_dc = _nearest(pred['dc_emb'][0, -1, :], 'dc')
252
- pred_sh = _nearest(pred['sh_emb'][0, -1, :], 'sh')
253
-
254
- child = {
255
- 'dx': float(pred_xyz[0]),
256
- 'dy': float(pred_xyz[1]),
257
- 'dz': float(pred_xyz[2]),
258
- 'scale_idx': pred_scale,
259
- 'rot_idx': pred_rot,
260
- 'dc_idx': pred_dc,
261
- 'sh_idx': pred_sh,
262
- 'opacity': float(np.clip(pred_opa, -20, 20)),
263
- 'role': ROLE_CHILD,
264
- 'world_pos': parent_pos + pred_xyz,
265
- }
266
- children.append(child)
267
-
268
- # 把新 token 加入序列(opacity 保持归一化状态)
269
- np_token = np.zeros(1, dtype=TOKEN_DTYPE)
270
- np_token['dx'] = child['dx']
271
- np_token['dy'] = child['dy']
272
- np_token['dz'] = child['dz']
273
- np_token['scale_idx'] = pred_scale
274
- np_token['rot_idx'] = pred_rot
275
- np_token['dc_idx'] = pred_dc
276
- np_token['sh_idx'] = pred_sh
277
- np_token['opacity'] = pred_opa / 10.0
278
- np_token['role'] = ROLE_CHILD
279
- current_batch = _append_token(current_batch, np_token[0], device)
280
-
281
- return children
282
-
283
-
284
- # ─────────────────────────────────────────────
285
- # 6. 写出 .ply
286
- # ─────────────────────────────────────────────
287
-
288
- def children_to_ply(
289
- all_children: list,
290
- codebooks: dict,
291
- save_path: str,
292
- n_sh_rest: int = 45,
293
- ) -> None:
294
- N = len(all_children)
295
- if N == 0:
296
- print("[write_ply] 警告:没有子节点,跳过")
297
- return
298
-
299
- print(f"[write_ply] 共 {N} 个子节点,解码并写出 {save_path} ...")
300
-
301
- positions = np.array([c['world_pos'] for c in all_children], dtype=np.float32)
302
- opacities = np.array([c['opacity'] for c in all_children], dtype=np.float32)
303
- scale_idx = np.array([c['scale_idx'] for c in all_children], dtype=np.int32)
304
- rot_idx = np.array([c['rot_idx'] for c in all_children], dtype=np.int32)
305
- dc_idx = np.array([c['dc_idx'] for c in all_children], dtype=np.int32)
306
- sh_idx = np.array([c['sh_idx'] for c in all_children], dtype=np.int32)
307
-
308
- scales = codebooks['scale'][scale_idx]
309
- rotations = codebooks['rotation'][rot_idx]
310
- dc = codebooks['dc'][dc_idx]
311
- sh_rest = codebooks['sh'][sh_idx]
312
-
313
- fields = (
314
- [('x','f4'), ('y','f4'), ('z','f4'),
315
- ('opacity','f4'),
316
- ('scale_0','f4'), ('scale_1','f4'), ('scale_2','f4'),
317
- ('rot_0','f4'), ('rot_1','f4'), ('rot_2','f4'), ('rot_3','f4'),
318
- ('f_dc_0','f4'), ('f_dc_1','f4'), ('f_dc_2','f4')] +
319
- [(f'f_rest_{i}', 'f4') for i in range(n_sh_rest)]
320
- )
321
- vd = np.zeros(N, dtype=np.dtype(fields))
322
-
323
- vd['x'] = positions[:, 0]
324
- vd['y'] = positions[:, 1]
325
- vd['z'] = positions[:, 2]
326
- vd['opacity'] = opacities
327
- vd['scale_0'] = scales[:, 0]
328
- vd['scale_1'] = scales[:, 1]
329
- vd['scale_2'] = scales[:, 2]
330
- vd['rot_0'] = rotations[:, 0]
331
- vd['rot_1'] = rotations[:, 1]
332
- vd['rot_2'] = rotations[:, 2]
333
- vd['rot_3'] = rotations[:, 3]
334
- vd['f_dc_0'] = dc[:, 0]
335
- vd['f_dc_1'] = dc[:, 1]
336
- vd['f_dc_2'] = dc[:, 2]
337
- for i in range(n_sh_rest):
338
- vd[f'f_rest_{i}'] = sh_rest[:, i]
339
-
340
- os.makedirs(os.path.dirname(os.path.abspath(save_path)), exist_ok=True)
341
- PlyData([PlyElement.describe(vd, 'vertex')]).write(save_path)
342
- size_mb = os.path.getsize(save_path) / 1024 / 1024
343
- print(f"[write_ply] 完成 {size_mb:.2f} MB")
344
-
345
-
346
- # ─────────────────────────────────────────────
347
- # 7. 主推断流程
348
- # ─────────────────────────────────────────────
349
-
350
- def infer_upsample(
351
- ckpt_path: str,
352
- quant_npz: str,
353
- codebook_dir: str,
354
- save_path: str,
355
- max_uncles: int = MAX_UNCLES,
356
- max_children: int = MAX_CHILDREN,
357
- temperature: float = 0.8,
358
- top_k: int = 50,
359
- device: str = 'auto',
360
- max_gaussians: int = -1,
361
- ) -> None:
362
- if device == 'auto':
363
- device = 'cuda' if torch.cuda.is_available() else 'cpu'
364
- print(f"[infer] device={device}")
365
-
366
- model = load_model(ckpt_path, device)
367
- codebooks = load_codebooks(codebook_dir)
368
- quant = load_quantized(quant_npz)
369
-
370
- N = quant['positions'].shape[0]
371
- if max_gaussians > 0:
372
- N = min(N, max_gaussians)
373
- print(f"[infer] 处理 {N} 个粗节点")
374
-
375
- all_children = []
376
- total_generated = 0
377
- early_stop_count = 0
378
-
379
- for p_idx in range(N):
380
- if p_idx % 5000 == 0:
381
- print(f" 进度:{p_idx}/{N} 已生成:{total_generated}")
382
-
383
- prefix_batch, parent_pos = make_prefix_batch(
384
- p_idx, quant, max_uncles=max_uncles, device=device
385
- )
386
- children = generate_children(
387
- model, prefix_batch, parent_pos,
388
- max_children=max_children,
389
- temperature=temperature,
390
- top_k=top_k,
391
- device=device,
392
- )
393
-
394
- if len(children) < max_children:
395
- early_stop_count += 1
396
-
397
- all_children.extend(children)
398
- total_generated += len(children)
399
-
400
- print(f"\n[infer] 生成完成")
401
- print(f" 总子节点数:{total_generated}")
402
- print(f" 平均每粗节点子节点数:{total_generated / max(N, 1):.2f}")
403
- print(f" EOS 提前终止:{early_stop_count}/{N} "
404
- f"({100 * early_stop_count / max(N, 1):.1f}%)")
405
-
406
- children_to_ply(all_children, codebooks, save_path)
407
- print(f"\n[infer] 完成!输出 → {save_path}")
408
-
409
-
410
- # ─────────────────────────────────────────────
411
- # 8. CLI
412
- # ─────────────────────────────────────────────
413
-
414
- def parse_args():
415
- p = argparse.ArgumentParser(description="用 Transformer 上采样 3DGS")
416
- p.add_argument('--ckpt', required=True)
417
- p.add_argument('--quant_npz', required=True)
418
- p.add_argument('--codebook_dir', required=True)
419
- p.add_argument('--save_path', required=True)
420
- p.add_argument('--max_uncles', type=int, default=MAX_UNCLES)
421
- p.add_argument('--max_children', type=int, default=MAX_CHILDREN)
422
- p.add_argument('--temperature', type=float, default=0.8)
423
- p.add_argument('--top_k', type=int, default=50)
424
- p.add_argument('--device', default='auto')
425
- p.add_argument('--max_gaussians', type=int, default=-1)
426
- return p.parse_args()
427
-
428
-
429
- if __name__ == '__main__':
430
- args = parse_args()
431
- infer_upsample(
432
- ckpt_path=args.ckpt,
433
- quant_npz=args.quant_npz,
434
- codebook_dir=args.codebook_dir,
435
- save_path=args.save_path,
436
- max_uncles=args.max_uncles,
437
- max_children=args.max_children,
438
- temperature=args.temperature,
439
- top_k=args.top_k,
440
- device=args.device,
441
- max_gaussians=args.max_gaussians,
442
- )