HayrettinIscan commited on
Commit
022eb51
·
verified ·
1 Parent(s): 6808dc6

Upload code/faz3_v6/meshai_api/trellis.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. code/faz3_v6/meshai_api/trellis.py +347 -0
code/faz3_v6/meshai_api/trellis.py ADDED
@@ -0,0 +1,347 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Faz3 TRELLIS geometry — full Microsoft TRELLIS image/text-to-3D.
3
+
4
+ Requires: third_party/TRELLIS (or MESHAI_TRELLIS_ROOT) + weights (HF / local).
5
+ Hafif hybrid yol: meshai_api.legacy_hybrid (deprecated, env ile).
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import gc
10
+ import hashlib
11
+ import os
12
+ import threading
13
+ from pathlib import Path
14
+ from typing import Any
15
+
16
+ from meshai_api.weights import (
17
+ ensure_sys_path_for_runtime,
18
+ ensure_trellis_local_snapshot,
19
+ resolve_faz2_ckpt,
20
+ resolve_trellis_model_path,
21
+ runtime_status,
22
+ )
23
+
24
+ ROOT = Path(__file__).resolve().parents[1]
25
+
26
+ _lock = threading.Lock()
27
+ _pipe_cache: dict[str, Any] = {"image": None, "text": None, "image_id": None, "text_id": None}
28
+
29
+
30
+ def _truthy(name: str) -> bool:
31
+ return os.environ.get(name, "").strip().lower() in {"1", "true", "yes"}
32
+
33
+
34
+ def allow_legacy_hybrid() -> bool:
35
+ return _truthy("MESHAI_ALLOW_LEGACY_HYBRID")
36
+
37
+
38
+ def allow_trellis_stub() -> bool:
39
+ return _truthy("MESHAI_ALLOW_TRELLIS_STUB")
40
+
41
+
42
+ def trellis_ready() -> dict[str, Any]:
43
+ st = runtime_status()
44
+ faz2 = resolve_faz2_ckpt(download=False)
45
+ full = bool(st.get("trellis_package"))
46
+ return {
47
+ "ready": full or allow_trellis_stub() or (allow_legacy_hybrid() and bool(faz2)),
48
+ "mode": "full" if full else ("legacy_hybrid" if allow_legacy_hybrid() and faz2 else ("stub" if allow_trellis_stub() else "missing")),
49
+ "trellis_full": full,
50
+ "trellis_package": st.get("trellis_package"),
51
+ "trellis_error": st.get("trellis_error"),
52
+ "trellis_root": st.get("trellis_root"),
53
+ "trellis_model": st.get("trellis_model"),
54
+ "faz2_ckpt": str(faz2) if faz2 else None,
55
+ "faz2_ready": bool(faz2),
56
+ "faz2_bind": "pending_peft" if faz2 else "missing",
57
+ "faz3_geo_lora": str(ROOT / "checkpoints" / "latest_faz3_lora.pt")
58
+ if (ROOT / "checkpoints" / "latest_faz3_lora.pt").is_file()
59
+ else None,
60
+ "faz3_paint_lora": str(ROOT / "checkpoints" / "latest_faz3_paint_lora.pt")
61
+ if (ROOT / "checkpoints" / "latest_faz3_paint_lora.pt").is_file()
62
+ else None,
63
+ "allow_stub": allow_trellis_stub(),
64
+ "allow_legacy_hybrid": allow_legacy_hybrid(),
65
+ "hf_token_set": st.get("hf_token_set"),
66
+ }
67
+
68
+
69
+ def release_trellis_cuda(*, log: Any = print) -> None:
70
+ """Drop cached TRELLIS pipelines so Hunyuan Paint can fit on the same GPU."""
71
+ with _lock:
72
+ for key in ("image", "text"):
73
+ _pipe_cache[key] = None
74
+ _pipe_cache["image_id"] = None
75
+ _pipe_cache["text_id"] = None
76
+ gc.collect()
77
+ try:
78
+ import torch
79
+
80
+ if torch.cuda.is_available():
81
+ torch.cuda.empty_cache()
82
+ log("[faz3] TRELLIS CUDA cache released")
83
+ except Exception as exc:
84
+ log(f"[faz3] TRELLIS CUDA release skip: {exc}")
85
+
86
+
87
+ def _seed(prompt: str, image_path: Path | None) -> int:
88
+ key = (prompt or "meshai").encode("utf-8")
89
+ if image_path and image_path.is_file():
90
+ key += hashlib.sha256(image_path.read_bytes()[:65536]).digest()
91
+ return int(hashlib.sha256(key).hexdigest()[:8], 16)
92
+
93
+
94
+ def _patch_trellis_pipeline_local_load(log: Any = print) -> None:
95
+ """
96
+ TRELLIS Pipeline.from_pretrained does:
97
+ try: models.from_pretrained(f\"{path}/{v}\")
98
+ except: models.from_pretrained(v) # relative ckpts/* → fake HF repo 404
99
+ If local .json+.safetensors exist, never fall back to HF.
100
+ """
101
+ import os
102
+
103
+ from trellis.pipelines import base as trellis_base
104
+ from trellis import models as trellis_models
105
+
106
+ if getattr(trellis_base.Pipeline, "_meshai_local_patch", False):
107
+ return
108
+
109
+ orig = trellis_base.Pipeline.from_pretrained
110
+
111
+ @staticmethod
112
+ def _from_pretrained_fixed(path: str):
113
+ import json
114
+
115
+ is_local = os.path.exists(f"{path}/pipeline.json")
116
+ if is_local:
117
+ config_file = f"{path}/pipeline.json"
118
+ else:
119
+ from huggingface_hub import hf_hub_download
120
+
121
+ config_file = hf_hub_download(path, "pipeline.json")
122
+
123
+ with open(config_file, "r", encoding="utf-8") as f:
124
+ args = json.load(f)["args"]
125
+
126
+ _models: dict[str, Any] = {}
127
+ for k, v in args["models"].items():
128
+ local_stem = f"{path}/{v}" if is_local and not str(v).startswith("/") else None
129
+ local_ok = bool(
130
+ local_stem
131
+ and os.path.exists(f"{local_stem}.json")
132
+ and os.path.exists(f"{local_stem}.safetensors")
133
+ )
134
+ if local_ok:
135
+ try:
136
+ _models[k] = trellis_models.from_pretrained(local_stem)
137
+ continue
138
+ except Exception as exc:
139
+ raise RuntimeError(
140
+ f"TRELLIS local model load failed for {local_stem}: {exc}"
141
+ ) from exc
142
+ # HF id paths (JeffreyXiang/...) or missing local — try joined then bare
143
+ try:
144
+ _models[k] = trellis_models.from_pretrained(f"{path}/{v}")
145
+ except Exception as first:
146
+ # Only fall back for real HF-style ids (org/repo/...), never bare ckpts/*
147
+ if isinstance(v, str) and v.startswith("ckpts/"):
148
+ raise RuntimeError(
149
+ f"TRELLIS missing local weights for {path}/{v} "
150
+ f"(.json+.safetensors). First error: {first}"
151
+ ) from first
152
+ try:
153
+ _models[k] = trellis_models.from_pretrained(v)
154
+ except Exception as second:
155
+ raise RuntimeError(
156
+ f"TRELLIS model load failed path={path}/{v} "
157
+ f"fallback={v}: {first} | {second}"
158
+ ) from second
159
+
160
+ new_pipeline = trellis_base.Pipeline(_models)
161
+ new_pipeline._pretrained_args = args
162
+ return new_pipeline
163
+
164
+ trellis_base.Pipeline.from_pretrained = _from_pretrained_fixed
165
+ trellis_base.Pipeline._meshai_local_patch = True
166
+ log("[faz3] patched TRELLIS Pipeline.from_pretrained (no ckpts/* HF fallback)")
167
+
168
+
169
+ def _prepare_trellis_env(log: Any = print) -> None:
170
+ """Must run before any `import trellis`. Sparse attn only: xformers|flash_attn (not sdpa)."""
171
+ ensure_sys_path_for_runtime()
172
+ os.environ.setdefault("SPCONV_ALGO", "native")
173
+ current = os.environ.get("ATTN_BACKEND", "").strip()
174
+ if current == "sdpa":
175
+ # TRELLIS sparse ignores sdpa and keeps default flash_attn → ModuleNotFoundError
176
+ log("[faz3] WARN: ATTN_BACKEND=sdpa sparse icin gecersiz; xformers deneniyor")
177
+ current = ""
178
+ if not current:
179
+ try:
180
+ import flash_attn # noqa: F401
181
+
182
+ current = "flash_attn"
183
+ except Exception:
184
+ try:
185
+ import xformers # noqa: F401
186
+
187
+ current = "xformers"
188
+ except Exception:
189
+ raise RuntimeError(
190
+ "TRELLIS icin flash_attn veya xformers gerekli (sdpa yetmez). "
191
+ "Torch'u bozmadan: pip install xformers==0.0.28.post1 --no-deps "
192
+ "--index-url https://download.pytorch.org/whl/cu121"
193
+ )
194
+ os.environ["ATTN_BACKEND"] = current
195
+ os.environ["SPARSE_ATTN_BACKEND"] = os.environ["ATTN_BACKEND"]
196
+ log(f"[faz3] ATTN_BACKEND={os.environ['ATTN_BACKEND']} SPARSE_ATTN_BACKEND={os.environ['SPARSE_ATTN_BACKEND']}")
197
+
198
+
199
+ def _load_image_pipeline(log: Any = print):
200
+ _prepare_trellis_env(log=log)
201
+ model_id = resolve_trellis_model_path(text=False)
202
+ local_path = ensure_trellis_local_snapshot(model_id, log=log)
203
+ with _lock:
204
+ if _pipe_cache["image"] is not None and _pipe_cache["image_id"] == local_path:
205
+ return _pipe_cache["image"], local_path
206
+ _patch_trellis_pipeline_local_load(log=log)
207
+ from trellis.pipelines import TrellisImageTo3DPipeline
208
+
209
+ log(f"[faz3] loading TRELLIS image pipeline: {local_path}")
210
+ pipe = TrellisImageTo3DPipeline.from_pretrained(local_path)
211
+ if hasattr(pipe, "cuda"):
212
+ try:
213
+ pipe.cuda()
214
+ except Exception as exc:
215
+ log(f"[faz3] TRELLIS cuda() skip: {exc}")
216
+ # Optional Faz3 geo LoRA bind
217
+ try:
218
+ from meshai_api.faz3_lora_bind import apply_faz3_lora_state, resolve_faz3_geo_ckpt
219
+
220
+ ckpt = resolve_faz3_geo_ckpt()
221
+ if ckpt is not None:
222
+ import torch
223
+
224
+ blob = torch.load(ckpt, map_location="cpu", weights_only=False)
225
+ models = getattr(pipe, "models", None)
226
+ n = 0
227
+ if isinstance(models, dict):
228
+ for m in models.values():
229
+ if hasattr(m, "named_modules"):
230
+ n += apply_faz3_lora_state(m, blob, log=log)
231
+ log(f"[faz3] geo LoRA ckpt={ckpt} applied_modules={n}")
232
+ except Exception as exc:
233
+ log(f"[faz3] geo LoRA bind skip: {exc}")
234
+ _pipe_cache["image"] = pipe
235
+ _pipe_cache["image_id"] = local_path
236
+ return pipe, local_path
237
+
238
+
239
+ def _load_text_pipeline(log: Any = print):
240
+ _prepare_trellis_env(log=log)
241
+ model_id = resolve_trellis_model_path(text=True)
242
+ local_path = ensure_trellis_local_snapshot(model_id, log=log)
243
+ with _lock:
244
+ if _pipe_cache["text"] is not None and _pipe_cache["text_id"] == local_path:
245
+ return _pipe_cache["text"], local_path
246
+ _patch_trellis_pipeline_local_load(log=log)
247
+ from trellis.pipelines import TrellisTextTo3DPipeline
248
+
249
+ log(f"[faz3] loading TRELLIS text pipeline: {local_path}")
250
+ pipe = TrellisTextTo3DPipeline.from_pretrained(local_path)
251
+ if hasattr(pipe, "cuda"):
252
+ try:
253
+ pipe.cuda()
254
+ except Exception as exc:
255
+ log(f"[faz3] TRELLIS text cuda() skip: {exc}")
256
+ _pipe_cache["text"] = pipe
257
+ _pipe_cache["text_id"] = local_path
258
+ return pipe, local_path
259
+
260
+
261
+ def _export_glb(outputs: dict[str, Any], out_path: Path, log: Any) -> Path:
262
+ from trellis.utils import postprocessing_utils
263
+
264
+ gaussians = outputs.get("gaussian") or outputs.get("gaussians")
265
+ meshes = outputs.get("mesh") or outputs.get("meshes")
266
+ if not gaussians or not meshes:
267
+ raise RuntimeError(f"TRELLIS outputs eksik keys={list(outputs.keys())}")
268
+ g0 = gaussians[0] if isinstance(gaussians, (list, tuple)) else gaussians
269
+ m0 = meshes[0] if isinstance(meshes, (list, tuple)) else meshes
270
+ simplify = float(os.environ.get("MESHAI_TRELLIS_SIMPLIFY", "0.95") or "0.95")
271
+ tex_size = int(os.environ.get("MESHAI_TRELLIS_TEXTURE_SIZE", "1024") or "1024")
272
+ glb = postprocessing_utils.to_glb(g0, m0, simplify=simplify, texture_size=tex_size)
273
+ out_path.parent.mkdir(parents=True, exist_ok=True)
274
+ glb.export(str(out_path))
275
+ log(f"[faz3] TRELLIS full GLB: {out_path} ({out_path.stat().st_size} B)")
276
+ return out_path
277
+
278
+
279
+ def run_trellis_full(
280
+ *,
281
+ job_dir: Path,
282
+ prompt: str = "",
283
+ image_path: Path | None = None,
284
+ log: Any = print,
285
+ ) -> tuple[Path, dict[str, Any]]:
286
+ """Official TRELLIS -> trellis.glb."""
287
+ from PIL import Image
288
+
289
+ out = job_dir / "trellis.glb"
290
+ seed = _seed(prompt, image_path)
291
+ meta: dict[str, Any] = {"backend": "trellis_full", "seed": seed}
292
+
293
+ if image_path is not None and image_path.is_file():
294
+ pipe, model_id = _load_image_pipeline(log=log)
295
+ image = Image.open(image_path).convert("RGBA")
296
+ meta["model"] = model_id
297
+ meta["cond"] = "image"
298
+ outputs = pipe.run(image, seed=seed)
299
+ elif (prompt or "").strip():
300
+ pipe, model_id = _load_text_pipeline(log=log)
301
+ meta["model"] = model_id
302
+ meta["cond"] = "text"
303
+ # API varies slightly across TRELLIS versions
304
+ try:
305
+ outputs = pipe.run(prompt.strip(), seed=seed)
306
+ except TypeError:
307
+ outputs = pipe.run(prompt.strip())
308
+ else:
309
+ raise ValueError("TRELLIS full icin image veya prompt gerekli")
310
+
311
+ _export_glb(outputs, out, log)
312
+ # Faz2 ckpt: indirilmis/cached — full PEFT merge ayri is; health'te hazir
313
+ faz2 = resolve_faz2_ckpt(download=_truthy("MESHAI_FAZ2_AUTO_DOWNLOAD"))
314
+ meta["faz2_ckpt"] = str(faz2) if faz2 else None
315
+ meta["faz2_bind"] = "pending_peft" if faz2 else "missing"
316
+ return out, meta
317
+
318
+
319
+ def run_trellis_geometry(
320
+ *,
321
+ job_dir: Path,
322
+ prompt: str = "",
323
+ image_path: Path | None = None,
324
+ log: Any = print,
325
+ ) -> tuple[Path, dict[str, Any]]:
326
+ """
327
+ Production entry: full TRELLIS.
328
+ Legacy hybrid sadece MESHAI_ALLOW_LEGACY_HYBRID=1.
329
+ """
330
+ # Prefer full when package present
331
+ st = runtime_status()
332
+ if st.get("trellis_package"):
333
+ return run_trellis_full(job_dir=job_dir, prompt=prompt, image_path=image_path, log=log)
334
+
335
+ if allow_legacy_hybrid():
336
+ log("[faz3] WARN: TRELLIS package yok — LEGACY hybrid (production degil)")
337
+ from meshai_api.legacy_hybrid import run_trellis_geometry as _legacy
338
+
339
+ glb, feats = _legacy(job_dir=job_dir, prompt=prompt, image_path=image_path, log=log)
340
+ meta = {"backend": "legacy_hybrid", **(feats.get("meta") or {}), "feats": feats}
341
+ return glb, meta
342
+
343
+ raise RuntimeError(
344
+ "Full TRELLIS yok. third_party/TRELLIS kur + MESHAI_TRELLIS_ROOT "
345
+ "veya pip/sys.path; smoke icin MESHAI_ALLOW_TRELLIS_STUB=1 "
346
+ "(legacy: MESHAI_ALLOW_LEGACY_HYBRID=1)."
347
+ )