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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Faz 2: hibrit kopru + gercek TRELLIS/Hunyuan safetensors uzerinde LoRA."""
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from typing import Any
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
import torch.nn as nn
|
| 10 |
+
|
| 11 |
+
from meshai_train.base_weights import (
|
| 12 |
+
BaseLoRATower,
|
| 13 |
+
_load_safetensors,
|
| 14 |
+
pick_lora_targets,
|
| 15 |
+
)
|
| 16 |
+
from meshai_train.models import GEOM_IN_DIM, TEXTURE_LATENT_DIM, MeshAIHybridTrainBundle
|
| 17 |
+
|
| 18 |
+
FAZ2_VERSION = "v5.0-faz2-lora-base"
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class MeshAIFaz2Bundle(nn.Module):
|
| 22 |
+
"""
|
| 23 |
+
Faz1 hibrit (geometry/texture/bridge) + TRELLIS/Hunyuan LoRA kuleleri.
|
| 24 |
+
Base agirliklar frozen; sadece LoRA + proj + hibrit egitilir.
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
def __init__(
|
| 28 |
+
self,
|
| 29 |
+
*,
|
| 30 |
+
trellis_targets: list[tuple[str, torch.Tensor]],
|
| 31 |
+
hunyuan_targets: list[tuple[str, torch.Tensor]],
|
| 32 |
+
lora_rank: int = 8,
|
| 33 |
+
) -> None:
|
| 34 |
+
super().__init__()
|
| 35 |
+
self.hybrid = MeshAIHybridTrainBundle()
|
| 36 |
+
self.trellis_tower = BaseLoRATower(
|
| 37 |
+
trellis_targets,
|
| 38 |
+
input_dim=GEOM_IN_DIM,
|
| 39 |
+
rank=lora_rank,
|
| 40 |
+
out_dim=TEXTURE_LATENT_DIM,
|
| 41 |
+
)
|
| 42 |
+
# Hunyuan: view embedding -> tower
|
| 43 |
+
self.view_pool = nn.Sequential(
|
| 44 |
+
nn.Conv2d(3, 32, 3, stride=2, padding=1),
|
| 45 |
+
nn.GELU(),
|
| 46 |
+
nn.AdaptiveAvgPool2d(1),
|
| 47 |
+
)
|
| 48 |
+
self.view_proj = nn.Linear(32, GEOM_IN_DIM)
|
| 49 |
+
self.hunyuan_tower = BaseLoRATower(
|
| 50 |
+
hunyuan_targets,
|
| 51 |
+
input_dim=GEOM_IN_DIM,
|
| 52 |
+
rank=lora_rank,
|
| 53 |
+
out_dim=TEXTURE_LATENT_DIM,
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
def forward(self, geom_in: torch.Tensor, views: torch.Tensor) -> dict[str, torch.Tensor]:
|
| 57 |
+
hy = self.hybrid(geom_in, views)
|
| 58 |
+
trellis_feat = self.trellis_tower(geom_in)
|
| 59 |
+
|
| 60 |
+
b, v, c, h, w = views.shape
|
| 61 |
+
pooled = self.view_pool(views.reshape(b * v, c, h, w)).reshape(b, v, -1).mean(dim=1)
|
| 62 |
+
view_cond = self.view_proj(pooled)
|
| 63 |
+
hunyuan_feat = self.hunyuan_tower(view_cond)
|
| 64 |
+
|
| 65 |
+
return {
|
| 66 |
+
**hy,
|
| 67 |
+
"trellis_feat": trellis_feat,
|
| 68 |
+
"hunyuan_feat": hunyuan_feat,
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def faz2_loss(
|
| 73 |
+
out: dict[str, torch.Tensor],
|
| 74 |
+
batch: dict[str, torch.Tensor],
|
| 75 |
+
) -> tuple[torch.Tensor, dict[str, float]]:
|
| 76 |
+
voxel_loss = nn.functional.mse_loss(out["voxel_pred"], batch["voxel_tgt"])
|
| 77 |
+
bridge_loss = nn.functional.mse_loss(out["bridge_out"], out["tex_latent"].detach())
|
| 78 |
+
# Gercek base kosullama: LoRA ciktilari hibrit latente hizalansin
|
| 79 |
+
trellis_align = nn.functional.mse_loss(out["trellis_feat"], out["bridge_out"].detach())
|
| 80 |
+
hunyuan_align = nn.functional.mse_loss(out["hunyuan_feat"], out["tex_latent"].detach())
|
| 81 |
+
tex_reg = out["tex_latent"].pow(2).mean() * 1e-4
|
| 82 |
+
total = voxel_loss + bridge_loss + 0.5 * trellis_align + 0.5 * hunyuan_align + tex_reg
|
| 83 |
+
return total, {
|
| 84 |
+
"voxel": float(voxel_loss.item()),
|
| 85 |
+
"bridge": float(bridge_loss.item()),
|
| 86 |
+
"trellis_align": float(trellis_align.item()),
|
| 87 |
+
"hunyuan_align": float(hunyuan_align.item()),
|
| 88 |
+
"tex_reg": float(tex_reg.item()),
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def build_faz2_from_weight_files(
|
| 93 |
+
weight_paths: dict[str, Path],
|
| 94 |
+
*,
|
| 95 |
+
lora_rank: int = 8,
|
| 96 |
+
trellis_mats: int = 4,
|
| 97 |
+
hunyuan_mats: int = 4,
|
| 98 |
+
log_fn: Any = print,
|
| 99 |
+
) -> MeshAIFaz2Bundle:
|
| 100 |
+
trellis_targets: list[tuple[str, torch.Tensor]] = []
|
| 101 |
+
hunyuan_targets: list[tuple[str, torch.Tensor]] = []
|
| 102 |
+
|
| 103 |
+
for rel, path in weight_paths.items():
|
| 104 |
+
state = _load_safetensors(path)
|
| 105 |
+
picks = pick_lora_targets(state, max_matrices=trellis_mats if "TRELLIS" in rel else hunyuan_mats)
|
| 106 |
+
log_fn(f"[faz2] {rel}: {len(state)} tensor, LoRA aday={len(picks)}")
|
| 107 |
+
if "TRELLIS" in rel:
|
| 108 |
+
trellis_targets.extend(picks)
|
| 109 |
+
else:
|
| 110 |
+
hunyuan_targets.extend(picks)
|
| 111 |
+
|
| 112 |
+
if not trellis_targets:
|
| 113 |
+
raise RuntimeError("TRELLIS LoRA hedefi bulunamadi")
|
| 114 |
+
if not hunyuan_targets:
|
| 115 |
+
raise RuntimeError("Hunyuan LoRA hedefi bulunamadi")
|
| 116 |
+
|
| 117 |
+
# En buyuk N
|
| 118 |
+
trellis_targets = sorted(trellis_targets, key=lambda x: x[1].numel(), reverse=True)[:trellis_mats]
|
| 119 |
+
hunyuan_targets = sorted(hunyuan_targets, key=lambda x: x[1].numel(), reverse=True)[:hunyuan_mats]
|
| 120 |
+
log_fn(
|
| 121 |
+
f"[faz2] secilen TRELLIS mats={len(trellis_targets)} "
|
| 122 |
+
f"Hunyuan mats={len(hunyuan_targets)} rank={lora_rank}"
|
| 123 |
+
)
|
| 124 |
+
return MeshAIFaz2Bundle(
|
| 125 |
+
trellis_targets=trellis_targets,
|
| 126 |
+
hunyuan_targets=hunyuan_targets,
|
| 127 |
+
lora_rank=lora_rank,
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def save_faz2_checkpoint(
|
| 132 |
+
path: Path,
|
| 133 |
+
*,
|
| 134 |
+
epoch: int,
|
| 135 |
+
global_step: int,
|
| 136 |
+
model: MeshAIFaz2Bundle,
|
| 137 |
+
extra: dict[str, Any] | None = None,
|
| 138 |
+
) -> None:
|
| 139 |
+
payload = {
|
| 140 |
+
"version": FAZ2_VERSION,
|
| 141 |
+
"epoch": epoch,
|
| 142 |
+
"global_step": global_step,
|
| 143 |
+
"model": model.state_dict(),
|
| 144 |
+
"extra": extra or {},
|
| 145 |
+
}
|
| 146 |
+
torch.save(payload, path)
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def load_faz2_checkpoint(path: Path, model: MeshAIFaz2Bundle, device: str) -> int:
|
| 150 |
+
state = torch.load(path, map_location=device, weights_only=False)
|
| 151 |
+
if state.get("version") != FAZ2_VERSION:
|
| 152 |
+
# Faz1 hibrit ckpt ise sadece hybrid yukle
|
| 153 |
+
if "geometry" in state and "texture" in state and "bridge" in state:
|
| 154 |
+
model.hybrid.geometry.load_state_dict(state["geometry"])
|
| 155 |
+
model.hybrid.texture.load_state_dict(state["texture"])
|
| 156 |
+
model.hybrid.bridge.load_state_dict(state["bridge"])
|
| 157 |
+
return int(state.get("global_step", 0))
|
| 158 |
+
return 0
|
| 159 |
+
model.load_state_dict(state["model"], strict=False)
|
| 160 |
+
return int(state.get("global_step", 0))
|