-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathprovider.py
587 lines (455 loc) · 21.8 KB
/
provider.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
'''
-----------------------------------------------------------------------------
Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved.
NVIDIA CORPORATION and its licensors retain all intellectual property
and proprietary rights in and to this software, related documentation
and any modifications thereto. Any use, reproduction, disclosure or
distribution of this software and related documentation without an express
license agreement from NVIDIA CORPORATION is strictly prohibited.
-----------------------------------------------------------------------------
'''
import os
import cv2
import json
import glob
import random
import trimesh
import numpy as np
import megfile
import tarfile
import sys
sys.path.append('.')
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.transforms.functional as TF
from torch.utils.data import Dataset, DataLoader
import kiui
from kiui.mesh_utils import clean_mesh, decimate_mesh
from kiui.op import recenter
from core.options import Options
from core.utils import load_mesh, normalize_mesh, get_tokenizer
def save_mesh(tokens, opt: Options, path=None, tokenizer=None, clean=True, verbose=False):
# tokens: [M], only for single-batch!
# trim EOS and make divisible
eos_idx = (tokens == opt.eos_token_id).nonzero()[0]
if len(eos_idx) > 0:
tokens = tokens[:eos_idx[0]]
vertices, faces = detokenize_mesh(tokens, opt.discrete_bins, tokenizer=tokenizer)
if verbose:
print(f'[INFO] vertices: {vertices.shape[0]}, faces: {faces.shape[0]}')
mesh = trimesh.Trimesh(vertices=vertices, faces=faces)
# fix flipped faces and merge close vertices
if clean:
mesh.merge_vertices()
mesh.update_faces(mesh.unique_faces())
mesh.fix_normals()
if verbose:
print(f'[INFO] cleaned vertices: {mesh.vertices.shape[0]}, faces: {mesh.faces.shape[0]}')
if path is None:
return mesh
else:
mesh.export(path)
def tokenize_mesh(vertices, faces, discrete_bins, tokenizer=None):
# vertices: [N, 3]
# faces: [M, 3]
# encode mesh into tokens using different tokenizers
if tokenizer is None:
# sort vertices
sort_inds = np.lexsort(vertices.T) # [N]
vertices = vertices[sort_inds]
# xyz to zyx
vertices = vertices[:, [2, 1, 0]] # [N, 3]
# re-index faces
inv_inds = np.argsort(sort_inds)
faces = inv_inds[faces]
# cyclically permute each face's 3 vertices, and place the lowest vertex first
start_inds = faces.argmin(axis=1) # [M]
all_inds = start_inds[:, None] + np.arange(3)[None, :] # [M, 3]
faces = np.concatenate([faces, faces[:, :2]], axis=1) # [M, 5], ABCAB
faces = np.take_along_axis(faces, all_inds, axis=1) # [M, 3]
# sort among faces (faces.sort(0) will break each face, so we have to sort as list)
faces = faces.tolist()
faces.sort()
faces = np.array(faces)
# flatten face to vertices
verts_per_face = vertices[faces] # [M, 3, 3]
# discretize
coords = ((verts_per_face + 1) * 0.5 * discrete_bins).clip(0, discrete_bins - 1).astype(np.int32)
# tokenize
tokens = coords.reshape(-1)
else:
# meto tokenizer (no need to sort)
tokens, _, _ = tokenizer.encode(vertices, faces)
# offset special tokens
tokens = tokens + 3 # [M]
return tokens
def detokenize_mesh(tokens, discrete_bins=None, tokenizer=None):
# tokens: [M]
tokens = tokens - 3
if tokenizer is None:
# after decoding, the tokens should be multiples of 9
if len(tokens) % 9 != 0:
print(f'[WARN] tokens len is {len(tokens)} % 9 != 0, trimming...')
tokens = tokens[:-(len(tokens) % 9)]
# all special tokens are treated as invalid triangles
invalid_mask = tokens < 0
# tokens = tokens[~invalid_mask] # just remove those bad tokens...
invalid_mask = invalid_mask.reshape(-1, 9).any(axis=1)
coords = tokens.reshape(-1, 3)
# renormalize to [-1, 1]
if discrete_bins is None:
vertices = coords / coords.max() * 2 - 1
else:
vertices = (coords + 0.5) / discrete_bins * 2 - 1
faces = np.arange(len(vertices)).reshape(-1, 3)
faces = faces[~invalid_mask]
vertices = vertices[:, [2, 1, 0]] # zyx to xyz
else:
# meto tokenizer
vertices, faces, face_type = tokenizer.decode(tokens)
# kiui.lo(vertices, faces)
# vertices and faces still need to be deduplicated and reindexed
return vertices, faces
class ObjaverseDataset(Dataset):
def __init__(self, opt: Options, training=True, tokenizer=None):
self.opt = opt
self.training = training
# data list
metadata = kiui.read_json('data_list/objaverse_wface.json')
self.items = []
for item in metadata:
if item[1] < opt.max_face_length: # allow dynamic adjustment
self.items.append(item[0])
self.obj_path = 's3://objaverse_ply/'
# gobj for image
self.gobj_path = 's3://gobjaverse/'
# load obj to gobj mapping
gobj_to_obj = kiui.read_json('data/gobjaverse_280k_index_to_objaverse.json')
self.obj_to_gobj = {v.replace('.glb', ''): k for k, v in gobj_to_obj.items()} # 000-xxx/bbb --> cc/dd
if self.training:
self.items = self.items[:-self.opt.testset_size]
else:
self.items = self.items[-self.opt.testset_size:]
# gobj vid candidates
self.vids = list(range(33, 40)) + list(range(12, 24))
# self.vids = list(range(28, 40)) + list(range(0, 24))
self.resolution = 512
# tokenizer
self.tokenizer = tokenizer
def __len__(self):
return len(self.items)
def __getitem__(self, idx):
results = {}
path = self.items[idx]
while True:
try:
### scale augmentation (not for image condition)
if self.opt.use_scale_aug and self.training and self.opt.cond_mode != 'image':
# if False:
bound = np.random.uniform(0.75, 0.95)
border_ratio = 0.2 + 0.95 - bound
else:
bound = 0.95
border_ratio = 0.2
### none condition
if self.opt.cond_mode == 'none':
cond = torch.zeros((1, 0), dtype=torch.float32) # dummy cond, we need the batch info during generation
### rotation augmentation
if self.training:
# image cond align with rendered data
if self.opt.cond_mode == 'image':
vid = np.random.choice(self.vids, 1)[0] # 7 front-ish views
if vid > 27:
azimuth = ((vid - 27) * 30 + 90) % 360 # [0-90, 270-360]
else:
azimuth = ((vid - 0) * 15 + 90) % 360
# point/uncond
else:
vid = 36 # no use
azimuth = np.random.choice([0, 30, 60, 90, 120, 150, 180, 210, 240, 270, 300, 330], 1)[0]
else:
vid = 36
azimuth = 0
### load image
if self.opt.cond_mode == 'image':
gobj_uid = self.obj_to_gobj[path]
tar_path = os.path.join(self.gobj_path, gobj_uid + '.tar')
uid_last = gobj_uid.split('/')[1]
image_path = os.path.join(uid_last, 'campos_512_v4', f"{vid:05d}/{vid:05d}.png")
with megfile.smart_open(tar_path, 'rb') as f:
with tarfile.open(fileobj=f, mode='r') as tar:
with tar.extractfile(image_path) as f:
image = np.frombuffer(f.read(), np.uint8)
image = cv2.imdecode(image, cv2.IMREAD_UNCHANGED).astype(np.float32) / 255 # [512, 512, 4] in [0, 1]
mask = image[..., 3:4] > 0.5 # [512, 512, 1]
# augment image (recenter)
image = recenter(image, mask, border_ratio=border_ratio)
image = image[..., :3] * image[..., 3:] + (1 - image[..., 3:]) # [512, 512, 3], to white bg
image = image[..., [2,1,0]] # bgr to rgb
cond = torch.from_numpy(image).permute(2, 0, 1).contiguous()
### load mesh
mesh_path = os.path.join(self.obj_path, path + '.ply')
v, f = load_mesh(mesh_path)
# already cleaned
# v, f = clean_mesh(v, f, min_f=0, min_d=0, remesh=False, verbose=False)
# face may exceed max_face_length, stats maybe inaccurate...
if f.shape[0] > self.opt.max_face_length:
raise ValueError(f"{f.shape[0]} exceeds face limit.")
# decimate mesh augmentation
if self.opt.use_decimate_aug and self.training:
if f.shape[0] >= 200 and random.random() < 0.5:
# at most decimate to 25% of original faces.
target = np.random.randint(max(100, f.shape[0] // 4), f.shape[0])
# print(f'[INFO] decimating {f.shape[0]} to {target} faces...')
v, f = decimate_mesh(v, f, target=target, verbose=False)
# rotate augmentation
if azimuth != 0:
roty = np.stack([
[np.cos(np.radians(-azimuth)), 0, np.sin(np.radians(-azimuth))],
[0, 1, 0],
[-np.sin(np.radians(-azimuth)), 0, np.cos(np.radians(-azimuth))],
])
v = v @ roty.T
# normalize after rotation in case of oob (augment scale)
v = normalize_mesh(v, bound=bound)
# point cloud cond
if self.opt.cond_mode == 'point':
mesh = trimesh.Trimesh(vertices=v, faces=f)
points = mesh.sample(self.opt.point_num)
# perturbation as augmentation
if self.training and random.random() < 0.5:
points += np.random.randn(*points.shape) * 0.01
cond = torch.from_numpy(points) # [N, 3]
coords = tokenize_mesh(v, f, self.opt.discrete_bins, self.tokenizer) # [M]
# rare cases that relative coordinate encoding is out-of-bound
if (coords - 3 < 0).any():
raise Exception(f'Invalid token range: {coords.min() - 3} - {coords.max() - 3}')
# truncate to max length instead of dropping
if coords.shape[0] > self.opt.max_seq_length:
# print(f'[WARN] {path}: coords.shape[0] > {self.opt.max_seq_length}, truncating...')
# coords = coords[:self.opt.max_seq_length]
raise ValueError(f"{coords.shape[0]} exceeds token limit.")
break
except Exception as e:
# print(f'[WARN] {path}: {e}')
# raise e # DANGEROUS, may cause infinite loop
idx = np.random.randint(0, len(self.items))
path = self.items[idx]
results['cond'] = cond # [3, H, W] for image, [N, 6] for point
results['coords'] = coords # [M]
results['len'] = coords.shape[0] # [1]
results['num_faces'] = f.shape[0] # [1]
results['azimuth'] = azimuth # [1]
results['path'] = path
# a custom collate_fn is needed for padding and masking
return results
class GithubDataset(Dataset):
def __init__(self, opt: Options, training=True, tokenizer=None):
self.opt = opt
self.training = training
assert opt.cond_mode != 'image', 'GithubDataset does not support image condition'
# load items
self.items = []
metadata = kiui.read_json('data/github_cleaned_wface.json') # 48k
for k, v in metadata.items():
if v < opt.max_face_length:
self.items.append(k)
metadata_fbx = kiui.read_json('data/github_fbx_wface.json') # 30K
for k, v in metadata_fbx.items():
if v < opt.max_face_length:
self.items.append(k)
self.obj_path = 's3://github_ply/'
# tokenizer
self.tokenizer = tokenizer
def __len__(self):
return len(self.items)
def __getitem__(self, idx):
results = {}
path = self.items[idx]
while True:
try:
# print(idx, path)
### scale augmentation (not for image condition)
if self.opt.use_scale_aug and self.training and self.opt.cond_mode != 'image':
# if False:
bound = np.random.uniform(0.75, 0.95)
else:
bound = 0.95
### none condition
if self.opt.cond_mode == 'none':
cond = torch.zeros((1, 0), dtype=torch.float32) # dummy cond, we need the batch info during generation
### rotation augmentation
if self.training:
azimuth = np.random.choice([0, 30, 60, 90, 120, 150, 180, 210, 240, 270, 300, 330], 1)[0]
else:
azimuth = 0
mesh_path = os.path.join(self.obj_path, path)
v, f = load_mesh(mesh_path)
# github data still need to be cleaned... otherwise may cause random segfault
v, f = clean_mesh(v, f, min_f=0, min_d=0, remesh=False, verbose=False)
# decimate mesh augmentation
if self.opt.use_decimate_aug and self.training:
if f.shape[0] >= 200 and random.random() < 0.5:
# at most decimate to 10% of original faces.
target = np.random.randint(max(100, f.shape[0] // 4), f.shape[0])
# print(f'[INFO] decimating {f.shape[0]} to {target} faces...')
v, f = decimate_mesh(v, f, target=target, verbose=False)
# rotate augmentation
if azimuth != 0:
roty = np.stack([
[np.cos(np.radians(azimuth)), 0, np.sin(np.radians(azimuth))],
[0, 1, 0],
[-np.sin(np.radians(azimuth)), 0, np.cos(np.radians(azimuth))],
])
v = v @ roty.T
# normalize after rotation in case of oob (augment scale)
v = normalize_mesh(v, bound=bound)
# point cloud cond
if self.opt.cond_mode == 'point':
mesh = trimesh.Trimesh(vertices=v, faces=f)
points = mesh.sample(self.opt.point_num)
# perturbation as augmentation
if self.training and random.random() < 0.5:
points += np.random.randn(*points.shape) * 0.01
cond = torch.from_numpy(points) # [N, 3]
coords = tokenize_mesh(v, f, self.opt.discrete_bins, self.tokenizer) # [M]
# rare cases that relative coordinate encoding is out-of-bound
if (coords - 3 < 0).any():
raise Exception(f'Invalid token range: {coords.min() - 3} - {coords.max() - 3}')
# truncate to max length instead of dropping
if coords.shape[0] > self.opt.max_seq_length:
coords = coords[:self.opt.max_seq_length]
break
except Exception as e:
print(f'[WARN] {path}: {e}')
# raise e # DANGEROUS, may cause infinite loop
idx = np.random.randint(0, len(self.items))
path = self.items[idx]
results['cond'] = cond # [3, H, W] for image, [N, 6] for point
results['coords'] = coords # [M]
results['len'] = coords.shape[0] # [1]
results['num_faces'] = f.shape[0] # [1]
results['azimuth'] = azimuth # [1]
results['idx'] = idx
results['path'] = path
# a custom collate_fn is needed for padding and masking
return results
class MixedDataset(Dataset):
def __init__(self, opt: Options, training=True, tokenizer=None):
self.opt = opt
self.training = training
assert self.training, 'MixedDataset only supports training mode'
assert opt.cond_mode != 'image', 'MixedDataset does not support image condition'
self.datasets = [
ObjaverseDataset(opt, training=training, tokenizer=tokenizer),
GithubDataset(opt, training=training, tokenizer=tokenizer),
]
self.lens = [len(dataset) for dataset in self.datasets]
# print(f'[INFO] MixedDataset: {self.lens}')
# tokenizer
self.tokenizer = tokenizer
def __len__(self):
return sum(self.lens)
def __getitem__(self, idx):
for i, dataset in enumerate(self.datasets):
if idx < len(dataset):
return dataset[idx]
else:
idx -= len(dataset)
raise Exception('Invalid index')
def collate_fn(batch, opt: Options):
# conds
conds = [item['cond'] for item in batch]
num_faces = [item['num_faces'] for item in batch]
azimuths = [item['azimuth'] for item in batch]
# get max len of this batch
max_len = max([item['len'] for item in batch])
max_len = min(max_len, opt.max_seq_length)
# num cond tokens (may add face conds)
num_cond_tokens = opt.num_cond_tokens
# pad or truncate to max_len, and prepare masks
tokens = []
labels = []
masks = []
num_tokens = []
for item in batch:
if max_len >= item['len']:
pad_len = max_len - item['len']
tokens.append(np.concatenate([
# COND tokens will be inserted here later
np.full((1,), opt.bos_token_id), # BOS
item['coords'], # mesh tokens
np.full((1,), opt.eos_token_id), # EOS
np.full((pad_len,), opt.pad_token_id), # padding
], axis=0)) # [1+M+1]
labels.append(np.concatenate([
np.full((num_cond_tokens + 1), -100), # condition & BOS don't need to be supervised
item['coords'], # tokens to be supervised
np.full((1,), opt.eos_token_id), # EOS to be supervised
np.full((pad_len,), -100), # padding
], axis=0)) # [C+1+M+1]
masks.append(np.concatenate([
np.ones(num_cond_tokens + 1 + item['len'] + 1),
np.zeros(pad_len)
], axis=0)) # [C+1+M+1]
num_tokens.append(num_cond_tokens + 1 + item['len'] + 1)
else:
tokens.append(np.concatenate([
# COND tokens will be inserted here later
np.full((1,), opt.bos_token_id), # BOS
item['coords'][:max_len], # mesh tokens
# no EOS as it's truncated
], axis=0))
labels.append(np.concatenate([
np.full((num_cond_tokens + 1), -100), # condition & BOS don't need to be supervised
item['coords'][:max_len], # tokens to be supervised
# no EOS as it's truncated
], axis=0))
masks.append(np.ones(num_cond_tokens + 1 + max_len))
num_tokens.append(num_cond_tokens + 1 + max_len)
results = {}
results['conds'] = torch.from_numpy(np.stack(conds, axis=0)).float()
results['num_faces'] = torch.from_numpy(np.stack(num_faces, axis=0)).long()
results['num_tokens'] = torch.from_numpy(np.stack(num_tokens, axis=0)).long()
results['azimuths'] = torch.from_numpy(np.stack(azimuths, axis=0)).long()
results['tokens'] = torch.from_numpy(np.stack(tokens, axis=0)).long()
results['labels'] = torch.from_numpy(np.stack(labels, axis=0)).long()
results['masks'] = torch.from_numpy(np.stack(masks, axis=0)).bool()
results['paths'] = [item['path'] for item in batch]
return results
if __name__ == "__main__":
import tyro
from core.options import AllConfigs
from functools import partial
opt = tyro.cli(AllConfigs)
kiui.seed_everything(opt.seed)
# tokenizer
tokenizer, _ = get_tokenizer(opt)
dataset = ObjaverseDataset(opt, training=True, tokenizer=tokenizer)
print(len(dataset))
dataloader = DataLoader(
dataset,
batch_size=2,
shuffle=True,
collate_fn=partial(collate_fn, opt=opt),
)
for i in range(5):
results = next(iter(dataloader))
kiui.lo(results['conds'], results['tokens'], results['azimuths'])
# restore mesh
for b in range(len(results['masks'])):
masks = results['masks'][b].numpy()
tokens = results['labels'][b].numpy()[masks][1+opt.num_cond_tokens:-1]
# write obj using the original order to check face orientation
vertices, faces = detokenize_mesh(tokens, opt.discrete_bins, tokenizer=tokenizer)
with open(f'{i}_{b}.obj', 'w') as f:
for v in vertices:
f.write(f'v {v[0]:.6f} {v[1]:.6f} {v[2]:.6f}\n')
for face in faces:
f.write(f'f {" ".join([str(v+1) for v in face])}\n')
# kiui.lo(tokens, faces)
print(results['paths'][b])
print(f'[INFO] tokens: {tokens.shape[0]}, faces: {faces.shape[0]}, ratio={100 * tokens.shape[0] / (9 * faces.shape[0]):.2f}%')
if opt.cond_mode == 'image':
kiui.write_image(f'{i}_{b}.png', results['conds'][b].numpy().transpose(1, 2, 0))