0xZohar commited on
Commit
398283d
·
verified ·
1 Parent(s): c18faa3

Upload code/cube3d/training/engine.py

Browse files
Files changed (1) hide show
  1. code/cube3d/training/engine.py +1120 -0
code/cube3d/training/engine.py ADDED
@@ -0,0 +1,1120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Union, Optional, Tuple
2
+
3
+ import torch
4
+ import torch.nn.functional as F
5
+ from torch.optim.lr_scheduler import CosineAnnealingLR
6
+ from peft import LoraConfig, get_peft_model, TaskType
7
+ from tqdm import tqdm
8
+ from transformers import CLIPTextModelWithProjection, CLIPTokenizerFast
9
+
10
+ from cube3d.inference.logits_postprocesses import process_logits
11
+ from cube3d.inference.utils import load_config, load_model_weights, parse_structured, load_model_weights_adaption
12
+ from cube3d.model.autoencoder.one_d_autoencoder import OneDAutoEncoder
13
+ from cube3d.model.gpt.dual_stream_roformer import DualStreamRoformer
14
+ from cube3d.model.transformers.cache import Cache
15
+ from cube3d.model.transformers.rope import precompute_freqs_cis
16
+ from cube3d.training.utils import positional_encoding
17
+ from cube3d.config import HF_CACHE_DIR
18
+
19
+ class Engine:
20
+ def __init__(
21
+ self,
22
+ config_path: str,
23
+ gpt_ckpt_path: str,
24
+ shape_ckpt_path: str,
25
+ save_gpt_ckpt_path: str,
26
+ device: torch.device,
27
+ mode: str
28
+ ):
29
+ """
30
+ Initializes the inference engine with the given configuration and checkpoint paths.
31
+ Args:
32
+ config_path (str): Path to the configuration file.
33
+ gpt_ckpt_path (str): Path to the GPT model checkpoint file.
34
+ shape_ckpt_path (str): Path to the shape model checkpoint file.
35
+ device (torch.device): The device to run the models on (e.g., 'cpu' or 'cuda').
36
+ Attributes:
37
+ cfg (dict): Loaded configuration from the config file.
38
+ device (torch.device): The device to run the models on.
39
+ gpt_model (DualStreamRoformer): The GPT model initialized and loaded with weights.
40
+ shape_model (OneDAutoEncoder): The shape model initialized and loaded with weights.
41
+ text_model (CLIPTextModelWithProjection): The text model initialized from a pretrained model.
42
+ text_tokenizer (CLIPTokenizerFast): The tokenizer for the text model.
43
+ max_new_tokens (int): Maximum number of new tokens for the shape model.
44
+ min_id (int): Minimum ID for the shape model codes.
45
+ max_id (int): Maximum ID for the shape model codes.
46
+ """
47
+
48
+ self.cfg = load_config(config_path)
49
+ self.device = device
50
+
51
+ self.gpt_model = DualStreamRoformer(
52
+ parse_structured(DualStreamRoformer.Config, self.cfg.gpt_model)
53
+ )
54
+
55
+ #------training load
56
+ if mode=='test':
57
+ load_model_weights(
58
+ self.gpt_model,
59
+ save_gpt_ckpt_path,
60
+ )
61
+ #-------traing load
62
+
63
+
64
+
65
+ self.gpt_model = self.gpt_model.to(self.device)
66
+
67
+ self.shape_model = OneDAutoEncoder(
68
+ parse_structured(OneDAutoEncoder.Config, self.cfg.shape_model)
69
+ )
70
+ load_model_weights(
71
+ self.shape_model,
72
+ shape_ckpt_path,
73
+ )
74
+ self.shape_model = self.shape_model.eval().to(self.device)
75
+
76
+ # copy vq codebook to gpt
77
+ with torch.no_grad():
78
+ codebook = self.shape_model.bottleneck.block.get_codebook()
79
+ codebook = self.gpt_model.shape_proj(codebook).detach()
80
+ self.gpt_model.transformer.wte.weight.data[: codebook.shape[0]] = codebook
81
+ #import ipdb; ipdb.set_trace()
82
+ self.text_model = CLIPTextModelWithProjection.from_pretrained(
83
+ self.cfg.text_model_pretrained_model_name_or_path,
84
+ force_download=False,
85
+ device_map=self.device,
86
+ cache_dir=HF_CACHE_DIR,
87
+ ).eval()
88
+ print("------text_model device---------", self.text_model.device)
89
+ self.text_tokenizer = CLIPTokenizerFast.from_pretrained(
90
+ self.cfg.text_model_pretrained_model_name_or_path,
91
+ cache_dir=HF_CACHE_DIR,
92
+ #force_download=False,
93
+ )
94
+
95
+ self.max_new_tokens = self.shape_model.cfg.num_encoder_latents
96
+ self.min_id = 0
97
+ self.max_id = self.shape_model.cfg.num_codes
98
+ self.max_token_length = 110 #bottom #310 #car
99
+
100
+ self.x_prembeds = None
101
+ self.x_prembeds = None
102
+ self.x_prembeds = None
103
+ @torch.inference_mode()
104
+ def prepare_conditions_with_bbox(
105
+ self,
106
+ cond: torch.Tensor,
107
+ bounding_box_tensor: Optional[torch.Tensor] = None,
108
+ ):
109
+ """
110
+ Prepares condition embeddings by incorporating bounding box information.
111
+
112
+ Concatenates bounding box embeddings to the existing condition tensor if the model
113
+ supports bounding box projection. If no bounding box is provided, uses zero padding.
114
+
115
+ Args:
116
+ cond (torch.Tensor): The input condition embeddings tensor of shape (B, seq_len, dim).
117
+ bounding_box_xyz (Optional[torch.Tensor], optional): The size of the bounding box
118
+ as (x, y, z) dimensions represented as a tensor. If None, uses zero padding for
119
+ bounding box embeddings.
120
+
121
+ Returns:
122
+ torch.Tensor: The condition tensor with bounding box embeddings concatenated along
123
+ the sequence dimension if bounding box projection is supported, otherwise
124
+ returns the original condition tensor unchanged.
125
+ """
126
+ if not hasattr(self.gpt_model, "bbox_proj"):
127
+ return cond
128
+
129
+ if bounding_box_tensor is None:
130
+ B = cond.shape[0]
131
+ bounding_box_tensor = torch.zeros((B, 3), dtype=cond.dtype, device=self.device)
132
+
133
+ bbox_emb = self.gpt_model.bbox_proj(bounding_box_tensor).unsqueeze(dim=1).expand(cond.shape[0], -1, -1)
134
+
135
+ cond = torch.cat([cond, bbox_emb], dim=1)
136
+ return cond
137
+
138
+ @torch.inference_mode()
139
+ def prepare_conditions_with_bboxs(
140
+ self,
141
+ cond: torch.Tensor,
142
+ bounding_box_tensor: Optional[torch.Tensor] = None,
143
+ ):
144
+ """
145
+ Prepares condition embeddings by incorporating bounding box information.
146
+
147
+ Concatenates bounding box embeddings to the existing condition tensor if the model
148
+ supports bounding box projection. If no bounding box is provided, uses zero padding.
149
+
150
+ Args:
151
+ cond (torch.Tensor): The input condition embeddings tensor of shape (B, seq_len, dim).
152
+ bounding_box_xyz (Optional[torch.Tensor], optional): The size of the bounding box
153
+ as (x, y, z) dimensions represented as a tensor. If None, uses zero padding for
154
+ bounding box embeddings.
155
+
156
+ Returns:
157
+ torch.Tensor: The condition tensor with bounding box embeddings concatenated along
158
+ the sequence dimension if bounding box projection is supported, otherwise
159
+ returns the original condition tensor unchanged.
160
+ """
161
+ if not hasattr(self.gpt_model, "bbox_proj"):
162
+ return cond
163
+
164
+ if bounding_box_tensor is None:
165
+ B = cond.shape[0]
166
+ bounding_box_tensor = torch.zeros((B, 3), dtype=cond.dtype, device=self.device)
167
+
168
+ bbox_emb = self.gpt_model.bbox_proj(bounding_box_tensor).unsqueeze(dim=1).expand(cond.shape[0], -1, -1)
169
+
170
+ cond = torch.cat([cond, bbox_emb], dim=1)
171
+ return cond
172
+
173
+ @torch.inference_mode()
174
+ def prepare_inputs(
175
+ self,
176
+ prompts: list[str],
177
+ guidance_scale: float,
178
+ bounding_box_xyz: Optional[Tuple[float]] = None,
179
+ ):
180
+ """
181
+ Prepares the input embeddings for the model based on the provided prompts and guidance scale.
182
+ Args:
183
+ prompts (list[str]): A list of prompt strings to be encoded.
184
+ guidance_scale (float): A scaling factor for guidance. If greater than 0.0, additional processing is applied.
185
+ bounding_box_xyz (Optional[Tuple[float]], optional): The size of the bounding box for generation
186
+ as (x, y, z) dimensions. Each value must be between 0 and 1.925. If None,
187
+ uses default bounding box sizing.
188
+ Returns:
189
+ tuple: A tuple containing:
190
+ - embed (torch.Tensor): The encoded input embeddings.
191
+ - cond (torch.Tensor): The condition embeddings, which may include unconditional embeddings if guidance_scale is greater than 0.0.
192
+ """
193
+ prompt_embeds = self.run_clip(prompts) # [1, 77, 1536]
194
+
195
+ with torch.autocast(self.device.type, dtype=torch.bfloat16):
196
+ embed = self.encode_input(prompt_embeds, self.gpt_model.shape_bos_id) # (prompt_embeds, 16384) -> [1, 1, 1536], just embedding shape_bos_id
197
+ #bos embed
198
+
199
+ if bounding_box_xyz is not None:
200
+ cond_bbox = torch.atleast_2d(torch.tensor(bounding_box_xyz)).to(self.device)
201
+ uncond_bbox = torch.zeros_like(cond_bbox).to(self.device)
202
+ else:
203
+ cond_bbox = None
204
+ uncond_bbox = None
205
+
206
+ cond = self.prepare_conditions_with_bbox(prompt_embeds, cond_bbox)
207
+ if guidance_scale > 0.0:
208
+ embed = torch.cat([embed, embed], dim=0) #why cat ? for chunk=2
209
+ uncond_embeds = self.run_clip([""] * len(prompts))
210
+ uncond = self.prepare_conditions_with_bbox(uncond_embeds, uncond_bbox)
211
+ cond = torch.cat([cond, uncond], dim=0)
212
+
213
+ return embed, cond
214
+
215
+ @torch.inference_mode()
216
+ def canonical_inputs(
217
+ self,
218
+ input_ids: torch.Tensor,
219
+ mask: torch.Tensor,
220
+ ):
221
+ """
222
+ Prepares the input embeddings for the model based on the provided prompts and guidance scale.
223
+ Args:
224
+ prompts (list[str]): A list of prompt strings to be encoded.
225
+ guidance_scale (float): A scaling factor for guidance. If greater than 0.0, additional processing is applied.
226
+ bounding_box_xyz (Optional[Tuple[float]], optional): The size of the bounding box for generation
227
+ as (x, y, z) dimensions. Each value must be between 0 and 1.925. If None,
228
+ uses default bounding box sizing.
229
+ Returns:
230
+ tuple: A tuple containing:
231
+ - embed (torch.Tensor): The encoded input embeddings.
232
+ - cond (torch.Tensor): The condition embeddings, which may include unconditional embeddings if guidance_scale is greater than 0.0.
233
+ """
234
+ # import ipdb; ipdb.set_trace()
235
+ x_num = 213
236
+ y_num = 217
237
+ z_num = 529
238
+ rot_num = 24
239
+ xyz = x_num + y_num + z_num + rot_num
240
+ #mask_input = input_ids[mask==1]
241
+ #cut_idx = (mask == False)[:, :, 0].int().argmax(dim=1)
242
+ input_ids[:, :xyz] = 0
243
+ input_ids[:, 0] = 1
244
+ return input_ids
245
+
246
+ @torch.inference_mode()
247
+ def run_clip(self, text_inputs):
248
+ """
249
+ Processes the given text inputs using a text tokenizer and a text model, and returns the encoded text embeddings.
250
+ Args:
251
+ text_inputs (str or List[str]): The input text or list of texts to be processed.
252
+ Returns:
253
+ torch.Tensor: The encoded text embeddings.
254
+ """
255
+ #import ipdb; ipdb.set_trace()
256
+ text_inputs = self.text_tokenizer(
257
+ text_inputs,
258
+ max_length=self.text_tokenizer.model_max_length,
259
+ padding="max_length",
260
+ truncation=True,
261
+ return_tensors="pt",
262
+ )
263
+ with torch.no_grad():
264
+ text_inputs = {k: v.to(self.device) for k, v in text_inputs.items()}
265
+ # use full precision for text encoder
266
+ with torch.autocast(device_type=self.device.type, enabled=False):
267
+ encoded = self.text_model(**text_inputs)
268
+ if self.gpt_model.cfg.use_pooled_text_embed:
269
+ embed = encoded.text_embeds.unsqueeze(1) # [bs, 1, 512]
270
+ else:
271
+ embed = encoded.last_hidden_state # [bs, 77, 512]
272
+ embed = self.gpt_model.encode_text(embed)
273
+
274
+ return embed
275
+
276
+ @torch.inference_mode()
277
+ def encode_input(self, inputs: torch.Tensor, bos: int):
278
+ """
279
+ Encodes the beginning of sequence (BOS) token for the given input tensor.
280
+ Args:
281
+ inputs (torch.Tensor): The input tensor containing sequences.
282
+ bos (int): The beginning of sequence token ID.
283
+ Returns:
284
+ torch.Tensor: The encoded BOS token embeddings.
285
+ """
286
+
287
+ b = inputs.shape[0]
288
+ bos_embed = self.gpt_model.encode_token(
289
+ torch.full(
290
+ (b, 1),
291
+ fill_value=bos,
292
+ dtype=torch.long,
293
+ device=self.device,
294
+ )
295
+ )
296
+ return bos_embed
297
+
298
+ @torch.inference_mode()
299
+ def run_gpt(
300
+ self,
301
+ prompts: list[str],
302
+ use_kv_cache: bool,
303
+ guidance_scale: float = 3.0,
304
+ top_p: float = None,
305
+ bounding_box_xyz: Optional[Tuple[float]] = None,
306
+ ):
307
+ """
308
+ Generates text using a GPT model based on the provided prompts.
309
+ Args:
310
+ prompts (list[str]): A list of input prompts to generate text from.
311
+ use_kv_cache (bool): Whether to use key-value caching for faster generation.
312
+ guidance_scale (float, optional): The scale for guidance during generation. Default is 3.0.
313
+ top_p (float, optional): The cumulative probability threshold for nucleus sampling.
314
+ If None, argmax selection is performed (deterministic generation). Otherwise, smallest set of tokens with cumulative probability ≥ top_p are kept (stochastic generation).
315
+ bounding_box_xyz (Optional[Tuple[float]], optional): The size of the bounding box for generation
316
+ as (x, y, z) dimensions. Each value must be between 0 and 1.925. If None,
317
+ uses default bounding box sizing.
318
+ Returns:
319
+ torch.Tensor: A tensor containing the generated token IDs.
320
+ """
321
+ embed, cond = self.prepare_inputs(prompts, guidance_scale, bounding_box_xyz) #embed: bos
322
+
323
+ output_ids = []
324
+
325
+ batch_size, input_seq_len, dim = embed.shape
326
+ max_seq_len = input_seq_len + self.max_new_tokens
327
+ embed_buffer = torch.zeros(
328
+ (batch_size, max_seq_len, dim), dtype=embed.dtype, device=embed.device
329
+ )
330
+ embed_buffer[:, :input_seq_len, :].copy_(embed)
331
+ cond_len = cond.shape[1]
332
+ kv_cache = None
333
+ if use_kv_cache:
334
+ # import ipdb; ipdb.set_trace()
335
+ kv_cache = self.gpt_model.init_kv_cache(
336
+ batch_size,
337
+ cond_len,
338
+ self.max_new_tokens + 1, # +1 for the BOS token
339
+ torch.bfloat16,
340
+ embed.device,
341
+ )
342
+
343
+ # import ipdb; ipdb.set_trace()
344
+ with torch.autocast(self.device.type, dtype=torch.bfloat16):
345
+ for i in tqdm(range(self.max_new_tokens), desc=f"generating"):
346
+ curr_pos_id = torch.tensor([i], dtype=torch.long, device=embed.device)
347
+ logits = self.gpt_model(
348
+ embed_buffer,
349
+ cond,
350
+ kv_cache=kv_cache,
351
+ curr_pos_id=curr_pos_id if use_kv_cache else None,
352
+ decode=(i > 0) if use_kv_cache else False,
353
+ )
354
+ if use_kv_cache:
355
+ logits = logits[:, 0, ...]
356
+ else:
357
+ logits = logits[:, i, ...]
358
+
359
+ # import ipdb; ipdb.set_trace()
360
+ logits = logits[..., self.min_id : self.max_id]
361
+
362
+ if guidance_scale > 0.0:
363
+ logits, uncond_logits = logits.float().chunk(2, dim=0)
364
+ gamma = (
365
+ guidance_scale * (self.max_new_tokens - i) / self.max_new_tokens
366
+ )
367
+ logits = (1 + gamma) * logits - gamma * uncond_logits
368
+ next_id = process_logits(
369
+ logits,
370
+ top_p=top_p,
371
+ )
372
+ output_ids.append(next_id)
373
+ next_embed = self.gpt_model.encode_token(next_id)
374
+ if guidance_scale > 0.0:
375
+ next_embed = torch.cat([next_embed, next_embed], dim=0)
376
+ embed_buffer[:, i + input_seq_len, :].copy_(next_embed.squeeze(1))
377
+ # import ipdb; ipdb.set_trace()
378
+ print(logits)
379
+
380
+ return torch.cat(output_ids, dim=1)
381
+
382
+ @torch.inference_mode()
383
+ def run_shape_decode(
384
+ self,
385
+ output_ids: torch.Tensor,
386
+ resolution_base: float = 8.0,
387
+ chunk_size: int = 100_000,
388
+ ):
389
+ """
390
+ Decodes the shape from the given output IDs and extracts the geometry.
391
+ Args:
392
+ output_ids (torch.Tensor): The tensor containing the output IDs.
393
+ resolution_base (float, optional): The base resolution for geometry extraction. Defaults to 8.43.
394
+ chunk_size (int, optional): The chunk size for processing. Defaults to 100,000.
395
+ Returns:
396
+ tuple: A tuple containing the vertices and faces of the mesh.
397
+ """
398
+ shape_ids = (
399
+ output_ids[:, : self.shape_model.cfg.num_encoder_latents, ...]
400
+ .clamp_(0, self.shape_model.cfg.num_codes - 1)
401
+ .view(-1, self.shape_model.cfg.num_encoder_latents)
402
+ )
403
+ latents = self.shape_model.decode_indices(shape_ids) #where loss?
404
+
405
+ mesh_v_f, _ = self.shape_model.extract_geometry(
406
+ latents,
407
+ resolution_base=resolution_base,
408
+ chunk_size=chunk_size,
409
+ use_warp=True,
410
+ )
411
+ return mesh_v_f
412
+
413
+ @torch.inference_mode()
414
+ def t2s(
415
+ self,
416
+ prompts: list[str],
417
+ use_kv_cache: bool,
418
+ guidance_scale: float = 3.0,
419
+ resolution_base: float = 8.0,
420
+ chunk_size: int = 100_000,
421
+ top_p: float = None,
422
+ bounding_box_xyz: Optional[Tuple[float]] = None,
423
+ ):
424
+ """
425
+ Generates a 3D mesh from text prompts using a GPT model and shape decoder.
426
+ Args:
427
+ prompts (list[str]): A list of text prompts to guide the generation.
428
+ use_kv_cache (bool): Whether to use key-value caching for the GPT model.
429
+ guidance_scale (float, optional): The scale of guidance for the GPT model. Default is 3.0.
430
+ resolution_base (float, optional): The base resolution for the shape decoder. Default is 8.0.
431
+ chunk_size (int, optional): The chunk size for processing the shape decoding. Default is 100,000.
432
+ top_p (float, optional): The cumulative probability threshold for nucleus sampling.
433
+ If None, argmax selection is performed (deterministic generation). Otherwise, smallest set of tokens with cumulative probability ≥ top_p are kept (stochastic generation).
434
+ bounding_box_xyz (Tuple[float] | None, optional): The size of the bounding box for the generated mesh
435
+ as (x, y, z) dimensions. Each value must be between 0 and 1.925. If None,
436
+ uses default bounding box sizing.
437
+ Returns:
438
+ mesh_v_f: The generated 3D mesh vertices and faces.
439
+ """
440
+ output_ids = self.run_gpt(
441
+ prompts, use_kv_cache, guidance_scale, top_p, bounding_box_xyz
442
+ )
443
+ with torch.autocast(self.device.type, dtype=torch.bfloat16):
444
+ mesh_v_f = self.run_shape_decode(output_ids, resolution_base, chunk_size)
445
+ return mesh_v_f
446
+
447
+
448
+ class EngineFast(Engine):
449
+ def __init__(
450
+ self,
451
+ config_path: str,
452
+ gpt_ckpt_path: str,
453
+ shape_ckpt_path: str,
454
+ save_gpt_ckpt_path: str,
455
+ device: torch.device,
456
+ mode: str
457
+ ):
458
+ """
459
+ Initializes the inference engine with the given configuration and checkpoint paths.
460
+ Args:
461
+ config_path (str): Path to the configuration file.
462
+ gpt_ckpt_path (str): Path to the GPT checkpoint file.
463
+ shape_ckpt_path (str): Path to the shape checkpoint file.
464
+ device (torch.device): The device to run the inference on (e.g., CPU or CUDA).
465
+ """
466
+
467
+ assert (
468
+ device.type == "cuda"
469
+ ), "EngineFast is only supported on cuda devices, please use Engine on non-cuda devices"
470
+
471
+ super().__init__(config_path, gpt_ckpt_path, shape_ckpt_path, save_gpt_ckpt_path, device, mode)
472
+
473
+ # CUDA Graph params
474
+ self.graph = torch.cuda.CUDAGraph()
475
+ self.embed_buffer = torch.Tensor()
476
+ self.cond_buffer = torch.Tensor()
477
+ self.logits_buffer = torch.Tensor()
478
+ self.curr_pos_id = torch.tensor([0], dtype=torch.long, device=self.device)
479
+ self.kv_cache: list[Cache] = []
480
+
481
+ #self._warmup_and_capture_graph()
482
+
483
+
484
+ def _warmup_and_capture_graph(self):
485
+ """
486
+ Warms up the model by running a series of forward passes and captures the CUDA graph for efficient execution.
487
+ This method performs the following steps:
488
+ 1. Prepares the input embeddings and conditions using a warmup prompt.
489
+ 2. Initializes buffers for embeddings and conditions.
490
+ 3. Initializes the key-value cache for the GPT model.
491
+ 4. Runs a series of warmup passes to prefill the model and generate logits.
492
+ 5. Captures the CUDA graph for the model's forward pass to optimize future executions.
493
+ """
494
+
495
+ warmup_prompt = "A cube"
496
+ embed, cond = self.prepare_inputs([warmup_prompt], guidance_scale=3.0)
497
+
498
+ batch_size, input_seq_len, dim = embed.shape
499
+ max_seq_len = input_seq_len + self.max_new_tokens
500
+ self.embed_buffer = torch.zeros(
501
+ (batch_size, max_seq_len, dim), dtype=embed.dtype, device=self.device
502
+ )
503
+ self.embed_buffer[:, :input_seq_len, :].copy_(embed)
504
+
505
+ self.cond_buffer = torch.empty_like(cond)
506
+ self.cond_buffer.copy_(cond)
507
+ cond_len = self.cond_buffer.shape[1]
508
+
509
+ # Initialize kv_cache for the first time
510
+ self.kv_cache = self.gpt_model.init_kv_cache(
511
+ batch_size,
512
+ cond_len,
513
+ self.max_new_tokens + 1, # +1 for the BOS token
514
+ torch.bfloat16,
515
+ self.device,
516
+ )
517
+
518
+ num_warmup_passes = 10
519
+
520
+ with torch.autocast(self.device.type, dtype=torch.bfloat16):
521
+ self._set_curr_pos_id(0)
522
+ _ = self._prefill_and_return_logits()
523
+
524
+ for x in range(1, num_warmup_passes):
525
+ self._set_curr_pos_id(x)
526
+ self.logits_buffer = self.gpt_model(
527
+ embed=self.embed_buffer,
528
+ cond=self.cond_buffer,
529
+ kv_cache=self.kv_cache,
530
+ curr_pos_id=self.curr_pos_id,
531
+ #decode=True,
532
+ decode=False
533
+ )
534
+
535
+ side_stream = torch.cuda.Stream(device=self.device)
536
+ with torch.cuda.graph(self.graph, stream=side_stream):
537
+ with torch.autocast(self.device.type, dtype=torch.bfloat16):
538
+ self.logits_buffer = self.gpt_model(
539
+ embed=self.embed_buffer,
540
+ cond=self.cond_buffer,
541
+ kv_cache=self.kv_cache,
542
+ curr_pos_id=self.curr_pos_id,
543
+ decode=True,
544
+ )
545
+
546
+ def _reset_kv_cache(self):
547
+ """
548
+ Resets the key-value cache by setting all key and value states to zero.
549
+ This method iterates through each cache in the `kv_cache` attribute and
550
+ calls the `zero_()` method on both `key_states` and `value_states` to
551
+ reset them to their initial state.
552
+ """
553
+
554
+ for cache in self.kv_cache:
555
+ cache.key_states.zero_()
556
+ cache.value_states.zero_()
557
+
558
+ def _prefill_and_return_logits(self) -> torch.Tensor:
559
+ """
560
+ Prefills the model's key-value cache and returns the logits.
561
+ This method resets the key-value cache and then performs a forward pass
562
+ through the GPT model in eager mode to prefill the logits.
563
+ Returns:
564
+ torch.Tensor: The prefilled logits tensor with the first dimension removed.
565
+ """
566
+
567
+ self._reset_kv_cache()
568
+
569
+ # Prefill is always eager
570
+ prefill_logits = self.gpt_model(
571
+ embed=self.embed_buffer,
572
+ cond=self.cond_buffer,
573
+ kv_cache=self.kv_cache,
574
+ curr_pos_id=self.curr_pos_id,
575
+ decode=False,
576
+ )
577
+
578
+ return prefill_logits[:, 0, ...]
579
+
580
+ def _set_curr_pos_id(self, pos: int):
581
+ """
582
+ Set the current position ID.
583
+ This method updates the `curr_pos_id` attribute with the given position.
584
+ Args:
585
+ pos (int): The position ID to set.
586
+ """
587
+
588
+ self.curr_pos_id.copy_(
589
+ torch.tensor([pos], dtype=torch.long, device=self.device)
590
+ )
591
+
592
+ def run_gpt(
593
+ self,
594
+ prompts: list[str],
595
+ use_kv_cache: bool,
596
+ guidance_scale: float = 3.0,
597
+ top_p: float = None,
598
+ bounding_box_xyz: Optional[Tuple[float]] = None,
599
+ ):
600
+ """
601
+ Runs the GPT model to generate text based on the provided prompts.
602
+ Args:
603
+ prompts (list[str]): A list of input prompts for the GPT model. Only a single prompt is supported.
604
+ use_kv_cache (bool): Flag indicating whether to use key-value caching. (Currently not used)
605
+ guidance_scale (float, optional): The scale factor for guidance. Default is 3.0.
606
+ top_p (float, optional): The cumulative probability threshold for nucleus sampling.
607
+ If None, argmax selection is performed. Otherwise, smallest
608
+ set of tokens with cumulative probability ≥ top_p are kept.
609
+ bounding_box_xyz (Tuple[float] | None, optional): The size of the bounding box for the generated mesh
610
+ as (x, y, z) dimensions. Each value must be between 0 and 1.925. If None,
611
+ uses default bounding box sizing.
612
+ Returns:
613
+ torch.Tensor: A tensor containing the generated output token IDs.
614
+ Raises:
615
+ AssertionError: If the batch size is greater than 1.
616
+ """
617
+
618
+ embed, cond = self.prepare_inputs(prompts, guidance_scale, bounding_box_xyz)
619
+ assert len(prompts) == 1, "batch size > 1 not support for EngineFast"
620
+
621
+ batch_size, input_seq_len, _ = embed.shape
622
+ self.embed_buffer.zero_()
623
+ self.embed_buffer[:, :input_seq_len, :].copy_(embed)
624
+
625
+ assert self.cond_buffer.shape == cond.shape
626
+ self.cond_buffer.copy_(cond)
627
+
628
+ output_ids = torch.zeros(
629
+ (batch_size // 2, self.max_new_tokens), dtype=torch.int, device=self.device
630
+ )
631
+
632
+ with torch.autocast(self.device.type, dtype=torch.bfloat16):
633
+ self._set_curr_pos_id(0)
634
+
635
+ logits = self._prefill_and_return_logits()
636
+ # import ipdb; ipdb.set_trace()
637
+ logits = logits[..., self.min_id : self.max_id] #[2, 16387]
638
+ if guidance_scale > 0.0:
639
+ logits, uncond_logits = logits.float().chunk(2, dim=0)
640
+ gamma = guidance_scale
641
+ logits = (1 + gamma) * logits - gamma * uncond_logits
642
+
643
+ next_id = process_logits(logits, top_p=top_p)
644
+
645
+ output_ids[:, 0] = next_id.squeeze()
646
+ next_embed = self.gpt_model.encode_token(next_id)
647
+ next_embed = next_embed.repeat(2, 1, 1)
648
+ self.embed_buffer[:, input_seq_len, :].copy_(next_embed.squeeze(1))
649
+
650
+ for i in tqdm(range(1, self.max_new_tokens), desc=f"generating"):
651
+ self._set_curr_pos_id(i)
652
+ self.graph.replay()
653
+
654
+ logits = self.logits_buffer[:, 0, ...]
655
+
656
+ logits = logits[..., self.min_id : self.max_id]
657
+ if guidance_scale > 0.0:
658
+ logits, uncond_logits = logits.float().chunk(2, dim=0)
659
+ gamma = (
660
+ guidance_scale * (self.max_new_tokens - i) / self.max_new_tokens
661
+ )
662
+ logits = (1 + gamma) * logits - gamma * uncond_logits
663
+ next_id = process_logits(logits, top_p=top_p)
664
+
665
+ output_ids[:, i] = next_id.squeeze()
666
+ next_embed = self.gpt_model.encode_token(next_id)
667
+ next_embed = next_embed.repeat(2, 1, 1)
668
+ self.embed_buffer[:, i + input_seq_len, :].copy_(next_embed.squeeze(1))
669
+ print(logits)
670
+
671
+ return output_ids
672
+
673
+ def pad_id_and_attn(self, inputs_ids, attention_mask): # same
674
+ # reserve one space for `bos`, the pad_id will be replaced to `bos`
675
+ place_holder = torch.ones_like(inputs_ids[:, [0]]) # batch x 1
676
+ # prepare input_ids and attention_mask for transformers
677
+ #input_ids[attention_mask.bool()] += 3 # 0 - num_tokens to 3 - num_tokens + 3, total: 0 - num_tokens + 3, num: numtokens + 4
678
+ #input_ids[~attention_mask.bool()] = self.padding_token_id # 2 # in transformers pad token id is only used for init nn.embedding which we won't use
679
+
680
+ # input_ids = torch.cat(
681
+ # (place_holder * self.shape_bos_id, input_ids, place_holder * self.pad_id),
682
+ # dim=1
683
+ # )
684
+
685
+ inputs_ids = torch.cat(
686
+ #(place_holder * self.gpt_model.shape_bos_id, input_ids, place_holder * self.gpt_model.shape_eos_id),
687
+ (place_holder * self.gpt_model.shape_bos_id, inputs_ids),
688
+ dim=1
689
+ )
690
+
691
+ #input_ids[torch.arange(0, input_ids.shape[0]), attention_mask.sum(dim=1).long()+1] = self.eos_token_id #
692
+ #bos: begin of sequence, eos: end of sequence, pad: padding token
693
+
694
+ #import ipdb; ipdb.set_trace()
695
+ #input_ids[attention_mask.sum(dim=1).long()+1] = self.gpt_model.shape_eos_id #
696
+
697
+ attention_mask = torch.cat(
698
+ (place_holder, place_holder, attention_mask, ),
699
+ dim=1
700
+ )
701
+ # length
702
+ return inputs_ids, attention_mask
703
+
704
+ def precompute_freqs_cis_position(self, b, x_l, y_l, z_l, device):
705
+ """
706
+ Set the current position ID.
707
+ This method updates the `curr_pos_id` attribute with the given position.
708
+ Args:
709
+ pos (int): The position ID to set.
710
+ """
711
+ x_ids = torch.arange(x_l, dtype=torch.long, device=device) # shape (t)
712
+ x_ids = x_ids.unsqueeze_(0).expand(b, -1)
713
+
714
+ x_freqs_cis = precompute_freqs_cis(
715
+ dim=self.gpt_model.cfg.n_embd // self.gpt_model.cfg.n_head * 4, # 128
716
+ t=x_ids,
717
+ theta=self.gpt_model.cfg.rope_theta, #10000.0
718
+ )
719
+
720
+ y_ids = torch.arange(y_l, dtype=torch.long, device=device) # shape (t)
721
+ y_ids = y_ids.unsqueeze_(0).expand(b, -1)
722
+
723
+ y_freqs_cis = precompute_freqs_cis(
724
+ dim=self.gpt_model.cfg.n_embd // self.gpt_model.cfg.n_head * 4, # 128*4
725
+ t=y_ids,
726
+ theta=self.gpt_model.cfg.rope_theta, #10000.0
727
+ )
728
+
729
+ z_ids = torch.arange(z_l, dtype=torch.long, device=device) # shape (t)
730
+ z_ids = z_ids.unsqueeze_(0).expand(b, -1)
731
+
732
+ z_freqs_cis = precompute_freqs_cis(
733
+ dim=self.gpt_model.cfg.n_embd // self.gpt_model.cfg.n_head * 4, # 128
734
+ t=z_ids,
735
+ theta=self.gpt_model.cfg.rope_theta, #10000.0
736
+ )
737
+
738
+ return x_freqs_cis, y_freqs_cis, z_freqs_cis
739
+
740
+
741
+ def fwd_gpt(
742
+ self,
743
+ prompts: list[str],
744
+ inputs_ids: list[torch.Tensor],
745
+ latent: list[torch.Tensor],
746
+ use_kv_cache: bool,
747
+ guidance_scale: float = 3.0,
748
+ top_p: float = None,
749
+ bounding_box_xyz: Optional[Tuple[float]] = None,
750
+ strategy: int = None,
751
+ mode: str = 'train'
752
+ ):
753
+ """
754
+ Runs the GPT model to generate text based on the provided prompts.
755
+ Args:
756
+ prompts (list[str]): A list of input prompts for the GPT model. Only a single prompt is supported.
757
+ use_kv_cache (bool): Flag indicating whether to use key-value caching. (Currently not used)
758
+ guidance_scale (float, optional): The scale factor for guidance. Default is 3.0.
759
+ top_p (float, optional): The cumulative probability threshold for nucleus sampling.
760
+ If None, argmax selection is performed. Otherwise, smallest
761
+ set of tokens with cumulative probability ≥ top_p are kept.
762
+ bounding_box_xyz (Tuple[float] | None, optional): The size of the bounding box for the generated mesh
763
+ as (x, y, z) dimensions. Each value must be between 0 and 1.925. If None,
764
+ uses default bounding box sizing.
765
+ Returns:
766
+ torch.Tensor: A tensor containing the generated output token IDs.
767
+ Raises:
768
+ AssertionError: If the batch size is greater than 1.
769
+ """
770
+
771
+ #_, cond = self.prepare_inputs(prompts, guidance_scale, bounding_box_xyz)
772
+ #assert len(prompts) == 1, "batch size > 1 not support for EngineFast" #why?
773
+
774
+ #batch_size, input_seq_len, _ = embed.shape
775
+ with torch.no_grad():
776
+ attention_mask = inputs_ids != -1
777
+
778
+ cut_idx = (attention_mask == False)[:, :, -3].int().argmax(dim=1)
779
+ #dat_id = inputs_ids[:,:,self.gpt_model.xyz:self.gpt_model.xyz+self.gpt_model.dat_num].argmax(-1)
780
+ dat_id = inputs_ids[:,:,-6].long()
781
+ dat_id = torch.where(torch.arange(dat_id.shape[1], device=dat_id.device)[None,:] >= cut_idx[:,None], self.gpt_model.dat_num, dat_id)
782
+
783
+ inputs_embeds = self.gpt_model.dte(dat_id)
784
+ # x_id = inputs_ids[:,:,24:self.gpt_model.x+24].argmax(-1)
785
+ # y_id = inputs_ids[:,:,self.gpt_model.x:self.gpt_model.xy].argmax(-1)
786
+ # z_id = inputs_ids[:,:,self.gpt_model.xy:self.gpt_model.xyz].argmax(-1)
787
+
788
+ # coord_ids = torch.cat([x_id.unsqueeze(-1), y_id.unsqueeze(-1), z_id.unsqueeze(-1)], dim=-1)
789
+ # max_vals = torch.tensor([self.gpt_model.x_num - 1, self.gpt_model.y_num - 1, self.gpt_model.z_num - 1],
790
+ # dtype=torch.float32,
791
+ # device=coord_ids.device)
792
+ # normliz_coord = coord_ids.float() / max_vals.view(1, 1, 3) * 2 - 1 #
793
+ # pos_embeds = positional_encoding(normliz_coord, 128)
794
+ #embeds_from_id = self.gpt_model.encode_embed(inputs_ids[:, :, self.gpt_model.xyz:self.gpt_model.xyz + self.gpt_model.dat_num].float())
795
+ #embeds_from_id = self.gpt_model.encode_embed(inputs_ids[:, :, 24:self.gpt_model.xyz + self.gpt_model.dat_num].float())
796
+ #embeds_from_id = self.gpt_model.encode_embed(inputs_ids[:, :, 24:self.gpt_model.xyz].float())
797
+
798
+ #flatten rot id
799
+ r_id = inputs_ids[:,:,0]
800
+ r_id = torch.where(torch.arange(r_id.shape[1], device=r_id.device)[None,:] >= cut_idx[:,None], self.gpt_model.rot_num, r_id)
801
+
802
+
803
+ #flatten postion id
804
+ x_id = inputs_ids[:,:,-5]
805
+ y_id = inputs_ids[:,:,-4]
806
+ z_id = inputs_ids[:,:,-3]
807
+
808
+ x_id = torch.where(torch.arange(x_id.shape[1], device=x_id.device)[None,:] >= cut_idx[:,None], self.gpt_model.x_num, x_id)
809
+ y_id = torch.where(torch.arange(y_id.shape[1], device=y_id.device)[None,:] >= cut_idx[:,None], self.gpt_model.y_num, y_id)
810
+ z_id = torch.where(torch.arange(z_id.shape[1], device=z_id.device)[None,:] >= cut_idx[:,None], self.gpt_model.z_num, z_id)
811
+
812
+ inputs_ids[:, :, 0] = r_id.clone()
813
+ inputs_ids[:, :, -6] = dat_id.clone()
814
+ inputs_ids[:, :, -5] = x_id.clone()
815
+ inputs_ids[:, :, -4] = y_id.clone()
816
+ inputs_ids[:, :, -3] = z_id.clone()
817
+
818
+ #mask token
819
+ strategy = strategy if mode=='test' else torch.randint(0, 4, (1,)).item()
820
+
821
+ if strategy == 0:
822
+ x_id = torch.where(torch.arange(x_id.shape[1], device=x_id.device)[None,:] < cut_idx[:,None], self.gpt_model.x_num+1, x_id)
823
+ y_id = torch.where(torch.arange(y_id.shape[1], device=y_id.device)[None,:] < cut_idx[:,None], self.gpt_model.y_num+1, y_id)
824
+ z_id = torch.where(torch.arange(z_id.shape[1], device=z_id.device)[None,:] < cut_idx[:,None], self.gpt_model.z_num+1, z_id)
825
+ mask = None
826
+ elif strategy == 1:
827
+ x_id = torch.where(torch.arange(x_id.shape[1], device=x_id.device)[None,:] < cut_idx[:,None], self.gpt_model.x_num+1, x_id)
828
+ y_id = torch.where(torch.arange(y_id.shape[1], device=y_id.device)[None,:] < cut_idx[:,None], self.gpt_model.y_num+1, y_id)
829
+ z_id = torch.where(torch.arange(z_id.shape[1], device=z_id.device)[None,:] < cut_idx[:,None], self.gpt_model.z_num+1, z_id)
830
+ r_id = torch.where(torch.arange(r_id.shape[1], device=r_id.device)[None,:] < cut_idx[:,None], self.gpt_model.rot_num+1, r_id)
831
+ mask = None
832
+ elif strategy == 2:
833
+ x_id = torch.where(torch.arange(x_id.shape[1], device=x_id.device)[None,:] < cut_idx[:,None], self.gpt_model.x_num+1, x_id)
834
+ y_id = torch.where(torch.arange(y_id.shape[1], device=y_id.device)[None,:] < cut_idx[:,None], self.gpt_model.y_num+1, y_id)
835
+ z_id = torch.where(torch.arange(z_id.shape[1], device=z_id.device)[None,:] < cut_idx[:,None], self.gpt_model.z_num+1, z_id)
836
+ mask = (torch.arange(r_id.shape[1], device=r_id.device)[None,:] < cut_idx[:,None]) & (torch.rand(r_id.shape, device=r_id.device) > torch.empty(1, device=r_id.device).uniform_(0.0, 1.0).item())
837
+ r_id = torch.where(mask, self.gpt_model.rot_num+1, r_id)
838
+ else:
839
+ mask = (torch.arange(x_id.shape[1], device=x_id.device)[None,:] < cut_idx[:,None]) & (torch.rand(x_id.shape, device=x_id.device) > torch.empty(1, device=r_id.device).uniform_(0.0, 1.).item())
840
+ x_id = torch.where(mask, self.gpt_model.x_num+1, x_id)
841
+ y_id = torch.where(mask, self.gpt_model.y_num+1, y_id)
842
+ z_id = torch.where(mask, self.gpt_model.z_num+1, z_id)
843
+
844
+ #print(strategy)
845
+ rembeds_from_id = self.gpt_model.rte(r_id)
846
+ xembeds_from_id = self.gpt_model.xte(x_id)
847
+ yembeds_from_id = self.gpt_model.yte(y_id)
848
+ zembeds_from_id = self.gpt_model.zte(z_id)
849
+
850
+ embeds_from_id = torch.stack([inputs_embeds.clone(), rembeds_from_id, yembeds_from_id, xembeds_from_id, zembeds_from_id], dim=2) # [b, 310, 3, 1536]
851
+ #embeds_from_id = torch.stack([yembeds_from_id, xembeds_from_id, zembeds_from_id], dim=2)
852
+ embeds_from_id = embeds_from_id.view(xembeds_from_id.shape[0], xembeds_from_id.shape[1] * 5, xembeds_from_id.shape[2]) # [b, 930, 1536]
853
+
854
+ #inputs_embeds = self.gpt_model.encode_token(latent)
855
+
856
+ #position embedding
857
+ #inputs_embeds = torch.cat([pos_embeds, inputs_embeds], dim=-1)
858
+
859
+ inputs_embeds = self.prepare_conditions_with_bboxs(inputs_embeds, bounding_box_xyz)
860
+
861
+ #add token number padding
862
+ #sequence_length = inputs_ids.shape[1]
863
+ #pad_sequence = torch.ones((inputs_ids.shape[0], sequence_length), dtype=torch.long, device=inputs_ids.device) * self.gpt_model.dat_num #self.gpt_model.padding_id
864
+ #pad_sequence_embed = self.gpt_model.encode_token(pad_sequence) #[b, 1536]
865
+
866
+ #!!!--------litte wrong
867
+ #embeds_from_id[~attention_mask[:,:,:inputs_embeds.shape[2]]] = pad_sequence_embed[~attention_mask[:,:,:inputs_embeds.shape[2]]]
868
+
869
+ #add bos
870
+ place_holder = torch.ones_like(inputs_ids[:, 0, 0]).long() # batch x 1
871
+ bos_embed = self.gpt_model.encode_token(place_holder * self.gpt_model.shape_bos_id) #[1, 1536]
872
+ embeds_from_id = torch.cat([bos_embed[:, None, :], embeds_from_id], dim=1)
873
+
874
+ inputs_embeds = bos_embed.unsqueeze(1)
875
+ #exchange
876
+ # ex = inputs_embeds.clone()
877
+ # inputs_embeds = self.prepare_conditions_with_bboxs(embeds_from_id, bounding_box_xyz)
878
+ # embeds_from_id = torch.cat([bos_embed[:, None, :], ex], dim=1)
879
+
880
+ # Prefill is always eager
881
+ prefill_logits = self.gpt_model(
882
+ embed=embeds_from_id, #_repeat,
883
+ cond=inputs_embeds, #_repeat,
884
+ kv_cache=None,
885
+ curr_pos_id=None,
886
+ decode=False,
887
+ )
888
+
889
+ logits = prefill_logits[..., self.min_id : self.max_id]
890
+
891
+ # if guidance_scale > 0.0:
892
+ # logits, uncond_logits = logits.float().chunk(2, dim=0)
893
+ # gamma = guidance_scale
894
+ # # seq_len = logits.size(1)
895
+ # # gamma_list = guidance_scale * (seq_len - torch.arange(seq_len)) / seq_len
896
+ # # # shape: [seq_len]
897
+ # logits = (1 + gamma) * logits - gamma * uncond_logits
898
+
899
+ return logits, inputs_ids, strategy, mask, cut_idx
900
+
901
+ def t2t(
902
+ self,
903
+ prompts: list[str],
904
+ inputs_ids: list[torch.Tensor],
905
+ latent: list[torch.Tensor],
906
+ use_kv_cache: bool,
907
+ guidance_scale: float = 3.0,
908
+ resolution_base: float = 8.0,
909
+ chunk_size: int = 100_000,
910
+ top_p: float = None,
911
+ bounding_box_xyz: Optional[Tuple[float]] = None,
912
+ strategy: int = None,
913
+ mode: str = None
914
+ ):
915
+ """
916
+ Generates a 3D mesh from text prompts using a GPT model.
917
+ Args:
918
+ prompts (list[str]): A list of text prompts to guide the generation.
919
+ use_kv_cache (bool): Whether to use key-value caching for the GPT model.
920
+ guidance_scale (float, optional): The scale of guidance for the GPT model. Default is 3.0.
921
+ resolution_base (float, optional): The base resolution for the shape decoder. Default is 8.0.
922
+ chunk_size (int, optional): The chunk size for processing the shape decoding. Default is 100,000.
923
+ top_p (float, optional): The cumulative probability threshold for nucleus sampling.
924
+ If None, argmax selection is performed (deterministic generation). Otherwise, smallest set of tokens with cumulative probability ≥ top_p are kept (stochastic generation).
925
+ bounding_box_xyz (Tuple[float] | None, optional): The size of the bounding box for the generated mesh
926
+ as (x, y, z) dimensions. Each value must be between 0 and 1.925. If None,
927
+ uses default bounding box sizing.
928
+ Returns:
929
+ output_ids: The generated 3D mesh tokens.
930
+ """
931
+ logits = self.fwd_gpt(
932
+ prompts, inputs_ids, latent, use_kv_cache, guidance_scale, top_p, bounding_box_xyz, strategy, mode
933
+ )
934
+
935
+ return logits
936
+
937
+ def configure_optimizers(
938
+ self,
939
+ train_config
940
+ ):
941
+ """
942
+ This long function is unfortunately doing something very simple and is being very defensive:
943
+ We are separating out all parameters of the model into two buckets: those that will experience
944
+ weight decay for regularization and those that won't (biases, and layernorm/embedding weights).
945
+ We are then returning the PyTorch optimizer object.
946
+ """
947
+
948
+ # separate out all parameters to those that will and won't experience regularizing weight decay
949
+ decay = set()
950
+ no_decay = set()
951
+ whitelist_weight_modules = (torch.nn.Linear, )
952
+ blacklist_weight_modules = (torch.nn.LayerNorm, torch.nn.Embedding)
953
+ # import ipdb; ipdb.set_trace()
954
+ for mn, m in self.gpt_model.named_modules():
955
+ #print(mn, m)
956
+ if mn!='lm_head':
957
+ continue
958
+ for pn, p in m.named_parameters():
959
+ fpn = '%s.%s' % (mn, pn) if mn else pn # full param name
960
+ # random note: because named_modules and named_parameters are recursive
961
+ # we will see the same tensors p many many times. but doing it this way
962
+ # allows us to know which parent module any tensor p belongs to...
963
+ if pn.endswith('bias'):
964
+ # all biases will not be decayed
965
+ no_decay.add(fpn)
966
+ elif pn.endswith('weight') and isinstance(m, whitelist_weight_modules):
967
+ # weights of whitelist modules will be weight decayed
968
+ decay.add(fpn)
969
+ elif pn.endswith('weight') and isinstance(m, blacklist_weight_modules):
970
+ # weights of blacklist modules will NOT be weight decayed
971
+ no_decay.add(fpn)
972
+ elif '_norm.weight' in pn: #
973
+ no_decay.add(fpn)
974
+
975
+ #import ipdb; ipdb.set_trace()
976
+
977
+ # validate that we considered every parameter
978
+ param_dict = {pn: p for pn, p in self.gpt_model.named_parameters()}
979
+ inter_params = decay & no_decay
980
+ union_params = decay | no_decay
981
+
982
+ # assert len(inter_params) == 0, "parameters %s made it into both decay/no_decay sets!" % (str(inter_params), )
983
+ # assert len(param_dict.keys() - union_params) == 0, "parameters %s were not separated into either decay/no_decay set!" \
984
+ # % (str(param_dict.keys() - union_params), )
985
+
986
+ # create the pytorch optimizer object
987
+ optim_groups = [
988
+ {"params": [param_dict[pn] for pn in sorted(list(decay))], "weight_decay": train_config.weight_decay},
989
+ {"params": [param_dict[pn] for pn in sorted(list(no_decay))], "weight_decay": 0.0},
990
+ ]
991
+ optimizer = torch.optim.AdamW(optim_groups, lr=train_config.learning_rate, betas=train_config.betas)
992
+ return optimizer
993
+ def configure_optimizers_lora(
994
+ self,
995
+ train_config
996
+ ):
997
+ """
998
+ This long function is unfortunately doing something very simple and is being very defensive:
999
+ We are separating out all parameters of the model into two buckets: those that will experience
1000
+ weight decay for regularization and those that won't (biases, and layernorm/embedding weights).
1001
+ We are then returning the PyTorch optimizer object.
1002
+ """
1003
+
1004
+ optim_groups = (p for p in self.gpt_model.parameters() if p.requires_grad)
1005
+ optimizer = torch.optim.AdamW(optim_groups, lr=train_config.learning_rate, betas=train_config.betas)
1006
+ return optimizer
1007
+
1008
+ def configure_optimizers_lora_linear(
1009
+ self,
1010
+ train_config
1011
+ ):
1012
+ """
1013
+ This long function is unfortunately doing something very simple and is being very defensive:
1014
+ We are separating out all parameters of the model into two buckets: those that will experience
1015
+ weight decay for regularization and those that won't (biases, and layernorm/embedding weights).
1016
+ We are then returning the PyTorch optimizer object.
1017
+ """
1018
+ # separate out all parameters to those that will and won't experience regularizing weight decay
1019
+ decay = set()
1020
+ no_decay = set()
1021
+ whitelist_weight_modules = (torch.nn.Linear, )
1022
+ blacklist_weight_modules = (torch.nn.LayerNorm, torch.nn.Embedding)
1023
+ for mn, m in self.gpt_model.named_modules():
1024
+ #print(mn, m)
1025
+ if mn!='ldr_head' or mn!='ldr_proj' or mn!='dte' or mn!='xte' or mn!='yte' or mn!='zte' or mn!='rte':
1026
+ continue
1027
+ for pn, p in m.named_parameters():
1028
+ fpn = '%s.%s' % (mn, pn) if mn else pn # full param name
1029
+ # random note: because named_modules and named_parameters are recursive
1030
+ # we will see the same tensors p many many times. but doing it this way
1031
+ # allows us to know which parent module any tensor p belongs to...
1032
+ if pn.endswith('bias'):
1033
+ # all biases will not be decayed
1034
+ no_decay.add(fpn)
1035
+ elif pn.endswith('weight') and isinstance(m, whitelist_weight_modules):
1036
+ # weights of whitelist modules will be weight decayed
1037
+ decay.add(fpn)
1038
+ elif pn.endswith('weight') and isinstance(m, blacklist_weight_modules):
1039
+ # weights of blacklist modules will NOT be weight decayed
1040
+ no_decay.add(fpn)
1041
+ elif '_norm.weight' in pn: #
1042
+ no_decay.add(fpn)
1043
+
1044
+ # validate that we considered every parameter
1045
+ param_dict = {pn: p for pn, p in self.gpt_model.named_parameters()}
1046
+ inter_params = decay & no_decay
1047
+ union_params = decay | no_decay
1048
+ lora_optim_groups = [p for p in self.gpt_model.parameters() if p.requires_grad]
1049
+
1050
+ optim_groups = [
1051
+ {"params": [param_dict[pn] for pn in sorted(list(decay))], "weight_decay": train_config.weight_decay},
1052
+ {"params": [param_dict[pn] for pn in sorted(list(no_decay))], "weight_decay": 0.0},
1053
+ {"params": lora_optim_groups},
1054
+ ]
1055
+ optimizer = torch.optim.AdamW(optim_groups, lr=train_config.learning_rate, betas=train_config.betas)
1056
+
1057
+ scheduler = CosineAnnealingLR(
1058
+ optimizer,
1059
+ T_max=train_config.max_iters,
1060
+ eta_min=train_config.learning_rate * 0.01
1061
+ )
1062
+ return optimizer, scheduler
1063
+
1064
+ def configure_optimizers_scratch_linear(
1065
+ self,
1066
+ train_config
1067
+ ):
1068
+ """
1069
+ This long function is unfortunately doing something very simple and is being very defensive:
1070
+ We are separating out all parameters of the model into two buckets: those that will experience
1071
+ weight decay for regularization and those that won't (biases, and layernorm/embedding weights).
1072
+ We are then returning the PyTorch optimizer object.
1073
+ """
1074
+ # separate out all parameters to those that will and won't experience regularizing weight decay
1075
+ decay = set()
1076
+ no_decay = set()
1077
+ whitelist_weight_modules = (torch.nn.Linear, )
1078
+ blacklist_weight_modules = (torch.nn.LayerNorm, torch.nn.Embedding)
1079
+ for mn, m in self.gpt_model.named_modules():
1080
+ #print(mn, m)
1081
+ # if mn!='ldr_head' or mn!='ldr_proj' or mn!='dte' or mn!='xte' or mn!='yte' or mn!='zte' or mn!='rte':
1082
+ # continue
1083
+ for pn, p in m.named_parameters():
1084
+ fpn = '%s.%s' % (mn, pn) if mn else pn # full param name
1085
+ # random note: because named_modules and named_parameters are recursive
1086
+ # we will see the same tensors p many many times. but doing it this way
1087
+ # allows us to know which parent module any tensor p belongs to...
1088
+ if pn.endswith('bias'):
1089
+ # all biases will not be decayed
1090
+ no_decay.add(fpn)
1091
+ elif pn.endswith('weight') and isinstance(m, whitelist_weight_modules):
1092
+ # weights of whitelist modules will be weight decayed
1093
+ decay.add(fpn)
1094
+ elif pn.endswith('weight') and isinstance(m, blacklist_weight_modules):
1095
+ # weights of blacklist modules will NOT be weight decayed
1096
+ no_decay.add(fpn)
1097
+ elif '_norm.weight' in pn: #
1098
+ no_decay.add(fpn)
1099
+
1100
+ # validate that we considered every parameter
1101
+ param_dict = {pn: p for pn, p in self.gpt_model.named_parameters()}
1102
+ inter_params = decay & no_decay
1103
+ union_params = decay | no_decay
1104
+
1105
+ assert len(inter_params) == 0, "parameters %s made it into both decay/no_decay sets!" % (str(inter_params), )
1106
+ assert len(param_dict.keys() - union_params) == 0, "parameters %s were not separated into either decay/no_decay set!" \
1107
+ % (str(param_dict.keys() - union_params), )
1108
+
1109
+ optim_groups = [
1110
+ {"params": [param_dict[pn] for pn in sorted(list(decay))], "weight_decay": train_config.weight_decay},
1111
+ {"params": [param_dict[pn] for pn in sorted(list(no_decay))], "weight_decay": 0.0},
1112
+ ]
1113
+ optimizer = torch.optim.AdamW(optim_groups, lr=train_config.learning_rate, betas=train_config.betas)
1114
+
1115
+ scheduler = CosineAnnealingLR(
1116
+ optimizer,
1117
+ T_max=train_config.max_iters,
1118
+ eta_min=train_config.learning_rate * 0.01
1119
+ )
1120
+ return optimizer, scheduler