SlekLi commited on
Commit
98a682c
ยท
verified ยท
1 Parent(s): 2d2f9ed

Upload 3 files

Browse files
Files changed (3) hide show
  1. build_sequence.py +330 -0
  2. infer_upsample.py +456 -0
  3. train_transformer.py +526 -0
build_sequence.py ADDED
@@ -0,0 +1,330 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ )