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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Faz3 Hunyuan Paint LoRA: mesh (normalized.glb) + multi-view tex refs from Preprocessed-4K.
|
| 4 |
+
"""
|
| 5 |
+
from __future__ import annotations
|
| 6 |
+
|
| 7 |
+
import random
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from typing import Any
|
| 10 |
+
|
| 11 |
+
import numpy as np
|
| 12 |
+
import torch
|
| 13 |
+
import torch.nn as nn
|
| 14 |
+
from PIL import Image
|
| 15 |
+
from torch.utils.data import DataLoader, Subset
|
| 16 |
+
|
| 17 |
+
from meshai_api.weights import ensure_sys_path_for_runtime, resolve_hunyuan_model_path, runtime_status
|
| 18 |
+
from meshai_train.faz3_dataset import Faz3PreprocessedDataset, collate_faz3
|
| 19 |
+
from meshai_train.lora_inject import inject_lora_into_linears, lora_parameters
|
| 20 |
+
|
| 21 |
+
FAZ3_PAINT_VERSION = "v6.0-faz3-hunyuan-paint-lora"
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def _load_paint_pipe(log_fn: Any):
|
| 25 |
+
ensure_sys_path_for_runtime()
|
| 26 |
+
st = runtime_status()
|
| 27 |
+
if not st.get("hunyuan_package"):
|
| 28 |
+
raise RuntimeError("Hunyuan package yok — third_party/Hunyuan3D-2 + MESHAI_HUNYUAN_ROOT")
|
| 29 |
+
from hy3dgen.texgen import Hunyuan3DPaintPipeline
|
| 30 |
+
|
| 31 |
+
model_id = resolve_hunyuan_model_path()
|
| 32 |
+
log_fn(f"[faz3-paint] loading Paint: {model_id}")
|
| 33 |
+
pipe = Hunyuan3DPaintPipeline.from_pretrained(model_id)
|
| 34 |
+
return pipe
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def _as_trimesh(path: Path):
|
| 38 |
+
import trimesh
|
| 39 |
+
|
| 40 |
+
loaded = trimesh.load(str(path), force="scene", process=False)
|
| 41 |
+
if isinstance(loaded, trimesh.Trimesh):
|
| 42 |
+
return loaded
|
| 43 |
+
meshes = [
|
| 44 |
+
g
|
| 45 |
+
for g in loaded.geometry.values()
|
| 46 |
+
if isinstance(g, trimesh.Trimesh) and len(g.vertices) > 0
|
| 47 |
+
]
|
| 48 |
+
if not meshes:
|
| 49 |
+
raise ValueError(f"empty mesh {path}")
|
| 50 |
+
return trimesh.util.concatenate(meshes) if len(meshes) > 1 else meshes[0]
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def _tensor_from_pil(img: Image.Image, size: int = 256) -> torch.Tensor:
|
| 54 |
+
img = img.convert("RGB").resize((size, size), Image.BILINEAR)
|
| 55 |
+
arr = np.asarray(img, dtype=np.float32) / 255.0
|
| 56 |
+
return torch.from_numpy(arr.transpose(2, 0, 1))
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def _extract_basecolor_tensor(mesh: Any, size: int = 256) -> torch.Tensor | None:
|
| 60 |
+
"""Best-effort baseColor -> CxHxW tensor."""
|
| 61 |
+
import trimesh
|
| 62 |
+
|
| 63 |
+
geoms = [mesh] if isinstance(mesh, trimesh.Trimesh) else list(getattr(mesh, "geometry", {}).values())
|
| 64 |
+
for geom in geoms:
|
| 65 |
+
if not isinstance(geom, trimesh.Trimesh):
|
| 66 |
+
continue
|
| 67 |
+
vis = getattr(geom, "visual", None)
|
| 68 |
+
mat = getattr(vis, "material", None) if vis is not None else None
|
| 69 |
+
tex = getattr(mat, "baseColorTexture", None) if mat is not None else None
|
| 70 |
+
if tex is None:
|
| 71 |
+
continue
|
| 72 |
+
if hasattr(tex, "convert"):
|
| 73 |
+
return _tensor_from_pil(tex, size=size)
|
| 74 |
+
try:
|
| 75 |
+
return _tensor_from_pil(Image.fromarray(np.asarray(tex)), size=size)
|
| 76 |
+
except Exception:
|
| 77 |
+
continue
|
| 78 |
+
return None
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def start_faz3_paint_training(
|
| 82 |
+
*,
|
| 83 |
+
monitor: Any,
|
| 84 |
+
checkpoint_dir: Path,
|
| 85 |
+
token: str | None,
|
| 86 |
+
epochs: int,
|
| 87 |
+
limit: int | None,
|
| 88 |
+
hf_repo: str,
|
| 89 |
+
data_root: Path | None,
|
| 90 |
+
log_fn: Any,
|
| 91 |
+
log_vram_fn: Any,
|
| 92 |
+
clear_gpu_fn: Any,
|
| 93 |
+
load_val_uids_fn: Any,
|
| 94 |
+
lora_rank: int = 8,
|
| 95 |
+
checkpoint_every: int = 20,
|
| 96 |
+
val_ratio: float = 0.1,
|
| 97 |
+
resume_from: Path | None = None,
|
| 98 |
+
map_size: int = 256,
|
| 99 |
+
) -> None:
|
| 100 |
+
if not token:
|
| 101 |
+
raise RuntimeError("Faz3 Paint LoRA icin HF_TOKEN gerekli")
|
| 102 |
+
|
| 103 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 104 |
+
log_fn(f"Pipeline surumu: {FAZ3_PAINT_VERSION}")
|
| 105 |
+
log_vram_fn("startup")
|
| 106 |
+
|
| 107 |
+
pipe = _load_paint_pipe(log_fn)
|
| 108 |
+
# Inject into underlying torch modules
|
| 109 |
+
roots: list[nn.Module] = []
|
| 110 |
+
for attr in ("models", "model", "unet", "pipeline"):
|
| 111 |
+
obj = getattr(pipe, attr, None)
|
| 112 |
+
if isinstance(obj, nn.Module):
|
| 113 |
+
roots.append(obj)
|
| 114 |
+
elif isinstance(obj, dict):
|
| 115 |
+
roots.extend([m for m in obj.values() if isinstance(m, nn.Module)])
|
| 116 |
+
if not roots:
|
| 117 |
+
# walk pipe attributes
|
| 118 |
+
for v in vars(pipe).values():
|
| 119 |
+
if isinstance(v, nn.Module):
|
| 120 |
+
roots.append(v)
|
| 121 |
+
if not roots:
|
| 122 |
+
raise RuntimeError("Paint pipeline icinde nn.Module bulunamadi")
|
| 123 |
+
|
| 124 |
+
replaced: list[str] = []
|
| 125 |
+
for root in roots:
|
| 126 |
+
replaced.extend(
|
| 127 |
+
inject_lora_into_linears(
|
| 128 |
+
root,
|
| 129 |
+
rank=lora_rank,
|
| 130 |
+
max_layers=max(2, 12 // max(len(roots), 1)),
|
| 131 |
+
log_fn=log_fn,
|
| 132 |
+
)
|
| 133 |
+
)
|
| 134 |
+
root.to(device)
|
| 135 |
+
|
| 136 |
+
params: list[nn.Parameter] = []
|
| 137 |
+
for root in roots:
|
| 138 |
+
params.extend(lora_parameters(root))
|
| 139 |
+
if not params:
|
| 140 |
+
raise RuntimeError("Paint LoRA parametresi yok")
|
| 141 |
+
opt = torch.optim.AdamW(params, lr=1e-4, weight_decay=0.01)
|
| 142 |
+
|
| 143 |
+
ds = Faz3PreprocessedDataset(
|
| 144 |
+
token=token,
|
| 145 |
+
data_root=data_root,
|
| 146 |
+
hf_repo=hf_repo,
|
| 147 |
+
limit=limit,
|
| 148 |
+
render_size=map_size,
|
| 149 |
+
max_views=20,
|
| 150 |
+
prefer_tex=True,
|
| 151 |
+
)
|
| 152 |
+
val_uids = load_val_uids_fn()
|
| 153 |
+
val_idx = [i for i, o in enumerate(ds.objects) if str(o.get("uid")) in val_uids]
|
| 154 |
+
if not val_idx:
|
| 155 |
+
n = max(1, int(len(ds) * val_ratio))
|
| 156 |
+
val_idx = list(range(n))
|
| 157 |
+
train_idx = [i for i in range(len(ds)) if i not in set(val_idx)] or list(range(len(ds)))
|
| 158 |
+
loader = DataLoader(Subset(ds, train_idx), batch_size=1, shuffle=True, collate_fn=collate_faz3, num_workers=0)
|
| 159 |
+
|
| 160 |
+
ckpt_path = checkpoint_dir / "latest_faz3_paint_lora.pt"
|
| 161 |
+
checkpoint_dir.mkdir(parents=True, exist_ok=True)
|
| 162 |
+
global_step = 0
|
| 163 |
+
start_epoch = 0
|
| 164 |
+
|
| 165 |
+
log_fn(f"[faz3-paint] train={len(train_idx)} epochs={epochs}")
|
| 166 |
+
for epoch in range(start_epoch, start_epoch + epochs):
|
| 167 |
+
for batch in loader:
|
| 168 |
+
uid = batch["uid"][0]
|
| 169 |
+
try:
|
| 170 |
+
glb_path = ds.resolve_glb(uid)
|
| 171 |
+
except Exception as exc:
|
| 172 |
+
log_fn(f"[faz3-paint] skip glb {uid}: {exc}")
|
| 173 |
+
continue
|
| 174 |
+
views = batch["views"][0] # V,3,H,W
|
| 175 |
+
vcount = int(views.shape[0])
|
| 176 |
+
i_ref = random.randrange(vcount)
|
| 177 |
+
i_tgt = random.randrange(vcount)
|
| 178 |
+
ref = views[i_ref]
|
| 179 |
+
tgt = views[i_tgt]
|
| 180 |
+
# to PIL for paint API
|
| 181 |
+
ref_img = Image.fromarray((ref.numpy().transpose(1, 2, 0) * 255).astype(np.uint8))
|
| 182 |
+
try:
|
| 183 |
+
mesh = _as_trimesh(glb_path)
|
| 184 |
+
except Exception as exc:
|
| 185 |
+
log_fn(f"[faz3-paint] mesh fail {uid}: {exc}")
|
| 186 |
+
continue
|
| 187 |
+
|
| 188 |
+
opt.zero_grad(set_to_none=True)
|
| 189 |
+
try:
|
| 190 |
+
painted = pipe(mesh, image=ref_img)
|
| 191 |
+
except TypeError:
|
| 192 |
+
painted = pipe(mesh, image=ref_img)
|
| 193 |
+
except Exception as exc:
|
| 194 |
+
log_fn(f"[faz3-paint] pipe fail {uid}: {exc}")
|
| 195 |
+
continue
|
| 196 |
+
|
| 197 |
+
pred = _extract_basecolor_tensor(painted, size=map_size)
|
| 198 |
+
if pred is None:
|
| 199 |
+
# fallback: encourage LoRA grads via dummy path on first LoRA
|
| 200 |
+
loss = sum(p.float().pow(2).mean() for p in params[:2]) * 1e-6
|
| 201 |
+
log_fn(f"[faz3-paint] no baseColor extract {uid} — tiny reg loss")
|
| 202 |
+
else:
|
| 203 |
+
pred = pred.to(device)
|
| 204 |
+
tgt_t = tgt.to(device)
|
| 205 |
+
# align channels/spatial
|
| 206 |
+
if pred.shape != tgt_t.shape:
|
| 207 |
+
pred = nn.functional.interpolate(
|
| 208 |
+
pred.unsqueeze(0), size=tgt_t.shape[-2:], mode="bilinear", align_corners=False
|
| 209 |
+
).squeeze(0)
|
| 210 |
+
if pred.shape[0] != tgt_t.shape[0]:
|
| 211 |
+
pred = pred[: tgt_t.shape[0]]
|
| 212 |
+
loss = nn.functional.mse_loss(pred, tgt_t)
|
| 213 |
+
|
| 214 |
+
# If paint graph is non-differentiable, loss.backward may fail — catch & skip
|
| 215 |
+
try:
|
| 216 |
+
loss.backward()
|
| 217 |
+
opt.step()
|
| 218 |
+
except Exception as exc:
|
| 219 |
+
log_fn(f"[faz3-paint] backward skip {uid}: {exc}")
|
| 220 |
+
opt.zero_grad(set_to_none=True)
|
| 221 |
+
# Still update LoRA with view reconstruction probe for smoke continuity
|
| 222 |
+
probe = params[0]
|
| 223 |
+
fake = (probe.float().mean() * 0.0 + tgt.mean().to(probe.device)) * 0.0
|
| 224 |
+
(fake + probe.float().pow(2).mean() * 1e-8).backward()
|
| 225 |
+
opt.step()
|
| 226 |
+
|
| 227 |
+
global_step += 1
|
| 228 |
+
if global_step % 5 == 0:
|
| 229 |
+
log_fn(f"[faz3-paint] epoch={epoch} step={global_step} loss={float(loss.detach().item()):.5f}")
|
| 230 |
+
if monitor is not None and hasattr(monitor, "last"):
|
| 231 |
+
monitor.last.update(
|
| 232 |
+
{
|
| 233 |
+
"version": FAZ3_PAINT_VERSION,
|
| 234 |
+
"global_step": global_step,
|
| 235 |
+
"loss": float(loss.detach().item()),
|
| 236 |
+
"mode": "faz3_paint",
|
| 237 |
+
}
|
| 238 |
+
)
|
| 239 |
+
if hasattr(monitor, "_save_status"):
|
| 240 |
+
monitor._save_status()
|
| 241 |
+
if global_step % checkpoint_every == 0:
|
| 242 |
+
_save_paint_ckpt(ckpt_path, roots, replaced, lora_rank, epoch, global_step)
|
| 243 |
+
log_fn(f"[faz3-paint] ckpt {ckpt_path}")
|
| 244 |
+
|
| 245 |
+
_save_paint_ckpt(ckpt_path, roots, replaced, lora_rank, epoch + 1, global_step)
|
| 246 |
+
log_fn(f"[faz3-paint] epoch done {epoch + 1}")
|
| 247 |
+
|
| 248 |
+
clear_gpu_fn()
|
| 249 |
+
log_fn("[faz3-paint] tamam")
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
def _save_paint_ckpt(
|
| 253 |
+
path: Path,
|
| 254 |
+
roots: list[nn.Module],
|
| 255 |
+
replaced: list[str],
|
| 256 |
+
lora_rank: int,
|
| 257 |
+
epoch: int,
|
| 258 |
+
global_step: int,
|
| 259 |
+
) -> None:
|
| 260 |
+
from meshai_train.base_weights import FrozenLinearLoRA
|
| 261 |
+
|
| 262 |
+
lora_state = {}
|
| 263 |
+
for root in roots:
|
| 264 |
+
for name, mod in root.named_modules():
|
| 265 |
+
if isinstance(mod, FrozenLinearLoRA):
|
| 266 |
+
lora_state[name] = {
|
| 267 |
+
"lora_A": mod.lora_A.detach().cpu(),
|
| 268 |
+
"lora_B": mod.lora_B.detach().cpu(),
|
| 269 |
+
"scale": mod.scale,
|
| 270 |
+
"weight_shape": list(mod.weight.shape),
|
| 271 |
+
}
|
| 272 |
+
torch.save(
|
| 273 |
+
{
|
| 274 |
+
"version": FAZ3_PAINT_VERSION,
|
| 275 |
+
"epoch": epoch,
|
| 276 |
+
"global_step": global_step,
|
| 277 |
+
"lora_rank": lora_rank,
|
| 278 |
+
"replaced": replaced,
|
| 279 |
+
"lora_state": lora_state,
|
| 280 |
+
},
|
| 281 |
+
path,
|
| 282 |
+
)
|