File size: 13,585 Bytes
98a682c | 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 | """
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
# ๅบๅฎๅบๅ้ฟๅบฆ๏ผparent(1) + uncle(4) + child(32) + EOS(1)
MAX_SEQ_LEN = 1 + MAX_UNCLES + MAX_CHILDREN + 1 # = 38
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_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(),
}
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# 2. ๅ ่ฝฝๆ่ฐฑ
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def load_genealogy(genealogy_path: str) -> dict:
with open(genealogy_path, 'rb') as f:
return pickle.load(f)
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# 3. Token ๆ้ ๅทฅๅ
ท
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
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]
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# 4. ๆๅปบๅๅฑๆๆ split ๅบๅ
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def build_level_sequences(
parent_quant: dict,
child_quant: dict,
children_ids: np.ndarray, # (N_coarse, MAX_CHILDREN)๏ผ-1 ไธบ็ฉบไฝ
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 = []
# โโ parent๏ผๅๆ ็ฝฎ้ถ๏ผโโโโโโโโโโโโโโโโโโโโโโโโโ
t = make_token(p_idx, parent_quant, parent_pos, ROLE_PARENT)
t['dx'] = t['dy'] = t['dz'] = 0.0
tokens.append(t)
# โโ uncle๏ผๅๅๅ half ไธช็ฉบ้ด้ปๅฑ
๏ผโโโโโโโโโโโโ
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
# โโ child๏ผๆๆๆๆๅญ่็น๏ผโโโโโโโโโโโโโโโโโโโโโโ
for c_idx in valid_children:
tokens.append(
make_token(int(c_idx), child_quant, parent_pos, ROLE_CHILD)
)
# โโ EOS โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
tokens.append(make_eos_token())
# โโ PAD ่กฅ้ฝๅฐ fixed_len โโโโโโโโโโโโโโโโโโโโโโโโ
while len(tokens) < fixed_len:
tokens.append(make_pad_token())
# ่ถ
้ฟๆชๆญ๏ผๆ็ซฏๆ
ๅต๏ผuncle+child ่ถ
ๅบ fixed_len-2๏ผ
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
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# 5. ๅคๅฑๅบๅๆๅปบไธปๅฝๆฐ
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def build_all_sequences(
quant_paths: list, # ๆ็ฒโ็ป้กบๅบ๏ผ[L3.npz, L2.npz, L1.npz, L0.npz]
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))
# quants[0]=ๆ็ฒ(L3), quants[1]=L2, ..., quants[-1]=ๆ็ป(L0)
n_levels = len(quants)
# genealogy key: quants[0]โquants[1] ๅฏนๅบ key=n_levels-1๏ผๅณ3๏ผ
# quants[1]โquants[2] ๅฏนๅบ key=n_levels-2๏ผๅณ2๏ผ
# ...
for i in range(n_levels - 1):
coarse_level = n_levels - 1 - i # 3, 2, 1
fine_level = coarse_level - 1 # 2, 1, 0
gen_key = coarse_level # genealogy key ไธ็ฒๅฐบๅบฆ็ผๅทไธ่ด
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'] # (N_coarse, 32)
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}")
# role ๅๅธ็ป่ฎก
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)")
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# 6. CLI
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
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,
) |