| """
|
| build_sequences.py
|
| ==================
|
| ไปๆ่ฐฑ๏ผgenealogy.pkl๏ผๅๅคๅฐบๅบฆ 3DGS ้ๅ็ดขๅผๆๅปบ split ๅบๅใ
|
|
|
| ๅบๅ็ปๆ๏ผๅบๅฎ้ฟๅบฆ MAX_SEQ_LEN = 38๏ผ๏ผ
|
| [parent(1)] [uncleรโค4] [childรโค32] [EOS(1)] [PADร...]
|
|
|
| ๆฏไธช token ๅญๆฎต๏ผ
|
| dx, dy, dz float32 ๅๆ ๅ็งป๏ผparent=0,0,0๏ผๅ
ถไป=็ธๅฏนparent๏ผ
|
| scale_idx int32 scale codebook ็ดขๅผ
|
| rot_idx int32 rotation codebook ็ดขๅผ
|
| dc_idx int32 DC codebook ็ดขๅผ
|
| sh_idx int32 SH codebook ็ดขๅผ
|
| opacity float32 ไธ้ๆๅบฆๅๅผ๏ผไธ้ๅ๏ผ
|
| role uint8 ่บซไปฝๆ ่ฏ๏ผ
|
| 0 = parent๏ผ็ถ่็น๏ผๅๆ ๅ็น๏ผ
|
| 1 = uncle ๏ผๅไผฏ่็น๏ผ็ธๅฏนๅๆ ๏ผ
|
| 2 = child ๏ผๅญ่็น๏ผ็ธๅฏนๅๆ ๏ผ
|
| 3 = EOS ๏ผๅบๅ็ปๆ็ฌฆ๏ผ
|
| 4 = PAD ๏ผ่กฅ้ฝ๏ผไธๅไธ่ฎก็ฎ๏ผ
|
|
|
| ๅฑ็บงๆนๅ๏ผ็ฒโ็ป๏ผ๏ผ
|
| quant_paths ๆ L3, L2, L1, L0 ้กบๅบไผ ๅ
ฅ
|
| L3 ๆ็ฒ๏ผ็นๆๅฐ๏ผไฝไธบ parent๏ผ้็บงๅ็ปๅฑๅผ
|
| """
|
|
|
| import os
|
| import argparse
|
| import pickle
|
| import numpy as np
|
|
|
|
|
|
|
|
|
|
|
| ROLE_PARENT = np.uint8(0)
|
| ROLE_UNCLE = np.uint8(1)
|
| ROLE_CHILD = np.uint8(2)
|
| ROLE_EOS = np.uint8(3)
|
| ROLE_PAD = np.uint8(4)
|
|
|
| MAX_CHILDREN = 32
|
| MAX_UNCLES = 4
|
|
|
| MAX_SEQ_LEN = 1 + MAX_UNCLES + MAX_CHILDREN + 1
|
|
|
| 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),
|
| ])
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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(),
|
| }
|
|
|
|
|
|
|
|
|
|
|
|
|
| def load_genealogy(genealogy_path: str) -> dict:
|
| with open(genealogy_path, 'rb') as f:
|
| return pickle.load(f)
|
|
|
|
|
|
|
|
|
|
|
|
|
| def make_token(gauss_idx: int, quant: dict,
|
| parent_pos: np.ndarray, role: np.uint8) -> np.ndarray:
|
| """ๆ้ ๅไธช็นๅพ token๏ผๅๆ ไธบ็ธๅฏน parent_pos ็ๅ็งปใ"""
|
| 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]
|
| token['role'] = role
|
| return token[0]
|
|
|
|
|
| def make_eos_token() -> np.ndarray:
|
| """็ปๆ็ฌฆ๏ผ็นๅพๅ
จ 0๏ผrole=3ใ"""
|
| token = np.zeros(1, dtype=TOKEN_DTYPE)
|
| token['role'] = ROLE_EOS
|
| return token[0]
|
|
|
|
|
| def make_pad_token() -> np.ndarray:
|
| """่กฅ้ฝ็ฌฆ๏ผ็นๅพๅ
จ 0๏ผrole=4๏ผไธๅไธไปปไฝ loss/attentionใ"""
|
| token = np.zeros(1, dtype=TOKEN_DTYPE)
|
| token['role'] = ROLE_PAD
|
| return token[0]
|
|
|
|
|
|
|
|
|
|
|
|
|
| def build_level_sequences(
|
| parent_quant: dict,
|
| child_quant: dict,
|
| children_ids: np.ndarray,
|
| max_uncles: int = MAX_UNCLES,
|
| min_children: int = 1,
|
| fixed_len: int = MAX_SEQ_LEN,
|
| ) -> list:
|
| """
|
| ้ๅๆฏไธช็ฒ่็น๏ผๆ้ ไธๆกๅบๅฎ้ฟๅบฆ็ split ๅบๅใ
|
|
|
| ๅบๅ token ้กบๅบ๏ผ
|
| [parent(1)] [uncleรโคmax_uncles] [childรN_valid] [EOS(1)] [PADร...]
|
|
|
| role ็ผ็ ๏ผ
|
| 0 = parent ๅๆ ๅบๅฎไธบ (0,0,0)๏ผ็นๅพๆฅ่ช่ช่บซ
|
| 1 = uncle ๅๆ ็ธๅฏน parent๏ผ็นๅพๆฅ่ช่ช่บซ
|
| 2 = child ๅๆ ็ธๅฏน parent๏ผ็นๅพๆฅ่ช็ปๅฐบๅบฆ
|
| 3 = EOS ็ปๆ็ฌฆ๏ผๆ ๅฟ็ๅฎๅญ่็นๅทฒๅ
จ้จ่พๅบ
|
| 4 = PAD ่กฅ้ฝ๏ผattention mask ไธญ่ขซๅฑ่ฝ
|
|
|
| ่ฟๅ๏ผlist of np.ndarray๏ผๆฏไธชๅ
็ด shape (fixed_len,) TOKEN_DTYPE
|
| """
|
| N_parents = children_ids.shape[0]
|
| sequences = []
|
|
|
| for p_idx in range(N_parents):
|
| child_row = children_ids[p_idx]
|
| valid_children = child_row[child_row >= 0]
|
|
|
| if len(valid_children) < min_children:
|
| continue
|
|
|
| parent_pos = parent_quant['positions'][p_idx]
|
| tokens = []
|
|
|
|
|
| t = make_token(p_idx, parent_quant, parent_pos, ROLE_PARENT)
|
| t['dx'] = t['dy'] = t['dz'] = 0.0
|
| tokens.append(t)
|
|
|
|
|
| half = max_uncles // 2
|
| added_uncles = 0
|
| for offset in list(range(-half, 0)) + list(range(1, half + 1)):
|
| u_idx = p_idx + offset
|
| if 0 <= u_idx < N_parents and added_uncles < max_uncles:
|
| tokens.append(
|
| make_token(u_idx, parent_quant, parent_pos, ROLE_UNCLE)
|
| )
|
| added_uncles += 1
|
|
|
|
|
| for c_idx in valid_children:
|
| tokens.append(
|
| make_token(int(c_idx), child_quant, parent_pos, ROLE_CHILD)
|
| )
|
|
|
|
|
| tokens.append(make_eos_token())
|
|
|
|
|
| while len(tokens) < fixed_len:
|
| tokens.append(make_pad_token())
|
|
|
|
|
| if len(tokens) > fixed_len:
|
| tokens = tokens[:fixed_len - 1]
|
| tokens.append(make_eos_token())
|
|
|
| sequences.append(np.array(tokens, dtype=TOKEN_DTYPE))
|
|
|
| return sequences
|
|
|
|
|
|
|
|
|
|
|
|
|
| def build_all_sequences(
|
| quant_paths: list,
|
| genealogy_path: str,
|
| save_dir: str,
|
| max_uncles: int = MAX_UNCLES,
|
| min_children: int = 1,
|
| ) -> None:
|
| """
|
| quant_paths ๆ็ฒโ็ป้กบๅบไผ ๅ
ฅ๏ผไพๅฆ๏ผ
|
| [L3_quantized.npz, L2_quantized.npz, L1_quantized.npz, L0_quantized.npz]
|
|
|
| genealogy.pkl ๆ ผๅผ๏ผ
|
| genealogy[3]['children_ids'] shape (N_L3, MAX_CHILDREN)
|
| L3็ฒ่็น โ L2็ป่็น็ดขๅผ
|
| genealogy[2]['children_ids'] shape (N_L2, MAX_CHILDREN)
|
| L2็ฒ่็น โ L1็ป่็น็ดขๅผ
|
| genealogy[1]['children_ids'] shape (N_L1, MAX_CHILDREN)
|
| L1็ฒ่็น โ L0็ป่็น็ดขๅผ
|
|
|
| ่พๅบ๏ผๆ็ฒโ็ปๅฝๅ๏ผ๏ผ
|
| save_dir/sequences_L3_to_L2.pkl
|
| save_dir/sequences_L2_to_L1.pkl
|
| save_dir/sequences_L1_to_L0.pkl
|
| """
|
| os.makedirs(save_dir, exist_ok=True)
|
|
|
| print(f"[build] ๅ ่ฝฝๆ่ฐฑ๏ผ{genealogy_path}")
|
| genealogy = load_genealogy(genealogy_path)
|
|
|
| print(f"[build] ๅ ่ฝฝ้ๅๆฐๆฎ๏ผๅ
ฑ {len(quant_paths)} ไธชๅฐบๅบฆ๏ผ็ฒโ็ป้กบๅบ๏ผ...")
|
| quants = []
|
| for path in quant_paths:
|
| print(f" {os.path.basename(path)}")
|
| quants.append(load_quantized(path))
|
|
|
|
|
| n_levels = len(quants)
|
|
|
|
|
|
|
|
|
| for i in range(n_levels - 1):
|
| coarse_level = n_levels - 1 - i
|
| fine_level = coarse_level - 1
|
| gen_key = coarse_level
|
|
|
| coarse_name = f"L{coarse_level}"
|
| fine_name = f"L{fine_level}"
|
|
|
| if gen_key not in genealogy:
|
| print(f"[build] ่ญฆๅ๏ผๆ่ฐฑไธญๆ key={gen_key}๏ผ่ทณ่ฟ {coarse_name}โ{fine_name}")
|
| continue
|
|
|
| parent_quant = quants[i]
|
| child_quant = quants[i + 1]
|
| children_ids = genealogy[gen_key]['children_ids']
|
|
|
| print(f"\n[build] ๆๅปบ {coarse_name}โ{fine_name} ๅบๅ")
|
| print(f" ็ถ่็นๆฐ={children_ids.shape[0]}, "
|
| f"children_ids.shape={children_ids.shape}")
|
|
|
| sequences = build_level_sequences(
|
| parent_quant, child_quant, children_ids,
|
| max_uncles=max_uncles,
|
| min_children=min_children,
|
| fixed_len=MAX_SEQ_LEN,
|
| )
|
|
|
| if len(sequences) == 0:
|
| print(" [่ญฆๅ] ๆฒกๆๆๆๅบๅ๏ผ่ฏทๆฃๆฅๆ่ฐฑไธ้ๅๆฐๆฎ")
|
| continue
|
|
|
|
|
| child_counts = np.array([
|
| int((s['role'] == ROLE_CHILD).sum()) for s in sequences
|
| ])
|
| print(f" ็ๆๅบๅๆฐ๏ผ{len(sequences)}")
|
| print(f" ๅญ่็นๆฐ๏ผmin={child_counts.min()}, "
|
| f"max={child_counts.max()}, mean={child_counts.mean():.2f}")
|
|
|
|
|
| all_roles = np.concatenate([s['role'] for s in sequences])
|
| for r, name in [(0,'parent'),(1,'uncle'),(2,'child'),(3,'EOS'),(4,'PAD')]:
|
| cnt = (all_roles == r).sum()
|
| print(f" role={r}({name:6s})๏ผ{cnt:,} tokens")
|
|
|
| out_path = os.path.join(save_dir,
|
| f"sequences_{coarse_name}_to_{fine_name}.pkl")
|
| with open(out_path, 'wb') as f:
|
| pickle.dump(sequences, f, protocol=4)
|
|
|
| size_mb = os.path.getsize(out_path) / 1024 / 1024
|
| print(f" ไฟๅญ โ {out_path} ({size_mb:.2f} MB)")
|
|
|
| print(f"\n[build] ๅ
จ้จๅบๅๆๅปบๅฎๆ๏ผ")
|
| print(f" ๅบๅฎๅบๅ้ฟๅบฆ MAX_SEQ_LEN={MAX_SEQ_LEN} "
|
| f"(parent=1, uncleโค{MAX_UNCLES}, childโค{MAX_CHILDREN}, EOS=1)")
|
|
|
|
|
|
|
|
|
|
|
|
|
| def parse_args():
|
| parser = argparse.ArgumentParser(description="ๆๅปบ 3DGS split ๅบๅ")
|
| parser.add_argument('--quant_paths', nargs='+', required=True,
|
| help='้ๅ .npz ่ทฏๅพ๏ผๆ็ฒโ็ป้กบๅบ๏ผL3 L2 L1 L0')
|
| parser.add_argument('--genealogy', required=True,
|
| help='ๆ่ฐฑ genealogy.pkl ่ทฏๅพ')
|
| parser.add_argument('--save_dir', default='./sequences',
|
| help='ๅบๅ่พๅบ็ฎๅฝ๏ผ้ป่ฎค ./sequences๏ผ')
|
| parser.add_argument('--max_uncles', type=int, default=MAX_UNCLES)
|
| parser.add_argument('--min_children', type=int, default=1)
|
| return parser.parse_args()
|
|
|
|
|
| if __name__ == '__main__':
|
| args = parse_args()
|
| build_all_sequences(
|
| quant_paths=args.quant_paths,
|
| genealogy_path=args.genealogy,
|
| save_dir=args.save_dir,
|
| max_uncles=args.max_uncles,
|
| min_children=args.min_children,
|
| ) |