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|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
build_sequences.py
|
| 3 |
+
==================
|
| 4 |
+
ไปๆ่ฐฑ๏ผgenealogy.pkl๏ผๅๅคๅฐบๅบฆ 3DGS ้ๅ็ดขๅผๆๅปบ split ๅบๅใ
|
| 5 |
+
|
| 6 |
+
ๅบๅ็ปๆ๏ผๅบๅฎ้ฟๅบฆ MAX_SEQ_LEN = 38๏ผ๏ผ
|
| 7 |
+
[parent(1)] [uncleรโค4] [childรโค32] [EOS(1)] [PADร...]
|
| 8 |
+
|
| 9 |
+
ๆฏไธช token ๅญๆฎต๏ผ
|
| 10 |
+
dx, dy, dz float32 ๅๆ ๅ็งป๏ผparent=0,0,0๏ผๅ
ถไป=็ธๅฏนparent๏ผ
|
| 11 |
+
scale_idx int32 scale codebook ็ดขๅผ
|
| 12 |
+
rot_idx int32 rotation codebook ็ดขๅผ
|
| 13 |
+
dc_idx int32 DC codebook ็ดขๅผ
|
| 14 |
+
sh_idx int32 SH codebook ็ดขๅผ
|
| 15 |
+
opacity float32 ไธ้ๆๅบฆๅๅผ๏ผไธ้ๅ๏ผ
|
| 16 |
+
role uint8 ่บซไปฝๆ ่ฏ๏ผ
|
| 17 |
+
0 = parent๏ผ็ถ่็น๏ผๅๆ ๅ็น๏ผ
|
| 18 |
+
1 = uncle ๏ผๅไผฏ่็น๏ผ็ธๅฏนๅๆ ๏ผ
|
| 19 |
+
2 = child ๏ผๅญ่็น๏ผ็ธๅฏนๅๆ ๏ผ
|
| 20 |
+
3 = EOS ๏ผๅบๅ็ปๆ็ฌฆ๏ผ
|
| 21 |
+
4 = PAD ๏ผ่กฅ้ฝ๏ผไธๅไธ่ฎก็ฎ๏ผ
|
| 22 |
+
|
| 23 |
+
ๅฑ็บงๆนๅ๏ผ็ฒโ็ป๏ผ๏ผ
|
| 24 |
+
quant_paths ๆ L3, L2, L1, L0 ้กบๅบไผ ๅ
ฅ
|
| 25 |
+
L3 ๆ็ฒ๏ผ็นๆๅฐ๏ผไฝไธบ parent๏ผ้็บงๅ็ปๅฑๅผ
|
| 26 |
+
"""
|
| 27 |
+
|
| 28 |
+
import os
|
| 29 |
+
import argparse
|
| 30 |
+
import pickle
|
| 31 |
+
import numpy as np
|
| 32 |
+
|
| 33 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 34 |
+
# ๅธธ้
|
| 35 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 36 |
+
|
| 37 |
+
ROLE_PARENT = np.uint8(0)
|
| 38 |
+
ROLE_UNCLE = np.uint8(1)
|
| 39 |
+
ROLE_CHILD = np.uint8(2)
|
| 40 |
+
ROLE_EOS = np.uint8(3)
|
| 41 |
+
ROLE_PAD = np.uint8(4)
|
| 42 |
+
|
| 43 |
+
MAX_CHILDREN = 32
|
| 44 |
+
MAX_UNCLES = 4
|
| 45 |
+
# ๅบๅฎๅบๅ้ฟๅบฆ๏ผparent(1) + uncle(4) + child(32) + EOS(1)
|
| 46 |
+
MAX_SEQ_LEN = 1 + MAX_UNCLES + MAX_CHILDREN + 1 # = 38
|
| 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_quantized(npz_path: str) -> dict:
|
| 66 |
+
npz = np.load(npz_path)
|
| 67 |
+
return {
|
| 68 |
+
'scale_indices': npz['scale_indices'],
|
| 69 |
+
'rotation_indices': npz['rotation_indices'],
|
| 70 |
+
'dc_indices': npz['dc_indices'],
|
| 71 |
+
'sh_indices': npz['sh_indices'],
|
| 72 |
+
'positions': npz['positions'],
|
| 73 |
+
'opacities': npz['opacities'].squeeze(),
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 78 |
+
# 2. ๅ ่ฝฝๆ่ฐฑ
|
| 79 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 80 |
+
|
| 81 |
+
def load_genealogy(genealogy_path: str) -> dict:
|
| 82 |
+
with open(genealogy_path, 'rb') as f:
|
| 83 |
+
return pickle.load(f)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 87 |
+
# 3. Token ๆ้ ๅทฅๅ
ท
|
| 88 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 89 |
+
|
| 90 |
+
def make_token(gauss_idx: int, quant: dict,
|
| 91 |
+
parent_pos: np.ndarray, role: np.uint8) -> np.ndarray:
|
| 92 |
+
"""ๆ้ ๅไธช็นๅพ token๏ผๅๆ ไธบ็ธๅฏน parent_pos ็ๅ็งปใ"""
|
| 93 |
+
pos = quant['positions'][gauss_idx]
|
| 94 |
+
delta = pos - parent_pos
|
| 95 |
+
|
| 96 |
+
token = np.zeros(1, dtype=TOKEN_DTYPE)
|
| 97 |
+
token['dx'] = delta[0]
|
| 98 |
+
token['dy'] = delta[1]
|
| 99 |
+
token['dz'] = delta[2]
|
| 100 |
+
token['scale_idx'] = quant['scale_indices'][gauss_idx]
|
| 101 |
+
token['rot_idx'] = quant['rotation_indices'][gauss_idx]
|
| 102 |
+
token['dc_idx'] = quant['dc_indices'][gauss_idx]
|
| 103 |
+
token['sh_idx'] = quant['sh_indices'][gauss_idx]
|
| 104 |
+
token['opacity'] = quant['opacities'][gauss_idx]
|
| 105 |
+
token['role'] = role
|
| 106 |
+
return token[0]
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def make_eos_token() -> np.ndarray:
|
| 110 |
+
"""็ปๆ็ฌฆ๏ผ็นๅพๅ
จ 0๏ผrole=3ใ"""
|
| 111 |
+
token = np.zeros(1, dtype=TOKEN_DTYPE)
|
| 112 |
+
token['role'] = ROLE_EOS
|
| 113 |
+
return token[0]
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def make_pad_token() -> np.ndarray:
|
| 117 |
+
"""่กฅ้ฝ็ฌฆ๏ผ็นๅพๅ
จ 0๏ผrole=4๏ผไธๅไธไปปไฝ loss/attentionใ"""
|
| 118 |
+
token = np.zeros(1, dtype=TOKEN_DTYPE)
|
| 119 |
+
token['role'] = ROLE_PAD
|
| 120 |
+
return token[0]
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 124 |
+
# 4. ๆๅปบๅๅฑๆๆ split ๅบๅ
|
| 125 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโ๏ฟฝ๏ฟฝโโโโโโโโโโโโโโโโโโ
|
| 126 |
+
|
| 127 |
+
def build_level_sequences(
|
| 128 |
+
parent_quant: dict,
|
| 129 |
+
child_quant: dict,
|
| 130 |
+
children_ids: np.ndarray, # (N_coarse, MAX_CHILDREN)๏ผ-1 ไธบ็ฉบไฝ
|
| 131 |
+
max_uncles: int = MAX_UNCLES,
|
| 132 |
+
min_children: int = 1,
|
| 133 |
+
fixed_len: int = MAX_SEQ_LEN,
|
| 134 |
+
) -> list:
|
| 135 |
+
"""
|
| 136 |
+
้ๅๆฏไธช็ฒ่็น๏ผๆ้ ไธๆกๅบๅฎ้ฟๅบฆ็ split ๅบๅใ
|
| 137 |
+
|
| 138 |
+
ๅบๅ token ้กบๅบ๏ผ
|
| 139 |
+
[parent(1)] [uncleรโคmax_uncles] [childรN_valid] [EOS(1)] [PADร...]
|
| 140 |
+
|
| 141 |
+
role ็ผ็ ๏ผ
|
| 142 |
+
0 = parent ๅๆ ๅบๅฎไธบ (0,0,0)๏ผ็นๅพๆฅ่ช่ช่บซ
|
| 143 |
+
1 = uncle ๅๆ ็ธๅฏน parent๏ผ็นๅพๆฅ่ช่ช่บซ
|
| 144 |
+
2 = child ๅๆ ็ธๅฏน parent๏ผ็นๅพๆฅ่ช็ปๅฐบๅบฆ
|
| 145 |
+
3 = EOS ็ปๆ็ฌฆ๏ผๆ ๅฟ็ๅฎๅญ่็นๅทฒๅ
จ้จ่พๅบ
|
| 146 |
+
4 = PAD ่กฅ้ฝ๏ผattention mask ไธญ่ขซๅฑ่ฝ
|
| 147 |
+
|
| 148 |
+
่ฟๅ๏ผlist of np.ndarray๏ผๆฏไธชๅ
็ด shape (fixed_len,) TOKEN_DTYPE
|
| 149 |
+
"""
|
| 150 |
+
N_parents = children_ids.shape[0]
|
| 151 |
+
sequences = []
|
| 152 |
+
|
| 153 |
+
for p_idx in range(N_parents):
|
| 154 |
+
child_row = children_ids[p_idx]
|
| 155 |
+
valid_children = child_row[child_row >= 0]
|
| 156 |
+
|
| 157 |
+
if len(valid_children) < min_children:
|
| 158 |
+
continue
|
| 159 |
+
|
| 160 |
+
parent_pos = parent_quant['positions'][p_idx]
|
| 161 |
+
tokens = []
|
| 162 |
+
|
| 163 |
+
# โโ parent๏ผๅๆ ็ฝฎ้ถ๏ผโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 164 |
+
t = make_token(p_idx, parent_quant, parent_pos, ROLE_PARENT)
|
| 165 |
+
t['dx'] = t['dy'] = t['dz'] = 0.0
|
| 166 |
+
tokens.append(t)
|
| 167 |
+
|
| 168 |
+
# โโ uncle๏ผๅๅๅ half ไธช็ฉบ้ด้ปๅฑ
๏ผโโโโโโโโโโโโ
|
| 169 |
+
half = max_uncles // 2
|
| 170 |
+
added_uncles = 0
|
| 171 |
+
for offset in list(range(-half, 0)) + list(range(1, half + 1)):
|
| 172 |
+
u_idx = p_idx + offset
|
| 173 |
+
if 0 <= u_idx < N_parents and added_uncles < max_uncles:
|
| 174 |
+
tokens.append(
|
| 175 |
+
make_token(u_idx, parent_quant, parent_pos, ROLE_UNCLE)
|
| 176 |
+
)
|
| 177 |
+
added_uncles += 1
|
| 178 |
+
|
| 179 |
+
# โโ child๏ผๆๆๆๆๅญ่็น๏ผโโโโโโโโโโโโโโโโโโโโโโ
|
| 180 |
+
for c_idx in valid_children:
|
| 181 |
+
tokens.append(
|
| 182 |
+
make_token(int(c_idx), child_quant, parent_pos, ROLE_CHILD)
|
| 183 |
+
)
|
| 184 |
+
|
| 185 |
+
# โโ EOS โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 186 |
+
tokens.append(make_eos_token())
|
| 187 |
+
|
| 188 |
+
# โโ PAD ่กฅ้ฝๅฐ fixed_len โโโโโโโโโโโโโโโโโโโโโโโโ
|
| 189 |
+
while len(tokens) < fixed_len:
|
| 190 |
+
tokens.append(make_pad_token())
|
| 191 |
+
|
| 192 |
+
# ่ถ
้ฟๆชๆญ๏ผๆ็ซฏๆ
ๅต๏ผuncle+child ่ถ
ๅบ fixed_len-2๏ผ
|
| 193 |
+
if len(tokens) > fixed_len:
|
| 194 |
+
tokens = tokens[:fixed_len - 1]
|
| 195 |
+
tokens.append(make_eos_token())
|
| 196 |
+
|
| 197 |
+
sequences.append(np.array(tokens, dtype=TOKEN_DTYPE))
|
| 198 |
+
|
| 199 |
+
return sequences
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 203 |
+
# 5. ๅคๅฑๅบๅๆๅปบไธปๅฝๆฐ
|
| 204 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 205 |
+
|
| 206 |
+
def build_all_sequences(
|
| 207 |
+
quant_paths: list, # ๆ็ฒโ็ป้กบๅบ๏ผ[L3.npz, L2.npz, L1.npz, L0.npz]
|
| 208 |
+
genealogy_path: str,
|
| 209 |
+
save_dir: str,
|
| 210 |
+
max_uncles: int = MAX_UNCLES,
|
| 211 |
+
min_children: int = 1,
|
| 212 |
+
) -> None:
|
| 213 |
+
"""
|
| 214 |
+
quant_paths ๆ็ฒโ็ป้กบๅบไผ ๅ
ฅ๏ผไพๅฆ๏ผ
|
| 215 |
+
[L3_quantized.npz, L2_quantized.npz, L1_quantized.npz, L0_quantized.npz]
|
| 216 |
+
|
| 217 |
+
genealogy.pkl ๆ ผๅผ๏ผ
|
| 218 |
+
genealogy[3]['children_ids'] shape (N_L3, MAX_CHILDREN)
|
| 219 |
+
L3็ฒ่็น โ L2็ป่็น็ดขๅผ
|
| 220 |
+
genealogy[2]['children_ids'] shape (N_L2, MAX_CHILDREN)
|
| 221 |
+
L2็ฒ่็น โ L1็ป่็น็ดขๅผ
|
| 222 |
+
genealogy[1]['children_ids'] shape (N_L1, MAX_CHILDREN)
|
| 223 |
+
L1็ฒ่็น โ L0็ป่็น็ดขๅผ
|
| 224 |
+
|
| 225 |
+
่พๅบ๏ผๆ็ฒโ็ปๅฝๅ๏ผ๏ผ
|
| 226 |
+
save_dir/sequences_L3_to_L2.pkl
|
| 227 |
+
save_dir/sequences_L2_to_L1.pkl
|
| 228 |
+
save_dir/sequences_L1_to_L0.pkl
|
| 229 |
+
"""
|
| 230 |
+
os.makedirs(save_dir, exist_ok=True)
|
| 231 |
+
|
| 232 |
+
print(f"[build] ๅ ่ฝฝๆ่ฐฑ๏ผ{genealogy_path}")
|
| 233 |
+
genealogy = load_genealogy(genealogy_path)
|
| 234 |
+
|
| 235 |
+
print(f"[build] ๅ ่ฝฝ้ๅๆฐๆฎ๏ผๅ
ฑ {len(quant_paths)} ไธชๅฐบๅบฆ๏ผ็ฒโ็ป้กบๅบ๏ผ...")
|
| 236 |
+
quants = []
|
| 237 |
+
for path in quant_paths:
|
| 238 |
+
print(f" {os.path.basename(path)}")
|
| 239 |
+
quants.append(load_quantized(path))
|
| 240 |
+
|
| 241 |
+
# quants[0]=ๆ็ฒ(L3), quants[1]=L2, ..., quants[-1]=ๆ็ป(L0)
|
| 242 |
+
n_levels = len(quants)
|
| 243 |
+
# genealogy key: quants[0]โquants[1] ๅฏนๅบ key=n_levels-1๏ผๅณ3๏ผ
|
| 244 |
+
# quants[1]โquants[2] ๅฏนๅบ key=n_levels-2๏ผๅณ2๏ผ
|
| 245 |
+
# ...
|
| 246 |
+
|
| 247 |
+
for i in range(n_levels - 1):
|
| 248 |
+
coarse_level = n_levels - 1 - i # 3, 2, 1
|
| 249 |
+
fine_level = coarse_level - 1 # 2, 1, 0
|
| 250 |
+
gen_key = coarse_level # genealogy key ไธ็ฒๅฐบๅบฆ็ผๅทไธ่ด
|
| 251 |
+
|
| 252 |
+
coarse_name = f"L{coarse_level}"
|
| 253 |
+
fine_name = f"L{fine_level}"
|
| 254 |
+
|
| 255 |
+
if gen_key not in genealogy:
|
| 256 |
+
print(f"[build] ่ญฆๅ๏ผๆ่ฐฑไธญๆ key={gen_key}๏ผ่ทณ่ฟ {coarse_name}โ{fine_name}")
|
| 257 |
+
continue
|
| 258 |
+
|
| 259 |
+
parent_quant = quants[i]
|
| 260 |
+
child_quant = quants[i + 1]
|
| 261 |
+
children_ids = genealogy[gen_key]['children_ids'] # (N_coarse, 32)
|
| 262 |
+
|
| 263 |
+
print(f"\n[build] ๆๅปบ {coarse_name}โ{fine_name} ๅบๅ")
|
| 264 |
+
print(f" ็ถ่็นๆฐ={children_ids.shape[0]}, "
|
| 265 |
+
f"children_ids.shape={children_ids.shape}")
|
| 266 |
+
|
| 267 |
+
sequences = build_level_sequences(
|
| 268 |
+
parent_quant, child_quant, children_ids,
|
| 269 |
+
max_uncles=max_uncles,
|
| 270 |
+
min_children=min_children,
|
| 271 |
+
fixed_len=MAX_SEQ_LEN,
|
| 272 |
+
)
|
| 273 |
+
|
| 274 |
+
if len(sequences) == 0:
|
| 275 |
+
print(" [่ญฆๅ] ๆฒกๆๆๆๅบๅ๏ผ่ฏทๆฃๆฅๆ่ฐฑไธ้ๅๆฐๆฎ")
|
| 276 |
+
continue
|
| 277 |
+
|
| 278 |
+
# ็ป่ฎกๅญ่็นๆฐๅๅธ
|
| 279 |
+
child_counts = np.array([
|
| 280 |
+
int((s['role'] == ROLE_CHILD).sum()) for s in sequences
|
| 281 |
+
])
|
| 282 |
+
print(f" ็ๆๅบๅๆฐ๏ผ{len(sequences)}")
|
| 283 |
+
print(f" ๅญ่็นๆฐ๏ผmin={child_counts.min()}, "
|
| 284 |
+
f"max={child_counts.max()}, mean={child_counts.mean():.2f}")
|
| 285 |
+
|
| 286 |
+
# role ๅๅธ็ป่ฎก
|
| 287 |
+
all_roles = np.concatenate([s['role'] for s in sequences])
|
| 288 |
+
for r, name in [(0,'parent'),(1,'uncle'),(2,'child'),(3,'EOS'),(4,'PAD')]:
|
| 289 |
+
cnt = (all_roles == r).sum()
|
| 290 |
+
print(f" role={r}({name:6s})๏ผ{cnt:,} tokens")
|
| 291 |
+
|
| 292 |
+
out_path = os.path.join(save_dir,
|
| 293 |
+
f"sequences_{coarse_name}_to_{fine_name}.pkl")
|
| 294 |
+
with open(out_path, 'wb') as f:
|
| 295 |
+
pickle.dump(sequences, f, protocol=4)
|
| 296 |
+
|
| 297 |
+
size_mb = os.path.getsize(out_path) / 1024 / 1024
|
| 298 |
+
print(f" ไฟๅญ โ {out_path} ({size_mb:.2f} MB)")
|
| 299 |
+
|
| 300 |
+
print(f"\n[build] ๅ
จ้จๅบๅๆๅปบๅฎๆ๏ผ")
|
| 301 |
+
print(f" ๅบๅฎๅบๅ้ฟๅบฆ MAX_SEQ_LEN={MAX_SEQ_LEN} "
|
| 302 |
+
f"(parent=1, uncleโค{MAX_UNCLES}, childโค{MAX_CHILDREN}, EOS=1)")
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 306 |
+
# 6. CLI
|
| 307 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 308 |
+
|
| 309 |
+
def parse_args():
|
| 310 |
+
parser = argparse.ArgumentParser(description="ๆๅปบ 3DGS split ๅบๅ")
|
| 311 |
+
parser.add_argument('--quant_paths', nargs='+', required=True,
|
| 312 |
+
help='้ๅ .npz ่ทฏๅพ๏ผๆ็ฒโ็ป้กบๅบ๏ผL3 L2 L1 L0')
|
| 313 |
+
parser.add_argument('--genealogy', required=True,
|
| 314 |
+
help='ๆ่ฐฑ genealogy.pkl ่ทฏๅพ')
|
| 315 |
+
parser.add_argument('--save_dir', default='./sequences',
|
| 316 |
+
help='ๅบๅ่พๅบ็ฎๅฝ๏ผ้ป่ฎค ./sequences๏ผ')
|
| 317 |
+
parser.add_argument('--max_uncles', type=int, default=MAX_UNCLES)
|
| 318 |
+
parser.add_argument('--min_children', type=int, default=1)
|
| 319 |
+
return parser.parse_args()
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
if __name__ == '__main__':
|
| 323 |
+
args = parse_args()
|
| 324 |
+
build_all_sequences(
|
| 325 |
+
quant_paths=args.quant_paths,
|
| 326 |
+
genealogy_path=args.genealogy,
|
| 327 |
+
save_dir=args.save_dir,
|
| 328 |
+
max_uncles=args.max_uncles,
|
| 329 |
+
min_children=args.min_children,
|
| 330 |
+
)
|
infer_upsample.py
ADDED
|
@@ -0,0 +1,456 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
)
|
train_transformer.py
ADDED
|
@@ -0,0 +1,526 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
train_transformer.py
|
| 3 |
+
====================
|
| 4 |
+
่ฎญ็ปๅฑ็บง 3DGS split ็ๆ Transformerใ
|
| 5 |
+
|
| 6 |
+
ๆจกๅ๏ผGPT ้ฃๆ ผ decoder-only Transformer๏ผ่ชๅๅฝ้ขๆตๅบๅไธญๆฏไธชไธไธไธช tokenใ
|
| 7 |
+
|
| 8 |
+
่พๅ
ฅๅบๅ๏ผๅบๅฎ้ฟๅบฆ MAX_SEQ_LEN=38๏ผ๏ผ
|
| 9 |
+
[parent(1)] [uncleรโค4] [childรโค32] [EOS(1)] [PADร...]
|
| 10 |
+
|
| 11 |
+
role ็ผ็ ๏ผ
|
| 12 |
+
0 = parent 1 = uncle 2 = child 3 = EOS 4 = PAD
|
| 13 |
+
|
| 14 |
+
่พๅบ๏ผๅคๅคด๏ผ๏ผ
|
| 15 |
+
role ๅ็ฑป (0~3๏ผ4็ฑป๏ผPADไธ้ขๆต) cross-entropy
|
| 16 |
+
xyz ๅๅฝ MSE๏ผๅชๅจ child ไฝ็ฝฎ๏ผ
|
| 17 |
+
opacity ๅๅฝ MSE๏ผๅชๅจ child ไฝ็ฝฎ๏ผ
|
| 18 |
+
scale ๅ็ฑป N_SCALE=16384 CE๏ผๅชๅจ child ไฝ็ฝฎ๏ผ
|
| 19 |
+
rot ๅ็ฑป N_ROT=16384 CE๏ผๅชๅจ child ไฝ็ฝฎ๏ผ
|
| 20 |
+
dc ๅ็ฑป N_DC=4096 CE๏ผๅชๅจ child ไฝ็ฝฎ๏ผ
|
| 21 |
+
sh ๅ็ฑป N_SH=4096 CE๏ผๅชๅจ child ไฝ็ฝฎ๏ผ
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
import os
|
| 25 |
+
import math
|
| 26 |
+
import argparse
|
| 27 |
+
import pickle
|
| 28 |
+
import numpy as np
|
| 29 |
+
|
| 30 |
+
import torch
|
| 31 |
+
import torch.nn as nn
|
| 32 |
+
import torch.nn.functional as F
|
| 33 |
+
from torch.utils.data import Dataset, DataLoader
|
| 34 |
+
|
| 35 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 36 |
+
# ๅธธ้๏ผไธ build_sequences.py ไฟๆไธ่ด๏ผ
|
| 37 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 38 |
+
|
| 39 |
+
ROLE_PARENT = 0
|
| 40 |
+
ROLE_UNCLE = 1
|
| 41 |
+
ROLE_CHILD = 2
|
| 42 |
+
ROLE_EOS = 3
|
| 43 |
+
ROLE_PAD = 4
|
| 44 |
+
|
| 45 |
+
MAX_CHILDREN = 32
|
| 46 |
+
MAX_UNCLES = 4
|
| 47 |
+
MAX_SEQ_LEN = 1 + MAX_UNCLES + MAX_CHILDREN + 1 # = 38
|
| 48 |
+
|
| 49 |
+
N_SCALE = 16384
|
| 50 |
+
N_ROT = 16384
|
| 51 |
+
N_DC = 4096
|
| 52 |
+
N_SH = 4096
|
| 53 |
+
N_ROLE = 4 # ๆจกๅๅช้ขๆต 0~3๏ผPAD ไธ่พๅบ
|
| 54 |
+
|
| 55 |
+
TOKEN_DTYPE = np.dtype([
|
| 56 |
+
('dx', np.float32),
|
| 57 |
+
('dy', np.float32),
|
| 58 |
+
('dz', np.float32),
|
| 59 |
+
('scale_idx', np.int32),
|
| 60 |
+
('rot_idx', np.int32),
|
| 61 |
+
('dc_idx', np.int32),
|
| 62 |
+
('sh_idx', np.int32),
|
| 63 |
+
('opacity', np.float32),
|
| 64 |
+
('role', np.uint8),
|
| 65 |
+
])
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 69 |
+
# 1. Dataset
|
| 70 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 71 |
+
|
| 72 |
+
class SplitSequenceDataset(Dataset):
|
| 73 |
+
"""
|
| 74 |
+
ๅ ่ฝฝ build_sequences.py ็ๆ็ .pkl ๅบๅๆไปถใ
|
| 75 |
+
ๅบๅๅทฒๆฏๅบๅฎ้ฟๅบฆ MAX_SEQ_LEN๏ผๆ ้ๅ padใ
|
| 76 |
+
"""
|
| 77 |
+
|
| 78 |
+
def __init__(self, seq_pkl_paths: list):
|
| 79 |
+
self.sequences = []
|
| 80 |
+
for path in seq_pkl_paths:
|
| 81 |
+
with open(path, 'rb') as f:
|
| 82 |
+
seqs = pickle.load(f)
|
| 83 |
+
self.sequences.extend(seqs)
|
| 84 |
+
print(f" ๅ ่ฝฝ {os.path.basename(path)}๏ผ{len(seqs)} ๆก")
|
| 85 |
+
print(f"[Dataset] ๅ
ฑ {len(self.sequences)} ๆกๅบๅ๏ผ"
|
| 86 |
+
f"ๅบๅฎ้ฟๅบฆ {MAX_SEQ_LEN}")
|
| 87 |
+
|
| 88 |
+
def __len__(self):
|
| 89 |
+
return len(self.sequences)
|
| 90 |
+
|
| 91 |
+
def __getitem__(self, idx):
|
| 92 |
+
seq = self.sequences[idx] # (MAX_SEQ_LEN,) TOKEN_DTYPE
|
| 93 |
+
role = seq['role'].astype(np.int64) # (L,)
|
| 94 |
+
|
| 95 |
+
# attention mask๏ผPAD ไฝ็ฝฎไธบ False
|
| 96 |
+
attn_mask = (role != ROLE_PAD) # (L,) bool
|
| 97 |
+
|
| 98 |
+
# loss_mask_feat๏ผๅชๅจ child ไฝ็ฝฎ่ฎก็ฎ็นๅพ loss๏ผxyz/opa/scale/rot/dc/sh๏ผ
|
| 99 |
+
loss_mask_feat = (role == ROLE_CHILD) # (L,) bool
|
| 100 |
+
|
| 101 |
+
# loss_mask_role๏ผๅจๆๆ้ PAD ไฝ็ฝฎ่ฎก็ฎ role ๅ็ฑป loss๏ผๅ
ๅซ EOS๏ผ
|
| 102 |
+
loss_mask_role = (role != ROLE_PAD) # (L,) bool
|
| 103 |
+
|
| 104 |
+
xyz = np.stack([seq['dx'], seq['dy'], seq['dz']], axis=1) # (L, 3)
|
| 105 |
+
|
| 106 |
+
return {
|
| 107 |
+
'xyz': torch.from_numpy(xyz).float(),
|
| 108 |
+
'scale': torch.from_numpy(seq['scale_idx'].astype(np.int64)),
|
| 109 |
+
'rot': torch.from_numpy(seq['rot_idx'].astype(np.int64)),
|
| 110 |
+
'dc': torch.from_numpy(seq['dc_idx'].astype(np.int64)),
|
| 111 |
+
'sh': torch.from_numpy(seq['sh_idx'].astype(np.int64)),
|
| 112 |
+
'opacity': torch.from_numpy(seq['opacity'].astype(np.float32)),
|
| 113 |
+
'role': torch.from_numpy(role),
|
| 114 |
+
'attn_mask': torch.from_numpy(attn_mask),
|
| 115 |
+
'loss_mask_feat': torch.from_numpy(loss_mask_feat),
|
| 116 |
+
'loss_mask_role': torch.from_numpy(loss_mask_role),
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def collate_fn(batch):
|
| 121 |
+
keys = ['xyz', 'scale', 'rot', 'dc', 'sh', 'opacity',
|
| 122 |
+
'role', 'attn_mask', 'loss_mask_feat', 'loss_mask_role']
|
| 123 |
+
return {k: torch.stack([b[k] for b in batch], dim=0) for k in keys}
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 127 |
+
# 2. Token Embedding
|
| 128 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ๏ฟฝ๏ฟฝ๏ฟฝโโโโโโโ
|
| 129 |
+
|
| 130 |
+
class TokenEmbedding(nn.Module):
|
| 131 |
+
"""
|
| 132 |
+
ๅฐๆฏไธช token ็ๅคๅญๆฎต๏ผ็ฆปๆฃ็ดขๅผ + ่ฟ็ปญๅผ + role๏ผๆ ๅฐๅฐ d_model ็ปดใ
|
| 133 |
+
"""
|
| 134 |
+
|
| 135 |
+
def __init__(self, d_model: int):
|
| 136 |
+
super().__init__()
|
| 137 |
+
d = d_model // 8 # ๆฏไธชๅญๅญๆฎต็ embedding ็ปดๅบฆ
|
| 138 |
+
|
| 139 |
+
# ็ฆปๆฃ็ดขๅผ embedding๏ผ็ดขๅผ +1 ๅ็งป๏ผ0 ็็ป padding_idx๏ผ
|
| 140 |
+
self.emb_scale = nn.Embedding(N_SCALE + 1, d, padding_idx=0)
|
| 141 |
+
self.emb_rot = nn.Embedding(N_ROT + 1, d, padding_idx=0)
|
| 142 |
+
self.emb_dc = nn.Embedding(N_DC + 1, d, padding_idx=0)
|
| 143 |
+
self.emb_sh = nn.Embedding(N_SH + 1, d, padding_idx=0)
|
| 144 |
+
|
| 145 |
+
# role embedding๏ผ0~3 ๆๆ๏ผ4=PAD๏ผpadding_idx ๅฑ่ฝๆขฏๅบฆ๏ผ
|
| 146 |
+
self.emb_role = nn.Embedding(5, d, padding_idx=ROLE_PAD)
|
| 147 |
+
|
| 148 |
+
# ่ฟ็ปญ้ๆๅฝฑ
|
| 149 |
+
self.proj_xyz = nn.Linear(3, d * 2)
|
| 150 |
+
self.proj_opa = nn.Linear(1, d)
|
| 151 |
+
|
| 152 |
+
# ๅๅนถ๏ผxyz(2d) + scale(d) + rot(d) + dc(d) + sh(d) + opa(d) + role(d) = 8d
|
| 153 |
+
self.proj = nn.Linear(d * 8, d_model)
|
| 154 |
+
|
| 155 |
+
def forward(self, batch: dict) -> torch.Tensor:
|
| 156 |
+
# ็ฆปๆฃ็ดขๅผ +1 ้ฟๅ
ไธ padding_idx=0 ๅฒ็ช
|
| 157 |
+
e_s = self.emb_scale(batch['scale'] + 1) # (B, L, d)
|
| 158 |
+
e_r = self.emb_rot( batch['rot'] + 1)
|
| 159 |
+
e_d = self.emb_dc( batch['dc'] + 1)
|
| 160 |
+
e_h = self.emb_sh( batch['sh'] + 1)
|
| 161 |
+
|
| 162 |
+
# role ็ดๆฅไฝฟ็จ๏ผ0~4๏ผ๏ผPAD(4) ็ฑ padding_idx ่ชๅจๅฝ้ถ
|
| 163 |
+
e_role = self.emb_role(batch['role']) # (B, L, d)
|
| 164 |
+
|
| 165 |
+
e_xyz = self.proj_xyz(batch['xyz'].float()) # (B, L, 2d)
|
| 166 |
+
e_opa = self.proj_opa(batch['opacity'].unsqueeze(-1).float()) # (B, L, d)
|
| 167 |
+
|
| 168 |
+
cat = torch.cat([e_xyz, e_s, e_r, e_d, e_h, e_opa, e_role], dim=-1) # (B,L,8d)
|
| 169 |
+
return self.proj(cat) # (B, L, d_model)
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 173 |
+
# 3. Transformer Model
|
| 174 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 175 |
+
|
| 176 |
+
class SplitTransformer(nn.Module):
|
| 177 |
+
"""
|
| 178 |
+
Decoder-only Transformer๏ผ่ชๅๅฝ้ขๆตไธไธไธช token ็ๆๆๅญๆฎตใ
|
| 179 |
+
ไฝฟ็จ Pre-LayerNorm๏ผๆด็จณๅฎ๏ผ๏ผๅ ๆ mask + PAD key_padding_maskใ
|
| 180 |
+
"""
|
| 181 |
+
|
| 182 |
+
def __init__(
|
| 183 |
+
self,
|
| 184 |
+
d_model: int = 512,
|
| 185 |
+
n_heads: int = 8,
|
| 186 |
+
n_layers: int = 6,
|
| 187 |
+
d_ff: int = 2048,
|
| 188 |
+
max_seq_len: int = MAX_SEQ_LEN,
|
| 189 |
+
dropout: float = 0.1,
|
| 190 |
+
):
|
| 191 |
+
super().__init__()
|
| 192 |
+
self.d_model = d_model
|
| 193 |
+
self.max_seq_len = max_seq_len
|
| 194 |
+
|
| 195 |
+
self.token_emb = TokenEmbedding(d_model)
|
| 196 |
+
self.pos_emb = nn.Embedding(max_seq_len, d_model)
|
| 197 |
+
|
| 198 |
+
layer = nn.TransformerDecoderLayer(
|
| 199 |
+
d_model=d_model,
|
| 200 |
+
nhead=n_heads,
|
| 201 |
+
dim_feedforward=d_ff,
|
| 202 |
+
dropout=dropout,
|
| 203 |
+
batch_first=True,
|
| 204 |
+
norm_first=True, # Pre-LN๏ผๆด็จณๅฎ
|
| 205 |
+
)
|
| 206 |
+
self.transformer = nn.TransformerDecoder(layer, num_layers=n_layers)
|
| 207 |
+
|
| 208 |
+
# ๅ ๆ mask๏ผไธไธ่งๅฑ่ฝๆชๆฅไฝ็ฝฎ๏ผ
|
| 209 |
+
self.register_buffer(
|
| 210 |
+
'causal_mask',
|
| 211 |
+
torch.triu(torch.ones(max_seq_len, max_seq_len), diagonal=1).bool()
|
| 212 |
+
)
|
| 213 |
+
|
| 214 |
+
# โโ ๅคๅคด่พๅบ โโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 215 |
+
self.head_role = nn.Linear(d_model, N_ROLE) # ๅ็ฑป 4 ็ฑป๏ผไธๅซ PAD๏ผ
|
| 216 |
+
self.head_xyz = nn.Linear(d_model, 3) # ๅๅฝ
|
| 217 |
+
self.head_opacity = nn.Linear(d_model, 1) # ๅๅฝ
|
| 218 |
+
self.head_scale = nn.Linear(d_model, N_SCALE) # ๅ็ฑป
|
| 219 |
+
self.head_rot = nn.Linear(d_model, N_ROT) # ๅ็ฑป
|
| 220 |
+
self.head_dc = nn.Linear(d_model, N_DC) # ๅ็ฑป
|
| 221 |
+
self.head_sh = nn.Linear(d_model, N_SH) # ๅ็ฑป
|
| 222 |
+
|
| 223 |
+
self._init_weights()
|
| 224 |
+
|
| 225 |
+
def _init_weights(self):
|
| 226 |
+
for m in self.modules():
|
| 227 |
+
if isinstance(m, nn.Linear):
|
| 228 |
+
nn.init.xavier_uniform_(m.weight)
|
| 229 |
+
if m.bias is not None:
|
| 230 |
+
nn.init.zeros_(m.bias)
|
| 231 |
+
elif isinstance(m, nn.Embedding):
|
| 232 |
+
nn.init.normal_(m.weight, std=0.02)
|
| 233 |
+
if m.padding_idx is not None:
|
| 234 |
+
nn.init.zeros_(m.weight[m.padding_idx])
|
| 235 |
+
|
| 236 |
+
def forward(self, batch: dict) -> dict:
|
| 237 |
+
B, L = batch['scale'].shape
|
| 238 |
+
|
| 239 |
+
# Token embedding + ไฝ็ฝฎ embedding
|
| 240 |
+
tok_emb = self.token_emb(batch) # (B, L, D)
|
| 241 |
+
pos = torch.arange(L, device=tok_emb.device)
|
| 242 |
+
x = tok_emb + self.pos_emb(pos).unsqueeze(0) # (B, L, D)
|
| 243 |
+
|
| 244 |
+
# key_padding_mask๏ผTrue ็ไฝ็ฝฎ่ขซๅฟฝ็ฅ๏ผPAD๏ผ
|
| 245 |
+
pad_mask = ~batch['attn_mask'] # (B, L)
|
| 246 |
+
|
| 247 |
+
# ๅ ๆ mask๏ผLรL ไธไธ่ง๏ผ
|
| 248 |
+
causal = self.causal_mask[:L, :L] # (L, L)
|
| 249 |
+
|
| 250 |
+
# Decoder๏ผtgt=memory=x๏ผ้ๅไธบ็บฏ self-attn๏ผ
|
| 251 |
+
out = self.transformer(
|
| 252 |
+
tgt=x,
|
| 253 |
+
memory=x,
|
| 254 |
+
tgt_mask=causal,
|
| 255 |
+
memory_mask=causal,
|
| 256 |
+
tgt_key_padding_mask=pad_mask,
|
| 257 |
+
memory_key_padding_mask=pad_mask,
|
| 258 |
+
) # (B, L, D)
|
| 259 |
+
|
| 260 |
+
return {
|
| 261 |
+
'role': self.head_role(out), # (B, L, 4)
|
| 262 |
+
'xyz': self.head_xyz(out), # (B, L, 3)
|
| 263 |
+
'opacity': self.head_opacity(out), # (B, L, 1)
|
| 264 |
+
'scale': self.head_scale(out), # (B, L, N_SCALE)
|
| 265 |
+
'rot': self.head_rot(out), # (B, L, N_ROT)
|
| 266 |
+
'dc': self.head_dc(out), # (B, L, N_DC)
|
| 267 |
+
'sh': self.head_sh(out), # (B, L, N_SH)
|
| 268 |
+
}
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 272 |
+
# 4. Loss
|
| 273 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 274 |
+
|
| 275 |
+
def compute_loss(pred: dict, batch: dict, weights: dict = None) -> tuple:
|
| 276 |
+
"""
|
| 277 |
+
่ชๅๅฝ loss๏ผไฝ็ฝฎ t ็่พๅบ้ขๆตไฝ็ฝฎ t+1 ็ tokenใ
|
| 278 |
+
|
| 279 |
+
loss_mask_feat๏ผchild ไฝ็ฝฎ๏ผโ ็นๅพ loss๏ผxyz/opa/scale/rot/dc/sh๏ผ
|
| 280 |
+
loss_mask_role๏ผ้PADไฝ็ฝฎ๏ผ โ role ๅ็ฑป loss๏ผๅ
ๅซ EOS ็ role=3๏ผ
|
| 281 |
+
|
| 282 |
+
ไธค็ฑป mask ๅๅจ shift ๅ๏ผ[:, 1:]๏ผๅใ
|
| 283 |
+
"""
|
| 284 |
+
if weights is None:
|
| 285 |
+
weights = {
|
| 286 |
+
'role': 1.5,
|
| 287 |
+
'xyz': 1.0, 'opacity': 0.5,
|
| 288 |
+
'scale': 2.0, 'rot': 2.0, 'dc': 1.0, 'sh': 1.0,
|
| 289 |
+
}
|
| 290 |
+
|
| 291 |
+
# shift๏ผ็จไฝ็ฝฎ t ็่พๅบ้ขๆตไฝ็ฝฎ t+1
|
| 292 |
+
feat_mask = batch['loss_mask_feat'][:, 1:] # (B, L-1) child ไฝ็ฝฎ
|
| 293 |
+
role_mask = batch['loss_mask_role'][:, 1:] # (B, L-1) ้PADไฝ็ฝฎ
|
| 294 |
+
|
| 295 |
+
def _reg_loss(pred_key, tgt_key, mask, squeeze=False):
|
| 296 |
+
p = pred[pred_key][:, :-1] # (B, L-1, ...)
|
| 297 |
+
t = batch[tgt_key][:, 1:]
|
| 298 |
+
if squeeze:
|
| 299 |
+
p = p.squeeze(-1)
|
| 300 |
+
mse = F.mse_loss(p, t.float(), reduction='none')
|
| 301 |
+
if mse.dim() == 3:
|
| 302 |
+
mse = mse.mean(-1)
|
| 303 |
+
denom = mask.sum().clamp(min=1)
|
| 304 |
+
return (mse * mask).sum() / denom
|
| 305 |
+
|
| 306 |
+
def _cls_loss(pred_key, tgt_key, mask):
|
| 307 |
+
p = pred[pred_key][:, :-1] # (B, L-1, C)
|
| 308 |
+
t = batch[tgt_key][:, 1:] # (B, L-1)
|
| 309 |
+
if not mask.any():
|
| 310 |
+
return p.sum() * 0.0
|
| 311 |
+
return F.cross_entropy(p[mask], t[mask])
|
| 312 |
+
|
| 313 |
+
# role loss๏ผๅจๆๆ้ PAD ไฝ็ฝฎ๏ผๅ
ๅซ EOS๏ผ
|
| 314 |
+
loss_role = _cls_loss('role', 'role', role_mask)
|
| 315 |
+
|
| 316 |
+
# ็นๅพ loss๏ผๅชๅจ child ไฝ็ฝฎ
|
| 317 |
+
loss_xyz = _reg_loss('xyz', 'xyz', feat_mask)
|
| 318 |
+
loss_opa = _reg_loss('opacity', 'opacity', feat_mask, squeeze=True)
|
| 319 |
+
loss_scale = _cls_loss('scale', 'scale', feat_mask)
|
| 320 |
+
loss_rot = _cls_loss('rot', 'rot', feat_mask)
|
| 321 |
+
loss_dc = _cls_loss('dc', 'dc', feat_mask)
|
| 322 |
+
loss_sh = _cls_loss('sh', 'sh', feat_mask)
|
| 323 |
+
|
| 324 |
+
total = (
|
| 325 |
+
weights['role'] * loss_role +
|
| 326 |
+
weights['xyz'] * loss_xyz +
|
| 327 |
+
weights['opacity'] * loss_opa +
|
| 328 |
+
weights['scale'] * loss_scale +
|
| 329 |
+
weights['rot'] * loss_rot +
|
| 330 |
+
weights['dc'] * loss_dc +
|
| 331 |
+
weights['sh'] * loss_sh
|
| 332 |
+
)
|
| 333 |
+
|
| 334 |
+
return total, {
|
| 335 |
+
'role': loss_role.item(),
|
| 336 |
+
'xyz': loss_xyz.item(),
|
| 337 |
+
'opacity': loss_opa.item(),
|
| 338 |
+
'scale': loss_scale.item(),
|
| 339 |
+
'rot': loss_rot.item(),
|
| 340 |
+
'dc': loss_dc.item(),
|
| 341 |
+
'sh': loss_sh.item(),
|
| 342 |
+
'total': total.item(),
|
| 343 |
+
}
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 347 |
+
# 5. ่ฎญ็ปไธปๅพช็ฏ
|
| 348 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 349 |
+
|
| 350 |
+
def train(
|
| 351 |
+
seq_pkl_paths: list,
|
| 352 |
+
save_dir: str,
|
| 353 |
+
# ๆจกๅ่ถ
ๅ
|
| 354 |
+
d_model: int = 512,
|
| 355 |
+
n_heads: int = 8,
|
| 356 |
+
n_layers: int = 6,
|
| 357 |
+
d_ff: int = 2048,
|
| 358 |
+
dropout: float = 0.1,
|
| 359 |
+
# ่ฎญ็ป่ถ
ๅ
|
| 360 |
+
batch_size: int = 64,
|
| 361 |
+
lr: float = 3e-4,
|
| 362 |
+
epochs: int = 50,
|
| 363 |
+
warmup_steps: int = 1000,
|
| 364 |
+
grad_clip: float = 1.0,
|
| 365 |
+
val_ratio: float = 0.05,
|
| 366 |
+
save_every: int = 5,
|
| 367 |
+
device: str = 'auto',
|
| 368 |
+
):
|
| 369 |
+
os.makedirs(save_dir, exist_ok=True)
|
| 370 |
+
|
| 371 |
+
if device == 'auto':
|
| 372 |
+
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
| 373 |
+
print(f"[train] device={device}")
|
| 374 |
+
|
| 375 |
+
# โโ ๆฐๆฎ้ โโโโโโโโโโโโโโโโ๏ฟฝ๏ฟฝ๏ฟฝโโโโโโโโโโโโโโ
|
| 376 |
+
full_dataset = SplitSequenceDataset(seq_pkl_paths)
|
| 377 |
+
n_val = max(1, int(len(full_dataset) * val_ratio))
|
| 378 |
+
n_train = len(full_dataset) - n_val
|
| 379 |
+
train_set, val_set = torch.utils.data.random_split(
|
| 380 |
+
full_dataset, [n_train, n_val],
|
| 381 |
+
generator=torch.Generator().manual_seed(42)
|
| 382 |
+
)
|
| 383 |
+
|
| 384 |
+
train_loader = DataLoader(
|
| 385 |
+
train_set, batch_size=batch_size, shuffle=True,
|
| 386 |
+
collate_fn=collate_fn, num_workers=4, pin_memory=True,
|
| 387 |
+
)
|
| 388 |
+
val_loader = DataLoader(
|
| 389 |
+
val_set, batch_size=batch_size, shuffle=False,
|
| 390 |
+
collate_fn=collate_fn, num_workers=2,
|
| 391 |
+
)
|
| 392 |
+
|
| 393 |
+
# โโ ๆจกๅ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 394 |
+
model = SplitTransformer(
|
| 395 |
+
d_model=d_model, n_heads=n_heads, n_layers=n_layers,
|
| 396 |
+
d_ff=d_ff, max_seq_len=MAX_SEQ_LEN, dropout=dropout,
|
| 397 |
+
).to(device)
|
| 398 |
+
n_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
|
| 399 |
+
print(f"[train] ๅๆฐ้๏ผ{n_params / 1e6:.2f}M")
|
| 400 |
+
|
| 401 |
+
# โโ ไผๅๅจ + ่ฐๅบฆๅจ โโโโโโโโโโโโโโโโโโโโโโโ
|
| 402 |
+
optimizer = torch.optim.AdamW(model.parameters(), lr=lr, weight_decay=1e-2)
|
| 403 |
+
total_steps = epochs * len(train_loader)
|
| 404 |
+
|
| 405 |
+
def lr_lambda(step):
|
| 406 |
+
if step < warmup_steps:
|
| 407 |
+
return step / max(1, warmup_steps)
|
| 408 |
+
progress = (step - warmup_steps) / max(1, total_steps - warmup_steps)
|
| 409 |
+
return max(0.1, 0.5 * (1 + math.cos(math.pi * progress)))
|
| 410 |
+
|
| 411 |
+
scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda)
|
| 412 |
+
|
| 413 |
+
# โโ ่ฎญ็ปๅพช็ฏ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 414 |
+
best_val_loss = float('inf')
|
| 415 |
+
global_step = 0
|
| 416 |
+
|
| 417 |
+
for epoch in range(1, epochs + 1):
|
| 418 |
+
model.train()
|
| 419 |
+
epoch_losses = []
|
| 420 |
+
|
| 421 |
+
for batch in train_loader:
|
| 422 |
+
batch = {k: v.to(device) if isinstance(v, torch.Tensor) else v
|
| 423 |
+
for k, v in batch.items()}
|
| 424 |
+
|
| 425 |
+
pred = model(batch)
|
| 426 |
+
loss, loss_dict = compute_loss(pred, batch)
|
| 427 |
+
|
| 428 |
+
optimizer.zero_grad()
|
| 429 |
+
loss.backward()
|
| 430 |
+
nn.utils.clip_grad_norm_(model.parameters(), grad_clip)
|
| 431 |
+
optimizer.step()
|
| 432 |
+
scheduler.step()
|
| 433 |
+
epoch_losses.append(loss_dict['total'])
|
| 434 |
+
global_step += 1
|
| 435 |
+
|
| 436 |
+
train_loss = np.mean(epoch_losses)
|
| 437 |
+
|
| 438 |
+
# โโ ้ช่ฏ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 439 |
+
model.eval()
|
| 440 |
+
val_losses = []
|
| 441 |
+
with torch.no_grad():
|
| 442 |
+
for batch in val_loader:
|
| 443 |
+
batch = {k: v.to(device) if isinstance(v, torch.Tensor) else v
|
| 444 |
+
for k, v in batch.items()}
|
| 445 |
+
pred = model(batch)
|
| 446 |
+
_, ld = compute_loss(pred, batch)
|
| 447 |
+
val_losses.append(ld['total'])
|
| 448 |
+
val_loss = np.mean(val_losses)
|
| 449 |
+
|
| 450 |
+
print(f"[epoch {epoch:03d}/{epochs}] "
|
| 451 |
+
f"train={train_loss:.4f} val={val_loss:.4f} "
|
| 452 |
+
f"lr={scheduler.get_last_lr()[0]:.2e}")
|
| 453 |
+
|
| 454 |
+
# โโ checkpoint โโโโโโโโโโโโโโโโโโโโโโโโ
|
| 455 |
+
if epoch % save_every == 0:
|
| 456 |
+
ckpt_path = os.path.join(save_dir, f"ckpt_epoch{epoch:03d}.pt")
|
| 457 |
+
torch.save({
|
| 458 |
+
'epoch': epoch,
|
| 459 |
+
'model_state': model.state_dict(),
|
| 460 |
+
'optimizer_state': optimizer.state_dict(),
|
| 461 |
+
'val_loss': val_loss,
|
| 462 |
+
'config': dict(
|
| 463 |
+
d_model=d_model, n_heads=n_heads, n_layers=n_layers,
|
| 464 |
+
d_ff=d_ff, max_seq_len=MAX_SEQ_LEN, dropout=dropout,
|
| 465 |
+
),
|
| 466 |
+
}, ckpt_path)
|
| 467 |
+
print(f" checkpoint โ {ckpt_path}")
|
| 468 |
+
|
| 469 |
+
if val_loss < best_val_loss:
|
| 470 |
+
best_val_loss = val_loss
|
| 471 |
+
best_path = os.path.join(save_dir, 'best_model.pt')
|
| 472 |
+
torch.save({
|
| 473 |
+
'model_state': model.state_dict(),
|
| 474 |
+
'config': dict(
|
| 475 |
+
d_model=d_model, n_heads=n_heads, n_layers=n_layers,
|
| 476 |
+
d_ff=d_ff, max_seq_len=MAX_SEQ_LEN, dropout=dropout,
|
| 477 |
+
),
|
| 478 |
+
}, best_path)
|
| 479 |
+
|
| 480 |
+
print(f"\n[train] ่ฎญ็ปๅฎๆ๏ผๆไผ val_loss={best_val_loss:.4f}")
|
| 481 |
+
print(f" ๆไผๆจกๅ โ {best_path}")
|
| 482 |
+
return model
|
| 483 |
+
|
| 484 |
+
|
| 485 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 486 |
+
# 6. CLI
|
| 487 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 488 |
+
|
| 489 |
+
def parse_args():
|
| 490 |
+
p = argparse.ArgumentParser(description="่ฎญ็ป 3DGS split ็ๆ Transformer")
|
| 491 |
+
p.add_argument('--seq_paths', nargs='+', required=True,
|
| 492 |
+
help='ๅบๅ .pkl ่ทฏๅพ๏ผๅฏๅคไธชๅๅนถ่ฎญ็ป๏ผ')
|
| 493 |
+
p.add_argument('--save_dir', default='./checkpoints')
|
| 494 |
+
p.add_argument('--d_model', type=int, default=512)
|
| 495 |
+
p.add_argument('--n_heads', type=int, default=8)
|
| 496 |
+
p.add_argument('--n_layers', type=int, default=6)
|
| 497 |
+
p.add_argument('--d_ff', type=int, default=2048)
|
| 498 |
+
p.add_argument('--batch_size', type=int, default=64)
|
| 499 |
+
p.add_argument('--lr', type=float, default=3e-4)
|
| 500 |
+
p.add_argument('--epochs', type=int, default=50)
|
| 501 |
+
p.add_argument('--warmup', type=int, default=1000)
|
| 502 |
+
p.add_argument('--val_ratio', type=float, default=0.05)
|
| 503 |
+
p.add_argument('--save_every', type=int, default=5)
|
| 504 |
+
p.add_argument('--dropout', type=float, default=0.1)
|
| 505 |
+
p.add_argument('--device', default='auto')
|
| 506 |
+
return p.parse_args()
|
| 507 |
+
|
| 508 |
+
|
| 509 |
+
if __name__ == '__main__':
|
| 510 |
+
args = parse_args()
|
| 511 |
+
train(
|
| 512 |
+
seq_pkl_paths=args.seq_paths,
|
| 513 |
+
save_dir=args.save_dir,
|
| 514 |
+
d_model=args.d_model,
|
| 515 |
+
n_heads=args.n_heads,
|
| 516 |
+
n_layers=args.n_layers,
|
| 517 |
+
d_ff=args.d_ff,
|
| 518 |
+
dropout=args.dropout,
|
| 519 |
+
batch_size=args.batch_size,
|
| 520 |
+
lr=args.lr,
|
| 521 |
+
epochs=args.epochs,
|
| 522 |
+
warmup_steps=args.warmup,
|
| 523 |
+
val_ratio=args.val_ratio,
|
| 524 |
+
save_every=args.save_every,
|
| 525 |
+
device=args.device,
|
| 526 |
+
)
|