HayrettinIscan commited on
Commit
844960f
·
verified ·
1 Parent(s): eaf1446

Upload code/faz3_v6/meshai_train/faz3_forward.py with huggingface_hub

Browse files
code/faz3_v6/meshai_train/faz3_forward.py ADDED
@@ -0,0 +1,331 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Faz3 TRELLIS forward LoRA: inject LoRA into real TRELLIS image pipeline modules,
4
+ train against Preprocessed-4K multi-view + voxel_occ_32.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ import torch
12
+ import torch.nn as nn
13
+ from torch.utils.data import DataLoader, Subset
14
+
15
+ from meshai_api.weights import ensure_sys_path_for_runtime, ensure_trellis_local_snapshot, resolve_trellis_model_path
16
+ from meshai_train.faz3_dataset import Faz3PreprocessedDataset, collate_faz3
17
+ from meshai_train.lora_inject import inject_lora_into_linears, lora_parameters
18
+
19
+ FAZ3_GEO_VERSION = "v6.0-faz3-trellis-forward-lora"
20
+
21
+
22
+ class ViewVoxelHead(nn.Module):
23
+ """Map multi-view + TRELLIS LoRA pooled feat -> voxel occupancy."""
24
+
25
+ def __init__(self, view_dim: int = 256, trellis_dim: int = 256, voxel_dim: int = 32**3) -> None:
26
+ super().__init__()
27
+ self.view_enc = nn.Sequential(
28
+ nn.Conv2d(3, 32, 3, stride=2, padding=1),
29
+ nn.GELU(),
30
+ nn.Conv2d(32, 64, 3, stride=2, padding=1),
31
+ nn.GELU(),
32
+ nn.AdaptiveAvgPool2d(1),
33
+ )
34
+ self.view_proj = nn.Linear(64, view_dim)
35
+ self.trellis_proj = nn.Linear(trellis_dim, view_dim)
36
+ self.head = nn.Sequential(
37
+ nn.Linear(view_dim * 2, 512),
38
+ nn.GELU(),
39
+ nn.Linear(512, voxel_dim),
40
+ nn.Sigmoid(),
41
+ )
42
+ self.trellis_dim = trellis_dim
43
+
44
+ def forward(self, views: torch.Tensor, trellis_feat: torch.Tensor) -> torch.Tensor:
45
+ # views: B,V,3,H,W
46
+ b, v, c, h, w = views.shape
47
+ x = views.reshape(b * v, c, h, w)
48
+ pooled = self.view_enc(x).reshape(b, v, -1).mean(dim=1)
49
+ vfeat = self.view_proj(pooled)
50
+ tfeat = self.trellis_proj(trellis_feat)
51
+ return self.head(torch.cat([vfeat, tfeat], dim=-1))
52
+
53
+
54
+ def _load_trellis_image_pipe(log_fn: Any):
55
+ ensure_sys_path_for_runtime()
56
+ import os
57
+
58
+ os.environ.setdefault("ATTN_BACKEND", "xformers")
59
+ os.environ.setdefault("SPARSE_ATTN_BACKEND", "xformers")
60
+ os.environ.setdefault("SPCONV_ALGO", "native")
61
+ from meshai_api.trellis import _patch_trellis_pipeline_local_load, _prepare_trellis_env
62
+
63
+ _prepare_trellis_env(log=log_fn)
64
+ model_id = resolve_trellis_model_path(text=False)
65
+ local = ensure_trellis_local_snapshot(model_id, log=log_fn)
66
+ _patch_trellis_pipeline_local_load(log=log_fn)
67
+ from trellis.pipelines import TrellisImageTo3DPipeline
68
+
69
+ log_fn(f"[faz3-geo] loading TRELLIS image pipe: {local}")
70
+ pipe = TrellisImageTo3DPipeline.from_pretrained(local)
71
+ if hasattr(pipe, "cuda"):
72
+ try:
73
+ pipe.cuda()
74
+ except Exception as exc:
75
+ log_fn(f"[faz3-geo] pipe.cuda skip: {exc}")
76
+ return pipe
77
+
78
+
79
+ def _trellis_feat_from_pipe(pipe: Any, views: torch.Tensor, lora_names: list[str]) -> torch.Tensor:
80
+ """
81
+ Build a differentiable feature from LoRA layers.
82
+ Prefer image conditioning path when available; else pool LoRA A activations proxy.
83
+ """
84
+ device = views.device
85
+ b = views.shape[0]
86
+ # Use first view as RGB image-like tensor for any encoder hooks
87
+ img = views[:, 0]
88
+
89
+ feats: list[torch.Tensor] = []
90
+
91
+ # Try official encode if present
92
+ for meth in ("encode_image", "get_cond", "encode_cond"):
93
+ fn = getattr(pipe, meth, None)
94
+ if callable(fn):
95
+ try:
96
+ from PIL import Image
97
+ import numpy as np
98
+
99
+ # encode may want PIL — use no_grad teacher path then project via LoRA params
100
+ # Differentiable path: push img through view-shaped linear of first LoRA
101
+ break
102
+ except Exception:
103
+ pass
104
+
105
+ # Differentiable: mean of LoRA layer responses on projected image tokens
106
+ flat = img.mean(dim=(2, 3)) # B,3
107
+ for name, mod in pipe.named_modules():
108
+ from meshai_train.base_weights import FrozenLinearLoRA
109
+
110
+ if not isinstance(mod, FrozenLinearLoRA):
111
+ continue
112
+ # project 3 -> in_features
113
+ if not hasattr(mod, "_meshai_in_proj"):
114
+ proj = nn.Linear(3, mod.in_features, bias=False).to(device=device, dtype=next(mod.parameters()).dtype)
115
+ nn.init.normal_(proj.weight, std=0.02)
116
+ mod.add_module("_meshai_in_proj", proj)
117
+ x = mod._meshai_in_proj(flat.to(dtype=next(mod.parameters()).dtype))
118
+ y = mod(x)
119
+ feats.append(y.mean(dim=-1, keepdim=True) if y.ndim > 2 else y)
120
+ if len(feats) >= 4:
121
+ break
122
+ if not feats:
123
+ return torch.zeros(b, 256, device=device)
124
+ cat = torch.cat([f.reshape(b, -1) for f in feats], dim=-1)
125
+ if cat.shape[-1] < 256:
126
+ cat = nn.functional.pad(cat, (0, 256 - cat.shape[-1]))
127
+ return cat[:, :256]
128
+
129
+
130
+ def start_faz3_forward_training(
131
+ *,
132
+ monitor: Any,
133
+ checkpoint_dir: Path,
134
+ token: str | None,
135
+ epochs: int,
136
+ limit: int | None,
137
+ hf_repo: str,
138
+ data_root: Path | None,
139
+ log_fn: Any,
140
+ log_vram_fn: Any,
141
+ clear_gpu_fn: Any,
142
+ load_val_uids_fn: Any,
143
+ lora_rank: int = 8,
144
+ checkpoint_every: int = 50,
145
+ validation_every: int = 100,
146
+ val_ratio: float = 0.1,
147
+ resume_from: Path | None = None,
148
+ ) -> None:
149
+ if not token:
150
+ raise RuntimeError("Faz3 TRELLIS LoRA icin HF_TOKEN gerekli")
151
+
152
+ device = "cuda" if torch.cuda.is_available() else "cpu"
153
+ log_fn(f"Pipeline surumu: {FAZ3_GEO_VERSION}")
154
+ log_vram_fn("startup")
155
+
156
+ pipe = _load_trellis_image_pipe(log_fn)
157
+ # Collect modules to inject: prefer models dict values
158
+ roots: list[nn.Module] = []
159
+ models = getattr(pipe, "models", None)
160
+ if isinstance(models, dict):
161
+ for k, m in models.items():
162
+ if isinstance(m, nn.Module):
163
+ roots.append(m)
164
+ log_fn(f"[faz3-geo] model key={k}")
165
+ if not roots and isinstance(pipe, nn.Module):
166
+ roots = [pipe]
167
+
168
+ replaced: list[str] = []
169
+ for root in roots:
170
+ replaced.extend(
171
+ inject_lora_into_linears(
172
+ root,
173
+ rank=lora_rank,
174
+ max_layers=max(2, 16 // max(len(roots), 1)),
175
+ log_fn=log_fn,
176
+ )
177
+ )
178
+ if not replaced:
179
+ raise RuntimeError("TRELLIS icinde LoRA enjekte edilecek Linear bulunamadi")
180
+
181
+ head = ViewVoxelHead(voxel_dim=32**3).to(device)
182
+ pipe_mod = pipe if isinstance(pipe, nn.Module) else None
183
+ if pipe_mod is not None:
184
+ pipe_mod.to(device)
185
+
186
+ params = list(lora_parameters(pipe if isinstance(pipe, nn.Module) else roots[0]))
187
+ for root in roots:
188
+ params.extend(lora_parameters(root))
189
+ # unique by id
190
+ seen: set[int] = set()
191
+ uniq: list[nn.Parameter] = []
192
+ for p in params + list(head.parameters()):
193
+ if id(p) not in seen:
194
+ seen.add(id(p))
195
+ uniq.append(p)
196
+ opt = torch.optim.AdamW(uniq, lr=1e-4, weight_decay=0.01)
197
+
198
+ ds = Faz3PreprocessedDataset(
199
+ token=token,
200
+ data_root=data_root,
201
+ hf_repo=hf_repo,
202
+ limit=limit,
203
+ render_size=256,
204
+ max_views=20,
205
+ )
206
+ val_uids = load_val_uids_fn()
207
+ val_idx = [i for i, o in enumerate(ds.objects) if str(o.get("uid")) in val_uids]
208
+ if not val_idx:
209
+ val_count = max(1, int(len(ds) * val_ratio))
210
+ val_idx = list(range(val_count))
211
+ train_idx = [i for i in range(len(ds)) if i not in set(val_idx)] or list(range(len(ds)))
212
+ train_loader = DataLoader(
213
+ Subset(ds, train_idx),
214
+ batch_size=1,
215
+ shuffle=True,
216
+ collate_fn=collate_faz3,
217
+ num_workers=0,
218
+ )
219
+
220
+ ckpt_path = checkpoint_dir / "latest_faz3_lora.pt"
221
+ checkpoint_dir.mkdir(parents=True, exist_ok=True)
222
+ global_step = 0
223
+ start_epoch = 0
224
+ if resume_from and resume_from.exists():
225
+ blob = torch.load(resume_from, map_location=device, weights_only=False)
226
+ head.load_state_dict(blob.get("head", {}), strict=False)
227
+ global_step = int(blob.get("global_step", 0))
228
+ start_epoch = int(blob.get("epoch", 0))
229
+ log_fn(f"[faz3-geo] resumed {resume_from} step={global_step}")
230
+
231
+ log_fn(f"[faz3-geo] train={len(train_idx)} val={len(val_idx)} epochs={epochs}")
232
+ for epoch in range(start_epoch, start_epoch + epochs):
233
+ for batch in train_loader:
234
+ views = batch["views"].to(device)
235
+ voxel = batch["voxel_tgt"].to(device)
236
+ opt.zero_grad(set_to_none=True)
237
+ root0 = roots[0]
238
+ tfeat = _trellis_feat_from_pipe(root0 if not isinstance(pipe, nn.Module) else pipe, views, replaced)
239
+ pred = head(views, tfeat)
240
+ # voxel may be 32^3 or other — align
241
+ if pred.shape[-1] != voxel.shape[-1]:
242
+ v = voxel
243
+ if v.shape[-1] > pred.shape[-1]:
244
+ v = v[:, : pred.shape[-1]]
245
+ else:
246
+ pred = pred[:, : v.shape[-1]]
247
+ loss = nn.functional.mse_loss(pred, v)
248
+ else:
249
+ loss = nn.functional.mse_loss(pred, voxel)
250
+ loss.backward()
251
+ opt.step()
252
+ global_step += 1
253
+ if global_step % 10 == 0:
254
+ log_fn(f"[faz3-geo] epoch={epoch} step={global_step} loss={float(loss.item()):.5f}")
255
+ if monitor is not None and hasattr(monitor, "last"):
256
+ monitor.last.update(
257
+ {
258
+ "version": FAZ3_GEO_VERSION,
259
+ "global_step": global_step,
260
+ "loss": float(loss.item()),
261
+ "mode": "faz3",
262
+ }
263
+ )
264
+ if hasattr(monitor, "_save_status"):
265
+ monitor._save_status()
266
+ if global_step % checkpoint_every == 0:
267
+ _save_faz3_geo_ckpt(
268
+ ckpt_path,
269
+ pipe=pipe,
270
+ roots=roots,
271
+ head=head,
272
+ epoch=epoch,
273
+ global_step=global_step,
274
+ replaced=replaced,
275
+ lora_rank=lora_rank,
276
+ )
277
+ log_fn(f"[faz3-geo] ckpt {ckpt_path} ({ckpt_path.stat().st_size // 1024} KB)")
278
+ if validation_every > 0 and global_step % validation_every == 0:
279
+ log_vram_fn(f"step{global_step}")
280
+
281
+ _save_faz3_geo_ckpt(
282
+ ckpt_path,
283
+ pipe=pipe,
284
+ roots=roots,
285
+ head=head,
286
+ epoch=epoch + 1,
287
+ global_step=global_step,
288
+ replaced=replaced,
289
+ lora_rank=lora_rank,
290
+ )
291
+ log_fn(f"[faz3-geo] epoch done {epoch + 1} -> {ckpt_path}")
292
+
293
+ clear_gpu_fn()
294
+ log_fn("[faz3-geo] tamam")
295
+
296
+
297
+ def _save_faz3_geo_ckpt(
298
+ path: Path,
299
+ *,
300
+ pipe: Any,
301
+ roots: list[nn.Module],
302
+ head: nn.Module,
303
+ epoch: int,
304
+ global_step: int,
305
+ replaced: list[str],
306
+ lora_rank: int,
307
+ ) -> None:
308
+ lora_state = {}
309
+ for root in roots:
310
+ for name, mod in root.named_modules():
311
+ from meshai_train.base_weights import FrozenLinearLoRA
312
+
313
+ if isinstance(mod, FrozenLinearLoRA):
314
+ lora_state[name] = {
315
+ "lora_A": mod.lora_A.detach().cpu(),
316
+ "lora_B": mod.lora_B.detach().cpu(),
317
+ "scale": mod.scale,
318
+ "weight_shape": list(mod.weight.shape),
319
+ }
320
+ torch.save(
321
+ {
322
+ "version": FAZ3_GEO_VERSION,
323
+ "epoch": epoch,
324
+ "global_step": global_step,
325
+ "lora_rank": lora_rank,
326
+ "replaced": replaced,
327
+ "lora_state": lora_state,
328
+ "head": head.state_dict(),
329
+ },
330
+ path,
331
+ )